Repository navigation
feat(labeler): email adapter, issuance triggers, and retry sweep (W10.5 slice 2) - #2077
Conversation
….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).
|
Scope checkThis 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. |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-playground | e6c5aa3 | Jul 16 2026, 05:13 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-cache | e6c5aa3 | Jul 16 2026, 05:14 PM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ✅ Deployment successful! View logs |
emdash-demo-do | e6c5aa3 | Jul 16 2026, 05:13 PM |
There was a problem hiding this comment.
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.
| sendDiscoveryJob: async (job) => { | ||
| await env.DISCOVERY_QUEUE.send(job); | ||
| }, | ||
| notify: await createNotifyDeps(env), |
There was a problem hiding this comment.
[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.
| notify: await createNotifyDeps(env), | |
| import { createNotifyDeps, type NotifyDeps } from "./notification-triggers.js"; |
| 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), | |
| }); |
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]>
There was a problem hiding this comment.
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_SUPPRESSEDto thesuppress: '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
undeliverableto 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
sourceAlreadyProcessedcheck 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.
7d4682c
into
feat/plugin-registry-labelling-service
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 injectedNotificationSenderover the unrestrictedsend_emailbinding (arbitrary external recipients). Structuredenv.EMAIL.send()withhtml+textbodies,List-Unsubscribe+ one-click headers on every message, from-address from a var. Thrown coded errors map to aSendResultcode only (never the provider message or the payload — it is persisted verbatim inlast_error);E_RECIPIENT_SUPPRESSEDcarries asuppress: 'bounce'discriminant that the orchestration layer turns into our own suppression + a never-retriedundeliverablerow.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.notification-sweep.ts), a thirdwaitUntilbranch inscheduled(): re-drivesfailedand crash-stuckpendingrows under a CAS claim, abandons the exhausted toundeliverable(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
pendingand exhaustedfailedconfirmation rows, flipping abandonment toundeliverableso 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.comsending domain (wrangler email sending enable, auto-managed SPF/DKIM/DMARC), plus a review of theNOTIFICATION_FROM_ADDRESSvar and theNOTIFICATION_HASH_PEPPERsecret, 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 branchfeat/plugin-registry-labelling-service, notmain.Type of change
main)Checklist
pnpm typecheckpasses (all three labeler tsconfigs)pnpm lintpasses — no new diagnostics in touched files (the soleapps/labeler/src/dead-letters.tswarning predates this PR, from W9.6 feat(labeler): admin dead-letter retry and quarantine controls (W9.6 PR-3) #2028)pnpm testpasses (full labeler suite: 745 passed, 40 files)pnpm formathas been run (oxfmt, touched files)apps/labeleris an unpublished applicationmainAI-generated code disclosure
Screenshots / test output
New coverage: adapter (success/
providerId, per-code mapping,E_RECIPIENT_SUPPRESSED→ suppression discriminant,List-Unsubscribeheaders, 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.