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