typeclaw 0.48.12 → 0.49.0

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.
Files changed (213) hide show
  1. package/package.json +6 -3
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/attention-escalation.ts +8 -5
  4. package/src/agent/auth-reloadable.ts +2 -3
  5. package/src/agent/auth.ts +59 -79
  6. package/src/agent/compaction.ts +2 -2
  7. package/src/agent/index.ts +173 -85
  8. package/src/agent/live-sessions.ts +2 -2
  9. package/src/agent/live-subagents.ts +1 -0
  10. package/src/agent/llm-replay-sanitizer.ts +1 -1
  11. package/src/agent/model-overrides.ts +1 -1
  12. package/src/agent/multimodal/look-at.ts +3 -3
  13. package/src/agent/multimodal/read-redirect.ts +1 -1
  14. package/src/agent/plugin-tools.ts +76 -39
  15. package/src/agent/prompt-cache-key.ts +42 -0
  16. package/src/agent/provider-error.ts +179 -10
  17. package/src/agent/reload-tool.ts +1 -1
  18. package/src/agent/restart-handoff/index.ts +7 -14
  19. package/src/agent/reviewer-activity.ts +68 -0
  20. package/src/agent/session-origin.ts +33 -0
  21. package/src/agent/subagents.ts +14 -2
  22. package/src/agent/system-prompt.ts +68 -202
  23. package/src/agent/todo/continuation-policy.ts +12 -4
  24. package/src/agent/tool-error-remediation.ts +1 -1
  25. package/src/agent/tool-file-safety.ts +113 -14
  26. package/src/agent/tool-not-found-nudge.ts +1 -1
  27. package/src/agent/tool-result-budget.ts +2 -2
  28. package/src/agent/tools/channel-disengage.ts +2 -2
  29. package/src/agent/tools/channel-edit.ts +2 -2
  30. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  31. package/src/agent/tools/channel-history-render.ts +2 -1
  32. package/src/agent/tools/channel-history.ts +2 -2
  33. package/src/agent/tools/channel-react.ts +2 -2
  34. package/src/agent/tools/channel-read.ts +2 -2
  35. package/src/agent/tools/channel-reply.ts +25 -7
  36. package/src/agent/tools/channel-send.ts +51 -9
  37. package/src/agent/tools/curl-impersonate.ts +11 -2
  38. package/src/agent/tools/grant-role.ts +2 -2
  39. package/src/agent/tools/post-github-review.ts +79 -17
  40. package/src/agent/tools/restart.ts +2 -2
  41. package/src/agent/tools/skip-response.ts +4 -4
  42. package/src/agent/tools/spawn-subagent.ts +165 -14
  43. package/src/agent/tools/stream-snapshot.ts +2 -2
  44. package/src/agent/tools/subagent-cancel.ts +2 -2
  45. package/src/agent/tools/subagent-output.ts +10 -2
  46. package/src/agent/tools/todo/index.ts +2 -2
  47. package/src/agent/tools/webfetch/tool.ts +2 -2
  48. package/src/agent/tools/websearch.ts +2 -2
  49. package/src/bundled-plugins/backup/README.md +10 -9
  50. package/src/bundled-plugins/backup/runner.ts +140 -58
  51. package/src/bundled-plugins/backup/subagents.ts +58 -26
  52. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  53. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  54. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  55. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  56. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  57. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  58. package/src/bundled-plugins/operator/operator.ts +15 -4
  59. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  60. package/src/bundled-plugins/security/index.ts +50 -2
  61. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  62. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/discord-bot.ts +122 -67
  64. package/src/channels/adapters/discord-reactions.ts +18 -0
  65. package/src/channels/adapters/discord.ts +114 -8
  66. package/src/channels/adapters/github/inbound.ts +103 -8
  67. package/src/channels/adapters/github/index.ts +251 -19
  68. package/src/channels/adapters/github/last-alive.ts +27 -0
  69. package/src/channels/adapters/github/outbound.ts +54 -18
  70. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  71. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  72. package/src/channels/adapters/github/reactions.ts +100 -0
  73. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  74. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  75. package/src/channels/adapters/github/recovery.ts +106 -0
  76. package/src/channels/adapters/github/review-check.ts +510 -0
  77. package/src/channels/adapters/github/review-submitter.ts +34 -2
  78. package/src/channels/adapters/instagram.ts +32 -14
  79. package/src/channels/adapters/kakaotalk.ts +22 -7
  80. package/src/channels/adapters/line.ts +18 -3
  81. package/src/channels/adapters/outbound-account.ts +20 -0
  82. package/src/channels/adapters/own-reactions.ts +66 -0
  83. package/src/channels/adapters/recovery-correlation.ts +214 -0
  84. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  85. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  86. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  87. package/src/channels/adapters/slack-bot.ts +125 -57
  88. package/src/channels/adapters/slack-classify.ts +25 -4
  89. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  90. package/src/channels/adapters/slack-reactions.ts +18 -0
  91. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  92. package/src/channels/adapters/slack.ts +48 -3
  93. package/src/channels/adapters/teams.ts +14 -4
  94. package/src/channels/adapters/telegram-bot.ts +56 -10
  95. package/src/channels/adapters/webex-bot.ts +12 -2
  96. package/src/channels/adapters/webex.ts +12 -2
  97. package/src/channels/background-handoff.ts +434 -0
  98. package/src/channels/background-obligations.ts +893 -0
  99. package/src/channels/continuity-types.ts +271 -0
  100. package/src/channels/github-review-check.ts +598 -0
  101. package/src/channels/github-review-turn-ledger.ts +102 -28
  102. package/src/channels/github-review-verdict-coordinator.ts +96 -13
  103. package/src/channels/github-token-bridge.ts +11 -5
  104. package/src/channels/inbound-journal.ts +1738 -0
  105. package/src/channels/index.ts +6 -1
  106. package/src/channels/manager.ts +17 -7
  107. package/src/channels/recovery-dispatcher.ts +264 -0
  108. package/src/channels/recovery-notice.ts +94 -0
  109. package/src/channels/recovery-outbox.ts +459 -0
  110. package/src/channels/router.ts +2582 -633
  111. package/src/channels/schema.ts +8 -1
  112. package/src/channels/subagent-completion-bridge.ts +17 -14
  113. package/src/channels/types.ts +121 -16
  114. package/src/channels/waiting-reactions.ts +664 -0
  115. package/src/cli/compose.ts +7 -4
  116. package/src/cli/hostd.ts +49 -3
  117. package/src/cli/inspect.ts +11 -14
  118. package/src/cli/model.ts +7 -5
  119. package/src/cli/oauth-callbacks.ts +38 -23
  120. package/src/coding-agent/broker-body.ts +38 -0
  121. package/src/coding-agent/broker.ts +290 -0
  122. package/src/coding-agent/claude.ts +95 -0
  123. package/src/coding-agent/codex.ts +104 -0
  124. package/src/coding-agent/index.ts +506 -0
  125. package/src/coding-agent/omo-state.ts +69 -0
  126. package/src/coding-agent/omo-stream.ts +98 -0
  127. package/src/coding-agent/omo.ts +192 -0
  128. package/src/coding-agent/runner.ts +263 -0
  129. package/src/coding-agent/tool.ts +62 -0
  130. package/src/coding-agent/worktree.ts +355 -0
  131. package/src/compose/restart.ts +10 -3
  132. package/src/compose/start.ts +20 -3
  133. package/src/config/config.ts +70 -26
  134. package/src/config/providers.ts +278 -50
  135. package/src/container/exit-reason.ts +44 -0
  136. package/src/container/index.ts +5 -0
  137. package/src/container/log-archive.ts +51 -13
  138. package/src/container/memory-limit.ts +1 -1
  139. package/src/container/memory-oversubscription.ts +36 -6
  140. package/src/container/oom-events.ts +86 -0
  141. package/src/container/restart.ts +2 -0
  142. package/src/container/shared.ts +8 -1
  143. package/src/container/start.ts +25 -13
  144. package/src/container/stop.ts +6 -2
  145. package/src/container/tool-oom-priority.ts +32 -0
  146. package/src/cron/consumer.ts +10 -4
  147. package/src/cron/reloadable.ts +23 -2
  148. package/src/doctor/checks.ts +14 -2
  149. package/src/hostd/daemon.ts +20 -10
  150. package/src/hostd/spawn.ts +106 -5
  151. package/src/hostd/version.ts +20 -0
  152. package/src/hostd/watchdog.ts +241 -0
  153. package/src/init/dockerfile.ts +57 -592
  154. package/src/init/index.ts +6 -7
  155. package/src/init/oauth-login.ts +57 -17
  156. package/src/inspect/transcript-view.ts +6 -3
  157. package/src/mcp/client.ts +3 -1
  158. package/src/operations/classify-tool-outcome.ts +45 -1
  159. package/src/operations/incidents.ts +10 -5
  160. package/src/plugin/core-tool-names.ts +1 -1
  161. package/src/plugin/define.ts +1 -0
  162. package/src/plugin/index.ts +1 -0
  163. package/src/plugin/types.ts +6 -1
  164. package/src/run/background-handoff-boot.ts +86 -0
  165. package/src/run/channel-session-factory.ts +5 -4
  166. package/src/run/index.ts +93 -93
  167. package/src/run/resource-sample.ts +19 -0
  168. package/src/sandbox/build.ts +4 -0
  169. package/src/sandbox/coding-agent.ts +214 -0
  170. package/src/sandbox/policy.ts +1 -0
  171. package/src/sandbox/runtime-private.ts +4 -1
  172. package/src/secrets/coding-agent-auth.ts +97 -0
  173. package/src/secrets/index.ts +0 -16
  174. package/src/secrets/refresh-provider-oauth.ts +30 -76
  175. package/src/secrets/schema.ts +3 -4
  176. package/src/secrets/storage.ts +133 -234
  177. package/src/server/command-runner.ts +6 -2
  178. package/src/server/index.ts +102 -41
  179. package/src/sessions/index.ts +1 -1
  180. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  181. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  182. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  183. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  184. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  185. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  186. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  187. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  188. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  189. package/src/skills/typeclaw-config/SKILL.md +24 -24
  190. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  191. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  192. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  193. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  194. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  195. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  196. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  197. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  198. package/src/skills/typeclaw-plugins/SKILL.md +20 -20
  199. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  200. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  201. package/src/tui/index.ts +5 -3
  202. package/src/tui/theme.ts +1 -1
  203. package/typeclaw.schema.json +44 -2
  204. package/src/agent/adaptive-thinking-compat.ts +0 -79
  205. package/src/secrets/claude-credentials-json.ts +0 -129
  206. package/src/secrets/codex-auth-json.ts +0 -102
  207. package/src/secrets/export-claude-credentials-file.ts +0 -270
  208. package/src/secrets/export-codex-auth-file.ts +0 -250
  209. package/src/secrets/oauth-xai.ts +0 -348
  210. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  211. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  212. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  213. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -0,0 +1,893 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { mkdir, open, readFile, readdir, rename, unlink } from 'node:fs/promises'
