Skip to content

feat(labeler): image AI adapter (W8.3) - #2003

Merged
ascorbic merged 2 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-image-ai-adapter
Jul 13, 2026
Merged

ascorbic merged 2 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-image-ai-adapter

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Adds the labeler's image AI adapter — plan item W8.3, the sibling of #1994's code adapter. analyzeImages(input, deps) analyzes a plugin's icons/screenshots with the same Kimi model (vision) via the injected Workers AI binding and returns validated NormalizedFinding[] (source "image"), looking for impersonation, phishing UI, misleading content, and policy imagery.

  • Same hardened shape as the code adapter. Pure module, injected binding, satisfies ChatCompletionsInput request pin, { name, schema } structured output constrained to the policy's category/severity enums, unconditional provenance override, model/transport/parse failures and out-of-contract model output → retryable ModelTransientError.
  • Images as data-URI content parts on a single chat-completions request — no external fetch, no per-image concurrency to bound. The MIME allowlist (png/jpeg/webp/gif, exact match) is enforced before URI construction, so a crafted MIME can't reach the URI.
  • In-image text is untrusted. Screenshots can contain rendered text like "ignore previous instructions"; the system prompt explicitly declares text inside images plugin-controlled content, never instructions. Metadata and the image manifest (paths JSON-encoded + sentinel-escaped) ride in the same exact-token untrusted fences as the code adapter.
  • Honest bounded coverage. Per-image cap (2MB base64), count cap (12), and an aggregate payload cap (8MB) — the Workers AI binding has no documented request ceiling, and an over-large request would fail as retryable-forever; dropping to fit degrades coverage honestly instead (coverage: "partial" + deduplicated, input-ordered droppedImages). Zero kept images (empty input or all dropped) skips the model call entirely and reports call: null.
  • Closes a retry-forever gap in both adapters (found by the adversarial pass, inherited from feat(labeler): code/metadata AI adapter (W8.2) #1994): an over-long promptVersion or modelId would fail sourceMetadata validation on every call and be misclassified as retryable. Both adapters now fail fast with a non-retryable TypeError (bounded by MAX_METADATA_FIELD_LENGTH, now exported from findings.ts).

Not wired to the orchestrator's imageAi stage — that waits on the W7.3 bundle-input producer, same as the code adapter. No migration, no lexicon change, no public-API change.

Reviewed with an opus adversarial pass before opening; it confirmed the MIME/data-URI and manifest-fence surfaces safe and drove the aggregate-payload cap and the shared over-long-config fix.

Targets feat/plugin-registry-labelling-service. Related to #1909 and RFC #694.

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main.
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion: RFC RFC: Decentralized Plugin Registry #694

Admin i18n and changeset are n/a — this touches only apps/labeler, a private, unpublished Worker app (no admin UI, not on npm).

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Code with Claude Fable 5 (design, review coordination, fixes), an Opus 4.8 subagent (adversarial review), and a Sonnet subagent (implementation)

Screenshots / test output

  • pnpm --filter @emdash-cms/labeler test: 256 pass (17 files) — 25 new (happy path; provenance override; data-URI parts; manifest fence injection resistance; in-image-text prompt rule; MIME/size/count/aggregate bounds incl. near-miss MIME variants and duplicate-path dedup; no-call short-circuits; schema enum; transport/parse/out-of-enum → ModelTransientError; blank + over-long config → TypeError; promptHash stability)
  • Typecheck clean; pnpm lint:json diagnostics unchanged at 19 (0 in apps/labeler)
  • Tests use a fake binding only — never the live model

Try this PR

Open a fresh playground →

A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.

Tracks feat/labeler-image-ai-adapter. Updated automatically when the playground redeploys.

Add analyzeImages: a pure module that analyzes plugin icons/screenshots
with the Kimi vision model via the injected env.AI binding and returns
validated NormalizedFinding[] (source "image"). Images travel as
data-URI content parts on one chat-completions request pinned with
satisfies; the system prompt declares text rendered inside images
untrusted, and metadata plus the image manifest ride in the same
per-request untrusted fences as the code adapter.

Bounds: MIME allowlist, per-image and aggregate byte caps, and a count
cap, all dropping with honest partial coverage; zero kept images skips
the model call entirely (call: null). Both adapters now also fail fast
with a non-retryable TypeError on over-long promptVersion/modelId,
which validateSourceMetadata would otherwise reject on every call as a
misclassified retryable failure.
@changeset-bot

changeset-bot Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 203b267

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions Bot added review/needs-review No maintainer or bot review yet size/XL labels Jul 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 881 lines across 5 files. Large PRs are harder to review and more likely to be closed without review.

If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs.

See CONTRIBUTING.md for contribution guidelines.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-playground 203b267 Jul 13 2026, 06:58 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-do 203b267 Jul 13 2026, 06:57 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-cache 203b267 Jul 13 2026, 06:57 AM

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the right change at the right time: it adds the W8.3 image AI adapter as a symmetric sibling to the existing code adapter, keeps the same pure-module/injected-binding shape, and deliberately leaves orchestrator wiring to the W7.3 consumer work. The security model—exact-token fences, data-URI image parts, exact MIME allowlist, provenance override, and converting model/validation failures to ModelTransientError—is consistent with the code adapter and the implementation plan.

I read the diff and the full changed files but did not run the test suite, linter, or typechecker. The new tests look comprehensive for the behavior they cover (happy path, source/metadata override, data-URI construction, fence injection resistance, size/count/aggregate bounds, no-call short-circuits, config validation, and prompt-hash stability).

I found one spec gap that should be addressed before this part of W8.3 is considered complete, and one smaller defensive suggestion:

  1. Missing image hash in the adapter contract — the spec §9.7 and the W8.3 plan require private evidence to retain every image's original MIME type, hash, dimensions, and source path. ImageAnalysisImage currently has no hash field, so the adapter cannot pass the hash through to the manifest or to any downstream evidence object. This is a broken contract with the spec, not a stylistic nit.
  2. Blank modelId slips through fail-fast validation — deps.modelId ?? DEFAULT_MODEL_ID only falls back on undefined/null; an empty string reaches the binding and becomes a retryable ModelTransientError. A blank modelId should be rejected up front like a blank promptVersion.

Neither issue is a security/data-loss blocker, so I'm leaving this as comment rather than request_changes.

run(model: string, inputs: ImageAiRunInputs): Promise<unknown>;
}

