Skip to content

feat(labeler): code/metadata AI adapter (W8.2) - #1994

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

ascorbic merged 4 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-code-ai-adapter

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Adds the labeler's code/metadata AI adapter — plan item W8.2. analyzeCode(input, deps) analyzes a plugin's source files and metadata with a code model (Kimi @cf/moonshotai/kimi-k2.7-code) via the Workers AI binding (env.AI, injected — not AI Gateway) and returns validated NormalizedFinding[] (source "model"), feeding the W8.5 policy resolver.

  • Pure module. The AI binding is injected via deps; the module does no DB writes and imports nothing from cloudflare:workers, so it's fully testable against a fake binding and decoupled from the orchestrator's still-abstract StageContext. Wiring it into the codeAi stage — threading the acquired bundle and recording evidence objects — is deferred to the W7.3-consumer work once a real bundle-input producer exists.
  • Strict structured output. response_format: json_schema constrains each finding's category to exactly the policy's allowed set (automated-block ∪ warning) and severity/confidence to their ranges. The enum is derived from the versioned policy, not hardcoded.
  • Untrusted-input hardening. All plugin-controlled text — file content, file paths, and metadata — is wrapped in an untrusted fence with a unique per-request boundary token and sentinel-escaped, and the system prompt instructs the model to honor only an exact-token close. A malicious path or file can neither forge a boundary nor inject instructions.
  • Honest coverage. Input is budgeted against the assembled prompt size (escaping expansion + fences + paths + metadata + system prompt), not raw content. An oversized bundle drops largest-rendered files first and reports coverage: "partial" with the dropped paths — it never truncates silently.
  • Failure semantics. Model transport/parse failures, and model output that fails the W8.1 finding contract (e.g. an out-of-enum category), are ModelTransientError (retryable) — a flaky model is not the non-retryable stage-adapter bug a FindingValidationError signals. Model-supplied source/evidenceRefs/sourceMetadata are overridden so a model can't spoof provenance. A blank promptVersion is a caller bug and throws up front (not retried).

No migration, no lexicon change, no public-API change. Adds the AI binding to apps/labeler/wrangler.jsonc (regenerated worker-configuration.d.ts).

Reviewed with an opus adversarial pass that found and drove fixes for a fence-escape via unescaped paths, budget undercounting, a misclassified-retryable config bug, and two missing tests — all addressed here before opening.

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 Opus 4.8 (design, adversarial review, fixes) and a Sonnet subagent (implementation)

Screenshots / test output

  • pnpm --filter @emdash-cms/labeler test: 228 pass (16 files) — 17 new for the adapter (happy path; content-fence + malicious-path injection resistance; model-field override; schema enum = policy; transport/parse/out-of-enum → ModelTransientError; blank promptVersion → TypeError; oversized-bundle coverage/drops; no-cache option; promptHash stability + policy-sensitivity)
  • Typecheck clean; pnpm lint:json diagnostics unchanged at 19 (0 in apps/labeler)
  • Tests use a fake AiBinding only — never the live model (Workers AI bills even in local dev)

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-code-ai-adapter. Updated automatically when the playground redeploys.

@changeset-bot

changeset-bot Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 6f77950

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

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 652 lines across 4 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.

@github-actions github-actions Bot added size/XL review/needs-review No maintainer or bot review yet cla: signed labels Jul 12, 2026
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 12, 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 1716fa9 Jul 13 2026, 06:15 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 12, 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 1716fa9 Jul 13 2026, 06:17 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 12, 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 1716fa9 Jul 13 2026, 06:17 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 PR adds a self-contained W8.2 code/metadata AI adapter for the labeler, and the approach is sound: a pure module with injected AI binding, deterministic output normalization through validateFindings, explicit provenance overrides, fence escaping, and retry/failure semantics mapped to ModelTransientError.

I checked the prompt-fence escaping, path injection hardening, field-override behavior, policy-derived schema enum, failure mapping, Worker config updates, and test coverage. They all look correct and well-tested.

