typeclaw 0.48.13 → 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 (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -0,0 +1,434 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { link, mkdir, open, readFile, readdir, rename, stat, unlink } from 'node:fs/promises'
3
+ import { basename, dirname, join, resolve } from 'node:path'
4
+
5
+ import { validateRecoveryRecord, type RecoveryRecord } from './continuity-types'
6
+ import { createRecoveryNotice } from './recovery-notice'
7
+ import type { ChannelKey, ReactionRef } from './types'
8
+ import { channelKeyId } from './types'
9
+
10
+ export type BackgroundInventoryRecord = {
11
+ schemaVersion: 1
12
+ generationId: string
13
+ processEpoch: string
14
+ parentSessionId: string
15
+ parentSessionFile?: string
16
+ key: ChannelKey
17
+ triggeringAuthorId?: string
18
+ parentChat?: string
19
+ accountIdentity?: string
20
+ recoveryTransfer?: { phase: 'notice-prepared' | 'notice-owned'; record: RecoveryRecord }
21
+ tasks: {
22
+ taskId: string
23
+ subagentName: string
24
+ startedAt: number
25
+ accountIdentity?: string
26
+ triggerReactionRef?: ReactionRef
27
+ }[]
28
+ }
29
+
30
+ export type BackgroundRecoveryIdentity = {
31
+ accountIdentity: string
32
+ accountIdentityConflict?: string[]
33
+ }
34
+
35
+ /** Resolve admitted task evidence; legacy group identity applies only to absent row fields. */
36
+ export function resolveBackgroundRecoveryIdentity(record: BackgroundInventoryRecord): BackgroundRecoveryIdentity {
37
+ const identities = [
38
+ ...new Set(
39
+ record.tasks
40
+ .map((task) => task.accountIdentity ?? record.accountIdentity ?? 'unbound-legacy')
41
+ .filter((identity) => identity !== 'unbound-legacy'),
42
+ ),
43
+ ].sort()
44
+ if (identities.length === 1) return { accountIdentity: identities[0]! }
45
+ return {
46
+ accountIdentity: 'unbound-legacy',
47
+ ...(identities.length > 1 ? { accountIdentityConflict: identities } : {}),
48
+ }
49
+ }
50
+
51
+ /** Frozen PR1 identity; upgrading the source must not create another delivery. */
52
+ export function createLegacyRecoveryNotice(source: BackgroundInventoryRecord): RecoveryRecord {
53
+ const identity = JSON.stringify([channelKeyId(source.key), source.parentSessionId, source.generationId])
54
+ return createRecoveryNotice({
55
+ target: source.key,
56
+ ...resolveBackgroundRecoveryIdentity(source),
57
+ principal: {
58
+ kind: 'channel',
59
+ adapter: source.key.adapter,
60
+ workspace: source.key.workspace,
61
+ chat: source.key.chat,
62
+ ...(source.parentChat !== undefined ? { parentChat: source.parentChat } : {}),
63
+ ...(source.triggeringAuthorId ? { lastInboundAuthorId: source.triggeringAuthorId } : {}),
64
+ },
65
+ covers: source.tasks.map((task) => ({
66
+ store: 'inventory' as const,
67
+ id: createHash('sha256').update(`inventory:${identity}:${task.taskId}`).digest('hex'),
68
+ generation: 1,
69
+ })),
70
+ recoveryGeneration: `${source.generationId}:${source.parentSessionId}`,
71
+ transferId: createHash('sha256').update(`inventory-transfer:${identity}`).digest('hex'),
72
+ sourceParentSessionId: source.parentSessionId,
73
+ })
74
+ }
75
+
76
+ function transferMatchesSource(source: BackgroundInventoryRecord, transfer: RecoveryRecord): boolean {
77
+ const resolved = resolveBackgroundRecoveryIdentity(source)
78
+ const identity = JSON.stringify([channelKeyId(source.key), source.parentSessionId, source.generationId])
79
+ const expectedIds = source.tasks
80
+ .map((task) => createHash('sha256').update(`inventory:${identity}:${task.taskId}`).digest('hex'))
81
+ .sort()
82
+ return (
83
+ channelKeyId(transfer.target) === channelKeyId(source.key) &&
84
+ transfer.sourceParentSessionId === source.parentSessionId &&
85
+ transfer.principal.kind === 'channel' &&
86
+ transfer.principal.adapter === source.key.adapter &&
87
+ transfer.principal.workspace === source.key.workspace &&
88
+ transfer.principal.chat === source.key.chat &&
89
+ transfer.principal.parentChat === source.parentChat &&
90
+ transfer.principal.lastInboundAuthorId === (source.triggeringAuthorId || undefined) &&
91
+ transfer.accountIdentity === resolved.accountIdentity &&
92
+ JSON.stringify(transfer.accountIdentityConflict) === JSON.stringify(resolved.accountIdentityConflict) &&
93
+ transfer.recoveryGeneration === `${source.generationId}:${source.parentSessionId}` &&
94
+ transfer.transferId === createHash('sha256').update(`inventory-transfer:${identity}`).digest('hex') &&
95
+ transfer.covers.every((coverage) => coverage.store === 'inventory' && coverage.generation === 1) &&
96
+ JSON.stringify(transfer.covers.map((coverage) => coverage.id).sort()) === JSON.stringify(expectedIds)
97
+ )
98
+ }
99
+
100
+ export type ClaimedBackgroundInventory = { record: BackgroundInventoryRecord; claimPath: string }
101
+
102
+ const hashPattern = '[a-f0-9]{64}'
103
+ const uuidPattern = '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}'
104
+ const pendingPattern = new RegExp(`^${hashPattern}\\.json$`)
105
+ const claimedPattern = new RegExp(`^(${hashPattern})\\.${uuidPattern}\\.json$`)
106
+ const tempPattern = new RegExp(`^${hashPattern}\\.json\\.${uuidPattern}\\.tmp$`)
107
+ const generationPattern = new RegExp(`^${uuidPattern}$`)
108
+ // Single active runtime writer; boot readers can compete for rename ownership.
109
+ // Sharing queues also prevents two collaborators in that runtime taking stale snapshots.
110
+ const operations = new Map<string, Promise<void>>()
111
+
112
+ function missing(error: unknown): boolean {
113
+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT'
114
+ }
115
+
116
+ async function serialized<T>(path: string, action: () => Promise<T>): Promise<T> {
117
+ const result = (operations.get(path) ?? Promise.resolve()).then(action)
118
+ const settled = result.then(
119
+ () => {},
120
+ () => {},
121
+ )
122
+ operations.set(path, settled)
123
+ try {
124
+ return await result
125
+ } finally {
126
+ if (operations.get(path) === settled) operations.delete(path)
127
+ }
128
+ }
129
+
130
+ async function syncDirectory(path: string): Promise<void> {
131
+ // Container runtime is POSIX. Windows dev does not support directory fsync.
132
+ if (process.platform === 'win32') return
133
+ const handle = await open(path, 'r')
134
+ try {
135
+ await handle.sync()
136
+ } finally {
137
+ await handle.close()
138
+ }
139
+ }
140
+
141
+ async function removeFile(path: string): Promise<void> {
142
+ try {
143
+ await unlink(path)
144
+ await syncDirectory(dirname(path))
145
+ } catch (error) {
146
+ if (!missing(error)) throw error
147
+ }
148
+ }
149
+
150
+ function recordHash(key: ChannelKey, parentSessionId: string): string {
151
+ return createHash('sha256')
152
+ .update(JSON.stringify([channelKeyId(key), parentSessionId]))
153
+ .digest('hex')
154
+ }
155
+
156
+ function validSessionFile(file: unknown): file is string {
157
+ return (
158
+ typeof file === 'string' &&
159
+ file.endsWith('.jsonl') &&
160
+ file !== '.jsonl' &&
161
+ basename(file) === file &&
162
+ !file.includes('\\') &&
163
+ !file.includes(String.fromCharCode(0)) &&
164
+ file !== '..'
165
+ )
166
+ }
167
+
168
+ function object(value: unknown): value is Record<string, unknown> {
169
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
170
+ }
171
+
172
+ function validKey(value: unknown): value is ChannelKey {
173
+ return (
174
+ object(value) &&
175
+ typeof value.adapter === 'string' &&
176
+ value.adapter.length > 0 &&
177
+ typeof value.workspace === 'string' &&
178
+ typeof value.chat === 'string' &&
179
+ (value.thread === null || typeof value.thread === 'string')
180
+ )
181
+ }
182
+
183
+ function validReaction(value: unknown): boolean {
184
+ return value === undefined || (object(value) && typeof value.adapter === 'string' && typeof value.value === 'string')
185
+ }
186
+
187
+ class InvalidBackgroundInventory extends Error {}
188
+
189
+ async function readRecord(path: string, hash: string): Promise<BackgroundInventoryRecord | undefined> {
190
+ let raw: string
191
+ try {
192
+ raw = await readFile(path, 'utf8')
193
+ } catch (error) {
194
+ if (missing(error)) return undefined
195
+ throw error
196
+ }
197
+ let record: unknown
198
+ try {
199
+ record = JSON.parse(raw)
200
+ } catch (error) {
201
+ if (!(error instanceof SyntaxError)) throw error
202
+ throw new InvalidBackgroundInventory(`Malformed background inventory: ${path}`, { cause: error })
203
+ }
204
+ if (
205
+ !object(record) ||
206
+ record.schemaVersion !== 1 ||
207
+ !validKey(record.key) ||
208
+ typeof record.parentSessionId !== 'string' ||
209
+ !record.parentSessionId ||
210
+ (record.parentSessionFile !== undefined && !validSessionFile(record.parentSessionFile)) ||
211
+ typeof record.generationId !== 'string' ||
212
+ !generationPattern.test(record.generationId) ||
213
+ typeof record.processEpoch !== 'string' ||
214
+ !record.processEpoch ||
215
+ (record.triggeringAuthorId !== undefined && typeof record.triggeringAuthorId !== 'string') ||
216
+ (record.parentChat !== undefined && (typeof record.parentChat !== 'string' || !record.parentChat)) ||
217
+ (record.accountIdentity !== undefined && (typeof record.accountIdentity !== 'string' || !record.accountIdentity)) ||
218
+ (record.recoveryTransfer !== undefined &&
219
+ (!object(record.recoveryTransfer) ||
220
+ !['notice-prepared', 'notice-owned'].includes(String(record.recoveryTransfer.phase)) ||
221
+ !validateRecoveryRecord(record.recoveryTransfer.record))) ||
222
+ !Array.isArray(record.tasks) ||
223
+ record.tasks.length === 0 ||
224
+ !record.tasks.every(
225
+ (task) =>
226
+ object(task) &&
227
+ typeof task.taskId === 'string' &&
228
+ task.taskId.length > 0 &&
229
+ typeof task.subagentName === 'string' &&
230
+ typeof task.startedAt === 'number' &&
231
+ Number.isFinite(task.startedAt) &&
232
+ (task.accountIdentity === undefined ||
233
+ (typeof task.accountIdentity === 'string' && task.accountIdentity.length > 0)) &&
234
+ validReaction(task.triggerReactionRef),
235
+ ) ||
236
+ new Set(record.tasks.map((task) => task.taskId)).size !== record.tasks.length ||
237
+ recordHash(record.key, record.parentSessionId) !== hash
238
+ ) {
239
+ throw new InvalidBackgroundInventory(`Malformed background inventory: ${path}`)
240
+ }
241
+ const validated = record as BackgroundInventoryRecord
242
+ if (validated.recoveryTransfer && !transferMatchesSource(validated, validated.recoveryTransfer.record)) {
243
+ throw new InvalidBackgroundInventory(`Background recovery transfer does not cover its source: ${path}`)
244
+ }
245
+ return validated
246
+ }
247
+
248
+ async function publish(path: string, record: BackgroundInventoryRecord, exclusive: boolean): Promise<boolean> {
249
+ const temp = `${path}.${randomUUID()}.tmp`
250
+ try {
251
+ const handle = await open(temp, 'wx')
252
+ try {
253
+ await handle.writeFile(`${JSON.stringify(record)}\n`, 'utf8')
254
+ await handle.sync()
255
+ } finally {
256
+ await handle.close()
257
+ }
258
+ if (exclusive) {
259
+ try {
260
+ await link(temp, path)
261
+ } catch (error) {
262
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
263
+ throw error
264
+ }
265
+ } else {
266
+ await rename(temp, path)
267
+ }
268
+ await syncDirectory(dirname(path))
269
+ return true
270
+ } finally {
271
+ await removeFile(temp)
272
+ }
273
+ }
274
+
275
+ export class LegacyBackgroundHandoffReader {
276
+ /** Upgrade-only legacy reader. New launches are admitted by BackgroundObligationStore. */
277
+ readonly processEpoch: string
278
+ private readonly directory: string
279
+ private readonly bootStartedAt: number
280
+ private readonly onError: (error: unknown) => void
281
+ private readonly ownedClaims = new Set<string>()
282
+
283
+ constructor(
284
+ agentDir: string,
285
+ options: { processEpoch?: string; now?: () => number; onError?: (error: unknown) => void } = {},
286
+ ) {
287
+ this.directory = resolve(agentDir, 'channels', 'background-handoffs')
288
+ this.processEpoch = options.processEpoch ?? randomUUID()
289
+ this.bootStartedAt = (options.now ?? Date.now)()
290
+ this.onError = options.onError ?? ((error) => console.error('[background-handoff]', error))
291
+ if (!this.processEpoch) throw new Error('Background inventory requires a process epoch')
292
+ }
293
+
294
+ private report(error: unknown): void {
295
+ try {
296
+ this.onError(error)
297
+ } catch {
298
+ /* Logging must not strand other records. */
299
+ }
300
+ }
301
+
302
+ private async files(): Promise<string[]> {
303
+ try {
304
+ return (await readdir(this.directory)).sort()
305
+ } catch (error) {
306
+ if (!missing(error)) this.report(error)
307
+ return []
308
+ }
309
+ }
310
+
311
+ async claim(): Promise<ClaimedBackgroundInventory[]> {
312
+ const claims: ClaimedBackgroundInventory[] = []
313
+ // A process can die after rename, preparation, or import. Claimed bytes
314
+ // remain a source until durable outbox ownership permits retirement.
315
+ const claimDirectory = join(this.directory, 'claimed')
316
+ let abandoned: string[] = []
317
+ try {
318
+ abandoned = (await readdir(claimDirectory)).sort()
319
+ } catch (error) {
320
+ if (!missing(error)) this.report(error)
321
+ }
322
+ for (const file of abandoned) {
323
+ const match = claimedPattern.exec(file)
324
+ if (!match) continue
325
+ try {
326
+ const claimPath = join(claimDirectory, file)
327
+ const record = await readRecord(claimPath, match[1]!)
328
+ if (record && record.processEpoch !== this.processEpoch && !this.ownedClaims.has(claimPath)) {
329
+ this.ownedClaims.add(claimPath)
330
+ claims.push({ record, claimPath })
331
+ }
332
+ } catch (error) {
333
+ this.report(error)
334
+ }
335
+ }
336
+ for (const file of await this.files()) {
337
+ const path = join(this.directory, file)
338
+ try {
339
+ if (tempPattern.test(file)) {
340
+ if ((await stat(path)).mtimeMs < this.bootStartedAt) await removeFile(path)
341
+ continue
342
+ }
343
+ if (!pendingPattern.test(file)) continue
344
+ const hash = file.slice(0, -5)
345
+ const claim = await serialized(path, async () => {
346
+ const before = await readRecord(path, hash)
347
+ if (!before || before.processEpoch === this.processEpoch) return undefined
348
+ const claimDirectory = join(this.directory, 'claimed')
349
+ await mkdir(claimDirectory, { recursive: true })
350
+ const claimPath = join(claimDirectory, `${hash}.${randomUUID()}.json`)
351
+ try {
352
+ await rename(path, claimPath)
353
+ } catch (error) {
354
+ if (missing(error)) return undefined
355
+ throw error
356
+ }
357
+ await syncDirectory(claimDirectory)
358
+ await syncDirectory(this.directory)
359
+ // The renamed bytes, not the earlier read, are the owned generation.
360
+ const record = await readRecord(claimPath, hash)
361
+ if (!record) return undefined
362
+ if (record.processEpoch === this.processEpoch) {
363
+ await link(claimPath, path)
364
+ await syncDirectory(this.directory)
365
+ await removeFile(claimPath)
366
+ return undefined
367
+ }
368
+ return { record, claimPath }
369
+ })
370
+ if (claim) {
371
+ this.ownedClaims.add(claim.claimPath)
372
+ claims.push(claim)
373
+ }
374
+ } catch (error) {
375
+ if (!missing(error)) this.report(error)
376
+ }
377
+ }
378
+ return claims
379
+ }
380
+
381
+ async prepareRecovery(claim: ClaimedBackgroundInventory, record: RecoveryRecord): Promise<RecoveryRecord> {
382
+ return this.updateRecovery(claim, 'notice-prepared', record)
383
+ }
384
+
385
+ async ownRecovery(claim: ClaimedBackgroundInventory, record: RecoveryRecord): Promise<RecoveryRecord> {
386
+ return this.updateRecovery(claim, 'notice-owned', record)
387
+ }
388
+
389
+ private async updateRecovery(
390
+ claim: ClaimedBackgroundInventory,
391
+ phase: 'notice-prepared' | 'notice-owned',
392
+ recovery: RecoveryRecord,
393
+ ): Promise<RecoveryRecord> {
394
+ const path = resolve(claim.claimPath)
395
+ const match = claimedPattern.exec(basename(path))
396
+ if (dirname(path) !== join(this.directory, 'claimed') || !match) throw new Error('Invalid inventory claim')
397
+ return serialized(path, async () => {
398
+ const current = await readRecord(path, match[1]!)
399
+ if (!current || current.generationId !== claim.record.generationId)
400
+ throw new Error('Background inventory generation changed during transfer')
401
+ const existing = current.recoveryTransfer
402
+ if (existing && JSON.stringify(existing.record) !== JSON.stringify(recovery))
403
+ throw new Error('Conflicting background recovery transfer')
404
+ const frozen = existing?.record ?? recovery
405
+ if (!validateRecoveryRecord(frozen)) throw new Error('Invalid background recovery payload')
406
+ if (!transferMatchesSource(current, frozen))
407
+ throw new Error('Background recovery transfer does not cover its source')
408
+ if (existing?.phase === 'notice-owned') return frozen
409
+ const next = { ...current, recoveryTransfer: { phase, record: frozen } }
410
+ await publish(path, next, false)
411
+ claim.record = next
412
+ return frozen
413
+ })
414
+ }
415
+
416
+ retire(claim: ClaimedBackgroundInventory): Promise<void> {
417
+ const path = resolve(claim.claimPath)
418
+ const match = claimedPattern.exec(basename(path))
419
+ if (
420
+ dirname(path) !== join(this.directory, 'claimed') ||
421
+ !match ||
422
+ match[1] !== recordHash(claim.record.key, claim.record.parentSessionId)
423
+ ) {
424
+ return Promise.reject(new Error('Invalid background inventory claim path'))
425
+ }
426
+ return serialized(path, async () => {
427
+ const current = await readRecord(path, match[1]!)
428
+ if (!current) return
429
+ if (current.generationId !== claim.record.generationId)
430
+ throw new Error('Background inventory generation changed before retirement')
431
+ await removeFile(path)
432
+ })
433
+ }
434
+ }