export interface ImageAnalysisImage {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] ImageAnalysisImage captures path, mime, dataBase64, width, height, and kind, but it has no content-hash field. The spec §9.7 and the W8.3 plan both require private evidence to retain every image's original MIME type, hash, dimensions, and source path. Without a hash field, the adapter contract is incomplete and the orchestrator/evidence layer must reconstruct the hash out-of-band from the path, which risks losing it at the boundary.

Add readonly hash: string, include it in the image manifest, and update tests to pass and assert it.

Suggested change
export interface ImageAnalysisImage {
export interface ImageAnalysisImage {
readonly path: string;
readonly mime: string;
readonly dataBase64: string;
+ readonly hash: string;
readonly width: number;
readonly height: number;
readonly kind: "icon" | "screenshot";
}

Also include the hash in buildManifestFence:

images.map((image) => ({
	path: image.path,
+	hash: image.hash,
	kind: image.kind,
	width: image.width,
	height: image.height,
})),

throw new TypeError(
`analyzeImages: deps.promptVersion must be at most ${MAX_METADATA_FIELD_LENGTH} characters`,
);
if (modelId.length > MAX_METADATA_FIELD_LENGTH)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] modelId is normalized with deps.modelId ?? DEFAULT_MODEL_ID, which only falls back when the value is null or undefined. An empty string is not nullish, so it slips through and is passed to deps.ai.run, which will fail and be wrapped as a retryable ModelTransientError. A caller/config bug like a blank model ID should fail fast with a non-retryable TypeError, just like the blank promptVersion check above.

