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,459 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { link, mkdir, open, readFile, readdir, rename, unlink } from 'node:fs/promises'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+
5
+ import { z } from 'zod'
6
+
7
+ import { parseRecoveryRecord, recoveryPayload, recoveryPayloadDigest } from './continuity-types'
8
+ import type { RecoveryFailure, RecoveryLease, RecoveryReceipt, RecoveryRecord } from './continuity-types'
9
+
10
+ const operations = new Map<string, Promise<void>>()
11
+ const idPattern = /^[a-f0-9]{64}$/
12
+ export type RecoveryOutboxOptions = {
13
+ epoch?: string
14
+ now?: () => number
15
+ onError?: (error: unknown) => void
16
+ /** Fault-injection boundary; production callers leave this unset. */
17
+ onDurability?: (
18
+ phase: 'temp-synced' | 'replaced' | 'directory-synced' | 'retirement-synced' | 'retired',
19
+ record: RecoveryRecord,
20
+ ) => void | Promise<void>
21
+ }
22
+ /**
23
+ * Immutable fence left when a terminal record leaves the active outbox. It keeps only the frozen
24
+ * payload digest and terminal dispatch state, so a later import of the same frozen transfer
25
+ * resolves to the finished delivery instead of creating a new send, without retaining the payload.
26
+ */
27
+ export type RecoveryRetirement = {
28
+ schemaVersion: 1
29
+ deliveryId: string
30
+ payloadDigest: string
31
+ retiredAt: number
32
+ dispatch: Pick<
33
+ RecoveryRecord,
34
+ 'generation' | 'attempts' | 'lease' | 'receipt' | 'failure' | 'suppression' | 'boundAccountIdentity'
35
+ > & { state: 'delivered' | 'suppressed' }
36
+ }
37
+ const retirementSchema = z
38
+ .object({
39
+ schemaVersion: z.literal(1),
40
+ deliveryId: z.string().regex(idPattern),
41
+ payloadDigest: z.string().regex(idPattern),
42
+ retiredAt: z.number().finite().nonnegative(),
43
+ // Nested dispatch fields are validated in full when a fence is joined back to its payload.
44
+ dispatch: z
45
+ .object({
46
+ state: z.enum(['delivered', 'suppressed']),
47
+ generation: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
48
+ attempts: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
49
+ lease: z.unknown().optional(),
50
+ receipt: z.unknown().optional(),
51
+ failure: z.unknown().optional(),
52
+ suppression: z.unknown().optional(),
53
+ boundAccountIdentity: z.string().min(1).optional(),
54
+ })
55
+ .strict(),
56
+ })
57
+ .strict()
58
+
59
+ async function syncDirectory(path: string): Promise<void> {
60
+ // POSIX process-death durability. Windows lacks directory-sync power-loss guarantees.
61
+ if (process.platform === 'win32') return
62
+ const handle = await open(path, 'r')
63
+ try {
64
+ await handle.sync()
65
+ } finally {
66
+ await handle.close()
67
+ }
68
+ }
69
+
70
+ export class RecoveryOutbox {
71
+ readonly epoch: string
72
+ private readonly directory: string
73
+ private readonly retiredDirectory: string
74
+ private readonly now: () => number
75
+ private readonly options: RecoveryOutboxOptions
76
+ private readonly pending = new Set<Promise<unknown>>()
77
+ private readonly importListeners = new Set<(record: RecoveryRecord) => void>()
78
+
79
+ constructor(agentDir: string, options: RecoveryOutboxOptions = {}) {
80
+ this.directory = resolve(agentDir, 'channels', 'recovery-outbox')
81
+ this.retiredDirectory = join(this.directory, 'retired')
82
+ this.epoch = options.epoch ?? randomUUID()
83
+ this.now = options.now ?? Date.now
84
+ this.options = options
85
+ }
86
+
87
+ private path(id: string): string {
88
+ if (!idPattern.test(id)) throw new Error('Invalid recovery delivery ID')
89
+ return join(this.directory, `${id}.json`)
90
+ }
91
+
92
+ private async read(id: string): Promise<RecoveryRecord | undefined> {
93
+ let bytes: string
94
+ try {
95
+ bytes = await readFile(this.path(id), 'utf8')
96
+ } catch (error) {
97
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
98
+ throw error
99
+ }
100
+ const record = parseRecoveryRecord(JSON.parse(bytes))
101
+ if (record.deliveryId !== id) throw new Error(`Recovery filename identity mismatch: ${id}`)
102
+ return record
103
+ }
104
+
105
+ private async readRetirement(id: string): Promise<RecoveryRetirement | undefined> {
106
+ let bytes: string
107
+ try {
108
+ bytes = await readFile(join(this.retiredDirectory, basename(this.path(id))), 'utf8')
109
+ } catch (error) {
110
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
111
+ throw error
112
+ }
113
+ const fence = retirementSchema.parse(JSON.parse(bytes)) as RecoveryRetirement
114
+ if (fence.deliveryId !== id) throw new Error(`Recovery retirement identity mismatch: ${id}`)
115
+ return fence
116
+ }
117
+
118
+ private async publish(record: RecoveryRecord, exclusive = false): Promise<boolean> {
119
+ parseRecoveryRecord(record)
120
+ await mkdir(this.directory, { recursive: true })
121
+ // Persist newly created directory entries all the way through channels to agentDir.
122
+ await syncDirectory(dirname(dirname(this.directory)))
123
+ await syncDirectory(dirname(this.directory))
124
+ const path = this.path(record.deliveryId)
125
+ const temp = `${path}.${randomUUID()}.tmp`
126
+ try {
127
+ const handle = await open(temp, 'wx', 0o600)
128
+ try {
129
+ await handle.writeFile(`${JSON.stringify(record)}\n`, 'utf8')
130
+ await handle.sync()
131
+ } finally {
132
+ await handle.close()
133
+ }
134
+ await this.options.onDurability?.('temp-synced', record)
135
+ if (exclusive) {
136
+ try {
137
+ await link(temp, path)
138
+ } catch (error) {
139
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
140
+ throw error
141
+ }
142
+ } else await rename(temp, path)
143
+ await this.options.onDurability?.('replaced', record)
144
+ await syncDirectory(this.directory)
145
+ await this.options.onDurability?.('directory-synced', record)
146
+ return true
147
+ } finally {
148
+ await unlink(temp).catch((error: NodeJS.ErrnoException) => {
149
+ if (error.code !== 'ENOENT') throw error
150
+ })
151
+ }
152
+ }
153
+
154
+ private serialized<T>(id: string, action: () => Promise<T>): Promise<T> {
155
+ const path = this.path(id)
156
+ const result = (operations.get(path) ?? Promise.resolve()).then(action)
157
+ const settled = result.then(
158
+ () => {},
159
+ () => {},
160
+ )
161
+ operations.set(path, settled)
162
+ this.pending.add(result)
163
+ void settled.then(() => {
164
+ this.pending.delete(result)
165
+ if (operations.get(path) === settled) operations.delete(path)
166
+ })
167
+ return result
168
+ }
169
+
170
+ import(input: RecoveryRecord): Promise<RecoveryRecord> {
171
+ const record = parseRecoveryRecord(input)
172
+ return this.serialized(record.deliveryId, async () => {
173
+ const existing = await this.read(record.deliveryId)
174
+ if (existing) {
175
+ if (recoveryPayload(existing) !== recoveryPayload(record))
176
+ throw new Error(`Conflicting recovery import: ${record.deliveryId}`)
177
+ // An import acknowledges durability even after a previous directory-sync failure.
178
+ await syncDirectory(this.directory)
179
+ return existing
180
+ }
181
+ const retired = await this.readRetirement(record.deliveryId)
182
+ if (retired) {
183
+ // A finished delivery stays finished: re-importing its frozen transfer never queues another send.
184
+ if (retired.payloadDigest !== recoveryPayloadDigest(record))
185
+ throw new Error(`Conflicting recovery import: ${record.deliveryId}`)
186
+ const {
187
+ state: _state,
188
+ generation: _generation,
189
+ attempts: _attempts,
190
+ lease: _lease,
191
+ receipt: _receipt,
192
+ failure: _failure,
193
+ suppression: _suppression,
194
+ nextAttemptAt: _next,
195
+ boundAccountIdentity: _bound,
196
+ ...payload
197
+ } = record
198
+ return parseRecoveryRecord({ ...payload, ...retired.dispatch })
199
+ }
200
+ if (
201
+ record.state !== 'pending' ||
202
+ record.generation !== 1 ||
203
+ record.attempts !== 0 ||
204
+ record.failure ||
205
+ record.nextAttemptAt !== undefined ||
206
+ record.boundAccountIdentity !== undefined
207
+ )
208
+ throw new Error('Recovery import must be an initial pending transfer')
209
+ if (!(await this.publish(record, true))) {
210
+ const winner = await this.read(record.deliveryId)
211
+ if (!winner || recoveryPayload(winner) !== recoveryPayload(record))
212
+ throw new Error(`Conflicting recovery import: ${record.deliveryId}`)
213
+ await syncDirectory(this.directory)
214
+ return winner
215
+ }
216
+ for (const listener of this.importListeners) listener(record)
217
+ return record
218
+ })
219
+ }
220
+
221
+ /** Called after each new record becomes durable; listeners must not throw. */
222
+ subscribe(listener: (record: RecoveryRecord) => void): () => void {
223
+ this.importListeners.add(listener)
224
+ return () => this.importListeners.delete(listener)
225
+ }
226
+
227
+ /**
228
+ * Moves a terminal record out of the active outbox once its source has acknowledged it and
229
+ * validates as resolved. The fence is durable before the active file is removed, so every crash
230
+ * point leaves the record, the fence, or both (the next retirement converges them).
231
+ */
232
+ retire(id: string, expectedGeneration: number): Promise<boolean> {
233
+ return this.serialized(id, async () => {
234
+ const record = await this.read(id)
235
+ if (!record) return (await this.readRetirement(id)) !== undefined
236
+ if (record.generation !== expectedGeneration || (record.state !== 'delivered' && record.state !== 'suppressed'))
237
+ return false
238
+ const payloadDigest = recoveryPayloadDigest(record)
239
+ const prior = await this.readRetirement(id)
240
+ if (prior && prior.payloadDigest !== payloadDigest) throw new Error(`Conflicting recovery retirement: ${id}`)
241
+ if (!prior) {
242
+ const fence: RecoveryRetirement = {
243
+ schemaVersion: 1,
244
+ deliveryId: id,
245
+ payloadDigest,
246
+ retiredAt: this.now(),
247
+ dispatch: {
248
+ state: record.state === 'delivered' ? 'delivered' : 'suppressed',
249
+ generation: record.generation,
250
+ attempts: record.attempts,
251
+ ...(record.lease ? { lease: record.lease } : {}),
252
+ ...(record.receipt ? { receipt: record.receipt } : {}),
253
+ ...(record.failure ? { failure: record.failure } : {}),
254
+ ...(record.suppression ? { suppression: record.suppression } : {}),
255
+ ...(record.boundAccountIdentity !== undefined ? { boundAccountIdentity: record.boundAccountIdentity } : {}),
256
+ },
257
+ }
258
+ await mkdir(this.retiredDirectory, { recursive: true })
259
+ await syncDirectory(this.directory)
260
+ const path = join(this.retiredDirectory, `${id}.json`)
261
+ const temp = `${path}.${randomUUID()}.tmp`
262
+ try {
263
+ const handle = await open(temp, 'wx', 0o600)
264
+ try {
265
+ await handle.writeFile(`${JSON.stringify(fence)}\n`, 'utf8')
266
+ await handle.sync()
267
+ } finally {
268
+ await handle.close()
269
+ }
270
+ await rename(temp, path)
271
+ await syncDirectory(this.retiredDirectory)
272
+ } finally {
273
+ await unlink(temp).catch((error: NodeJS.ErrnoException) => {
274
+ if (error.code !== 'ENOENT') throw error
275
+ })
276
+ }
277
+ }
278
+ await this.options.onDurability?.('retirement-synced', record)
279
+ await unlink(this.path(id))
280
+ await syncDirectory(this.directory)
281
+ await this.options.onDurability?.('retired', record)
282
+ return true
283
+ })
284
+ }
285
+
286
+ retired(id: string): Promise<RecoveryRetirement | undefined> {
287
+ return this.serialized(id, () => this.readRetirement(id))
288
+ }
289
+
290
+ async listRetired(): Promise<RecoveryRetirement[]> {
291
+ let names: string[]
292
+ try {
293
+ names = await readdir(this.retiredDirectory)
294
+ } catch (error) {
295
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
296
+ throw error
297
+ }
298
+ const fences: RecoveryRetirement[] = []
299
+ for (const name of names.sort()) {
300
+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue
301
+ try {
302
+ const fence = await this.retired(name.slice(0, -5))
303
+ if (fence) fences.push(fence)
304
+ } catch (error) {
305
+ if (this.options.onError) this.options.onError(error)
306
+ else console.error('Recovery retirement fence unavailable:', name, error)
307
+ }
308
+ }
309
+ return fences
310
+ }
311
+
312
+ get(id: string): Promise<RecoveryRecord | undefined> {
313
+ return this.serialized(id, () => this.read(id))
314
+ }
315
+
316
+ async list(): Promise<RecoveryRecord[]> {
317
+ let names: string[]
318
+ try {
319
+ names = await readdir(this.directory)
320
+ } catch (error) {
321
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
322
+ throw error
323
+ }
324
+ const records: RecoveryRecord[] = []
325
+ for (const name of names.sort()) {
326
+ if (!/^[a-f0-9]{64}\.json$/.test(name)) continue
327
+ try {
328
+ const record = await this.get(name.slice(0, -5))
329
+ if (record) records.push(record)
330
+ } catch (error) {
331
+ if (this.options.onError) this.options.onError(error)
332
+ else console.error('Recovery outbox record unavailable:', name, error)
333
+ }
334
+ }
335
+ return records
336
+ }
337
+
338
+ lease(id: string, expectedGeneration: number): Promise<RecoveryLease | undefined> {
339
+ return this.serialized(id, async () => {
340
+ const record = await this.read(id)
341
+ if (
342
+ !record ||
343
+ record.generation !== expectedGeneration ||
344
+ record.state === 'delivered' ||
345
+ record.state === 'suppressed'
346
+ )
347
+ return undefined
348
+ if (record.state === 'leased' && record.lease?.epoch === this.epoch) return undefined
349
+ if (record.nextAttemptAt !== undefined && record.nextAttemptAt > this.now()) return undefined
350
+ const lease = {
351
+ epoch: this.epoch,
352
+ generation: record.generation + 1,
353
+ attemptId: randomUUID(),
354
+ acquiredAt: this.now(),
355
+ }
356
+ const { failure: _failure, nextAttemptAt: _next, ...rest } = record
357
+ await this.publish({
358
+ ...rest,
359
+ state: 'leased',
360
+ generation: lease.generation,
361
+ lease,
362
+ attempts: record.attempts + 1,
363
+ })
364
+ return lease
365
+ })
366
+ }
367
+
368
+ repairLease(id: string, lease: RecoveryLease): Promise<boolean> {
369
+ return this.serialized(id, async () => {
370
+ const record = await this.read(id)
371
+ if (!record || record.state !== 'leased' || !this.owns(record, lease)) return false
372
+ // Visible bytes may follow a failed directory sync; republish before reuse.
373
+ await this.publish(record)
374
+ return true
375
+ })
376
+ }
377
+
378
+ delivered(id: string, lease: RecoveryLease, receipt: RecoveryReceipt): Promise<boolean> {
379
+ return this.serialized(id, async () => {
380
+ const record = await this.read(id)
381
+ if (!record || !this.owns(record, lease)) return false
382
+ if (record.receipt)
383
+ return (
384
+ record.receipt.confirmedAt === receipt.confirmedAt &&
385
+ record.receipt.messageId === receipt.messageId &&
386
+ JSON.stringify(record.receipt.messageIds) === JSON.stringify(receipt.messageIds)
387
+ )
388
+ if (record.state !== 'leased' && record.state !== 'suppressed') return false
389
+ await this.publish({ ...record, state: record.state === 'suppressed' ? 'suppressed' : 'delivered', receipt })
390
+ return true
391
+ })
392
+ }
393
+
394
+ bindAccount(id: string, lease: RecoveryLease, identity: string): Promise<boolean> {
395
+ return this.serialized(id, async () => {
396
+ const record = await this.read(id)
397
+ if (!record || record.state !== 'leased' || !this.owns(record, lease)) return false
398
+ if (record.accountIdentity !== 'unbound-legacy') return record.accountIdentity === identity
399
+ if (record.boundAccountIdentity !== undefined) return record.boundAccountIdentity === identity
400
+ await this.publish({ ...record, boundAccountIdentity: identity })
401
+ return true
402
+ })
403
+ }
404
+
405
+ fail(id: string, lease: RecoveryLease, failure: RecoveryFailure): Promise<boolean> {
406
+ return this.serialized(id, async () => {
407
+ const record = await this.read(id)
408
+ if (!record || record.state !== 'leased' || !this.owns(record, lease)) return false
409
+ const blocked =
410
+ failure.kind === 'permission' ||
411
+ failure.kind === 'identity' ||
412
+ failure.kind === 'target' ||
413
+ failure.kind === 'configuration'
414
+ const { lease: _lease, ...rest } = record
415
+ const delay = Math.max(
416
+ failure.retryAfter ?? 0,
417
+ Math.min(60_000, 1000 * 2 ** Math.min(record.attempts - 1, 6)) * (0.8 + Math.random() * 0.4),
418
+ )
419
+ await this.publish({
420
+ ...rest,
421
+ state: blocked ? 'blocked' : 'pending',
422
+ failure,
423
+ ...(!blocked ? { nextAttemptAt: this.now() + delay } : {}),
424
+ })
425
+ return true
426
+ })
427
+ }
428
+
429
+ suppress(id: string, reason: string, decisionId: string): Promise<boolean> {
430
+ return this.serialized(id, async () => {
431
+ const record = await this.read(id)
432
+ if (!record || record.state === 'delivered') return false
433
+ if (record.state === 'suppressed')
434
+ return record.suppression?.reason === reason && record.suppression.decisionId === decisionId
435
+ const { nextAttemptAt: _next, ...rest } = record
436
+ await this.publish({
437
+ ...rest,
438
+ generation: record.generation + 1,
439
+ state: 'suppressed',
440
+ suppression: { reason, decisionId },
441
+ })
442
+ return true
443
+ })
444
+ }
445
+
446
+ private owns(record: RecoveryRecord, lease: RecoveryLease): boolean {
447
+ return (
448
+ lease.epoch === this.epoch &&
449
+ record.lease?.epoch === lease.epoch &&
450
+ record.lease.generation === lease.generation &&
451
+ record.lease.attemptId === lease.attemptId &&
452
+ record.lease.acquiredAt === lease.acquiredAt
453
+ )
454
+ }
455
+
456
+ async flush(): Promise<void> {
457
+ await Promise.all(this.pending)
458
+ }
459
+ }