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