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