Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.10% covered (success)
93.10%
445 / 478
80.77% covered (warning)
80.77%
21 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
Backup_Abilities
93.49% covered (success)
93.49%
445 / 476
80.77% covered (warning)
80.77%
21 / 26
145.41
0.00% covered (danger)
0.00%
0 / 1
 enabled_by_default
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_definition
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 register_category
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_abilities
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 backup_is_loaded
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_abilities
100.00% covered (success)
100.00%
247 / 247
100.00% covered (success)
100.00%
1 / 1
1
 can_view_backups
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 can_manage_backups
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute_get_backup_overview
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 execute_list_backups
49.02% covered (danger)
49.02%
25 / 51
0.00% covered (danger)
0.00%
0 / 1
167.68
 execute_list_restores
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
3.58
 pick_backup_near_timestamp
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
11
 extract_rewindable_items
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
8.06
 summarize_backup_event
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
12.02
 map_event_status
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 event_has_warnings
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 parse_timestamp
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
7
 execute_request_backup
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 unwrap_response
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 apply_id_or_pagination
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
7
 summarize_last_backup
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 summarize_backup
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 summarize_restore
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 summarize_schedule
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 summarize_storage
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
14
1<?php
2/**
3 * Jetpack Backup Abilities Registration.
4 *
5 * Registers Jetpack Backup abilities with the WordPress Abilities API so AI
6 * agents can read backup status and trigger on-demand backups through the
7 * standard `wp-abilities/v1` REST surface.
8 *
9 * @package automattic/jetpack-backup
10 */
11
12namespace Automattic\Jetpack\Backup\V0005\Abilities;
13
14use Automattic\Jetpack\Backup\V0005\Jetpack_Backup;
15use Automattic\Jetpack\My_Jetpack\Products\Backup as My_Jetpack_Backup;
16use Automattic\Jetpack\WP_Abilities\Registrar;
17use WP_Error;
18use WP_REST_Response;
19
20if ( ! defined( 'ABSPATH' ) ) {
21    exit( 0 );
22}
23
24/**
25 * Registers Jetpack Backup abilities with the WordPress Abilities API.
26 *
27 * Exposes a small, agent-friendly surface for site backups:
28 *
29 * - `jetpack-backup/get-backup-overview` — single-call site backup health snapshot.
30 * - `jetpack-backup/list-backups` — recent backups with optional id/pagination filters.
31 * - `jetpack-backup/list-restores` — recent restores with optional id/pagination filters.
32 * - `jetpack-backup/request-backup` — enqueue an on-demand backup.
33 */
34class Backup_Abilities extends Registrar {
35
36    const PER_PAGE_DEFAULT = 20;
37    const PER_PAGE_MAX     = 100;
38
39    /**
40     * {@inheritDoc}
41     */
42    protected static function enabled_by_default(): bool {
43        return true;
44    }
45
46    /**
47     * Return the ability category slug.
48     *
49     * @return string
50     */
51    public static function get_category_slug(): string {
52        return 'site';
53    }
54
55    /**
56     * Required by the abstract parent, but unused: the `site` category is
57     * already registered upstream (WordPress core / wpcom), so we don't
58     * re-declare it. Kept so the contract holds if a consumer ever asks for
59     * the definition we *would* use.
60     *
61     * @return array
62     */
63    public static function get_category_definition(): array {
64        return array(
65            'label'       => __( 'Site', 'jetpack-backup-pkg' ),
66            'description' => __( 'Site-wide management abilities (registered upstream).', 'jetpack-backup-pkg' ),
67        );
68    }
69
70    /**
71     * Override the Registrar lifecycle so the backup abilities only register
72     * on sites that actually have a Jetpack Backup product provisioned.
73     * There's no point exposing tool surfaces an agent can never use, and on free
74     * sites the upstream wpcom endpoints either silently accept writes (e.g.
75     * `request-backup` reported `enqueued: true`) or return null payloads
76     * that confuse callers.
77     *
78     * The `site` category is registered upstream by WordPress core / wpcom,
79     * so this class never tries to register a category — `register_category`
80     * is a no-op even though the parent hooks it.
81     *
82     * @return void
83     */
84    public static function register_category() {
85        // No-op: `site` is registered upstream; re-registering would either
86        // no-op or trigger "already registered" notices.
87    }
88
89    /**
90     * Register every ability returned by `get_abilities()`, gated on the
91     * Backup product being loaded. See `register_category()` for why we
92     * never register a category from here.
93     *
94     * @return void
95     */
96    public static function register_abilities() {
97        if ( ! self::backup_is_loaded() ) {
98            return;
99        }
100        parent::register_abilities();
101    }
102
103    /**
104     * Is the Jetpack Backup product actually loaded on this site?
105     *
106     * True when a plugin that ships Backup is active and the site has a Backup plan. Deliberately
107     * not `My_Jetpack\Products\Backup::is_active()`: next to an older Jetpack plugin that still
108     * follows the backup module, while backups keep running on WordPress.com. The plan lookup
109     * is cached in `MY_JETPACK_SITE_FEATURES_TRANSIENT_KEY`.
110     *
111     * The `jetpack_backup_abilities_should_load` filter lets consumers and
112     * tests override the answer without round-tripping through the My
113     * Jetpack product class.
114     *
115     * @return bool
116     */
117    private static function backup_is_loaded(): bool {
118        $default = class_exists( My_Jetpack_Backup::class )
119            && My_Jetpack_Backup::is_plugin_active()
120            && My_Jetpack_Backup::has_any_plan_for_product();
121
122        /**
123         * Filters whether the Jetpack Backup abilities should register on
124         * this site. Defaults to whether Backup's plugin is active and the site has a Backup plan.
125         *
126         * @since 0.1.0
127         *
128         * @param bool $should_load Whether to register the backup abilities.
129         */
130        return (bool) apply_filters( 'jetpack_backup_abilities_should_load', $default );
131    }
132
133    /**
134     * Return the abilities this Registrar exposes, keyed by slug.
135     *
136     * @return array<string, array<string, mixed>>
137     */
138    public static function get_abilities(): array {
139        // `id` is the rewind_id (a timestamp-fractional string like
140        // "1752860369.781") — the single cross-system identifier exposed by
141        // the wpcom rewind, restore, and activity-log APIs. Use it whenever
142        // referring to a specific backup across abilities.
143        //
144        // For in-progress backup attempts the rewind_id isn't assigned yet,
145        // in which case `id` is null. Such backups can't be looked up by id
146        // anywhere — wait for completion and re-query.
147        $backup_item_schema = array(
148            'type'       => 'object',
149            'properties' => array(
150                'id'            => array( 'type' => array( 'string', 'null' ) ),
151                'started'       => array( 'type' => array( 'string', 'null' ) ),
152                'last_updated'  => array( 'type' => array( 'string', 'null' ) ),
153                'status'        => array( 'type' => array( 'string', 'null' ) ),
154                'period'        => array( 'type' => array( 'string', 'integer', 'null' ) ),
155                'is_rewindable' => array( 'type' => array( 'boolean', 'null' ) ),
156                'has_warnings'  => array( 'type' => array( 'boolean', 'null' ) ),
157            ),
158        );
159
160        // Same convention applies to restores: `id` is the rewind_id of the
161        // backup being restored to.
162        $restore_item_schema = array(
163            'type'       => 'object',
164            'properties' => array(
165                'id'           => array( 'type' => array( 'string', 'null' ) ),
166                'started'      => array( 'type' => array( 'string', 'null' ) ),
167                'last_updated' => array( 'type' => array( 'string', 'null' ) ),
168                'status'       => array( 'type' => array( 'string', 'null' ) ),
169                'progress'     => array( 'type' => array( 'integer', 'null' ) ),
170            ),
171        );
172
173        return array(
174            'jetpack-backup/get-backup-overview' => array(
175                'label'               => __( 'Get backup overview', 'jetpack-backup-pkg' ),
176                'description'         => __(
177                    'Return a single-call snapshot of the site backup state: { last_backup, recent_backup_count, schedule, storage }. Use this to answer "is my site protected?" before deciding whether to call list-backups, list-restores, or request-backup. Read-only and idempotent. Fields whose backing service is unreachable come back as null rather than failing the call. Requires the manage_options capability.',
178                    'jetpack-backup-pkg'
179                ),
180                'input_schema'        => array(
181                    'type'                 => 'object',
182                    'default'              => array(),
183                    'properties'           => array(),
184                    'additionalProperties' => false,
185                ),
186                'output_schema'       => array(
187                    'type'       => 'object',
188                    'properties' => array(
189                        'recent_backup_count' => array( 'type' => array( 'integer', 'null' ) ),
190                        'last_backup'         => array(
191                            'type'       => array( 'object', 'null' ),
192                            'properties' => array(
193                                'id'            => array( 'type' => array( 'string', 'null' ) ),
194                                'last_updated'  => array( 'type' => array( 'string', 'null' ) ),
195                                'status'        => array( 'type' => array( 'string', 'null' ) ),
196                                'is_rewindable' => array( 'type' => array( 'boolean', 'null' ) ),
197                                'has_warnings'  => array( 'type' => array( 'boolean', 'null' ) ),
198                            ),
199                        ),
200                        // Hour only: no WordPress.com endpoint carries a minute,
201                        // so a `minute` field could only ever be null.
202                        'schedule'            => array(
203                            'type'       => array( 'object', 'null' ),
204                            'properties' => array(
205                                'hour' => array( 'type' => array( 'integer', 'null' ) ),
206                            ),
207                        ),
208                        'storage'             => array(
209                            'type'       => array( 'object', 'null' ),
210                            'properties' => array(
211                                'used_bytes'  => array( 'type' => array( 'integer', 'null' ) ),
212                                'limit_bytes' => array( 'type' => array( 'integer', 'null' ) ),
213                            ),
214                        ),
215                    ),
216                ),
217                'execute_callback'    => array( __CLASS__, 'execute_get_backup_overview' ),
218                'permission_callback' => array( __CLASS__, 'can_view_backups' ),
219                'meta'                => array(
220                    'annotations'  => array(
221                        'readonly'    => true,
222                        'destructive' => false,
223                        'idempotent'  => true,
224                    ),
225                    'public'       => true,
226                    'mcp'          => array(
227                        'public' => true,
228                        'type'   => 'tool',
229                    ),
230                    'show_in_rest' => true,
231                ),
232            ),
233
234            'jetpack-backup/list-backups'        => array(
235                'label'               => __( 'List backups', 'jetpack-backup-pkg' ),
236                'description'         => __(
237                    'Return zero or more backups as an array. Each item summarises one backup: { id, rewind_id, started, last_updated, status, period, is_rewindable, has_warnings }. Combine filters to narrow the result without making multiple calls. `id` returns a 0- or 1-element array for a single rewind_id. `date_from` and `date_to` window the results (ISO 8601 datetimes; server-side filter). `date` + `match` ("on_or_before" default, "on_or_after", "closest") pick a single backup near a target datetime — useful for "find a restore point near this incident"; the response stays a 0- or 1-element array. `status` filters by mapped status (e.g. "finished", "error"). `page` + `per_page` paginate the result; iterate `page=1,2,...` until you get an empty array. A page may come back with fewer than `per_page` items even when more pages exist — `status` is applied client-side, and non-backup events are filtered out — so only an empty page reliably signals end of history. Read-only and idempotent. Backed by the wpcom activity-log feed.',
238                    'jetpack-backup-pkg'
239                ),
240                'input_schema'        => array(
241                    'type'                 => 'object',
242                    'default'              => array(),
243                    'properties'           => array(
244                        'id'        => array(
245                            'type'        => 'string',
246                            'description' => __( 'Return only the backup with this rewind_id. Unknown ids yield an empty array.', 'jetpack-backup-pkg' ),
247                            'minLength'   => 1,
248                        ),
249                        'date_from' => array(
250                            'type'        => 'string',
251                            'format'      => 'date-time',
252                            'description' => __( 'Lower bound (inclusive) on backup `started` time. ISO 8601 datetime, e.g. "2026-04-01T00:00:00Z".', 'jetpack-backup-pkg' ),
253                            'minLength'   => 1,
254                        ),
255                        'date_to'   => array(
256                            'type'        => 'string',
257                            'format'      => 'date-time',
258                            'description' => __( 'Upper bound (inclusive) on backup `started` time. ISO 8601 datetime, e.g. "2026-04-30T23:59:59Z".', 'jetpack-backup-pkg' ),
259                            'minLength'   => 1,
260                        ),
261                        'date'      => array(
262                            'type'        => 'string',
263                            'format'      => 'date-time',
264                            'description' => __( 'Target datetime to find a single matching backup. When set, the response is a 0- or 1-element array. Pair with `match` to choose direction.', 'jetpack-backup-pkg' ),
265                            'minLength'   => 1,
266                        ),
267                        'match'     => array(
268                            'type'        => 'string',
269                            'enum'        => array( 'on_or_before', 'on_or_after', 'closest' ),
270                            'default'     => 'on_or_before',
271                            'description' => __( 'How to interpret `date`. "on_or_before" (default; the latest backup at or before the target — typical for restores), "on_or_after" (earliest backup at or after), or "closest" (smallest absolute time difference). Ignored when `date` is not set.', 'jetpack-backup-pkg' ),
272                        ),
273                        'status'    => array(
274                            'type'        => 'string',
275                            'description' => __( 'Filter by mapped status string (e.g. "finished", "error"). Applied client-side after the server query.', 'jetpack-backup-pkg' ),
276                            'minLength'   => 1,
277                        ),
278                        'page'      => array(
279                            'type'        => 'integer',
280                            'description' => __( '1-based page number. Ignored when `id` or `date` is set (those are single-result lookups).', 'jetpack-backup-pkg' ),
281                            'default'     => 1,
282                            'minimum'     => 1,
283                        ),
284                        'per_page'  => array(
285                            'type'        => 'integer',
286                            'description' => __( 'Cap on items returned per page (default 20, max 100). Also bounds the server-side query window the date filters are evaluated against.', 'jetpack-backup-pkg' ),
287                            'default'     => self::PER_PAGE_DEFAULT,
288                            'minimum'     => 1,
289                            'maximum'     => self::PER_PAGE_MAX,
290                        ),
291                    ),
292                    'additionalProperties' => false,
293                ),
294                'output_schema'       => array(
295                    'type'  => 'array',
296                    'items' => $backup_item_schema,
297                ),
298                'execute_callback'    => array( __CLASS__, 'execute_list_backups' ),
299                'permission_callback' => array( __CLASS__, 'can_view_backups' ),
300                'meta'                => array(
301                    'annotations'  => array(
302                        'readonly'    => true,
303                        'destructive' => false,
304                        'idempotent'  => true,
305                    ),
306                    'public'       => true,
307                    'mcp'          => array(
308                        'public' => true,
309                        'type'   => 'tool',
310                    ),
311                    'show_in_rest' => true,
312                ),
313            ),
314
315            'jetpack-backup/list-restores'       => array(
316                'label'               => __( 'List restores', 'jetpack-backup-pkg' ),
317                'description'         => __(
318                    'Return zero or more recent restore operations as an array. Each item: { id, rewind_id, started, last_updated, status, progress }. Pass id to fetch a single restore (returns 0- or 1-element array). Otherwise paginate with page and per_page (default 20, max 100). Read-only and idempotent.',
319                    'jetpack-backup-pkg'
320                ),
321                'input_schema'        => array(
322                    'type'                 => 'object',
323                    'default'              => array(),
324                    'properties'           => array(
325                        'id'       => array(
326                            'type'        => 'string',
327                            'description' => __( 'Return only the restore with this id. Unknown ids yield an empty array.', 'jetpack-backup-pkg' ),
328                            'minLength'   => 1,
329                        ),
330                        'page'     => array(
331                            'type'        => 'integer',
332                            'description' => __( 'Page number, 1-based.', 'jetpack-backup-pkg' ),
333                            'default'     => 1,
334                            'minimum'     => 1,
335                        ),
336                        'per_page' => array(
337                            'type'        => 'integer',
338                            'description' => __( 'Items per page (default 20, max 100).', 'jetpack-backup-pkg' ),
339                            'default'     => self::PER_PAGE_DEFAULT,
340                            'minimum'     => 1,
341                            'maximum'     => self::PER_PAGE_MAX,
342                        ),
343                    ),
344                    'additionalProperties' => false,
345                ),
346                'output_schema'       => array(
347                    'type'  => 'array',
348                    'items' => $restore_item_schema,
349                ),
350                'execute_callback'    => array( __CLASS__, 'execute_list_restores' ),
351                'permission_callback' => array( __CLASS__, 'can_view_backups' ),
352                'meta'                => array(
353                    'annotations'  => array(
354                        'readonly'    => true,
355                        'destructive' => false,
356                        'idempotent'  => true,
357                    ),
358                    'public'       => true,
359                    'mcp'          => array(
360                        'public' => true,
361                        'type'   => 'tool',
362                    ),
363                    'show_in_rest' => true,
364                ),
365            ),
366
367            'jetpack-backup/request-backup'      => array(
368                'label'               => __( 'Request a backup', 'jetpack-backup-pkg' ),
369                'description'         => __(
370                    'Enqueue an on-demand backup of this site. Returns { enqueued: bool, message: string }. Each successful call queues a new backup job; this is a state-changing write, not idempotent. Use get-backup-overview or list-backups afterwards to track progress. Requires the manage_options capability. Returns jetpack_backup_data_unavailable when the upstream service rejects the request.',
371                    'jetpack-backup-pkg'
372                ),
373                'input_schema'        => array(
374                    'type'                 => 'object',
375                    'default'              => array(),
376                    'properties'           => array(),
377                    'additionalProperties' => false,
378                ),
379                'output_schema'       => array(
380                    'type'       => 'object',
381                    'properties' => array(
382                        'enqueued' => array( 'type' => 'boolean' ),
383                        'message'  => array( 'type' => 'string' ),
384                    ),
385                ),
386                'execute_callback'    => array( __CLASS__, 'execute_request_backup' ),
387                'permission_callback' => array( __CLASS__, 'can_manage_backups' ),
388                'meta'                => array(
389                    'annotations'  => array(
390                        'readonly'    => false,
391                        'destructive' => false,
392                        'idempotent'  => false,
393                    ),
394                    'public'       => true,
395                    'mcp'          => array(
396                        'public' => true,
397                        'type'   => 'tool',
398                    ),
399                    'show_in_rest' => true,
400                ),
401            ),
402        );
403    }
404
405    /**
406     * Permission check for read abilities: the REST routes' own check,
407     * Jetpack_Backup::backups_permissions_callback(), whose error names the reason.
408     * Kept separate from `can_manage_backups()` so the read and write surfaces
409     * can diverge later without touching every spec.
410     *
411     * @return bool|WP_Error
412     */
413    public static function can_view_backups() {
414        return Jetpack_Backup::backups_permissions_callback();
415    }
416
417    /**
418     * Permission check for write abilities. See `can_view_backups()`.
419     *
420     * @return bool|WP_Error
421     */
422    public static function can_manage_backups() {
423        return Jetpack_Backup::backups_permissions_callback();
424    }
425
426    /**
427     * Composite read: each subfield is null on upstream failure rather than
428     * failing the whole call, so a partial wpcom outage degrades to "missing
429     * pieces" instead of "no data." Registration is gated on a Backup product
430     * being loaded (see register_abilities), so this callback assumes the
431     * site has one and only reports on the data it can fetch.
432     *
433     * @param mixed $input Unused; ability accepts no input. Typed `mixed` because
434     *                     the Abilities API may pass the raw caller-supplied value
435     *                     (string/null/array) before our `additionalProperties:false`
436     *                     schema runs — a strict array type would fatal on garbage input.
437     * @return array
438     */
439    public static function execute_get_backup_overview( $input = null ): array {
440        unset( $input );
441
442        $backups       = self::unwrap_response( Jetpack_Backup::get_recent_backups() );
443        $schedule_data = self::unwrap_response( Jetpack_Backup::get_site_backup_schedule_time() );
444        $size_data     = self::unwrap_response( Jetpack_Backup::get_site_backup_size() );
445        // Two round-trips because neither route describes storage alone: `/rewind/size`
446        // reports usage, `/rewind/policies` the limit. Fetched unconditionally so a
447        // usable limit still arrives when usage cannot be measured.
448        $policies_data = self::unwrap_response( Jetpack_Backup::get_site_backup_policies() );
449
450        return array(
451            'recent_backup_count' => is_array( $backups ) ? count( $backups ) : null,
452            'last_backup'         => self::summarize_last_backup( is_array( $backups ) ? ( $backups[0] ?? null ) : null ),
453            'schedule'            => self::summarize_schedule( $schedule_data ),
454            'storage'             => self::summarize_storage( $size_data, $policies_data ),
455        );
456    }
457
458    /**
459     * Consolidated read: queries the wpcom activity-log rewindable feed
460     * (server-side date filtering, up to 1000 items/page) and reshapes
461     * activity events back into the backup-item schema. All input filters
462     * land here; the picker is invoked when a `date` + `match` is set.
463     *
464     * @param mixed $input See input_schema on `jetpack-backup/list-backups`.
465     * @return array|WP_Error
466     */
467    public static function execute_list_backups( $input = null ) {
468        $input = is_array( $input ) ? $input : array();
469
470        // Validate `date` / `date_from` / `date_to` ahead of the round-trip so
471        // agents get a specific error rather than a 200 with mysterious empty
472        // results. Schema's `format: date-time` is advisory in WP REST.
473        foreach ( array( 'date', 'date_from', 'date_to' ) as $key ) {
474            if ( isset( $input[ $key ] ) && '' !== $input[ $key ] && null === self::parse_timestamp( $input[ $key ] ) ) {
475                return new WP_Error(
476                    'jetpack_backup_invalid_date',
477                    /* translators: %s is an input parameter name. */
478                    sprintf( __( 'The `%s` parameter must be a valid ISO 8601 datetime (e.g. "2026-05-13T14:30:00Z").', 'jetpack-backup-pkg' ), $key )
479                );
480            }
481        }
482
483        $per_page = min(
484            self::PER_PAGE_MAX,
485            max( 1, isset( $input['per_page'] ) ? (int) $input['per_page'] : self::PER_PAGE_DEFAULT )
486        );
487        $page     = max( 1, isset( $input['page'] ) ? (int) $input['page'] : 1 );
488
489        // `page` is suppressed on the single-result lookups (id, date+match)
490        // — those resolve from page 1 and walking later pages would skip
491        // candidates without an obvious benefit.
492        $is_single_lookup = ( isset( $input['id'] ) && '' !== $input['id'] )
493            || ( isset( $input['date'] ) && '' !== $input['date'] );
494
495        $query = array(
496            'number'     => $per_page,
497            'page'       => $is_single_lookup ? 1 : $page,
498            'sort_order' => 'desc',
499        );
500        if ( isset( $input['date_from'] ) && '' !== $input['date_from'] ) {
501            $query['after'] = (string) $input['date_from'];
502        }
503        if ( isset( $input['date_to'] ) && '' !== $input['date_to'] ) {
504            $query['before'] = (string) $input['date_to'];
505        }
506
507        $envelope = self::unwrap_response( Jetpack_Backup::list_backup_events( $query ) );
508        $events   = self::extract_rewindable_items( $envelope );
509        if ( ! is_array( $events ) ) {
510            return array();
511        }
512
513        $items = array_values( array_filter( array_map( array( __CLASS__, 'summarize_backup_event' ), $events ) ) );
514
515        // Single-id filter — same convention as the old endpoint: 0/1-element array.
516        if ( isset( $input['id'] ) && is_string( $input['id'] ) && '' !== $input['id'] ) {
517            foreach ( $items as $item ) {
518                if ( isset( $item['id'] ) && (string) $item['id'] === $input['id'] ) {
519                    return array( $item );
520                }
521            }
522            return array();
523        }
524
525        // Client-side status filter (server-side filters by event name, not status).
526        if ( isset( $input['status'] ) && is_string( $input['status'] ) && '' !== $input['status'] ) {
527            $want  = $input['status'];
528            $items = array_values(
529                array_filter(
530                    $items,
531                    static function ( $i ) use ( $want ) {
532                        return ( $i['status'] ?? null ) === $want;
533                    }
534                )
535            );
536        }
537
538        // Single-match shortcut.
539        if ( isset( $input['date'] ) && '' !== $input['date'] ) {
540            $target = self::parse_timestamp( $input['date'] );
541            $match  = isset( $input['match'] ) && is_string( $input['match'] ) ? $input['match'] : 'on_or_before';
542            if ( ! in_array( $match, array( 'on_or_before', 'on_or_after', 'closest' ), true ) ) {
543                $match = 'on_or_before';
544            }
545            $pick = self::pick_backup_near_timestamp( $items, (int) $target, $match );
546            return null === $pick ? array() : array( $pick );
547        }
548
549        return array_slice( $items, 0, $per_page );
550    }
551
552    /**
553     * Execute callback for `jetpack-backup/list-restores`.
554     *
555     * @param mixed $input See input_schema on the ability.
556     * @return array
557     */
558    public static function execute_list_restores( $input = null ): array {
559        $restores = self::unwrap_response( Jetpack_Backup::get_recent_restores() );
560        if ( ! is_array( $restores ) ) {
561            return array();
562        }
563
564        $summarized = array_map( array( __CLASS__, 'summarize_restore' ), $restores );
565        return self::apply_id_or_pagination( $summarized, is_array( $input ) ? $input : array() );
566    }
567
568    /**
569     * Pure picker for the `date` + `match` shortcut. Operates on already-
570     * summarized backup items (so it works regardless of which upstream
571     * helper produced them) and uses `started` as the comparison timestamp.
572     *
573     * @param array  $items     Summarized backup items.
574     * @param int    $target_ts Unix timestamp the caller is searching around.
575     * @param string $match     'on_or_before' | 'on_or_after' | 'closest'.
576     * @return array|null The winning item or null when nothing matches.
577     */
578    private static function pick_backup_near_timestamp( array $items, int $target_ts, string $match ): ?array {
579        $best       = null;
580        $best_score = null;
581
582        foreach ( $items as $item ) {
583            $ts = self::parse_timestamp( $item['started'] ?? null );
584            if ( null === $ts ) {
585                continue;
586            }
587
588            $diff  = $ts - $target_ts;
589            $score = 0;
590            switch ( $match ) {
591                case 'on_or_after':
592                    if ( $diff < 0 ) {
593                        continue 2;
594                    }
595                    $score = $diff;
596                    break;
597                case 'closest':
598                    $score = abs( $diff );
599                    break;
600                case 'on_or_before':
601                default:
602                    if ( $diff > 0 ) {
603                        continue 2;
604                    }
605                    $score = -$diff;
606                    break;
607            }
608
609            if ( null === $best_score || $score < $best_score ) {
610                $best       = $item;
611                $best_score = $score;
612            }
613        }
614
615        return $best;
616    }
617
618    /**
619     * Pull the activity-event array out of the W3C ActivityStreams envelope
620     * that `/activity/rewindable` returns. The endpoint puts the items in
621     * `current.orderedItems`; older proxy shapes used `orderedItems` at the
622     * top level, so check both before giving up.
623     *
624     * @param mixed $envelope Raw decoded response body.
625     * @return array|null
626     */
627    private static function extract_rewindable_items( $envelope ): ?array {
628        if ( ! is_array( $envelope ) && ! is_object( $envelope ) ) {
629            return null;
630        }
631        $envelope = (array) $envelope;
632        if ( isset( $envelope['current'] ) ) {
633            $current = (array) $envelope['current'];
634            if ( isset( $current['orderedItems'] ) && is_array( $current['orderedItems'] ) ) {
635                return $current['orderedItems'];
636            }
637        }
638        if ( isset( $envelope['orderedItems'] ) && is_array( $envelope['orderedItems'] ) ) {
639            return $envelope['orderedItems'];
640        }
641        return null;
642    }
643
644    /**
645     * Translate one /activity/rewindable event into the same backup-item
646     * shape `summarize_backup()` produces, so the ability's output schema
647     * stays stable across the upstream switch. Returns null for events that
648     * don't look like backups (no `rewind_id`).
649     *
650     * @param mixed $raw One element from `current.orderedItems`.
651     * @return array|null
652     */
653    private static function summarize_backup_event( $raw ): ?array {
654        if ( ! is_array( $raw ) && ! is_object( $raw ) ) {
655            return null;
656        }
657        $raw = (array) $raw;
658
659        $rewind_id = $raw['rewind_id'] ?? null;
660        if ( null === $rewind_id || '' === $rewind_id ) {
661            return null;
662        }
663
664        $published     = isset( $raw['published'] ) && is_string( $raw['published'] ) ? $raw['published'] : null;
665        $status_raw    = isset( $raw['status'] ) && is_string( $raw['status'] ) ? $raw['status'] : null;
666        $name          = isset( $raw['name'] ) && is_string( $raw['name'] ) ? $raw['name'] : '';
667        $is_rewindable = isset( $raw['is_rewindable'] ) ? (bool) $raw['is_rewindable'] : null;
668
669        return array(
670            'id'            => (string) $rewind_id,
671            'started'       => $published,
672            'last_updated'  => $published,
673            'status'        => self::map_event_status( $status_raw, $name ),
674            'period'        => self::parse_timestamp( $rewind_id ),
675            'is_rewindable' => $is_rewindable,
676            'has_warnings'  => self::event_has_warnings( $status_raw, $name ),
677        );
678    }
679
680    /**
681     * Map activity-event status / action-name to the status vocabulary the
682     * ability's output schema uses (the same labels as the old
683     * `/rewind/backups` endpoint: "finished", "error", ...). Falls back to
684     * the raw status when no mapping fits so the caller still sees signal.
685     *
686     * @param string|null $status_raw Activity event status (e.g. "success", "warning", "error").
687     * @param string      $name       Activity name, e.g. "rewind__backup_complete_full".
688     * @return string|null
689     */
690    private static function map_event_status( ?string $status_raw, string $name ): ?string {
691        if ( 'success' === $status_raw || false !== strpos( $name, 'backup_complete' ) ) {
692            return 'finished';
693        }
694        return $status_raw;
695    }
696
697    /**
698     * Derive `has_warnings` from an activity event's status / name.
699     *
700     * @param string|null $status_raw Activity event status.
701     * @param string      $name       Activity name.
702     * @return bool|null
703     */
704    private static function event_has_warnings( ?string $status_raw, string $name ): ?bool {
705        if ( 'warning' === $status_raw ) {
706            return true;
707        }
708        if ( 'success' === $status_raw || false !== strpos( $name, 'backup_complete' ) ) {
709            return false;
710        }
711        return null;
712    }
713
714    /**
715     * Coerce an ISO 8601 string, RFC-style date string, or numeric unix
716     * timestamp to an int unix timestamp. Returns null for anything that
717     * can't be unambiguously parsed (instead of strtotime's `false`, which
718     * is also a valid timestamp for 1969-12-31).
719     *
720     * Fractional numeric strings (e.g. rewind_id "1778804242.107") are
721     * accepted — the fractional part is truncated.
722     *
723     * @param mixed $value Source value (string, int, float, or anything else).
724     * @return int|null
725     */
726    private static function parse_timestamp( $value ): ?int {
727        if ( is_int( $value ) ) {
728            return $value;
729        }
730        if ( is_float( $value ) ) {
731            return (int) $value;
732        }
733        if ( is_string( $value ) && '' !== $value ) {
734            if ( is_numeric( $value ) ) {
735                return (int) $value;
736            }
737            $ts = strtotime( $value );
738            return false === $ts ? null : $ts;
739        }
740        return null;
741    }
742
743    /**
744     * Enqueue an on-demand backup. Registration is gated on a Backup product
745     * being loaded so we assume one exists by the time this runs. Returns
746     * WP_Error only when the upstream connection itself fails so agents can
747     * retry strategically.
748     *
749     * @param mixed $input Unused; see note on execute_get_backup_overview().
750     * @return array|WP_Error
751     */
752    public static function execute_request_backup( $input = null ) {
753        unset( $input );
754
755        // wpcom can return HTTP 200 with `{ success: false, error: ... }`; treat
756        // that as a failure rather than reporting the backup was enqueued.
757        $result = self::unwrap_response( Jetpack_Backup::enqueue_backup() );
758        if ( ! is_array( $result ) || empty( $result['success'] ) ) {
759            return new WP_Error(
760                'jetpack_backup_data_unavailable',
761                __( 'The backup service did not accept the request. The connection to WordPress.com may be temporarily unavailable; retry shortly.', 'jetpack-backup-pkg' )
762            );
763        }
764
765        return array(
766            'enqueued' => true,
767            'message'  => __( 'Backup enqueued. Use jetpack-backup/list-backups to monitor progress.', 'jetpack-backup-pkg' ),
768        );
769    }
770
771    /**
772     * Normalize a Jetpack_Backup helper result (WP_REST_Response, array, null,
773     * or WP_Error) to a plain value or null. Jetpack_Backup uses
774     * `rest_ensure_response()` on success; on failure its routes return a
775     * WP_Error and `list_backup_events()` returns null, so abilities need
776     * every shape flattened before summarising.
777     *
778     * @param mixed $maybe_response Result of a Jetpack_Backup helper call.
779     * @return mixed
780     */
781    private static function unwrap_response( $maybe_response ) {
782        if ( null === $maybe_response || is_wp_error( $maybe_response ) ) {
783            return null;
784        }
785        if ( $maybe_response instanceof WP_REST_Response ) {
786            return $maybe_response->get_data();
787        }
788        return $maybe_response;
789    }
790
791    /**
792     * Slice the (already-summarized) list down to a single id, or apply
793     * page/per_page pagination. Always returns the same item shape.
794     *
795     * @param array $items Summarized items.
796     * @param array $input Sanitized input.
797     * @return array
798     */
799    private static function apply_id_or_pagination( array $items, array $input ): array {
800        if ( isset( $input['id'] ) && is_string( $input['id'] ) && '' !== $input['id'] ) {
801            foreach ( $items as $item ) {
802                if ( isset( $item['id'] ) && (string) $item['id'] === $input['id'] ) {
803                    return array( $item );
804                }
805            }
806            return array();
807        }
808
809        $page     = max( 1, (int) ( $input['page'] ?? 1 ) );
810        $per_page = min( self::PER_PAGE_MAX, max( 1, (int) ( $input['per_page'] ?? self::PER_PAGE_DEFAULT ) ) );
811
812        return array_slice( $items, ( $page - 1 ) * $per_page, $per_page );
813    }
814
815    /**
816     * High-signal summary used inside `last_backup` for the overview. Same as
817     * `summarize_backup` minus the `started`/`period` fields which the agent
818     * doesn't need at a glance.
819     *
820     * @param mixed $raw One element from the upstream backups list.
821     * @return array|null
822     */
823    private static function summarize_last_backup( $raw ): ?array {
824        if ( ! is_array( $raw ) && ! is_object( $raw ) ) {
825            return null;
826        }
827        return array_diff_key(
828            self::summarize_backup( $raw ),
829            array_flip( array( 'started', 'period' ) )
830        );
831    }
832
833    /**
834     * Summarize a `/rewind/backups` payload item using `rewind_id` as the
835     * canonical `id`. The numeric attempt id wpcom also exposes is
836     * internal to VaultPress and can't be looked up via any other endpoint,
837     * so it's intentionally dropped from the agent-facing shape — see the
838     * note on `$backup_item_schema` in `get_abilities()`.
839     *
840     * @param mixed $raw Upstream backup item.
841     * @return array
842     */
843    private static function summarize_backup( $raw ): array {
844        $raw       = (array) $raw;
845        $rewind_id = $raw['rewind_id'] ?? null;
846        return array(
847            'id'            => ( null === $rewind_id || '' === $rewind_id ) ? null : (string) $rewind_id,
848            'started'       => $raw['started'] ?? null,
849            'last_updated'  => $raw['last_updated'] ?? null,
850            'status'        => $raw['status'] ?? null,
851            'period'        => $raw['period'] ?? null,
852            'is_rewindable' => isset( $raw['is_rewindable'] ) ? (bool) $raw['is_rewindable'] : null,
853            'has_warnings'  => isset( $raw['has_warnings'] ) ? (bool) $raw['has_warnings'] : null,
854        );
855    }
856
857    /**
858     * Summarize a `/rewind/restores` payload item. `id` is the rewind_id
859     * of the backup being restored to — same canonical id system as
860     * `summarize_backup()`.
861     *
862     * @param mixed $raw Upstream restore item.
863     * @return array
864     */
865    private static function summarize_restore( $raw ): array {
866        $raw       = (array) $raw;
867        $rewind_id = $raw['rewind_id'] ?? null;
868        return array(
869            'id'           => ( null === $rewind_id || '' === $rewind_id ) ? null : (string) $rewind_id,
870            'started'      => $raw['started'] ?? null,
871            'last_updated' => $raw['last_updated'] ?? null,
872            'status'       => $raw['status'] ?? null,
873            'progress'     => isset( $raw['progress'] ) ? (int) $raw['progress'] : null,
874        );
875    }
876
877    /**
878     * Summarize the `/site/backup/schedule` payload to `{ hour }`.
879     *
880     * WordPress.com answers `{ ok, scheduled_hour, scheduled_by }` — the UTC hour of the
881     * daily backup, and no minute anywhere. `ok` is its own success flag inside a 200
882     * body, so a payload without it carries no usable hour.
883     *
884     * @param mixed $raw Upstream schedule payload.
885     * @return array|null
886     */
887    private static function summarize_schedule( $raw ): ?array {
888        if ( ! is_array( $raw ) && ! is_object( $raw ) ) {
889            return null;
890        }
891        $raw = (array) $raw;
892        if ( empty( $raw['ok'] ) ) {
893            return null;
894        }
895        return array(
896            'hour' => isset( $raw['scheduled_hour'] ) ? (int) $raw['scheduled_hour'] : null,
897        );
898    }
899
900    /**
901     * Summarize storage from the two payloads that between them describe it.
902     *
903     * Usage is `size` on `/site/backup/size`, which despite its name carries no limit;
904     * the limit is `policies.storage_limit_bytes` on `/site/backup/policies`.
905     *
906     * The two are read independently, so a site whose usage could not be measured still
907     * reports what it is allowed. That is deliberately unlike `summarize_schedule()`,
908     * which has nothing left to report once its hour is gone.
909     *
910     * @param mixed $size_raw     Upstream `/site/backup/size` payload.
911     * @param mixed $policies_raw Upstream `/site/backup/policies` payload.
912     * @return array|null
913     */
914    private static function summarize_storage( $size_raw, $policies_raw ): ?array {
915        $size     = ( is_array( $size_raw ) || is_object( $size_raw ) ) ? (array) $size_raw : null;
916        $policies = ( is_array( $policies_raw ) || is_object( $policies_raw ) ) ? (array) $policies_raw : null;
917
918        if ( null === $size && null === $policies ) {
919            return null;
920        }
921
922        $used_bytes = ( null !== $size && ! empty( $size['ok'] ) && isset( $size['size'] ) )
923            ? (int) $size['size']
924            : null;
925
926        // `policies` is itself nullable inside a 200: a plan with no retention policy
927        // answers `{ "policies": null }`.
928        $policy = $policies['policies'] ?? null;
929        $policy = ( is_array( $policy ) || is_object( $policy ) ) ? (array) $policy : null;
930
931        $limit_bytes = ( null !== $policy && isset( $policy['storage_limit_bytes'] ) )
932            ? (int) $policy['storage_limit_bytes']
933            : null;
934
935        return array(
936            'used_bytes'  => $used_bytes,
937            'limit_bytes' => $limit_bytes,
938        );
939    }
940}