Skip to content

feat(labeler): model calibration harness and OpenAI envelope support (W8.6) - #2058

Merged
ascorbic merged 5 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-calibration-harness
Jul 15, 2026
Merged

ascorbic merged 5 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-calibration-harness

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

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/analyzeImages with their real prompts, response schemas, and live policy) over the ported legacy audit corpus (13 fixtures from packages/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 REST AiBinding (wrangler auth token; token never logged or persisted, artifacts contain no credentials — adversary-grepped). Each result resolves through resolvePolicyOutcome; 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:report scripts live outside the test CI 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 of pnpm 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)

parseModelOutput in 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 shared unwrapModelEnvelope reduces 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, and validateFindings gates everything unchanged. TDD: failing tests with the live-observed envelope shape first; existing {response} tests untouched. The harness binding returns the REST result verbatim, 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_schema and returns prose.

Findings feeding the ratified follow-up (separate PR, already ratified in the plan)

  • Severity gate: models rate real malware high where the resolver blocks only critical (data-exfiltration false negative) → ≥high blocks + sub-high block-category findings degrade to a warning, never dropped.
  • Systemic over-warning: no model ever returns passed on clean code (19 over-warns per run — the new tally the FP=0 count was hiding) → prompt/threshold work.
  • Policy gap: no image-content categories exist (hate-imagery cannot be blocked) → hateful-imagery/explicit-imagery/graphic-violence additions.

Type of change

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)
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8 (implementation + two adversarial review passes; orchestrated via Claude Code)

Screenshots / test output

 Test Files  33 passed | 11 passed | 5 passed
      Tests  561 + 98 + 32 = 691 passed

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.

ascorbic added 2 commits July 15, 2026 13:37
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
@changeset-bot

changeset-bot Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: ee36ec4

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 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Scope check

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

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 15, 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 ee36ec4 Jul 15 2026, 01:26 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 15, 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 ee36ec4 Jul 15 2026, 01:26 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 15, 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 ee36ec4 Jul 15 2026, 01:26 PM

@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 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:106

    The image adapter reuses the code adapter’s DEFAULT_MODEL_ID, which this PR changed to @cf/zai-org/glm-5.2. The calibration matrix in apps/labeler/calibration/models.ts deliberately limits that model to the "code" lane, so an analyzeImages caller that omits modelId will 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_ID backed by one of the image-lane models the harness already validates, or make modelId required for analyzeImages so 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-343

    parseModelOutput is now identical to the one in code-ai-adapter.ts except for the shared unwrapModelEnvelope call. Since the PR’s stated goal is to keep the two adapters from drifting, consider exporting parseModelOutput (and the small isRecord / hashPromptText helpers) from code-ai-adapter.ts and deleting this local copy, so a future envelope change only has one place to land.

@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 15, 2026
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
@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 15, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 15, 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 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.

Comment on lines +73 to +77
export function createRunDir(timestamp: string, label: string): string {
const runDir = join(RUNS_DIR, `${timestamp.replaceAll(":", "-")}-${label}`);
mkdirSync(runDir, { recursive: true });
return runDir;
}

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] 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/.

Suggested change
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;
}

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 15, 2026
@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-rereview New commits since the last review labels Jul 15, 2026
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
@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 15, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 15, 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 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 {

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

Suggested change
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[];
}

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 15, 2026
@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-rereview New commits since the last review labels Jul 15, 2026
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
@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 15, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 15, 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 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 → parseModelOutput path in both adapters,
  • the new DEFAULT_IMAGE_MODEL_ID and updated DEFAULT_MODEL_ID,
  • the calibration I/O guards, runner orchestration, REST AiBinding, and report rendering,
  • package.json/vitest.config.ts wiring,
  • 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.

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 15, 2026
@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 15, 2026
@ascorbic
ascorbic merged commit 3eefd12 into feat/plugin-registry-labelling-service Jul 15, 2026
11 checks passed
@ascorbic
ascorbic deleted the feat/labeler-calibration-harness branch July 15, 2026 13:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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