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