Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.92% covered (success)
92.92%
433 / 466
80.77% covered (warning)
80.77%
21 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1
Backup_Abilities
93.32% covered (success)
93.32%
433 / 464
80.77% covered (warning)
80.77%
21 / 26
145.85
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%
235 / 235
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).',
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'         => '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.',
177                'input_schema'        => array(
178                    'type'                 => 'object',
179                    'default'              => array(),
180                    'properties'           => array(),
181                    'additionalProperties' => false,
182                ),
183                'output_schema'       => array(
184                    'type'       => 'object',
185                    'properties' => array(
186                        'recent_backup_count' => array( 'type' => array( 'integer', 'null' ) ),
187                        'last_backup'         => array(
188                            'type'       => array( 'object', 'null' ),
189                            'properties' => array(
190                                'id'            => array( 'type' => array( 'string', 'null' ) ),
191                                'last_updated'  => array( 'type' => array( 'string', 'null' ) ),
192                                'status'        => array( 'type' => array( 'string', 'null' ) ),
193                                'is_rewindable' => array( 'type' => array( 'boolean', 'null' ) ),
194                                'has_warnings'  => array( 'type' => array( 'boolean', 'null' ) ),
195                            ),
196                        ),
197                        // Hour only: no WordPress.com endpoint carries a minute,
198                        // so a `minute` field could only ever be null.
199                        'schedule'            => array(
200                            'type'       => array( 'object', 'null' ),
201                            'properties' => array(
202                                'hour' => array( 'type' => array( 'integer', 'null' ) ),
203                            ),
204                        ),
205                        'storage'             => array(
206                            'type'       => array( 'object', 'null' ),
207                            'properties' => array(
208                                'used_bytes'  => array( 'type' => array( 'integer', 'null' ) ),
209                                'limit_bytes' => array( 'type' => array( 'integer', 'null' ) ),
210                            ),
211                        ),
212                    ),
213                ),
214                'execute_callback'    => array( __CLASS__, 'execute_get_backup_overview' ),
215                'permission_callback' => array( __CLASS__, 'can_view_backups' ),
216                'meta'                => array(
217                    'annotations'  => array(
218                        'readonly'    => true,
219                        'destructive' => false,
220                        'idempotent'  => true,
221                    ),
222                    'public'       => true,
223                    'mcp'          => array(
224                        'public' => true,
225                        'type'   => 'tool',
226                    ),
227                    'show_in_rest' => true,
228                ),
229            ),
230
231            'jetpack-backup/list-backups'        => array(
232                'label'               => __( 'List backups', 'jetpack-backup-pkg' ),
233                'description'         => '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.',
234                'input_schema'        => array(
235                    'type'                 => 'object',
236                    'default'              => array(),
237                    'properties'           => array(
238                        'id'        => array(
239                            'type'        => 'string',
240                            'description' => 'Return only the backup with this rewind_id. Unknown ids yield an empty array.',
241                            'minLength'   => 1,
242                        ),
243                        'date_from' => array(
244                            'type'        => 'string',
245                            'format'      => 'date-time',
246                            'description' => 'Lower bound (inclusive) on backup `started` time. ISO 8601 datetime, e.g. "2026-04-01T00:00:00Z".',
247                            'minLength'   => 1,
248                        ),
249                        'date_to'   => array(
250                            'type'        => 'string',
251                            'format'      => 'date-time',
252                            'description' => 'Upper bound (inclusive) on backup `started` time. ISO 8601 datetime, e.g. "2026-04-30T23:59:59Z".',
253                            'minLength'   => 1,
254                        ),
255                        'date'      => array(
256                            'type'        => 'string',
257                            'format'      => 'date-time',
258                            '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.',
259                            'minLength'   => 1,
260                        ),
261                        'match'     => array(
262                            'type'        => 'string',
263                            'enum'        => array( 'on_or_before', 'on_or_after', 'closest' ),
264                            'default'     => 'on_or_before',
265                            '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.',
266                        ),
267                        'status'    => array(
268                            'type'        => 'string',
269                            'description' => 'Filter by mapped status string (e.g. "finished", "error"). Applied client-side after the server query.',
270                            'minLength'   => 1,
271                        ),
272                        'page'      => array(
273                            'type'        => 'integer',
274                            'description' => '1-based page number. Ignored when `id` or `date` is set (those are single-result lookups).',
275                            'default'     => 1,
276                            'minimum'     => 1,
277                        ),
278                        'per_page'  => array(
279                            'type'        => 'integer',
280                            'description' => 'Cap on items returned per page (default 20, max 100). Also bounds the server-side query window the date filters are evaluated against.',
281                            'default'     => self::PER_PAGE_DEFAULT,
282                            'minimum'     => 1,
283                            'maximum'     => self::PER_PAGE_MAX,
284                        ),
285                    ),
286                    'additionalProperties' => false,
287                ),
288                'output_schema'       => array(
289                    'type'  => 'array',
290                    'items' => $backup_item_schema,
291                ),
292                'execute_callback'    => array( __CLASS__, 'execute_list_backups' ),
293                'permission_callback' => array( __CLASS__, 'can_view_backups' ),
294                'meta'                => array(
295                    'annotations'  => array(
296                        'readonly'    => true,
297                        'destructive' => false,
298                        'idempotent'  => true,
299                    ),
300                    'public'       => true,
301                    'mcp'          => array(
302                        'public' => true,
303                        'type'   => 'tool',
304                    ),
305                    'show_in_rest' => true,
306                ),
307            ),
308
309            'jetpack-backup/list-restores'       => array(
310                'label'               => __( 'List restores', 'jetpack-backup-pkg' ),
311                'description'         => '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.',
312                'input_schema'        => array(
313                    'type'                 => 'object',
314                    'default'              => array(),
315                    'properties'           => array(
316                        'id'       => array(
317                            'type'        => 'string',
318                            'description' => 'Return only the restore with this id. Unknown ids yield an empty array.',
319                            'minLength'   => 1,
320                        ),
321                        'page'     => array(
322                            'type'        => 'integer',
323                            'description' => 'Page number, 1-based.',
324                            'default'     => 1,
325                            'minimum'     => 1,
326                        ),
327                        'per_page' => array(
328                            'type'        => 'integer',
329                            'description' => 'Items per page (default 20, max 100).',
330                            'default'     => self::PER_PAGE_DEFAULT,
331                            'minimum'     => 1,
332                            'maximum'     => self::PER_PAGE_MAX,
333                        ),
334                    ),
335                    'additionalProperties' => false,
336                ),
337                'output_schema'       => array(
338                    'type'  => 'array',
339                    'items' => $restore_item_schema,
340                ),
341                'execute_callback'    => array( __CLASS__, 'execute_list_restores' ),
342                'permission_callback' => array( __CLASS__, 'can_view_backups' ),
343                'meta'                => array(
344                    'annotations'  => array(
345                        'readonly'    => true,
346                        'destructive' => false,
347                        'idempotent'  => true,
348                    ),
349                    'public'       => true,
350                    'mcp'          => array(
351                        'public' => true,
352                        'type'   => 'tool',
353                    ),
354                    'show_in_rest' => true,
355                ),
356            ),
357
358            'jetpack-backup/request-backup'      => array(
359                'label'               => __( 'Request a backup', 'jetpack-backup-pkg' ),
360                'description'         => '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.',
361                'input_schema'        => array(
362                    'type'                 => 'object',
363                    'default'              => array(),
364                    'properties'           => array(),
365                    'additionalProperties' => false,
366                ),
367                'output_schema'       => array(
368                    'type'       => 'object',
369                    'properties' => array(
370                        'enqueued' => array( 'type' => 'boolean' ),
371                        'message'  => array( 'type' => 'string' ),
372                    ),
373                ),
374                'execute_callback'    => array( __CLASS__, 'execute_request_backup' ),
375                'permission_callback' => array( __CLASS__, 'can_manage_backups' ),
376                'meta'                => array(
377                    'annotations'  => array(
378                        'readonly'    => false,
379                        'destructive' => false,
380                        'idempotent'  => false,
381                    ),
382                    'public'       => true,
383                    'mcp'          => array(
384                        'public' => true,
385                        'type'   => 'tool',
386                    ),
387                    'show_in_rest' => true,
388                ),
389            ),
390        );
391    }
392
393    /**
394     * Permission check for read abilities: the REST routes' own check,
395     * Jetpack_Backup::backups_permissions_callback(), whose error names the reason.
396     * Kept separate from `can_manage_backups()` so the read and write surfaces
397     * can diverge later without touching every spec.
398     *
399     * @return bool|WP_Error
400     */
401    public static function can_view_backups() {
402        return Jetpack_Backup::backups_permissions_callback();
403    }
404
405    /**
406     * Permission check for write abilities. See `can_view_backups()`.
407     *
408     * @return bool|WP_Error
409     */
410    public static function can_manage_backups() {
411        return Jetpack_Backup::backups_permissions_callback();
412    }
413
414    /**
415     * Composite read: each subfield is null on upstream failure rather than
416     * failing the whole call, so a partial wpcom outage degrades to "missing
417     * pieces" instead of "no data." Registration is gated on a Backup product
418     * being loaded (see register_abilities), so this callback assumes the
419     * site has one and only reports on the data it can fetch.
420     *
421     * @param mixed $input Unused; ability accepts no input. Typed `mixed` because
422     *                     the Abilities API may pass the raw caller-supplied value
423     *                     (string/null/array) before our `additionalProperties:false`
424     *                     schema runs — a strict array type would fatal on garbage input.
425     * @return array
426     */
427    public static function execute_get_backup_overview( $input = null ): array {
428        unset( $input );
429
430        $backups       = self::unwrap_response( Jetpack_Backup::get_recent_backups() );
431        $schedule_data = self::unwrap_response( Jetpack_Backup::get_site_backup_schedule_time() );
432        $size_data     = self::unwrap_response( Jetpack_Backup::get_site_backup_size() );
433        // Two round-trips because neither route describes storage alone: `/rewind/size`
434        // reports usage, `/rewind/policies` the limit. Fetched unconditionally so a
435        // usable limit still arrives when usage cannot be measured.
436        $policies_data = self::unwrap_response( Jetpack_Backup::get_site_backup_policies() );
437
438        return array(
439            'recent_backup_count' => is_array( $backups ) ? count( $backups ) : null,
440            'last_backup'         => self::summarize_last_backup( is_array( $backups ) ? ( $backups[0] ?? null ) : null ),
441            'schedule'            => self::summarize_schedule( $schedule_data ),
442            'storage'             => self::summarize_storage( $size_data, $policies_data ),
443        );
444    }
445
446    /**
447     * Consolidated read: queries the wpcom activity-log rewindable feed
448     * (server-side date filtering, up to 1000 items/page) and reshapes
449     * activity events back into the backup-item schema. All input filters
450     * land here; the picker is invoked when a `date` + `match` is set.
451     *
452     * @param mixed $input See input_schema on `jetpack-backup/list-backups`.
453     * @return array|WP_Error
454     */
455    public static function execute_list_backups( $input = null ) {
456        $input = is_array( $input ) ? $input : array();
457
458        // Validate `date` / `date_from` / `date_to` ahead of the round-trip so
459        // agents get a specific error rather than a 200 with mysterious empty
460        // results. Schema's `format: date-time` is advisory in WP REST.
461        foreach ( array( 'date', 'date_from', 'date_to' ) as $key ) {
462            if ( isset( $input[ $key ] ) && '' !== $input[ $key ] && null === self::parse_timestamp( $input[ $key ] ) ) {
463                return new WP_Error(
464                    'jetpack_backup_invalid_date',
465                    /* translators: %s is an input parameter name. */
466                    sprintf( __( 'The `%s` parameter must be a valid ISO 8601 datetime (e.g. "2026-05-13T14:30:00Z").', 'jetpack-backup-pkg' ), $key )
467                );
468            }
469        }
470
471        $per_page = min(
472            self::PER_PAGE_MAX,
473            max( 1, isset( $input['per_page'] ) ? (int) $input['per_page'] : self::PER_PAGE_DEFAULT )
474        );
475        $page     = max( 1, isset( $input['page'] ) ? (int) $input['page'] : 1 );
476
477        // `page` is suppressed on the single-result lookups (id, date+match)
478        // — those resolve from page 1 and walking later pages would skip
479        // candidates without an obvious benefit.
480        $is_single_lookup = ( isset( $input['id'] ) && '' !== $input['id'] )
481            || ( isset( $input['date'] ) && '' !== $input['date'] );
482
483        $query = array(
484            'number'     => $per_page,
485            'page'       => $is_single_lookup ? 1 : $page,
486            'sort_order' => 'desc',
487        );
488        if ( isset( $input['date_from'] ) && '' !== $input['date_from'] ) {
489            $query['after'] = (string) $input['date_from'];
490        }
491        if ( isset( $input['date_to'] ) && '' !== $input['date_to'] ) {
492            $query['before'] = (string) $input['date_to'];
493        }
494
495        $envelope = self::unwrap_response( Jetpack_Backup::list_backup_events( $query ) );
496        $events   = self::extract_rewindable_items( $envelope );
497        if ( ! is_array( $events ) ) {
498            return array();
499        }
500
501        $items = array_values( array_filter( array_map( array( __CLASS__, 'summarize_backup_event' ), $events ) ) );
502
503        // Single-id filter — same convention as the old endpoint: 0/1-element array.
504        if ( isset( $input['id'] ) && is_string( $input['id'] ) && '' !== $input['id'] ) {
505            foreach ( $items as $item ) {
506                if ( isset( $item['id'] ) && (string) $item['id'] === $input['id'] ) {
507                    return array( $item );
508                }
509            }
510            return array();
511        }
512
513        // Client-side status filter (server-side filters by event name, not status).
514        if ( isset( $input['status'] ) && is_string( $input['status'] ) && '' !== $input['status'] ) {
515            $want  = $input['status'];
516            $items = array_values(
517                array_filter(
518                    $items,
519                    static function ( $i ) use ( $want ) {
520                        return ( $i['status'] ?? null ) === $want;
521                    }
522                )
523            );
524        }
525
526        // Single-match shortcut.
527        if ( isset( $input['date'] ) && '' !== $input['date'] ) {
528            $target = self::parse_timestamp( $input['date'] );
529            $match  = isset( $input['match'] ) && is_string( $input['match'] ) ? $input['match'] : 'on_or_before';
530            if ( ! in_array( $match, array( 'on_or_before', 'on_or_after', 'closest' ), true ) ) {
531                $match = 'on_or_before';
532            }
533            $pick = self::pick_backup_near_timestamp( $items, (int) $target, $match );
534            return null === $pick ? array() : array( $pick );
535        }
536
537        return array_slice( $items, 0, $per_page );
538    }
539
540    /**
541     * Execute callback for `jetpack-backup/list-restores`.
542     *
543     * @param mixed $input See input_schema on the ability.
544     * @return array
545     */
546    public static function execute_list_restores( $input = null ): array {
547        $restores = self::unwrap_response( Jetpack_Backup::get_recent_restores() );
548        if ( ! is_array( $restores ) ) {
549            return array();
550        }
551
552        $summarized = array_map( array( __CLASS__, 'summarize_restore' ), $restores );
553        return self::apply_id_or_pagination( $summarized, is_array( $input ) ? $input : array() );
554    }
555
556    /**
557     * Pure picker for the `date` + `match` shortcut. Operates on already-
558     * summarized backup items (so it works regardless of which upstream
559     * helper produced them) and uses `started` as the comparison timestamp.
560     *
561     * @param array  $items     Summarized backup items.
562     * @param int    $target_ts Unix timestamp the caller is searching around.
563     * @param string $match     'on_or_before' | 'on_or_after' | 'closest'.
564     * @return array|null The winning item or null when nothing matches.
565     */
566    private static function pick_backup_near_timestamp( array $items, int $target_ts, string $match ): ?array {
567        $best       = null;
568        $best_score = null;
569
570        foreach ( $items as $item ) {
571            $ts = self::parse_timestamp( $item['started'] ?? null );
572            if ( null === $ts ) {
573                continue;
574            }
575
576            $diff  = $ts - $target_ts;
577            $score = 0;
578            switch ( $match ) {
579                case 'on_or_after':
580                    if ( $diff < 0 ) {
581                        continue 2;
582                    }
583                    $score = $diff;
584                    break;
585                case 'closest':
586                    $score = abs( $diff );
587                    break;
588                case 'on_or_before':
589                default:
590                    if ( $diff > 0 ) {
591                        continue 2;
592                    }
593                    $score = -$diff;
594                    break;
595            }
596
597            if ( null === $best_score || $score < $best_score ) {
598                $best       = $item;
599                $best_score = $score;
600            }
601        }
602
603        return $best;
604    }
605
606    /**
607     * Pull the activity-event array out of the W3C ActivityStreams envelope
608     * that `/activity/rewindable` returns. The endpoint puts the items in
609     * `current.orderedItems`; older proxy shapes used `orderedItems` at the
610     * top level, so check both before giving up.
611     *
612     * @param mixed $envelope Raw decoded response body.
613     * @return array|null
614     */
615    private static function extract_rewindable_items( $envelope ): ?array {
616        if ( ! is_array( $envelope ) && ! is_object( $envelope ) ) {
617            return null;
618        }
619        $envelope = (array) $envelope;
620        if ( isset( $envelope['current'] ) ) {
621            $current = (array) $envelope['current'];
622            if ( isset( $current['orderedItems'] ) && is_array( $current['orderedItems'] ) ) {
623                return $current['orderedItems'];
624            }
625        }
626        if ( isset( $envelope['orderedItems'] ) && is_array( $envelope['orderedItems'] ) ) {
627            return $envelope['orderedItems'];
628        }
629        return null;
630    }
631
632    /**
633     * Translate one /activity/rewindable event into the same backup-item
634     * shape `summarize_backup()` produces, so the ability's output schema
635     * stays stable across the upstream switch. Returns null for events that
636     * don't look like backups (no `rewind_id`).
637     *
638     * @param mixed $raw One element from `current.orderedItems`.
639     * @return array|null
640     */
641    private static function summarize_backup_event( $raw ): ?array {
642        if ( ! is_array( $raw ) && ! is_object( $raw ) ) {
643            return null;
644        }
645        $raw = (array) $raw;
646
647        $rewind_id = $raw['rewind_id'] ?? null;
648        if ( null === $rewind_id || '' === $rewind_id ) {
649            return null;
650        }
651
652        $published     = isset( $raw['published'] ) && is_string( $raw['published'] ) ? $raw['published'] : null;
653        $status_raw    = isset( $raw['status'] ) && is_string( $raw['status'] ) ? $raw['status'] : null;
654        $name          = isset( $raw['name'] ) && is_string( $raw['name'] ) ? $raw['name'] : '';
655        $is_rewindable = isset( $raw['is_rewindable'] ) ? (bool) $raw['is_rewindable'] : null;
656
657        return array(
658            'id'            => (string) $rewind_id,
659            'started'       => $published,
660            'last_updated'  => $published,
661            'status'        => self::map_event_status( $status_raw, $name ),
662            'period'        => self::parse_timestamp( $rewind_id ),
663            'is_rewindable' => $is_rewindable,
664            'has_warnings'  => self::event_has_warnings( $status_raw, $name ),
665        );
666    }
667
668    /**
669     * Map activity-event status / action-name to the status vocabulary the
670     * ability's output schema uses (the same labels as the old
671     * `/rewind/backups` endpoint: "finished", "error", ...). Falls back to
672     * the raw status when no mapping fits so the caller still sees signal.
673     *
674     * @param string|null $status_raw Activity event status (e.g. "success", "warning", "error").
675     * @param string      $name       Activity name, e.g. "rewind__backup_complete_full".
676     * @return string|null
677     */
678    private static function map_event_status( ?string $status_raw, string $name ): ?string {
679        if ( 'success' === $status_raw || false !== strpos( $name, 'backup_complete' ) ) {
680            return 'finished';
681        }
682        return $status_raw;
683    }
684
685    /**
686     * Derive `has_warnings` from an activity event's status / name.
687     *
688     * @param string|null $status_raw Activity event status.
689     * @param string      $name       Activity name.
690     * @return bool|null
691     */
692    private static function event_has_warnings( ?string $status_raw, string $name ): ?bool {
693        if ( 'warning' === $status_raw ) {
694            return true;
695        }
696        if ( 'success' === $status_raw || false !== strpos( $name, 'backup_complete' ) ) {
697            return false;
698        }
699        return null;
700    }
701
702    /**
703     * Coerce an ISO 8601 string, RFC-style date string, or numeric unix
704     * timestamp to an int unix timestamp. Returns null for anything that
705     * can't be unambiguously parsed (instead of strtotime's `false`, which
706     * is also a valid timestamp for 1969-12-31).
707     *
708     * Fractional numeric strings (e.g. rewind_id "1778804242.107") are
709     * accepted — the fractional part is truncated.
710     *
711     * @param mixed $value Source value (string, int, float, or anything else).
712     * @return int|null
713     */
714    private static function parse_timestamp( $value ): ?int {
715        if ( is_int( $value ) ) {
716            return $value;
717        }
718        if ( is_float( $value ) ) {
719            return (int) $value;
720        }
721        if ( is_string( $value ) && '' !== $value ) {
722            if ( is_numeric( $value ) ) {
723                return (int) $value;
724            }
725            $ts = strtotime( $value );
726            return false === $ts ? null : $ts;
727        }
728        return null;
729    }
730
731    /**
732     * Enqueue an on-demand backup. Registration is gated on a Backup product
733     * being loaded so we assume one exists by the time this runs. Returns
734     * WP_Error only when the upstream connection itself fails so agents can
735     * retry strategically.
736     *
737     * @param mixed $input Unused; see note on execute_get_backup_overview().
738     * @return array|WP_Error
739     */
740    public static function execute_request_backup( $input = null ) {
741        unset( $input );
742
743        // wpcom can return HTTP 200 with `{ success: false, error: ... }`; treat
744        // that as a failure rather than reporting the backup was enqueued.
745        $result = self::unwrap_response( Jetpack_Backup::enqueue_backup() );
746        if ( ! is_array( $result ) || empty( $result['success'] ) ) {
747            return new WP_Error(
748                'jetpack_backup_data_unavailable',
749                __( 'The backup service did not accept the request. The connection to WordPress.com may be temporarily unavailable; retry shortly.', 'jetpack-backup-pkg' )
750            );
751        }
752
753        return array(
754            'enqueued' => true,
755            'message'  => __( 'Backup enqueued. Use jetpack-backup/list-backups to monitor progress.', 'jetpack-backup-pkg' ),
756        );
757    }
758
759    /**
760     * Normalize a Jetpack_Backup helper result (WP_REST_Response, array, null,
761     * or WP_Error) to a plain value or null. Jetpack_Backup uses
762     * `rest_ensure_response()` on success; on failure its routes return a
763     * WP_Error and `list_backup_events()` returns null, so abilities need
764     * every shape flattened before summarising.
765     *
766     * @param mixed $maybe_response Result of a Jetpack_Backup helper call.
767     * @return mixed
768     */
769    private static function unwrap_response( $maybe_response ) {
770        if ( null === $maybe_response || is_wp_error( $maybe_response ) ) {
771            return null;
772        }
773        if ( $maybe_response instanceof WP_REST_Response ) {
774            return $maybe_response->get_data();
775        }
776        return $maybe_response;
777    }
778
779    /**
780     * Slice the (already-summarized) list down to a single id, or apply
781     * page/per_page pagination. Always returns the same item shape.
782     *
783     * @param array $items Summarized items.
784     * @param array $input Sanitized input.
785     * @return array
786     */
787    private static function apply_id_or_pagination( array $items, array $input ): array {
788        if ( isset( $input['id'] ) && is_string( $input['id'] ) && '' !== $input['id'] ) {
789            foreach ( $items as $item ) {
790                if ( isset( $item['id'] ) && (string) $item['id'] === $input['id'] ) {
791                    return array( $item );
792                }
793            }
794            return array();
795        }
796
797        $page     = max( 1, (int) ( $input['page'] ?? 1 ) );
798        $per_page = min( self::PER_PAGE_MAX, max( 1, (int) ( $input['per_page'] ?? self::PER_PAGE_DEFAULT ) ) );
799
800        return array_slice( $items, ( $page - 1 ) * $per_page, $per_page );
801    }
802
803    /**
804     * High-signal summary used inside `last_backup` for the overview. Same as
805     * `summarize_backup` minus the `started`/`period` fields which the agent
806     * doesn't need at a glance.
807     *
808     * @param mixed $raw One element from the upstream backups list.
809     * @return array|null
810     */
811    private static function summarize_last_backup( $raw ): ?array {
812        if ( ! is_array( $raw ) && ! is_object( $raw ) ) {
813            return null;
814        }
815        return array_diff_key(
816            self::summarize_backup( $raw ),
817            array_flip( array( 'started', 'period' ) )
818        );
819    }
820
821    /**
822     * Summarize a `/rewind/backups` payload item using `rewind_id` as the
823     * canonical `id`. The numeric attempt id wpcom also exposes is
824     * internal to VaultPress and can't be looked up via any other endpoint,
825     * so it's intentionally dropped from the agent-facing shape — see the
826     * note on `$backup_item_schema` in `get_abilities()`.
827     *
828     * @param mixed $raw Upstream backup item.
829     * @return array
830     */
831    private static function summarize_backup( $raw ): array {
832        $raw       = (array) $raw;
833        $rewind_id = $raw['rewind_id'] ?? null;
834        return array(
835            'id'            => ( null === $rewind_id || '' === $rewind_id ) ? null : (string) $rewind_id,
836            'started'       => $raw['started'] ?? null,
837            'last_updated'  => $raw['last_updated'] ?? null,
838            'status'        => $raw['status'] ?? null,
839            'period'        => $raw['period'] ?? null,
840            'is_rewindable' => isset( $raw['is_rewindable'] ) ? (bool) $raw['is_rewindable'] : null,
841            'has_warnings'  => isset( $raw['has_warnings'] ) ? (bool) $raw['has_warnings'] : null,
842        );
843    }
844
845    /**
846     * Summarize a `/rewind/restores` payload item. `id` is the rewind_id
847     * of the backup being restored to — same canonical id system as
848     * `summarize_backup()`.
849     *
850     * @param mixed $raw Upstream restore item.
851     * @return array
852     */
853    private static function summarize_restore( $raw ): array {
854        $raw       = (array) $raw;
855        $rewind_id = $raw['rewind_id'] ?? null;
856        return array(
857            'id'           => ( null === $rewind_id || '' === $rewind_id ) ? null : (string) $rewind_id,
858            'started'      => $raw['started'] ?? null,
859            'last_updated' => $raw['last_updated'] ?? null,
860            'status'       => $raw['status'] ?? null,
861            'progress'     => isset( $raw['progress'] ) ? (int) $raw['progress'] : null,
862        );
863    }
864
865    /**
866     * Summarize the `/site/backup/schedule` payload to `{ hour }`.
867     *
868     * WordPress.com answers `{ ok, scheduled_hour, scheduled_by }` — the UTC hour of the
869     * daily backup, and no minute anywhere. `ok` is its own success flag inside a 200
870     * body, so a payload without it carries no usable hour.
871     *
872     * @param mixed $raw Upstream schedule payload.
873     * @return array|null
874     */
875    private static function summarize_schedule( $raw ): ?array {
876        if ( ! is_array( $raw ) && ! is_object( $raw ) ) {
877            return null;
878        }
879        $raw = (array) $raw;
880        if ( empty( $raw['ok'] ) ) {
881            return null;
882        }
883        return array(
884            'hour' => isset( $raw['scheduled_hour'] ) ? (int) $raw['scheduled_hour'] : null,
885        );
886    }
887
888    /**
889     * Summarize storage from the two payloads that between them describe it.
890     *
891     * Usage is `size` on `/site/backup/size`, which despite its name carries no limit;
892     * the limit is `policies.storage_limit_bytes` on `/site/backup/policies`.
893     *
894     * The two are read independently, so a site whose usage could not be measured still
895     * reports what it is allowed. That is deliberately unlike `summarize_schedule()`,
896     * which has nothing left to report once its hour is gone.
897     *
898     * @param mixed $size_raw     Upstream `/site/backup/size` payload.
899     * @param mixed $policies_raw Upstream `/site/backup/policies` payload.
900     * @return array|null
901     */
902    private static function summarize_storage( $size_raw, $policies_raw ): ?array {
903        $size     = ( is_array( $size_raw ) || is_object( $size_raw ) ) ? (array) $size_raw : null;
904        $policies = ( is_array( $policies_raw ) || is_object( $policies_raw ) ) ? (array) $policies_raw : null;
905
906        if ( null === $size && null === $policies ) {
907            return null;
908        }
909
910        $used_bytes = ( null !== $size && ! empty( $size['ok'] ) && isset( $size['size'] ) )
911            ? (int) $size['size']
912            : null;
913
914        // `policies` is itself nullable inside a 200: a plan with no retention policy
915        // answers `{ "policies": null }`.
916        $policy = $policies['policies'] ?? null;
917        $policy = ( is_array( $policy ) || is_object( $policy ) ) ? (array) $policy : null;
918
919        $limit_bytes = ( null !== $policy && isset( $policy['storage_limit_bytes'] ) )
920            ? (int) $policy['storage_limit_bytes']
921            : null;
922
923        return array(
924            'used_bytes'  => $used_bytes,
925            'limit_bytes' => $limit_bytes,
926        );
927    }
928}