Suggested change
if (modelId.length > MAX_METADATA_FIELD_LENGTH)
const modelId = deps.modelId ?? DEFAULT_MODEL_ID;
+ if (modelId.trim().length === 0)
+ throw new TypeError("analyzeImages: deps.modelId must be a non-empty string");
if (modelId.length > MAX_METADATA_FIELD_LENGTH)
throw new TypeError(
`analyzeImages: modelId must be at most ${MAX_METADATA_FIELD_LENGTH} characters`,
);

The same gap exists in analyzeCode (apps/labeler/src/code-ai-adapter.ts).

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jul 13, 2026
…ront

ImageAnalysisImage now carries the original image's sha256, and the
model-visible manifest retains mime/sha256/dimensions/path (spec §9.7).
A blank modelId slipped past the ?? fallback in both adapters and
surfaced as an endlessly-retried ModelTransientError; both now fail
fast with a non-retryable TypeError.
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Jul 13, 2026
@ascorbic

Copy link
Copy Markdown
Member Author

Both addressed:

  1. Image hash retained (spec §9.7): ImageAnalysisImage gains sha256, and the manifest now retains each image's mime/sha256/width/height/path — test asserts every field survives into the fenced manifest. The downstream evidence recorder (W7.3-consumer wiring) reads the same contract, so the retention chain is intact from input to model-visible manifest.
  2. Blank modelId: both adapters now reject a blank (empty/whitespace) modelId up front with a non-retryable TypeError — same treatment as blank promptVersion, tests assert TypeError-not-ModelTransientError with zero binding calls.

259 tests green. Re-triggering.

~ 🤖 Fable

@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 13, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: prior findings are fixed, no new blockers

This is the right change at the right place: it lands the W8.3 image AI adapter as a symmetric sibling to the existing code adapter, preserves the same pure-module/injected-binding shape, and deliberately defers orchestrator wiring to the W7.3 consumer work. The security model (exact-token fences, data-URI image parts, exact MIME allowlist, provenance override, and converting model/validation failures to ModelTransientError) remains consistent with #1994.

I read the updated diff and the full changed files. Both findings from the previous review are addressed:

  1. Image hash is now in the adapter contract. ImageAnalysisImage gained a required sha256 field and buildManifestFence() now emits the hash, dimensions, MIME type, and source path for every kept image — matching spec §9.7's private-evidence retention requirement.
  2. Blank and over-long modelId / promptVersion now fail fast. Both analyzeCode and analyzeImages reject whitespace-only values and values longer than MAX_METADATA_FIELD_LENGTH with a non-retryable TypeError, closing the retry-forever gap described in the PR.

I also re-scanned the new adapter for the cross-cutting concerns in AGENTS.md: no SQL or migrations, no admin UI / i18n surface, no public API breakage, no locale-filtered content queries, ESM imports use .js extensions, type-only imports use import type, and the test-only fake-binding approach is unchanged. The partition/drop logic, aggregate cap, MIME allowlist, data-URI construction, and fence-escaping all behave as described; the coverage / call: null short-circuit for zero kept images is honest and tested.

I found no new blocking issues. Approving.

@ascorbic
ascorbic merged commit 569832c into feat/plugin-registry-labelling-service Jul 13, 2026
9 of 10 checks passed
@ascorbic
ascorbic deleted the feat/labeler-image-ai-adapter branch July 13, 2026 06:58
@github-actions github-actions Bot added review/approved Approved; no new commits since and removed review/needs-rereview New commits since the last review labels Jul 13, 2026
@ascorbic ascorbic mentioned this pull request Jul 14, 2026
60 of 81 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:review Trigger an emdashbot code review on this PR cla: signed review/approved Approved; no new commits since size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant