Skip to content

feat(labeler): email adapter, issuance triggers, and retry sweep (W10.5 slice 2) - #2077

Merged
ascorbic merged 3 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-notification-email
Jul 16, 2026
Merged

ascorbic merged 3 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-notification-email

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Implements W10.5 slice 2 of the labeler publisher-notification subsystem, on top of slice 1's gated send-core (#2076): the Cloudflare Email Sending adapter, the five issuance/operator triggers, verified-publisher skip, and the cron retry sweep. This is the layer that turns a committed label action into a real email to the publisher's resolved contact.

  • CloudflareEmailSender (notification-email.ts) implements the injected NotificationSender over the unrestricted send_email binding (arbitrary external recipients). Structured env.EMAIL.send() with html+text bodies, List-Unsubscribe + one-click headers on every message, from-address from a var. Thrown coded errors map to a SendResult code only (never the provider message or the payload — it is persisted verbatim in last_error); E_RECIPIENT_SUPPRESSED carries a suppress: 'bounce' discriminant that the orchestration layer turns into our own suppression + a never-retried undeliverable row.
  • Triggers (notification-triggers.ts) fire post-commit from the deferred (waitUntil) tail at the five ratified events — automated block/warning (assessment workflow), reviewer label issue/retract, override, override-retract, and emergency takedown (console mutations). A notification failure never rolls back or fails a label: every entry point swallows and logs. Per-source dedup plus an atomic per-source guard on the notice claim give "one notice per action" even under a replay race.
  • Verified-publisher skip: a publisher with an in-force verification claim (reusing history-context's expiry logic over the W8.4 aggregator read) bypasses double opt-in via a token-less confirm. The verification read fails closed — any error routes to the normal confirmation-mail path — and suppressed/declined addresses get nothing regardless.
  • Cron sweep (notification-sweep.ts), a third waitUntil branch in scheduled(): re-drives failed and crash-stuck pending rows under a CAS claim, abandons the exhausted to undeliverable (which clears plaintext and reopens a confirmation's lifetime cap so the channel is never silently foreclosed), re-checks suppression before every send, mints a fresh token for confirmation retries, re-renders notice content from source, and prunes terminal rows / stale ledger entries (keeping cap-holding sent confirmations).

Satisfies the three recorded slice-2 contracts: (a) the adapter never puts the confirm URL/token into its returned error; (b) a failed confirmation retry regenerates the token (only the hash was stored); (c) the sweep re-drives stuck pending and exhausted failed confirmation rows, flipping abandonment to undeliverable so the lifetime cap re-opens rather than a dead row locking the channel out.

Operator go-live prereq (not blocking merge): one-time Email Sending onboarding of the emdashcms.com sending domain (wrangler email sending enable, auto-managed SPF/DKIM/DMARC), plus a review of the NOTIFICATION_FROM_ADDRESS var and the NOTIFICATION_HASH_PEPPER secret, before any real delivery. Until then the subsystem is inert (no cron sends without an onboarded domain).

Design is governed by the ratified plan .opencode/plans/plugin-registry-labelling-service/implementation-plan.md § W10.5; targets the integration branch feat/plugin-registry-labelling-service, not main.

Type of change

  • Feature (ratified in the W10.5 plan; targets the labeler integration branch, not main)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes (all three labeler tsconfigs)
  • pnpm lint passes — no new diagnostics in touched files (the sole apps/labeler/src/dead-letters.ts warning predates this PR, from W9.6 feat(labeler): admin dead-letter retry and quarantine controls (W9.6 PR-3) #2028)
  • pnpm test passes (full labeler suite: 745 passed, 40 files)
  • pnpm format has been run (oxfmt, touched files)
  • I have added/updated tests for my changes (adapter, triggers, sweep — 37 new tests)
  • User-visible strings in the admin UI are wrapped for translation — n/a: no admin UI, no user-facing admin strings (email bodies are transactional, not localized in this slice)
  • I have added a changeset — n/a: apps/labeler is an unpublished application
  • New features link to an approved Discussion — n/a: governed by the ratified W10.5 plan doc; targets the labeler integration branch, not main

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Opus 4.8

Screenshots / test output

Test Files  40 passed (40)
     Tests  745 passed (745)

New coverage: adapter (success/providerId, per-code mapping, E_RECIPIENT_SUPPRESSED → suppression discriminant, List-Unsubscribe headers, no-payload-in-error), triggers (each of the five events, per-source dedup, verified-skip in-force/expired/read-failure/suppressed, throw isolation), sweep (retry→sent, fresh-token stamp, cap exhaustion + reopen, stuck-pending re-drive, suppression re-check → no mail, provider suppression, transient-read self-heal, 30-day cleanup, ledger prune).


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-notification-email. Updated automatically when the playground redeploys.

ascorbic added 2 commits July 16, 2026 17:31
….5 slice 2)

Cloudflare Email Sending adapter + the five ratified notification triggers +
the cron retry sweep, completing the publisher-notification subsystem on top of
slice 1's gated send-core.

CloudflareEmailSender (notification-email.ts) implements NotificationSender over
the unrestricted `send_email` binding (arbitrary external recipients): structured
env.EMAIL.send() with html+text bodies, List-Unsubscribe + one-click headers on
every message, from-address from a var. Thrown coded errors map to SendResult
CODE ONLY (never the provider message or payload) — E_RECIPIENT_SUPPRESSED
carries a `suppress: 'bounce'` discriminant the send-core turns into our own
suppression + an undeliverable, never-retried row; other codes are retryable.

Triggers (notification-triggers.ts) fire post-commit from the deferred tail at
the five events — automated block/warning (assessment-workflow), reviewer label
issue/retract, override, override-retract, and emergency takedown
(console-mutation) — building a public-safe NoticeContent and calling
sendNotification. A notification failure never touches the label: every entry
point swallows and logs. Per-source dedup (a source already carrying a
notifications row is skipped) plus an atomic per-source guard on the notice
claim give the "one notice per action" invariant even under a replay race.
Verified publishers (in-force verification claim, reused from history-context's
expiry logic) skip double opt-in via a token-less confirm; the verification read
fails CLOSED to the confirmation-mail path, and suppressed/declined addresses get
nothing regardless.

Cron sweep (notification-sweep.ts) re-drives `failed` and crash-stuck `pending`
rows (attempts-capped via a CAS claim), abandoning the exhausted to
`undeliverable` — which clears plaintext and reopens a confirmation's lifetime
cap so the channel is never silently foreclosed. Confirmation retries mint a
FRESH token (only the hash was stored); notice retries re-render public content
from source (no extra PII persisted). Terminal rows and stale ledger entries are
pruned, but a sent confirmation row is kept to hold the lifetime cap.

Tests: adapter (success/providerId, per-code mapping, suppression discriminant,
List-Unsubscribe headers, no-payload-in-error), triggers (each of the five events,
dedup, verified-skip in-force/expired/read-failure/suppressed, throw isolation),
sweep (retry->sent, fresh-token stamp, cap exhaustion + reopen, stuck-pending,
provider suppression, 30-day cleanup, ledger prune). vitest runs bindings locally
(remoteBindings:false) so the unrestricted send_email binding never proxies to
real Cloudflare.
…t-read self-heal (W10.5 slice 2 review)

Adversary-pass fixes:

- F1 (HIGH): the retry sweep re-mailed suppressed addresses. `claimRetry` had
  no suppression guard and the row was never re-checked, so a confirmed publisher
  whose notice failed transiently and who then clicked Unsubscribe (leaving a
  `failed` row, since declineContact only touches unconfirmed contacts) got
  re-mailed on the next cron, up to the attempt cap. `sweepRow` now re-checks
  `isSuppressed` before the claim and ABANDONS the row (undeliverable + plaintext
  cleared) rather than skipping — a skip would leave the suppressed failed row as
  a candidate forever, since retention only prunes terminal rows. Covers notice
  and confirmation uniformly.

- F2 (MEDIUM): both suppression paths flipped the row to `undeliverable` (which
  reopens a confirmation's lifetime cap) BEFORE recording the suppression, so a
  concurrent live claim in the D1 round-trip gap saw cap-open + suppression-absent
  and could send a second mail. `markProviderSuppressed` (send-core) and
  `markSuppressed` (sweep) now `suppress()` FIRST, then flip: before the suppress
  write the still-non-undeliverable row blocks a concurrent claim via the lifetime
  guard, after it via the suppression guard — no admitting window. A crash between
  the two is covered by F1's new isSuppressed→abandon check.

- F3 (LOW): the sweep's `loadAssessmentSafe` blanket-caught every getAssessment
  error and abandoned the notice, so a transient D1 read permanently dropped a
  legitimate block/warning notice. It now returns null only for a `TypeError`
  (malformed id — never a stored source_id) and rethrows anything else, so the
  claimed row stays `pending` and self-heals on the next pass, matching the
  operator path.

Tests: sweep does NOT mail a suppressed address (notice + confirmation) and
retires the row undeliverable; a transient assessment read leaves the notice row
pending (attempts bumped, not abandoned).
@github-actions github-actions Bot added the review/needs-review No maintainer or bot review yet label Jul 16, 2026
@changeset-bot

changeset-bot Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: e6c5aa3

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

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 2,390 lines across 16 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 16, 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 e6c5aa3 Jul 16 2026, 05:13 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 16, 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 e6c5aa3 Jul 16 2026, 05:14 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 16, 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 e6c5aa3 Jul 16 2026, 05:13 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.

This is the right slice of the W10.5 plan to wire up real email delivery. The Cloudflare Email adapter, the five issuance/operator triggers, verified-publisher skip, and cron retry sweep are well-scoped and keep notifications as a post-commit, never-blocking side effect. I read the full diff, the changed source files, the notification/operator migrations, and the relevant unchanged dependencies, and checked against AGENTS.md conventions.

The core logic looks sound: SQL is fully parameterized, the notifications migration indexes cover the sweep and dedup queries, the adapter surfaces only provider error codes (never the payload), confirmation retries mint fresh tokens and flip exhausted rows to undeliverable to reopen the lifetime cap, and the sweep correctly re-drives failed/pending rows, records provider suppressions, and prunes stale terminal rows.

However, there is one blocking regression: handleConsoleApiRequest builds notification deps with await createNotifyDeps(env) before it invokes handleConsoleMutation. If NOTIFICATION_HASH_PEPPER is missing or its binding rejects, the request handler throws before the label mutation runs, directly contradicting the “notification failure never blocks or fails a label” contract. The assessment-workflow and scheduled paths already wrap this in try/catch; the console path does not. That makes this a true merge blocker in my view.

Comment thread apps/labeler/src/index.ts Outdated
sendDiscoveryJob: async (job) => {
await env.DISCOVERY_QUEUE.send(job);
},
notify: await createNotifyDeps(env),

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] handleConsoleApiRequest awaits createNotifyDeps(env) while building the handleConsoleMutation argument object. createNotifyDeps calls getNotificationHashPepper(env).get(), which throws a TypeError when NOTIFICATION_HASH_PEPPER is missing or not a string/pepper binding. Because this happens before handleConsoleMutation is called, the entire operator console mutation would return a 500 and the label action would never commit, breaking the subsystem’s “post-commit / never-blocking” guarantee. The workflow and scheduled paths already catch this; the console path must too.

Also add a regression test that stubs a rejecting notification-pepper binding and asserts the label mutation still commits.

Suggested change
notify: await createNotifyDeps(env),
import { createNotifyDeps, type NotifyDeps } from "./notification-triggers.js";
Suggested change
notify: await createNotifyDeps(env),
const keys = getAccessKeyResolver(accessConfig.teamDomain);
let notify: NotifyDeps | undefined;
try {
notify = await createNotifyDeps(env);
} catch (err) {
console.error(
"[labeler] notification deps unavailable; console mutations will proceed without notices",
{ error: err instanceof Error ? err.message : String(err) },
);
}
if (request.method === "POST") {
return handleConsoleMutation(request, {
db: env.DB,
accessConfig,
keys,
config,
createSigner: async () =>
(await createRuntimeSigner(config, getRuntimeSigningSecret(env))).signer,
now: () => new Date(),
afterCommit: (actionId) => publishAfterCommit(env, actionId),
defer: (work) => ctx.waitUntil(work),
sendDiscoveryJob: async (job) => {
await env.DISCOVERY_QUEUE.send(job);
},
notify,
});
}
return handleConsoleApi(request, {
db: env.DB,
config: accessConfig,
keys,
labelerDid: config.labelerDid,
jetstreamConnected: () => probeJetstreamConnected(env),
});

@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 16, 2026
The console mutation path built notify deps with a bare
`await createNotifyDeps(env)` before `handleConsoleMutation`, so a
deps-construction failure (e.g. a missing NOTIFICATION_HASH_PEPPER or a
rejecting binding) threw before the label mutation ran — violating the
invariant that a notification concern never blocks or fails a label. The
workflow and scheduled paths already guard this; the console path did not.

Wrap construction in `safeCreateNotifyDeps`, which logs under the
`[notifications]` prefix and returns `undefined` on failure. The mutation
proceeds and issues the label; the defer helpers already no-op when
`notify` is undefined, so notifications degrade rather than the label
failing.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@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 16, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 16, 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.

This is the right slice of W10.5 to wire real email delivery: the Cloudflare Email adapter, the five issuance/operator triggers, verified-publisher skip, and the cron retry sweep are all well-scoped and keep notifications as a post-commit, never-blocking side effect. The previous blocker is fixed — handleConsoleApiRequest now builds notification deps via safeCreateNotifyDeps, which catches a missing/rejecting NOTIFICATION_HASH_PEPPER and degrades notifications to undefined so the label mutation still commits. Tests cover that failure-isolation path.

I re-read the full diff, the changed source files, the notification migrations, and the relevant unchanged dependencies, and checked against AGENTS.md conventions. What's fixed:

  • Console mutation notification deps are now constructed safely; a missing pepper/binding no longer throws before the label path runs.
  • Assessment-workflow and scheduled paths already wrapped notification construction in try/catch; the console path now matches.

What I checked and found clean:

  • SQL is fully parameterized; no interpolation into queries.
  • Migration 0008 indexes cover the sweep queries (state/created_at_epoch_ms, created_at_epoch_ms, recipient_hash, source_type/source_id) and the confirm-ledger sweep.
  • The adapter surfaces only provider error codes, never the payload or provider message, and maps E_RECIPIENT_SUPPRESSED to the suppress: 'bounce' discriminant.
  • Verified-publisher skip fails closed: any verification-read error or expired claim routes to double opt-in, and suppressed/declined addresses still receive nothing.
  • Confirmation retries mint fresh tokens (only the hash was ever stored), and exhausted/failed confirmations are flipped to undeliverable to reopen the lifetime cap.
  • The sweep re-checks suppression before re-sending, abandons suppressed rows, and prunes terminal rows/stale ledger entries while keeping sent confirmation rows for the lifetime cap.
  • Per-source dedup in the notice claim plus the trigger-level sourceAlreadyProcessed check gives the "one notice per action" invariant.
  • No admin UI strings or content-table queries were added, so Lingui/RTL/locale-filter conventions are not applicable; no published package changed, so no changeset is needed.

No remaining blocking or needs-fixing issues. LGTM.

@emdashbot emdashbot Bot removed the bot:review Trigger an emdashbot code review on this PR label Jul 16, 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 16, 2026
@ascorbic
ascorbic merged commit 7d4682c into feat/plugin-registry-labelling-service Jul 16, 2026
11 checks passed
@ascorbic
ascorbic deleted the feat/labeler-notification-email branch July 16, 2026 17:16
@ascorbic ascorbic mentioned this pull request Jul 16, 2026
60 of 81 tasks
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