Skip to content

feat(labeler): operational events, outbox, and automation kill-switch (W9.6 PR-0) - #2024

Merged
ascorbic merged 2 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-ops-foundation
Jul 13, 2026
Merged

ascorbic merged 2 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-ops-foundation

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

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 from 0004):

  • 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 from operator_actions (who did what) and the publisher-facing notifications (W10). payload_json is 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 — additive status (default 'new', backfills existing rows) / resolved_at / resolved_by_action_id columns + status index, for the retry/quarantine controls.

Builders (operational-events.ts, automation-state.ts) return bare D1PreparedStatements so the later endpoint PRs can hand them to commitMutation as 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: processDiscoveryMessage checks isAutomationPaused at 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 to controller.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 EXISTS semantics, and migration safety: no blockers — it confirmed verifyAndCreateRun has 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_id is UNIQUE), and isAutomationPaused genuinely throws on both missing-row and D1-error. Its two test-honesty fixes are included: the T1 gate is now proven inside a real db.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

  • 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 — backend only, no UI. Changeset n/a — apps/labeler is a private, unpublished Worker app.

AI-generated code disclosure

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

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)
  • Typecheck (both projects) clean; 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-ops-foundation. Updated automatically when the playground redeploys.

…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
@changeset-bot

changeset-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 7c68a9b

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

Copy link
Copy Markdown
Contributor

Scope check

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

@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 fd8ca7c Jul 13 2026, 08:16 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 fd8ca7c Jul 13 2026, 08:15 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-do fd8ca7c Jul 13 2026, 08:14 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

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 on operational_events (unconditional BEFORE UPDATE/DELETE RAISE), mutable notification_outbox, automation_state singleton (CHECK (id = 1), seeded unpaused), additive dead_letters ALTERs (NOT NULL DEFAULT 'new' backfills existing rows — forward-only, no inaccessible content). payload_json typed { reason?: string } with no evidence field, matching §18.2. All SQL parameterized; no interpolation.
  • In-batch WHERE EXISTS gate: confirmed issued_labels.action_id is UNIQUE (0001), so WHERE 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-batch issued_labels insert (real db.batch) and inserts nothing when the label is suppressed in-batch — not a mock assertion. Good.
  • Kill-switch: readAutomationPaused runs at the top of the create branch only; a paused switch calls controller.retry(), and an unreadable switch (AutomationStateUnavailableError) is mapped to LabelIssuanceUnavailableError → classifyDiscoveryError retries. 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 real db.batch, and the fail-closed/delete-exemption behaviors have dedicated tests.
  • Changeset/i18n: correctly omitted — @emdash-cms/labeler is private: 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).

Comment on lines +46 to +48
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);

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

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

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

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

Suggested change
CREATE INDEX idx_notification_outbox_pending
CREATE INDEX idx_notification_outbox_event ON notification_outbox(event_id);

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 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);

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

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

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.

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(

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

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.

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

@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
@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 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_id FK is now indexed (idx_operational_events_action … WHERE action_id IS NOT NULL).
  • notification_outbox.event_id FK is now indexed (idx_notification_outbox_event).
  • dead_letters.resolved_by_action_id FK 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 commitMutation PR; correctly not in scope here.

What I re-verified this pass

  • Kill-switch: readAutomationPaused runs only at the top of the create branch; paused → controller.retry(), unreadable (AutomationStateUnavailableError) → mapped to LabelIssuanceUnavailableError → classifyDiscoveryError retries. 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.
  • verifyAndCreateRun has 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 EXISTS gate: issued_labels.action_id is UNIQUE (0001), so the EXISTS can only match the exact action's label. The suite proves the gate observes an in-batch issued_labels insert and inserts nothing when suppressed — assertions on real DB state, not mocks.
  • Migration 0005: unconditional immutability triggers on operational_events; notification_outbox mutable; automation_state singleton (CHECK id = 1, seeded unpaused); dead_letters ALTERs are additive with NOT NULL DEFAULT 'new' backfill (forward-only). payload_json typed { reason?: string }, no evidence field, matching §18.2. All SQL parameterized.
  • automation_state.paused_by_action_id is an unindexed FK, but it's a one-row singleton never queried by that column, consistent with the sibling signing_state singleton (whose rotation_id is likewise unindexed) — not a finding.
  • @emdash-cms/labeler is private: true, version 0.0.0 → changeset correctly omitted; backend-only → i18n n/a.

No new issues. LGTM.

@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 13, 2026
@ascorbic
ascorbic merged commit cf6c14f into feat/plugin-registry-labelling-service Jul 13, 2026
25 of 26 checks passed
@ascorbic
ascorbic deleted the feat/labeler-ops-foundation branch July 13, 2026 20:45
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/approved Approved; no new commits since size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant