Skip to content

Port the wp/media-query ability from WordPress/ai PR #1098 - #5

Merged
nikmclaughlin merged 1 commit into
mainfrom
add/wp-media-query
Oct 29, 2026
Merged

nikmclaughlin merged 1 commit into
mainfrom
add/wp-media-query

Conversation

@nikmclaughlin

@nikmclaughlin nikmclaughlin commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

What?

Ports the read-only media query ability from WordPress/ai PR #1098 ("Add core/media-query ability", author @jorgefilipecosta) into this package as wp/media-query, tier experimental.

Follows the AI-plugin-port pattern of the content trio (#2/#3), not the tier-core backport pattern: the ability class is hand-authored on Abstract_Core_Ability, and the PR's core/media-query name is not adopted (no alias, per the rename protocol).

Why?

Agents can read posts, users, and settings through abilities, but not the media library. The WordPress/ai plugin registers core/media-query behind its experiment flag; this package gives consumers one canonical, consumer-free copy while the upstream proposal settles. The experimental tier fits: the upstream ability is an open PR, not landed core, so the name and schema carry no promises yet (core_since: null).

How?

  • src/Media/Media_Query.php (WordPress\Abilities\Media\Media_Query, final, extends Abstract_Core_Ability) — a faithful port of the PR's ability class:
    • Two mutually exclusive modes, modeled as a oneOf input schema: one item by id, or a collection returning { media, total, total_pages }.
    • Filters search, media_type, mime_type, parent, author, include, exclude, status; sorting orderby/order; paging page/per_page (max 100).
    • fields picks the returned fields with the PR's lean default set; id is always returned; title/caption/description flatten to *_raw/*_rendered; a raw field switches the request to the edit context (collections then list only editable items).
    • The PR's REST-mirroring quirks are kept as-is and pinned in tests: totals count unreadable items; exclude is ignored when include is given; disallowed MIME types are ignored; password-protected items' generated captions stay gated while rendered descriptions do not; a missing item is denied like an unreadable one; a queryable-but-forbidden status reports media_invalid_param (400) from the execute callback rather than ability_invalid_permissions.
    • Registration entry points, the experiment flag, wpai_* filters, and the plugin's base class are not ported — the Registrar owns registration, the text domain is default, callbacks are closures, and no support-feature polyfill is needed (requires stays empty; everything the ability reads predates WP 6.9).
  • src/Manifest.php — entry 'wp/media-query', tier TIER_EXPERIMENTAL, min_wp_version: 6.9, core_since: null, proposal: https://github.com/WordPress/ai/pull/1098.
  • src/Categories.php — new package-authored media ability category "Abilities that retrieve or manage media items and attachments.". Core trunk's wp_register_core_ability_categories() registers no media category, so there is nothing to copy verbatim; the entry is styled like trunk's own registrations and carries an in-code note to replace it with core's strings should core land one. This is the first manifest category the host does not provide on any environment.
  • tests/Abilities/MediaQueryTest.php — the per-ability contract suite in this repo's shape, ported from the PR's MediaTest: schemas (input and output) asserted through the Registrar; permission negative and positive on every gate path (logged out, per-role visibility by status/parent, raw-field edit gates, hidden-from-REST denial, missing-item denial indistinguishable from unreadable); fail-closed on malformed/unknown input across 18 oneOf cases; execute against factory data — filters, string/CSV inputs, statuses, ordering rules (relevance/include guards), pagination bounds, password gate, rendered-field filters, filesize metadata normalization, media-details sizes (skipped only when GD lacks JPEG), output-schema validation, global-post restore, and filter cleanup after a throwing title filter.
  • tests/RegistrarTest.php — the two P8 tests (opt-out filter, late first contact) assumed every manifest category is host-provided, which is no longer true now that the manifest declares the host-less media category. Both generalize to observe which manifest slugs the host lacks (observed state, no version sniffing): the loud Gate-8 path is asserted for those slugs, per-ability registration branches on the host-owned content category, and both tests now also replay their windows on the host-owned path so package-declared categories survive for the following suites. On stable (7.1.x) the behavior is unchanged.
  • Docs — README row + roadmap note (media read is shipped; future media abilities incubate under wp/), CHANGELOG Added entry (experimental), and KNOWN-ISSUES "Ported-as-is PR behaviors" entries for the quirks above.

Testing Instructions

All four local gates pass, and the PHPUnit suite passes on both wp-env environments:

composer run lint:phpcs      # pass
composer run lint:phpstan    # pass
composer run verify:manifest # pass
composer run verify:coreify  # pass
npx @wordpress/env run tests-cli --config=.wp-env.trunk.json bash -c "cd wp-content/plugins/wordpress-abilities && vendor/bin/phpunit"   # OK: 126 tests (trunk, 7.2-dev)
npx @wordpress/env run tests-cli --config=.wp-env.stable.json bash -c "cd wp-content/plugins/wordpress-abilities && vendor/bin/phpunit"  # OK: 126 tests, 1154 assertions (stable, 7.1.4)

Manual: register the package in a wp_abilities_api_init callback and run wp_get_ability( 'wp/media-query' )->execute( array( 'id' => ATTACHMENT_ID ) ) as an editor (default fields) and as a subscriber (denied for others' drafts' attachments; raw fields need edit access). Collection mode returns media/total/total_pages.

Deviations from the source PR

  1. Name/tier: wp/media-query + experimental per the settled decision D5 (the PR's core/media-query name is reserved for core adoption via the promotion path; no alias ships).
  2. Category: the PR used content and registered it as a fallback; the port uses the package-authored media category (see How).
  3. Registration plumbing (init hooks, core-copy replacement) is the Registrar's job here and was not ported.
  4. Text domain 'ai' → default; callbacks are closures wrapping the ported methods (the PR's protected_title_format() filter callback keeps its array form for callback identity).
  5. Two PHPStan-driven notes: get_input_schema()/get_output_schema() were renamed to ability-specific builders (get_media_query_input_schema()/get_media_query_output_schema()) to avoid colliding with WP_Ability's public getters; two @phpstan-ignores cover stored attachment metadata being looser than core's docblock shape (the PR's own tests pin strings/booleans in filesize metadata).
  6. RegistrarTest P8 generalization (see How) — an existing-suite contract update required by the first host-less manifest category, not a change to the PR behavior.

Changelog Entry

Added - New wp/media-query ability that mirrors the REST API media endpoint's read path, an experimental-tier port of WordPress/ai PR #1098, with the new package-authored media ability category.

Use of AI Tools

AI assistance: Yes
Tool(s): goose (agent)
Model(s): provided via the harness
Used for: Implementation, tests, and docs. Reviewed and edited by the committer.

Co-authored-by: jorgefilipecosta jorgefilipecosta@users.noreply.github.com

## What?

Adds `wp/media-query` to the package: a faithful port of the read-only media
query ability from WordPress/ai PR #1098 ("Add core/media-query ability",
author @jorgefilipecosta), incubating under the experimental tier's `wp/`
prefix. The PR's registration name is not adopted; no alias exists.

## Why?

Agents can read posts, users, and settings through abilities, but not the
media library. This package ports the ability so consumers get one canonical
copy, while the upstream proposal settles.

## How?

- **The ability:** `src/Media/Media_Query.php` mirrors the PR's class — label,
  description, input/output schemas (a `oneOf` of single-item and collection
  modes), annotations (`readonly`/`idempotent`, `open_world` false),
  error codes, the global-post restore, and the PR's documented REST quirks —
  on the package's `Abstract_Core_Ability` authoring surface, with the
  `default` text domain and closures for the registered callbacks.
- **Naming and tier:** manifest entry `wp/media-query`, tier `experimental`,
  `core_since: null` (flips when core lands it), proposal pointing at the
  WordPress/ai PR.
- **Category:** the `media` ability category is package-authored (core trunk
  registers no media category; nothing to copy verbatim) — declared through
  the Registrar's existing single-sourced `Categories` table.
- **No polyfill:** every core function the ability reads (attachments plumbing,
  `wp_get_original_image_path`, `wp_filesize`, the filename-search hook) long
  predates the 6.9 support floor; `requires` stays empty.
- **RegistrarTest P8 generalization:** with a package-declared-only category
  in the manifest, the opt-out and late-first-contact tests can no longer
  assume a 7.2+ host provides every manifest category; both tests now observe
  which manifest slugs the host lacks (no version sniffing), assert the loud
  Gate-8 path for those, and restore their replayed windows so the
  package-declared categories survive for the following suites.

### Use of AI Tools

AI assistance: Yes
Tool(s): goose (agent)
Model(s): provided via the harness
Used for: Implementation, tests, and docs. Reviewed and edited by the
committer.

## Testing Instructions

1. Load the package in a `wp_abilities_api_init` callback:
   `( new WordPress\Abilities\Registrar )->register_all();`
2. `wp_get_ability( 'wp/media-query' )->execute( array( 'id' => <attachment_id> ) )`
   returns the default fields (`id`, `date`, `slug`, `title_rendered`,
   `alt_text`, `media_type`, `mime_type`, `source_url`); adding
   `array( 'fields' => array( 'title_raw' ) )` requires edit access.
3. Collection mode: `execute( array( 'media_type' => 'image', 'per_page' => 2 ) )`
   returns `media`/`total`/`total_pages`.
4. Logged-out callers are denied with `ability_invalid_permissions`; a status
   the caller may not query reports `media_invalid_param`.
5. `composer run lint:phpcs && composer run lint:phpstan &&
   composer run verify:manifest && composer run verify:coreify` and the
   PHPUnit suite on both wp-env environments pass.

Co-authored-by: jorgefilipecosta <jorgefilipecosta@users.noreply.github.com>
@nikmclaughlin
nikmclaughlin merged commit 1fb99f0 into main Oct 29, 2026
12 checks passed
nikmclaughlin added a commit that referenced this pull request Oct 30, 2026
…Abilities from WordPress/ai PR #1104 (#7)

## What?

Adds the three media write abilities to the package: a faithful port of
WordPress/ai PR #1104 ("Add core/media-upload, core/media-update, and
core/media-delete abilities", author @jorgefilipecosta), incubating under the
experimental tier's `wp/` prefix on the shared `media` category and field
projection of `wp/media-query` (PR #5). The PR's `core/media-*` registration
names, gating, and unregister-core-copy wiring are not copied; no aliases exist.

## Why?

Agents can read the media library through abilities (`wp/media-query`) but not
write it. This package ports the three writes so consumers get one canonical
copy while the upstream proposal settles.

## How?

- **The abilities:** `src/Media/Abstract_Media_Write.php` (shared base) +
  `Media_Upload.php` / `Media_Update.php` / `Media_Delete.php` mirror the PR's
  logic — labels, descriptions, schemas (upload is a `oneOf` of base64-data and
  URL-branch; delete output is a `oneOf` of the trashed item and the
  `deleted`/`previous` pair), annotations (`open_world: true` on upload),
  error codes, the URL-sideload SSRF guard and download-size cap, the status /
  author / parent checks that name the refused field in the execute callback,
  and the global-post restoration — on the package's `Abstract_Core_Ability`
  authoring surface, with the `default` text domain and closures for the
  registered callbacks. Shared helpers are extracted verbatim from the
  package's `Media_Query` port with `private` relaxed to `protected`.
- **Naming and tier:** manifest entries `wp/media-*`, tier `experimental`,
  `core_since: null` (flips when core lands them), proposal pointing at the
  WordPress/ai PR.
- **No polyfill needed:** every core primitive the writes rely on
  (`wp_handle_sideload`, `wp_http_validate_url`, `MEDIA_TRASH`, the media-cap
  mapping) exists on the supported floor (WordPress 6.9+).
- **Tests:** `MediaUploadTest` / `MediaUpdateTest` / `MediaDeleteTest` —
  Registrar-based, ported from the PR's integration tests: negative and
  positive checks on every permission path (upload_files, edit_post, publish
  floors), wrapped and URL transports, trash/force semantics with the media
  trash guard, gone-read field parity against the live media REST endpoint
  responses, and hook/globals hygiene.

## Use of AI tools

Tool(s): goose (agent)
Model(s): provided via the harness
Used for: Implementation, tests, and docs. Reviewed and edited by the
committer.

## Testing Instructions

1. Load the package in a `wp_abilities_api_init` callback:
   `( new WordPress\Abilities\Registrar )->register_all();`
2. `wp_get_ability( 'wp/media-upload' )->execute( array( 'data' => base64_encode( $bytes ), 'filename' => 'p.jpg' ) )`
   uploads the file and returns the item in the edit context (raw fields
   included when requested — the caller already had edit access to upload).
3. `wp_get_ability( 'wp/media-update' )->execute( array( 'id' => $id, 'title' => 'New title' ) )`
   updates fields (omitted fields keep their values); a status other than the
   attachment's current one is validated, so non-attachment statuses are
   rejected while `inherit` can be kept.
4. `wp_get_ability( 'wp/media-delete' )->execute( array( 'id' => $id ) )`
   trashes (requires `MEDIA_TRASH`, else `media_trash_not_supported`);
   `array( 'id' => $id, 'force' => true )` deletes the attachment and its files
   permanently and returns `deleted`/`previous`.
5. `composer run lint:phpcs && composer run lint:phpstan && composer run verify:manifest`
   and the PHPUnit suite on both wp-env environments (one at a time) pass.

Co-authored-by: jorgefilipecosta <jorgefilipecosta@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add a core/media-query ability (read-only Media Library coverage)

1 participant