The one real issue is in capFilesToBudget: the per-file cost and overhead constants undercount the actual assembled user content by N + 1 newline characters for N files. That contradicts the PR's "honest coverage" guarantee—near the 200 k-char limit the adapter can still report coverage: "complete" while sending a slightly oversized context to the model. This is small but exactly the kind of silent truncation the change is meant to prevent.

Fixing the arithmetic and adding a close-to-limit regression test would make this clean to approve.

Comment thread apps/labeler/src/code-ai-adapter.ts Outdated
Comment on lines +264 to +265
const renderedCost = (file: CodeAnalysisFile) => buildFence(file, boundary).length + 1;
const total = files.reduce((sum, file) => sum + renderedCost(file), fixedOverheadChars);

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] buildUserContent assembles the user message by joining [metadataFence, "", file1Fence, "", file2Fence, "", ...], which produces 2N + 1 newline characters for N files. However, the budget math in capFilesToBudget only adds + 1 newline per file and starts from fixedOverheadChars without accounting for the leading separator between metadataFence and the first empty part. The assembled prompt is therefore undercounted by N + 1 characters.

For a bundle near the 200 k-char limit this allows the adapter to mark coverage: "complete" while still exceeding the model's context window, silently truncating instead of reporting partial coverage.

Suggested change
const renderedCost = (file: CodeAnalysisFile) => buildFence(file, boundary).length + 1;
const total = files.reduce((sum, file) => sum + renderedCost(file), fixedOverheadChars);
const renderedCost = (file: CodeAnalysisFile) => buildFence(file, boundary).length + 2;
const total = files.reduce((sum, file) => sum + renderedCost(file), fixedOverheadChars + 1);

The current oversized-bundle test uses very large files, so please also add a regression test sized just under/over the real 200 k limit so this arithmetic doesn't drift again.

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond review/needs-rereview New commits since the last review and removed review/needs-review No maintainer or bot review yet review/awaiting-author Reviewed; waiting on the author to respond labels Jul 12, 2026
@ascorbic

Copy link
Copy Markdown
Member Author

Fixed the budget undercount you flagged. capFilesToBudget was counting only rendered fence length; the assembled user content adds a blank-line separator per file plus a leading newline, so it undercounted by N+1 and near the cap could report complete while the prompt was slightly over. Now it charges the exact overhead — +2 per file (fence + separator) and +1 fixed — and a new test asserts the assembled prompt (system + user messages) stays <= MAX_MODEL_INPUT_CHARS under a 55-file over-budget bundle. Re-triggering.

