Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.33% covered (success)
97.33%
728 / 748
75.61% covered (warning)
75.61%
31 / 41
CRAP
0.00% covered (danger)
0.00%
0 / 1
AI_Launchpad_REST
97.46% covered (success)
97.46%
728 / 747
75.61% covered (warning)
75.61%
31 / 41
210
0.00% covered (danger)
0.00%
0 / 1
 is_private_site
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 __construct
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 schedule_completion_pass
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 run_scheduled_completion_passes
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
5.12
 register_routes
100.00% covered (success)
100.00%
167 / 167
100.00% covered (success)
100.00%
1 / 1
1
 sanitize_validation_errors
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
7
 can_read
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 can_write
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 check_eligibility
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 get_data
100.00% covered (success)
100.00%
35 / 35
100.00% covered (success)
100.00%
1 / 1
12
 get_current_tasks
91.30% covered (success)
91.30%
21 / 23
0.00% covered (danger)
0.00%
0 / 1
15.15
 backfill_to_minimum
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
9
 backfill_pool
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 maybe_mark_completed
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
6.01
 report_task_completions
95.83% covered (success)
95.83%
23 / 24
0.00% covered (danger)
0.00%
0 / 1
10
 update_wizard
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
3
 update_tailored
100.00% covered (success)
100.00%
56 / 56
100.00% covered (success)
100.00%
1 / 1
12
 log_tailoring
22.22% covered (danger)
22.22%
2 / 9
0.00% covered (danger)
0.00%
0 / 1
7.23
 tailoring_log_extra
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 complete_task
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
4
 skip_task
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
3
 dismiss
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 get_skipped_task_ids
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 apply_skipped_tasks
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 sanitize_subtitle
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
5
 get_available_tasks
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 excluded_task_ids_for_goal
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 available_task_ids
96.97% covered (success)
96.97%
32 / 33
0.00% covered (danger)
0.00%
0 / 1
4
 build_all_catalog_tasks
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
5
 build_tasks
95.45% covered (success)
95.45%
63 / 66
0.00% covered (danger)
0.00%
0 / 1
28
 get_cta_override
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 get_themes_showcase_path
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 ensure_theme_task
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
6
 move_task_after
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
3.02
 build_store_tasks
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 build_install_woocommerce_task
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
5
 build_setup_store_task
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 insert_before_launch_task
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
7.05
 get_in_progress_draft_url
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 get_task_title
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 get_output_schema
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * AI Launchpad REST endpoints.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 * @since 6.11.0
7 */
8
9/**
10 * REST endpoints for the AI Launchpad wizard and AI output options.
11 */
12class AI_Launchpad_REST extends WP_REST_Controller {
13
14    const OPTION_WIZARD    = 'wpcom_ai_launchpad_wizard';
15    const OPTION_AI_OUTPUT = 'wpcom_ai_launchpad_ai_output';
16    const OPTION_DISMISSED = 'wpcom_ai_launchpad_dismissed';
17    const OPTION_SKIPPED   = 'wpcom_ai_launchpad_skipped_tasks';
18    // Latched "every task is done" flag, autoloaded so the menu gate reads it without rebuilding the task list.
19    // Set once; cleared only by an explicit reset (re-tailor, dismiss, reset).
20    const OPTION_COMPLETED = 'wpcom_ai_launchpad_completed';
21
22    /**
23     * Options whose writes can finish a task outside Site Setup: every listener records completion in the statuses
24     * option, and the launch task reads `launch-status` live.
25     */
26    const COMPLETION_TRIGGER_OPTIONS = array( 'launchpad_checklist_tasks_statuses', 'launch-status' );
27
28    const MIN_VALID_TASKS = 4;
29
30    /**
31     * Caps on the client-reported `validation_errors` that reach the `tailored` Logstash record. The client applies
32     * the same caps; these are the ones that hold for any caller.
33     */
34    const MAX_VALIDATION_ERRORS       = 4;
35    const MAX_VALIDATION_ERROR_LENGTH = 400;
36
37    /**
38     * Blogs with a completion pass queued for shutdown, as blog id => true.
39     *
40     * @var array<int, true>
41     */
42    private $pending_completion_blog_ids = array();
43
44    // `woo_launch_site`, `link_in_bio_launched`, and `videopress_launched` stay valid launch tasks so a stray AI
45    // emission passes PUT validation rather than failing the whole list into the deterministic fallback. It is
46    // normalized to `site_launched` as it is persisted (see update_tailored) and again on read (see build_tasks,
47    // which is what covers lists persisted before the write-side remap existed).
48    const LAUNCH_TASK_IDS = array( 'site_launched', 'blog_launched', 'woo_launch_site', 'link_in_bio_launched', 'videopress_launched' );
49
50    /**
51     * Tasks the AI Launchpad marks complete on CTA click, because their real signal is unreachable from wp-admin.
52     *
53     * Server-side allowlist so the complete-task route can only tick these ids. Mirrored client-side in model.ts.
54     *
55     * A registry task may be listed here, but only if its `is_complete` reads `launchpad_checklist_tasks_statuses`:
56     * that is the option complete_task() writes for it, and a definition computing completion from live site state
57     * would ignore the write and render as to-do straight after being ticked.
58     */
59    const COMPLETE_ON_CLICK_TASK_IDS = array(
60        'complete_profile',
61        'manage_subscribers',
62        'manage_paid_newsletter_plan',
63        'earn_money',
64        'start_building_your_audience',
65        'site_monitoring_page',
66        'setup_ssh',
67        'share_site',
68        'pick_fonts_colors',
69    );
70
71    /**
72     * Task ids the AI Launchpad synthesizes itself (never present in the AI payload): the sell goal's store-setup
73     * lead tasks. Skips must accept them alongside the AI-selected ids.
74     *
75     * Must list every id minted by build_store_tasks() â€” a synthetic task missing here renders with a
76     * Skip button whose write is rejected.
77     */
78    const SYNTHETIC_TASK_IDS = array(
79        'install_woocommerce',
80        'setup_woocommerce_store',
81    );
82
83    /**
84     * Tasks whose catalog visibility gate is a false negative in this read path, so the AI Launchpad overrides it.
85     *
86     * `add_10_email_subscribers` is gated off WordPress.com, but AI_Launchpad_Subscribers_Listener reads the count on
87     * Atomic, so the task must still render. `add_about_page` is gated on the `_wpcom_template_layout_category`
88     * page-meta key being registered, which does not happen during a REST request, so the task is wrongly hidden even
89     * though its "add a page" CTA works â€” force it visible so tailoring can offer this genuinely useful task.
90     */
91    const FORCE_VISIBLE_TASK_IDS = array(
92        'add_10_email_subscribers',
93        'add_about_page',
94    );
95
96    /**
97     * Commerce tasks whose catalog visibility gate requires WooCommerce to be active.
98     *
99     * On a fresh sell site these would be dropped, collapsing the list. Instead the sell branch keeps them as a
100     * disabled preview of the store roadmap until WooCommerce is active. See build_tasks()'s $disable_hidden_woo mode.
101     */
102    const WOO_TASK_IDS = array(
103        'woo_customize_store',
104        'woo_products',
105        'set_up_payments',
106    );
107
108    /**
109     * CTA destinations the AI Launchpad repoints to wp-admin, keyed by task id, each mapping to an `admin_url()` path.
110     *
111     * The catalog sends these to Calypso flows that are a poor fit for wp-admin. Overridden on read so the shared
112     * catalog (used by the legacy launchpad too) is left untouched.
113     */
114    const CTA_OVERRIDES = array(
115        'connect_social_media' => 'admin.php?page=jetpack-social',
116    );
117
118    /**
119     * Jetpack Social tasks, hidden on private sites where wpcom does not load Publicize (so their CTA page would 404).
120     * `drive_traffic` needs no entry: it remaps onto `connect_social_media` before this gate runs.
121     */
122    const SOCIAL_PAGE_TASK_IDS = array(
123        'connect_social_media',
124    );
125
126    /**
127     * Tasks the model may pick only when the site's goal is one of the listed goals.
128     *
129     * These were prose rules in the tailoring prompt ("Only include woo_* if the goal is sell OR the user
130     * explicitly mentions selling"). Prose is not enforcement: the model can ignore it, and when the
131     * available-tasks lookup fails the prompt falls back to the unfiltered menu. Enforced here instead, at
132     * both ends â€” the menu never offers them (available_task_ids) and PUT drops them (update_tailored).
133     *
134     * The free-text escape hatch is deliberately gone. The wizard goal is an explicit user choice, and the
135     * escape hatch was the non-determinism being removed.
136     *
137     * The two directions of disagreement with a task's `goals` annotation in js/lib/prompts.ts are not
138     * equivalent, and only one is acceptable:
139     *
140     * - Annotation BROADER than this map is fine. The annotation is soft affinity for the model, this is the
141     *   hard rule, and a task can be a tasteful fit for a goal it is not permitted on â€” the rule still blocks
142     *   it. The payment tasks are the live example: annotated for `newsletter` as well as `sell`, permitted
143     *   only on `sell`.
144     * - Annotation NARROWER than this map is a bug. It means a task the annotation itself calls goal-specific
145     *   can be selected and persisted on any goal, which is the inappropriate-task problem this whole change
146     *   exists to fix. `woo_tax`, `woo_marketing` and `woo_add_domain` were exactly that: annotated `sell`,
147     *   unrestricted here, and renderable on a blog â€” their catalog gate
148     *   (wpcom_launchpad_is_woocommerce_setup_visible) is goal-agnostic and passes on any WoA site with
149     *   WooCommerce active, which is every site this feature runs on.
150     *
151     * So: every id annotated with a single goal belongs here. No exceptions â€” `sensei_setup` is listed even
152     * though its catalog gate (WoA plus Sensei LMS active) already hides it almost everywhere, because a rule
153     * with one documented exception is a rule the next auditor has to re-derive. AI_Launchpad_Task_Menu_Test
154     * reads the annotations and fails if a single-goal one is missing here.
155     *
156     * The ids are matched after wpcom_ai_launchpad_remap_task_id(), so a twin of a restricted task is covered
157     * by the entry for the id it renders as and must not be listed separately.
158     */
159    const GOAL_RESTRICTED_TASK_IDS = array(
160        'woo_products'             => 'sell',
161        'woo_customize_store'      => 'sell',
162        'woo_woocommerce_payments' => 'sell',
163        'woo_tax'                  => 'sell',
164        'woo_marketing'            => 'sell',
165        'woo_add_domain'           => 'sell',
166        'set_up_payments'          => 'sell',
167        'stripe_connected'         => 'sell',
168        'add_10_email_subscribers' => 'newsletter',
169        'import_subscribers'       => 'newsletter',
170        'newsletter_plan_created'  => 'newsletter',
171        'sensei_setup'             => 'educate',
172    );
173
174    /**
175     * Tasks excluded for one specific goal and allowed on every other â€” the inverse of GOAL_RESTRICTED_TASK_IDS.
176     *
177     * Split into its own map rather than folded in behind a `!sell` marker, so neither map needs a value whose
178     * meaning flips on a prefix and each docblock describes all of its own entries.
179     *
180     * `add_gallery_page` is excluded for sell so a store site cannot end up with both the store sequence and a
181     * gallery. get_current_tasks() used to enforce that structurally, through the if/else that injected the
182     * gallery only on the non-sell branch; now that the model picks the gallery from the menu, this entry is
183     * the only thing holding it â€” the menu never offers it on sell, and PUT drops it if the model picks it anyway.
184     *
185     * Both ends are write-side: build_tasks() applies no exclusion, so a payload that already holds an excluded id
186     * renders it. Reaching that needs a compound failure (the availability lookup fails, so the prompt falls back
187     * to the full menu, AND the wizard-goal option has not landed yet, so the goal comes from the model's echo).
188     * True of every entry in both maps, not just this one; read-side enforcement is the fix if it ever bites.
189     */
190    const GOAL_EXCLUDED_TASK_IDS = array(
191        'add_gallery_page' => 'sell',
192    );
193
194    /**
195     * First-post tasks that can sit "in progress": the AI-created draft post exists but has not been published yet.
196     *
197     * Detected through the `_wpcom_ai_launchpad_first_post` marker meta (via AI_Launchpad_First_Post_Listener), so an
198     * unrelated pre-existing draft never counts. Paired with `add_about_page`, which has its own marker meta.
199     * `first_post_published_newsletter` needs no entry: it remaps onto `first_post_published` before this runs.
200     */
201    const IN_PROGRESS_FIRST_POST_TASK_IDS = array(
202        'first_post_published',
203    );
204
205    /**
206     * Whether the site's visibility is set to private (`blog_public = -1`).
207     *
208     * Read directly to avoid a hard dependency on the Status package in this read path.
209     *
210     * @return bool
211     */
212    private function is_private_site() {
213        return '-1' === (string) get_option( 'blog_public' );
214    }
215
216    /**
217     * Class constructor.
218     */
219    public function __construct() {
220        $this->namespace = 'wpcom/v2';
221        $this->rest_base = 'ai-launchpad';
222
223        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
224
225        foreach ( self::COMPLETION_TRIGGER_OPTIONS as $option ) {
226            add_action( "add_option_{$option}", array( $this, 'schedule_completion_pass' ) );
227            add_action( "update_option_{$option}", array( $this, 'schedule_completion_pass' ) );
228        }
229    }
230
231    /**
232     * Queues a completion pass for shutdown, so finishing the last task outside Site Setup (a launch, the editor)
233     * hides the menu on the next page load. Deferred so it sees the request's final state, not a write mid-way.
234     *
235     * @return void
236     */
237    public function schedule_completion_pass() {
238        // Some tasks judge completion by the current user, so cron or a visitor must not decide the owner's list.
239        if (
240            ! current_user_can( 'manage_options' )
241            || get_option( self::OPTION_COMPLETED )
242            || ! get_option( self::OPTION_AI_OUTPUT )
243            || true !== $this->check_eligibility()
244        ) {
245            return;
246        }
247
248        $this->pending_completion_blog_ids[ get_current_blog_id() ] = true;
249        add_action( 'shutdown', array( $this, 'run_scheduled_completion_passes' ) );
250    }
251
252    /**
253     * Runs the queued completion passes, each in the blog that queued it: on WordPress.com Simple the write can
254     * happen inside a switch_to_blog() that is restored by shutdown.
255     *
256     * @return void
257     */
258    public function run_scheduled_completion_passes() {
259        foreach ( array_keys( $this->pending_completion_blog_ids ) as $blog_id ) {
260            $switched = is_multisite() && get_current_blog_id() !== $blog_id && switch_to_blog( $blog_id );
261            $this->maybe_mark_completed();
262            if ( $switched ) {
263                restore_current_blog();
264            }
265        }
266        $this->pending_completion_blog_ids = array();
267    }
268
269    /**
270     * Register our routes.
271     */
272    public function register_routes() {
273        register_rest_route(
274            $this->namespace,
275            $this->rest_base,
276            array(
277                array(
278                    'methods'             => WP_REST_Server::READABLE,
279                    'callback'            => array( $this, 'get_data' ),
280                    'permission_callback' => array( $this, 'can_read' ),
281                    'args'                => array(
282                        // Testing aid: render the full task catalog so every task can be exercised from one site.
283                        'all_tasks' => array(
284                            'description' => 'Return the full task catalog instead of the tailored list (testing aid).',
285                            'type'        => 'boolean',
286                            'default'     => false,
287                        ),
288                    ),
289                ),
290                array(
291                    'methods'             => WP_REST_Server::DELETABLE,
292                    'callback'            => array( $this, 'dismiss' ),
293                    'permission_callback' => array( $this, 'can_write' ),
294                ),
295            )
296        );
297
298        register_rest_route(
299            $this->namespace,
300            $this->rest_base . '/wizard',
301            array(
302                array(
303                    'methods'             => 'PUT',
304                    'callback'            => array( $this, 'update_wizard' ),
305                    'permission_callback' => array( $this, 'can_write' ),
306                    'args'                => array(
307                        'goal'        => array(
308                            'description' => 'The site goal picked in the wizard.',
309                            'type'        => 'string',
310                            'enum'        => array( 'write', 'build', 'sell', 'newsletter', 'educate', 'portfolio' ),
311                            'required'    => true,
312                        ),
313                        'site_name'   => array(
314                            'description'       => 'The site name entered in the wizard.',
315                            'type'              => 'string',
316                            'required'          => true,
317                            'sanitize_callback' => 'sanitize_text_field',
318                        ),
319                        'description' => array(
320                            'description'       => 'The free-text site description entered in the wizard.',
321                            'type'              => 'string',
322                            'required'          => true,
323                            'sanitize_callback' => 'sanitize_textarea_field',
324                        ),
325                        'locale'      => array(
326                            'description'       => 'The site language the AI writes the drafts and page intros in.',
327                            'type'              => 'string',
328                            'default'           => 'en',
329                            'sanitize_callback' => 'sanitize_text_field',
330                        ),
331                        'ui_locale'   => array(
332                            'description'       => 'The account language the AI writes the task subtitles in.',
333                            'type'              => 'string',
334                            'default'           => 'en',
335                            'sanitize_callback' => 'sanitize_text_field',
336                        ),
337                    ),
338                ),
339            )
340        );
341
342        register_rest_route(
343            $this->namespace,
344            $this->rest_base . '/available-tasks',
345            array(
346                array(
347                    'methods'             => WP_REST_Server::READABLE,
348                    'callback'            => array( $this, 'get_available_tasks' ),
349                    'permission_callback' => array( $this, 'can_read' ),
350                    'args'                => array(
351                        'goal' => array(
352                            'description'       => 'The selected goal; sell keeps commerce tasks as available previews.',
353                            'type'              => 'string',
354                            'default'           => '',
355                            'sanitize_callback' => 'sanitize_key',
356                        ),
357                    ),
358                ),
359            )
360        );
361
362        register_rest_route(
363            $this->namespace,
364            $this->rest_base . '/complete-task',
365            array(
366                array(
367                    'methods'             => 'POST',
368                    'callback'            => array( $this, 'complete_task' ),
369                    'permission_callback' => array( $this, 'can_write' ),
370                    'args'                => array(
371                        'task_id' => array(
372                            'description'       => 'The acknowledgment task to mark complete.',
373                            'type'              => 'string',
374                            'required'          => true,
375                            'sanitize_callback' => 'sanitize_key',
376                        ),
377                    ),
378                ),
379            )
380        );
381
382        register_rest_route(
383            $this->namespace,
384            $this->rest_base . '/skip-task',
385            array(
386                array(
387                    'methods'             => 'POST',
388                    'callback'            => array( $this, 'skip_task' ),
389                    'permission_callback' => array( $this, 'can_write' ),
390                    'args'                => array(
391                        'task_id' => array(
392                            'description'       => 'The task to skip.',
393                            'type'              => 'string',
394                            'required'          => true,
395                            'sanitize_callback' => 'sanitize_key',
396                        ),
397                    ),
398                ),
399            )
400        );
401
402        register_rest_route(
403            $this->namespace,
404            $this->rest_base . '/tailored',
405            array(
406                array(
407                    'methods'             => 'PUT',
408                    'callback'            => array( $this, 'update_tailored' ),
409                    'permission_callback' => array( $this, 'can_write' ),
410                    'args'                => array(
411                        'source'            => array(
412                            'description' => 'Whether the payload came from the AI or the deterministic fallback. Query parameter; the JSON body must match the agent output schema exactly.',
413                            'type'        => 'string',
414                            'enum'        => array( 'ai', 'fallback' ),
415                            'default'     => 'ai',
416                        ),
417                        'duration_ms'       => array(
418                            'description' => 'Client-measured tailoring duration in milliseconds, for the tailored Logstash record.',
419                            'type'        => 'integer',
420                            'minimum'     => 0,
421                        ),
422                        'attempts'          => array(
423                            'description' => 'How many jetpack-ai-query attempts the client made, for the tailored Logstash record.',
424                            'type'        => 'integer',
425                            'minimum'     => 0,
426                        ),
427                        'ai_session_id'     => array(
428                            'description'       => 'Client-minted id for this tailoring run, carried by every Tracks event fired afterwards.',
429                            'type'              => 'string',
430                            'default'           => '',
431                            // A UUID is 36 characters; 64 leaves headroom without letting an
432                            // oversized value reach the option, the inline script, and every
433                            // Tracks event. sanitize_key() doesn't bound length on its own, so
434                            // the validate_callback is what actually enforces maxLength here â€”
435                            // WP only runs per-arg schema validation when one is wired in.
436                            'maxLength'         => 64,
437                            'sanitize_callback' => 'sanitize_key',
438                            'validate_callback' => 'rest_validate_request_arg',
439                        ),
440                        'validation_errors' => array(
441                            'description'       => 'Why each failed jetpack-ai-query attempt failed, one entry per attempt (schema paths and rule names, never values), for the tailored Logstash record.',
442                            'type'              => 'array',
443                            'items'             => array( 'type' => 'string' ),
444                            'default'           => array(),
445                            // Sanitized down rather than validated: a malformed diagnostic must never cost the
446                            // user their tailored list.
447                            'sanitize_callback' => array( self::class, 'sanitize_validation_errors' ),
448                        ),
449                    ),
450                ),
451            )
452        );
453    }
454
455    /**
456     * Sanitizes the client-reported jetpack-ai-query failure reasons for the `tailored` Logstash record.
457     *
458     * The client sends only schema paths and rule names. This keeps it that way for any caller: anything that is
459     * not a string is dropped, every reason is reduced to the characters such a path and rule use (no quotes, so no
460     * quoted value survives), each is cut to MAX_VALIDATION_ERROR_LENGTH, and at most MAX_VALIDATION_ERRORS are kept.
461     *
462     * @param mixed $value The raw param value.
463     * @return string[] The sanitized reasons.
464     */
465    public static function sanitize_validation_errors( $value ) {
466        if ( is_string( $value ) ) {
467            $value = array( $value );
468        }
469        if ( ! is_array( $value ) ) {
470            return array();
471        }
472
473        $reasons = array();
474        foreach ( $value as $reason ) {
475            if ( ! is_string( $reason ) ) {
476                continue;
477            }
478            $reason = trim( substr( (string) preg_replace( '/[^A-Za-z0-9_.$\[\]:;<>= -]/', '', $reason ), 0, self::MAX_VALIDATION_ERROR_LENGTH ) );
479            if ( '' === $reason ) {
480                continue;
481            }
482            $reasons[] = $reason;
483            if ( count( $reasons ) >= self::MAX_VALIDATION_ERRORS ) {
484                break;
485            }
486        }
487
488        return $reasons;
489    }
490
491    /**
492     * Permission callback for reads.
493     *
494     * @return true|WP_Error|false
495     */
496    public function can_read() {
497        if ( ! current_user_can( 'edit_posts' ) ) {
498            return false;
499        }
500
501        return $this->check_eligibility();
502    }
503
504    /**
505     * Permission callback for writes.
506     *
507     * @return true|WP_Error|false
508     */
509    public function can_write() {
510        if ( ! current_user_can( 'manage_options' ) ) {
511            return false;
512        }
513
514        return $this->check_eligibility();
515    }
516
517    /**
518     * Returns a 404 error for ineligible sites, true otherwise.
519     *
520     * @return true|WP_Error
521     */
522    private function check_eligibility() {
523        // Fail closed: if the gate is unavailable, treat the site as not eligible.
524        if ( ! function_exists( 'wpcom_ai_launchpad_is_eligible' ) || ! wpcom_ai_launchpad_is_eligible() ) {
525            return new WP_Error(
526                'ai_launchpad_not_eligible',
527                __( 'This site is not eligible for the AI Launchpad.', 'jetpack-mu-wpcom' ),
528                array( 'status' => 404 )
529            );
530        }
531
532        return true;
533    }
534
535    /**
536     * Composite read: wizard payload, AI output, enriched tasks, statuses, and eligibility.
537     *
538     * @param WP_REST_Request|null $request Request object (for the `all_tasks` testing param).
539     * @return array
540     */
541    public function get_data( $request = null ) {
542        $wizard    = get_option( self::OPTION_WIZARD );
543        $ai_output = get_option( self::OPTION_AI_OUTPUT );
544        if ( is_array( $ai_output ) ) {
545            // Internal analytics bookkeeping (see report_task_completions), not part of the client contract.
546            unset( $ai_output['tracked_completed'] );
547        }
548
549        // Testing aid: ?all_tasks=1 renders the whole catalog, independent of the persisted tailored output.
550        $all_tasks = $request instanceof WP_REST_Request && $request->get_param( 'all_tasks' );
551
552        // The client shows the wizard when there is no AI output and ?all_tasks=1 is off (decideInitialView()
553        // in js/lib/orchestration.ts). The banner never renders there, so skip the offer and its ExPlat
554        // assignment: a user who sees only the wizard must not count as exposed. The list reads this endpoint
555        // again once the wizard finishes, and that read carries the offer.
556        $shows_wizard = ! is_array( $ai_output ) && ! $all_tasks;
557
558        // Assigned before the tasks are built, so the launch task's title (which only peeks) matches its CTA.
559        $use_publish_copy = ! $shows_wizard && wpcom_site_launch_uses_publish_copy();
560
561        if ( $all_tasks ) {
562            $tasks = $this->apply_skipped_tasks( $this->build_all_catalog_tasks() );
563        } else {
564            $tasks = $this->get_current_tasks();
565        }
566
567        // The membership tasks' completion is recomputed in build_tasks(), so overlay it to keep
568        // checklist_statuses consistent with tasks[].completed for them.
569        $checklist_statuses = (array) get_option( 'launchpad_checklist_tasks_statuses', array() );
570        foreach ( $tasks as $task ) {
571            if ( AI_Launchpad_Memberships::has_override( $task['id'] ) ) {
572                $checklist_statuses[ $task['id'] ] = $task['completed'];
573            }
574        }
575
576        $this->maybe_mark_completed();
577
578        return array(
579            'wizard'             => is_array( $wizard ) ? $wizard : null,
580            'ai_output'          => is_array( $ai_output ) ? $ai_output : null,
581            'tasks'              => $tasks,
582            'checklist_statuses' => $checklist_statuses,
583            'dismissed'          => (bool) get_option( self::OPTION_DISMISSED, false ),
584            // Lets the page celebrate a list finished elsewhere, which this read latches.
585            'list_completed'     => (bool) get_option( self::OPTION_COMPLETED ),
586            'is_eligible'        => true,
587            // The language this request is translated into, which is the reader's own. Task subtitles
588            // follow it, since they are read here and never published.
589            'user_language'      => determine_locale(),
590            // Site context the client needs for the launch-task CTA, the preview thumbnail/title, and wizard prefill.
591            'site'               => array(
592                'url'         => home_url(),
593                'title'       => get_bloginfo( 'name' ),
594                'description' => get_bloginfo( 'description' ),
595                // Block themes open the Site Editor; classic themes fall back to the Customizer.
596                'edit_url'    => wp_is_block_theme() ? admin_url( 'site-editor.php' ) : admin_url( 'customize.php' ),
597                // The site language, which the AI output and the copy written into pages follow.
598                'language'    => wpcom_ai_launchpad_site_locale(),
599                'copy'        => wpcom_ai_launchpad_site_copy(),
600            ),
601            // The free DIFM offer banner under the task list, or null when it must not show.
602            'difm_offer'         => $shows_wizard ? null : AI_Launchpad_Difm_Offer::get_offer(),
603            // Whether the launch task's CTA says "Publish" instead of "Launch".
604            'use_publish_copy'   => $use_publish_copy,
605        );
606    }
607
608    /**
609     * The site's tailored task list (AI-selected + the synthetic store tasks, skip overlay applied) â€” the tasks
610     * GET renders, minus the ?all_tasks testing view. Shared by GET and the completion check.
611     *
612     * @return array
613     */
614    public function get_current_tasks() {
615        $ai_output = get_option( self::OPTION_AI_OUTPUT );
616
617        // Guard the nested payload: partial/failed writes may leave the option without payload.tasks.
618        $payload = is_array( $ai_output ) && isset( $ai_output['payload'] ) && is_array( $ai_output['payload'] )
619            ? $ai_output['payload']
620            : array();
621        // Validate `inferred` as an array before reading from it, since a partial write could leave it non-array.
622        $inferred       = isset( $payload['inferred'] ) && is_array( $payload['inferred'] ) ? $payload['inferred'] : array();
623        $theme_category = isset( $inferred['theme_category'] ) && is_string( $inferred['theme_category'] )
624            ? $inferred['theme_category']
625            : '';
626
627        // The same authority update_tailored() enforces against: the user's own wizard goal, not the
628        // model's echo of it. Anything else lets PUT strip a goal's tasks while GET injects them.
629        $goal = wpcom_ai_launchpad_resolve_goal( $payload );
630
631        if ( ! function_exists( 'is_plugin_active' ) ) {
632            require_once ABSPATH . 'wp-admin/includes/plugin.php';
633        }
634        $woo_active = is_plugin_active( 'woocommerce/woocommerce.php' );
635
636        // On a sell site without WooCommerce, keep the gated commerce tasks as a disabled preview of the store
637        // roadmap instead of dropping them (which would collapse the list to almost nothing).
638        $disable_hidden_woo = 'sell' === $goal && ! $woo_active;
639
640        $theme_cta = $this->get_themes_showcase_path( $goal, $theme_category );
641
642        $ai_tasks = isset( $payload['tasks'] ) && is_array( $payload['tasks'] ) ? $payload['tasks'] : array();
643
644        // A store needs a theme, so the sell list always offers "Choose a theme" â€” the AI is not required to pick
645        // one. Add it when absent so build_tasks enriches it like any catalog task (get_ai_task_ids mirrors this).
646        if ( 'sell' === $goal ) {
647            $ai_tasks = $this->ensure_theme_task( $ai_tasks );
648        }
649
650        $tasks = empty( $ai_tasks ) ? array() : $this->build_tasks( $ai_tasks, false, $theme_cta, $disable_hidden_woo );
651
652        // The sell goal leads with the store-setup tasks; the theme task then follows them: pick the
653        // store's look once the store exists. Other goals need no injection â€” the gallery task is now
654        // on the menu, so the AI picks it when the site is visual.
655        if ( 'sell' === $goal ) {
656            $tasks = array_merge( $this->build_store_tasks( $woo_active ), $tasks );
657            $tasks = $this->move_task_after( $tasks, 'site_theme_selected', 'setup_woocommerce_store' );
658        }
659
660        // Restore the list toward six after the visibility gate has dropped tasks (before skips, which are the
661        // user's own removals). No-op on an empty list so the wizard still runs when there is no AI output.
662        $tasks = $this->backfill_to_minimum( $tasks, $theme_cta, $disable_hidden_woo );
663
664        return $this->apply_skipped_tasks( $tasks );
665    }
666
667    /**
668     * Tops a short rendered list back up toward the six tasks the AI is asked to return.
669     *
670     * The catalog visibility gate in build_tasks() drops any task it hides on this site (e.g. add_about_page needs a
671     * page-template meta key that is absent during a REST request) with no replacement, so a gate-heavy AI pick can
672     * collapse the list to two or three cards. This backfills from a small pool of broadly-useful tasks and keeps the
673     * launch task last. Candidates are built one at a time, stopping at the target, so the tail of the pool is only
674     * evaluated when the earlier fillers were not enough â€” mobile_app_installed's completion check does a remote
675     * lookup while incomplete, which the common short-by-one list never has to pay for. Backfilled cards are
676     * skippable (see skip_task); a fuller, AI-ranked overflow pool is the eventual replacement.
677     *
678     * @param array  $tasks              The rendered task list, already gated, launch task last.
679     * @param string $theme_cta          Pre-resolved themes-showcase CTA passed through to build_tasks().
680     * @param bool   $disable_hidden_woo Whether hidden commerce tasks render as a disabled preview.
681     * @return array
682     */
683    private function backfill_to_minimum( $tasks, $theme_cta, $disable_hidden_woo ) {
684        $target = 6;
685        if ( count( $tasks ) >= $target || empty( $tasks ) ) {
686            return $tasks;
687        }
688
689        foreach ( $this->backfill_pool() as $id => $subtitle ) {
690            if ( count( $tasks ) >= $target ) {
691                break;
692            }
693            $present = array_column( $tasks, 'id' );
694            if ( in_array( $id, $present, true ) ) {
695                continue;
696            }
697
698            // build_tasks() applies the same gating and remap the AI list gets, so a pool task the site
699            // hides simply does not appear.
700            $built = $this->build_tasks(
701                array(
702                    array(
703                        'id'       => $id,
704                        'subtitle' => $subtitle,
705                    ),
706                ),
707                false,
708                $theme_cta,
709                $disable_hidden_woo
710            );
711            if ( empty( $built ) ) {
712                continue;
713            }
714            $task = $built[0];
715            // A filler card that is already complete offers nothing to do; better a shorter list. The remap
716            // inside build_tasks() can also land the card on an id already present â€” skip that too.
717            if ( ! empty( $task['completed'] ) || in_array( $task['id'], $present, true ) ) {
718                continue;
719            }
720            $tasks = $this->insert_before_launch_task( $tasks, $task );
721        }
722
723        return $tasks;
724    }
725
726    /**
727     * The ordered id => subtitle pool the short-list backfill draws from: broadly-useful tasks that render on most
728     * sites and are skippable, most-broadly-applicable first. Each has a distinct card title, and none duplicate work
729     * the wizard already did (e.g. no site-title task â€” the wizard captured the name). Excludes tasks whose completion
730     * depends on the AI-task list (the theme/social listeners, the complete-on-click route), since a backfilled card is
731     * not on that list. skip_task() reads the ids here to keep every backfilled card skippable, so the set lives here.
732     *
733     * @return array<string, string>
734     */
735    private function backfill_pool() {
736        return array(
737            'design_edited'        => __( 'Make the design your own.', 'jetpack-mu-wpcom' ),
738            'add_new_page'         => __( 'Add a page your visitors will want, like About or Contact.', 'jetpack-mu-wpcom' ),
739            'connect_social_media' => __( 'Connect your social accounts to reach more people.', 'jetpack-mu-wpcom' ),
740            'mobile_app_installed' => __( 'Manage your site from anywhere with the Jetpack app.', 'jetpack-mu-wpcom' ),
741        );
742    }
743
744    /**
745     * Runs the completion pass: reports newly-completed tasks to Tracks, then latches OPTION_COMPLETED (and records
746     * the all-tasks-completed event) the first time the list is fully done. Called on every path that can finish a
747     * task (read, skip, complete-on-click, a COMPLETION_TRIGGER_OPTIONS write); the already-set check skips the
748     * rebuild once latched.
749     *
750     * @return void
751     */
752    private function maybe_mark_completed() {
753        if ( get_option( self::OPTION_COMPLETED ) ) {
754            return;
755        }
756
757        // No AI output means the wizard hasn't produced a list yet: nothing to report or latch.
758        if ( ! get_option( self::OPTION_AI_OUTPUT ) ) {
759            return;
760        }
761
762        $tasks = $this->get_current_tasks();
763        // After the rebuild, whose own status writes queue a pass too: this one covers them all.
764        unset( $this->pending_completion_blog_ids[ get_current_blog_id() ] );
765        // An empty list is not "complete" â€” the wizard still needs to run.
766        if ( empty( $tasks ) ) {
767            return;
768        }
769
770        $this->report_task_completions( $tasks );
771
772        foreach ( $tasks as $task ) {
773            // A skip coerces `completed` true; a disabled preview task stays incomplete until its prerequisite is met.
774            if ( empty( $task['completed'] ) ) {
775                return;
776            }
777        }
778
779        update_option( self::OPTION_COMPLETED, true, true );
780        // After the per-task reports above, so any task_completed reports precede it (a list finished
781        // purely by skips or born-completed tasks latches with none).
782        wpcom_ai_launchpad_record_tracks_event(
783            'jetpack_ai_launchpad_all_tasks_completed',
784            array(),
785            array_column( $tasks, 'id' )
786        );
787    }
788
789    /**
790     * Records a `task_completed` Tracks event for every rendered task that newly reads as completed, whatever
791     * completed it (client click, PHP listener, or live recomputation Ã  la Woo/domains/memberships) â€” the only
792     * uniform signal is the rendered list itself, so completions are diffed on read.
793     *
794     * The already-reported ids are embedded in the existing AI-output envelope (`tracked_completed`) rather than a
795     * new option; a re-tailor rewrites the envelope, which re-baselines the set at the same moment the skip/completed
796     * options reset. PUT /tailored seeds the key with the born-completed tasks, so a pass here only ever reports
797     * user-triggered completions; an envelope persisted before the key existed gets the same silent baseline on its
798     * first pass. Skipped tasks render as completed but already emit `task_skipped`, so they are excluded (and never
799     * reported later).
800     *
801     * @param array $tasks The current rendered tasks.
802     * @return void
803     */
804    private function report_task_completions( $tasks ) {
805        $ai_output = get_option( self::OPTION_AI_OUTPUT );
806        if ( ! is_array( $ai_output ) ) {
807            return;
808        }
809
810        $skipped   = $this->get_skipped_task_ids();
811        $completed = array();
812        foreach ( $tasks as $task ) {
813            if ( ! empty( $task['completed'] ) && ! in_array( $task['id'], $skipped, true ) ) {
814                $completed[] = $task['id'];
815            }
816        }
817
818        // null = no key yet, i.e. the baseline pass right after tailoring. Remapped like the skip overlay: a
819        // baseline recorded under a since-remapped id must keep covering the id its card renders as now, or the
820        // same completion would be re-reported once under the new id.
821        $reported = isset( $ai_output['tracked_completed'] ) && is_array( $ai_output['tracked_completed'] )
822            ? array_values( array_unique( array_map( 'wpcom_ai_launchpad_remap_task_id', $ai_output['tracked_completed'] ) ) )
823            : null;
824        $newly    = array_values( array_diff( $completed, $reported ?? array() ) );
825
826        if ( null !== $reported ) {
827            if ( empty( $newly ) ) {
828                return;
829            }
830            $rendered_ids = array_column( $tasks, 'id' );
831            foreach ( $newly as $task_id ) {
832                wpcom_ai_launchpad_record_tracks_event(
833                    'jetpack_ai_launchpad_task_completed',
834                    array( 'task_id' => $task_id ),
835                    $rendered_ids
836                );
837            }
838        }
839
840        $ai_output['tracked_completed'] = array_merge( $reported ?? array(), $newly );
841        update_option( self::OPTION_AI_OUTPUT, $ai_output, false );
842    }
843
844    /**
845     * Persists the wizard input and writes the entered Name and Brief description back to blogname / blogdescription.
846     *
847     * Empty values are skipped so the wizard never blanks an existing title or tagline.
848     *
849     * @param WP_REST_Request $request Request object.
850     * @return array
851     */
852    public function update_wizard( $request ) {
853        $wizard = array(
854            'version'      => 1,
855            'goal'         => $request['goal'],
856            'site_name'    => $request['site_name'],
857            'description'  => $request['description'],
858            'locale'       => $request['locale'],
859            'ui_locale'    => $request['ui_locale'],
860            'generated_at' => time(),
861        );
862
863        update_option( self::OPTION_WIZARD, $wizard, false );
864
865        if ( '' !== trim( (string) $request['site_name'] ) ) {
866            update_option( 'blogname', $request['site_name'] );
867        }
868        if ( '' !== trim( (string) $request['description'] ) ) {
869            // Collapse the textarea brief's newlines to keep the inline-rendered tagline single-line.
870            update_option( 'blogdescription', sanitize_text_field( $request['description'] ) );
871        }
872
873        return array( 'wizard' => $wizard );
874    }
875
876    /**
877     * Validates the AI output payload against the agent output schema, wraps it, and persists it.
878     *
879     * @param WP_REST_Request $request Request object.
880     * @return array|WP_Error
881     */
882    public function update_tailored( $request ) {
883        $payload = $request->get_json_params();
884
885        $validation = rest_validate_value_from_schema( $payload, $this->get_output_schema(), 'payload' );
886        if ( is_wp_error( $validation ) ) {
887            return new WP_Error( 'ai_launchpad_invalid_payload', $validation->get_error_message(), array( 'status' => 422 ) );
888        }
889
890        $last_task = end( $payload['tasks'] );
891        if ( ! in_array( $last_task['id'], self::LAUNCH_TASK_IDS, true ) ) {
892            return new WP_Error(
893                'ai_launchpad_missing_launch_task',
894                __( 'The last task must be a launch task.', 'jetpack-mu-wpcom' ),
895                array( 'status' => 422 )
896            );
897        }
898
899        // The AI's raw picks, captured before the unknown-id filter below so hallucinated ids stay observable.
900        $raw_task_ids = array_column( $payload['tasks'], 'id' );
901
902        $definitions = wpcom_launchpad_get_task_definitions();
903        $tasks       = array();
904
905        // The exclusions key off the goal the user chose, resolved through the shared helper so this and the
906        // read path cannot disagree about which goal the site has.
907        $excluded = self::excluded_task_ids_for_goal( wpcom_ai_launchpad_resolve_goal( $payload ) );
908
909        foreach ( $payload['tasks'] as $task ) {
910            // Judge â€” and persist â€” the id this task will actually render as. build_tasks() remaps broken and
911            // twinned ids on read, so checking the raw id would let a restricted task in under its other name:
912            // `subscribers_added` is off the menu and unrestricted, yet renders as the newsletter-restricted
913            // `import_subscribers`. The rule has to see the card, not the spelling.
914            $task_id = wpcom_ai_launchpad_remap_task_id( $task['id'] );
915
916            if ( ! isset( $definitions[ $task_id ] ) && ! AI_Launchpad_Task_Registry::has( $task_id ) ) {
917                continue;
918            }
919
920            // Goal-restricted tasks are dropped even if the model picked them: the menu filter is advisory
921            // (a failed availability lookup falls back to the full menu), this is not.
922            if ( in_array( $task_id, $excluded, true ) ) {
923                continue;
924            }
925
926            $subtitle = $this->sanitize_subtitle( $task['subtitle'] );
927            if ( is_wp_error( $subtitle ) ) {
928                return $subtitle;
929            }
930
931            $tasks[] = array(
932                'id'       => $task_id,
933                'subtitle' => $subtitle,
934            );
935        }
936
937        if ( count( $tasks ) < self::MIN_VALID_TASKS ) {
938            return new WP_Error(
939                'ai_launchpad_unknown_tasks',
940                __( 'Too few tasks matched the task catalog.', 'jetpack-mu-wpcom' ),
941                array( 'status' => 422 )
942            );
943        }
944
945        $payload['tasks'] = $tasks;
946
947        $ai_output = array(
948            'version'      => 1,
949            'source'       => $request['source'],
950            'generated_at' => time(),
951            'payload'      => $payload,
952        );
953
954        // Omitted rather than stored empty, so the props builder reports "none" for a write
955        // that carried no session id (a client from before this shipped, or a direct call).
956        if ( '' !== $request['ai_session_id'] ) {
957            $ai_output['ai_session_id'] = $request['ai_session_id'];
958        }
959
960        update_option( self::OPTION_AI_OUTPUT, $ai_output, false );
961
962        // A fresh list must not inherit the previous one's skips or "done" flag.
963        delete_option( self::OPTION_SKIPPED );
964        delete_option( self::OPTION_COMPLETED );
965
966        // Baseline the born-completed tasks now (needs the fresh options above), so completion
967        // reporting only ever emits for completions the user actually triggers afterwards.
968        $rendered_tasks = $this->get_current_tasks();
969        $baseline       = array();
970        foreach ( $rendered_tasks as $task ) {
971            if ( ! empty( $task['completed'] ) ) {
972                $baseline[] = $task['id'];
973            }
974        }
975        $ai_output['tracked_completed'] = $baseline;
976        update_option( self::OPTION_AI_OUTPUT, $ai_output, false );
977
978        // After the writes, so the observed rendered list is the fresh one.
979        $this->log_tailoring( $ai_output, $raw_task_ids, $request['duration_ms'], $request['attempts'], array_column( $rendered_tasks, 'id' ), (array) $request['validation_errors'] );
980
981        // The analytics bookkeeping stays out of responses, mirroring get_data().
982        unset( $ai_output['tracked_completed'] );
983
984        return array( 'ai_output' => $ai_output );
985    }
986
987    /**
988     * Emits the tailoring observation event to Logstash, keyed `feature: atomic_ai_launchpad`, `message: tailored`
989     * (the public-api logstash endpoint whitelists features by their `atomic_` prefix â€” a bare feature name is
990     * rejected with a 400 on the Atomic HTTP dispatch path). Best-effort: logging must never fail the tailoring write.
991     *
992     * @param array         $ai_output    The persisted AI output envelope.
993     * @param string[]      $raw_task_ids The AI's selected ids before the unknown-id filter.
994     * @param int|null      $duration_ms  Client-measured tailoring duration, or null when not sent.
995     * @param int|null      $attempts     Client-reported jetpack-ai-query attempt count, or null when not sent.
996     * @param string[]|null $rendered_ids The rendered task ids, when the caller already computed them.
997     * @param string[]      $validation_errors Why each failed jetpack-ai-query attempt failed, already sanitized.
998     * @return void
999     */
1000    private function log_tailoring( $ai_output, $raw_task_ids, $duration_ms = null, $attempts = null, $rendered_ids = null, $validation_errors = array() ) {
1001        try {
1002            /**
1003             * Gates the tailoring observation event sent to Logstash. Checked before the event
1004             * is built, so disabling it also skips the extra task-list rebuild the event needs.
1005             *
1006             * @param bool $enabled Whether to send the event. Default true.
1007             */
1008            if ( ! apply_filters( 'wpcom_ai_launchpad_tailoring_log_enabled', true ) ) {
1009                return;
1010            }
1011
1012            \Automattic\Jetpack\Jetpack_Mu_Wpcom::log2logstash(
1013                'atomic_ai_launchpad',
1014                'tailored',
1015                $this->tailoring_log_extra( $ai_output, $raw_task_ids, $duration_ms, $attempts, $rendered_ids, $validation_errors )
1016            );
1017        } catch ( \Throwable $e ) {
1018            unset( $e );
1019        }
1020    }
1021
1022    /**
1023     * The tailoring observation event: how the AI's output relates to what the site will actually render.
1024     *
1025     * Carries the inferred details, the AI's raw selected ids (pre-filter, so hallucinated ids are observable), the
1026     * rendered ids, and their delta â€” `dropped` is what the unknown-id filter and the visibility gate removed, `added`
1027     * is what synthetics and the backfill floor put in. The delta is diffed post-remap so a selected id that renders
1028     * under its working equivalent does not read as a drop plus an addition. The raw wizard title/description are
1029     * never included, and the one inferred field that echoes the user's own words near-verbatim is stripped:
1030     * `brand_name` restates the title.
1031     *
1032     * @param array         $ai_output    The persisted AI output envelope.
1033     * @param string[]      $raw_task_ids The AI's selected ids before the unknown-id filter.
1034     * @param int|null      $duration_ms  Client-measured tailoring duration, or null when not sent.
1035     * @param int|null      $attempts     Client-reported jetpack-ai-query attempt count, or null when not sent.
1036     * @param string[]|null $rendered_ids The rendered task ids, when the caller already computed them.
1037     * @param string[]      $validation_errors Why each failed jetpack-ai-query attempt failed, already sanitized.
1038     * @return array
1039     */
1040    private function tailoring_log_extra( $ai_output, $raw_task_ids, $duration_ms = null, $attempts = null, $rendered_ids = null, $validation_errors = array() ) {
1041        // Schema-validated on the write path, so `inferred` is always present here.
1042        $inferred = $ai_output['payload']['inferred'];
1043        unset( $inferred['brand_name'] );
1044
1045        $rendered = $rendered_ids ?? array_column( $this->get_current_tasks(), 'id' );
1046        $remapped = array_unique( array_map( 'wpcom_ai_launchpad_remap_task_id', $raw_task_ids ) );
1047
1048        $extra = array(
1049            'source'   => $ai_output['source'],
1050            'inferred' => $inferred,
1051            'selected' => $raw_task_ids,
1052            'rendered' => $rendered,
1053            'dropped'  => array_values( array_diff( $remapped, $rendered ) ),
1054            'added'    => array_values( array_diff( $rendered, $remapped ) ),
1055        );
1056
1057        // Client-measured timing, replacing the retired ai_response_received Tracks event.
1058        if ( null !== $duration_ms ) {
1059            $extra['duration_ms'] = (int) $duration_ms;
1060        }
1061        if ( null !== $attempts ) {
1062            $extra['attempts'] = (int) $attempts;
1063        }
1064        // Only when an attempt failed, so a first-try success keeps the record's usual shape.
1065        if ( ! empty( $validation_errors ) ) {
1066            $extra['validation_errors'] = array_values( $validation_errors );
1067        }
1068
1069        return $extra;
1070    }
1071
1072    /**
1073     * Marks an acknowledgment task complete when the user clicks its CTA, since these tasks have no wp-admin signal.
1074     *
1075     * Restricted to the COMPLETE_ON_CLICK_TASK_IDS allowlist and to tasks on the site's AI-selected list.
1076     *
1077     * @param WP_REST_Request $request Request object.
1078     * @return array|WP_Error
1079     */
1080    public function complete_task( $request ) {
1081        $task_id = $request['task_id'];
1082
1083        if ( ! in_array( $task_id, self::COMPLETE_ON_CLICK_TASK_IDS, true ) ) {
1084            return new WP_Error(
1085                'ai_launchpad_task_not_completable',
1086                __( 'This task cannot be completed this way.', 'jetpack-mu-wpcom' ),
1087                array( 'status' => 400 )
1088            );
1089        }
1090
1091        // Only tasks the AI put on this site's list may be completed.
1092        if ( ! in_array( $task_id, wpcom_ai_launchpad_get_ai_task_ids(), true ) ) {
1093            return new WP_Error(
1094                'ai_launchpad_task_not_selected',
1095                __( 'This task is not on the tailored list.', 'jetpack-mu-wpcom' ),
1096                array( 'status' => 404 )
1097            );
1098        }
1099
1100        // The registry's ids are not in the shared catalog, and wpcom_mark_launchpad_task_complete() drops
1101        // what the catalog does not define, so those go through the registry's own write.
1102        if ( AI_Launchpad_Task_Registry::has( $task_id ) ) {
1103            AI_Launchpad_Task_Registry::mark_complete( $task_id );
1104        } else {
1105            wpcom_mark_launchpad_task_complete( $task_id );
1106        }
1107
1108        // Latch now so completing the last task hides the menu on the next page load, not just on the next read.
1109        $this->maybe_mark_completed();
1110
1111        return array(
1112            'completed'      => true,
1113            'task_id'        => $task_id,
1114            'list_completed' => (bool) get_option( self::OPTION_COMPLETED ),
1115        );
1116    }
1117
1118    /**
1119     * Marks a task as skipped: it renders (and counts) as completed without its real completion signal ever firing.
1120     *
1121     * Restricted to tasks on the site's AI-selected list, the synthetic ids the list adds itself, and the short-list
1122     * backfill pool â€” so every rendered card (AI, synthetic, or filler) is skippable. Persisted separately from
1123     * `launchpad_checklist_tasks_statuses` because several catalog tasks recompute completion live (memberships, woo,
1124     * domains) and would ignore a status write; the skip set is overlaid on read instead.
1125     *
1126     * @param WP_REST_Request $request Request object.
1127     * @return array|WP_Error
1128     */
1129    public function skip_task( $request ) {
1130        $task_id = $request['task_id'];
1131
1132        $skippable = array_merge( wpcom_ai_launchpad_get_ai_task_ids(), self::SYNTHETIC_TASK_IDS, array_keys( $this->backfill_pool() ) );
1133        if ( ! in_array( $task_id, $skippable, true ) ) {
1134            return new WP_Error(
1135                'ai_launchpad_task_not_skippable',
1136                __( 'This task is not on the tailored list.', 'jetpack-mu-wpcom' ),
1137                array( 'status' => 404 )
1138            );
1139        }
1140
1141        $skipped = $this->get_skipped_task_ids();
1142        if ( ! in_array( $task_id, $skipped, true ) ) {
1143            $skipped[] = $task_id;
1144            update_option( self::OPTION_SKIPPED, $skipped, false );
1145        }
1146
1147        // Latch now so skipping the last task hides the menu on the next page load, not just on the next read.
1148        $this->maybe_mark_completed();
1149
1150        return array(
1151            'skipped'        => true,
1152            'task_id'        => $task_id,
1153            'list_completed' => (bool) get_option( self::OPTION_COMPLETED ),
1154        );
1155    }
1156
1157    /**
1158     * Deletes the AI output and marks the AI Launchpad as dismissed.
1159     *
1160     * @return array
1161     */
1162    public function dismiss() {
1163        delete_option( self::OPTION_AI_OUTPUT );
1164        delete_option( self::OPTION_SKIPPED );
1165        delete_option( self::OPTION_COMPLETED );
1166        update_option( self::OPTION_DISMISSED, true, true );
1167
1168        return array( 'dismissed' => true );
1169    }
1170
1171    /**
1172     * The persisted skipped task ids, always as a clean string array, remapped onto the
1173     * ids the launchpad renders â€” a skip recorded under a task's raw id before that id
1174     * was remapped must keep applying to the card it renders as now.
1175     *
1176     * @return string[]
1177     */
1178    private function get_skipped_task_ids() {
1179        $skipped = get_option( self::OPTION_SKIPPED, array() );
1180        if ( ! is_array( $skipped ) ) {
1181            return array();
1182        }
1183
1184        $skipped = array_map( 'wpcom_ai_launchpad_remap_task_id', array_filter( $skipped, 'is_string' ) );
1185
1186        return array_values( array_unique( $skipped ) );
1187    }
1188
1189    /**
1190     * Overlays the persisted skips onto the enriched tasks: a skipped task carries `skipped: true` and is coerced to
1191     * completed, so progress, auto-expand, and reloads all treat it as done (a skip must never pop back open).
1192     *
1193     * @param array $tasks The enriched task list.
1194     * @return array
1195     */
1196    private function apply_skipped_tasks( $tasks ) {
1197        $skipped = $this->get_skipped_task_ids();
1198
1199        foreach ( $tasks as &$task ) {
1200            $task['skipped'] = in_array( $task['id'], $skipped, true );
1201            if ( $task['skipped'] ) {
1202                $task['completed'] = true;
1203            }
1204        }
1205        unset( $task );
1206
1207        return $tasks;
1208    }
1209
1210    /**
1211     * Strips HTML from a subtitle and rejects URLs and template syntax.
1212     *
1213     * @param string $subtitle The raw subtitle.
1214     * @return string|WP_Error The sanitized subtitle, or an error.
1215     */
1216    private function sanitize_subtitle( $subtitle ) {
1217        $subtitle = trim( wp_strip_all_tags( $subtitle, true ) );
1218
1219        if ( '' === $subtitle ) {
1220            return new WP_Error(
1221                'ai_launchpad_invalid_subtitle',
1222                __( 'Task subtitles must contain text.', 'jetpack-mu-wpcom' ),
1223                array( 'status' => 422 )
1224            );
1225        }
1226
1227        if ( preg_match( '#https?://#i', $subtitle ) ) {
1228            return new WP_Error(
1229                'ai_launchpad_subtitle_contains_url',
1230                __( 'Task subtitles must not contain URLs.', 'jetpack-mu-wpcom' ),
1231                array( 'status' => 422 )
1232            );
1233        }
1234
1235        if ( str_contains( $subtitle, '{{' ) || str_contains( $subtitle, '[[' ) ) {
1236            return new WP_Error(
1237                'ai_launchpad_subtitle_contains_template',
1238                __( 'Task subtitles must not contain template syntax.', 'jetpack-mu-wpcom' ),
1239                array( 'status' => 422 )
1240            );
1241        }
1242
1243        return mb_substr( $subtitle, 0, 200 );
1244    }
1245
1246    /**
1247     * Read endpoint backing the client's availability-aware tailoring: the task ids that will render for the given
1248     * goal. Fetched before the AI call, so the prompt offers only renderable tasks.
1249     *
1250     * @param WP_REST_Request $request Request object.
1251     * @return array
1252     */
1253    public function get_available_tasks( $request ) {
1254        $ids = $this->available_task_ids( (string) $request['goal'] );
1255        return array(
1256            'available_task_ids'  => $ids['actionable'],
1257            'renderable_task_ids' => $ids['renderable'],
1258        );
1259    }
1260
1261    /**
1262     * The task ids that must not be offered to, or accepted from, the model for a given goal.
1263     *
1264     * The two maps read in opposite directions, and an unknown or empty goal matches neither: every
1265     * GOAL_RESTRICTED_TASK_IDS entry is excluded (it never got the goal it requires), while every
1266     * GOAL_EXCLUDED_TASK_IDS entry is allowed (it never hit the goal that excludes it).
1267     *
1268     * @param string $goal The selected goal.
1269     * @return string[]
1270     */
1271    public static function excluded_task_ids_for_goal( $goal ) {
1272        $excluded = array();
1273
1274        foreach ( self::GOAL_RESTRICTED_TASK_IDS as $task_id => $required_goal ) {
1275            if ( $goal !== $required_goal ) {
1276                $excluded[] = $task_id;
1277            }
1278        }
1279
1280        foreach ( self::GOAL_EXCLUDED_TASK_IDS as $task_id => $excluded_goal ) {
1281            if ( $goal === $excluded_goal ) {
1282                $excluded[] = $task_id;
1283            }
1284        }
1285
1286        return $excluded;
1287    }
1288
1289    /**
1290     * The task ids that will actually render on this site for the given goal â€” the menu tailoring should choose from.
1291     *
1292     * Built by running the whole catalog through the real gate (visibility + force-visible overrides, and the sell
1293     * goal's woo-preview mode), so a task the AI could pick but the site would drop is never offered. `actionable`
1294     * additionally excludes tasks that are already complete â€” they leave nothing to do â€” except the launch tasks,
1295     * which the output contract requires last even on a site that already launched. `renderable` keeps the completed
1296     * ones: the client falls back to it when completion leaves too few actionable tasks to fill a valid list. The
1297     * client intersects these with its own TASK_MENU. Computed once per wizard submit.
1298     *
1299     * The AI Launchpad's own tasks are appended separately, since they are not catalog entries and the catalog
1300     * sweep cannot find them. They run their own gate on the way in: a registry definition may declare an
1301     * `is_visible` callable, and one that fails it is withheld from both lists here exactly as a catalog task
1302     * failing wpcom_launchpad_checklists()->is_visible() is. A definition without one is visible everywhere â€”
1303     * the gallery's shape, since it asks nothing of the site.
1304     *
1305     * @param string $goal The inferred/selected goal.
1306     * @return array{renderable: string[], actionable: string[]}
1307     */
1308    private function available_task_ids( $goal ) {
1309        if ( ! function_exists( 'is_plugin_active' ) ) {
1310            require_once ABSPATH . 'wp-admin/includes/plugin.php';
1311        }
1312        // Sell keeps the commerce tasks as a disabled preview until WooCommerce is active, so they count as available.
1313        $disable_hidden_woo = 'sell' === $goal && ! is_plugin_active( 'woocommerce/woocommerce.php' );
1314
1315        $tasks = $this->build_all_catalog_tasks( false, $disable_hidden_woo );
1316
1317        $actionable = array_filter(
1318            $tasks,
1319            static function ( $task ) {
1320                return ! $task['completed'] || in_array( $task['id'], self::LAUNCH_TASK_IDS, true );
1321            }
1322        );
1323
1324        $excluded = self::excluded_task_ids_for_goal( $goal );
1325
1326        // The registry's tasks are not in the catalog, so the sweep above cannot see them. Offer every registry
1327        // task that this site can render and that is not already complete; a completed one still renders, so it
1328        // stays on the renderable list the client relaxes to.
1329        $registry_renderable = array_values(
1330            array_filter(
1331                AI_Launchpad_Task_Registry::task_ids(),
1332                static function ( $task_id ) {
1333                    return AI_Launchpad_Task_Registry::is_visible( $task_id );
1334                }
1335            )
1336        );
1337        $registry_actionable = array_values(
1338            array_filter(
1339                $registry_renderable,
1340                static function ( $task_id ) {
1341                    return ! AI_Launchpad_Task_Registry::is_complete( $task_id );
1342                }
1343            )
1344        );
1345
1346        // array_unique guards a future registry id that shadows a catalog one: the endpoint would otherwise
1347        // advertise it twice.
1348        $renderable = array_unique( array_merge( array_column( $tasks, 'id' ), $registry_renderable ) );
1349        $actionable = array_unique( array_merge( array_column( $actionable, 'id' ), $registry_actionable ) );
1350
1351        return array(
1352            'renderable' => array_values( array_diff( $renderable, $excluded ) ),
1353            'actionable' => array_values( array_diff( $actionable, $excluded ) ),
1354        );
1355    }
1356
1357    /**
1358     * Builds the enriched task list for every catalog task (backs `?all_tasks=1` when the gate is bypassed, and
1359     * available_task_ids() when it is not).
1360     *
1361     * Each task is enriched in isolation so one that can't be built is skipped rather than breaking the whole view.
1362     *
1363     * @param bool $bypass_visibility  Whether to skip the catalog visibility gate (the testing view does).
1364     * @param bool $disable_hidden_woo Whether hidden commerce tasks render as a disabled preview instead of dropping.
1365     * @return array
1366     */
1367    private function build_all_catalog_tasks( $bypass_visibility = true, $disable_hidden_woo = false ) {
1368        $built    = array();
1369        $seen_ids = array();
1370        foreach ( array_keys( wpcom_launchpad_get_task_definitions() ) as $task_id ) {
1371            try {
1372                $one = $this->build_tasks(
1373                    array(
1374                        array(
1375                            'id'       => $task_id,
1376                            'subtitle' => $task_id,
1377                        ),
1378                    ),
1379                    $bypass_visibility,
1380                    null,
1381                    $disable_hidden_woo
1382                );
1383            } catch ( \Throwable $e ) {
1384                continue;
1385            }
1386            // build_tasks runs per id here, so its own dedup can't see this collision: the catalog holds both
1387            // `woo_launch_site` and `site_launched`, and the former is remapped onto the latter. Keep the first.
1388            $card = $one[0] ?? null;
1389            if ( null === $card || isset( $seen_ids[ $card['id'] ] ) ) {
1390                continue;
1391            }
1392            $seen_ids[ $card['id'] ] = true;
1393            $built[]                 = $card;
1394        }
1395        return $built;
1396    }
1397
1398    /**
1399     * Enriches the persisted tasks with title, completion state, and CTA path from the catalog.
1400     *
1401     * @param array       $tasks              The persisted `payload.tasks` array.
1402     * @param bool        $bypass_visibility  Skip the catalog visibility gate (for the all-tasks testing view).
1403     * @param string|null $theme_cta          The resolved themes-showcase path for the theme-picker tasks, or
1404     *                                        null to keep their default CTAs.
1405     * @param bool        $disable_hidden_woo Keep WOO_TASK_IDS that fail the visibility gate as disabled preview
1406     *                                        cards instead of dropping them (sell goal while WooCommerce is inactive).
1407     * @return array
1408     */
1409    private function build_tasks( $tasks, $bypass_visibility = false, $theme_cta = null, $disable_hidden_woo = false ) {
1410        $definitions = wpcom_launchpad_get_task_definitions();
1411        $built       = array();
1412        $seen_ids    = array();
1413
1414        // Some catalog visibility callbacks call is_plugin_active(), which is not loaded during a REST request.
1415        if ( ! function_exists( 'is_plugin_active' ) ) {
1416            require_once ABSPATH . 'wp-admin/includes/plugin.php';
1417        }
1418
1419        $is_private_site = $this->is_private_site();
1420
1421        foreach ( $tasks as $task ) {
1422            if ( ! is_array( $task ) || ! isset( $task['id'] ) || ! isset( $task['subtitle'] ) ) {
1423                continue;
1424            }
1425
1426            // Broken/meaningless-in-context ids render as their working equivalent (see the helper for the why).
1427            $task['id'] = wpcom_ai_launchpad_remap_task_id( $task['id'] );
1428
1429            // One card per id â€” the client keys cards by id. The remap above can collide with the target id already
1430            // being present (notably the ?all_tasks=1 view, which enumerates every catalog id), so collapse any
1431            // repeat to the first occurrence.
1432            if ( isset( $seen_ids[ $task['id'] ] ) ) {
1433                continue;
1434            }
1435
1436            // Tasks the AI Launchpad owns are built from its own registry: the shared catalog does not
1437            // define them, and routing them through wpcom_launchpad_checklists() would mean relying on
1438            // the catalog accepting entries it never registered.
1439            if ( AI_Launchpad_Task_Registry::has( $task['id'] ) ) {
1440                // The registry's own visibility gate, filtered on read for the same reason as the catalog's
1441                // below: a persisted list outlives the site state it was tailored for, so a task whose
1442                // precondition has since gone must stop rendering rather than offer a CTA that leads nowhere.
1443                if ( ! $bypass_visibility && ! AI_Launchpad_Task_Registry::is_visible( $task['id'] ) ) {
1444                    continue;
1445                }
1446
1447                $card = AI_Launchpad_Task_Registry::build( $task['id'], (string) $task['subtitle'] );
1448                if ( null !== $card ) {
1449                    $seen_ids[ $task['id'] ] = true;
1450                    $built[]                 = $card;
1451                }
1452                continue;
1453            }
1454
1455            if ( ! isset( $definitions[ $task['id'] ] ) ) {
1456                continue;
1457            }
1458
1459            // The Jetpack Social tasks point at an admin page wpcom doesn't load on a private site, so hide them there.
1460            if ( $is_private_site && in_array( $task['id'], self::SOCIAL_PAGE_TASK_IDS, true ) ) {
1461                continue;
1462            }
1463
1464            $definition       = $definitions[ $task['id'] ];
1465            $definition['id'] = $task['id'];
1466            $disabled         = false;
1467
1468            // Honor the catalog's own visibility gate: a task the catalog would hide here must not render, since its
1469            // CTA would 404 and it could never complete. Filtered on read so the deterministic fallback stays usable.
1470            if (
1471                ! $bypass_visibility
1472                && ! in_array( $task['id'], self::FORCE_VISIBLE_TASK_IDS, true )
1473                && ! wpcom_launchpad_checklists()->is_visible( $definition )
1474            ) {
1475                // On a sell site without WooCommerce, keep the commerce tasks as a disabled preview of the store
1476                // roadmap rather than dropping them and collapsing the list. Everything else stays hidden.
1477                if ( $disable_hidden_woo && in_array( $task['id'], self::WOO_TASK_IDS, true ) ) {
1478                    $disabled = true;
1479                } else {
1480                    continue;
1481                }
1482            }
1483
1484            if ( $disabled ) {
1485                // A disabled preview always renders as the locked card: never resolve its completion (the woo
1486                // completion callback marks the task complete as a side effect, which must not fire on a read) and
1487                // never resolve a CTA path (it has no reachable action).
1488                $completed    = false;
1489                $calypso_path = null;
1490            } else {
1491                // The membership tasks' catalog callbacks are always false on Atomic; recompute from local signals.
1492                $completed = AI_Launchpad_Memberships::has_override( $task['id'] )
1493                    ? AI_Launchpad_Memberships::is_task_complete( $task['id'] )
1494                    : wpcom_launchpad_checklists()->is_task_complete( $definition );
1495
1496                // The theme-picker task points at the showcase pre-filtered for the site (Store category on sell,
1497                // the AI's inferred category elsewhere) instead of plain themes.php. The legacy design_selected/
1498                // design_completed ids consolidate onto site_theme_selected via wpcom_ai_launchpad_remap_task_id().
1499                $theme_showcase_path = 'site_theme_selected' === $task['id'] ? $theme_cta : null;
1500                $cta_override        = $this->get_cta_override( $task['id'] );
1501                if ( null !== $theme_showcase_path ) {
1502                    $calypso_path = $theme_showcase_path;
1503                } elseif ( null !== $cta_override ) {
1504                    $calypso_path = $cta_override;
1505                } else {
1506                    $calypso_path = wpcom_launchpad_checklists()->load_calypso_path( $definition );
1507                }
1508
1509                // Simple sites have no reachable wp-admin plugins screen; route any plugin-screen CTA to Calypso.
1510                $calypso_path = wpcom_ai_launchpad_to_simple_plugins_path( $calypso_path );
1511            }
1512
1513            $title       = isset( $definition['get_title'] ) ? $definition['get_title']() : '';
1514            $in_progress = false;
1515
1516            // A saved-but-unpublished draft (found by marker meta) puts a site-editor task "in progress": reopen that
1517            // draft instead of creating a new one, and surface the drafts icon + a "Continue…" prompt in the card.
1518            if ( ! $completed && ! $disabled ) {
1519                $draft_url = $this->get_in_progress_draft_url( $task['id'] );
1520                if ( null !== $draft_url ) {
1521                    $in_progress  = true;
1522                    $calypso_path = $draft_url;
1523                }
1524            }
1525
1526            // Title follows our precise in-progress signal so it, the icon, and the CTA agree.
1527            $title = $this->get_task_title( $task['id'], $in_progress, $title );
1528
1529            $seen_ids[ $task['id'] ] = true;
1530            $built[]                 = array(
1531                'id'           => $task['id'],
1532                'subtitle'     => $task['subtitle'],
1533                'title'        => $title,
1534                'completed'    => $completed,
1535                'in_progress'  => $in_progress,
1536                'disabled'     => $disabled,
1537                'calypso_path' => $calypso_path,
1538            );
1539        }
1540
1541        return $built;
1542    }
1543
1544    /**
1545     * The wp-admin CTA destination the AI Launchpad substitutes for a task's catalog path, or null to keep the catalog's.
1546     *
1547     * Static repoints live in CTA_OVERRIDES; `add_subscribe_block` is resolved here because its destination depends on
1548     * the active theme: the Site Editor is where a block theme adds the Subscribe block to a template (the action its
1549     * completion listener watches), and the block-based widget editor is the closest equivalent on a classic theme
1550     * (normally unreachable â€” the task's catalog visibility is FSE-only â€” but the theme can change after tailoring).
1551     *
1552     * @param string $task_id The catalog task id.
1553     * @return string|null
1554     */
1555    private function get_cta_override( $task_id ) {
1556        if ( 'add_subscribe_block' === $task_id ) {
1557            return admin_url( wp_is_block_theme() ? 'site-editor.php' : 'widgets.php' );
1558        }
1559
1560        if ( isset( self::CTA_OVERRIDES[ $task_id ] ) ) {
1561            return admin_url( self::CTA_OVERRIDES[ $task_id ] );
1562        }
1563
1564        return null;
1565    }
1566
1567    /**
1568     * The theme-showcase subject-category slugs (the `subject` taxonomy from /rest/v1.2/theme-filters).
1569     * Every category carries free themes, unlike free-text search, which surfaces mostly paid results.
1570     */
1571    const THEME_CATEGORIES = array(
1572        'blog',
1573        'portfolio',
1574        'business',
1575        'store',
1576        'art-design',
1577        'about',
1578        'real-estate',
1579        'health-wellness',
1580        'authors-writers',
1581        'newsletter',
1582        'education',
1583        'magazine',
1584        'music',
1585        'restaurant',
1586        'travel-lifestyle',
1587        'fashion-beauty',
1588        'community-non-profit',
1589        'podcast',
1590        'entertainment',
1591    );
1592
1593    /**
1594     * The wordpress.com themes-showcase path the theme-picker tasks should point at.
1595     *
1596     * Sell sites always land on the showcase's Store category so shop-ready templates lead; other goals get the
1597     * showcase pre-filtered by the AI's inferred category, re-checked against the allowlist since the envelope is
1598     * stored data. Without a valid category the plain showcase is returned (never null: the catalog CTA can resolve
1599     * to wp-admin's themes.php, which skips the showcase). The client's `toNavigableUrl` resolves the relative path
1600     * against wordpress.com.
1601     *
1602     * @param string $goal     The inferred goal.
1603     * @param string $category The AI's inferred theme_category slug.
1604     * @return string
1605     */
1606    private function get_themes_showcase_path( $goal, $category ) {
1607        if ( 'sell' === $goal ) {
1608            $category = 'store';
1609        }
1610
1611        if ( ! in_array( $category, self::THEME_CATEGORIES, true ) ) {
1612            return '/themes/' . rawurlencode( wpcom_get_site_slug() );
1613        }
1614
1615        return '/themes/filter/' . $category . '/' . rawurlencode( wpcom_get_site_slug() );
1616    }
1617
1618    /**
1619     * Ensures the persisted task list contains the theme-picker task, appending `site_theme_selected` when no
1620     * task already resolves to it. A design task that remaps onto it (via wpcom_ai_launchpad_remap_task_id)
1621     * counts as present, so a theme card is never duplicated.
1622     *
1623     * @param array $tasks The persisted `payload.tasks` array.
1624     * @return array
1625     */
1626    private function ensure_theme_task( $tasks ) {
1627        foreach ( $tasks as $task ) {
1628            if ( is_array( $task ) && isset( $task['id'] ) && is_string( $task['id'] )
1629                && 'site_theme_selected' === wpcom_ai_launchpad_remap_task_id( $task['id'] ) ) {
1630                return $tasks;
1631            }
1632        }
1633
1634        $tasks[] = array(
1635            'id'       => 'site_theme_selected',
1636            'subtitle' => __( 'Choose a theme that fits your store.', 'jetpack-mu-wpcom' ),
1637        );
1638
1639        return $tasks;
1640    }
1641
1642    /**
1643     * Moves the task with the given id to immediately after another task. The list is returned unchanged
1644     * unless both ids are present.
1645     *
1646     * @param array  $tasks    The built task list.
1647     * @param string $move_id  The id of the task to move.
1648     * @param string $after_id The id of the task to place it after.
1649     * @return array
1650     */
1651    private function move_task_after( $tasks, $move_id, $after_id ) {
1652        $ids  = array_column( $tasks, 'id' );
1653        $from = array_search( $move_id, $ids, true );
1654        if ( false === $from || false === array_search( $after_id, $ids, true ) ) {
1655            return $tasks;
1656        }
1657
1658        $moved = array_splice( $tasks, $from, 1 );
1659        // Recompute the anchor: extracting an earlier element shifts it left by one.
1660        $to = array_search( $after_id, array_column( $tasks, 'id' ), true );
1661        array_splice( $tasks, $to + 1, 0, $moved );
1662
1663        return $tasks;
1664    }
1665
1666    /**
1667     * Builds the synthetic store-setup lead tasks for the sell goal: an "install WooCommerce" task and a "set up
1668     * your store" task. Their ids are listed in SYNTHETIC_TASK_IDS so the tasks stay skippable.
1669     *
1670     * Both are read live (installed/active/profiler options), so no marker or listener is needed. While WooCommerce
1671     * is inactive the setup task shows as a disabled preview, matching the disabled commerce tasks below it. Callers
1672     * gate this on the sell goal.
1673     *
1674     * @param bool $active Whether WooCommerce is active.
1675     * @return array The lead tasks in display order.
1676     */
1677    private function build_store_tasks( $active ) {
1678        return array(
1679            $this->build_install_woocommerce_task( $active ),
1680            $this->build_setup_store_task( $active ),
1681        );
1682    }
1683
1684    /**
1685     * The "Install the WooCommerce plugin" lead task: to-do until the plugin exists, in-progress while it is
1686     * installed-but-inactive, and complete once active.
1687     *
1688     * @param bool $active Whether WooCommerce is active.
1689     * @return array
1690     */
1691    private function build_install_woocommerce_task( $active ) {
1692        $in_progress = ! $active && array_key_exists( 'woocommerce/woocommerce.php', get_plugins() );
1693
1694        $calypso_path = null;
1695        if ( ! $active ) {
1696            // Installed-but-inactive activates from the plugins list; not-installed installs from the plugin search.
1697            // On Simple both wp-admin screens are unreachable, so route through the Calypso WooCommerce plugin page.
1698            $wp_admin_path = $in_progress
1699                ? admin_url( 'plugins.php?plugin_status=inactive' )
1700                : admin_url( 'plugin-install.php?s=woocommerce&tab=search&type=term' );
1701            $calypso_path  = wpcom_ai_launchpad_to_simple_plugins_path( $wp_admin_path, 'woocommerce' );
1702        }
1703
1704        return array(
1705            'id'           => 'install_woocommerce',
1706            'subtitle'     => $in_progress
1707                ? __( 'Activate the WooCommerce plugin to continue.', 'jetpack-mu-wpcom' )
1708                : __( 'Add the WooCommerce plugin to start selling.', 'jetpack-mu-wpcom' ),
1709            'title'        => __( 'Install the WooCommerce plugin', 'jetpack-mu-wpcom' ),
1710            'completed'    => $active,
1711            'in_progress'  => $in_progress,
1712            'disabled'     => false,
1713            'calypso_path' => $calypso_path,
1714        );
1715    }
1716
1717    /**
1718     * The "Set up your store" lead task: to-do until the WooCommerce setup wizard (core profiler) is completed or
1719     * skipped, then complete. Shown as a disabled preview until WooCommerce is active, since the wizard needs it.
1720     *
1721     * @param bool $active Whether WooCommerce is active.
1722     * @return array
1723     */
1724    private function build_setup_store_task( $active ) {
1725        $profile   = (array) get_option( 'woocommerce_onboarding_profile', array() );
1726        $completed = $active && ( ! empty( $profile['completed'] ) || ! empty( $profile['skipped'] ) );
1727
1728        return array(
1729            'id'           => 'setup_woocommerce_store',
1730            'subtitle'     => __( 'Complete or skip the WooCommerce setup wizard.', 'jetpack-mu-wpcom' ),
1731            'title'        => __( 'Set up your store', 'jetpack-mu-wpcom' ),
1732            'completed'    => $completed,
1733            'in_progress'  => false,
1734            'disabled'     => ! $active,
1735            'calypso_path' => $completed || ! $active ? null : admin_url( 'admin.php?page=wc-admin&path=%2Fsetup-wizard' ),
1736        );
1737    }
1738
1739    /**
1740     * Inserts a task immediately before the trailing launch task (or appends it), idempotently by id.
1741     *
1742     * @param array $tasks The enriched task list.
1743     * @param array $task  The task entry to insert.
1744     * @return array
1745     */
1746    private function insert_before_launch_task( $tasks, $task ) {
1747        foreach ( $tasks as $existing ) {
1748            if ( isset( $existing['id'] ) && $existing['id'] === $task['id'] ) {
1749                return $tasks;
1750            }
1751        }
1752
1753        $insert_at = count( $tasks );
1754        foreach ( $tasks as $index => $existing ) {
1755            if ( isset( $existing['id'] ) && in_array( $existing['id'], self::LAUNCH_TASK_IDS, true ) ) {
1756                $insert_at = $index;
1757                break;
1758            }
1759        }
1760
1761        array_splice( $tasks, $insert_at, 0, array( $task ) );
1762        return $tasks;
1763    }
1764
1765    /**
1766     * Resolves the editor URL of a site-editor task's in-progress draft, or null when there is none.
1767     *
1768     * The About page is found by its marker meta; the first-post tasks by the latest draft post. Returned as an
1769     * `admin_url()` so the client reopens the existing draft rather than creating a duplicate.
1770     *
1771     * @param string $task_id The catalog task id.
1772     * @return string|null
1773     */
1774    private function get_in_progress_draft_url( $task_id ) {
1775        $draft_id = null;
1776
1777        if ( 'add_about_page' === $task_id ) {
1778            $draft_id = AI_Launchpad_About_Page_Listener::get_draft_id();
1779        } elseif ( in_array( $task_id, self::IN_PROGRESS_FIRST_POST_TASK_IDS, true ) ) {
1780            $draft_id = AI_Launchpad_First_Post_Listener::get_draft_id();
1781        }
1782
1783        if ( null === $draft_id ) {
1784            return null;
1785        }
1786
1787        return admin_url( 'post.php?post=' . $draft_id . '&action=edit' );
1788    }
1789
1790    /**
1791     * The card title for a site-editor task, chosen by our precise (marker-based) in-progress signal so the title,
1792     * icon, and CTA stay in agreement.
1793     *
1794     * This overrides `first_post_published`'s catalog title in both states: the catalog swaps it to "Continue…"
1795     * whenever ANY draft exists (a looser signal than our marker), so an unrelated draft would otherwise show a
1796     * "Continue…" title beside the not-started icon. Tasks not listed keep their catalog title.
1797     *
1798     * @param string $task_id     The catalog task id.
1799     * @param bool   $in_progress Whether our marker detected an in-progress draft.
1800     * @param string $default     The catalog-provided title, kept when we don't override.
1801     * @return string
1802     */
1803    private function get_task_title( $task_id, $in_progress, $default ) {
1804        switch ( $task_id ) {
1805            case 'add_about_page':
1806                return $in_progress ? __( 'Continue working on the About page', 'jetpack-mu-wpcom' ) : $default;
1807            case 'first_post_published':
1808                return $in_progress
1809                    ? __( 'Continue to write your first post', 'jetpack-mu-wpcom' )
1810                    : __( 'Write your first post', 'jetpack-mu-wpcom' );
1811            default:
1812                return $default;
1813        }
1814    }
1815
1816    /**
1817     * Loads the agent output schema used to validate `PUT /tailored` bodies.
1818     *
1819     * @return array
1820     */
1821    private function get_output_schema() {
1822        static $schema = null;
1823
1824        if ( null === $schema ) {
1825            $schema = json_decode( file_get_contents( __DIR__ . '/contracts/agent-output-schema.json' ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local package file.
1826        }
1827
1828        return $schema;
1829    }
1830}
1831
1832// @phan-suppress-next-line PhanNoopNew -- instantiated for the constructor's add_action side effect.
1833new AI_Launchpad_REST();