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