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,271 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ import { z } from 'zod'
4
+
5
+ import type { MatchableOrigin } from '../permissions/resolve'
6
+ import { ADAPTER_IDS } from './schema'
7
+ import type { ChannelKey } from './types'
8
+
9
+ export type RecoveryCoverage = {
10
+ store: 'inventory' | 'background' | 'inbound'
11
+ id: string
12
+ generation: number
13
+ parentSessionId?: string
14
+ }
15
+ export type RecoveryLease = { epoch: string; generation: number; attemptId: string; acquiredAt: number }
16
+ export type RecoveryReceipt = { confirmedAt: number; messageId?: string; messageIds?: string[] }
17
+ export type RecoveryFailure = {
18
+ kind: 'transient' | 'rate-limit' | 'unavailable' | 'permission' | 'identity' | 'target' | 'configuration'
19
+ safeReason: string
20
+ /** Milliseconds until another attempt is permitted. */
21
+ retryAfter?: number
22
+ }
23
+ /**
24
+ * Why owed coverage was transferred to a notice. `restart` is the frozen RFC en/v1 boot-recovery
25
+ * notice (schemaVersion 1, no `cause` field). `live-turn-ended` is a same-process turn that ended
26
+ * without a confirmed reply; it is a distinct schemaVersion 2 record and never claims a restart.
27
+ */
28
+ export type RecoveryNoticeCause = 'restart' | 'live-turn-ended'
29
+ export type RecoveryRecord = {
30
+ schemaVersion: 1 | 2
31
+ deliveryId: string
32
+ purpose: 'interruption-notice'
33
+ /** Present exactly on schemaVersion 2; absent means the frozen v1 restart notice. */
34
+ cause?: Exclude<RecoveryNoticeCause, 'restart'>
35
+ target: ChannelKey
36
+ accountIdentity: string
37
+ accountIdentityConflict?: string[]
38
+ boundAccountIdentity?: string
39
+ principal: MatchableOrigin
40
+ sourceParentSessionId?: string
41
+ covers: RecoveryCoverage[]
42
+ transferId: string
43
+ recoveryGeneration: string
44
+ templateVersion: 1
45
+ locale: 'en'
46
+ text: string
47
+ createdAt: number
48
+ generation: number
49
+ state: 'pending' | 'leased' | 'delivered' | 'blocked' | 'suppressed'
50
+ lease?: RecoveryLease
51
+ attempts: number
52
+ nextAttemptAt?: number
53
+ receipt?: RecoveryReceipt
54
+ failure?: RecoveryFailure
55
+ suppression?: { reason: string; decisionId: string }
56
+ }
57
+
58
+ export const RECOVERY_NOTICE_TEXT =
59
+ "⚠️ I restarted before I could confirm a reply to your earlier request. I didn't rerun it automatically — please ask again if you still need it."
60
+ export const LIVE_TURN_ENDED_NOTICE_TEXT =
61
+ "⚠️ My earlier turn ended before I could confirm a reply to your request. I didn't rerun it automatically — please ask again if you still need it."
62
+ // Both templates are frozen into persisted outbox payloads (fenced by `recoveryPayload`), so their
63
+ // bytes keep the historical ⚠️ prefix. Users see this rendered form: an interrupted turn is not an
64
+ // alarm, and the emoji is reserved for failures someone has to act on.
65
+ export function recoveryNoticeDisplayText(record: Pick<RecoveryRecord, 'text'>): string {
66
+ return record.text.replace(/^⚠️ /, '')
67
+ }
68
+ const nonempty = z.string().min(1)
69
+ const timestamp = z.number().finite().nonnegative()
70
+ const generation = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
71
+ const target = z
72
+ .object({ adapter: z.enum(ADAPTER_IDS), workspace: z.string(), chat: nonempty, thread: z.string().nullable() })
73
+ .strict()
74
+ const principal = z.discriminatedUnion('kind', [
75
+ z.object({ kind: z.literal('tui'), sessionId: nonempty.optional() }).strict(),
76
+ z.object({ kind: z.literal('cron'), jobId: nonempty.optional() }).strict(),
77
+ z.object({ kind: z.literal('subagent'), subagent: nonempty.optional() }).strict(),
78
+ z
79
+ .object({
80
+ kind: z.literal('channel'),
81
+ adapter: z.enum(ADAPTER_IDS),
82
+ workspace: z.string(),
83
+ chat: nonempty,
84
+ parentChat: nonempty.optional(),
85
+ lastInboundAuthorId: nonempty.optional(),
86
+ })
87
+ .strict(),
88
+ ])
89
+ // Frozen v1 field order: persisted outbox bytes follow it, so never reorder or insert here.
90
+ const recordFields = {
91
+ schemaVersion: z.literal(1),
92
+ deliveryId: z.string().regex(/^[a-f0-9]{64}$/),
93
+ purpose: z.literal('interruption-notice'),
94
+ target,
95
+ accountIdentity: nonempty,
96
+ accountIdentityConflict: z.array(nonempty).min(2).optional(),
97
+ boundAccountIdentity: nonempty.optional(),
98
+ principal,
99
+ sourceParentSessionId: nonempty.optional(),
100
+ covers: z
101
+ .array(
102
+ z
103
+ .object({
104
+ store: z.enum(['inventory', 'background', 'inbound']),
105
+ id: nonempty,
106
+ generation,
107
+ parentSessionId: nonempty.optional(),
108
+ })
109
+ .strict(),
110
+ )
111
+ .min(1),
112
+ transferId: nonempty,
113
+ recoveryGeneration: nonempty,
114
+ templateVersion: z.literal(1),
115
+ locale: z.literal('en'),
116
+ text: z.literal(RECOVERY_NOTICE_TEXT),
117
+ createdAt: timestamp,
118
+ generation,
119
+ state: z.enum(['pending', 'leased', 'delivered', 'blocked', 'suppressed']),
120
+ lease: z.object({ epoch: nonempty, generation, attemptId: nonempty, acquiredAt: timestamp }).strict().optional(),
121
+ attempts: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
122
+ nextAttemptAt: timestamp.optional(),
123
+ receipt: z
124
+ .object({
125
+ confirmedAt: timestamp,
126
+ messageId: nonempty.optional(),
127
+ messageIds: z.array(nonempty).min(1).optional(),
128
+ })
129
+ .strict()
130
+ .optional(),
131
+ failure: z
132
+ .object({
133
+ kind: z.enum(['transient', 'rate-limit', 'unavailable', 'permission', 'identity', 'target', 'configuration']),
134
+ safeReason: nonempty.max(512),
135
+ retryAfter: timestamp.optional(),
136
+ })
137
+ .strict()
138
+ .optional(),
139
+ suppression: z
140
+ .object({ reason: nonempty.max(512), decisionId: nonempty })
141
+ .strict()
142
+ .optional(),
143
+ }
144
+ const schema = z
145
+ .discriminatedUnion('schemaVersion', [
146
+ // en/v1 restart notice: the RFC's frozen boot-recovery template.
147
+ z.object(recordFields).strict(),
148
+ // v2 names its non-restart cause explicitly and pins that cause's own frozen template.
149
+ z
150
+ .object({
151
+ ...recordFields,
152
+ schemaVersion: z.literal(2),
153
+ text: z.literal(LIVE_TURN_ENDED_NOTICE_TEXT),
154
+ cause: z.literal('live-turn-ended'),
155
+ })
156
+ .strict(),
157
+ ])
158
+ .superRefine((record, context) => {
159
+ const invalid = (message: string) => context.addIssue({ code: 'custom', message })
160
+ if (new Set(record.covers.map((cover) => `${cover.store}:${cover.id}`)).size !== record.covers.length)
161
+ invalid('Duplicate coverage')
162
+ if (record.deliveryId !== recoveryDeliveryId(record)) invalid('Delivery identity mismatch')
163
+ if (
164
+ record.boundAccountIdentity !== undefined &&
165
+ (record.accountIdentity !== 'unbound-legacy' || record.boundAccountIdentity === 'unbound-legacy')
166
+ )
167
+ invalid('Invalid legacy account binding')
168
+ if (
169
+ record.accountIdentityConflict !== undefined &&
170
+ (record.accountIdentity !== 'unbound-legacy' ||
171
+ record.accountIdentityConflict.some(
172
+ (identity, index, identities) =>
173
+ identity === 'unbound-legacy' || (index > 0 && identities[index - 1]! >= identity),
174
+ ))
175
+ )
176
+ invalid('Invalid account identity conflict')
177
+ if (record.state === 'leased' && (!record.lease || record.lease.generation !== record.generation))
178
+ invalid('Invalid lease ownership')
179
+ if (record.lease && (record.lease.generation > record.generation || record.attempts === 0))
180
+ invalid('Invalid lease generation')
181
+ if (record.attempts >= record.generation) invalid('Attempts exceed ownership generation')
182
+ if (record.state === 'delivered' && (!record.lease || record.lease.generation !== record.generation))
183
+ invalid('Invalid delivered ownership')
184
+ if ((record.state === 'leased' || record.state === 'delivered') && record.failure)
185
+ invalid('Failure on active or delivered record')
186
+ if (record.failure && record.attempts === 0) invalid('Failure before dispatch attempt')
187
+ if (
188
+ record.state === 'blocked' &&
189
+ record.failure &&
190
+ !['permission', 'identity', 'target', 'configuration'].includes(record.failure.kind)
191
+ )
192
+ invalid('Transient failure cannot block')
193
+ if (record.receipt && !record.lease) invalid('Receipt without dispatch ownership')
194
+ if (record.state === 'delivered' && !record.receipt) invalid('Missing delivery receipt')
195
+ if (record.receipt && record.state !== 'delivered' && record.state !== 'suppressed')
196
+ invalid('Receipt on unresolved record')
197
+ if (record.state === 'blocked' && !record.failure) invalid('Missing blocked failure')
198
+ if ((record.state === 'pending' || record.state === 'blocked') && record.lease) invalid('Lease on unclaimed record')
199
+ if ((record.state === 'suppressed') !== !!record.suppression) invalid('Invalid suppression state')
200
+ if (record.nextAttemptAt !== undefined && record.state !== 'pending' && record.state !== 'blocked')
201
+ invalid('Retry on terminal or leased record')
202
+ })
203
+
204
+ type DeliveryIdentity = Pick<
205
+ RecoveryRecord,
206
+ 'purpose' | 'target' | 'accountIdentity' | 'covers' | 'recoveryGeneration' | 'cause'
207
+ >
208
+ export function recoveryDeliveryId(record: DeliveryIdentity): string {
209
+ const covers = record.covers
210
+ .map((cover) => [cover.store, cover.id, cover.generation, cover.parentSessionId ?? null])
211
+ .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))
212
+ // The v1 restart seed is frozen; a non-restart notice gets its own seed so the two can never share an ID.
213
+ const seed = record.cause === undefined ? ['typeclaw:recovery:v1'] : ['typeclaw:recovery:v2', record.cause]
214
+ return createHash('sha256')
215
+ .update(
216
+ JSON.stringify([
217
+ ...seed,
218
+ record.purpose,
219
+ [record.target.adapter, record.target.workspace, record.target.chat, record.target.thread],
220
+ record.accountIdentity,
221
+ covers,
222
+ record.recoveryGeneration,
223
+ ]),
224
+ )
225
+ .digest('hex')
226
+ }
227
+ export function recoveryNoticeCause(record: Pick<RecoveryRecord, 'cause'>): RecoveryNoticeCause {
228
+ return record.cause ?? 'restart'
229
+ }
230
+ export function validateRecoveryRecord(value: unknown): value is RecoveryRecord {
231
+ return schema.safeParse(value).success
232
+ }
233
+ export function parseRecoveryRecord(value: unknown): RecoveryRecord {
234
+ return schema.parse(value) as RecoveryRecord
235
+ }
236
+
237
+ /** Stable comparison of the frozen transfer payload, excluding dispatch state. */
238
+ export function recoveryPayload(record: RecoveryRecord): string {
239
+ return JSON.stringify([
240
+ record.deliveryId,
241
+ record.purpose,
242
+ record.target.adapter,
243
+ record.target.workspace,
244
+ record.target.chat,
245
+ record.target.thread,
246
+ record.accountIdentity,
247
+ record.accountIdentityConflict ?? null,
248
+ canonical(record.principal),
249
+ record.sourceParentSessionId ?? null,
250
+ record.covers.map(canonical).sort(),
251
+ record.transferId,
252
+ record.recoveryGeneration,
253
+ record.templateVersion,
254
+ record.locale,
255
+ record.text,
256
+ record.createdAt,
257
+ // v1 strings stay byte-identical; later versions also compare their explicit cause.
258
+ ...(record.schemaVersion === 1 ? [] : [record.schemaVersion, record.cause ?? null]),
259
+ ])
260
+ }
261
+ /** Fixed-size fence for a frozen transfer payload once the full record is no longer retained. */
262
+ export function recoveryPayloadDigest(record: RecoveryRecord): string {
263
+ return createHash('sha256').update(recoveryPayload(record)).digest('hex')
264
+ }
265
+ function canonical(value: object): string {
266
+ return JSON.stringify(
267
+ Object.entries(value)
268
+ .filter(([, field]) => field !== undefined)
269
+ .sort(([a], [b]) => a.localeCompare(b)),
270
+ )
271
+ }