Repository navigation
Conversation
|
Scope checkThis 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. |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | 1716fa9 | Jul 13 2026, 06:15 AM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | 1716fa9 | Jul 13 2026, 06:17 AM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | 1716fa9 | Jul 13 2026, 06:17 AM |
There was a problem hiding this comment.
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.
| const renderedCost = (file: CodeAnalysisFile) => buildFence(file, boundary).length + 1; | ||
| const total = files.reduce((sum, file) => sum + renderedCost(file), fixedOverheadChars); |
There was a problem hiding this comment.
[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.
| 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.
|
Fixed the budget undercount you flagged. (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 |
There was a problem hiding this comment.
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:
fixedOverheadCharscoverssystemPrompt.length + metadataFence.length + 1.- Each rendered file fence is counted as
buildFence(file, boundary).length + 2. - For
Nfiles, the code budgets for2N + 1newline separators, which is exactly whatbuildUserContentproduces 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.
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.
dcae42c to
6f77950
Compare
|
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 |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
[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:
| 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.
| remaining -= costOf(file); | ||
| } | ||
| return { | ||
| kept: files.filter((file) => !droppedPaths.has(file.path)), |
There was a problem hiding this comment.
[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:
| 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), | |
| }; |
…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.
|
Both addressed:
231 tests green. Re-triggering. ~ 🤖 Fable |
There was a problem hiding this comment.
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.
c4a2cae
into
feat/plugin-registry-labelling-service
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 validatedNormalizedFinding[](source"model"), feeding the W8.5 policy resolver.AIbinding is injected viadeps; the module does no DB writes and imports nothing fromcloudflare:workers, so it's fully testable against a fake binding and decoupled from the orchestrator's still-abstractStageContext. Wiring it into thecodeAistage — threading the acquired bundle and recording evidence objects — is deferred to the W7.3-consumer work once a real bundle-input producer exists.response_format: json_schemaconstrains each finding'scategoryto exactly the policy's allowed set (automated-block ∪ warning) andseverity/confidenceto their ranges. The enum is derived from the versioned policy, not hardcoded.coverage: "partial"with the dropped paths — it never truncates silently.ModelTransientError(retryable) — a flaky model is not the non-retryable stage-adapter bug aFindingValidationErrorsignals. Model-suppliedsource/evidenceRefs/sourceMetadataare overridden so a model can't spoof provenance. A blankpromptVersionis a caller bug and throws up front (not retried).No migration, no lexicon change, no public-API change. Adds the
AIbinding toapps/labeler/wrangler.jsonc(regeneratedworker-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
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.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
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)pnpm lint:jsondiagnostics unchanged at 19 (0 inapps/labeler)AiBindingonly — 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.