(Separately: once #2001 — the workers-types v5 bump — lands on the base and this rebases onto it, I'll pin the input type to the real ChatCompletionsInput/k2.6 ambient type, since CF confirms kimi-k2.7-code shares k2.6's exact interface.)

@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.

This re-review confirms the one issue from the previous round is fixed, and the W8.2 code/metadata AI adapter is now clean.

The approach remains sound: a pure module with an injected AI binding, deterministic output normalization through validateFindings, explicit provenance overrides, per-request fence escaping, and a retry/failure model mapped to ModelTransientError.

I re-checked capFilesToBudget, which was the blocking finding. The accounting now matches the exact assembled user content:

  • fixedOverheadChars covers systemPrompt.length + metadataFence.length + 1.
  • Each rendered file fence is counted as buildFence(file, boundary).length + 2.
  • For N files, the code budgets for 2N + 1 newline separators, which is exactly what buildUserContent produces when it joins [metadataFence, "", ...fence, "", ...] with "\n".

The regression test with 55 mid-sized files asserts the assembled prompt stays within MAX_MODEL_INPUT_CHARS and reports partial coverage with dropped files, so the previous silent-overcount risk is covered.

Also verified: fence-escape logic prevents embedded <<< from breaking out; JSON.stringify(file.path) plus sentinel escaping keeps malicious path payloads on a single line; the response schema category enum derives from allowedFindingCategories(policy); model-supplied source/evidenceRefs/sourceMetadata are overridden; model-call/parse/validation failures map to ModelTransientError; blank promptVersion throws TypeError; the AI binding is correctly declared in wrangler.jsonc and typed in worker-configuration.d.ts; and fake-binding tests avoid live model calls.

No remaining findings.

@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 added 3 commits July 13, 2026 06:57
Add analyzeCode: a pure module that analyzes a plugin's source and
metadata with Kimi via the injected env.AI binding and returns validated
NormalizedFinding[] (source "model"), with strict JSON-schema output
constrained to the policy's allowed categories.

Plugin-controlled text (file content, paths, metadata) is fenced as
untrusted with a per-request boundary and sentinel-escaped so it can't
forge a boundary or inject instructions. Model/parse failures and
model-produced invalid findings are ModelTransientError (retryable);
model-supplied source/evidenceRefs/sourceMetadata are overridden. Input
is budgeted against assembled prompt size and degrades coverage to
partial rather than truncating silently.

Not yet wired to the orchestrator's codeAi stage; that waits on the
W7.3 bundle-input producer.
capFilesToBudget summed only rendered fence length, undercounting the
assembled prompt by the per-file and leading newlines the user content
adds when joined. Near the input cap this could report coverage
"complete" while sending an over-budget prompt. Account the exact
per-file (+2) and fixed (+1) newline overhead, and assert the assembled
prompt stays within MAX_MODEL_INPUT_CHARS.
Ground the request shape in the real Workers AI input type (kimi-k2.7-code
shares kimi-k2.6's chat-completions interface) via satisfies. This surfaced
a real bug: the native binding's json_schema response format is
{ name, schema }, not the bare schema object — the schema was previously
nested wrong and would have been rejected at runtime. Correct it and pin
so the shape can't drift.
@ascorbic
ascorbic force-pushed the feat/labeler-code-ai-adapter branch from dcae42c to 6f77950 Compare July 13, 2026 06:02
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/approved Approved; no new commits since labels Jul 13, 2026
@ascorbic

Copy link
Copy Markdown
Member Author

Heads-up: pushed one more commit after your approval, so re-triggering. Now that the workers-types v5 bump (#2001) is on the base, I rebased onto it and pinned the request to the real Workers AI ChatCompletionsInput via satisfies (kimi-k2.7-code shares kimi-k2.6's chat-completions interface). That pin caught a real bug: the native binding's json_schema response format is { name, schema }, not the bare schema object — our schema was nested wrong and would've been rejected at runtime. Fixed + the type now can't drift. 229 tests green, typecheck clean on v5.

@ascorbic ascorbic added bot:review Trigger an emdashbot code review on this PR and removed bot:review Trigger an emdashbot code review on this PR labels 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.

Approach is sound: a pure, injected-binding adapter aligns with the W8.2 plan and keeps the module testable and decoupled from the orchestrator. The prior blocking capFilesToBudget overcount is fixed — the + 2 per-file cost plus the + 1 fixed overhead exactly match the newlines produced by buildUserContent. Tests cover fence escaping, path injection, field overrides, retry classification, blank promptVersion, and prompt-hash stability.

I found one remaining defensive gap: the budget function treats the metadata fence as fixed overhead that can never be dropped, so an attacker-controlled metadata blob can push the assembled prompt past MAX_MODEL_INPUT_CHARS even after every file is dropped. That contradicts the PR's own "honest coverage" guarantee and turns into a retryable ModelTransientError if the Workers AI binding rejects the oversized request. Also a smaller suggestion that dropping by file path can over-drop bundles that contain duplicate paths.

No AGENTS.md violations (no SQL, no admin UI, internal .js imports, type imports, no migration/changeset needed for a private app). With the metadata budget gap closed this would be an approve.

const metadataFence = buildMetadataFence(input, boundary);
const fixedOverheadChars = systemPrompt.length + metadataFence.length + 1;
const { kept, dropped } = capFilesToBudget(
input.files,

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] fixedOverheadChars includes the full metadataFence, which is built from plugin-controlled metadata (name, description, publisherDid, version, declaredAccess). capFilesToBudget can only drop files, not metadata, so if the metadata fence alone exceeds MAX_MODEL_INPUT_CHARS, every file is dropped and the function still reports coverage: "partial" while sending an over-budget prompt. The PR explicitly advertises that "metadata" is budgeted alongside files and paths, so this is a real gap in the guarantee.

Add an up-front guard as soon as fixedOverheadChars is known:

Suggested change
input.files,
const fixedOverheadChars = systemPrompt.length + metadataFence.length + 1;
if (fixedOverheadChars > MAX_MODEL_INPUT_CHARS) {
throw new TypeError(
`analyzeCode: metadata and system prompt exceed model input budget (${fixedOverheadChars} > ${MAX_MODEL_INPUT_CHARS} chars)`,
);
}
const { kept, dropped } = capFilesToBudget(

If a non-retryable error class is preferred over TypeError, the check can move inside capFilesToBudget after the drop loop instead, but it needs to be explicit rather than silently over-budget.

Comment thread apps/labeler/src/code-ai-adapter.ts Outdated
remaining -= costOf(file);
}
return {
kept: files.filter((file) => !droppedPaths.has(file.path)),

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] Dropping files by file.path means a bundle with two different files sharing the same path drops both when only one exceeded the budget. The cost map keys by CodeAnalysisFile identity, but the drop set keys by path, so accounting and actual keeps/drops can diverge and droppedFiles becomes ambiguous.

Track dropped file objects (or dedupe paths first) instead of collapsing by path:

Suggested change
kept: files.filter((file) => !droppedPaths.has(file.path)),
const droppedFiles = new Set<CodeAnalysisFile>();
for (const file of largestFirst) {
if (remaining <= maxChars) break;
droppedFiles.add(file);
remaining -= costOf(file);
}
return {
kept: files.filter((file) => !droppedFiles.has(file)),
dropped: files.filter((file) => droppedFiles.has(file)).map((file) => file.path),
};

@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
…ntity

Publisher-controlled metadata is never dropped by the budget cap, so a
hostile blob could exceed the model input budget on its own and surface
as an endlessly-retried ModelTransientError. Fail fast with a
non-retryable error instead. Also drop over-budget files by object
identity rather than path, so duplicate-path bundles don't over-drop.
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/approved Approved; no new commits since labels Jul 13, 2026
@ascorbic

Copy link
Copy Markdown
Member Author

Both addressed:

  • Metadata budget gap: capFilesToBudget now fails fast with a non-retryable TypeError when the fixed overhead (system prompt + metadata fence) alone exceeds MAX_MODEL_INPUT_CHARS — no amount of file-dropping fixes that, and retrying an oversized request can't succeed, so it must not surface as ModelTransientError. Test asserts the error class and that the model is never called.
  • Duplicate-path over-drop: dropping is now by object identity, not path; a bundle with two files at the same path keeps the small one when only the large one is over budget. Regression test included.

231 tests green. Re-triggering.

~ 🤖 Fable

@ascorbic ascorbic added bot:review Trigger an emdashbot code review on this PR and removed bot:review Trigger an emdashbot code review on this PR labels 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.

Approach is sound: this is a pure, injected-binding adapter for the W8.2 code/metadata AI stage, deliberately decoupled from the orchestrator and fully testable with a fake binding. It honors the W8.1 finding contract, derives its allowed-category enum from the versioned policy, and hardens untrusted input with a per-request fence/boundary design. The deferred wiring to a real codeAi consumer (W7.3) is the right scope call.

This is a re-review of PR #1994. I read the full diff, the new source module, its tests, and the updated apps/labeler/worker-configuration.d.ts/wrangler binding. The prior blocking issue is closed: capFilesToBudget now budgets the metadata fence as part of fixedOverheadChars, rejects publisher-only oversize as a non-retryable TypeError, and drops files by object identity (verified by a new test that keeps a smaller file sharing a duplicate path). I also traced the assembled-prompt accounting and it exactly matches the buildUserContent join separators for any kept-file count.

No remaining AGENTS.md violations: the module uses .js internal imports and import type, touches no SQL/admin UI/migrations, and lives in an unpublished private app so no changeset is required. No security, contract, type, or test gaps remain. No findings.

@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 merged commit c4a2cae into feat/plugin-registry-labelling-service Jul 13, 2026
9 of 10 checks passed
@ascorbic
ascorbic deleted the feat/labeler-code-ai-adapter branch July 13, 2026 06:17
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