Repository navigation
feat(labeler): reviewer label issue/retract actions (W9.4) - #2020
Conversation
POST /admin/api/labels/issue and /retract behind the mutation guard, signing a manual label whose prepared statements commit atomically with the operator audit row. Retract is manual negation. Adds server-derived effect preview, /whoami, a server-validated typed confirmation, and the console action dialog. Policy fixture grants reviewers issuance on descriptive release labels. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
…e audit commits A signing-key rotation between the pre-check and the batch can commit the operator_actions audit row while both guarded issuance INSERTs match zero rows, yielding a phantom "issued" 200 with no label. Read the label back by action id after commit and surface LABEL_ISSUANCE_UNAVAILABLE (503, retryable) when it's absent. Paused/stale signing on the console path now returns the same retryable error instead of a generic 500. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
|
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | 23d0a90 | Jul 13 2026, 04:26 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | 23d0a90 | Jul 13 2026, 04:25 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | 23d0a90 | Jul 13 2026, 04:25 PM |
Scope checkThis PR changes 2,203 lines across 17 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. |
There was a problem hiding this comment.
Approach judgment
This is the right change for the right problem, and it fits EmDash's labeler architecture well. Reusing buildIssuanceStatements + commitMutation so the signed issued_labels INSERTs and the operator_actions audit row commit in one atomic db.batch is the correct way to get effect/audit atomicity without a refactor. The design choices are sound and consistent with W9.2–W9.3: policy-driven vocabulary/scope validation mirroring the automated path, server-validated typed confirmation folded into the fingerprint, a write-free server-derived effect preview grounded in the same evaluator official clients use, whoami roles provably cosmetic with guardMutation as the enforcement boundary, and the §10 automated-negation-proof property preserved (retraction is a manual negation). The 503 "no phantom success" fix for the in-batch suppression race is a real, well-targeted improvement — but it has a gap (see finding 1).
What I checked
- Traced
runLabelMutation→guardMutation→commitMutation→ post-commit read-back for both the proceed, replay, and concurrent-key-conflict paths. - Verified
assertW94Issuable/assertConfirmation/validateManualProposalagree (noTypeErrorcan escapeprepareManualLabelIssuancefor anything that passed the W9.4 gate) and that the §10 in-batch guard still binds. - Verified the effect preview is read-only and that
context.release/acceptedLabelersmatch the official evaluator'sappliesToContextsemantics for release subjects (no drift for release-level labels; package/publisher previews correctly reportnull). - Verified authorization: every read (
whoami,effect-preview) and mutation runs the full guard with a freshly verified identity; admin satisfies reviewer by inheritance and is audited asadmin. - Verified no CORS headers are emitted,
D1PreparedStatement[]are parameterized (no interpolation), andafterCommitpublish is correctly keyed on the caller's own action id (race-loser skips).
Headline conclusion
One real integrity bug: the 503 "no phantom success" guarantee is defeated on retry because the guard's replay path returns the stored "success" descriptor for an action whose label was suppressed. Two smaller UX gaps on the AssessmentDetail integration (retract offered for labels the endpoint can't retract; issued manual labels don't surface in the list the issue button sits above). None of these are security/authorization holes; the signing path is otherwise solid.
| now: deps.now, | ||
| }; | ||
| const outcome = await guardMutation(request, spec, guardDeps); | ||
| if (outcome.outcome === "replay") return jsonData(outcome.result); |
There was a problem hiding this comment.
[needs fixing] The 503 "no phantom success" fix is defeated on retry. When a signing-key rotation races between the signing pre-check and the batch, the guarded issued_labels INSERTs match zero rows (a non-error in SQLite) while the unguarded operator_actions audit row commits — carrying result_json = the success descriptor. runLabelMutation's post-commit readIssuedLabelByActionKey then (correctly) throws LabelIssuanceUnavailableError → 503 for the first request. But the audit row is already committed with the success descriptor.
The console's stated model is that the idempotency key is "minted per open and reused across retries" and 503 is "retryable." So the operator clicks Submit again with the same idempotency key. guardMutation finds the prior audit row, the fingerprint (which includes confirmation + reason) matches, and the replay short-circuit here returns jsonData(outcome.result) — the stored success descriptor — as a 200, even though no label was ever persisted. A security-yanked the operator believes is in force was silently dropped, and both the API response and the audit log claim success. This is exactly the phantom-success failure the PR says it prevents, just deferred to the retry; the existing 503 test only drives the first request.
The replay path needs the same post-commit verification the proceed path has — a suppressed action should replay as 503, not as the stale success descriptor:
| if (outcome.outcome === "replay") return jsonData(outcome.result); | |
| if (outcome.outcome === "replay") { | |
| if (!(await readIssuedLabelByActionKey(deps.db, outcome.actionId))) | |
| throw new LabelIssuanceUnavailableError("label issuance did not persist"); | |
| return jsonData(outcome.result); | |
| } |
There was a problem hiding this comment.
Fixed in 23d0a90 — you were right, this was a real hole. The post-commit label read-back only ran on the proceed path; a same-key retry hit the guard's replay branch and returned the stored success descriptor as a 200. Both paths now call one assertIssuancePersisted(db, actionId) helper (keyed on the outcome's actionId), so a suppressed issuance returns 503 on the first call AND every replay. The suppression test now issues a second same-key call and asserts it also 503s (and that the replay wrote nothing); verified it fails (200≠503) without the replay-path check.
~ 🤖 Fable
| <div key={`${label.val}-${label.sequence}`} className="flex items-center gap-1"> | ||
| <Badge variant={label.neg ? "neutral" : "info"}>{label.val}</Badge> | ||
| {canAct && !label.neg && ( |
There was a problem hiding this comment.
[suggestion] The retract button is rendered for every non-negated label in the assessment's label list, but the list (getAllLabelsForAssessment) contains the automated assessment's eligibility labels — assessment-passed, assessment-overridden (override-coupled), and assessment-pending / assessment-error (automated-only). All four are rejected by assertW94Issuable on the retract endpoint: the override-coupled pair throws INVALID_BODY at the OVERRIDE_COUPLED check, and the automated-only pair has no reviewer issuance mode. So an operator who clicks "Retract" on an "Assessment passed" badge opens the ceremony, types the confirmation, and gets a generic 400 Request body is invalid with no explanation. The descriptive block/warning vocabulary (malware, security-yanked, …) does retract correctly.
Gate the button on labels the endpoint can actually retract — e.g. skip the override-coupled and automated-only-state values (or only offer retract for values present in RELEASE_ISSUABLE_LABELS), so the UI never offers an action that always 400s.
There was a problem hiding this comment.
Fixed in 23d0a90 — the retract button is now gated by isReleaseRetractable(val) (the same reviewer-issuable release set the issue menu is built from, mirroring the server allow-set), so it no longer renders for the eligibility labels the retract endpoint rejects.
~ 🤖 Fable
| <LabelActionDialog | ||
| open={issueOpen} | ||
| onOpenChange={setIssueOpen} | ||
| mode="issue" | ||
| subjectUri={assessment.uri} | ||
| subjectCid={assessment.cid} | ||
| issuable={RELEASE_ISSUABLE_LABELS} | ||
| invalidateKeys={[ | ||
| ["assessment", id, "labels"], |
There was a problem hiding this comment.
[suggestion] Issuing a manual label from this page does not surface in the "Labels" section below the button. listLabels(id) → getAllLabelsForAssessment filters WHERE a.assessment_id = ?, and console-issued labels are manual-label actions with assessment_id = NULL, so they are excluded. The invalidateKeys={["assessment", id, "labels"], ["assessment", id]} refresh implies the new label should appear, but it never will here — the operator gets a success/closed dialog and a label list that looks unchanged, and must navigate to Subject history to confirm the label landed.
If the assessment-detail labels list is intentionally only the assessment's own automated output, consider not invalidating ["assessment", id, "labels"] here (avoid implying it'll show) and/or surface a confirmation that points the operator at Subject history; otherwise widen the labels read to include manual labels for the assessment's (uri, cid).
There was a problem hiding this comment.
Confirmed and tracked as a follow-up rather than fixed here: manual labels carry assessment_id NULL (keyed to subject URI+CID), so getAllLabelsForAssessment legitimately can't show them — the label is correctly issued and audited, only its display is missing. A correct fix needs a new subject+CID label read (GET /admin/api/subjects/:uri/labels, wrapping getActiveLabelState) plus a merge-semantics decision, and W9.5's override/rerun needs that same subject-label read — so it's folded into W9.5 (recorded in the plan, d9c458d). I kept the dialog's invalidate rather than stripping it, since removing it without a replacement display would give a successful issuance zero feedback.
~ 🤖 Fable
…ccess The post-commit label read-back only ran on the proceed path, so a retry with the same idempotency key replayed the stored success descriptor as a 200 even when the label was suppressed. Both paths now share one assertIssuancePersisted helper. Also gates the retract button to labels the endpoint can actually retract. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
There was a problem hiding this comment.
Re-review (W9.4 reviewer label issue/retract actions)
The approach remains the right one, and this revision closes the integrity bug from the prior review.
Status of prior findings
-
Phantom-success-on-retry (was
needs_fixing) — FIXED.runLabelMutationnow runsassertIssuancePersistedon both the proceed path (returned.actionId) and the guard's replay path (outcome.actionId). Because the signing-layer idempotency key is deliberately set toctx.actionId,operator_actions.idandissuance_actions.idempotency_keyare the same string, so the read-back is consistent across both paths. The new test drives the in-batch suppression (suppressIssuanceDbcommits only the audit INSERT), asserts the first request returns 503 with no label, then retries with the same idempotency key against a plain DB and asserts the replay also returns 503 (not the stored "success" descriptor) while writing nothing. This is exactly the gap I raised; it's now covered end-to-end. -
Retract offered for labels the endpoint can't retract (was
suggestion) — ADDRESSED. The retract button now gates onisReleaseRetractable(label.val), which mirrors the server's reviewer-issuable allow-set (RELEASE_SCOPES), so eligibility labels (assessment-passed/overridden/pending/error) no longer get a retract button. -
Issued manual labels don't surface in the list the issue button sits above (was
suggestion) — STILL OPEN. See the one finding below. The diff didn't touchgetAllLabelsForAssessmentor the invalidation set, so a reviewer-issued manual label still doesn't render on the AssessmentDetail Labels section after a successful issue.
What I re-checked on this pass
runLabelMutationproceed, replay, andcommitMutationconflict paths: the race-loser'safterCommitis keyed on its own rolled-backactionId(reads nothing, skips), whileassertIssuancePersistedon the conflict path keys on the winner's storedactionId(label present) — correct, no double-publish and no false 503 on a legitimate concurrent win.assertW94Issuable/assertConfirmation/validateManualProposalstill agree: nothing that passes the W9.4 gate can throw aTypeErrorout ofprepareManualLabelIssuance(admin-only labels lack areviewermode and are rejected at 400;cidRule: optionalforpackage-disputedis handled by neither the forbidden nor required branch).- Routing: POST →
handleConsoleMutation(onlylabels/{issue,retract}; everything elseNOT_FOUND404), GET →handleConsoleApi(whoami,labels/effect-preview);effect-previewisrequireGetand read-guarded,whoamireturns only the verified identity, no CORS headers emitted. - Effect preview remains read-only and grounded in the same
evaluateHydratedReleaseModerationevaluator official clients use;before/aftercorrectly gonullfor non-release/unresolvable subjects; the test assertsaftermatches a direct evaluator call (no drift). LabelIssuanceUnavailableError(paused/stale/suppressed) consistently surfaces as 503;LabelMutationError(confirmation) as 400 with a static message that never echoes the confirmation value.apps/labeleris"private": truev0.0.0, so no changeset is required; the console is deliberately non-localized per the W9.3 decision — no AGENTS.md i18n/changeset violations.
Headline
No new correctness, authorization, or integrity bugs. The signing/audit atomicity and the no-phantom-success guarantee are now solid on every path. One non-blocking UX gap from the prior review is still open.
| invalidateKeys={[ | ||
| ["assessment", id, "labels"], | ||
| ["assessment", id], | ||
| ]} |
There was a problem hiding this comment.
[suggestion] The issue dialog invalidates ["assessment", id, "labels"] and ["assessment", id], but the Labels list it sits above (apiClient.listLabels(id) → getAllLabelsForAssessment) filters WHERE a.assessment_id = ?. A reviewer-issued manual label is written as an issuance_actions row with assessment_id = NULL (see buildIssuanceStatements: assessmentId = action.type === "automated-assessment" ? action.assessmentId : null), so it is excluded from that list. After a successful issue the dialog closes, the Labels section refetches to the same contents, and the audit log isn't in invalidateKeys either — the operator gets no on-page confirmation the label landed. The same applies in reverse to a manual retract of an automated label: the neg event has assessment_id = NULL, so the badge keeps showing as active here.
This is the same gap flagged in the prior review; it's still open. Options: surface subject-level (URI-scoped) manual labels on this view via a labels-by-URI read, add the audit-log query key to invalidateKeys, or show a success toast on onSuccess.
There was a problem hiding this comment.
Tracked, not fixed here (see the prior thread): manual labels are subject-keyed with assessment_id NULL, so the assessment-scoped read can't surface them — the correct fix is a new subject+CID label read that W9.5's override/rerun needs anyway, folded into W9.5 (plan commit d9c458d). The label is issued and audited correctly; only its display on this page is deferred.
~ 🤖 Fable
a3e7a3e
into
feat/plugin-registry-labelling-service
What does this PR do?
Adds plan item W9.4 — the operator console's first mutation endpoints: reviewers issue and retract moderation labels through the W9.2 mutation guard.
POST /admin/api/labels/issueandPOST /admin/api/labels/retractsign a manual label and commit its rows atomically with the operator audit row in a singlecommitMutationbatch; retract is a manual negation (neg: true) through the same path.The signing path needed no refactor:
buildIssuanceStatementsalready returns bareD1PreparedStatement[]split from the batch run, so the newprepareManualLabelIssuance(validation + statement build) hands those statements straight tocommitMutationas itseffect. Publication is deferred post-commit, keyed on the action id so a concurrent race-loser cleanly skips.Guarding and correctness:
X-EmDash-Request, a freshly verified Access identity, reviewer role) before any signing. Roles are re-derived server-side from the verified JWT —/whoami(new read) is used only to cosmetically gate console buttons.validateManualProposal(generalized from the old hardcoded arms, mirroring the automated path) enforces the label'ssubjectRule/cidRule; an automated-only label or a scope mismatch is rejected at 400 before signing. Per the ratified policy edit, reviewers may issue descriptive release labels (fixture bumped to2026-07-10.experimental.3); a reviewer-issued label is human-retract-only (§10 — automation can never negate it).GET /admin/api/labels/effect-preview) is server-derived from the aggregator evaluator overlaying the proposed event — the console holds zero policy logic, so official-client effect can't drift from what would actually happen.LABEL_ISSUANCE_UNAVAILABLE(503, retryable) instead of a 200 that falsely claims a release is blocked. Paused/stale signing on this path now returns the same retryable error rather than a generic 500.Console: action buttons + a Kumo dialog on assessment detail and subject history, with the typed-confirmation input, the effect preview, client-generated ULID idempotency keys, and 409/503 surfaced as retryable errors. Plain English strings (the console is not localized, per the W9.3 decision).
Reviewed by an independent Opus adversarial pass: confirmed no unauthenticated/under-privileged signing path,
whoamiroles provably cosmetic, vocabulary/scope non-escapable via the widenedval, the §10 automated-negation-proof property (tested end to end), deterministic replay, and a pure (write-free) effect preview. Its one finding — the audit-without-label phantom success — is the 503 fix above, with a test that drives the exact suppressed state and fails without the fix.Stacked directly on the integration branch (W9.1–W9.3 merged). 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.i18n n/a — no admin UI; the labeler console is deliberately not localized. Changeset n/a —
apps/labeleris a private, unpublished Worker app; the policy fixture it bundles is internal.AI-generated code disclosure
Screenshots / test output
pnpm --filter @emdash-cms/labeler test: worker 443 pass (25 files — newconsole-mutation-apisuite covers the guard integration, effect+audit atomicity, retract/negation, vocabulary/scope rejection, confirmation mismatch, replay returning the stored descriptor, effect preview, whoami, and the 503 suppression path), console 14 passconsole:buildsucceeds; lint: 0 diagnostics inapps/labelerhttps://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
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-label-actions. Updated automatically when the playground redeploys.