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