Skip to content

feat(labeler): reviewer label issue/retract actions (W9.4) - #2020

Merged
ascorbic merged 3 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-label-actions
Jul 13, 2026
Merged

ascorbic merged 3 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-label-actions

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

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/issue and POST /admin/api/labels/retract sign a manual label and commit its rows atomically with the operator audit row in a single commitMutation batch; retract is a manual negation (neg: true) through the same path.

The signing path needed no refactor: buildIssuanceStatements already returns bare D1PreparedStatement[] split from the batch run, so the new prepareManualLabelIssuance (validation + statement build) hands those statements straight to commitMutation as its effect. Publication is deferred post-commit, keyed on the action id so a concurrent race-loser cleanly skips.

Guarding and correctness:

  • Every request passes the full mutation guard (content-type, same-origin, 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.
  • Server-validated typed confirmation: the operator must retype the exact CID (CID-bound actions) or rkey (URI-wide), validated server-side and folded into the idempotency fingerprint (decision 2026-07-13).
  • Vocabulary and scope are policy-driven: validateManualProposal (generalized from the old hardcoded arms, mirroring the automated path) enforces the label's subjectRule/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 to 2026-07-10.experimental.3); a reviewer-issued label is human-retract-only (§10 — automation can never negate it).
  • Effect preview (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.
  • No phantom success: after commit, the handler reads the label back by action id; if a signing-key rotation raced between the pre-check and the batch such that the guarded issuance INSERTs matched zero rows (a non-error in SQLite) while the unguarded audit row committed, it returns 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, whoami roles provably cosmetic, vocabulary/scope non-escapable via the widened val, 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

  • 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

i18n n/a — no admin UI; the labeler console is deliberately not localized. Changeset n/a — apps/labeler is a private, unpublished Worker app; the policy fixture it bundles is internal.

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Code with Claude Fable 5 (coordination), Opus 4.8 subagents (design, implementation, adversarial review)

Screenshots / test output

  • pnpm --filter @emdash-cms/labeler test: worker 443 pass (25 files — new console-mutation-api suite 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 pass
  • Typecheck (both projects) clean; console:build succeeds; lint: 0 diagnostics in apps/labeler

https://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.

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

changeset-bot Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 23d0a90

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

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 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 23d0a90 Jul 13 2026, 04:26 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 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 23d0a90 Jul 13 2026, 04:25 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 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 23d0a90 Jul 13 2026, 04:25 PM

@github-actions

Copy link
Copy Markdown
Contributor

Scope check

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

@github-actions github-actions Bot added review/needs-review No maintainer or bot review yet cla: signed 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 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 / validateManualProposal agree (no TypeError can escape prepareManualLabelIssuance for 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/acceptedLabelers match the official evaluator's appliesToContext semantics for release subjects (no drift for release-level labels; package/publisher previews correctly report null).
  • 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 as admin.
  • Verified no CORS headers are emitted, D1PreparedStatement[] are parameterized (no interpolation), and afterCommit publish 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);

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

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +148 to +150
<div key={`${label.val}-${label.sequence}`} className="flex items-center gap-1">
<Badge variant={label.neg ? "neutral" : "info"}>{label.val}</Badge>
{canAct && !label.neg && (

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines +170 to +178
<LabelActionDialog
open={issueOpen}
onOpenChange={setIssueOpen}
mode="issue"
subjectUri={assessment.uri}
subjectCid={assessment.cid}
issuable={RELEASE_ISSUABLE_LABELS}
invalidateKeys={[
["assessment", id, "labels"],

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@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 13, 2026
…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
@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 13, 2026
@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.

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

  1. Phantom-success-on-retry (was needs_fixing) — FIXED. runLabelMutation now runs assertIssuancePersisted on both the proceed path (returned.actionId) and the guard's replay path (outcome.actionId). Because the signing-layer idempotency key is deliberately set to ctx.actionId, operator_actions.id and issuance_actions.idempotency_key are the same string, so the read-back is consistent across both paths. The new test drives the in-batch suppression (suppressIssuanceDb commits 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.

  2. Retract offered for labels the endpoint can't retract (was suggestion) — ADDRESSED. The retract button now gates on isReleaseRetractable(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.

  3. 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 touch getAllLabelsForAssessment or 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

  • runLabelMutation proceed, replay, and commitMutation conflict paths: the race-loser's afterCommit is keyed on its own rolled-back actionId (reads nothing, skips), while assertIssuancePersisted on the conflict path keys on the winner's stored actionId (label present) — correct, no double-publish and no false 503 on a legitimate concurrent win.
  • assertW94Issuable / assertConfirmation / validateManualProposal still agree: nothing that passes the W9.4 gate can throw a TypeError out of prepareManualLabelIssuance (admin-only labels lack a reviewer mode and are rejected at 400; cidRule: optional for package-disputed is handled by neither the forbidden nor required branch).
  • Routing: POST → handleConsoleMutation (only labels/{issue,retract}; everything else NOT_FOUND 404), GET → handleConsoleApi (whoami, labels/effect-preview); effect-preview is requireGet and read-guarded, whoami returns only the verified identity, no CORS headers emitted.
  • Effect preview remains read-only and grounded in the same evaluateHydratedReleaseModeration evaluator official clients use; before/after correctly go null for non-release/unresolvable subjects; the test asserts after matches 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/labeler is "private": true v0.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.

Comment on lines +177 to +180
invalidateKeys={[
["assessment", id, "labels"],
["assessment", id],
]}

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@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 13, 2026
@ascorbic
ascorbic merged commit a3e7a3e into feat/plugin-registry-labelling-service Jul 13, 2026
23 of 24 checks passed
@ascorbic
ascorbic deleted the feat/labeler-label-actions branch July 13, 2026 16:36
@ascorbic ascorbic mentioned this pull request Jul 14, 2026
60 of 81 tasks
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/awaiting-author Reviewed; waiting on the author to respond size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant