Repository navigation
feat(labeler): model calibration harness and OpenAI envelope support (W8.6) - #2058
Conversation
The code/image AI adapters expected only the classic Workers AI
`{response}` envelope, but the OpenAI-compatible chat models they target
(moonshot/kimi, zai/glm) return `{choices:[{message:{content}}]}` — as
written the adapters could parse none of their output. Add a shared
`unwrapModelEnvelope` that reduces the chat envelope to the content
string (discarding `reasoning_content`) before the existing parse path;
non-string content falls through to the existing error handling and
`validateFindings` gates everything unchanged.
Switch `DEFAULT_MODEL_ID` to `@cf/zai-org/glm-5.2`: in the first
calibration sweep it was the only zero-error code model, ~3x faster
than kimi-k2.7-code, and blocked more of the malware corpus.
Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
Local harness that runs the production code/image AI adapters — their real prompts, response schemas, and policy — over the ported legacy audit corpus (13 fixtures) against live Workers AI models via a REST `AiBinding`, resolves each result through `resolvePolicyOutcome`, and records per-call artifacts for review. A report entrypoint renders the fixture-by-model outcome matrix, per-model agreement/false-positive/ false-negative/over-warn tallies, and newly-blocked/newly-allowed diffs between runs. Runs execute via `calibrate`/`calibrate:report` scripts outside the `test` CI gate (real inference is non-deterministic and billed); run artifacts are gitignored review material. The 32 calibration unit tests (fixture loading, expectation mapping, report diffing, envelope handling) run in a node-env stage of `pnpm test`. The runner writes its manifest incrementally so an interrupted sweep stays loadable, and orders models slowest-first so a late kill loses the cheapest calls. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
|
Scope checkThis PR changes 2,103 lines across 67 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-cache | ee36ec4 | Jul 15 2026, 01:26 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | ee36ec4 | Jul 15 2026, 01:26 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | ee36ec4 | Jul 15 2026, 01:26 PM |
There was a problem hiding this comment.
Approach judgment: this is the right change for W8.6. The calibration harness exercises the real adapters and policy resolver against live Workers AI models, the OpenAI-compatible envelope unblocking is a genuine production gap the harness found, and the model switch to glm-5.2 is data-driven. The diff is careful about credentials, path traversal, fixture malware not being executed, and keeping billed sweep entrypoints outside of pnpm test.
I read the full diff, the adapter source/tests, the calibration runner/report/REST binding, fixture mapping, and the relevant AGENTS.md conventions. I checked for SQL injection / locale filter issues (none — this is an AI pipeline, no DB queries added), Lingui/Tailwind regressions (none — no admin UI), authorization changes (none), index/migration changes (none), and changesets (not required — @emdash-cms/labeler is private). The code is generally well tested and defensive.
Headline conclusion: one latent regression worth fixing before this merges — the image adapter still falls back to the code adapter’s DEFAULT_MODEL_ID, which is now @cf/zai-org/glm-5.2. That model is intentionally limited to the code lane in the calibration matrix, so analyzeImages called without an explicit modelId would silently send images to a non-image model. The previous default (@cf/moonshotai/kimi-k2.7-code) was at least exercised in the image lane. I also have a minor suggestion to share the duplicated parseModelOutput implementation across adapters, but that is not blocking.
Findings
-
[needs fixing]
apps/labeler/src/image-ai-adapter.ts:106The image adapter reuses the code adapter’s
DEFAULT_MODEL_ID, which this PR changed to@cf/zai-org/glm-5.2. The calibration matrix inapps/labeler/calibration/models.tsdeliberately limits that model to the"code"lane, so ananalyzeImagescaller that omitsmodelIdwill now default to a model that is not part of the validated image set. This is a broken contract / latent regression for the image path.Either add a dedicated
DEFAULT_IMAGE_MODEL_IDbacked by one of the image-lane models the harness already validates, or makemodelIdrequired foranalyzeImagesso there is no silent wrong default.import { DEFAULT_MODEL_ID as DEFAULT_CODE_MODEL_ID, escapeFenceSentinel, FENCE_SENTINEL, MAX_MODEL_INPUT_CHARS, ModelTransientError, unwrapModelEnvelope, type CodeAnalysisMetadata, } from "./code-ai-adapter.js"; const DEFAULT_IMAGE_MODEL_ID = "@cf/moonshotai/kimi-k2.7-code";and at line 106:
const modelId = deps.modelId ?? DEFAULT_IMAGE_MODEL_ID; -
[suggestion]
apps/labeler/src/image-ai-adapter.ts:326-343parseModelOutputis now identical to the one incode-ai-adapter.tsexcept for the sharedunwrapModelEnvelopecall. Since the PR’s stated goal is to keep the two adapters from drifting, consider exportingparseModelOutput(and the smallisRecord/hashPromptTexthelpers) fromcode-ai-adapter.tsand deleting this local copy, so a future envelope change only has one place to land.
analyzeImages fell back to the code adapter's DEFAULT_MODEL_ID, now the text-only glm-5.2, so an image caller that omitted modelId got a model that cannot see images. Add DEFAULT_IMAGE_MODEL_ID (kimi-k2.7-code, the only reliable image model in the W8.6 sweep) and use it as the fallback. Export parseModelOutput from code-ai-adapter.ts and drop the image adapter's identical local copy so a future envelope change lands in one place. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
There was a problem hiding this comment.
Approach judgment: This remains the right change for W8.6. The calibration harness exercises the real adapters and policy resolver against live Workers AI, the OpenAI-compatible envelope unblocking is a genuine production gap the harness found, and the model switch to glm-5.2 is data-driven. The diff is careful about credentials and fixture safety.
What changed since the last review: The prior needs_fixing issue is resolved. apps/labeler/src/image-ai-adapter.ts now declares its own vision-capable DEFAULT_IMAGE_MODEL_ID (@cf/moonshotai/kimi-k2.7-code) instead of inheriting the code adapter's text-only default, and the duplicated parseModelOutput implementation has been removed in favor of the shared, exported function from code-ai-adapter.ts. Both fixes are covered by new tests.
What I checked: I re-read the full diff and the updated adapters, calibration IO/runner/report, REST binding, fixture loader, and test additions. I also checked the PR against AGENTS.md conventions: no changeset is required (@emdash-cms/labeler is private and at 0.0.0), there are no admin UI strings needing Lingui or RTL-safe Tailwind, and there are no DB queries, migrations, indexes, or authorization changes.
Headline conclusion: The prior blockers are fixed, but a new path-traversal gap remains in the calibration harness. createRunDir builds the run directory from the operator-supplied CALIBRATE_LABEL without sanitization or a containment check, so a label containing .. can direct the billed artifacts outside the intended runs/ tree. It should be fixed and covered by a repro I/O test before merge.
| export function createRunDir(timestamp: string, label: string): string { | ||
| const runDir = join(RUNS_DIR, `${timestamp.replaceAll(":", "-")}-${label}`); | ||
| mkdirSync(runDir, { recursive: true }); | ||
| return runDir; | ||
| } |
There was a problem hiding this comment.
[needs fixing] createRunDir builds the run directory under runs/ by joining RUNS_DIR with ${timestamp}-${label} (line 74). The label comes directly from the operator's CALIBRATE_LABEL environment variable without validation or sanitization. Because path.join normalizes .. segments, a label such as ../../tmp/calibrate will create directories outside the intended runs/ tree, and a label starting with / resets the joined path entirely. The harness is otherwise adversarial-review-conscious about credentials and path safety, so this is an inconsistent gap.
Either reject labels containing path separators or parent references, or resolve the final path and verify it stays inside RUNS_DIR (add resolve and sep to the node:path import). Add a unit test in io.test.ts covering a label that attempts to escape runs/.
| export function createRunDir(timestamp: string, label: string): string { | |
| const runDir = join(RUNS_DIR, `${timestamp.replaceAll(":", "-")}-${label}`); | |
| mkdirSync(runDir, { recursive: true }); | |
| return runDir; | |
| } | |
| export function createRunDir(timestamp: string, label: string): string { | |
| const runDir = join(RUNS_DIR, `${timestamp.replaceAll(":", "-")}-${label}`); | |
| const resolved = resolve(runDir); | |
| const resolvedRuns = resolve(RUNS_DIR); | |
| if (!resolved.startsWith(resolvedRuns + sep)) | |
| throw new TypeError( | |
| `calibration: CALIBRATE_LABEL would create a run dir outside runs/: ${runDir}`, | |
| ); | |
| mkdirSync(runDir, { recursive: true }); | |
| return runDir; | |
| } |
createRunDir joined the operator-supplied CALIBRATE_LABEL into the run path unsanitized, so a label like '../../tmp/x' escaped runs/. Validate the label against a strict pattern (alphanumeric start; alphanumerics, '.', '-', '_'; 64-char cap) and reject otherwise, plus a containment assertion that the resolved dir stays under RUNS_DIR as defense-in-depth. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
There was a problem hiding this comment.
Approach judgment: This remains the right change for W8.6. The calibration harness exercises the real production adapters and policy resolver against live Workers AI, which matches the stated plan. The OpenAI-compatible envelope unblocking is a genuine latent gap the harness surfaced, and switching the default code model to @cf/zai-org/glm-5.2 is data-driven. There are no DB, auth, admin-UI, or schema changes — only the private @emdash-cms/labeler app and its tests.
What I checked: I re-read the full diff and focused on the calibration I/O, runner orchestration, report rendering, REST AiBinding, the shared unwrapModelOutput/parseModelOutput, the image adapter's new DEFAULT_IMAGE_MODEL_ID, package.json/vitest.config.ts wiring, and the new tests. I also re-verified that the prior createRunDir path-traversal issue from the previous review is fixed.
Headline conclusion: The prior blocker is resolved. CALIBRATE_LABEL is now pattern-validated (no /, .., leading dot, or absolute path) and further protected by a containment assertion, with repro I/O tests covering traversal/separator/absolute/leading-dot cases. I found no new security issues, logic bugs, regressions, or AGENTS.md violations. (Unit-test coverage is present for I/O, fixture parsing, expectation mapping, report rendering, and REST binding; I did not re-run the suite.) This is essentially clean, with one minor suggestion about what goes into the recorded artifact.
| readonly severity?: string; | ||
| } | ||
|
|
||
| export interface RecordedFinding { |
There was a problem hiding this comment.
[suggestion] The RecordedFinding shape keeps source/category/severity/title/summaries, but it drops affectedFiles and affectedImages from the validated NormalizedFinding. Since the calibration artifact is meant to be reviewed when a fixture changes state, losing the file/image evidence makes it harder to triage false positives/negatives. Extend the recorded shape to preserve the optional lists, and update recordFindings in run.ts to thread them through.
| export interface RecordedFinding { | |
| export interface RecordedFinding { | |
| readonly source: string; | |
| readonly category: string; | |
| readonly severity: string; | |
| readonly confidence?: number; | |
| readonly title: string; | |
| readonly publicSummary: string; | |
| readonly privateDetail: string; | |
| readonly affectedFiles?: readonly string[]; | |
| readonly affectedImages?: readonly string[]; | |
| } |
RecordedFinding dropped the validated finding's optional affectedFiles/affectedImages, so a run artifact couldn't show which files or images a finding cited — harder to triage a state change from artifacts alone. Thread both optional lists through recordFindings into the recorded shape. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
There was a problem hiding this comment.
Approach judgment
This PR remains the right change for the W8.6 calibration workstream. The harness runs the real production adapters and policy resolver against live Workers AI, the OpenAI-compatible envelope unblocking is a genuine latent gap it surfaced, and the default-code-model switch to @cf/zai-org/glm-5.2 is data-driven. It touches only the private @emdash-cms/labeler app and tests — no DB, auth, admin UI, schema, or published-package surface area.
What changed since the prior review
The prior blocker is cleanly fixed. CALIBRATE_LABEL is now validated against a strict pattern (/[a-z0-9][a-z0-9._-]*/i, no /, .., leading dot, or absolute path) and further protected by a resolved-path containment assertion in createRunDir, with repro I/O tests covering traversal/separator/absolute/leading-dot cases.
What I checked
I re-read the full diff and focused on:
- the shared
unwrapModelEnvelope→parseModelOutputpath in both adapters, - the new
DEFAULT_IMAGE_MODEL_IDand updatedDEFAULT_MODEL_ID, - the calibration I/O guards, runner orchestration, REST
AiBinding, and report rendering, package.json/vitest.config.tswiring,- AGENTS.md conventions (no i18n/RTL/admin, no SQL, no auth, no published-package changeset needed).
Headline conclusion
I found no new security issues, logic bugs, regressions, or AGENTS.md violations. The envelope handling correctly reduces the OpenAI chat shape before the existing {response} parse path and preserves all existing tests. The calibration runner keeps credentials out of artifacts, writes the manifest incrementally, and records model errors as data. Unit-test coverage is present for fixture loading, PNG parsing, expectation mapping, I/O guards, report diffing/summarization, envelope parsing, and REST binding diagnostics. I did not re-run the suite.
A previously noted minor suggestion about the recorded artifact is not visible as an unresolved defect in this revision; there are no further findings.
3eefd12
into
feat/plugin-registry-labelling-service
What does this PR do?
Implements W8.6 (calibration harness) for the labeler's AI moderation pipeline, plus the two production changes its first live runs motivated — all per the ratified W8.5/W8.6 decision paragraphs on the integration branch. Part of the plugin-registry labelling service (umbrella #1909, RFC #694).
The harness (
apps/labeler/calibration/)Runs the production adapters (
analyzeCode/analyzeImageswith their real prompts, response schemas, and live policy) over the ported legacy audit corpus (13 fixtures frompackages/marketplace/tests/fixtures/audit/, byte-identical malware/benign samples with expectations re-expressed in labeler terms as review priors) against live Workers AI models, via a RESTAiBinding(wrangler auth token; token never logged or persisted, artifacts contain no credentials — adversary-grepped). Each result resolves throughresolvePolicyOutcome; per-call JSON artifacts (outcome, findings, finish_reason, token usage, latency) land in gitignored run dirs, with an incrementally-written manifest so interrupted sweeps stay loadable. A report entrypoint renders the fixture×model outcome matrix, per-model agreement/FP/FN/over-warn tallies, and newly-blocked/newly-allowed diffs between runs — the plan's calibration report artifact.calibrate/calibrate:reportscripts live outside thetestCI gate (real inference, non-deterministic, billed). The 32 deterministic unit tests (fixture loading incl. PNG IHDR parsing, legacy→labeler expectation mapping, report diffing, envelope handling, run-dir IO guards) run in a node-env stage ofpnpm test. Fixture malware is only ever read as data — nothing imports or executes it (adversary-verified: no execution path exists).Production change 1: OpenAI chat-envelope support (found by the harness)
parseModelOutputin both adapters expected only the classic{response}envelope, but the OpenAI-compatible models they target return{choices:[{message:{content, reasoning_content?}}]}— as written the adapters could parse none of their default model's output (latent: they're test-only until W7/W8 wiring). A sharedunwrapModelEnvelopereduces the chat envelope to the content string before the existing parse path; non-string content (refusals, tool-calls, empty choices) falls through to existing error handling, andvalidateFindingsgates everything unchanged. TDD: failing tests with the live-observed envelope shape first; existing{response}tests untouched. The harness binding returns the RESTresultverbatim, so the eval exercises this exact production path (an earlier harness-side unwrap was removed for that reason after adversarial review).Production change 2: default model →
@cf/zai-org/glm-5.2(ratified from run data)Two full sweeps (48 calls each, three code models × 13 fixtures + three vision models × 3 image fixtures): glm-5.2 was the only zero-error code model, ~3× faster than kimi-k2.7-code (8.7s vs 28.8s mean), and blocked more of the malware corpus (credential-harvester, social-engineering, prompt-injection). kimi-k2.7-code under-blocked two real threats across runs and shares kimi-k2.6's invalid-structured-output flaw. kimi-k2.6 stays in the matrix as a detection-quality reference (best raw detection; not serving-viable at 61s mean + timeouts). llama-3.2-vision proved unusable for this design — it ignores
response_format: json_schemaand returns prose.Findings feeding the ratified follow-up (separate PR, already ratified in the plan)
highwhere the resolver blocks onlycritical(data-exfiltration false negative) → ≥high blocks + sub-high block-category findings degrade to a warning, never dropped.passedon clean code (19 over-warns per run — the new tally the FP=0 count was hiding) → prompt/threshold work.hateful-imagery/explicit-imagery/graphic-violenceadditions.Type of change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runAI-generated code disclosure
Screenshots / test output
Post-fixes sweep: 48/48 calls, per-model summary (code lane): glm-5.2 0 err / 8.7s mean, kimi-k2.7-code 1 err / 28.8s, kimi-k2.6 1 err / 61.4s; over-warn 6/6/6; FP 0; FN 2 (both severity-gate cases the ratified follow-up addresses).
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-calibration-harness. Updated automatically when the playground redeploys.