@yielded/agent-platform-cloudflare 0.1.0-beta.167 → 0.1.0-beta.169
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Alarm-B0ODr1NE.mjs → Alarm-BMEAZo3p.mjs} +261 -159
- package/dist/Alarm-BMEAZo3p.mjs.map +1 -0
- package/dist/Alarm.d.mts +29 -36
- package/dist/Alarm.mjs +2 -2
- package/dist/BrowserCredentials-C5IWfi7f.d.mts +91 -0
- package/dist/BrowserCredentials.d.mts +2 -91
- package/dist/BrowserRestCapture.mjs +3 -3
- package/dist/BrowserRestCapture.mjs.map +1 -1
- package/dist/BrowserRestCrawl.mjs +6 -6
- package/dist/BrowserRestCrawl.mjs.map +1 -1
- package/dist/{BrowserSession-RfIzxGCH.mjs → BrowserSession-BfNmyayH.mjs} +5 -5
- package/dist/BrowserSession-BfNmyayH.mjs.map +1 -0
- package/dist/{BrowserSession-B969Xg-2.d.mts → BrowserSession-Bx0V1-6_.d.mts} +6 -3
- package/dist/BrowserSession.d.mts +1 -1
- package/dist/BrowserSession.mjs +2 -2
- package/dist/BrowserUse-Bc2JdLW2.mjs +1528 -0
- package/dist/BrowserUse-Bc2JdLW2.mjs.map +1 -0
- package/dist/BrowserUse.d.mts +83 -0
- package/dist/BrowserUse.mjs +2 -0
- package/dist/CloudflareBindings.d.mts +8 -1
- package/dist/CloudflareBindings.mjs +2 -2
- package/dist/CloudflareBindings.mjs.map +1 -1
- package/dist/{CloudflareBrowser-5an6m-Qb.mjs → CloudflareBrowser-Vt8qTdYW.mjs} +11 -13
- package/dist/CloudflareBrowser-Vt8qTdYW.mjs.map +1 -0
- package/dist/CloudflareBrowser.mjs +1 -1
- package/dist/CloudflareCodeMode.mjs +1 -1
- package/dist/CloudflareCodeMode.mjs.map +1 -1
- package/dist/{CloudflareConfig-qDrRLofL.d.mts → CloudflareConfig-C9MvPbX8.d.mts} +9 -11
- package/dist/CloudflareConfig.d.mts +1 -1
- package/dist/CloudflareConfig.mjs +9 -12
- package/dist/CloudflareConfig.mjs.map +1 -1
- package/dist/CloudflareMemory.d.mts +3 -25
- package/dist/CloudflareMemory.mjs +33 -31
- package/dist/CloudflareMemory.mjs.map +1 -1
- package/dist/CloudflareScheduling.mjs +8 -15
- package/dist/CloudflareScheduling.mjs.map +1 -1
- package/dist/CloudflareSubscriptions.mjs +9 -16
- package/dist/CloudflareSubscriptions.mjs.map +1 -1
- package/dist/CloudflareThreadClient-CLZpN9zU.mjs +588 -0
- package/dist/CloudflareThreadClient-CLZpN9zU.mjs.map +1 -0
- package/dist/CloudflareThreadClient-QsVzLGGZ.d.mts +2033 -0
- package/dist/CloudflareThreadClient.d.mts +2 -1796
- package/dist/CloudflareThreadClient.mjs +2 -382
- package/dist/{InteractiveBrowser-BbG3kGA9.mjs → InteractiveBrowser-LdKzQeLR.mjs} +18 -19
- package/dist/InteractiveBrowser-LdKzQeLR.mjs.map +1 -0
- package/dist/InteractiveBrowser.mjs +1 -1
- package/dist/{ThreadObject-BcfXbzSO.d.mts → ThreadObject-7s5XnlH-.d.mts} +103 -79
- package/dist/{ThreadObject-DHjrnlX4.mjs → ThreadObject-CgXZMlr4.mjs} +265 -66
- package/dist/ThreadObject-CgXZMlr4.mjs.map +1 -0
- package/dist/ThreadObject.d.mts +2 -2
- package/dist/ThreadObject.mjs +2 -3
- package/dist/WakeScheduler.d.mts +6 -5
- package/dist/WakeScheduler.mjs +15 -11
- package/dist/WakeScheduler.mjs.map +1 -1
- package/dist/index.d.mts +7 -6
- package/dist/index.mjs +7 -6
- package/dist/page-function-CmUCcyNP.mjs +11 -0
- package/dist/page-function-CmUCcyNP.mjs.map +1 -0
- package/dist/{prepared-admission-DMX5p9dC.mjs → prepared-admission-B61A7y6O.mjs} +3 -3
- package/dist/{prepared-admission-DMX5p9dC.mjs.map → prepared-admission-B61A7y6O.mjs.map} +1 -1
- package/package.json +1 -1
- package/src/Alarm.ts +512 -279
- package/src/BrowserRestCapture.ts +2 -2
- package/src/BrowserRestCrawl.ts +10 -14
- package/src/BrowserSession.ts +10 -2
- package/src/BrowserUse.ts +1591 -0
- package/src/CloudflareBindings.ts +13 -4
- package/src/CloudflareCodeMode.ts +1 -1
- package/src/CloudflareConfig.ts +9 -12
- package/src/CloudflareMemory.ts +21 -28
- package/src/CloudflareScheduling.ts +7 -15
- package/src/CloudflareSubscriptions.ts +11 -20
- package/src/CloudflareThreadClient.ts +289 -9
- package/src/InteractiveBrowser.ts +325 -323
- package/src/ThreadObject.ts +172 -52
- package/src/WakeScheduler.ts +29 -18
- package/src/index.ts +1 -0
- package/src/internal/browser-dom.ts +886 -0
- package/src/internal/browser-file-selection.ts +8 -1
- package/src/internal/browser-jev-dom.ts +362 -0
- package/src/internal/browser-quick-action.ts +7 -8
- package/src/internal/browser-session-lifecycle.ts +2 -5
- package/src/internal/crypto.ts +41 -0
- package/src/internal/due-queue.ts +5 -69
- package/src/internal/layers.ts +100 -17
- package/src/internal/live-text-protocol.ts +51 -0
- package/src/internal/live-text.ts +256 -0
- package/src/internal/page-function.ts +12 -0
- package/src/internal/prepared-admission.ts +1 -1
- package/src/internal/progress-wait.ts +19 -24
- package/src/internal/transport.ts +1 -1
- package/dist/Alarm-B0ODr1NE.mjs.map +0 -1
- package/dist/BrowserSession-RfIzxGCH.mjs.map +0 -1
- package/dist/CloudflareBrowser-5an6m-Qb.mjs.map +0 -1
- package/dist/CloudflareThreadClient.mjs.map +0 -1
- package/dist/InteractiveBrowser-BbG3kGA9.mjs.map +0 -1
- package/dist/ThreadObject-DHjrnlX4.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Alarm-BMEAZo3p.mjs","names":["invalidate","DueQueue.invalidate","DueQueue.buffering","next","DueQueue.next","DueQueue.make","DueQueue.ownsTransaction","DueQueue.LaneId","DueQueue.Native","DueQueue.Publication","DueQueue.HostLaneId","DueQueue.ParkedRetryMillis","DueQueue.Projection","DueQueue.Messages","DueQueue.Lifecycle","DueQueue.RecoveryEvents"],"sources":["../src/internal/due-queue.ts","../src/Alarm.ts"],"sourcesContent":["import { Effect, Schema } from \"effect\";\n\nexport const LaneId = Schema.NonEmptyString.check(Schema.isMaxLength(256));\n\nexport const HostLaneId = LaneId.check(\n Schema.isPattern(/^(?!effect-agent:)/, {\n message: \"The effect-agent: namespace is reserved for framework maintenance lanes\",\n }),\n);\n\nexport const Deadline = Schema.NullOr(Schema.Finite);\nexport const MinimumRetryMillis = 1_000;\nexport const MaximumNoProgressRearms = 8;\nexport const ParkedRetryMillis = 60 * 60_000;\n\n/** Scheduling metadata only. Domain outboxes, claims and receipts remain authoritative. */\nexport class DueLane extends Schema.Class<DueLane>(\"CloudflareDueLane\")({\n id: LaneId,\n revision: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n dueAt: Deadline,\n stalls: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 30 })),\n progressKey: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(512))),\n notBefore: Schema.Finite,\n state: Schema.Literals([\"idle\", \"pending\", \"parked\"]),\n reported: Schema.Literals([0, 1]),\n}) {}\n\nexport const Native = \"effect-agent:native\";\nexport const Publication = \"effect-agent:publication\";\nexport const Projection = \"effect-agent:projection\";\nexport const Messages = \"effect-agent:messages\";\nexport const RecoveryEvents = \"effect-agent:recovery-events\";\nexport const Lifecycle = \"effect-agent:lifecycle\";\n\nconst decode = Schema.decodeUnknownSync(Schema.Array(DueLane));\n\nconst equivalent = Schema.toEquivalence(DueLane);\n\ntype Change = { readonly before: DueLane | undefined; readonly after: DueLane };\ntype Frame = {\n readonly parent: Frame | undefined;\n readonly sqlDepth: number | undefined;\n readonly rows: ReadonlyArray<DueLane> | undefined;\n readonly changes: Map<string, Change>;\n readonly deadlines: Map<string, number>;\n};\ntype View = {\n rows: ReadonlyArray<DueLane> | undefined;\n frame: Frame | undefined;\n retained: number;\n changes: Map<string, Change>;\n deadlines: Map<string, number>;\n};\nconst views = new WeakMap<DurableObjectStorage, View>();\n\n/** Only the explicit source boundary may retain speculative rows across operations. */\nexport const buffering = (storage: DurableObjectStorage): boolean =>\n views.get(storage)?.frame !== undefined;\n\nexport const ownsTransaction = (storage: DurableObjectStorage, depth: number): boolean =>\n views.get(storage)?.frame?.sqlDepth === depth;\n\nexport const invalidate = (storage: DurableObjectStorage): void => {\n const view = views.get(storage);\n\n if (view !== undefined) view.rows = undefined;\n};\n\n/** Callers reserve the shared SQL connection through commit. Keep the complete view\n * during a transaction, then retain at most 128 lanes between transactions. Intent\n * flushes before source commit; claims and prearming commit before fallible work. */\nexport const make = (storage: DurableObjectStorage) => {\n // Instrumentation may return a fresh SQL wrapper on every access.\n const sql = storage.sql;\n let view = views.get(storage);\n\n if (view === undefined) {\n view = {\n rows: undefined,\n frame: undefined,\n retained: 0,\n changes: new Map(),\n deadlines: new Map(),\n };\n views.set(storage, view);\n }\n const current = view;\n\n const trim = () => {\n if (current.frame === undefined && current.retained === 0 && (current.rows?.length ?? 0) > 128)\n current.rows = undefined;\n };\n\n /** Retain the pass's write-through view without deferring claims or source commits.\n * Failed source transactions still invalidate it; large views are released at exit. */\n const withView = <A, E, R>(body: Effect.Effect<A, E, R>) =>\n Effect.acquireUseRelease(\n Effect.sync(() => {\n current.retained++;\n }),\n () => body,\n () =>\n Effect.sync(() => {\n current.retained--;\n trim();\n }),\n );\n\n const begin = (sqlDepth?: number): Frame => {\n const frame: Frame = {\n parent: current.frame,\n sqlDepth,\n rows: current.rows,\n changes: current.changes,\n deadlines: current.deadlines,\n };\n\n current.frame = frame;\n current.changes = new Map(current.changes);\n current.deadlines = new Map(current.deadlines);\n\n return frame;\n };\n\n const finish = (frame: Frame, success: boolean) => {\n current.frame = frame.parent;\n if (!success) {\n // A child rollback must retain its parent's still-unflushed intent.\n current.rows = frame.parent === undefined ? undefined : frame.rows;\n current.changes = frame.changes;\n current.deadlines = frame.deadlines;\n }\n if (frame.parent === undefined) {\n current.changes.clear();\n current.deadlines.clear();\n trim();\n }\n };\n\n // Nine bindings per lane stay below Durable Object SQLite's 100-parameter limit.\n const write = (changes: ReadonlyArray<Change>) => {\n const rows = decode(\n sql\n .exec(\n `WITH changes (id, revision, dueAt, stalls, progressKey, notBefore, state, reported, expected_revision) AS (\n VALUES ${changes.map(() => \"(?, ?, ?, ?, ?, ?, ?, ?, ?)\").join(\", \")}\n ) INSERT INTO platform_cloudflare_due_queue\n (id, revision, dueAt, stalls, progressKey, notBefore, state, reported)\n SELECT id, revision, dueAt, stalls, progressKey, notBefore, state, reported FROM changes WHERE 1\n ON CONFLICT(id) DO UPDATE SET revision = excluded.revision, dueAt = excluded.dueAt,\n stalls = excluded.stalls, progressKey = excluded.progressKey,\n notBefore = excluded.notBefore, state = excluded.state, reported = excluded.reported\n WHERE platform_cloudflare_due_queue.revision = (\n SELECT expected_revision FROM changes WHERE changes.id = excluded.id\n ) RETURNING id, revision, dueAt, stalls, progressKey, notBefore, state, reported`,\n ...changes.flatMap(({ before, after }) => [\n after.id,\n after.revision,\n after.dueAt,\n after.stalls,\n after.progressKey,\n after.notBefore,\n after.state,\n after.reported,\n before?.revision ?? -1,\n ]),\n )\n .toArray(),\n );\n\n // Partial revision acceptance must reject the enclosing source transaction.\n if (rows.length !== changes.length)\n throw new Error(\"Maintenance due revision changed during transaction\");\n };\n\n const flush = (frame: Frame) => {\n if (frame.parent !== undefined) return;\n\n const changes = [...current.changes.values()].filter(\n ({ before, after }) => before === undefined || !equivalent(before, after),\n );\n\n for (let offset = 0; offset < changes.length; offset += 11)\n write(changes.slice(offset, offset + 11));\n };\n\n const transaction = async <A>(\n body: (transaction: DurableObjectTransaction) => Promise<A>,\n ): Promise<A> => {\n let frame: Frame | undefined;\n\n try {\n const result = await storage.transaction(async (transaction) => {\n frame = begin();\n const result = await body(transaction);\n\n flush(frame);\n\n return result;\n });\n\n if (frame !== undefined) finish(frame, true);\n\n return result;\n } catch (cause) {\n if (frame !== undefined) finish(frame, false);\n throw cause;\n }\n };\n\n const initialize = () => {\n sql.exec(`CREATE TABLE IF NOT EXISTS platform_cloudflare_due_queue (\n id TEXT PRIMARY KEY, revision INTEGER NOT NULL, dueAt REAL, stalls INTEGER NOT NULL,\n progressKey TEXT, notBefore REAL NOT NULL DEFAULT 0, state TEXT NOT NULL DEFAULT 'pending',\n reported INTEGER NOT NULL DEFAULT 0\n )`);\n\n const columns = new Set(\n sql\n .exec(\"PRAGMA table_info(platform_cloudflare_due_queue)\")\n .toArray()\n .map((row) => row.name),\n );\n\n if (!columns.has(\"reported\"))\n sql.exec(\n \"ALTER TABLE platform_cloudflare_due_queue ADD COLUMN reported INTEGER NOT NULL DEFAULT 0\",\n );\n if (!columns.has(\"progressKey\"))\n sql.exec(\"ALTER TABLE platform_cloudflare_due_queue ADD COLUMN progressKey TEXT\");\n if (!columns.has(\"notBefore\"))\n sql.exec(\n \"ALTER TABLE platform_cloudflare_due_queue ADD COLUMN notBefore REAL NOT NULL DEFAULT 0\",\n );\n if (!columns.has(\"state\")) {\n sql.exec(\n \"ALTER TABLE platform_cloudflare_due_queue ADD COLUMN state TEXT NOT NULL DEFAULT 'pending'\",\n );\n sql.exec(\"UPDATE platform_cloudflare_due_queue SET state = 'idle' WHERE dueAt IS NULL\");\n }\n };\n\n /** Keep dormant rows so delete/reinsert cannot reuse a revision held by an older wave. */\n const read = () => {\n if (current.rows !== undefined) return current.rows;\n\n const rows = decode(\n sql\n .exec(\n \"SELECT id, revision, dueAt, stalls, progressKey, notBefore, state, reported FROM platform_cloudflare_due_queue\",\n )\n .toArray(),\n );\n\n if (current.frame !== undefined || current.retained > 0 || rows.length <= 128)\n current.rows = rows;\n\n return rows;\n };\n\n const set = (after: DueLane) => {\n const rows = read();\n const before = rows.find((row) => row.id === after.id);\n\n if (before !== undefined && equivalent(before, after)) return before;\n const previous = current.changes.get(after.id);\n const change = { before: previous === undefined ? before : previous.before, after };\n\n if (current.frame === undefined) write([change]);\n else current.changes.set(after.id, change);\n current.rows = [...rows.filter((row) => row.id !== after.id), after];\n trim();\n\n return after;\n };\n\n const dirty = (id: string, dueAt: number, progress = false, progressKey?: string) => {\n Schema.decodeSync(LaneId)(id);\n Schema.decodeSync(Schema.Finite)(dueAt);\n const row = read().find((row) => row.id === id);\n const earliest = Math.min(current.deadlines.get(id) ?? dueAt, dueAt);\n\n if (current.frame !== undefined) current.deadlines.set(id, earliest);\n\n return set(\n DueLane.make({\n id,\n revision: row === undefined ? 1 : row.revision + Number(progress),\n dueAt:\n row === undefined || progress\n ? earliest\n : Math.max(row.notBefore, Math.min(row.dueAt ?? Infinity, earliest)),\n state:\n progress || (row?.stalls ?? 0) < MaximumNoProgressRearms\n ? \"pending\"\n : (row?.state ?? \"pending\"),\n stalls: progress ? 0 : (row?.stalls ?? 0),\n notBefore: progress ? 0 : (row?.notBefore ?? 0),\n reported: progress ? 0 : (row?.reported ?? 0),\n progressKey: progressKey ?? row?.progressKey ?? null,\n }),\n );\n };\n\n /** A strictly increasing source cursor; old or repeated notices cannot renew a budget. */\n const progress = (id: string, dueAt: number, cursor: bigint) => {\n Schema.decodeSync(Schema.BigInt.check(Schema.isGreaterThanOrEqualToBigInt(0n)))(cursor);\n const previous = read().find((row) => row.id === id)?.progressKey;\n\n if (previous !== undefined && previous !== null && cursor <= BigInt(previous)) return false;\n dirty(id, dueAt, true, String(cursor));\n\n return true;\n };\n\n /** One initial native discovery wave; host lanes always require explicit enrollment. */\n const register = (id: string) => {\n if (read().some((row) => row.id === id)) return;\n set(\n DueLane.make({\n id,\n revision: 0,\n dueAt: 0,\n stalls: 0,\n progressKey: null,\n notBefore: 0,\n state: \"pending\",\n reported: 0,\n }),\n );\n };\n\n /** This transaction must commit before fallible work: never defer a debit across a wave. */\n const claim = (lane: DueLane, nowMillis: number, native = false) => {\n const row = read().find((row) => row.id === lane.id);\n\n if (\n row === undefined ||\n row.revision !== lane.revision ||\n row.dueAt === null ||\n !(row.dueAt <= nowMillis || (native && row.notBefore <= nowMillis))\n )\n return;\n const stalls = Math.min(row.stalls + 1, MaximumNoProgressRearms);\n\n const notBefore =\n nowMillis +\n (stalls >= MaximumNoProgressRearms\n ? ParkedRetryMillis\n : Math.min(60_000, MinimumRetryMillis * 2 ** row.stalls));\n\n return set(\n DueLane.make({\n ...row,\n stalls,\n notBefore,\n dueAt: notBefore,\n state: stalls >= MaximumNoProgressRearms ? \"parked\" : \"pending\",\n }),\n );\n };\n\n const complete = (lane: DueLane, dueAt: number | null) => {\n Schema.decodeSync(Deadline)(dueAt);\n const row = read().find((row) => row.id === lane.id);\n\n if (row === undefined || row.revision !== lane.revision) return;\n\n const after = DueLane.make({\n ...row,\n dueAt: dueAt === null ? null : Math.max(dueAt, row.notBefore),\n state: dueAt === null ? \"idle\" : row.stalls >= MaximumNoProgressRearms ? \"parked\" : \"pending\",\n stalls: dueAt === null ? 0 : row.stalls,\n notBefore: dueAt === null ? 0 : row.notBefore,\n reported: dueAt === null ? 0 : row.reported,\n });\n\n return set(DueLane.make({ ...after, revision: row.revision + 1 }));\n };\n\n /** Native checkpoints already fence their own dirty/processed generation. */\n const checkpointNative = (dueAt: number | null) => {\n Schema.decodeSync(Deadline)(dueAt);\n const rows = read();\n const row = rows.find((row) => row.id === Native);\n\n if (row === undefined) return;\n const publication = rows.find((row) => row.id === Publication);\n\n set(\n DueLane.make({\n ...row,\n dueAt:\n dueAt === null || publication?.state === \"parked\" ? null : Math.max(dueAt, row.notBefore),\n state:\n dueAt === null ? \"idle\" : row.stalls >= MaximumNoProgressRearms ? \"parked\" : \"pending\",\n stalls: dueAt === null ? 0 : row.stalls,\n notBefore: dueAt === null ? 0 : row.notBefore,\n reported: dueAt === null ? 0 : row.reported,\n }),\n );\n };\n\n const takeParkedReports = () =>\n read()\n .filter((row) => row.state === \"parked\" && row.reported === 0)\n .map((row) => set(DueLane.make({ ...row, reported: 1 })));\n\n return {\n initialize,\n withView,\n // The host begins inside its transaction, flushes before commit, and finishes after settlement.\n begin,\n flush,\n finish,\n transaction,\n read,\n dirty,\n progress,\n register,\n claim,\n complete,\n checkpointNative,\n takeParkedReports,\n };\n};\n\nexport const next = (rows: ReadonlyArray<DueLane>) =>\n rows.reduce((next, row) => Math.min(next, row.dueAt ?? Infinity), Infinity);\n","import { CurrentNativeSource } from \"@yielded/agent-storage-cloudflare/port-routing\";\nimport { type DurableBindingFailure } from \"@yielded/agent/agent-registration\";\nimport {\n DurableAgentRuntime,\n DurableRuntimeConfig,\n isolateRecovery,\n RecoveryBlocked,\n RecoveryFailure,\n type DurableWorkerFailure,\n type RecoveryReport,\n RecoverySweepResult,\n} from \"@yielded/agent/durable-agent-runtime\";\nimport { ThreadId, SubmissionId } from \"@yielded/agent/identifiers\";\nimport {\n AbortIntentRequest,\n SubmissionLedger,\n type SubmissionWorkItem,\n} from \"@yielded/agent/submission-ledger\";\nimport {\n ThreadProjectionMaintenance,\n type ThreadProjectionError,\n} from \"@yielded/agent/thread-projection-maintenance\";\nimport { WakeScheduler } from \"@yielded/agent/wake-scheduler\";\nimport {\n Cause,\n Clock,\n Context,\n DateTime,\n Deferred,\n Effect,\n ErrorReporter,\n Exit,\n Fiber,\n Layer,\n Option,\n Random,\n Ref,\n Result,\n Scheduler,\n Schema,\n Scope,\n Semaphore,\n Stream,\n Struct,\n} from \"effect\";\nimport { DurableObjectAlarm, DurableObjectStorage } from \"effect-cf\";\nimport { SqlClient } from \"effect/sql/SqlClient\";\nimport { SqlError, UnknownError } from \"effect/sql/SqlError\";\n\nimport { DurableObjectContext } from \"./CloudflareBindings.ts\";\nimport { AuxiliaryDispatchMillis, CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport { safeCauseMessage } from \"./internal/boundary.ts\";\nimport * as DueQueue from \"./internal/due-queue.ts\";\n\n/**\n * The maintenance queue owns lease expiry, settlement, retries and dirty generations.\n * Its manual effect-cf alarm shares the native slot with other registered alarms.\n *\n * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable\n * maintenance generation and a committed alarm. Stable externally-driven waits may be\n * nonterminal without retaining an alarm; their resolving mutation advances the generation and\n * restores the alarm atomically.\n */\n\n/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */\nexport class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(\n \"DurableAlarmError\",\n {\n operation: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/** Content-free operational notice: pending work now retries at the hourly ceiling. */\nclass MaintenanceRetryParked extends Schema.TaggedError<MaintenanceRetryParked>()(\n \"MaintenanceRetryParked\",\n { lane: Schema.String, retryAfterMillis: Schema.Number },\n) {}\n\nconst alarmFailure =\n (operation: string) =>\n (cause: unknown): DurableAlarmError =>\n DurableAlarmError.make({\n operation,\n message: safeCauseMessage(cause, \"The Cloudflare alarm API failed without a diagnostic\"),\n cause,\n });\n\n// SQL and raw KV/alarm operations share one physical SQLite transaction. Reserve its\n// connection for each short storage operation, never around a mutation or snapshot body.\nconst makeStorageEffect = Effect.gen(function* () {\n const sql = yield* SqlClient;\n const { ctx } = yield* DurableObjectContext;\n const invalidate = Effect.sync(() => DueQueue.invalidate(ctx.storage));\n\n return <A, R>(operation: string, execute: Effect.Effect<A, DurableAlarmError, R>) =>\n Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {\n const body = Effect.uninterruptible(execute);\n\n // Explicit source transactions own the view through flush and rollback.\n // Unwrapped host SQL keeps eager writes and discards speculative cache rows.\n if (current._tag === \"Some\") {\n if (DueQueue.buffering(ctx.storage)) return body;\n\n return body.pipe(Effect.ensuring(invalidate));\n }\n\n return Effect.scoped(\n Effect.andThen(\n sql.reserve.pipe(Effect.mapError(alarmFailure(operation))),\n body.pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? invalidate : Effect.void))),\n ),\n );\n });\n});\n\nconst makeStorageOperation = Effect.map(\n makeStorageEffect,\n (run) =>\n <A>(operation: string, execute: () => Promise<A>) =>\n run(operation, Effect.tryPromise({ try: execute, catch: alarmFailure(operation) })),\n);\n\n/** One manual alarm for the entire consumer-owned maintenance queue. */\nexport class ThreadMaintenanceAlarm extends DurableObjectAlarm.Tag<ThreadMaintenanceAlarm>()(\n \"@yielded/agent/thread-maintenance\",\n { \"@yielded/agent/thread-maintenance\": { payload: Schema.Null, lifecycle: \"manual\" } },\n) {}\n\nconst maintenanceAlarmRef = { tag: \"@yielded/agent/thread-maintenance\", id: \"queue\" } as const;\n\nconst maintenanceAlarmInput = (deadline: number) => ({\n ...maintenanceAlarmRef,\n payload: null,\n runAt: DateTime.makeUnsafe(deadline),\n});\n\n/** Named maintenance checkpoint; the library owns the shared native alarm slot. */\nexport class DurableAlarmService extends Context.Service<\n DurableAlarmService,\n {\n readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /** Queue-aware promptness hint; idle queues stay idle and retry floors survive. */\n readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;\n /** Coalesce droppable inline hints without delaying committed deadlines or their delivery. */\n readonly withHintsDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n readonly cancel: Effect.Effect<void, DurableAlarmError>;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableAlarmService\") {\n static readonly layer = Layer.effect(DurableAlarmService)(\n Effect.gen(function* () {\n const alarms = yield* ThreadMaintenanceAlarm;\n const { ctx } = yield* DurableObjectContext;\n const run = yield* makeStorageEffect;\n const inlineWork = yield* Ref.make(0);\n\n const wrap = <A, E, R>(operation: string, effect: Effect.Effect<A, E, R>) =>\n run(operation, effect.pipe(Effect.mapError(alarmFailure(operation))));\n\n return DurableAlarmService.of({\n scheduled: wrap(\n \"read maintenance checkpoint\",\n alarms.getAlarmStatus(maintenanceAlarmRef),\n ).pipe(\n Effect.map((at) =>\n at === undefined ? Option.none() : Option.some(DateTime.toEpochMillis(at.runAt)),\n ),\n ),\n scheduleAt: (at) =>\n wrap(\"replace maintenance checkpoint\", alarms.scheduleAlarm(maintenanceAlarmInput(at))),\n ensureScheduledBy: (at) =>\n wrap(\n \"advance maintenance checkpoint\",\n alarms.scheduleAlarmEarlier(maintenanceAlarmInput(at)),\n ),\n scheduleNow: Ref.get(inlineWork).pipe(\n Effect.flatMap((active) =>\n active > 0\n ? Effect.void\n : wrap(\n \"hint maintenance checkpoint\",\n alarms.transaction((tx) =>\n Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis;\n const next = DueQueue.next(DueQueue.make(ctx.storage).read());\n\n if (Number.isFinite(next))\n yield* tx.scheduleAlarmEarlier(maintenanceAlarmInput(Math.max(now, next)));\n }),\n ),\n ),\n ),\n ),\n withHintsDeferred: (body) =>\n Effect.acquireUseRelease(\n Ref.update(inlineWork, (active) => active + 1),\n () => body,\n () => Ref.update(inlineWork, (active) => active - 1),\n ),\n cancel: wrap(\"cancel maintenance checkpoint\", alarms.cancelAlarm(maintenanceAlarmRef)),\n });\n }),\n );\n}\n\ntype CheckpointIntent = {\n readonly at: (deadline: number) => void;\n readonly earlier: (deadline: number) => void;\n readonly cancel: () => void;\n};\n\ntype MaintenanceStorage = Pick<DurableObjectTransaction, \"get\" | \"put\" | \"delete\">;\ntype MaintenanceCheckpoint = {\n readonly mutations: Parameters<\n Parameters<ThreadMaintenanceAlarm[\"Service\"][\"transaction\"]>[0]\n >[0];\n readonly requireActive: Effect.Effect<void, DurableAlarmError>;\n};\n\nconst CurrentCheckpoint = Context.Reference<MaintenanceCheckpoint | undefined>(\n \"@yielded/agent/cloudflare/CurrentCheckpoint\",\n { defaultValue: () => undefined },\n);\n\n/** One source transaction owns queue intent and the library checkpoint through commit. */\nconst makeAlarmOperation = Effect.gen(function* () {\n const alarms = yield* ThreadMaintenanceAlarm;\n const sql = yield* SqlClient;\n const { ctx } = yield* DurableObjectContext;\n const queue = DueQueue.make(ctx.storage);\n\n const transaction: SqlClient[\"withTransaction\"] = (body) =>\n alarms\n .transaction(\n (mutations) =>\n Effect.withFiber((owner) => {\n let active = true;\n\n const requireActive = Effect.withFiber((fiber) =>\n active && fiber === owner\n ? Effect.void\n : Effect.fail(\n DurableAlarmError.make({\n operation: \"enroll maintenance source\",\n message: \"Source intent requires its active transaction callback's fiber\",\n }),\n ),\n );\n\n return body.pipe(\n Effect.provideService(CurrentCheckpoint, { mutations, requireActive }),\n Effect.ensuring(\n Effect.sync(() => {\n active = false;\n }),\n ),\n );\n }),\n { sqlClient: sql },\n )\n .pipe(\n Effect.mapError((cause) =>\n cause instanceof DurableObjectStorage.StorageOperationError\n ? SqlError.make({\n reason: UnknownError.make({\n operation: \"commit maintenance checkpoint\",\n message: \"Source facts and maintenance checkpoint could not commit\",\n cause,\n }),\n })\n : cause,\n ),\n );\n\n const withTransaction = <A, E, R>(body: Effect.Effect<A, E, R>) =>\n Effect.flatMap(Effect.serviceOption(sql.transactionService), (ambient) => {\n if (ambient._tag === \"Some\" && !DueQueue.ownsTransaction(ctx.storage, ambient.value[1]))\n return Effect.fail(\n SqlError.make({\n reason: UnknownError.make({\n operation: \"begin maintenance source transaction\",\n message: \"Use ThreadMutationGate.withTransaction at the outermost source transaction\",\n cause: new Error(\"Unwrapped SQL transaction cannot own buffered maintenance intent\"),\n }),\n }),\n );\n\n return Effect.uninterruptibleMask((restore) =>\n Effect.suspend(() => {\n let frame: ReturnType<typeof queue.begin> | undefined;\n\n return transaction(\n Effect.flatMap(Effect.serviceOption(sql.transactionService), (transaction) =>\n Effect.sync(() => {\n if (transaction._tag === \"None\") throw new Error(\"SQL transaction unavailable\");\n frame = queue.begin(transaction.value[1]);\n }),\n ).pipe(\n Effect.andThen(restore(body)),\n Effect.tap(() =>\n Effect.try({\n try: () => {\n if (frame !== undefined) queue.flush(frame);\n },\n catch: (cause) =>\n SqlError.make({\n reason: UnknownError.make({\n cause,\n operation: \"flush maintenance due queue\",\n message: \"Maintenance intent could not commit\",\n }),\n }),\n }),\n ),\n ),\n ).pipe(\n Effect.onExit((exit) =>\n Effect.sync(() => {\n if (frame !== undefined) queue.finish(frame, Exit.isSuccess(exit));\n }),\n ),\n // A released permit can resume another transaction. Do not auto-yield\n // between the driver's settlement and removing this transaction's frame.\n Effect.provideService(Scheduler.PreventSchedulerYield, true),\n );\n }),\n );\n }).pipe(Effect.provideService(SqlClient, sql));\n\n const run = <A>(\n operation: string,\n execute: (transaction: MaintenanceStorage, checkpoint: CheckpointIntent) => Promise<A>,\n ) => {\n const commit = Effect.flatMap(CurrentCheckpoint, (tx) => {\n if (tx === undefined)\n return Effect.die(new Error(\"Maintenance checkpoint transaction unavailable\"));\n\n return tx.requireActive.pipe(\n Effect.andThen(\n Effect.suspend(() => {\n let checkpoint: ReturnType<DurableObjectAlarm.AlarmScheduler[\"scheduleAlarm\"]> =\n Effect.void;\n\n const intent: CheckpointIntent = {\n at: (at) => {\n checkpoint = tx.mutations.scheduleAlarm(maintenanceAlarmInput(at));\n },\n earlier: (at) => {\n checkpoint = tx.mutations.scheduleAlarmEarlier(maintenanceAlarmInput(at));\n },\n cancel: () => {\n checkpoint = tx.mutations.cancelAlarm(maintenanceAlarmRef);\n },\n };\n\n // The SQL/alarm callback already owns the native transaction; KV uses the same storage.\n return Effect.tryPromise({\n try: () => execute(ctx.storage, intent),\n catch: alarmFailure(operation),\n }).pipe(Effect.tap(() => checkpoint));\n }),\n ),\n );\n });\n\n return Effect.gen(function* () {\n const current = yield* CurrentCheckpoint;\n\n if (current !== undefined) return yield* commit;\n const ambient = yield* Effect.serviceOption(sql.transactionService);\n\n // Preserve eager writes and invalidation for an unwrapped host SQL transaction.\n return yield* ambient._tag === \"Some\" && !DueQueue.buffering(ctx.storage)\n ? transaction(commit).pipe(\n Effect.ensuring(Effect.sync(() => DueQueue.invalidate(ctx.storage))),\n )\n : withTransaction(commit);\n }).pipe(Effect.uninterruptible, Effect.mapError(alarmFailure(operation)));\n };\n\n return { run, withTransaction };\n});\n\nexport class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(\n \"@effect-agent/platform-cloudflare/MaintenancePassReport\",\n)({\n /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */\n phase: Schema.Literals([\"caught-up\", \"actionable\"]),\n /** Recovery decisions and Thread faults observed during this event. */\n recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Head Attempts settled during the event. Joined input may settle with each head. */\n settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */\n alarm: Schema.Literals([\"rearmed\", \"cleared\"]),\n}) {}\n\n/** Fault boundaries around every maintenance-owned durable mutation. */\nexport type ThreadMaintenanceFailpointLocation =\n | \"maintenance:dirty:before\"\n | \"maintenance:dirty:after\"\n | \"maintenance:mutation:armed\"\n | \"maintenance:mutation:finished\"\n | \"maintenance:ensure:before\"\n | \"maintenance:ensure:after\"\n | \"maintenance:begin:before\"\n | \"maintenance:begin:after\"\n | \"maintenance:select:before\"\n | \"maintenance:select:after\"\n | \"maintenance:binding-retry:before\"\n | \"maintenance:binding-retry:after\"\n | \"maintenance:recovery-status:before\"\n | \"maintenance:recovery-status:after\"\n | \"maintenance:retry:before\"\n | \"maintenance:retry:after\"\n | \"maintenance:checkpoint:before\"\n | \"maintenance:checkpoint:after\"\n | \"maintenance:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ThreadMaintenanceFailpointHandler = (\n location: ThreadMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ThreadMaintenanceFailpoint extends Context.Service<\n ThreadMaintenanceFailpoint,\n {\n readonly hit: ThreadMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\n}\n\n/**\n * Durable host publication of canonical records and ledger approval/abort/resolution intents.\n * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery\n * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.\n *\n * `invalidate` and `prepareGeneration` must be bounded local operations.\n * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated\n * calls must preserve partial scan progress. It runs with no source mutation in flight.\n * Use this gate only for publication required before dependent native execution. Independent\n * UI relays and outboxes belong to ThreadHostMaintenance.\n * `drain` performs bounded delivery and returns its next deadline (None when caught up),\n * after persisting receipts and retries. A pending deadline\n * defers runtime recovery/Attempts, allowing committed host publications to drain first.\n * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call\n * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need\n * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.\n */\nexport interface ThreadPublicationService {\n readonly invalidate: Effect.Effect<void, DurableAlarmError>;\n readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;\n readonly drain: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}\n\nconst emptyPublication: ThreadPublicationService = {\n invalidate: Effect.void,\n prepareGeneration: () => Effect.void,\n drain: Effect.succeed(Option.none()),\n};\n\n/** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */\nexport class ThreadPublication extends Context.Service<\n ThreadPublication,\n ThreadPublicationService\n>()(\"@effect-agent/platform-cloudflare/ThreadPublication\") {\n static readonly layer = Layer.succeed(this)(emptyPublication);\n}\n\n// Only the actual empty default can waive required publication. Missing or replaced\n// services retain the barrier, including hosts that rebuild maintenance Layers.\nconst requiresPublication = Effect.map(\n Effect.serviceOption(ThreadPublication),\n (service) => Option.isNone(service) || service.value !== emptyPublication,\n);\n\n/**\n * Host-assembled native message recovery. Preparation is a bounded local selection; the\n * driver bounds each actual Claim and persists its timeout/retry before `run` returns.\n * The alarm must not add a timer starting at selection: Claim setup and retry commits belong\n * to the driver. The prepared allowance decides only whether a wave fits this event.\n */\nexport const ThreadMessageDelivery = Context.Reference<{\n readonly prepare: Effect.Effect<\n {\n readonly timeoutMillis: number;\n readonly run: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n },\n DurableAlarmError\n >;\n}>(\"@effect-agent/platform-cloudflare/ThreadMessageDelivery\", {\n defaultValue: () => ({\n prepare: Effect.succeed({ timeoutMillis: 1, run: Effect.succeed(Option.none()) }),\n }),\n});\n\n/**\n * One explicitly scheduled application obligation. IDs are stable and unique within the\n * physical Object; the `@yielded/agent:` prefix is reserved. There is no initial host wave.\n * Producers enroll only affected IDs through ThreadMutationGate.withMutation({ lanes })\n * or schedule(id, dueAt). A lane returns its next epoch-millisecond deadline (None = idle)\n * with its finite wave, after persisting claims, receipts and retries. No deadline callback\n * or polling is used. A racing producer keeps its newer revision due.\n *\n * The 1..300000ms allowance includes selection, dispatch, commits and scoped cleanup.\n * Failed waves retain independent backoff and are not retried in the same event. Delivery\n * remains at least once: persist exact envelopes and deduplicate by domain receipt identity.\n * Hooks never write the alarm slot. Required execution gates belong to ThreadPublication.\n */\nexport interface ThreadHostMaintenanceLane {\n readonly id: string;\n /** Omission runs concurrently with native work. After-native lanes get one due wave\n * after all admitted native Attempts and their scoped cleanup, even on native failure.\n * They share the event deadline and remain inside the maintenance pass permit.\n * Newly enrolled concurrent work yields this phase after scoped cleanup; unfinished\n * waves retain their due revision and domain receipts for the next alarm.\n */\n readonly phase?: \"concurrent\" | \"after-native\";\n readonly dispatchTimeoutMillis: number;\n readonly run: Effect.Effect<Option.Option<number>, DurableAlarmError, Scope.Scope>;\n}\n\n/** Independent lanes share the existing alarm; compose hosts by concatenating their lanes. */\nexport const ThreadHostMaintenance = Context.Reference<{\n readonly lanes: ReadonlyArray<ThreadHostMaintenanceLane>;\n}>(\"@effect-agent/platform-cloudflare/ThreadHostMaintenance\", {\n defaultValue: () => ({ lanes: [] }),\n});\n\n/** @internal Framework handlers are separate from host registrations and their namespace. */\nexport const ThreadNativeMaintenance = Context.Reference<{\n readonly lanes: ReadonlyArray<ThreadHostMaintenanceLane>;\n /** Exact runtime built over a single-Thread placement; never apply to a replacement. */\n readonly singleThreadRuntime?: DurableAgentRuntime[\"Service\"];\n}>(\"@effect-agent/platform-cloudflare/ThreadNativeMaintenance\", {\n defaultValue: () => ({ lanes: [] }),\n});\n\n/** @internal Required host publication only; native lifecycle facts use a maintenance lane. */\nexport const publishCommitted = Effect.gen(function* () {\n const publication = yield* ThreadPublication;\n\n yield* publication.invalidate;\n yield* publication.drain;\n}).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\"Thread publication deferred after source commit\", cause),\n ),\n);\n\nconst MaintenanceGeneration = Schema.BigIntFromString.check(\n Schema.isGreaterThanOrEqualToBigInt(0n),\n);\n\n/** A committed recovery transition for one affected Submission; never a Settlement. */\nexport class ThreadRecoveryFaultEvent extends Schema.Class<ThreadRecoveryFaultEvent>(\n \"@effect-agent/platform-cloudflare/ThreadRecoveryFaultEvent\",\n)({\n schemaVersion: Schema.Literal(1),\n /** Monotonic within the physical Object; retained unchanged on delivery retries. */\n sequence: MaintenanceGeneration,\n transition: Schema.Literals([\"created\", \"changed\", \"cleared\"]),\n threadId: ThreadId,\n submissionId: SubmissionId,\n occurredAt: Schema.Finite,\n firstFailedAt: Schema.Finite,\n /** The current failure, or the last failure for a cleared event. */\n failure: RecoveryFailure,\n}) {}\n\nconst recoveryEventKey = (sequence: bigint) => `effect-agent:thread-recovery-event:v1:${sequence}`;\nconst encodeRecoveryEvent = Schema.encodeSync(ThreadRecoveryFaultEvent);\nconst decodeRecoveryEvent = Schema.decodeUnknownSync(ThreadRecoveryFaultEvent);\n\n/**\n * Ordered, at-least-once delivery through the existing host maintenance lane. Return only\n * after durably applying the event or retaining it in a host outbox. Deduplicate by physical\n * Object and sequence; callbacks may repeat after interruption. This is a trusted host hook,\n * not pre-authorized UI data: the host owns recipient authorization and safe presentation.\n * Capture services in the Layer. Do not call producers or write the raw alarm slot.\n * Without this service, maintenance acknowledges and discards transitions. Install the\n * handler before the first maintenance pass if the application needs that event stream.\n */\nexport class ThreadRecoveryEvents extends Context.Service<\n ThreadRecoveryEvents,\n { readonly publish: (event: ThreadRecoveryFaultEvent) => Effect.Effect<void, DurableAlarmError> }\n>()(\"@effect-agent/platform-cloudflare/ThreadRecoveryEvents\") {}\n\nclass BindingWait extends Schema.Class<BindingWait>(\"BindingWait\")({\n threadId: ThreadId,\n submissionId: SubmissionId,\n reportedAt: Schema.Finite,\n}) {}\n\n/**\n * A durable observation of blocked recovery, independent of the execution journal. This is\n * neither a Settlement nor proof that external effects did not happen. A successful recovery\n * sweep clears it; repair must preserve canonical history and the original admission identity.\n */\nclass ThreadRecoveryFault extends Schema.Class<ThreadRecoveryFault>(\n \"@effect-agent/platform-cloudflare/ThreadRecoveryFault\",\n)({\n schemaVersion: Schema.Literal(1),\n threadId: ThreadId,\n firstFailedAt: Schema.Finite,\n lastFailedAt: Schema.Finite,\n /** Earliest automatic recovery retry; new admissions do not erase this deadline. */\n retryAt: Schema.Finite,\n /** Saturates at 2^31 - 1; one observation per Thread per recovery sweep. */\n attempts: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2_147_483_647)),\n failure: RecoveryFailure,\n /** Individually retained recipients survive settlement until their clear commits. */\n recipientCount: Schema.optionalKey(Schema.Natural),\n}) {}\n\nconst recoveryFaultKey = (threadId: ThreadId) =>\n `effect-agent:thread-recovery-fault:v1:${threadId}`;\n\nconst decodeRecoveryFaultValue = Schema.decodeUnknownSync(ThreadRecoveryFault);\n\nconst decodeRecoveryFault = (threadId: ThreadId, encoded: unknown) => {\n const fault = decodeRecoveryFaultValue(encoded);\n\n if (fault.threadId !== threadId) throw new Error(\"Recovery status does not match its Thread key\");\n\n return fault;\n};\n\nconst encodeRecoveryFault = Schema.encodeSync(ThreadRecoveryFault);\nconst sameRecoveryFailure = Schema.toEquivalence(RecoveryFailure);\nconst decodeRecoveryRecipient = Schema.decodeUnknownSync(SubmissionId);\nconst encodeRecoveryRecipient = Schema.encodeSync(SubmissionId);\n\nconst recoveryRecipientKey = (threadId: ThreadId, index: number) =>\n `effect-agent:recovery-recipient:v1:${threadId.length}:${threadId}:${index}`;\n\nconst recoveryRecipientKeys = (fault: ThreadRecoveryFault, start: number) =>\n Array.from({ length: Math.min(128, (fault.recipientCount ?? 0) - start) }, (_, offset) =>\n recoveryRecipientKey(fault.threadId, start + offset),\n );\n\nconst readRecoveryRecipients = async (\n storage: Pick<DurableObjectTransaction, \"get\">,\n fault: ThreadRecoveryFault,\n): Promise<Array<SubmissionId>> => {\n const ids: Array<SubmissionId> = [];\n\n for (let start = 0; start < (fault.recipientCount ?? 0); start += 128) {\n const keys = recoveryRecipientKeys(fault, start);\n const values = await storage.get(keys);\n\n for (const key of keys) ids.push(decodeRecoveryRecipient(values.get(key)));\n }\n\n return ids;\n};\n\nconst appendRecoveryRecipients = async (\n transaction: MaintenanceStorage,\n threadId: ThreadId,\n count: number,\n added: ReadonlyArray<SubmissionId>,\n) => {\n for (let start = 0; start < added.length; start += 128)\n await transaction.put(\n Object.fromEntries(\n added\n .slice(start, start + 128)\n .map((id, offset) => [\n recoveryRecipientKey(threadId, count + start + offset),\n encodeRecoveryRecipient(id),\n ]),\n ),\n );\n};\n\nconst recoveryEvent = (\n fault: ThreadRecoveryFault,\n submissionId: SubmissionId,\n transition: ThreadRecoveryFaultEvent[\"transition\"],\n occurredAt: number,\n): Omit<ThreadRecoveryFaultEvent, \"sequence\"> => ({\n schemaVersion: 1,\n transition,\n threadId: fault.threadId,\n submissionId,\n occurredAt,\n firstFailedAt: fault.firstFailedAt,\n failure: fault.failure,\n});\n\ninterface NativePassResult {\n readonly phase: \"caught-up\" | \"actionable\";\n readonly nonterminal: number;\n readonly nextAttemptAt: number | undefined;\n readonly dispatched?: boolean;\n}\n\n/** Independent Threads share bounded native slots; one active head per Thread. */\ninterface NativeDispatch {\n readonly scope: Scope.Scope;\n readonly active: Map<ThreadId, Fiber.Fiber<number, MaintenancePassFailure>>;\n readonly deferred: Set<ThreadId>;\n dispatched: number;\n settled: number;\n progressed: boolean;\n needsCheckpoint: boolean;\n generation?: bigint;\n sourceRevision?: number;\n scanGeneration?: bigint;\n scanRevision?: number;\n}\n\n/** Post-native delivery shares a finite connection budget across independent host lanes. */\nconst afterNativeDispatchConcurrency = 2;\n\n/** Event-local observations only; durable ingress keeps racing mutations dirty. */\ninterface NativeRecovery {\n readonly queue: Deferred.Deferred<ReadonlyArray<ThreadId>>;\n readonly pending: Set<ThreadId>;\n readonly loaded: Set<ThreadId>;\n readonly reports: Map<SubmissionId, RecoveryReport>;\n readonly faults: Map<ThreadId, ThreadRecoveryFault>;\n readonly recipients: Map<ThreadId, ReadonlySet<SubmissionId>>;\n observation?: {\n readonly generation: bigint;\n readonly activeAtStart: number;\n };\n started: boolean;\n needsCheckpoint: boolean;\n recovered: number;\n repaired: boolean;\n discoveryPending: boolean;\n retryAtMillis?: number;\n}\n\nconst NativeWorkCursor = Schema.Struct({\n threadId: ThreadId,\n cursor: Schema.NonEmptyString.check(Schema.isMaxLength(8192)),\n});\n\nconst workCursorKey = (threadId: ThreadId) => `effect-agent:work-recovery-cursor:v1:${threadId}`;\n\ninterface MaintenanceObservation {\n readonly queue: Map<string, DueQueue.DueLane>;\n readonly charged: Map<string, number>;\n /** Initially available or serviced revisions; active producers are only failure observations. */\n readonly available: Map<string, number>;\n generation?: bigint;\n nativeOnly: boolean;\n}\n\nclass MaintenanceRetry extends Schema.Class<MaintenanceRetry>(\"MaintenanceRetry\")({\n generation: MaintenanceGeneration,\n notBefore: Schema.Finite,\n nativeOnly: Schema.Boolean,\n stalls: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(30)),\n}) {}\n\n/** Versioned, platform-private maintenance state stored through Durable Object KV. */\nclass ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ThreadMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** One physical-owner cursor; old single-lane records need no conversion. */\n lastServedThreadId: Schema.optionalKey(ThreadId),\n /** Rotate old recovery independently of dispatch, including after eviction or timeout. */\n lastRecoveredThreadId: Schema.optionalKey(ThreadId),\n /** Rotate bounded post-native admission across full events and Object eviction. */\n lastAfterNativeLaneId: Schema.optionalKey(DueQueue.LaneId),\n bindingRegistryKey: Schema.optionalKey(Schema.String),\n bindingWaits: Schema.optionalKey(Schema.Array(BindingWait)),\n recoveryEventSequence: Schema.optionalKey(MaintenanceGeneration),\n recoveryEventAcknowledged: Schema.optionalKey(MaintenanceGeneration),\n /** Absent on older records. A newer mutation makes this retry obsolete. */\n retry: Schema.optionalKey(MaintenanceRetry),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:thread-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);\n\nconst hasRecoveryEvents = (state: ThreadMaintenanceState) =>\n (state.recoveryEventSequence ?? 0n) > (state.recoveryEventAcknowledged ?? 0n);\n\nconst initialMaintenanceState = (): ThreadMaintenanceState =>\n ThreadMaintenanceState.make({\n schemaVersion: 1,\n // Bootstrap Objects created by the pre-generation release without scanning the ledger in\n // the constructor. One useful pass classifies and acknowledges any existing obligation.\n dirty: 1n,\n processed: 0n,\n nonterminal: 0,\n });\n\nconst readMaintenanceState = async (\n transaction: Pick<DurableObjectTransaction, \"get\">,\n): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\n\n return encoded === undefined\n ? { state: initialMaintenanceState(), initialized: false }\n : { state: decodeMaintenanceState(encoded), initialized: true };\n};\n\nconst stableExternalWait = (\n snapshot: SubmissionWorkItem,\n reports: ReadonlyMap<string, RecoveryReport>,\n): boolean => {\n const report = reports.get(snapshot.submissionId);\n const decision = report?.decision._tag;\n\n // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.\n if (decision === \"SettleAborted\") return false;\n switch (snapshot.state) {\n case \"suspended\":\n case \"joined\":\n return true;\n case \"unknown\":\n return report?.disposition === \"unknown\";\n case \"admitted\":\n return reports.get(snapshot.submissionId)?.decision._tag === \"AwaitParentEstablishment\";\n case \"input-applied\":\n case \"joining\":\n case \"ready\":\n case \"settled\":\n return false;\n }\n};\n\n/**\n * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.\n * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance\n * Layers must reuse that instance; a second gate cannot observe the native producers' activity.\n */\nconst CurrentMutationLanes = Context.Reference<ReadonlyArray<string>>(\n \"@effect-agent/platform-cloudflare/CurrentMutationLanes\",\n {\n defaultValue: () => [],\n },\n);\n\n// Source changes made by this pass are certified after its Attempts join. External\n// producers still advance the dirty generation and fence that certification.\nexport class ThreadMutationGate extends Context.Service<\n ThreadMutationGate,\n {\n /** Commit source facts and their scheduling intent together. Mutate from this callback's\n * fiber, or use an explicit child transaction. The flush runs before native commit;\n * failed or interrupted transactions discard their queue view. */\n readonly withTransaction: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | SqlError, R>;\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n /**\n * Call outside SQL transactions so prearming commits before the body runs.\n * Native admission, approval, abort and unknown resolution keep the default true.\n * Host producers use false and name only the lanes for which they create work.\n * Receipt-only bookkeeping with no new obligation names no lanes. Enrollment preserves\n * a pending retry budget; idle completion or actual source progress replenishes it.\n * Actual new work must record that progress in its source transaction, so a commit\n * after parking cannot be stranded by eviction before this body returns.\n */\n options?: {\n readonly invalidatesRecovery?: boolean;\n readonly lanes?: ReadonlyArray<string>;\n },\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n /** Enroll a known lane without accelerating its retry floor. A strictly increasing\n * source cursor replenishes its budget; equal/older notices are replayed hints.\n * Cursors identify committed source facts, never clocks, attempts or retry counters.\n * Local sources call inside their source transaction. Remote sources retain the cursor\n * notice with their work and retry delivery here; this call atomically accepts that\n * notice and its alarm. Prearming alone cannot fence a later remote commit. */\n readonly schedule: (\n id: string,\n dueAt: number,\n progressCursor?: bigint,\n ) => Effect.Effect<void, DurableAlarmError>;\n /** Record an actual new fact inside its local source SQL transaction. The source\n * transaction owns duplicate detection. Claims, lease renewals and retries are not progress.\n * Also enrolls the lanes selected by this producer's enclosing withMutation boundary. */\n readonly recordProgress: (\n lanes: ReadonlyArray<string>,\n ) => Effect.Effect<void, DurableAlarmError>;\n /** In-incarnation notification; the durable due queue is the recovery authority. */\n readonly activeLanes: Effect.Effect<ReadonlySet<string>>;\n readonly revision: Effect.Effect<number>;\n readonly awaitChange: (revision: number) => Effect.Effect<void>;\n readonly withSnapshot: <A, E, R>(\n body: (active: number) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/internal/ThreadMutationGate\") {\n static readonly layer = Layer.effect(this)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const sql = yield* SqlClient;\n const dueQueue = DueQueue.make(ctx.storage);\n\n const config = yield* CloudflareDurableRuntimeConfig;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n // A fresh incarnation has no live mutations; durable generations survive eviction.\n const activeMutations = yield* Ref.make(0);\n const activeLanes = new Map<string, number>();\n const generationGate = yield* Semaphore.make(1);\n let revision = 0;\n let changed = yield* Deferred.make<void>();\n\n const notify = Effect.gen(function* () {\n const previous = changed;\n\n changed = yield* Deferred.make<void>();\n revision++;\n yield* Deferred.succeed(previous, undefined);\n });\n\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n const { run: runAlarmTransaction, withTransaction } = yield* makeAlarmOperation;\n\n const validateSourceBoundary = Effect.flatMap(\n Effect.serviceOption(sql.transactionService),\n (current) =>\n current._tag === \"Some\" &&\n DueQueue.buffering(ctx.storage) &&\n !DueQueue.ownsTransaction(ctx.storage, current.value[1])\n ? Effect.fail(\n DurableAlarmError.make({\n operation: \"enroll maintenance source\",\n message: \"Nested source scheduling requires ThreadMutationGate.withTransaction\",\n }),\n )\n : Effect.void,\n );\n\n yield* runTransaction(\"initialize maintenance due queue\", async () => {\n dueQueue.initialize();\n dueQueue.register(DueQueue.Native);\n });\n\n const schedule = Effect.fnUntraced(function* (\n id: string,\n dueAt: number,\n progressCursor?: bigint,\n ) {\n yield* validateSourceBoundary;\n const now = yield* Clock.currentTimeMillis;\n\n const enroll = async (transaction: MaintenanceStorage, checkpoint: CheckpointIntent) => {\n if (progressCursor === undefined) dueQueue.dirty(id, dueAt);\n else if (\n dueQueue.progress(id, dueAt, progressCursor) &&\n (id === DueQueue.Native || id === DueQueue.Publication)\n ) {\n // Required publication is progress for its dependent native execution too.\n if (id === DueQueue.Publication) dueQueue.dirty(DueQueue.Native, dueAt, true);\n const { state } = await readMaintenanceState(transaction);\n\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({\n ...Struct.omit(state, [\"retry\"]),\n dirty: state.dirty + 1n,\n }),\n ),\n );\n }\n const next = DueQueue.next(dueQueue.read());\n\n if (Number.isFinite(next)) checkpoint.earlier(Math.max(next, now + minimumAlarmDelay));\n };\n\n yield* runAlarmTransaction(\"schedule maintenance lane\", enroll);\n yield* notify;\n });\n\n const beginMutation = Effect.fnUntraced(function* (\n invalidatesRecovery: boolean,\n lanes: ReadonlyArray<string>,\n ) {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n const nativeSource = yield* CurrentNativeSource;\n const publicationRequired = yield* requiresPublication;\n\n if (invalidatesRecovery || lanes.length > 0)\n yield* runAlarmTransaction(\n \"advance maintenance generation\",\n async (transaction, checkpoint) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (invalidatesRecovery) {\n dueQueue.dirty(DueQueue.Native, now);\n if (publicationRequired) dueQueue.dirty(DueQueue.Publication, now);\n }\n // Enrollment is a crash fallback, not evidence that the body committed.\n for (const id of lanes) dueQueue.dirty(id, now, false);\n\n if (!initialized || (invalidatesRecovery && !nativeSource))\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({\n ...state,\n dirty: state.dirty + (invalidatesRecovery && !nativeSource ? 1n : 0n),\n }),\n ),\n );\n // The earliest configured retry bounds a newly actionable mutation without relying\n // on its best-effort immediate wake hint.\n const deadline = DueQueue.next(dueQueue.read());\n\n if (Number.isFinite(deadline))\n checkpoint.earlier(Math.max(deadline, now + minimumAlarmDelay));\n },\n );\n yield* failpoint.hit(\"maintenance:dirty:after\");\n yield* Ref.update(activeMutations, (active) => active + 1);\n\n const enrolled = new Set([\n ...lanes,\n ...(invalidatesRecovery\n ? [DueQueue.Native, ...(publicationRequired ? [DueQueue.Publication] : [])]\n : []),\n ]);\n\n for (const id of enrolled) activeLanes.set(id, (activeLanes.get(id) ?? 0) + 1);\n\n return enrolled;\n });\n\n const releaseLanes = (enrolled: Set<string>, committed = false) =>\n Effect.sync(() => {\n for (const id of enrolled) {\n if (committed && (id === DueQueue.Native || id === DueQueue.Publication)) continue;\n const remaining = (activeLanes.get(id) ?? 1) - 1;\n\n if (remaining === 0) activeLanes.delete(id);\n else activeLanes.set(id, remaining);\n enrolled.delete(id);\n }\n });\n\n const endMutation = (enrolled: Set<string>) =>\n generationGate.withPermit(\n releaseLanes(enrolled).pipe(\n Effect.andThen(Ref.update(activeMutations, (active) => Math.max(0, active - 1))),\n ),\n );\n\n const withMutation = <A, E, R>(\n body: Effect.Effect<A, E, R>,\n options?: {\n readonly invalidatesRecovery?: boolean;\n readonly lanes?: ReadonlyArray<string>;\n },\n ): Effect.Effect<A, E | DurableAlarmError, R> =>\n Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) =>\n // Reject before the generation gate: a prearmer may already be waiting\n // for this caller's SQL connection while holding that gate.\n Option.isSome(current)\n ? Effect.fail(\n DurableAlarmError.make({\n operation: \"prearm maintenance mutation\",\n message:\n \"Run withMutation outside the source SQL transaction so prearming commits first\",\n }),\n )\n : Effect.acquireUseRelease(\n generationGate.withPermit(\n beginMutation(options?.invalidatesRecovery ?? true, options?.lanes ?? []),\n ),\n (enrolled) =>\n failpoint.hit(\"maintenance:mutation:armed\").pipe(\n Effect.andThen(\n Effect.flatMap(CurrentMutationLanes, (current) =>\n body.pipe(\n Effect.provideService(CurrentMutationLanes, [\n ...new Set([...current, ...enrolled]),\n ]),\n ),\n ),\n ),\n // The committed outbox may be claimed by the alarm even while the caller\n // is suspended after commit. This synchronous decrement does not acquire the\n // native snapshot gate: a snapshot may conservatively retain its active count.\n // Native certification keeps its broader guard until the mutation is released.\n Effect.tap(() => releaseLanes(enrolled, true).pipe(Effect.andThen(notify))),\n Effect.tap(() => failpoint.hit(\"maintenance:mutation:finished\")),\n ),\n (enrolled) => endMutation(enrolled).pipe(Effect.andThen(notify)),\n ),\n );\n\n const recordProgress = Effect.fnUntraced(function* (lanes: ReadonlyArray<string>) {\n yield* validateSourceBoundary;\n if (Option.isNone(yield* Effect.serviceOption(sql.transactionService)))\n return yield* DurableAlarmError.make({\n operation: \"record source progress\",\n message: \"Source progress requires its authoritative SQL transaction\",\n });\n const affected = new Set([...lanes, ...(yield* CurrentMutationLanes)]);\n\n if (!(yield* requiresPublication)) affected.delete(DueQueue.Publication);\n\n if (affected.has(DueQueue.Publication)) affected.add(DueQueue.Native);\n\n if (affected.size === 0) return;\n const now = yield* Clock.currentTimeMillis;\n const nativeSource = yield* CurrentNativeSource;\n\n yield* runAlarmTransaction(\n \"record maintenance producer progress\",\n async (transaction, checkpoint) => {\n for (const id of affected) dueQueue.dirty(id, now, true);\n if (affected.has(DueQueue.Native)) {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n // Native progress already belongs to this generation. Persist only\n // initialization, external progress, or the removal of a retry budget.\n if (!initialized || !nativeSource || state.retry !== undefined)\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({\n ...Struct.omit(state, [\"retry\"]),\n dirty: state.dirty + (nativeSource ? 0n : 1n),\n }),\n ),\n );\n }\n checkpoint.earlier(now + minimumAlarmDelay);\n },\n );\n yield* notify;\n });\n\n return ThreadMutationGate.of({\n withTransaction,\n withMutation,\n schedule,\n recordProgress,\n activeLanes: Effect.sync(() => new Set(activeLanes.keys())),\n revision: Effect.sync(() => revision),\n awaitChange: (observed) =>\n Effect.suspend(() => (observed === revision ? Deferred.await(changed) : Effect.void)),\n withSnapshot: (body) =>\n generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),\n });\n }),\n );\n}\n\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError\n | ThreadProjectionError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * One physical event owns native scheduling, auxiliary delivery and final alarm rearming.\n *\n * 1. Prearm before any work. A caught-up native step uses the O(1) generation record without\n * recovery, ledger scans or canonical-history reads.\n * 2. Reconcile before each head Attempt, then checkpoint only the observed generation. A racing\n * producer keeps its generation dirty and immediately eligible. Quiescent native retries\n * retain their durable backoff.\n * 3. Admit one Attempt for a single-Thread runtime, or at most two independent Thread\n * Attempts for a shared host, with one active head per Thread.\n * Keep native and delivery admission open together while finite waves remain active, so\n * fresh replies and abort controls can progress during unrelated cleanup. Close atomically\n * at quiescence, or at the original ten-minute yield deadline, then join admitted waves.\n * 4. Native message delivery retains its driver-owned Claim deadline. Host/backfill waves are\n * bounded independently; incoming native work never restarts or cancels their attempts.\n * Auxiliary failures are reported after the current native opportunity.\n * 5. Close every event resource before the final gated deadline snapshot and alarm decision.\n * The whole event retains one fourteen-minute cooperative timeout.\n */\nexport class ThreadMaintenance extends Context.Service<\n ThreadMaintenance,\n {\n /** One idempotent pass; failures propagate after durably scheduling bounded recovery. */\n readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;\n /**\n * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty\n * generation has an alarm. It never scans the ledger or canonical history.\n */\n readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;\n /**\n * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty\n * generation and arm the alarm in one transaction BEFORE running the caller's mutation.\n * A pass cannot acknowledge while that mutation remains in flight.\n */\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenance\") {\n static readonly layer: Layer.Layer<\n ThreadMaintenance,\n DurableAlarmError,\n | ThreadMutationGate\n | ThreadPublication\n | ThreadProjectionMaintenance\n | DurableAgentRuntime\n | DurableRuntimeConfig\n | SubmissionLedger\n | WakeScheduler\n | DurableAlarmService\n | ThreadMaintenanceAlarm\n | ThreadMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | DurableObjectContext\n | SqlClient\n > = Layer.effect(ThreadMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const recoveryConfig = yield* DurableRuntimeConfig;\n const ledger = yield* SubmissionLedger;\n const wakes = yield* WakeScheduler;\n const hints = yield* DurableAlarmService;\n const alarms = yield* ThreadMaintenanceAlarm;\n const config = yield* CloudflareDurableRuntimeConfig;\n const { ctx } = yield* DurableObjectContext;\n const dueQueue = DueQueue.make(ctx.storage);\n const storage = DurableObjectStorage.fromDurableObjectStorage(ctx.storage);\n const runStorage = yield* makeStorageEffect;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n\n const mutations = yield* ThreadMutationGate;\n const publication = yield* ThreadPublication;\n\n const publicationContext = yield* Effect.context<\n ThreadPublication | DurableObjectContext | SqlClient\n >();\n\n const projection = yield* ThreadProjectionMaintenance;\n const messages = yield* ThreadMessageDelivery;\n const host = yield* ThreadHostMaintenance;\n const framework = yield* ThreadNativeMaintenance;\n\n const nativeDispatchConcurrency = () => (framework.singleThreadRuntime === runtime ? 1 : 2);\n\n for (const lane of host.lanes)\n yield* Schema.decodeEffect(DueQueue.HostLaneId)(lane.id).pipe(\n Effect.mapError(alarmFailure(\"maintenance lane ID\")),\n );\n\n const recoveryEvents = Option.getOrElse(\n yield* Effect.serviceOption(ThreadRecoveryEvents),\n () => ThreadRecoveryEvents.of({ publish: () => Effect.void }),\n );\n\n // Hydrated by the existing maintenance-record reads, never by a status scan. All\n // queue mutations update this hint under the same storage reservation. Eviction\n // reconstructs it in ensureAlarm/beginPass; the durable queue remains authoritative.\n let recoveryEventsPending = false;\n\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n const runTransaction = yield* makeStorageOperation;\n const { run: runAlarmTransaction } = yield* makeAlarmOperation;\n\n const queueSnapshot = runTransaction(\"read maintenance due queue\", async () =>\n dueQueue.read(),\n );\n\n const reportParked = Effect.gen(function* () {\n if (!(yield* queueSnapshot).some((row) => row.state === \"parked\" && row.reported === 0))\n return;\n\n const rows = yield* runTransaction(\"mark parked maintenance reports\", () =>\n dueQueue.transaction(async () => dueQueue.takeParkedReports()),\n );\n\n for (const row of rows) {\n const lane = [\n DueQueue.Native,\n DueQueue.Publication,\n DueQueue.Projection,\n DueQueue.Messages,\n DueQueue.RecoveryEvents,\n DueQueue.Lifecycle,\n ].includes(row.id)\n ? row.id.slice(\"effect-agent:\".length)\n : \"host\";\n\n yield* ErrorReporter.report(\n Cause.fail(\n MaintenanceRetryParked.make({\n lane,\n retryAfterMillis: DueQueue.ParkedRetryMillis,\n }),\n ),\n );\n }\n }).pipe(Effect.catchCause((cause) => ErrorReporter.report(cause)));\n\n yield* runTransaction(\"register native maintenance lanes\", () =>\n dueQueue.transaction(async () => {\n for (const id of [\n DueQueue.Publication,\n DueQueue.Projection,\n DueQueue.Messages,\n ...framework.lanes.map((lane) => lane.id),\n ])\n dueQueue.register(id);\n\n // Earlier releases split this one outbox across start and after-native lanes.\n // Retire only scheduling metadata, retaining revision fencing and domain retries.\n if (framework.lanes.some((lane) => lane.id === DueQueue.Lifecycle)) {\n const start = dueQueue.read().find((row) => row.id === \"effect-agent:lifecycle-start\");\n\n if (start !== undefined && start.dueAt !== null) {\n dueQueue.dirty(DueQueue.Lifecycle, start.dueAt);\n dueQueue.complete(start, null);\n }\n }\n }),\n );\n\n const runQueued = <E, R>(\n selected: DueQueue.DueLane,\n work: Effect.Effect<Option.Option<number>, E, R>,\n observed: MaintenanceObservation,\n yielded?: () => boolean,\n ) => {\n let row = selected;\n let charged = false;\n\n return Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis;\n\n const claimed = yield* runAlarmTransaction(\n \"charge maintenance attempt\",\n async (_transaction, checkpoint) => {\n const claimed = dueQueue.claim(selected, now);\n const next = DueQueue.next(dueQueue.read());\n\n if (Number.isFinite(next)) checkpoint.at(Math.max(now + minimumAlarmDelay, next));\n else checkpoint.cancel();\n\n return claimed;\n },\n );\n\n if (claimed === undefined) return Option.none<number>();\n row = claimed;\n charged = true;\n observed.charged.set(row.id, row.revision);\n // Include mid-pass enrollments in failure rearming if their checkpoint is\n // interrupted. CAS still protects completed waves and racing producers.\n observed.queue.set(row.id, row);\n observed.available.set(row.id, row.revision);\n\n return yield* work;\n }).pipe(\n Effect.onExit((exit) => {\n if (!charged) return Effect.void;\n if (\n yielded?.() === true &&\n Exit.isFailure(exit) &&\n Cause.hasInterruptsOnly(exit.cause)\n ) {\n // A promptness yield is neither completion nor a failed delivery. Keep the\n // exact due revision; pass-level failure rearming must not back off this wave.\n observed.queue.delete(row.id);\n\n return Effect.void;\n }\n\n return mutations\n .withSnapshot(() =>\n Effect.gen(function* () {\n const active = (yield* mutations.activeLanes).has(row.id);\n const now = yield* Clock.currentTimeMillis;\n const failed = Exit.isFailure(exit);\n\n const next = failed\n ? now + backoffDelay(row.stalls, yield* Random.next)\n : Option.getOrNull(exit.value);\n\n const checkpointed = yield* runTransaction(\"checkpoint maintenance lane\", () =>\n dueQueue.transaction(async () => {\n // A producer can be between enrollment and its source commit. Never acknowledge\n // that observation; its completion will notify the event or retain the alarm.\n if (active) return;\n const current = dueQueue.read().find((lane) => lane.id === row.id);\n\n if (current?.revision !== row.revision) return;\n\n return dueQueue.complete(row, next)?.revision;\n }),\n );\n\n // This pass's own checkpoint is not fresh producer enrollment. Record it\n // only after commit, while the snapshot gate still excludes a new producer.\n if (checkpointed !== undefined) observed.available.set(row.id, checkpointed);\n }),\n )\n .pipe(\n // Waiting for a producer or the SQL connection belongs to the wave budget.\n // An interrupted checkpoint leaves its revision due for event rearming;\n // the short storage transaction itself remains atomic.\n Effect.interruptible,\n );\n }),\n );\n };\n\n const appendRecoveryEvents = async (\n transaction: MaintenanceStorage,\n events: ReadonlyArray<Omit<ThreadRecoveryFaultEvent, \"sequence\">>,\n ) => {\n if (events.length === 0) return;\n const { state } = await readMaintenanceState(transaction);\n let sequence = state.recoveryEventSequence ?? 0n;\n\n for (const event of events) {\n sequence++;\n await transaction.put(\n recoveryEventKey(sequence),\n encodeRecoveryEvent(ThreadRecoveryFaultEvent.make({ ...event, sequence })),\n );\n }\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({\n ...state,\n recoveryEventSequence: sequence,\n }),\n ),\n );\n dueQueue.dirty(DueQueue.RecoveryEvents, 0, true);\n recoveryEventsPending = true;\n };\n\n const recoveryEventLane: ThreadHostMaintenanceLane = {\n id: DueQueue.RecoveryEvents,\n dispatchTimeoutMillis: 30_000,\n run: Effect.gen(function* () {\n if (!recoveryEventsPending) return Option.none<number>();\n\n const range = yield* runTransaction(\"select recovery events\", () =>\n dueQueue.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n return {\n next: (state.recoveryEventAcknowledged ?? 0n) + 1n,\n through: state.recoveryEventSequence ?? 0n,\n };\n }),\n );\n\n for (let sequence = range.next; sequence <= range.through; sequence++) {\n const event = yield* runTransaction(\"read recovery event\", async () => {\n const event = decodeRecoveryEvent(await ctx.storage.get(recoveryEventKey(sequence)));\n\n if (event.sequence !== sequence)\n throw new Error(\"Recovery event does not match its sequence key\");\n\n return event;\n });\n\n // No storage reservation or source mutation gate is held during host delivery.\n yield* recoveryEvents.publish(event);\n const acknowledgedAt = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"acknowledge recovery event\", () =>\n dueQueue.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next = ThreadMaintenanceState.make({\n ...state,\n recoveryEventAcknowledged: sequence,\n });\n\n await transaction.delete(recoveryEventKey(sequence));\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n recoveryEventsPending = hasRecoveryEvents(next);\n dueQueue.progress(DueQueue.RecoveryEvents, acknowledgedAt, sequence);\n const lane = dueQueue.read().find((row) => row.id === DueQueue.RecoveryEvents);\n\n if (lane !== undefined)\n dueQueue.complete(lane, recoveryEventsPending ? acknowledgedAt : null);\n }),\n );\n }\n\n return recoveryEventsPending ? Option.some(0) : Option.none<number>();\n }),\n };\n\n const recordRecoveryFaults = Effect.fnUntraced(function* (\n result: RecoverySweepResult,\n recovery: NativeRecovery,\n current?: ReadonlyArray<SubmissionWorkItem>,\n selectedThread?: ThreadId,\n ) {\n const threads = new Map<ThreadId, RecoveryFailure | undefined>();\n\n if (selectedThread !== undefined) threads.set(selectedThread, undefined);\n for (const report of result.reports) threads.set(report.threadId, undefined);\n for (const report of result.workReports ?? []) threads.set(report.threadId, undefined);\n for (const blocked of result.blocked) threads.set(blocked.threadId, blocked.failure);\n if (threads.size === 0) return new Map<ThreadId, ThreadRecoveryFault>();\n const now = yield* Clock.currentTimeMillis;\n\n // Fault-only discovery uses control state even when retained payloads cannot decode.\n const submissions =\n current ??\n (result.blocked.length === 0 ? [] : yield* Stream.runCollect(ledger.scanNonterminal));\n\n yield* failpoint.hit(\"maintenance:recovery-status:before\");\n\n const retained = yield* runTransaction(\"record Thread recovery faults\", () =>\n dueQueue.transaction(async (transaction) => {\n const events: Array<Omit<ThreadRecoveryFaultEvent, \"sequence\">> = [];\n const newlyBlocked: Array<ThreadRecoveryFault> = [];\n const faults = new Map<ThreadId, ThreadRecoveryFault>();\n const recipients = new Map<ThreadId, ReadonlySet<SubmissionId>>();\n\n for (const [threadId, failure] of threads) {\n const key = recoveryFaultKey(threadId);\n const encoded = await transaction.get(key);\n\n const previous =\n encoded === undefined ? undefined : decodeRecoveryFault(threadId, encoded);\n\n const previousIds =\n previous === undefined ? [] : await readRecoveryRecipients(transaction, previous);\n\n const known = new Set(previousIds);\n\n recipients.set(threadId, known);\n\n if (failure === undefined) {\n if (previous !== undefined) {\n await transaction.delete(key);\n for (let start = 0; start < (previous.recipientCount ?? 0); start += 128)\n await transaction.delete(recoveryRecipientKeys(previous, start));\n for (const id of previous.recipientCount === undefined\n ? result.reports\n .filter((report) => report.threadId === threadId)\n .map((report) => report.submissionId)\n : previousIds)\n events.push(recoveryEvent(previous, id, \"cleared\", now));\n }\n continue;\n }\n\n const added = submissions\n .filter((row) => row.threadId === threadId && !known.has(row.submissionId))\n .map((row) => row.submissionId);\n\n await appendRecoveryRecipients(transaction, threadId, previousIds.length, added);\n\n const fault = ThreadRecoveryFault.make({\n schemaVersion: 1,\n threadId,\n firstFailedAt: previous?.firstFailedAt ?? now,\n lastFailedAt: now,\n attempts: Math.min(2_147_483_647, (previous?.attempts ?? 0) + 1),\n retryAt: now + Math.min(60_000, 5_000 * 2 ** Math.min(30, previous?.attempts ?? 0)),\n failure,\n recipientCount: previousIds.length + added.length,\n });\n\n await transaction.put(key, encodeRecoveryFault(fault));\n if (previous !== undefined && !sameRecoveryFailure(previous.failure, failure))\n for (const id of previousIds) events.push(recoveryEvent(fault, id, \"changed\", now));\n for (const id of added) {\n known.add(id);\n events.push(recoveryEvent(fault, id, \"created\", now));\n }\n faults.set(threadId, fault);\n if (previous === undefined) newlyBlocked.push(fault);\n }\n\n await appendRecoveryEvents(transaction, events);\n\n return {\n changed: new Set(events.map((event) => event.threadId)),\n newlyBlocked,\n faults,\n recipients,\n };\n }),\n );\n\n yield* failpoint.hit(\"maintenance:recovery-status:after\");\n for (const [threadId, ids] of retained.recipients) recovery.recipients.set(threadId, ids);\n // A healthy unchanged head must not wake its own maintenance loop.\n for (const threadId of retained.changed) yield* wakes.notify(threadId);\n for (const fault of retained.newlyBlocked)\n yield* Effect.logError(\n \"Native Thread recovery blocked; accepted work remains pending\",\n fault.failure.reason === \"defect\"\n ? Cause.die(fault.failure)\n : Cause.fail(fault.failure),\n ).pipe(Effect.annotateLogs({ threadId: fault.threadId }));\n\n return retained.faults;\n });\n\n const recoverThread = Effect.fnUntraced(function* (\n threadId: ThreadId,\n recovery: NativeRecovery,\n ) {\n let cursor = yield* runTransaction(\"read work recovery cursor\", async () => {\n const retained = await ctx.storage.get(workCursorKey(threadId));\n\n if (retained === undefined) return undefined;\n const decoded = Schema.decodeUnknownSync(NativeWorkCursor)(retained);\n\n if (decoded.threadId !== threadId)\n throw new Error(\"Work cursor belongs to another Thread\");\n\n return decoded.cursor;\n });\n\n do {\n const result = yield* runtime\n .runRecovery({ threadId, ...(cursor === undefined ? {} : { cursor }) })\n .pipe(Effect.provideService(CurrentNativeSource, true));\n\n // Persist each bounded pass before a claim; eviction resumes past consumed metadata.\n const faults = yield* recordRecoveryFaults(result, recovery, undefined, threadId);\n\n yield* runTransaction(\"checkpoint work recovery cursor\", async () => {\n if (result.cursor === undefined) await ctx.storage.delete(workCursorKey(threadId));\n else\n await ctx.storage.put(\n workCursorKey(threadId),\n Schema.encodeSync(NativeWorkCursor)({ threadId, cursor: result.cursor }),\n );\n });\n for (const report of result.reports) recovery.reports.set(report.submissionId, report);\n recovery.faults.delete(threadId);\n for (const [id, fault] of faults) recovery.faults.set(id, fault);\n recovery.recovered +=\n (result.workReports?.length ?? result.reports.length) + result.blocked.length;\n recovery.repaired ||= (result.workReports ?? result.reports).some(\n (report) => report.disposition === \"repaired\",\n );\n for (const report of result.workReports ?? [])\n if (report.retryAtMillis !== undefined)\n recovery.retryAtMillis = Math.min(\n recovery.retryAtMillis ?? Infinity,\n report.retryAtMillis,\n );\n cursor = result.blocked.length > 0 ? undefined : result.cursor;\n } while (cursor !== undefined);\n });\n\n // Registry changes, including upgrades from timed binding retries, create one native\n // opportunity. Unchanged registries leave parked work dormant across Object eviction.\n const readCurrentMaintenanceState = async (transaction: MaintenanceStorage) => {\n const current = await readMaintenanceState(transaction);\n\n if (current.state.bindingRegistryKey === runtime.bindingRegistryKey) return current;\n\n const state = ThreadMaintenanceState.make({\n ...Struct.omit(current.state, [\"retry\"]),\n bindingRegistryKey: runtime.bindingRegistryKey,\n bindingWaits: [],\n dirty: current.state.dirty + 1n,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n dueQueue.dirty(DueQueue.Native, 0, true);\n\n return { state, initialized: true };\n };\n\n const ensureAlarm = Effect.fnUntraced(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runAlarmTransaction(\"ensure maintenance alarm\", async (transaction, checkpoint) => {\n const { state, initialized } = await readCurrentMaintenanceState(transaction);\n\n recoveryEventsPending = hasRecoveryEvents(state);\n const rows = dueQueue.read();\n\n if (recoveryEventsPending && !rows.some((row) => row.id === DueQueue.RecoveryEvents))\n dueQueue.dirty(DueQueue.RecoveryEvents, now);\n if (!initialized)\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n\n const native =\n state.dirty > state.processed\n ? state.retry?.generation === state.dirty\n ? state.retry.notBefore\n : (rows.find((row) => row.id === DueQueue.Native)?.dueAt ?? now + minimumAlarmDelay)\n : null;\n\n dueQueue.checkpointNative(native);\n const next = DueQueue.next(dueQueue.read());\n\n if (Number.isFinite(next)) checkpoint.earlier(Math.max(now + minimumAlarmDelay, next));\n });\n yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fnUntraced(function* (observed: MaintenanceObservation) {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n\n const result = yield* runAlarmTransaction(\n \"begin maintenance pass\",\n async (transaction, checkpoint) => {\n const { state, initialized } = await readCurrentMaintenanceState(transaction);\n\n recoveryEventsPending = hasRecoveryEvents(state);\n\n observed.generation = state.dirty;\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n const retryAt = state.retry?.generation === state.dirty ? state.retry.notBefore : 0;\n\n const rows = dueQueue.read();\n const native = rows.find((row) => row.id === DueQueue.Native);\n const publication = rows.find((row) => row.id === DueQueue.Publication);\n\n if (\n state.processed >= state.dirty ||\n retryAt > now ||\n native === undefined ||\n native.dueAt === null ||\n native.notBefore > now ||\n publication?.state === \"parked\"\n ) {\n return {\n _tag: \"CaughtUp\" as const,\n nonterminal: state.nonterminal,\n };\n }\n\n // One debit per native progress revision in this event. Source progress may\n // legitimately admit another wave; a generation change alone cannot.\n const alreadyCharged = observed.charged.get(DueQueue.Native) === native.revision;\n const charged = alreadyCharged ? native : dueQueue.claim(native, now, true);\n\n if (charged === undefined)\n return { _tag: \"CaughtUp\" as const, nonterminal: state.nonterminal };\n observed.queue.set(DueQueue.Native, charged);\n observed.charged.set(DueQueue.Native, charged.revision);\n const deadline = DueQueue.next(dueQueue.read());\n\n if (Number.isFinite(deadline))\n checkpoint.at(Math.max(now + minimumAlarmDelay, deadline));\n else checkpoint.cancel();\n\n return {\n _tag: \"Actionable\" as const,\n generation: state.dirty,\n sourceRevision: charged.revision,\n nonterminal: state.nonterminal,\n stalls: charged.stalls,\n };\n },\n );\n\n yield* failpoint.hit(\"maintenance:begin:after\");\n\n return result;\n });\n\n const backoffDelay = (priorStalls: number, jitter: number) => {\n const backoff = Math.min(\n config.alarmBackoffCap,\n config.alarmBackoffBase * 2 ** Math.min(priorStalls, 30),\n );\n\n // Jitter over [backoff/2, backoff] spreads retries without exceeding the cap.\n return Math.ceil(backoff / 2 + (backoff / 2) * jitter);\n };\n\n const rearmDelay = Effect.fnUntraced(function* (progressed: boolean, priorStalls: number) {\n return progressed ? config.alarmBackoffBase : backoffDelay(priorStalls, yield* Random.next);\n });\n\n const rearmFailure = Effect.fnUntraced(function* (observed: MaintenanceObservation) {\n const { generation, nativeOnly } = observed;\n\n if (generation === undefined) return;\n yield* failpoint.hit(\"maintenance:retry:before\");\n yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis;\n\n const jitter = yield* Random.next;\n\n yield* runAlarmTransaction(\n \"back off failed maintenance\",\n async (transaction, checkpoint) => {\n const { state } = await readMaintenanceState(transaction);\n\n const previous =\n state.retry?.generation === generation && state.retry.nativeOnly === nativeOnly\n ? state.retry\n : undefined;\n\n const retry =\n state.retry?.generation === generation && state.retry.nativeOnly\n ? state.retry\n : MaintenanceRetry.make({\n generation,\n notBefore: Math.max(\n previous?.notBefore ?? 0,\n now + backoffDelay(previous?.stalls ?? 0, jitter),\n ),\n nativeOnly,\n stalls: Math.min(30, (previous?.stalls ?? 0) + 1),\n });\n\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(ThreadMaintenanceState.make({ ...state, retry })),\n );\n\n // Never postpone a producer that raced the failed observation. Host work\n // retains its own deadline; an early delivery skips native recovery below.\n const nativeDeadline =\n active > 0 || state.dirty !== generation\n ? now + minimumAlarmDelay\n : retry.notBefore;\n\n dueQueue.checkpointNative(\n state.dirty > state.processed || active > 0 ? nativeDeadline : null,\n );\n // Defer only the unacknowledged observations from this failed event. A\n // completed wave or racing enrollment has a different revision.\n for (const row of observed.queue.values()) {\n if (row.id !== DueQueue.Native && row.dueAt !== null && row.dueAt <= now) {\n const charged =\n observed.charged.get(row.id) === row.revision\n ? row\n : dueQueue.claim(row, now);\n\n if (charged !== undefined)\n dueQueue.complete(charged, now + backoffDelay(charged.stalls, jitter));\n }\n }\n const next = DueQueue.next(dueQueue.read());\n\n if (Number.isFinite(next)) checkpoint.at(Math.max(now + minimumAlarmDelay, next));\n else checkpoint.cancel();\n },\n );\n }),\n );\n yield* failpoint.hit(\"maintenance:retry:after\");\n });\n\n const beginNative = (observed: MaintenanceObservation) =>\n mutations.withSnapshot((activeAtStart) =>\n Effect.gen(function* () {\n const generation = yield* beginPass(observed);\n\n if (activeAtStart === 0) {\n const native = (yield* queueSnapshot).find((row) => row.id === DueQueue.Native);\n\n if (native !== undefined) observed.available.set(native.id, native.revision);\n }\n\n return { ...generation, activeAtStart };\n }),\n );\n\n const attemptSelected = Effect.fnUntraced(function* (\n selected: SubmissionWorkItem,\n previousWaits: ReadonlyArray<BindingWait>,\n yieldAfter: DateTime.Utc,\n recovery: NativeRecovery,\n ): Effect.fn.Return<number, MaintenancePassFailure> {\n yield* recoverThread(selected.threadId, recovery);\n\n let bindingFailure: DurableBindingFailure | undefined;\n\n // A missing binding releases its slot after retaining this exact Submission\n // and committing its registry wait below.\n const settlement = recovery.faults.has(selected.threadId)\n ? Option.none()\n : yield* runtime.processThreadHead(selected.threadId, { yieldAfter }).pipe(\n Effect.provideService(CurrentNativeSource, true),\n Effect.catchTag(\"BindingUnavailable\", (failure) => {\n bindingFailure = failure;\n\n return Effect.succeed(Option.none());\n }),\n );\n\n const previous = previousWaits.find((wait) => wait.submissionId === selected.submissionId);\n\n const wait =\n bindingFailure === undefined\n ? undefined\n : BindingWait.make({\n threadId: selected.threadId,\n submissionId: selected.submissionId,\n reportedAt: previous?.reportedAt ?? (yield* Clock.currentTimeMillis),\n });\n\n // Report before recording reportedAt. Interruption before the write may repeat a\n // report, but a durable wait must never suppress a report that was not delivered.\n if (bindingFailure !== undefined && previous === undefined) {\n yield* Effect.logError(\n \"Thread parked until its agent binding registry changes; original work remains pending\",\n Cause.fail(bindingFailure),\n ).pipe(\n Effect.annotateLogs({\n threadId: selected.threadId,\n submissionId: selected.submissionId,\n }),\n );\n }\n\n if (wait !== undefined || previous !== undefined) {\n // The Attempt released its Claim. Commit its binding wait (or clear) once,\n // before joining fallible auxiliary work. This local fact neither acknowledges\n // a generation nor changes the shared alarm.\n yield* failpoint.hit(\"maintenance:binding-retry:before\");\n yield* runStorage(\n \"record submission binding wait\",\n storage\n .transaction((transaction) =>\n Effect.gen(function* () {\n const encoded = yield* transaction.get(MAINTENANCE_STATE_KEY);\n\n const state =\n encoded === undefined\n ? initialMaintenanceState()\n : yield* Schema.decodeUnknownEffect(ThreadMaintenanceState)(encoded);\n\n const bindingWaits = [\n ...(state.bindingWaits ?? []).filter(\n (entry) => entry.submissionId !== selected.submissionId,\n ),\n ...(wait === undefined ? [] : [wait]),\n ];\n\n yield* transaction.put(\n MAINTENANCE_STATE_KEY,\n yield* Schema.encodeEffect(ThreadMaintenanceState)(\n ThreadMaintenanceState.make({ ...state, bindingWaits }),\n ),\n );\n }),\n )\n .pipe(Effect.mapError(alarmFailure(\"record submission binding wait\"))),\n );\n yield* failpoint.hit(\"maintenance:binding-retry:after\");\n }\n\n return Option.isSome(settlement) ? 1 : 0;\n });\n\n const advance = Effect.fnUntraced(function* (\n started: Effect.Success<ReturnType<typeof beginNative>>,\n yieldAfter: DateTime.Utc,\n observed: MaintenanceObservation,\n recovery: NativeRecovery,\n native: NativeDispatch,\n dispatch = true,\n reserved: ReadonlySet<ThreadId> = new Set(native.active.keys()),\n ): Effect.fn.Return<NativePassResult, MaintenancePassFailure> {\n let publicationRow = (yield* queueSnapshot).find((row) => row.id === DueQueue.Publication);\n\n if (\n publicationRow !== undefined &&\n publicationRow.dueAt !== null &&\n publicationRow.dueAt <= (yield* Clock.currentTimeMillis)\n ) {\n yield* runQueued(\n publicationRow,\n mutations\n .withSnapshot((active) =>\n started._tag === \"Actionable\" && active === 0\n ? publication.prepareGeneration(started.generation)\n : Effect.void,\n )\n .pipe(Effect.andThen(publication.drain)),\n observed,\n );\n publicationRow = (yield* queueSnapshot).find((row) => row.id === DueQueue.Publication);\n }\n const pending = Option.fromNullishOr(publicationRow?.dueAt);\n\n if (\n started._tag === \"CaughtUp\" ||\n Option.isSome(pending) ||\n publicationRow?.state === \"parked\"\n ) {\n const nextAttemptAt = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis;\n\n const { state } = yield* runTransaction(\"read native maintenance deadline\", () =>\n dueQueue.transaction((transaction) => readMaintenanceState(transaction)),\n );\n\n const native =\n active > 0 || state.dirty > state.processed\n ? state.retry?.generation === state.dirty && active === 0\n ? state.retry.notBefore\n : now + minimumAlarmDelay\n : Infinity;\n\n const next = Option.isSome(pending) ? pending.value : native;\n\n return Number.isFinite(next) ? Math.max(now + minimumAlarmDelay, next) : undefined;\n }),\n );\n\n return {\n phase: \"caught-up\",\n nonterminal: started.nonterminal,\n nextAttemptAt,\n };\n }\n if (\n native.generation !== started.generation ||\n native.sourceRevision !== started.sourceRevision\n ) {\n native.deferred.clear();\n native.generation = started.generation;\n native.sourceRevision = started.sourceRevision;\n }\n // A stable generation with no freed slot needs no second ledger/history scan.\n // Enrollment precedes admission: never cache a scan overlapping a producer body,\n // which may make a head ready later without another generation increment.\n if (\n native.active.size > 0 &&\n native.scanGeneration === started.generation &&\n native.scanRevision === started.sourceRevision\n ) {\n return {\n phase: \"actionable\",\n nonterminal: started.nonterminal,\n nextAttemptAt: undefined,\n };\n }\n native.scanGeneration = started.activeAtStart === 0 ? started.generation : undefined;\n native.scanRevision = started.activeAtStart === 0 ? started.sourceRevision : undefined;\n\n // Select from control state before reading execution history. A recovering or faulted\n // Thread cannot enter dispatch; old cleanup has its own scoped opportunity below.\n observed.nativeOnly = true;\n\n // Every checkpoint keeps the producer overlap that belongs to this recovery wave.\n const observation = (recovery.observation ??= {\n generation: started.generation,\n activeAtStart: started.activeAtStart,\n });\n\n const { scannedGeneration, afterWorkThread } = yield* runTransaction(\n \"read work discovery position\",\n async () => {\n const { state } = await readMaintenanceState(ctx.storage);\n\n return {\n scannedGeneration: state.dirty,\n afterWorkThread: state.lastRecoveredThreadId,\n };\n },\n );\n\n const current = yield* Stream.runCollect(ledger.scanNonterminal);\n\n let workOwners = yield* runtime\n .discoverWorkThreads({\n limit: 32,\n ...(afterWorkThread === undefined ? {} : { afterThreadId: afterWorkThread }),\n })\n .pipe(Effect.provideService(CurrentNativeSource, true));\n\n if (workOwners.threadIds.length === 0 && afterWorkThread !== undefined)\n workOwners = yield* runtime\n .discoverWorkThreads({ limit: 32 })\n .pipe(Effect.provideService(CurrentNativeSource, true));\n recovery.discoveryPending ||= workOwners.afterThreadId !== undefined;\n const selectionTime = yield* Clock.currentTimeMillis;\n const submissionsByThread = new Map<ThreadId, Array<SubmissionId>>();\n\n for (const row of current) {\n const ids = submissionsByThread.get(row.threadId) ?? [];\n\n ids.push(row.submissionId);\n submissionsByThread.set(row.threadId, ids);\n }\n // Canonical obligations survive their last Submission. Reload their retained backoff\n // before selecting recovery, including after eviction or a newer host mutation.\n for (const threadId of workOwners.threadIds)\n if (!submissionsByThread.has(threadId)) submissionsByThread.set(threadId, []);\n\n yield* runTransaction(\"read Thread recovery deadlines\", async () => {\n for (const [threadId, ids] of submissionsByThread) {\n if (!recovery.loaded.has(threadId)) {\n const encoded = await ctx.storage.get(recoveryFaultKey(threadId));\n\n if (encoded !== undefined) {\n const fault = decodeRecoveryFault(threadId, encoded);\n\n recovery.faults.set(threadId, fault);\n recovery.recipients.set(\n threadId,\n new Set(await readRecoveryRecipients(ctx.storage, fault)),\n );\n }\n recovery.loaded.add(threadId);\n }\n const fault = recovery.faults.get(threadId);\n\n if (\n fault === undefined ||\n ids.every((id) => recovery.recipients.get(threadId)?.has(id))\n )\n continue;\n\n // Admissions during backoff need visibility without accelerating recovery.\n // Preserve recipients even if recovery later settles them before clearing.\n await dueQueue.transaction(async (transaction) => {\n const encoded = await transaction.get(recoveryFaultKey(threadId));\n\n if (encoded === undefined) return;\n const previous = decodeRecoveryFault(threadId, encoded);\n const previousIds = await readRecoveryRecipients(transaction, previous);\n const known = new Set(previousIds);\n const added = ids.filter((id) => !known.has(id));\n\n if (added.length === 0) return;\n\n const updated = ThreadRecoveryFault.make({\n ...previous,\n recipientCount: previousIds.length + added.length,\n });\n\n await appendRecoveryRecipients(transaction, threadId, previousIds.length, added);\n await transaction.put(recoveryFaultKey(threadId), encodeRecoveryFault(updated));\n await appendRecoveryEvents(\n transaction,\n added.map((id) => recoveryEvent(updated, id, \"created\", selectionTime)),\n );\n recovery.faults.set(threadId, updated);\n recovery.recipients.set(threadId, new Set([...previousIds, ...added]));\n });\n }\n });\n const reports = recovery.reports;\n const recoveryFaults = recovery.faults;\n\n const bindingWaits = yield* runTransaction(\n \"read binding waits\",\n async () => (await readMaintenanceState(ctx.storage)).state.bindingWaits ?? [],\n );\n\n const parked = new Set(bindingWaits.map((wait) => wait.submissionId));\n\n const waiting = (row: SubmissionWorkItem) =>\n !recovery.pending.has(row.threadId) &&\n !recoveryFaults.has(row.threadId) &&\n (parked.has(row.submissionId) || stableExternalWait(row, reports));\n\n const heads = new Map<ThreadId, SubmissionWorkItem>();\n\n for (const row of current) {\n // Only recovered uncertainty may release later input; accepted aborts retain FIFO.\n if (row.state === \"unknown\" && waiting(row)) continue;\n if (!heads.has(row.threadId)) heads.set(row.threadId, row);\n }\n const stopping = new Set<ThreadId>();\n\n for (const head of heads.values()) {\n if (\n head.state !== \"ready\" ||\n native.active.has(head.threadId) ||\n recovery.pending.has(head.threadId) ||\n recoveryFaults.has(head.threadId)\n )\n continue;\n\n // An accepted abort is cleanup even when its input was never claimed. This\n // control-only read must not decode the execution journal or a recovery snapshot.\n const intent = yield* isolateRecovery(\n ledger.readAbortIntent(AbortIntentRequest.make({ submissionId: head.submissionId })),\n {\n timeout: recoveryConfig.recoveryTimeout,\n phase: () => \"recovery\",\n operation: \"read abort intent\",\n },\n );\n\n if (Result.isSuccess(intent)) {\n if (intent.success !== undefined) stopping.add(head.threadId);\n } else {\n const faults = yield* recordRecoveryFaults(\n RecoverySweepResult.make({\n reports: [],\n blocked: [\n RecoveryBlocked.make({ threadId: head.threadId, failure: intent.failure }),\n ],\n }),\n recovery,\n current,\n );\n\n for (const [threadId, fault] of faults) recoveryFaults.set(threadId, fault);\n recovery.recovered++;\n }\n }\n\n const eligible = [...heads.values()]\n .filter(\n (head) =>\n !recovery.pending.has(head.threadId) &&\n !stopping.has(head.threadId) &&\n !recoveryFaults.has(head.threadId) &&\n !waiting(head) &&\n (head.state === \"ready\" || reports.has(head.submissionId)),\n )\n .map((head) => head.threadId)\n .sort();\n\n yield* failpoint.hit(\"maintenance:select:before\");\n\n const selection = yield* runTransaction(\"select maintenance lane\", () =>\n dueQueue.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const waits = (state.bindingWaits ?? []).filter(\n (retry) => heads.get(retry.threadId)?.submissionId === retry.submissionId,\n );\n\n const runnable = eligible.filter(\n (threadId) =>\n !reserved.has(threadId) &&\n !native.active.has(threadId) &&\n !native.deferred.has(threadId) &&\n !waits.some((wait) => wait.threadId === threadId),\n );\n\n const pivot = Math.max(\n 0,\n runnable.findIndex(\n (threadId) =>\n state.lastServedThreadId === undefined || threadId > state.lastServedThreadId,\n ),\n );\n\n const selected = dispatch\n ? [...runnable.slice(pivot), ...runnable.slice(0, pivot)].slice(\n 0,\n nativeDispatchConcurrency() - reserved.size,\n )\n : [];\n\n const next = selected.at(-1);\n\n if (next !== undefined) {\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({ ...state, lastServedThreadId: next }),\n ),\n );\n }\n\n const backlog = recovery.started\n ? []\n : [...new Set([...heads.keys(), ...workOwners.threadIds])].filter((threadId) => {\n const fault = recoveryFaults.get(threadId);\n\n return (\n !eligible.includes(threadId) &&\n (fault === undefined || fault.retryAt <= selectionTime)\n );\n });\n\n // One finite wave, one Thread at a time, with the runtime's per-Thread deadline.\n // This cursor ensures an event deadline/eviction cannot always restart at the front.\n const after = backlog.filter(\n (threadId) =>\n state.lastRecoveredThreadId === undefined || threadId > state.lastRecoveredThreadId,\n );\n\n const before = backlog.filter(\n (threadId) =>\n state.lastRecoveredThreadId !== undefined &&\n threadId <= state.lastRecoveredThreadId,\n );\n\n return {\n selected,\n waits,\n backlog: [...after, ...before].slice(0, 32),\n discoveryPending: backlog.length > 32,\n };\n }),\n );\n\n yield* failpoint.hit(\"maintenance:select:after\");\n if (!recovery.started) {\n recovery.started = true;\n recovery.needsCheckpoint = selection.backlog.length > 0;\n recovery.discoveryPending ||= selection.discoveryPending;\n for (const threadId of selection.backlog) recovery.pending.add(threadId);\n yield* Deferred.succeed(recovery.queue, selection.backlog);\n }\n\n for (const threadId of selection.selected) {\n const selected = heads.get(threadId);\n\n if (selected === undefined) continue;\n // Reserve before recovery or claim acquisition. The durable Claim remains the\n // authority; this event-local reservation only prevents duplicate dispatch.\n native.dispatched++;\n native.active.set(\n threadId,\n yield* Effect.forkIn(\n attemptSelected(selected, selection.waits, yieldAfter, recovery),\n native.scope,\n ),\n );\n }\n\n if (native.active.size > 0) {\n // Active Attempts own their claims and may still append/settle. Only acknowledge\n // a generation after joining every admitted native Attempt.\n return {\n phase: \"actionable\",\n nonterminal: current.length,\n nextAttemptAt: undefined,\n dispatched: selection.selected.length > 0,\n };\n }\n\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const waitingHeads = new Map<ThreadId, boolean>();\n\n // Selected recovery must finish before its generation can be acknowledged: terminal\n // owners can supply a retry deadline only after their evidence read completes.\n const autonomous =\n recovery.pending.size > 0 ||\n recovery.discoveryPending ||\n recoveryFaults.size > 0 ||\n recovery.retryAtMillis !== undefined ||\n remaining.some((snapshot) => {\n if (snapshot.state === \"unknown\" && waiting(snapshot)) return false;\n const headWaiting = waitingHeads.get(snapshot.threadId);\n\n if (headWaiting === undefined) waitingHeads.set(snapshot.threadId, waiting(snapshot));\n // FIFO followers cannot execute through a stable external wait. Only plain queued\n // input is dormant here; admission repairs and accepted aborts still need a pass.\n if (\n headWaiting === true &&\n snapshot.state === \"ready\" &&\n reports.get(snapshot.submissionId)?.decision._tag === \"ApplyInput\"\n )\n return false;\n\n return !waiting(snapshot);\n });\n\n const progressed = native.progressed || recovery.repaired;\n\n const now = yield* Clock.currentTimeMillis;\n const ordinaryDelay = autonomous ? yield* rearmDelay(progressed, started.stalls) : 0;\n\n const nextEligible = [...recoveryFaults.values()]\n .map((fault) => fault.retryAt)\n .concat(\n eligible\n .filter((threadId) => !selection.waits.some((wait) => wait.threadId === threadId))\n .map(() => now),\n );\n\n if (recovery.retryAtMillis !== undefined) nextEligible.push(recovery.retryAtMillis);\n\n const retryDelay =\n nextEligible.length === 0 ? 0 : Math.max(0, Math.min(...nextEligible) - now);\n\n const delay = Math.max(ordinaryDelay, retryDelay);\n\n // Checkpoint native progress without changing the physical alarm. Auxiliary\n // delivery remains live; later mutations still advance the shared generation.\n yield* failpoint.hit(\"maintenance:checkpoint:before\");\n\n const nextAttemptAt = yield* mutations.withSnapshot((active) =>\n runTransaction(\"checkpoint native maintenance\", () =>\n dueQueue.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const mutationOverlap =\n observation.activeAtStart > 0 || started.activeAtStart > 0 || active > 0;\n\n // Only a scan without ledger work or canonical obligations can certify a newer\n // generation without another recovery wave. Read its generation before discovery\n // so progress committed during the scan retains its own recovery opportunity.\n const generation =\n remaining.length === 0 &&\n workOwners.threadIds.length === 0 &&\n !mutationOverlap &&\n state.dirty === scannedGeneration\n ? scannedGeneration\n : observation.generation;\n\n const processed =\n autonomous || mutationOverlap\n ? state.processed\n : state.processed > generation\n ? state.processed\n : generation;\n\n // Enrollment precedes the mutation body. A retry from an overlapping snapshot\n // must not defer work that becomes ready later in that same generation.\n const canBackoff = !mutationOverlap && state.dirty === started.generation;\n\n const next = ThreadMaintenanceState.make({\n ...Struct.omit(state, [\"retry\"]),\n processed,\n nonterminal: remaining.length,\n bindingWaits: (state.bindingWaits ?? []).filter((retry) =>\n remaining.some((row) => row.submissionId === retry.submissionId),\n ),\n ...(autonomous && !progressed && canBackoff\n ? {\n retry: MaintenanceRetry.make({\n generation: started.generation,\n notBefore: now + delay,\n nativeOnly: true,\n stalls: Math.min(30, started.stalls + 1),\n }),\n }\n : {}),\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n\n const dueAt = autonomous\n ? now + (canBackoff ? delay : minimumAlarmDelay)\n : mutationOverlap || next.dirty > next.processed\n ? now + minimumAlarmDelay\n : null;\n\n dueQueue.checkpointNative(dueAt);\n\n return dueAt ?? undefined;\n }),\n ),\n );\n\n yield* failpoint.hit(\"maintenance:checkpoint:after\");\n // A fresh empty scan may clear earlier producer overlap, but this pass has only\n // recovered its original generation. Retain that boundary for later canonical work.\n if (remaining.length === 0 && recovery.pending.size === 0)\n recovery.observation = { generation: observation.generation, activeAtStart: 0 };\n native.deferred.clear();\n native.progressed = false;\n native.needsCheckpoint = false;\n\n return {\n phase: \"actionable\",\n nonterminal: remaining.length,\n nextAttemptAt,\n };\n });\n\n const validateLanes = Effect.fnUntraced(function* (\n lanes: ReadonlyArray<ThreadHostMaintenanceLane>,\n queued: ReadonlyArray<DueQueue.DueLane>,\n ) {\n const ids = new Set([\n DueQueue.Native,\n DueQueue.Publication,\n DueQueue.Projection,\n DueQueue.Messages,\n ]);\n\n for (const lane of lanes) {\n yield* Schema.decodeEffect(DueQueue.LaneId)(lane.id).pipe(\n Effect.mapError(alarmFailure(\"maintenance lane ID\")),\n );\n if (ids.has(lane.id))\n return yield* DurableAlarmError.make({\n operation: \"maintenance lane ID\",\n message: `Duplicate maintenance lane: ${lane.id}`,\n });\n ids.add(lane.id);\n }\n for (const row of queued) {\n if (row.dueAt !== null && !ids.has(row.id))\n return yield* DurableAlarmError.make({\n operation: \"maintenance lane ID\",\n message: `No handler registered for scheduled lane: ${row.id}`,\n });\n }\n });\n\n const dispatch = Effect.fnUntraced(function* (\n yieldAfter: DateTime.Utc,\n dispatchUntil: DateTime.Utc,\n observed: MaintenanceObservation,\n ) {\n // Subscribe before the first snapshot. Durable enrollment recovers eviction;\n // producer completion and wake hints make work visible during this incarnation.\n const notified = (yield* Stream.toPull(wakes.wakes)).pipe(\n Effect.asVoid,\n Effect.catch(() => Effect.never),\n );\n\n // A wake may observe temporary backoff while this event's recovery is still running.\n // Its completion must retain the original actionable observation for acknowledgement.\n const started = yield* beginNative(observed);\n\n yield* mutations.withSnapshot(() =>\n Effect.gen(function* () {\n const queued = yield* queueSnapshot;\n const producing = yield* mutations.activeLanes;\n\n for (const row of queued) {\n observed.queue.set(row.id, row);\n if (!producing.has(row.id)) observed.available.set(row.id, row.revision);\n }\n }),\n );\n\n // This scope owns every admitted finite wave, including native advancement.\n // Close it before final alarm rearming, including on failure or event interruption.\n const auxiliaryScope = yield* Effect.acquireRelease(Scope.make(\"parallel\"), (scope, exit) =>\n Scope.close(scope, exit),\n );\n\n const fork = <A, E>(work: Effect.Effect<A, E>) => Effect.forkIn(work, auxiliaryScope);\n\n // Each lane has at most one finite wave. A completion is retained until the single\n // scheduling loop observes it; a busy sibling cannot consume another lane's hint.\n const lanes = [recoveryEventLane, ...framework.lanes, ...host.lanes].map((lane) => ({\n ...lane,\n exhausted: false,\n fiber: undefined as Fiber.Fiber<Option.Option<number>, DurableAlarmError> | undefined,\n }));\n\n let messageExhausted = false;\n let delivery: Fiber.Fiber<void, DurableAlarmError> | undefined;\n let failure: Cause.Cause<MaintenancePassFailure> | undefined;\n\n const recovery: NativeRecovery = {\n queue: yield* Deferred.make<ReadonlyArray<ThreadId>>(),\n pending: new Set(),\n loaded: new Set(),\n reports: new Map(),\n faults: new Map(),\n recipients: new Map(),\n started: false,\n needsCheckpoint: false,\n recovered: 0,\n repaired: false,\n discoveryPending: false,\n };\n\n const recoveryFiber = yield* fork(\n Effect.gen(function* () {\n for (const threadId of yield* Deferred.await(recovery.queue)) {\n yield* failpoint.hit(\"maintenance:select:before\");\n yield* runTransaction(\"select old recovery lane\", () =>\n dueQueue.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({\n ...state,\n lastRecoveredThreadId: threadId,\n }),\n ),\n );\n }),\n );\n yield* failpoint.hit(\"maintenance:select:after\");\n yield* recoverThread(threadId, recovery);\n recovery.pending.delete(threadId);\n if (!recovery.faults.has(threadId)) yield* wakes.notify(threadId);\n }\n }),\n );\n\n // Backfill is one disposable wave; native and host work keep their own opportunities.\n const backfill = yield* fork(\n Effect.gen(function* () {\n if ((yield* mutations.activeLanes).has(DueQueue.Projection)) return;\n const row = (yield* queueSnapshot).find((row) => row.id === DueQueue.Projection);\n\n if (\n row?.dueAt === null ||\n row === undefined ||\n row.dueAt > (yield* Clock.currentTimeMillis)\n )\n return;\n\n return yield* runQueued(\n row,\n projection.drain.pipe(Effect.andThen(projection.pendingDeadline)),\n observed,\n ).pipe(Effect.timeoutOption(config.projectionDispatchTimeoutMillis));\n }),\n );\n\n let backfillObserved = false;\n let recoveryObserved = false;\n\n const dispatch: NativeDispatch = {\n scope: auxiliaryScope,\n active: new Map(),\n deferred: new Set(),\n dispatched: 0,\n settled: 0,\n progressed: false,\n needsCheckpoint: false,\n };\n\n let native: Fiber.Fiber<NativePassResult, MaintenancePassFailure> | undefined = yield* fork(\n advance(started, yieldAfter, observed, recovery, dispatch),\n );\n\n let result: NativePassResult = {\n phase: \"caught-up\",\n nonterminal: started.nonterminal,\n nextAttemptAt: undefined,\n };\n\n let phase = result.phase;\n let nativeCheck = false;\n const until = DateTime.toEpochMillis(yieldAfter);\n const dispatchEnd = DateTime.toEpochMillis(dispatchUntil);\n\n while (true) {\n if (native?.pollUnsafe() !== undefined) {\n result = yield* Fiber.join(native);\n native = undefined;\n if (result.phase === \"actionable\") phase = \"actionable\";\n observed.nativeOnly = dispatch.active.size > 0;\n if (result.dispatched === true && dispatch.active.size < nativeDispatchConcurrency()) {\n dispatch.scanGeneration = undefined;\n nativeCheck = true;\n }\n // An empty initial scan still opens exactly one old-recovery opportunity.\n recovery.started = true;\n yield* Deferred.succeed(recovery.queue, []);\n }\n for (const [threadId, attempt] of dispatch.active) {\n const exit = attempt.pollUnsafe();\n\n if (exit === undefined) continue;\n dispatch.active.delete(threadId);\n dispatch.scanGeneration = undefined;\n if (Exit.isFailure(exit)) return yield* Effect.failCause(exit.cause);\n dispatch.settled += exit.value;\n dispatch.progressed ||= exit.value > 0;\n dispatch.needsCheckpoint = true;\n if (exit.value === 0) dispatch.deferred.add(threadId);\n nativeCheck = true;\n }\n if (!recoveryObserved && recoveryFiber.pollUnsafe() !== undefined) {\n yield* Fiber.join(recoveryFiber);\n recoveryObserved = true;\n dispatch.scanGeneration = undefined;\n nativeCheck ||= recovery.needsCheckpoint;\n }\n if (!backfillObserved) {\n const exit = backfill.pollUnsafe();\n\n if (exit !== undefined) {\n backfillObserved = true;\n if (Exit.isFailure(exit)) failure ??= exit.cause;\n }\n }\n for (const lane of lanes) {\n const exit = lane.fiber?.pollUnsafe();\n\n if (exit === undefined) continue;\n lane.fiber = undefined;\n if (Exit.isFailure(exit)) {\n failure ??= exit.cause;\n lane.exhausted = true;\n }\n }\n const deliveryExit = delivery?.pollUnsafe();\n\n if (deliveryExit !== undefined) {\n delivery = undefined;\n if (Exit.isFailure(deliveryExit)) {\n failure ??= deliveryExit.cause;\n messageExhausted = true;\n }\n }\n\n // A failed auxiliary lane is exhausted for this event. Its error must not\n // retire healthy admission, delivery or native work that still has an allowance.\n const now = yield* Clock.currentTimeMillis;\n\n if (now >= until) break;\n\n const queueRevision = yield* mutations.revision;\n const queued = yield* queueSnapshot;\n const producing = yield* mutations.activeLanes;\n\n yield* validateLanes(lanes, queued);\n for (const lane of lanes) {\n if (\n lane.phase === \"after-native\" ||\n lane.fiber !== undefined ||\n lane.exhausted ||\n producing.has(lane.id)\n )\n continue;\n const row = queued.find((row) => row.id === lane.id);\n\n if (row === undefined || row.dueAt === null || row.dueAt > now) continue;\n const dueAt = row.dueAt;\n\n lane.fiber = yield* fork(\n Effect.gen(function* () {\n yield* Schema.decodeEffect(AuxiliaryDispatchMillis)(\n lane.dispatchTimeoutMillis,\n ).pipe(Effect.mapError(alarmFailure(\"host dispatch allowance\")));\n const selectedAt = yield* Clock.currentTimeMillis;\n\n if (selectedAt >= until || selectedAt + lane.dispatchTimeoutMillis > dispatchEnd) {\n lane.exhausted = true;\n\n return Option.some(dueAt);\n }\n\n return yield* runQueued(row, lane.run.pipe(Effect.scoped), observed).pipe(\n Effect.timeoutOrElse({\n duration: lane.dispatchTimeoutMillis,\n orElse: () =>\n DurableAlarmError.make({\n operation: \"host dispatch allowance\",\n message:\n \"The admitted host wave exceeded its allowance; durable work remains pending\",\n }),\n }),\n );\n }),\n );\n }\n if (delivery === undefined && !messageExhausted && !producing.has(DueQueue.Messages)) {\n // Selection is bounded local work. Fork only an actual due wave, so an empty\n // deadline check cannot extend retirement or consume another scheduling turn.\n const row = queued.find((row) => row.id === DueQueue.Messages);\n\n if (row !== undefined && row.dueAt !== null && row.dueAt <= now) {\n // Selection can fail too, so charge its attempt before preparing the wave.\n delivery = yield* fork(\n runQueued(\n row,\n Effect.gen(function* () {\n const wave = yield* messages.prepare;\n const selectedAt = yield* Clock.currentTimeMillis;\n\n if (selectedAt >= until || selectedAt + wave.timeoutMillis > dispatchEnd) {\n messageExhausted = true;\n\n return Option.fromNullishOr(row.dueAt);\n }\n\n // No second timeout: the driver owes the Claim's timeout/retry commit.\n return yield* wave.run;\n }),\n observed,\n ).pipe(Effect.asVoid),\n );\n }\n }\n\n // Retire a quiet event before consuming hints queued during its native Attempt.\n // Recovery still gets its checkpoint and, if needed, initial dispatch opportunity.\n if (\n native === undefined &&\n dispatch.active.size === 0 &&\n recoveryObserved &&\n !recovery.needsCheckpoint &&\n backfillObserved &&\n delivery === undefined &&\n lanes.every((lane) => lane.fiber === undefined)\n )\n break;\n\n if (\n native === undefined &&\n nativeCheck &&\n dispatch.active.size < nativeDispatchConcurrency()\n ) {\n nativeCheck = false;\n const nativeCheckpoint = dispatch.needsCheckpoint && dispatch.active.size === 0;\n const checkpoint = (recoveryObserved && recovery.needsCheckpoint) || nativeCheckpoint;\n\n if (checkpoint) recovery.needsCheckpoint = false;\n // Keep this opportunity's reservations across beginNative's storage awaits.\n // A finishing Attempt cannot turn a refill into another same-Thread Attempt.\n const reserved = new Set(dispatch.active.keys());\n\n native = yield* fork(\n Effect.gen(function* () {\n const awakened = checkpoint ? started : yield* beginNative(observed);\n\n return yield* advance(\n awakened,\n yieldAfter,\n observed,\n recovery,\n dispatch,\n !nativeCheckpoint && (!checkpoint || dispatch.settled === 0),\n reserved,\n );\n }),\n );\n }\n\n const next = Math.min(\n native === undefined ? (result.nextAttemptAt ?? Infinity) : Infinity,\n ...queued.flatMap((row) =>\n row.id !== DueQueue.Native && row.dueAt !== null && row.dueAt > now\n ? [row.dueAt]\n : [],\n ),\n until,\n );\n\n const completing = [\n ...(native === undefined ? [] : [native]),\n ...dispatch.active.values(),\n ...(recoveryObserved ? [] : [recoveryFiber]),\n ...(backfillObserved ? [] : [backfill]),\n ...(delivery === undefined ? [] : [delivery]),\n ...lanes.flatMap((lane) => (lane.fiber === undefined ? [] : [lane.fiber])),\n ];\n\n const ready = yield* Effect.raceAllFirst([\n ...completing.map((fiber) =>\n Fiber.await<unknown, MaintenancePassFailure>(fiber).pipe(\n Effect.as(\"completed\" as const),\n ),\n ),\n Effect.raceAllFirst([\n notified,\n mutations.awaitChange(queueRevision),\n Effect.sleep(Math.max(0, next - now)),\n ]).pipe(Effect.as(\"scan\" as const)),\n ]);\n\n if (ready === \"scan\") {\n nativeCheck = true;\n }\n }\n // Dispatch is closed. Join each admitted wave without renewing its allowance.\n // Message Claims retain their driver's own timer and local retry commit.\n if (native !== undefined) {\n result = yield* Fiber.join(native);\n if (result.phase === \"actionable\") phase = \"actionable\";\n observed.nativeOnly = dispatch.active.size > 0;\n recovery.started = true;\n yield* Deferred.succeed(recovery.queue, []);\n }\n for (const attempt of dispatch.active.values()) {\n const settled = yield* Fiber.join(attempt);\n\n dispatch.settled += settled;\n dispatch.progressed ||= settled > 0;\n }\n dispatch.active.clear();\n observed.nativeOnly = false;\n for (const fiber of [\n recoveryFiber,\n backfill,\n ...(delivery === undefined ? [] : [delivery]),\n ...lanes.flatMap((lane) => (lane.fiber === undefined ? [] : [lane.fiber])),\n ]) {\n // Await exits without failing fast: every admitted wave owns its original\n // bounded allowance and cleanup even if another wave has already failed.\n const exit = yield* Fiber.await<unknown, MaintenancePassFailure>(fiber);\n\n if (Exit.isFailure(exit)) failure ??= exit.cause;\n }\n if (failure !== undefined) return yield* Effect.failCause(failure);\n if (recovery.needsCheckpoint || dispatch.dispatched > 0) {\n result = yield* advance(started, yieldAfter, observed, recovery, dispatch, false);\n if (result.phase === \"actionable\") phase = \"actionable\";\n }\n yield* Scope.close(auxiliaryScope, Exit.void);\n\n return { result, phase, recovered: recovery.recovered, settled: dispatch.settled };\n });\n\n const pass = Effect.fnUntraced(function* (\n yieldAfter: DateTime.Utc,\n dispatchUntil: DateTime.Utc,\n observed: MaintenanceObservation,\n ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure, Scope.Scope> {\n const concurrent = yield* Effect.exit(\n Effect.scoped(dispatch(yieldAfter, dispatchUntil, observed)),\n );\n\n // Closing the concurrent scope first releases every native Attempt and its resources.\n // Select fresh revisions: finalizers may have retained the last host obligation.\n const afterNative = yield* Effect.gen(function* () {\n const lanes = [recoveryEventLane, ...framework.lanes, ...host.lanes];\n const selected = lanes.filter((lane) => lane.phase === \"after-native\");\n\n if (selected.length === 0) return [];\n const queued = yield* queueSnapshot;\n const producing = yield* mutations.activeLanes;\n\n // Finished native work may have produced new source facts. They are already\n // present at this phase boundary; only arrivals during the host wave preempt it.\n for (const row of queued)\n if (!producing.has(row.id)) observed.available.set(row.id, row.revision);\n const dispatchEnd = DateTime.toEpochMillis(dispatchUntil);\n const afterNativeIds = new Set(selected.map((lane) => lane.id));\n const completed: Array<Exit.Exit<void, DurableAlarmError>> = [];\n let yielded = false;\n\n // Subscribe by revision before reading the queue, so an enrollment racing the\n // snapshot cannot be lost. Only producer notifications rescan scheduling state;\n // there is no timer or application deadline read. New arrivals renew no budget.\n const yieldToConcurrent = Effect.gen(function* () {\n while (true) {\n const revision = yield* mutations.revision;\n const now = yield* Clock.currentTimeMillis;\n\n const current = yield* queueSnapshot;\n const active = yield* mutations.activeLanes;\n\n if (\n current.some(\n (row) =>\n !afterNativeIds.has(row.id) &&\n !active.has(row.id) &&\n row.dueAt !== null &&\n row.dueAt <= now &&\n row.revision !== observed.available.get(row.id),\n )\n ) {\n yielded = true;\n\n return completed;\n }\n yield* mutations.awaitChange(revision);\n }\n });\n\n yield* validateLanes(lanes, queued);\n\n const cursor = yield* mutations.withSnapshot(() =>\n runTransaction(\"read post-native dispatch cursor\", () =>\n dueQueue.transaction(\n async (transaction) =>\n (await readMaintenanceState(transaction)).state.lastAfterNativeLaneId,\n ),\n ),\n );\n\n const ordered = selected.toSorted((left, right) =>\n left.id < right.id ? -1 : left.id > right.id ? 1 : 0,\n );\n\n const after = cursor === undefined ? 0 : ordered.findIndex((lane) => lane.id > cursor);\n\n const rotated =\n after <= 0 ? ordered : [...ordered.slice(after), ...ordered.slice(0, after)];\n\n const waves = Effect.forEach(\n rotated,\n (lane) =>\n Effect.gen(function* () {\n const row = queued.find((row) => row.id === lane.id);\n const now = yield* Clock.currentTimeMillis;\n\n if (\n row === undefined ||\n row.dueAt === null ||\n row.dueAt > now ||\n producing.has(lane.id)\n )\n return;\n yield* Schema.decodeEffect(AuxiliaryDispatchMillis)(\n lane.dispatchTimeoutMillis,\n ).pipe(Effect.mapError(alarmFailure(\"host dispatch allowance\")));\n if (now + lane.dispatchTimeoutMillis > dispatchEnd) return;\n\n // Persist admission, not completion: slow or failing early lanes must not\n // monopolize the next event's remaining allowance. Domain receipts stay local\n // to the lane and its due-queue revision still fences acknowledgement.\n const admit = mutations.withSnapshot(() =>\n runTransaction(\"advance post-native dispatch cursor\", () =>\n dueQueue.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({ ...state, lastAfterNativeLaneId: lane.id }),\n ),\n );\n }),\n ),\n );\n\n yield* runQueued(\n row,\n admit.pipe(Effect.andThen(lane.run.pipe(Effect.scoped))),\n observed,\n () => yielded,\n ).pipe(\n Effect.timeoutOrElse({\n duration: lane.dispatchTimeoutMillis,\n orElse: () =>\n DurableAlarmError.make({\n operation: \"host dispatch allowance\",\n message:\n \"The admitted host wave exceeded its allowance; durable work remains pending\",\n }),\n }),\n );\n }).pipe(\n Effect.exit,\n Effect.tap((exit) =>\n Effect.sync(() => {\n if (!yielded || Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause))\n completed.push(exit);\n }),\n ),\n ),\n { concurrency: afterNativeDispatchConcurrency },\n ).pipe(Effect.as(completed));\n\n // raceFirst waits for interrupted wave scopes to close before the alarm can\n // retire and admit native work in its next event. Finished receipts stay finished.\n return yield* Effect.raceFirst(waves, yieldToConcurrent);\n }).pipe(Effect.exit);\n\n let failure = Exit.isFailure(concurrent) ? concurrent.cause : Cause.empty;\n\n if (Exit.isFailure(afterNative)) failure = Cause.combine(failure, afterNative.cause);\n else\n for (const exit of afterNative.value) {\n if (Exit.isFailure(exit)) failure = Cause.combine(failure, exit.cause);\n }\n if (Exit.isFailure(concurrent) || failure.reasons.length > 0)\n return yield* Effect.failCause(failure);\n const { result, phase, recovered, settled } = concurrent.value;\n\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const disposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis;\n\n return yield* runAlarmTransaction(\n \"finish maintenance event\",\n async (transaction, checkpoint) => {\n const { state } = await readMaintenanceState(transaction);\n\n const native =\n active > 0 || state.dirty > state.processed\n ? state.retry?.generation === state.dirty && active === 0\n ? Math.max(now + minimumAlarmDelay, state.retry.notBefore)\n : state.dirty === observed.generation && active === 0\n ? (result.nextAttemptAt ?? now + minimumAlarmDelay)\n : now + minimumAlarmDelay\n : Infinity;\n\n dueQueue.checkpointNative(Number.isFinite(native) ? native : null);\n const next = DueQueue.next(dueQueue.read());\n\n if (Number.isFinite(next)) {\n checkpoint.at(Math.max(now + minimumAlarmDelay, next));\n\n return \"rearmed\" as const;\n }\n checkpoint.cancel();\n\n return \"cleared\" as const;\n },\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n\n const report = MaintenancePassReport.make({\n phase,\n recovered,\n settled,\n nonterminal: result.nonterminal,\n alarm: disposition,\n });\n\n yield* Effect.annotateCurrentSpan({\n phase: report.phase,\n recovered: report.recovered,\n settled: report.settled,\n nonterminal: report.nonterminal,\n alarm: report.alarm,\n });\n\n return report;\n });\n\n return ThreadMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis;\n const yieldAfter = DateTime.makeUnsafe(now + 10 * 60_000);\n const dispatchUntil = DateTime.makeUnsafe(now + 14 * 60_000);\n\n const observed: MaintenanceObservation = {\n nativeOnly: false,\n queue: new Map(),\n charged: new Map(),\n available: new Map(),\n };\n\n return yield* alarms\n .deferWakes(\n maintenancePassGate.withPermit(\n dueQueue.withView(Effect.scoped(pass(yieldAfter, dispatchUntil, observed))).pipe(\n // Close event-owned auxiliary work and release Attempt ownership before\n // failure rearming, while still holding the pass permit.\n Effect.onErrorIf(\n () => true,\n () => rearmFailure(observed),\n ),\n ),\n ),\n )\n .pipe(\n hints.withHintsDeferred,\n Effect.catchTags({\n StorageOperationError: (error) => alarmFailure(\"defer maintenance wakes\")(error),\n InvalidScheduleConfigurationError: (error) =>\n alarmFailure(\"defer maintenance wakes\")(error),\n }),\n );\n }).pipe(\n // Include permit waiting, recovery and acknowledgement in the event deadline.\n // Interruption releases Attempt ownership, leaving the prearmed dirty generation\n // for recovery. It never changes the logical Run duration or settles a policy failure.\n // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.\n Effect.timeoutOrElse({\n duration: \"14 minutes\",\n orElse: () =>\n DurableAlarmError.make({\n operation: \"maintenance pass deadline\",\n message:\n \"The maintenance event exceeded its 14 minute deadline; durable recovery remains pending\",\n }),\n }),\n Effect.ensuring(reportParked),\n ),\n ensureAlarm: mutations\n .withSnapshot(() => ensureAlarm())\n .pipe(Effect.tap(() => reportParked)),\n withMutation: (body) =>\n mutations.withMutation(\n body.pipe(Effect.tap(() => publishCommitted.pipe(Effect.provide(publicationContext)))),\n ),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAEA,MAAa,SAAS,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC;AAEzE,MAAa,aAAa,OAAO,MAC/B,OAAO,UAAU,sBAAsB,EACrC,SAAS,0EACX,CAAC,CACH;AAEA,MAAa,WAAW,OAAO,OAAO,OAAO,MAAM;AACnD,MAAa,qBAAqB;AAElC,MAAa,oBAAoB;;AAGjC,IAAa,UAAb,cAA6B,OAAO,MAAe,mBAAmB,CAAC,CAAC;CACtE,IAAI;CACJ,UAAU,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC3D,OAAO;CACP,QAAQ,OAAO,IAAI,MAAM,OAAO,UAAU;EAAE,SAAS;EAAG,SAAS;CAAG,CAAC,CAAC;CACtE,aAAa,OAAO,OAAO,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC,CAAC;CAC/E,WAAW,OAAO;CAClB,OAAO,OAAO,SAAS;EAAC;EAAQ;EAAW;CAAQ,CAAC;CACpD,UAAU,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC;AAClC,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAa,SAAS;AACtB,MAAa,cAAc;AAC3B,MAAa,aAAa;AAC1B,MAAa,WAAW;AACxB,MAAa,iBAAiB;AAC9B,MAAa,YAAY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