Repository navigation
feat(labeler): operational events, outbox, and automation kill-switch (W9.6 PR-0) - #2024
Conversation
…n kill-switch (W9.6 PR-0) Foundation for the admin emergency actions: migration 0005 adds the append-only operational_events alert stream, the notification_outbox delivery queue W11.3 drains, the automation_state singleton, and additive dead_letters status columns. Event/outbox insert builders support gating on an issued label's in-batch existence so a signing-suppressed batch queues no spurious alert. The discovery consumer checks the kill-switch at the top of its create branch — ingestion-only, fail-closed (pause or unreadable switch both retry), manual/admin issuance never gated. Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
|
Scope checkThis PR changes 946 lines across 7 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-playground | fd8ca7c | Jul 13 2026, 08:16 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | fd8ca7c | Jul 13 2026, 08:15 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | fd8ca7c | Jul 13 2026, 08:14 PM |
There was a problem hiding this comment.
Approach
This is the W9.6 backend foundation: the operational_events / notification_outbox / automation_state schema, additive dead_letters columns, the bare D1PreparedStatement builders for events/outbox/pause, and the one enforcement point that belongs with the schema — the discovery consumer's ingestion kill-switch. No endpoints, no console. It's stacked on feat/plugin-registry-labelling-service and the design (global, ingestion-only, fail-closed, consumer-retry) matches the ratified 2026-07-13 decision cited in the description. This is the right shape for a "PR-0" foundation: schema + builders + the consumer-side gate, with idempotency/wiring explicitly deferred to the endpoint PRs. The approach is sound.
What I checked
- Migration
0005: immutability triggers onoperational_events(unconditionalBEFORE UPDATE/DELETERAISE), mutablenotification_outbox,automation_statesingleton (CHECK (id = 1), seeded unpaused), additivedead_lettersALTERs (NOT NULL DEFAULT 'new'backfills existing rows — forward-only, no inaccessible content).payload_jsontyped{ reason?: string }with no evidence field, matching §18.2. All SQL parameterized; no interpolation. - In-batch
WHERE EXISTSgate: confirmedissued_labels.action_idisUNIQUE(0001), soWHERE EXISTS (SELECT 1 FROM issued_labels WHERE action_id = ?)can only be satisfied by the exact action's label. The test suite proves the gate sees an in-batchissued_labelsinsert (realdb.batch) and inserts nothing when the label is suppressed in-batch — not a mock assertion. Good. - Kill-switch:
readAutomationPausedruns at the top of the create branch only; a paused switch callscontroller.retry(), and an unreadable switch (AutomationStateUnavailableError) is mapped toLabelIssuanceUnavailableError→classifyDiscoveryErrorretries. Both fail closed. The delete branch is deliberately ungated and has an explicit test proving cancellation + negation still run during a pause. Consistent with the stated "signing layer untouched" scope. - Tests: honest — they assert real DB state (subject counts, assessment state, label
neg), the gate is proven inside a realdb.batch, and the fail-closed/delete-exemption behaviors have dedicated tests. - Changeset/i18n: correctly omitted —
@emdash-cms/labelerisprivate: true(version: 0.0.0); backend-only, no UI.
Headline
The implementation is correct and the tests are substantive. The one real gap is index discipline: the new operational_events.action_id and notification_outbox.event_id foreign keys have no index, and this PR ships queries (getOperationalEventsByActionId, getOutboxForEvent) that filter on exactly those columns — a full scan each, and a violation of AGENTS.md's "foreign key columns always get an index" rule that 0003 follows. Two needs_fixing index findings plus a couple of forward-looking suggestions (the unindexed dead_letters.resolved_by_action_id FK, and the event/outbox builders lacking the idempotency guards the sibling issuance builders carry — to be nailed down when commitMutation lands).
| CREATE INDEX idx_operational_events_created ON operational_events(created_at_epoch_ms DESC); | ||
| CREATE INDEX idx_operational_events_severity | ||
| ON operational_events(severity, created_at_epoch_ms DESC); |
There was a problem hiding this comment.
[needs fixing] operational_events.action_id (line 26) is a foreign key to operator_actions(id), and this PR's new getOperationalEventsByActionId queries it with WHERE action_id = ? (operational-events.ts:215). Neither of the two indexes created here covers it — idx_operational_events_created is on created_at_epoch_ms and idx_operational_events_severity on (severity, created_at_epoch_ms). So getOperationalEventsByActionId degrades to a full scan + sort as the event log grows. AGENTS.md ("Foreign key columns always get an index") and the repo's own 0003_assessment_lifecycle.sql convention (every *_assessment_id FK gets an index) say this column should be indexed. Add a single-column index on action_id.
| CREATE INDEX idx_operational_events_created ON operational_events(created_at_epoch_ms DESC); | |
| CREATE INDEX idx_operational_events_severity | |
| ON operational_events(severity, created_at_epoch_ms DESC); | |
| CREATE INDEX idx_operational_events_action ON operational_events(action_id); |
There was a problem hiding this comment.
Fixed in fd8ca7c — idx_operational_events_action, partial on action_id IS NOT NULL matching 0003's idx_issuance_actions_assessment style.
~ 🤖 Claude Opus 4.8
| sent_at TEXT | ||
| ); | ||
|
|
||
| CREATE INDEX idx_notification_outbox_pending |
There was a problem hiding this comment.
[needs fixing] notification_outbox.event_id (line 52) is a foreign key to operational_events(id), and this PR's new getOutboxForEvent queries it with WHERE event_id = ? (operational-events.ts:233). The only outbox index created here is the partial idx_notification_outbox_pending on (state, created_at_epoch_ms) WHERE state = 'pending', which the W11.3 drain uses but getOutboxForEvent cannot. That lookup is a full scan. Per AGENTS.md ("Foreign key columns always get an index") and the 0003 convention, add an index on event_id.
| CREATE INDEX idx_notification_outbox_pending | |
| CREATE INDEX idx_notification_outbox_event ON notification_outbox(event_id); |
There was a problem hiding this comment.
Fixed in fd8ca7c — idx_notification_outbox_event (plain, the column is NOT NULL).
~ 🤖 Claude Opus 4.8
| ALTER TABLE dead_letters ADD COLUMN resolved_at TEXT; | ||
| ALTER TABLE dead_letters ADD COLUMN resolved_by_action_id TEXT REFERENCES operator_actions(id); | ||
|
|
||
| CREATE INDEX idx_dead_letters_status ON dead_letters(status, received_at); |
There was a problem hiding this comment.
[suggestion] dead_letters.resolved_by_action_id (line 80) is a new foreign key to operator_actions(id) with no index. There's no query filtering on it in this PR, so this is lower priority than the two above, but AGENTS.md says foreign-key columns always get an index and the 0003 migration indexes its *_action_id-style FKs. Since the column is mostly null until a letter is resolved, a partial index keeps it cheap.
| CREATE INDEX idx_dead_letters_status ON dead_letters(status, received_at); | |
| CREATE INDEX idx_dead_letters_resolved_by ON dead_letters(resolved_by_action_id) | |
| WHERE resolved_by_action_id IS NOT NULL; |
There was a problem hiding this comment.
Done in fd8ca7c — idx_dead_letters_resolved_action, partial on IS NOT NULL since the column is null until resolution. (automation_state.paused_by_action_id deliberately stays unindexed: one-row singleton, nothing to scan.)
~ 🤖 Claude Opus 4.8
| * in-batch existence (see {@link OperationalEventInsert}); otherwise it is a | ||
| * plain INSERT for events with no issued label (pause/resume, DLQ controls). | ||
| */ | ||
| export function buildOperationalEventInsert( |
There was a problem hiding this comment.
[suggestion] The event/outbox inserts have no idempotency guard, unlike their sibling issuance effect statements. buildIssuanceStatements makes the issuance_actions insert ON CONFLICT(idempotency_key) DO NOTHING and the issued_labels insert NOT EXISTS (SELECT 1 FROM issued_labels WHERE action_id = a.id), so a replayed commitMutation batch converges. buildOperationalEventInsert/buildOutboxInsert have neither: the event id is caller-supplied (a deterministic id would PK-conflict on replay; a fresh ULID would produce duplicate events/outbox rows), and buildOutboxInsert mints a fresh nob_… id on every call. This is fine as long as the future endpoint PR gates the effect statements on the operator_actions insert being a fresh write (changes > 0) and never re-runs them on replay — but the builders themselves don't enforce that, so it's worth pinning down explicitly when commitMutation lands.
There was a problem hiding this comment.
No guard needed, by construction: these builders only ever run as batch-mates of commitMutation, whose plain operator_actions INSERT at the batch head makes the whole batch all-or-nothing on the idempotency key — a replay short-circuits in guardMutation before any batch runs, and a concurrent loser's entire batch (event and outbox included) aborts on the UNIQUE violation. So the event/outbox statements cannot execute twice for one action. The issuance builders' in-statement guards serve the automated path's separate issuance_actions idempotency, which these builders don't participate in. The endpoint PRs (W9.6 PR-1/2/3) will carry replay tests asserting exactly one operational event per action, which pins this property where the wiring actually exists.
~ 🤖 Claude Opus 4.8
There was a problem hiding this comment.
Re-review of #2024 (W9.6 PR-0: operational events, outbox, automation kill-switch). My previous review raised two needs_fixing index gaps and one suggestion index gap plus a forward-looking idempotency-guard note. All are addressed.
Fixed since the last review
operational_events.action_idFK is now indexed (idx_operational_events_action … WHERE action_id IS NOT NULL).notification_outbox.event_idFK is now indexed (idx_notification_outbox_event).dead_letters.resolved_by_action_idFK is now indexed (idx_dead_letters_resolved_action … WHERE resolved_by_action_id IS NOT NULL).- The idempotency-guard note was always a forward-looking item explicitly deferred to the
commitMutationPR; correctly not in scope here.
What I re-verified this pass
- Kill-switch:
readAutomationPausedruns only at the top of the create branch; paused →controller.retry(), unreadable (AutomationStateUnavailableError) → mapped toLabelIssuanceUnavailableError→classifyDiscoveryErrorretries. Both fail closed, both have dedicated tests. The delete branch is deliberately ungated and its exemption is tested (cancel + negate still run during a pause). Matches the ratified global / ingestion-only / fail-closed / consumer-retry decision. verifyAndCreateRunhas exactly one call-site (discovery-consumer.ts:234), inside the gated branch — no other automated-issuance path bypasses the switch; the W7/W8 orchestrator caveat is acknowledged in the PR description.- In-batch
WHERE EXISTSgate:issued_labels.action_idisUNIQUE(0001), so the EXISTS can only match the exact action's label. The suite proves the gate observes an in-batchissued_labelsinsert and inserts nothing when suppressed — assertions on real DB state, not mocks. - Migration
0005: unconditional immutability triggers onoperational_events;notification_outboxmutable;automation_statesingleton (CHECK id = 1, seeded unpaused);dead_lettersALTERs are additive withNOT NULL DEFAULT 'new'backfill (forward-only).payload_jsontyped{ reason?: string }, no evidence field, matching §18.2. All SQL parameterized. automation_state.paused_by_action_idis an unindexed FK, but it's a one-row singleton never queried by that column, consistent with the siblingsigning_statesingleton (whoserotation_idis likewise unindexed) — not a finding.@emdash-cms/labelerisprivate: true,version 0.0.0→ changeset correctly omitted; backend-only → i18n n/a.
No new issues. LGTM.
cf6c14f
into
feat/plugin-registry-labelling-service
What does this PR do?
First of the W9.6 (admin-only emergency actions) PRs: the backend foundation the takedown, pause/resume, and dead-letter controls build on. No endpoints, no console changes — schema and builders only, plus the one enforcement point that belongs with the schema.
Migration
0005_operational_events.sql(conventions from0004):operational_events— the append-only high-severity alert stream (immutability triggers reject UPDATE/DELETE). This is the source of truth W11.3 wires deployment alarms onto; distinct fromoperator_actions(who did what) and the publisher-facing notifications (W10).payload_jsonis typed as{ reason?: string }— no field for private evidence exists (spec §18.2).notification_outbox— mutable per-(event, channel) delivery state W11.3 drains; a delivery failure never rolls back the event or the label.automation_state— the global automation kill-switch singleton (id = 1, seeded unpaused).dead_letters— additivestatus(default'new', backfills existing rows) /resolved_at/resolved_by_action_idcolumns + status index, for the retry/quarantine controls.Builders (
operational-events.ts,automation-state.ts) return bareD1PreparedStatements so the later endpoint PRs can hand them tocommitMutationas effect statements, keeping the audit-atomicity invariant. The event and outbox inserts take an optional gate on an issued label's in-batch existence (INSERT … SELECT … WHERE EXISTS): if a signing-state rotation suppresses the label INSERT mid-batch, the event and outbox rows also don't insert — so no "takedown issued" alert can ever be queued for a takedown that never landed (the W9.4/W9.5 phantom-success guard, extended to the alert stream).The kill-switch enforcement lands here too, since it's consumer-side, not endpoint-side:
processDiscoveryMessagechecksisAutomationPausedat the top of its create branch. Per the ratified decisions (2026-07-13): global scope, ingestion-only — the signing layer is untouched, so manual/admin issuance and operator reruns stay available mid-incident; fail-closed — a paused or unreadable switch both route tocontroller.retry(), never past the gate; consumer-retry mechanism — a long pause drains to the DLQ, recovered by resume + the PR-3 retry control. The delete branch is deliberately ungated (verified deletes still cancel + negate during a pause), locked in by a test.Adversarially reviewed by an independent Opus pass targeting fail-open paths, in-batch
WHERE EXISTSsemantics, and migration safety: no blockers — it confirmedverifyAndCreateRunhas exactly one (gated) caller and automated create issuance has no other entry point, the gate can't be satisfied by another action's label (action_idis UNIQUE), andisAutomationPausedgenuinely throws on both missing-row and D1-error. Its two test-honesty fixes are included: the T1 gate is now proven inside a realdb.batch(both the label-present and label-suppressed compositions), and the delete-branch exemption has an explicit test. One forward-looking note (recorded in the plan): future automated issuance paths — notably the W7/W8 orchestrator finalization — will not inherit the consumer-side gate and must add their own check.Stacked directly on the integration branch. 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 — backend only, no UI. Changeset n/a —
apps/labeleris a private, unpublished Worker app.AI-generated code disclosure
Screenshots / test output
pnpm --filter @emdash-cms/labeler test: worker 462 pass (27 files; new suites for the event/outbox builders incl. the in-batch gate compositions, the fail-closed kill-switch, and the consumer's pause/unreadable/delete-exemption behavior), console 14 pass (untouched)apps/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-ops-foundation. Updated automatically when the playground redeploys.