3
+ import { dirname, join, resolve } from 'node:path'
4
+
5
+ import { z } from 'zod'
6
+
7
+ import type { MatchableOrigin } from '../permissions/resolve'
8
+ import { createLegacyRecoveryNotice } from './background-handoff'
9
+ import type { LegacyBackgroundHandoffReader } from './background-handoff'
10
+ import { parseRecoveryRecord } from './continuity-types'
11
+ import type { RecoveryNoticeCause, RecoveryRecord } from './continuity-types'
12
+ import { createRecoveryNotice, sameRecoveryPrincipal } from './recovery-notice'
13
+ import type { RecoveryOutbox } from './recovery-outbox'
14
+ import { channelKeyId, type ChannelKey } from './types'
15
+
16
+ export type BackgroundObligationRef = { obligationId: string; generation: number }
17
+ export type BackgroundApplicationReceipt = {
18
+ transitionId: string
19
+ decisionDigest: string
20
+ expectedGeneration: number
21
+ resultingGeneration: number
22
+ }
23
+ export type BackgroundObligation = BackgroundObligationRef & {
24
+ schemaVersion: 1
25
+ taskId: string
26
+ parentSessionId: string
27
+ parentSessionFile?: string
28
+ accountIdentity: string
29
+ target: ChannelKey
30
+ principal: MatchableOrigin
31
+ acceptedAt: number
32
+ epoch: string
33
+ phase: 'accepted' | 'result-ready' | 'turn-owned' | 'notice-prepared' | 'notice-owned' | 'closed'
34
+ completionId?: string
35
+ claim?: { turnId: string; ownerSessionId?: string; epoch: string; generation: number }
36
+ transfer?: RecoveryRecord
37
+ legacyCoverage?: { id: string; generation: number }
38
+ outcome?: { kind: 'delivered' | 'intentionally-suppressed'; decisionId: string; reason?: string; deliveryId?: string }
39
+ applications: BackgroundApplicationReceipt[]
40
+ }
41
+ export type BackgroundAcceptance = {
42
+ taskId: string
43
+ parentSessionId: string
44
+ parentSessionFile?: string
45
+ accountIdentity: string
46
+ target?: ChannelKey
47
+ key?: ChannelKey
48
+ principal?: MatchableOrigin
49
+ triggeringAuthorId?: string
50
+ parentChat?: string
51
+ acceptedAt?: number
52
+ startedAt?: number
53
+ subagentName?: string
54
+ legacyGeneration?: string
55
+ }
56
+ export type BackgroundDecision = { transitionId: string; decisionDigest: string }
57
+ const queues = new Map<string, Promise<void>>()
58
+ /**
59
+ * Process-wide lookup index per store directory, shared by every instance in this process. One
60
+ * directory scan builds it and every write in this process extends it, so completion lookups read
61
+ * only exact candidates. Provenance (taskId) and frozen transfers never change once written, and
62
+ * closed rows stay on disk as tombstones, so entries are only ever added. The directory has one
63
+ * writer process; a new instance (a new boot or test phase) discards the cached index.
64
+ */
65
+ type ObligationIndex = {
66
+ byTask: Map<string, Set<string>>
67
+ byDelivery: Map<string, Set<string>>
68
+ ready: Promise<void>
69
+ }
70
+ const indexes = new Map<string, ObligationIndex>()
71
+ function indexRow(directory: string, row: BackgroundObligation) {
72
+ const index = indexes.get(directory)
73
+ if (!index) return
74
+ const add = (map: Map<string, Set<string>>, key: string) => {
75
+ const ids = map.get(key) ?? new Set<string>()
76
+ ids.add(row.obligationId)
77
+ map.set(key, ids)
78
+ }
79
+ add(index.byTask, row.taskId)
80
+ if (row.transfer) add(index.byDelivery, row.transfer.deliveryId)
81
+ }
82
+ const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex')
83
+ async function syncDirectory(path: string) {
84
+ if (process.platform === 'win32') return
85
+ const fd = await open(path, 'r')
86
+ try {
87
+ await fd.sync()
88
+ } finally {
89
+ await fd.close()
90
+ }
91
+ }
92
+ const nonempty = z.string().min(1)
93
+ const generation = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
94
+ const backgroundSchema = z
95
+ .object({
96
+ schemaVersion: z.literal(1),
97
+ obligationId: z.string().regex(/^[a-f0-9]{64}$/),
98
+ generation,
99
+ taskId: nonempty,
100
+ parentSessionId: nonempty,
101
+ parentSessionFile: nonempty.optional(),
102
+ accountIdentity: nonempty,
103
+ target: z.unknown(),
104
+ principal: z.unknown(),
105
+ acceptedAt: z.number().finite().nonnegative(),
106
+ epoch: nonempty,
107
+ phase: z.enum(['accepted', 'result-ready', 'turn-owned', 'notice-prepared', 'notice-owned', 'closed']),
108
+ completionId: nonempty.optional(),
109
+ claim: z
110
+ .object({
111
+ turnId: nonempty,
112
+ ownerSessionId: nonempty.optional(),
113
+ epoch: nonempty,
114
+ generation,
115
+ })
116
+ .strict()
117
+ .optional(),
118
+ transfer: z.unknown().optional(),
119
+ legacyCoverage: z.object({ id: nonempty, generation }).strict().optional(),
120
+ outcome: z
121
+ .object({
122
+ kind: z.enum(['delivered', 'intentionally-suppressed']),
123
+ decisionId: nonempty,
124
+ reason: z.string().optional(),
125
+ deliveryId: nonempty.optional(),
126
+ })
127
+ .strict()
128
+ .optional(),
129
+ applications: z.array(
130
+ z
131
+ .object({
132
+ transitionId: nonempty,
133
+ decisionDigest: nonempty,
134
+ expectedGeneration: generation,
135
+ resultingGeneration: generation,
136
+ })
137
+ .strict(),
138
+ ),
139
+ })
140
+ .strict()
141
+ function parse(value: unknown): BackgroundObligation {
142
+ backgroundSchema.parse(value)
143
+ // The shared notice parser below validates the opaque target/principal/transfer fields.
144
+ const row = value as BackgroundObligation
145
+ // Reuse the shared destination/principal validator without creating any send intent.
146
+ createRecoveryNotice({
147
+ target: row.target,
148
+ accountIdentity: row.accountIdentity,
149
+ principal: row.principal,
150
+ covers: [{ store: 'background', id: row.obligationId, generation: row.generation }],
151
+ transferId: row.obligationId,
152
+ recoveryGeneration: row.obligationId,
153
+ createdAt: row.acceptedAt,
154
+ })
155
+ if (
156
+ (row.phase === 'closed') !== !!row.outcome ||
157
+ (row.phase === 'turn-owned' && !row.claim) ||
158
+ ((row.phase === 'notice-prepared' || row.phase === 'notice-owned') && !row.transfer)
159
+ )
160
+ throw new Error('Invalid background obligation phase')
161
+ if (row.outcome && (!['delivered', 'intentionally-suppressed'].includes(row.outcome.kind) || !row.outcome.decisionId))
162
+ throw new Error('Invalid background outcome')
163
+ if (
164
+ row.claim &&
165
+ (typeof row.claim.turnId !== 'string' ||
166
+ !row.claim.turnId ||
167
+ typeof row.claim.epoch !== 'string' ||
168
+ !row.claim.epoch ||
169
+ (row.claim.ownerSessionId !== undefined &&
170
+ (typeof row.claim.ownerSessionId !== 'string' || !row.claim.ownerSessionId)) ||
171
+ !Number.isSafeInteger(row.claim.generation) ||
172
+ row.claim.generation < 1 ||
173
+ row.claim.generation > row.generation ||
174
+ (row.phase === 'turn-owned' && row.claim.generation !== row.generation))
175
+ )
176
+ throw new Error('Invalid background claim')
177
+ if (row.transfer) {
178
+ parseRecoveryRecord(row.transfer)
179
+ if (
180
+ channelKeyId(row.transfer.target) !== channelKeyId(row.target) ||
181
+ row.transfer.accountIdentity !== row.accountIdentity ||
182
+ !sameRecoveryPrincipal(row.transfer.principal, row.principal) ||
183
+ !row.transfer.covers.some(
184
+ (cover) =>
185
+ (cover.store === 'background' && cover.id === row.obligationId && cover.generation <= row.generation) ||
186
+ (cover.store === 'inventory' &&
187
+ cover.id === row.legacyCoverage?.id &&
188
+ cover.generation === row.legacyCoverage?.generation),
189
+ )
190
+ )
191
+ throw new Error('Invalid background transfer coverage')
192
+ }
193
+ const transitionIds = new Set<string>()
194
+ for (const receipt of row.applications) {
195
+ if (
196
+ typeof receipt.transitionId !== 'string' ||
197
+ !receipt.transitionId ||
198
+ typeof receipt.decisionDigest !== 'string' ||
199
+ !receipt.decisionDigest ||
200
+ !Number.isSafeInteger(receipt.expectedGeneration) ||
201
+ receipt.expectedGeneration < 1 ||
202
+ receipt.resultingGeneration !== receipt.expectedGeneration + 1 ||
203
+ receipt.resultingGeneration > row.generation ||
204
+ transitionIds.has(receipt.transitionId)
205
+ )
206
+ throw new Error('Invalid background application receipt')
207
+ transitionIds.add(receipt.transitionId)
208
+ }
209
+ return row
210
+ }
211
+ export class BackgroundObligationStore {
212
+ readonly epoch: string
213
+ private readonly directory: string
214
+ private frozen?: unknown
215
+ constructor(
216
+ agentDir: string,
217
+ private readonly options: {
218
+ epoch?: string
219
+ now?: () => number
220
+ onError?: (error: unknown) => void
221
+ onDurability?: (
222
+ phase: 'temp-synced' | 'replaced' | 'directory-synced',
223
+ row: BackgroundObligation,
224
+ ) => void | Promise<void>
225
+ } = {},
226
+ ) {
227
+ this.directory = resolve(agentDir, 'channels', 'background-obligations')
228
+ this.epoch = options.epoch ?? randomUUID()
229
+ indexes.delete(this.directory)
230
+ }
231
+ assertAvailable() {
232
+ this.check()
233
+ }
234
+ /** PR3 journal repair must finish before any dependent background progress. */
235
+ setFrozen(error?: unknown) {
236
+ this.frozen = error
237
+ }
238
+ private check() {
239
+ if (this.frozen !== undefined)
240
+ throw new Error('Background continuity frozen pending journal repair', { cause: this.frozen })
241
+ }
242
+ private path(id: string) {
243
+ if (!/^[a-f0-9]{64}$/.test(id)) throw new Error('Invalid obligation ID')
244
+ return join(this.directory, `${id}.json`)
245
+ }
246
+ private serialize<T>(key: string, action: () => Promise<T>): Promise<T> {
247
+ const result = (queues.get(key) ?? Promise.resolve()).then(action)
248
+ const settled = result.then(
249
+ () => {},
250
+ () => {},
251
+ )
252
+ queues.set(key, settled)
253
+ void settled.then(() => {
254
+ if (queues.get(key) === settled) queues.delete(key)
255
+ })
256
+ return result
257
+ }
258
+ run<T>(target: ChannelKey, action: () => Promise<T>) {
259
+ return this.serialize(`${this.directory}:lane:${channelKeyId(target)}`, async () => {
260
+ this.check()
261
+ return action()
262
+ })
263
+ }
264
+ // The lane serializes ownership/cache decisions, including ordinary input.
265
+ // Dependent durable mutations enforce the freeze themselves; lane acquisition
266
+ // alone must not block unrelated input or a parent's abort.
267
+ withTargetLane<T>(target: ChannelKey, action: () => Promise<T>) {
268
+ return this.serialize(`${this.directory}:lane:${channelKeyId(target)}`, action)
269
+ }
270
+ private async read(id: string) {
271
+ try {
272
+ const row = parse(JSON.parse(await readFile(this.path(id), 'utf8')))
273
+ if (row.obligationId !== id) throw new Error('Background filename identity mismatch')
274
+ return row
275
+ } catch (error) {
276
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
277
+ throw error
278
+ }
279
+ }
280
+ private async write(row: BackgroundObligation) {
281
+ parse(row)
282
+ try {
283
+ await mkdir(this.directory, { recursive: true })
284
+ await syncDirectory(dirname(dirname(this.directory)))
285
+ await syncDirectory(dirname(this.directory))
286
+ } catch (error) {
287
+ this.frozen = error
288
+ throw error
289
+ }
290
+ const path = this.path(row.obligationId)
291
+ const temp = `${path}.${randomUUID()}.tmp`
292
+ try {
293
+ const fd = await open(temp, 'wx', 0o600)
294
+ try {
295
+ await fd.writeFile(`${JSON.stringify(row)}\n`)
296
+ await fd.sync()
297
+ } finally {
298
+ await fd.close()
299
+ }
300
+ await this.options.onDurability?.('temp-synced', row)
301
+ await rename(temp, path)
302
+ // Visible to a concurrent directory scan from here on; keep the lookup index in step.
303
+ indexRow(this.directory, row)
304
+ await this.options.onDurability?.('replaced', row)
305
+ await syncDirectory(this.directory)
306
+ await this.options.onDurability?.('directory-synced', row)
307
+ } catch (error) {
308
+ this.frozen = error
309
+ throw error
310
+ } finally {
311
+ await unlink(temp).catch((error: NodeJS.ErrnoException) => {
312
+ if (error.code !== 'ENOENT') {
313
+ this.frozen = error
314
+ throw error
315
+ }
316
+ })
317
+ }
318
+ }
319
+ get(id: string) {
320
+ return this.serialize(this.path(id), () => this.read(id))
321
+ }
322
+ async list() {
323
+ let files: string[]
324
+ try {
325
+ files = await readdir(this.directory)
326
+ } catch (error) {
327
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
328
+ throw error
329
+ }
330
+ const rows: BackgroundObligation[] = []
331
+ for (const file of files.sort()) {
332
+ if (!/^[a-f0-9]{64}\.json$/.test(file)) continue
333
+ const row = await this.get(file.slice(0, -5))
334
+ if (!row) continue
335
+ indexRow(this.directory, row)
336
+ rows.push(row)
337
+ }
338
+ return rows
339
+ }
340
+ /** Builds the lookup index with one directory scan per process; later lookups never scan. */
341
+ private async index(): Promise<ObligationIndex> {
342
+ const existing = indexes.get(this.directory)
343
+ if (existing) {
344
+ await existing.ready
345
+ return existing
346
+ }
347
+ const index: ObligationIndex = { byTask: new Map(), byDelivery: new Map(), ready: Promise.resolve() }
348
+ indexes.set(this.directory, index)
349
+ // Registered before the scan starts, so a row renamed in after its readdir is added by write().
350
+ index.ready = this.list().then(
351
+ () => undefined,
352
+ (error: unknown) => {
353
+ if (indexes.get(this.directory) === index) indexes.delete(this.directory)
354
+ throw error
355
+ },
356
+ )
357
+ await index.ready
358
+ return index
359
+ }
360
+ private async indexedRows(map: 'byTask' | 'byDelivery', key: string) {
361
+ const rows: BackgroundObligation[] = []
362
+ // Sorted IDs keep the previous canonical choice: the first matching file in directory order.
363
+ for (const id of [...((await this.index())[map].get(key) ?? [])].sort()) {
364
+ const row = await this.get(id)
365
+ if (row) rows.push(row)
366
+ }
367
+ return rows
368
+ }
369
+ /** Exact parent/task row, closed tombstones included so a late completion cannot reopen work. */
370
+ async lookup(parentSessionId: string, taskId: string) {
371
+ return (await this.indexedRows('byTask', taskId)).find(
372
+ (row) => row.parentSessionId === parentSessionId && row.taskId === taskId,
373
+ )
374
+ }
375
+ /** Task row on one destination, for a successor session fetching a predecessor's result. */
376
+ async lookupTask(taskId: string, target: ChannelKey) {
377
+ return (await this.indexedRows('byTask', taskId)).find(
378
+ (row) => row.taskId === taskId && channelKeyId(row.target) === channelKeyId(target),
379
+ )
380
+ }
381
+ private async deliveryRows(deliveryId: string) {
382
+ return (await this.indexedRows('byDelivery', deliveryId)).filter((row) => row.transfer?.deliveryId === deliveryId)
383
+ }
384
+ accept(input: BackgroundAcceptance): Promise<BackgroundObligation> {
385
+ const target = input.target ?? input.key
386
+ if (!target) return Promise.reject(new Error('Background acceptance requires target'))
387
+ const obligationId = hash([
388
+ 'background',
389
+ input.accountIdentity,
390
+ channelKeyId(target),
391
+ input.parentSessionId,
392
+ input.taskId,
393
+ input.legacyGeneration ?? null,
394
+ ])
395
+ const principal: MatchableOrigin = input.principal ?? {
396
+ kind: 'channel',
397
+ adapter: target.adapter,
398
+ workspace: target.workspace,
399
+ chat: target.chat,
400
+ ...(input.parentChat ? { parentChat: input.parentChat } : {}),
401
+ ...(input.triggeringAuthorId ? { lastInboundAuthorId: input.triggeringAuthorId } : {}),
402
+ }
403
+ return this.serialize(this.path(obligationId), async () => {
404
+ this.check()
405
+ const existing = await this.read(obligationId)
406
+ if (existing) {
407
+ if (JSON.stringify(existing.principal) !== JSON.stringify(principal))
408
+ throw new Error('Conflicting background acceptance')
409
+ try {
410
+ await syncDirectory(this.directory)
411
+ } catch (error) {
412
+ this.frozen = error
413
+ throw error
414
+ }
415
+ return existing
416
+ }
417
+ const row: BackgroundObligation = {
418
+ schemaVersion: 1,
419
+ obligationId,
420
+ generation: 1,
421
+ taskId: input.taskId,
422
+ parentSessionId: input.parentSessionId,
423
+ ...(input.parentSessionFile ? { parentSessionFile: input.parentSessionFile } : {}),
424
+ accountIdentity: input.accountIdentity,
425
+ target,
426
+ principal,
427
+ acceptedAt: input.acceptedAt ?? input.startedAt ?? (this.options.now ?? Date.now)(),
428
+ epoch: this.epoch,
429
+ phase: 'accepted',
430
+ applications: [],
431
+ }
432
+ await this.write(row)
433
+ return row
434
+ })
435
+ }
436
+ async resultReady(input: string | { parentSessionId: string; taskId: string }, completionId?: string) {
437
+ this.check()
438
+ const id =
439
+ typeof input === 'string' ? input : (await this.lookup(input.parentSessionId, input.taskId))?.obligationId
440
+ if (!id) return undefined
441
+ const row = await this.get(id)
442
+ if (!row || row.phase === 'closed' || row.transfer) return undefined
443
+ const stableId = completionId ?? hash(['completion', id])
444
+ const decision = { transitionId: `completion:${stableId}`, decisionDigest: hash(['result-ready', id, stableId]) }
445
+ if (row.completionId && row.completionId !== stableId) throw new Error('Conflicting background completion')
446
+ const previous = row.applications.find((receipt) => receipt.transitionId === decision.transitionId)
447
+ return this.apply(
448
+ { obligationId: id, generation: previous?.expectedGeneration ?? row.generation },
449
+ decision,
450
+ (current) => ({
451
+ ...current,
452
+ completionId: stableId,
453
+ phase: current.claim ? 'turn-owned' : 'result-ready',
454
+ }),
455
+ )
456
+ }
457
+ apply(
458
+ ref: BackgroundObligationRef,
459
+ decision: BackgroundDecision,
460
+ change: (row: Readonly<BackgroundObligation>) => BackgroundObligation,
461
+ ) {
462
+ return this.applyDecision(ref, decision, change, false)
463
+ }
464
+ /** Only journal replay may apply a committed decision while dependent work is frozen. */
465
+ applyJournalDecision(
466
+ ref: BackgroundObligationRef,
467
+ decision: BackgroundDecision,
468
+ change: (row: Readonly<BackgroundObligation>) => BackgroundObligation,
469
+ ) {
470
+ return this.applyDecision(ref, decision, change, true)
471
+ }
472
+ private applyDecision(
473
+ ref: BackgroundObligationRef,
474
+ decision: BackgroundDecision,
475
+ change: (row: Readonly<BackgroundObligation>) => BackgroundObligation,
476
+ journalRepair: boolean,
477
+ ) {
478
+ return this.serialize(this.path(ref.obligationId), async () => {
479
+ if (!journalRepair) this.check()
480
+ const row = await this.read(ref.obligationId)
481
+ if (!row) return undefined
482
+ const receipt = row.applications.find((item) => item.transitionId === decision.transitionId)
483
+ if (receipt) {
484
+ if (receipt.decisionDigest !== decision.decisionDigest || receipt.expectedGeneration !== ref.generation)
485
+ throw new Error('Conflicting background transition receipt')
486
+ try {
487
+ await syncDirectory(this.directory)
488
+ } catch (error) {
489
+ this.frozen = error
490
+ throw error
491
+ }
492
+ return row
493
+ }
494
+ if (row.generation !== ref.generation || row.phase === 'closed') return undefined
495
+ const next = change(row)
496
+ next.generation = row.generation + 1
497
+ next.applications = [
498
+ ...row.applications,
499
+ { ...decision, expectedGeneration: row.generation, resultingGeneration: next.generation },
500
+ ]
501
+ await this.write(next)
502
+ return next
503
+ })
504
+ }
505
+ async claim(
506
+ refs: BackgroundObligationRef[],
507
+ owner: { turnId: string; ownerSessionId?: string; target: ChannelKey },
508
+ decision?: BackgroundDecision,
509
+ ): Promise<BackgroundObligationRef[]> {
510
+ this.check()
511
+ // Validate all coverage before publishing any owner. Caller holds target lane until caches update.
512
+ for (const ref of refs) {
513
+ const row = await this.get(ref.obligationId)
514
+ const applied =
515
+ decision &&
516
+ row?.applications.find(
517
+ (item) =>
518
+ item.transitionId === decision.transitionId &&
519
+ item.decisionDigest === decision.decisionDigest &&
520
+ item.expectedGeneration === ref.generation,
521
+ )
522
+ if (
523
+ applied &&
524
+ (!row ||
525
+ row.generation !== applied.resultingGeneration ||
526
+ row.phase !== 'turn-owned' ||
527
+ !row.claim ||
528
+ row.claim.turnId !== owner.turnId ||
529
+ row.claim.ownerSessionId !== owner.ownerSessionId ||
530
+ row.claim.epoch !== this.epoch ||
531
+ row.claim.generation !== row.generation)
532
+ )
533
+ throw new Error('Background claim decision superseded')
534
+ if (
535
+ !applied &&
536
+ (!row ||
537
+ row.generation !== ref.generation ||
538
+ (row.phase !== 'result-ready' && row.phase !== 'turn-owned') ||
539
+ row.transfer ||
540
+ (row.claim &&
541
+ (row.claim.turnId !== owner.turnId ||
542
+ row.claim.ownerSessionId !== owner.ownerSessionId ||
543
+ row.claim.epoch !== this.epoch)) ||
544
+ channelKeyId(row.target) !== channelKeyId(owner.target))
545
+ )
546
+ throw new Error('Invalid background claim coverage')
547
+ }
548
+ const committed: BackgroundObligationRef[] = []
549
+ const identity = decision ?? { transitionId: randomUUID(), decisionDigest: hash(['claim', refs, owner]) }
550
+ for (const ref of refs) {
551
+ const row = await this.apply(ref, identity, (current) => ({
552
+ ...current,
553
+ phase: 'turn-owned',
554
+ claim: {
555
+ turnId: owner.turnId,
556
+ ownerSessionId: owner.ownerSessionId,
557
+ epoch: this.epoch,
558
+ generation: current.generation + 1,
559
+ },
560
+ }))
561
+ if (
562
+ !row ||
563
+ row.generation !== ref.generation + 1 ||
564
+ row.phase !== 'turn-owned' ||
565
+ !row.claim ||
566
+ row.claim.turnId !== owner.turnId ||
567
+ row.claim.ownerSessionId !== owner.ownerSessionId ||
568
+ row.claim.epoch !== this.epoch ||
569
+ row.claim.generation !== row.generation
570
+ )
571
+ throw new Error('Background claim decision superseded')
572
+ committed.push({ obligationId: row.obligationId, generation: row.generation })
573
+ }
574
+ return committed
575
+ }
576
+ async move(
577
+ refs: BackgroundObligationRef[],
578
+ owner: { fromTurnId: string; turnId: string; ownerSessionId?: string; target: ChannelKey },
579
+ decision?: BackgroundDecision,
580
+ ): Promise<BackgroundObligationRef[]> {
581
+ const identity = decision ?? { transitionId: randomUUID(), decisionDigest: hash(['move', refs, owner]) }
582
+ for (const ref of refs) {
583
+ const row = await this.get(ref.obligationId)
584
+ const applied = row?.applications.find(
585
+ (item) =>
586
+ item.transitionId === identity.transitionId &&
587
+ item.decisionDigest === identity.decisionDigest &&
588
+ item.expectedGeneration === ref.generation,
589
+ )
590
+ if (
591
+ applied &&
592
+ (!row ||
593
+ row.generation !== applied.resultingGeneration ||
594
+ row.phase !== 'turn-owned' ||
595
+ !row.claim ||
596
+ row.claim.turnId !== owner.turnId ||
597
+ row.claim.ownerSessionId !== owner.ownerSessionId ||
598
+ row.claim.epoch !== this.epoch ||
599
+ row.claim.generation !== row.generation)
600
+ )
601
+ throw new Error('Background move decision superseded')
602
+ if (
603
+ !applied &&
604
+ (!row ||
605
+ row.generation !== ref.generation ||
606
+ row.phase !== 'turn-owned' ||
607
+ row.claim?.turnId !== owner.fromTurnId ||
608
+ channelKeyId(row.target) !== channelKeyId(owner.target))
609
+ )
610
+ throw new Error('Invalid background move coverage')
611
+ }
612
+ const committed: BackgroundObligationRef[] = []
613
+ for (const ref of refs) {
614
+ const row = await this.apply(ref, identity, (current) => ({
615
+ ...current,
616
+ claim: {
617
+ turnId: owner.turnId,
618
+ ownerSessionId: owner.ownerSessionId,
619
+ epoch: this.epoch,
620
+ generation: current.generation + 1,
621
+ },
622
+ }))
623
+ if (
624
+ !row ||
625
+ row.generation !== ref.generation + 1 ||
626
+ row.phase !== 'turn-owned' ||
627
+ !row.claim ||
628
+ row.claim.turnId !== owner.turnId ||
629
+ row.claim.ownerSessionId !== owner.ownerSessionId ||
630
+ row.claim.epoch !== this.epoch ||
631
+ row.claim.generation !== row.generation
632
+ )
633
+ throw new Error('Background move decision superseded')
634
+ committed.push({ obligationId: row.obligationId, generation: row.generation })
635
+ }
636
+ return committed
637
+ }
638
+ async settle(
639
+ refs: BackgroundObligationRef[],
640
+ outcome: NonNullable<BackgroundObligation['outcome']>,
641
+ decision?: BackgroundDecision,
642
+ ) {
643
+ const identity = decision ?? { transitionId: outcome.decisionId, decisionDigest: hash(['outcome', refs, outcome]) }
644
+ for (const ref of refs) {
645
+ const row = await this.get(ref.obligationId)
646
+ const applied = row?.applications.find(
647
+ (item) =>
648
+ item.transitionId === identity.transitionId &&
649
+ item.decisionDigest === identity.decisionDigest &&
650
+ item.expectedGeneration === ref.generation,
651
+ )
652
+ if (!applied && (!row || row.generation !== ref.generation || row.phase === 'closed'))
653
+ throw new Error('Invalid background outcome coverage')
654
+ }
655
+ for (const ref of refs) {
656
+ const row = await this.apply(ref, identity, (current) => ({ ...current, phase: 'closed', outcome }))
657
+ if (!row) throw new Error('Background outcome generation changed')
658
+ }
659
+ }
660
+ /**
661
+ * Freezes this child's transfer. Boot recovery keeps the default `restart`; a same-process
662
+ * abandonment passes `live-turn-ended`. An already-frozen transfer is returned unchanged.
663
+ */
664
+ async prepareNotice(id: string, expectedGeneration: number, cause: RecoveryNoticeCause = 'restart') {
665
+ const ref = { obligationId: id, generation: expectedGeneration }
666
+ const row = await this.get(id)
667
+ if (!row || row.phase === 'closed') return undefined
668
+ if (row.transfer) return row
669
+ return this.apply(
670
+ ref,
671
+ {
672
+ transitionId: `notice:${id}:${expectedGeneration}`,
673
+ // The restart digest is frozen; another cause for the same generation conflicts with it.
674
+ decisionDigest: hash(
675
+ cause === 'restart' ? ['notice', id, expectedGeneration] : ['notice', id, expectedGeneration, cause],
676
+ ),
677
+ },
678
+ (current) => {
679
+ const generation = current.generation + 1
680
+ const transfer = createRecoveryNotice({
681
+ target: current.target,
682
+ accountIdentity: current.accountIdentity,
683
+ principal: current.principal,
684
+ covers: [{ store: 'background', id, generation, parentSessionId: current.parentSessionId }],
685
+ recoveryGeneration: `${id}:${generation}`,
686
+ transferId: hash(['background-transfer', id, generation]),
687
+ sourceParentSessionId: current.parentSessionId,
688
+ cause,
689
+ })
690
+ return { ...current, phase: 'notice-prepared', transfer }
691
+ },
692
+ )
693
+ }
694
+ async ownNotice(id: string, expectedGeneration: number, deliveryId: string) {
695
+ // Outbox ownership does not advance source coverage: the frozen covered generation stays authoritative.
696
+ return this.serialize(this.path(id), async () => {
697
+ this.check()
698
+ const row = await this.read(id)
699
+ if (
700
+ !row ||
701
+ row.generation !== expectedGeneration ||
702
+ row.transfer?.deliveryId !== deliveryId ||
703
+ row.phase === 'closed'
704
+ )
705
+ return undefined
706
+ if (row.phase !== 'notice-owned') {
707
+ row.phase = 'notice-owned'
708
+ await this.write(row)
709
+ }
710
+ return row
711
+ })
712
+ }
713
+ async validateNotice(record: RecoveryRecord): Promise<'open' | 'resolved'> {
714
+ const coverage = record.covers.filter((item) => item.store === 'background')
715
+ if (!coverage.length) {
716
+ if (!record.covers.every((cover) => cover.store === 'inventory')) return 'open'
717
+ const migrated = await this.deliveryRows(record.deliveryId)
718
+ for (const row of migrated) {
719
+ if (
720
+ !row.legacyCoverage ||
721
+ row.transfer?.covers.some((cover) => cover.store !== 'inventory') ||
722
+ !record.covers.some(
723
+ (cover) => cover.id === row.legacyCoverage?.id && cover.generation === row.legacyCoverage?.generation,
724
+ ) ||
725
+ channelKeyId(row.target) !== channelKeyId(record.target) ||
726
+ row.accountIdentity !== record.accountIdentity ||
727
+ JSON.stringify(row.principal) !== JSON.stringify(record.principal)
728
+ )
729
+ throw new Error('Legacy recovery provenance is not independent')
730
+ if (row.phase !== 'closed' && row.phase !== 'notice-owned')
731
+ throw new Error('Legacy recovery ownership is not ready')
732
+ }
733
+ return migrated.length && migrated.every((row) => row.phase === 'closed') ? 'resolved' : 'open'
734
+ }
735
+ this.check()
736
+ let open = false
737
+ for (const cover of coverage) {
738
+ const row = await this.get(cover.id)
739
+ if (
740
+ !row ||
741
+ channelKeyId(row.target) !== channelKeyId(record.target) ||
742
+ row.accountIdentity !== record.accountIdentity ||
743
+ !sameRecoveryPrincipal(row.principal, record.principal) ||
744
+ row.transfer?.deliveryId !== record.deliveryId
745
+ )
746
+ throw new Error('Recovery coverage conflicts with background authority')
747
+ if (row.phase === 'closed') continue
748
+ if (row.generation !== cover.generation || row.phase !== 'notice-owned')
749
+ throw new Error('Recovery background ownership is not ready')
750
+ open = true
751
+ }
752
+ return open ? 'open' : 'resolved'
753
+ }
754
+ async acknowledgeNotice(record: RecoveryRecord) {
755
+ if (record.state !== 'delivered' && record.state !== 'suppressed') return
756
+ const refs: BackgroundObligationRef[] = record.covers
757
+ .filter((cover) => cover.store === 'background')
758
+ .map((cover) => ({ obligationId: cover.id, generation: cover.generation }))
759
+ if (record.covers.some((cover) => cover.store === 'inventory')) {
760
+ for (const row of await this.deliveryRows(record.deliveryId)) {
761
+ if (
762
+ row.legacyCoverage &&
763
+ row.transfer?.deliveryId === record.deliveryId &&
764
+ record.covers.some(
765
+ (cover) =>
766
+ cover.store === 'inventory' &&
767
+ cover.id === row.legacyCoverage?.id &&
768
+ cover.generation === row.legacyCoverage?.generation,
769
+ )
770
+ )
771
+ refs.push({ obligationId: row.obligationId, generation: row.generation })
772
+ }
773
+ }
774
+ for (const ref of refs) {
775
+ const row = await this.get(ref.obligationId)
776
+ if (row?.phase === 'closed') continue
777
+ if (!row || row.transfer?.deliveryId !== record.deliveryId)
778
+ throw new Error('Recovery receipt does not match background transfer')
779
+ await this.settle([ref], {
780
+ kind: record.state === 'delivered' ? 'delivered' : 'intentionally-suppressed',
781
+ decisionId: record.suppression?.decisionId ?? `recovery:${record.deliveryId}`,
782
+ deliveryId: record.deliveryId,
783
+ reason: record.suppression?.reason,
784
+ })
785
+ }
786
+ }
787
+ async suppressNoticeCoverage(record: RecoveryRecord, decision: { decisionId: string; reason: string }) {
788
+ const refs: BackgroundObligationRef[] = []
789
+ for (const cover of record.covers.filter((item) => item.store === 'background')) {
790
+ const row = await this.get(cover.id)
791
+ if (
792
+ !row ||
793
+ row.transfer?.deliveryId !== record.deliveryId ||
794
+ channelKeyId(row.target) !== channelKeyId(record.target) ||
795
+ row.accountIdentity !== record.accountIdentity
796
+ )
797
+ throw new Error('Suppression does not match background notice coverage')
798
+ if (row.phase !== 'closed') refs.push({ obligationId: row.obligationId, generation: cover.generation })
799
+ }
800
+ if (record.covers.some((cover) => cover.store === 'inventory')) {
801
+ for (const row of await this.deliveryRows(record.deliveryId)) {
802
+ if (row.phase === 'closed') continue
803
+ if (
804
+ !row.legacyCoverage ||
805
+ !record.covers.some(
806
+ (cover) =>
807
+ cover.store === 'inventory' &&
808
+ cover.id === row.legacyCoverage?.id &&
809
+ cover.generation === row.legacyCoverage?.generation,
810
+ )
811
+ )
812
+ throw new Error('Suppression does not match legacy notice coverage')
813
+ refs.push({ obligationId: row.obligationId, generation: row.generation })
814
+ }
815
+ }
816
+ if (refs.length)
817
+ await this.settle(refs, { kind: 'intentionally-suppressed', ...decision, deliveryId: record.deliveryId })
818
+ }
819
+ async migrateLegacy(reader: LegacyBackgroundHandoffReader, outbox: RecoveryOutbox) {
820
+ this.check()
821
+ for (const claim of await reader.claim()) {
822
+ await this.run(claim.record.key, async () => {
823
+ const source = claim.record
824
+ const identity = JSON.stringify([channelKeyId(source.key), source.parentSessionId, source.generationId])
825
+ const transfer =
826
+ source.recoveryTransfer?.record ?? (await reader.prepareRecovery(claim, createLegacyRecoveryNotice(source)))
827
+ const migratedIds: string[] = []
828
+ for (const task of source.tasks) {
829
+ const legacyId = createHash('sha256').update(`inventory:${identity}:${task.taskId}`).digest('hex')
830
+ const accepted = await this.accept({
831
+ taskId: task.taskId,
832
+ parentSessionId: source.parentSessionId,
833
+ parentSessionFile: source.parentSessionFile,
834
+ accountIdentity: transfer.accountIdentity,
835
+ target: source.key,
836
+ principal: transfer.principal,
837
+ acceptedAt: task.startedAt,
838
+ legacyGeneration: source.generationId,
839
+ })
840
+ migratedIds.push(accepted.obligationId)
841
+ if (accepted.phase === 'closed') continue
842
+ if (accepted.transfer) {
843
+ if (accepted.transfer.deliveryId !== transfer.deliveryId || accepted.legacyCoverage?.id !== legacyId)
844
+ throw new Error('Conflicting legacy obligation transfer')
845
+ } else {
846
+ await this.apply(
847
+ accepted,
848
+ {
849
+ transitionId: `legacy-transfer:${source.generationId}:${task.taskId}`,
850
+ decisionDigest: hash(['legacy-transfer', transfer.deliveryId, legacyId]),
851
+ },
852
+ (row) => ({
853
+ ...row,
854
+ phase: 'notice-prepared',
855
+ transfer,
856
+ legacyCoverage: { id: legacyId, generation: 1 },
857
+ }),
858
+ )
859
+ }
860
+ }
861
+ const imported = await outbox.import(transfer)
862
+ for (const id of migratedIds) {
863
+ const row = await this.get(id)
864
+ if (row && row.phase !== 'closed' && row.transfer?.deliveryId === transfer.deliveryId)
865
+ await this.ownNotice(row.obligationId, row.generation, transfer.deliveryId)
866
+ }
867
+ await reader.ownRecovery(claim, transfer)
868
+ await this.acknowledgeNotice(imported)
869
+ await reader.retire(claim)
870
+ })
871
+ }
872
+ }
873
+ async importOldEpoch(outbox: RecoveryOutbox) {
874
+ this.check()
875
+ for (const source of await this.list()) {
876
+ if (source.phase === 'closed' || (source.epoch === this.epoch && !source.transfer)) continue
877
+ await this.run(source.target, async () => {
878
+ const prepared = source.transfer ? source : await this.prepareNotice(source.obligationId, source.generation)
879
+ if (!prepared?.transfer) return
880
+ const imported = await outbox.import(prepared.transfer)
881
+ await this.ownNotice(prepared.obligationId, prepared.generation, imported.deliveryId)
882
+ await this.acknowledgeNotice(imported)
883
+ })
884
+ }
885
+ }
886
+ async flush() {
887
+ await Promise.all(
888
+ [...queues.entries()].filter(([key]) => key.startsWith(this.directory)).map(([, pending]) => pending),
889
+ )
890
+ }
891
+ }
892
+
893
+ export { parse as parseBackgroundObligation }