coremind-runtime 0.3.1 → 0.7.1

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 (201) hide show
  1. package/README.md +49 -1
  2. package/dist/active-run-binding.d.ts +24 -0
  3. package/dist/active-run-binding.d.ts.map +1 -0
  4. package/dist/active-run-binding.js +22 -0
  5. package/dist/active-run-binding.js.map +1 -0
  6. package/dist/agent-driver.d.ts +139 -0
  7. package/dist/agent-driver.d.ts.map +1 -0
  8. package/dist/agent-driver.js +135 -0
  9. package/dist/agent-driver.js.map +1 -0
  10. package/dist/agent-factory.d.ts +10 -10
  11. package/dist/agent-factory.d.ts.map +1 -1
  12. package/dist/agent-factory.js +179 -14
  13. package/dist/agent-factory.js.map +1 -1
  14. package/dist/budget.d.ts +11 -1
  15. package/dist/budget.d.ts.map +1 -1
  16. package/dist/budget.js +59 -16
  17. package/dist/budget.js.map +1 -1
  18. package/dist/canonical-json.d.ts +3 -0
  19. package/dist/canonical-json.d.ts.map +1 -0
  20. package/dist/canonical-json.js +28 -0
  21. package/dist/canonical-json.js.map +1 -0
  22. package/dist/chat-session.d.ts +3 -0
  23. package/dist/chat-session.d.ts.map +1 -1
  24. package/dist/chat-session.js +5 -0
  25. package/dist/chat-session.js.map +1 -1
  26. package/dist/checkpoint.d.ts +25 -8
  27. package/dist/checkpoint.d.ts.map +1 -1
  28. package/dist/checkpoint.js +135 -52
  29. package/dist/checkpoint.js.map +1 -1
  30. package/dist/child-run.d.ts +344 -0
  31. package/dist/child-run.d.ts.map +1 -0
  32. package/dist/child-run.js +1373 -0
  33. package/dist/child-run.js.map +1 -0
  34. package/dist/child-runtime-adapter.d.ts +18 -0
  35. package/dist/child-runtime-adapter.d.ts.map +1 -0
  36. package/dist/child-runtime-adapter.js +309 -0
  37. package/dist/child-runtime-adapter.js.map +1 -0
  38. package/dist/compaction-projection.d.ts +5 -0
  39. package/dist/compaction-projection.d.ts.map +1 -1
  40. package/dist/compaction-projection.js +19 -1
  41. package/dist/compaction-projection.js.map +1 -1
  42. package/dist/context-lifecycle.d.ts +182 -0
  43. package/dist/context-lifecycle.d.ts.map +1 -0
  44. package/dist/context-lifecycle.js +455 -0
  45. package/dist/context-lifecycle.js.map +1 -0
  46. package/dist/context-task-state.d.ts +23 -0
  47. package/dist/context-task-state.d.ts.map +1 -0
  48. package/dist/context-task-state.js +183 -0
  49. package/dist/context-task-state.js.map +1 -0
  50. package/dist/control-inbox.d.ts +106 -0
  51. package/dist/control-inbox.d.ts.map +1 -0
  52. package/dist/control-inbox.js +291 -0
  53. package/dist/control-inbox.js.map +1 -0
  54. package/dist/delegated-context.d.ts +29 -0
  55. package/dist/delegated-context.d.ts.map +1 -0
  56. package/dist/delegated-context.js +76 -0
  57. package/dist/delegated-context.js.map +1 -0
  58. package/dist/delegation-tool.d.ts +30 -0
  59. package/dist/delegation-tool.d.ts.map +1 -0
  60. package/dist/delegation-tool.js +232 -0
  61. package/dist/delegation-tool.js.map +1 -0
  62. package/dist/effect-receipt-binding.d.ts +34 -0
  63. package/dist/effect-receipt-binding.d.ts.map +1 -0
  64. package/dist/effect-receipt-binding.js +125 -0
  65. package/dist/effect-receipt-binding.js.map +1 -0
  66. package/dist/errors.d.ts +11 -315
  67. package/dist/errors.d.ts.map +1 -1
  68. package/dist/errors.js +7 -129
  69. package/dist/errors.js.map +1 -1
  70. package/dist/evaluation.d.ts.map +1 -1
  71. package/dist/evaluation.js +12 -5
  72. package/dist/evaluation.js.map +1 -1
  73. package/dist/events.d.ts +91 -3
  74. package/dist/events.d.ts.map +1 -1
  75. package/dist/events.js +44 -0
  76. package/dist/events.js.map +1 -1
  77. package/dist/execution-error.d.ts +14 -0
  78. package/dist/execution-error.d.ts.map +1 -0
  79. package/dist/execution-error.js +129 -0
  80. package/dist/execution-error.js.map +1 -0
  81. package/dist/execution-security.d.ts +11 -0
  82. package/dist/execution-security.d.ts.map +1 -0
  83. package/dist/execution-security.js +45 -0
  84. package/dist/execution-security.js.map +1 -0
  85. package/dist/fact-ledger.d.ts +60 -0
  86. package/dist/fact-ledger.d.ts.map +1 -0
  87. package/dist/fact-ledger.js +167 -0
  88. package/dist/fact-ledger.js.map +1 -0
  89. package/dist/ids.d.ts +4 -0
  90. package/dist/ids.d.ts.map +1 -1
  91. package/dist/ids.js.map +1 -1
  92. package/dist/index.d.ts +15 -5
  93. package/dist/index.d.ts.map +1 -1
  94. package/dist/index.js +11 -2
  95. package/dist/index.js.map +1 -1
  96. package/dist/internal.d.ts +12 -0
  97. package/dist/internal.d.ts.map +1 -0
  98. package/dist/internal.js +12 -0
  99. package/dist/internal.js.map +1 -0
  100. package/dist/invariant-checker.d.ts.map +1 -1
  101. package/dist/invariant-checker.js +51 -10
  102. package/dist/invariant-checker.js.map +1 -1
  103. package/dist/loop-runner.d.ts.map +1 -1
  104. package/dist/loop-runner.js +14 -8
  105. package/dist/loop-runner.js.map +1 -1
  106. package/dist/observability.d.ts +211 -0
  107. package/dist/observability.d.ts.map +1 -0
  108. package/dist/observability.js +814 -0
  109. package/dist/observability.js.map +1 -0
  110. package/dist/orchestrator.d.ts +2 -2
  111. package/dist/orchestrator.d.ts.map +1 -1
  112. package/dist/orchestrator.js +12 -6
  113. package/dist/orchestrator.js.map +1 -1
  114. package/dist/project-check.d.ts +3 -0
  115. package/dist/project-check.d.ts.map +1 -1
  116. package/dist/project-check.js +21 -5
  117. package/dist/project-check.js.map +1 -1
  118. package/dist/projection.d.ts +131 -0
  119. package/dist/projection.d.ts.map +1 -0
  120. package/dist/projection.js +981 -0
  121. package/dist/projection.js.map +1 -0
  122. package/dist/provider.d.ts +23 -1
  123. package/dist/provider.d.ts.map +1 -1
  124. package/dist/provider.js +134 -23
  125. package/dist/provider.js.map +1 -1
  126. package/dist/public-tool.d.ts +3 -0
  127. package/dist/public-tool.d.ts.map +1 -1
  128. package/dist/public-tool.js +28 -3
  129. package/dist/public-tool.js.map +1 -1
  130. package/dist/replay-kit.d.ts +41 -0
  131. package/dist/replay-kit.d.ts.map +1 -0
  132. package/dist/replay-kit.js +96 -0
  133. package/dist/replay-kit.js.map +1 -0
  134. package/dist/result.d.ts +17 -1
  135. package/dist/result.d.ts.map +1 -1
  136. package/dist/result.js +16 -0
  137. package/dist/result.js.map +1 -1
  138. package/dist/retry-policy.d.ts.map +1 -1
  139. package/dist/retry-policy.js +22 -72
  140. package/dist/retry-policy.js.map +1 -1
  141. package/dist/run-context.d.ts +77 -0
  142. package/dist/run-context.d.ts.map +1 -0
  143. package/dist/run-context.js +159 -0
  144. package/dist/run-context.js.map +1 -0
  145. package/dist/run-effect-coordinator.d.ts.map +1 -1
  146. package/dist/run-effect-coordinator.js +3 -0
  147. package/dist/run-effect-coordinator.js.map +1 -1
  148. package/dist/run-kernel.d.ts +14 -0
  149. package/dist/run-kernel.d.ts.map +1 -0
  150. package/dist/run-kernel.js +34 -0
  151. package/dist/run-kernel.js.map +1 -0
  152. package/dist/run-state.d.ts +71 -5
  153. package/dist/run-state.d.ts.map +1 -1
  154. package/dist/run-state.js +601 -78
  155. package/dist/run-state.js.map +1 -1
  156. package/dist/run-terminalizer.d.ts.map +1 -1
  157. package/dist/run-terminalizer.js +4 -3
  158. package/dist/run-terminalizer.js.map +1 -1
  159. package/dist/runtime-instance-authority.d.ts +3 -0
  160. package/dist/runtime-instance-authority.d.ts.map +1 -0
  161. package/dist/runtime-instance-authority.js +8 -0
  162. package/dist/runtime-instance-authority.js.map +1 -0
  163. package/dist/runtime.d.ts +93 -2
  164. package/dist/runtime.d.ts.map +1 -1
  165. package/dist/runtime.js +2136 -347
  166. package/dist/runtime.js.map +1 -1
  167. package/dist/session.d.ts +4 -3
  168. package/dist/session.d.ts.map +1 -1
  169. package/dist/session.js.map +1 -1
  170. package/dist/tool-call-lifecycle.d.ts +89 -0
  171. package/dist/tool-call-lifecycle.d.ts.map +1 -0
  172. package/dist/tool-call-lifecycle.js +379 -0
  173. package/dist/tool-call-lifecycle.js.map +1 -0
  174. package/dist/tool-capability-identity.d.ts +3 -0
  175. package/dist/tool-capability-identity.d.ts.map +1 -0
  176. package/dist/tool-capability-identity.js +5 -0
  177. package/dist/tool-capability-identity.js.map +1 -0
  178. package/dist/tool-capability-projection.d.ts +17 -0
  179. package/dist/tool-capability-projection.d.ts.map +1 -0
  180. package/dist/tool-capability-projection.js +99 -0
  181. package/dist/tool-capability-projection.js.map +1 -0
  182. package/dist/tool-effect-selectors.d.ts +3 -0
  183. package/dist/tool-effect-selectors.d.ts.map +1 -0
  184. package/dist/tool-effect-selectors.js +18 -0
  185. package/dist/tool-effect-selectors.js.map +1 -0
  186. package/dist/tool-policy.d.ts +13 -2
  187. package/dist/tool-policy.d.ts.map +1 -1
  188. package/dist/tool-policy.js +149 -44
  189. package/dist/tool-policy.js.map +1 -1
  190. package/dist/trace.d.ts +1 -0
  191. package/dist/trace.d.ts.map +1 -1
  192. package/dist/trace.js +10 -3
  193. package/dist/trace.js.map +1 -1
  194. package/dist/turn-tracker.d.ts.map +1 -1
  195. package/dist/turn-tracker.js +1 -0
  196. package/dist/turn-tracker.js.map +1 -1
  197. package/dist/workspace-lease.d.ts +81 -0
  198. package/dist/workspace-lease.d.ts.map +1 -0
  199. package/dist/workspace-lease.js +300 -0
  200. package/dist/workspace-lease.js.map +1 -0
  201. package/package.json +11 -5
package/dist/run-state.js CHANGED
@@ -1,12 +1,24 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { isResolvedToolCapability, RECOVERY_DISPOSITIONS, recoveryDispositionFor, } from "coremind-tools";
5
+ import { canonicalJson as stableJson } from "./canonical-json.js";
6
+ import { validateEffectReceiptBindingsAgainstFacts } from "./effect-receipt-binding.js";
4
7
  import { CoreMindError } from "./errors.js";
5
- import { inputFingerprint } from "./input-receipt.js";
8
+ import { FactLedger, flushFactLedgerWith, } from "./fact-ledger.js";
9
+ import { foldInputReceipts, inputFingerprint } from "./input-receipt.js";
6
10
  import { restoreDurableOperation, } from "./operation-state.js";
11
+ import { projectToolCallLifecycles, validateToolCallLifecycleFact } from "./tool-call-lifecycle.js";
12
+ import { toolCapabilityCallKey } from "./tool-capability-identity.js";
13
+ import { projectToolCapabilities } from "./tool-capability-projection.js";
14
+ // ponytail: 只缓存父 Run 与默认 32 个子 Run 的近期游标;淘汰后全量复核,不牺牲正确性。
15
+ const MAX_RUN_FILE_CURSORS = 64;
7
16
  export class FileRunStore {
8
17
  directory;
9
18
  options;
19
+ supportedDurability = ["ordinary", "critical"];
20
+ durabilityBoundary = "process_crash";
21
+ cursors = new Map();
10
22
  constructor(directory, options = {}) {
11
23
  this.directory = directory;
12
24
  this.options = options;
@@ -19,23 +31,7 @@ export class FileRunStore {
19
31
  }
20
32
  async append(record) {
21
33
  try {
22
- const destination = this.pathFor(record.runId);
23
- validateRecord(record, record.runId);
24
- await this.withWriterLock(destination, async () => {
25
- const parsed = await this.readUnlocked(record.runId, destination);
26
- const duplicate = parsed.records.find((item) => item.sequence === record.sequence);
27
- if (duplicate) {
28
- if (stableJson(duplicate) === stableJson(record))
29
- return;
30
- throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 的 sequence ${record.sequence} 已由另一条记录占用`);
31
- }
32
- const expectedSequence = (parsed.records.at(-1)?.sequence ?? 0) + 1;
33
- if (record.sequence !== expectedSequence) {
34
- throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 期望 sequence ${expectedSequence},实际为 ${record.sequence}`);
35
- }
36
- const text = `${parsed.records.map((item) => JSON.stringify(item)).join("\n")}${parsed.records.length > 0 ? "\n" : ""}${JSON.stringify(record)}\n`;
37
- await this.publishAtomically(destination, text, record);
38
- });
34
+ await this.writeRecord(record, "ordinary");
39
35
  }
40
36
  catch (error) {
41
37
  if (error instanceof CoreMindError)
@@ -43,6 +39,42 @@ export class FileRunStore {
43
39
  throw new CoreMindError("run_state_failed", `RunState 写入失败:${error instanceof Error ? error.message : String(error)}`);
44
40
  }
45
41
  }
42
+ async commit(record, durability) {
43
+ assertSupportedDurability(this, durability);
44
+ try {
45
+ await this.writeRecord(record, durability);
46
+ return durabilityAcknowledgement(this, durability);
47
+ }
48
+ catch (error) {
49
+ if (error instanceof CoreMindError)
50
+ throw error;
51
+ const code = durability === "critical" ? "durability_barrier_failed" : "run_state_failed";
52
+ throw new CoreMindError(code, `RunState ${record.runId} 的 ${durability} commit 失败:${error instanceof Error ? error.message : String(error)}`);
53
+ }
54
+ }
55
+ async barrier(runId, requested) {
56
+ assertSupportedDurability(this, requested);
57
+ if (requested === "ordinary")
58
+ return durabilityAcknowledgement(this, requested);
59
+ const destination = this.pathFor(runId);
60
+ try {
61
+ return await this.withWriterLock(destination, async () => {
62
+ let handle;
63
+ try {
64
+ handle = await open(destination, "r+");
65
+ await this.options.beforeBarrier?.({ destination, runId, requested });
66
+ await handle.sync();
67
+ return durabilityAcknowledgement(this, requested);
68
+ }
69
+ finally {
70
+ await handle?.close().catch(() => undefined);
71
+ }
72
+ });
73
+ }
74
+ catch (error) {
75
+ throw new CoreMindError("durability_barrier_failed", `RunState ${runId} 的 critical barrier 失败:${error instanceof Error ? error.message : String(error)}`);
76
+ }
77
+ }
46
78
  async read(runId) {
47
79
  try {
48
80
  const destination = this.pathFor(runId);
@@ -51,6 +83,7 @@ export class FileRunStore {
51
83
  if (parsed.repairedText !== undefined) {
52
84
  await this.publishAtomically(destination, parsed.repairedText);
53
85
  }
86
+ await this.rememberCursor(destination, parsed.records.at(-1), parsed.needsSeparator ?? false);
54
87
  return parsed.records;
55
88
  });
56
89
  }
@@ -98,32 +131,191 @@ export class FileRunStore {
98
131
  }
99
132
  records.push(record);
100
133
  }
101
- return { records };
134
+ return { records, needsSeparator: text.length > 0 && !terminated };
102
135
  }
103
- async publishAtomically(destination, text, record) {
136
+ async publishAtomically(destination, text, record, durability = "ordinary") {
104
137
  const temporary = `${destination}.${process.pid}.${randomUUID()}.tmp`;
105
138
  try {
106
139
  await writeFile(temporary, text, { encoding: "utf8", flag: "wx" });
107
140
  await this.options.beforeCommit?.({ destination, temporary, record });
108
- await rename(temporary, destination);
141
+ if (durability === "critical") {
142
+ let handle;
143
+ try {
144
+ handle = await open(temporary, "r+");
145
+ await this.options.beforeBarrier?.({
146
+ destination,
147
+ runId: record.runId,
148
+ requested: durability,
149
+ record,
150
+ });
151
+ await handle.sync();
152
+ }
153
+ finally {
154
+ await handle?.close().catch(() => undefined);
155
+ }
156
+ }
157
+ await renameAtomically(temporary, destination);
158
+ }
159
+ finally {
160
+ await rm(temporary, { force: true }).catch(() => undefined);
161
+ }
162
+ }
163
+ async prepareAppend(destination, record, text) {
164
+ if (!this.options.beforeCommit)
165
+ return;
166
+ const temporary = `${destination}.${process.pid}.${randomUUID()}.tmp`;
167
+ try {
168
+ await writeFile(temporary, text, { encoding: "utf8", flag: "wx" });
169
+ await this.options.beforeCommit({ destination, temporary, record });
109
170
  }
110
171
  finally {
111
172
  await rm(temporary, { force: true }).catch(() => undefined);
112
173
  }
113
174
  }
175
+ async fileIdentity(destination) {
176
+ try {
177
+ const current = await stat(destination);
178
+ return {
179
+ dev: current.dev,
180
+ ino: current.ino,
181
+ size: current.size,
182
+ mtimeMs: current.mtimeMs,
183
+ ctimeMs: current.ctimeMs,
184
+ };
185
+ }
186
+ catch (error) {
187
+ if (error.code === "ENOENT")
188
+ return undefined;
189
+ throw error;
190
+ }
191
+ }
192
+ async rememberCursor(destination, lastRecord, needsSeparator, identity) {
193
+ const resolvedIdentity = identity ?? (await this.fileIdentity(destination));
194
+ this.cursors.delete(destination);
195
+ this.cursors.set(destination, {
196
+ identity: resolvedIdentity,
197
+ lastRecord: lastRecord ? structuredClone(lastRecord) : undefined,
198
+ needsSeparator,
199
+ });
200
+ if (this.cursors.size > MAX_RUN_FILE_CURSORS) {
201
+ this.cursors.delete(this.cursors.keys().next().value);
202
+ }
203
+ }
204
+ sameIdentity(left, right) {
205
+ if (!left || !right)
206
+ return left === right;
207
+ return (left.dev === right.dev &&
208
+ left.ino === right.ino &&
209
+ left.size === right.size &&
210
+ left.mtimeMs === right.mtimeMs &&
211
+ left.ctimeMs === right.ctimeMs);
212
+ }
213
+ async writeRecord(record, durability) {
214
+ const destination = this.pathFor(record.runId);
215
+ validateRecord(record, record.runId);
216
+ await this.withWriterLock(destination, async () => {
217
+ const currentIdentity = await this.fileIdentity(destination);
218
+ const cached = this.cursors.get(destination);
219
+ let records;
220
+ let tail = cached && this.sameIdentity(cached.identity, currentIdentity)
221
+ ? { record: cached.lastRecord, needsSeparator: cached.needsSeparator }
222
+ : undefined;
223
+ if (!tail || (tail.record && record.sequence < tail.record.sequence)) {
224
+ const parsed = await this.readUnlocked(record.runId, destination);
225
+ records = parsed.records;
226
+ if (parsed.repairedText !== undefined) {
227
+ await this.publishAtomically(destination, parsed.repairedText);
228
+ }
229
+ tail = {
230
+ record: parsed.records.at(-1),
231
+ needsSeparator: parsed.repairedText === undefined && (parsed.needsSeparator ?? false),
232
+ };
233
+ await this.rememberCursor(destination, tail.record, tail.needsSeparator);
234
+ }
235
+ const duplicate = tail.record?.sequence === record.sequence
236
+ ? tail.record
237
+ : records?.find((item) => item.sequence === record.sequence);
238
+ if (duplicate) {
239
+ if (stableJson(duplicate) === stableJson(record)) {
240
+ if (durability === "critical") {
241
+ let handle;
242
+ try {
243
+ handle = await open(destination, "r+");
244
+ await this.options.beforeBarrier?.({
245
+ destination,
246
+ runId: record.runId,
247
+ requested: durability,
248
+ record,
249
+ });
250
+ await handle.sync();
251
+ }
252
+ finally {
253
+ await handle?.close().catch(() => undefined);
254
+ }
255
+ }
256
+ return;
257
+ }
258
+ throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 的 sequence ${record.sequence} 已由另一条记录占用`);
259
+ }
260
+ const expectedSequence = (tail.record?.sequence ?? records?.at(-1)?.sequence ?? 0) + 1;
261
+ if (record.sequence !== expectedSequence) {
262
+ throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 期望 sequence ${expectedSequence},实际为 ${record.sequence}`);
263
+ }
264
+ const serializedRecord = JSON.stringify(record);
265
+ if (durability === "critical" || record.sequence === 1) {
266
+ if (!records) {
267
+ const parsed = await this.readUnlocked(record.runId, destination);
268
+ records = parsed.records;
269
+ if (parsed.repairedText !== undefined) {
270
+ await this.publishAtomically(destination, parsed.repairedText);
271
+ }
272
+ }
273
+ const text = `${records.map((item) => JSON.stringify(item)).join("\n")}${records.length > 0 ? "\n" : ""}${serializedRecord}\n`;
274
+ await this.publishAtomically(destination, text, record, durability);
275
+ await this.rememberCursor(destination, JSON.parse(serializedRecord), false);
276
+ return;
277
+ }
278
+ const text = `${tail.needsSeparator ? "\n" : ""}${serializedRecord}\n`;
279
+ await this.prepareAppend(destination, record, text);
280
+ let handle;
281
+ try {
282
+ handle = await open(destination, "a");
283
+ await handle.writeFile(text, "utf8");
284
+ }
285
+ finally {
286
+ await handle?.close().catch(() => undefined);
287
+ }
288
+ await this.rememberCursor(destination, JSON.parse(serializedRecord), false);
289
+ });
290
+ }
114
291
  async withWriterLock(destination, operation) {
115
292
  await mkdir(this.directory, { recursive: true });
116
293
  const lockPath = `${destination}.lock`;
117
- const deadline = Date.now() + (this.options.lockTimeoutMs ?? 2_000);
118
- let handle;
119
- while (!handle) {
294
+ const deadline = Date.now() + (this.options.lockTimeoutMs ?? 10_000);
295
+ const owner = {
296
+ pid: process.pid,
297
+ createdAt: new Date().toISOString(),
298
+ nonce: randomUUID(),
299
+ };
300
+ let acquired = false;
301
+ let transientPermissionError;
302
+ while (!acquired) {
120
303
  try {
121
- handle = await open(lockPath, "wx");
304
+ await publishWriterLock(lockPath, owner);
305
+ acquired = true;
122
306
  }
123
307
  catch (error) {
124
- if (error.code !== "EEXIST")
308
+ const contention = await classifyWriterLockContention(error, lockPath);
309
+ if (contention === "not_contention")
125
310
  throw error;
311
+ if (contention === "transient_missing")
312
+ transientPermissionError ??= error;
313
+ if (await this.reclaimStaleWriterLock(lockPath))
314
+ continue;
126
315
  if (Date.now() >= deadline) {
316
+ if (contention === "transient_missing" && transientPermissionError) {
317
+ throw transientPermissionError;
318
+ }
127
319
  throw new CoreMindError("run_state_locked", `RunState ${path.basename(destination)} 正由另一 writer 使用`);
128
320
  }
129
321
  await new Promise((resolve) => setTimeout(resolve, 5));
@@ -133,14 +325,128 @@ export class FileRunStore {
133
325
  return await operation();
134
326
  }
135
327
  finally {
136
- await handle.close();
137
328
  await rm(lockPath, { force: true });
138
329
  }
139
330
  }
331
+ async reclaimStaleWriterLock(lockPath) {
332
+ const inspected = await inspectWriterLock(lockPath);
333
+ if (inspected.state !== "valid" || isProcessAlive(inspected.owner.pid))
334
+ return false;
335
+ const claimPath = `${lockPath}.reclaim-${inspected.owner.nonce}`;
336
+ const tombstonePath = `${claimPath}.tombstone-${randomUUID()}`;
337
+ let claimHandle;
338
+ try {
339
+ claimHandle = await open(claimPath, "wx");
340
+ }
341
+ catch (error) {
342
+ if (error.code === "EEXIST")
343
+ return false;
344
+ throw error;
345
+ }
346
+ try {
347
+ await claimHandle.writeFile(JSON.stringify({ pid: process.pid, ownerNonce: inspected.owner.nonce }), "utf8");
348
+ const current = await inspectWriterLock(lockPath);
349
+ if (current.state !== "valid" ||
350
+ current.owner.nonce !== inspected.owner.nonce ||
351
+ isProcessAlive(current.owner.pid)) {
352
+ return false;
353
+ }
354
+ // 固定 claim 文件由 wx 原子选出唯一回收者;只移动已复核的旧锁,随后只删 tombstone,
355
+ // 永远不对可能已由新 writer 重建的 lockPath 执行删除。
356
+ await rename(lockPath, tombstonePath);
357
+ return true;
358
+ }
359
+ finally {
360
+ await claimHandle.close().catch(() => undefined);
361
+ await rm(tombstonePath, { force: true }).catch(() => undefined);
362
+ await rm(claimPath, { force: true }).catch(() => undefined);
363
+ }
364
+ }
365
+ }
366
+ async function publishWriterLock(lockPath, owner) {
367
+ const candidatePath = `${lockPath}.candidate-${owner.nonce}`;
368
+ try {
369
+ // 先完整并持久化候选文件,再通过 hard link 原子发布,避免崩溃留下无 owner 的空锁。
370
+ await writeFile(candidatePath, JSON.stringify(owner), {
371
+ encoding: "utf8",
372
+ flag: "wx",
373
+ flush: true,
374
+ });
375
+ await link(candidatePath, lockPath);
376
+ }
377
+ finally {
378
+ await rm(candidatePath, { force: true }).catch(() => undefined);
379
+ }
380
+ }
381
+ const ATOMIC_RENAME_RETRY_DELAYS_MS = [5, 10, 20, 40, 80, 160, 320, 640, 1_280];
382
+ /** Windows 扫描器可能短暂占用新文件;只重试可恢复的 rename 错误。 */
383
+ async function renameAtomically(temporary, destination) {
384
+ for (let attempt = 0;; attempt += 1) {
385
+ try {
386
+ await rename(temporary, destination);
387
+ return;
388
+ }
389
+ catch (error) {
390
+ const delay = ATOMIC_RENAME_RETRY_DELAYS_MS[attempt];
391
+ if (delay === undefined || !isTransientRenameError(error))
392
+ throw error;
393
+ await new Promise((resolve) => setTimeout(resolve, delay));
394
+ }
395
+ }
396
+ }
397
+ function isTransientRenameError(error) {
398
+ const code = error?.code;
399
+ return code === "EPERM" || code === "EACCES" || code === "EBUSY";
400
+ }
401
+ async function classifyWriterLockContention(error, lockPath) {
402
+ const code = error.code;
403
+ if (code === "EEXIST") {
404
+ return (await inspectWriterLock(lockPath)).state === "valid"
405
+ ? "valid_contention"
406
+ : "path_contention";
407
+ }
408
+ if (process.platform !== "win32" || (code !== "EPERM" && code !== "EACCES")) {
409
+ return "not_contention";
410
+ }
411
+ const inspected = await inspectWriterLock(lockPath);
412
+ if (inspected.state === "valid")
413
+ return "valid_contention";
414
+ // 锁刚好消失时允许短暂重试,但若截止前从未观察到有效 owner,调用方保留原权限异常。
415
+ return inspected.state === "missing" ? "transient_missing" : "not_contention";
416
+ }
417
+ async function inspectWriterLock(lockPath) {
418
+ try {
419
+ const owner = JSON.parse(await readFile(lockPath, "utf8"));
420
+ if (typeof owner.pid === "number" &&
421
+ Number.isInteger(owner.pid) &&
422
+ owner.pid > 0 &&
423
+ typeof owner.nonce === "string" &&
424
+ owner.nonce.length > 0) {
425
+ return { state: "valid", owner: { pid: owner.pid, nonce: owner.nonce } };
426
+ }
427
+ return { state: "invalid" };
428
+ }
429
+ catch (error) {
430
+ return error.code === "ENOENT"
431
+ ? { state: "missing" }
432
+ : { state: "invalid" };
433
+ }
434
+ }
435
+ function isProcessAlive(pid) {
436
+ try {
437
+ process.kill(pid, 0);
438
+ return true;
439
+ }
440
+ catch (error) {
441
+ return error.code !== "ESRCH";
442
+ }
140
443
  }
141
444
  export class MemoryRunStore {
445
+ supportedDurability = ["ordinary"];
446
+ durabilityBoundary = "process_memory";
142
447
  records = new Map();
143
448
  async append(record) {
449
+ validateRecord(record, record.runId);
144
450
  const items = this.records.get(record.runId) ?? [];
145
451
  const duplicate = items.find((item) => item.sequence === record.sequence);
146
452
  if (duplicate) {
@@ -155,23 +461,35 @@ export class MemoryRunStore {
155
461
  items.push(structuredClone(record));
156
462
  this.records.set(record.runId, items);
157
463
  }
464
+ async commit(record, durability) {
465
+ assertSupportedDurability(this, durability);
466
+ await this.append(record);
467
+ return durabilityAcknowledgement(this, durability);
468
+ }
158
469
  async read(runId) {
159
470
  return structuredClone(this.records.get(runId) ?? []);
160
471
  }
472
+ async barrier(_runId, requested) {
473
+ assertSupportedDurability(this, requested);
474
+ return durabilityAcknowledgement(this, requested);
475
+ }
161
476
  }
162
477
  /** 把同步事件串行化为 RunStore 的有序异步写入。 */
163
478
  export class RunStateJournal {
164
479
  runId;
165
480
  store;
166
- sequence;
167
- pending = Promise.resolve();
481
+ ledger;
168
482
  aborted = false;
169
483
  rejectedAfterAbortCount = 0;
170
484
  knownTurnIds;
485
+ durabilityCounters = {
486
+ ordinary: { succeeded: 0, failed: 0 },
487
+ critical: { succeeded: 0, failed: 0 },
488
+ };
171
489
  constructor(runId, store, initialSequence = 0) {
172
490
  this.runId = runId;
173
491
  this.store = store;
174
- this.sequence = initialSequence;
492
+ this.ledger = new FactLedger(runId, store, initialSequence);
175
493
  }
176
494
  /**
177
495
  * 取消收敛:设置事件准入分界点(规格 03 §3)。
@@ -204,8 +522,7 @@ export class RunStateJournal {
204
522
  return true;
205
523
  }
206
524
  async start(payload) {
207
- this.enqueue("start", payload);
208
- await this.flush();
525
+ await this.appendFact("start", payload);
209
526
  }
210
527
  event(payload) {
211
528
  this.enqueue("event", payload);
@@ -228,8 +545,37 @@ export class RunStateJournal {
228
545
  finish(payload) {
229
546
  this.enqueue("finish", payload);
230
547
  }
231
- async flush() {
232
- await this.pending;
548
+ async flush(durability = "ordinary") {
549
+ try {
550
+ const acknowledgement = await flushFactLedgerWith(this.ledger, async () => {
551
+ assertSupportedDurability(this.store, durability);
552
+ return this.store.barrier
553
+ ? this.store.barrier(this.runId, durability)
554
+ : legacyDurabilityAcknowledgement(this.store, durability);
555
+ });
556
+ validateDurabilityAcknowledgement(this.store, durability, acknowledgement);
557
+ this.durabilityCounters[durability].succeeded += 1;
558
+ return acknowledgement;
559
+ }
560
+ catch (error) {
561
+ this.durabilityCounters[durability].failed += 1;
562
+ throw error;
563
+ }
564
+ }
565
+ durabilityMetrics() {
566
+ return structuredClone(this.durabilityCounters);
567
+ }
568
+ appendFact(kind, payload, options = {}) {
569
+ return this.ledger.append(kind, payload, options);
570
+ }
571
+ factMetrics() {
572
+ return this.ledger.metrics();
573
+ }
574
+ factStatus() {
575
+ return this.ledger.status();
576
+ }
577
+ pendingFactCount() {
578
+ return this.ledger.metrics().pending;
233
579
  }
234
580
  enqueue(kind, payload) {
235
581
  // 事件准入(规格 03 §3):分界点后的终态类事件拒绝写入,静默不抛错
@@ -237,39 +583,45 @@ export class RunStateJournal {
237
583
  this.rejectedAfterAbortCount += 1;
238
584
  return;
239
585
  }
240
- const record = {
241
- version: 1,
242
- runId: this.runId,
243
- sequence: ++this.sequence,
244
- timestamp: new Date().toISOString(),
245
- kind,
246
- payload,
247
- };
248
- incrementPendingFlush(this);
249
- this.pending = this.pending
250
- .then(() => this.store.append(record))
251
- .finally(() => decrementPendingFlush(this));
586
+ void this.appendFact(kind, payload);
252
587
  }
253
588
  }
254
- /**
255
- * 每个 journal 的未落盘 append 计数(静止判定用:append 队列空且已落盘)。
256
- * 模块级 WeakMap 而非类字段:避免进入 api-extractor 的 untrimmed d.ts(冻结基线逐字哈希,
257
- * #39 教训:类私有成员也会出现在 d.ts 中)。
258
- */
259
- const journalPendingWrites = new WeakMap();
260
- function incrementPendingFlush(journal) {
261
- journalPendingWrites.set(journal, (journalPendingWrites.get(journal) ?? 0) + 1);
589
+ function assertSupportedDurability(store, requested) {
590
+ const supported = store.supportedDurability ?? ["ordinary"];
591
+ if (supported.includes(requested))
592
+ return;
593
+ throw new CoreMindError("durability_unsupported", `RunStore 仅支持 ${supported.join(", ")},不能满足 ${requested}`);
262
594
  }
263
- function decrementPendingFlush(journal) {
264
- const count = (journalPendingWrites.get(journal) ?? 1) - 1;
265
- if (count <= 0)
266
- journalPendingWrites.delete(journal);
267
- else
268
- journalPendingWrites.set(journal, count);
595
+ function durabilityAcknowledgement(store, requested) {
596
+ return {
597
+ requested,
598
+ achieved: requested,
599
+ boundary: store.durabilityBoundary ?? "process_memory",
600
+ };
601
+ }
602
+ function legacyDurabilityAcknowledgement(store, requested) {
603
+ assertSupportedDurability(store, requested);
604
+ if (requested === "critical") {
605
+ throw new CoreMindError("durability_unsupported", "旧 RunStore 未实现 critical barrier acknowledgement");
606
+ }
607
+ return durabilityAcknowledgement(store, requested);
608
+ }
609
+ function validateDurabilityAcknowledgement(store, requested, acknowledgement) {
610
+ const supported = store.supportedDurability ?? ["ordinary"];
611
+ const boundary = store.durabilityBoundary ?? "process_memory";
612
+ const achievedSatisfiesRequest = acknowledgement.achieved === "critical" || requested === "ordinary";
613
+ if (acknowledgement.requested === requested &&
614
+ achievedSatisfiesRequest &&
615
+ supported.includes(acknowledgement.achieved) &&
616
+ acknowledgement.boundary === boundary &&
617
+ !(requested === "critical" && boundary === "process_memory")) {
618
+ return;
619
+ }
620
+ throw new CoreMindError("durability_barrier_failed", `RunStore 返回了与 ${requested}/${boundary} 不一致的 durability acknowledgement`);
269
621
  }
270
622
  /** journal 是否仍有未落盘的写入(规格 03 §5:静止条件之一) */
271
623
  export function hasPendingJournalFlush(journal) {
272
- return (journalPendingWrites.get(journal) ?? 0) > 0;
624
+ return journal.pendingFactCount() > 0;
273
625
  }
274
626
  /**
275
627
  * 准入判定:分界点后到达的终态类事件(规格 03 §3)。
@@ -295,15 +647,72 @@ export function isRejectedAfterAbort(payload, knownTurnIds) {
295
647
  }
296
648
  return false;
297
649
  }
298
- const REPLAY_SAFE_TOOLS = new Set(["read", "ls", "find", "grep", "web-fetch", "web-search"]);
299
650
  /**
300
651
  * resumable 安全门单点实现(缺口 G-1):
301
652
  * 找出第一个副作用状态无法证明为 not_started 的非 replay-safe 工具调用。
302
653
  * 快照 resumable 标志与恢复计划共用此判定,避免双实现漂移。
303
654
  */
304
655
  export function findUnsafeToolCall(trace) {
656
+ const replayCandidateKeys = new Set(collectToolReplayCandidates(trace).map((candidate) => toolCapabilityCallKey(candidate.agent, candidate.stepId, candidate.previousCallId)));
657
+ const completedSteps = new Set(trace
658
+ .map((entry) => entry.event)
659
+ .filter((event) => event.type === "step_output")
660
+ .map((event) => event.stepId));
661
+ const lifecycleFacts = trace
662
+ .map((entry) => entry.event)
663
+ .filter((event) => event.type === "tool_lifecycle");
664
+ const lifecycleStates = projectToolCallLifecycles(lifecycleFacts);
665
+ const receiptByIdempotencyKey = new Map();
666
+ const receiptByLifecycleCall = new Map();
667
+ for (const entry of trace) {
668
+ const event = entry.event;
669
+ if (event.type === "effect_receipt") {
670
+ receiptByIdempotencyKey.set(event.idempotencyKey, event);
671
+ }
672
+ }
673
+ for (const entry of trace) {
674
+ const event = entry.event;
675
+ if (event.type !== "tool_call" || !event.callId || !event.idempotencyKey)
676
+ continue;
677
+ const receipt = receiptByIdempotencyKey.get(event.idempotencyKey);
678
+ if (receipt) {
679
+ receiptByLifecycleCall.set(toolCapabilityCallKey(event.agent, event.stepId, event.callId), receipt);
680
+ }
681
+ }
682
+ const lifecycleCallKeys = new Set(lifecycleStates.map((state) => toolCapabilityCallKey(state.agent, state.stepId, state.callId)));
683
+ if (lifecycleFacts.length > 0) {
684
+ for (const state of lifecycleStates) {
685
+ if (state.stepId && completedSteps.has(state.stepId))
686
+ continue;
687
+ const receipt = receiptByLifecycleCall.get(toolCapabilityCallKey(state.agent, state.stepId, state.callId));
688
+ const effectState = state.result.effectState === "not_started" && receipt?.status === "started"
689
+ ? "unknown"
690
+ : state.result.effectState === "not_started" &&
691
+ (receipt?.status === "committed" || receipt?.status === "unknown")
692
+ ? receipt.status
693
+ : state.result.effectState;
694
+ if (effectState === "not_started")
695
+ continue;
696
+ if (state.result.recoveryDisposition === "replay_safe")
697
+ continue;
698
+ if (replayCandidateKeys.has(toolCapabilityCallKey(state.agent, state.stepId, state.callId))) {
699
+ continue;
700
+ }
701
+ return {
702
+ tool: state.tool,
703
+ ...(state.stepId ? { stepId: state.stepId } : {}),
704
+ ...(receipt?.idempotencyKey ? { idempotencyKey: receipt.idempotencyKey } : {}),
705
+ receiptStatus: effectState,
706
+ };
707
+ }
708
+ }
305
709
  const receipts = new Map();
306
- const completedSteps = new Set();
710
+ const capabilities = new Map(projectToolCapabilities(trace.map((entry) => entry.event))
711
+ .filter((projection) => projection.callId !== undefined)
712
+ .map((projection) => [
713
+ toolCapabilityCallKey(projection.agent, projection.stepId, projection.callId),
714
+ projection,
715
+ ]));
307
716
  for (const entry of trace) {
308
717
  const event = entry.event;
309
718
  if (event.type === "effect_receipt")
@@ -315,13 +724,24 @@ export function findUnsafeToolCall(trace) {
315
724
  const event = entry.event;
316
725
  if (event.type !== "tool_call")
317
726
  continue;
318
- if (REPLAY_SAFE_TOOLS.has(event.tool))
727
+ if (event.callId &&
728
+ lifecycleCallKeys.has(toolCapabilityCallKey(event.agent, event.stepId, event.callId))) {
319
729
  continue;
730
+ }
320
731
  if (event.stepId && completedSteps.has(event.stepId))
321
732
  continue;
322
733
  const receipt = event.idempotencyKey ? receipts.get(event.idempotencyKey) : undefined;
323
734
  if (receipt?.status === "not_started")
324
735
  continue;
736
+ const capability = event.callId
737
+ ? capabilities.get(toolCapabilityCallKey(event.agent, event.stepId, event.callId))
738
+ : undefined;
739
+ if (capability?.recoveryDisposition === "replay_safe")
740
+ continue;
741
+ if (event.callId &&
742
+ replayCandidateKeys.has(toolCapabilityCallKey(event.agent, event.stepId, event.callId))) {
743
+ continue;
744
+ }
325
745
  return {
326
746
  tool: event.tool,
327
747
  ...(event.stepId ? { stepId: event.stepId } : {}),
@@ -331,6 +751,62 @@ export function findUnsafeToolCall(trace) {
331
751
  }
332
752
  return undefined;
333
753
  }
754
+ export function collectToolReplayCandidates(trace) {
755
+ const events = trace.map((entry) => entry.event);
756
+ const completedSteps = new Set(events.filter((event) => event.type === "step_output").map((event) => event.stepId));
757
+ const bindings = events.some((event) => event.type === "effect_receipt" && event.binding !== undefined)
758
+ ? validateEffectReceiptBindingsAgainstFacts(trace[0]?.runId ?? "", events)
759
+ : [];
760
+ const bindingByReceipt = new Map(bindings.map((binding) => [binding.idempotencyKey, binding]));
761
+ const capabilityByCall = new Map(projectToolCapabilities(events)
762
+ .filter((projection) => projection.callId !== undefined)
763
+ .map((projection) => [
764
+ toolCapabilityCallKey(projection.agent, projection.stepId, projection.callId),
765
+ projection,
766
+ ]));
767
+ const priorAttemptByCall = new Map(events.flatMap((event) => event.type === "tool_attempt"
768
+ ? [[toolCapabilityCallKey(event.agent, event.stepId, event.callId), event.attempt]]
769
+ : []));
770
+ const candidates = [];
771
+ for (const event of events) {
772
+ if (event.type !== "tool_call" ||
773
+ !event.callId ||
774
+ !event.idempotencyKey ||
775
+ (event.stepId && completedSteps.has(event.stepId))) {
776
+ continue;
777
+ }
778
+ const callKey = toolCapabilityCallKey(event.agent, event.stepId, event.callId);
779
+ const capability = capabilityByCall.get(callKey);
780
+ const receipt = bindingByReceipt.get(event.idempotencyKey);
781
+ if (capability?.capability.replay !== "idempotent" ||
782
+ capability.recoveryDisposition !== "requires_proof" ||
783
+ receipt?.provenance !== "bound" ||
784
+ !receipt.binding ||
785
+ (receipt.status !== "started" && receipt.status !== "unknown")) {
786
+ continue;
787
+ }
788
+ candidates.push({
789
+ previousReceiptId: event.idempotencyKey,
790
+ previousCallId: event.callId,
791
+ attempt: (priorAttemptByCall.get(callKey) ?? 1) + 1,
792
+ agent: event.agent,
793
+ tool: event.tool,
794
+ ...(event.stepId ? { stepId: event.stepId } : {}),
795
+ argumentsFingerprint: receipt.binding.argumentsFingerprint,
796
+ capabilityFingerprint: receipt.binding.capabilityFingerprint,
797
+ });
798
+ }
799
+ return candidates;
800
+ }
801
+ /** 由 Runtime 单点判断持久化运行是否满足自动恢复的安全前提。 */
802
+ export function isRunStateResumable(records) {
803
+ if (records.length === 0 || records.some((record) => record.kind === "finish"))
804
+ return false;
805
+ const trace = records
806
+ .filter((record) => record.kind === "event")
807
+ .map((record) => tracePayload(record.payload, record.runId));
808
+ return inputReceiptsAreResumable(trace) && findUnsafeToolCall(trace) === undefined;
809
+ }
334
810
  /** 从中断的 append-only RunState 构造安全恢复计划。 */
335
811
  export function prepareRunResume(records, configFingerprint, requestedPrompt) {
336
812
  if (records.length === 0)
@@ -405,6 +881,9 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
405
881
  }
406
882
  }
407
883
  const operationSnapshot = operationSnapshotFromRecords(ordered);
884
+ if (!inputReceiptsAreResumable(previousTrace)) {
885
+ throw new CoreMindError("run_already_finished", "输入已到终态,不能自动恢复");
886
+ }
408
887
  const unsafe = findUnsafeToolCall(previousTrace);
409
888
  if (unsafe) {
410
889
  if (unsafe.receiptStatus === "committed") {
@@ -419,12 +898,22 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
419
898
  nextTraceSequence,
420
899
  completedSteps,
421
900
  effectReceipts,
901
+ toolReplayCandidates: collectToolReplayCandidates(previousTrace),
422
902
  previousTrace,
423
903
  operationRecords,
424
904
  ...(loopSnapshot ? { loopSnapshot } : {}),
425
905
  ...(operationSnapshot ? { operationSnapshot } : {}),
426
906
  };
427
907
  }
908
+ function inputReceiptsAreResumable(trace) {
909
+ try {
910
+ const statuses = foldInputReceipts(trace.map((entry) => entry.event));
911
+ return [...statuses.values()].every((status) => status === "pending" || status === "claimed");
912
+ }
913
+ catch (error) {
914
+ throw new CoreMindError("run_state_corrupt", `输入收据无法安全折叠:${error instanceof Error ? error.message : String(error)}`);
915
+ }
916
+ }
428
917
  /** 从 RunState 中校验并提取最新 operation 快照,供 CLI/SDK/Worker 共用。 */
429
918
  export function operationSnapshotFromRecords(records) {
430
919
  const operationRecords = records
@@ -436,7 +925,10 @@ export function operationSnapshotFromRecords(records) {
436
925
  }
437
926
  /** 配置指纹只落 hash,不把配置或凭据复制进 RunState。 */
438
927
  export function fingerprintRunConfig(config) {
439
- return createHash("sha256").update(stableJson(config)).digest("hex");
928
+ const resumeConfig = config !== null && typeof config === "object" && !Array.isArray(config)
929
+ ? Object.fromEntries(Object.entries(config).filter(([key]) => key !== "telemetry"))
930
+ : config;
931
+ return createHash("sha256").update(stableJson(resumeConfig)).digest("hex");
440
932
  }
441
933
  function tracePayload(payload, expectedRunId) {
442
934
  if (payload === null || typeof payload !== "object") {
@@ -476,17 +968,26 @@ function tracePayload(payload, expectedRunId) {
476
968
  (event.stepId !== undefined && typeof event.stepId !== "string"))) {
477
969
  throw new CoreMindError("run_state_corrupt", "RunState 包含非法 effect_receipt");
478
970
  }
479
- return trace;
480
- }
481
- function stableJson(value) {
482
- if (value === null || typeof value !== "object")
483
- return JSON.stringify(value);
484
- if (Array.isArray(value))
485
- return `[${value.map(stableJson).join(",")}]`;
486
- const entries = Object.entries(value)
487
- .filter(([, item]) => item !== undefined)
488
- .sort(([left], [right]) => left.localeCompare(right));
489
- return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(",")}}`;
971
+ if (event.type === "capability_resolved" &&
972
+ (typeof event.agent !== "string" ||
973
+ typeof event.tool !== "string" ||
974
+ typeof event.callId !== "string" ||
975
+ (event.stepId !== undefined && typeof event.stepId !== "string") ||
976
+ !isResolvedToolCapability(event.capability, event.tool) ||
977
+ !RECOVERY_DISPOSITIONS.includes(event.recoveryDisposition) ||
978
+ recoveryDispositionFor(event.capability) !== event.recoveryDisposition)) {
979
+ throw new CoreMindError("run_state_corrupt", "RunState 包含非法 capability_resolved");
980
+ }
981
+ if (event.type === "tool_lifecycle") {
982
+ try {
983
+ validateToolCallLifecycleFact(event);
984
+ }
985
+ catch {
986
+ throw new CoreMindError("run_state_corrupt", "RunState 包含非法 tool_lifecycle");
987
+ }
988
+ }
989
+ const { protocolToolResult: _internal, ...publicTrace } = trace;
990
+ return publicTrace;
490
991
  }
491
992
  const LOOP_PHASES = new Set([
492
993
  "idle",
@@ -541,9 +1042,31 @@ function validateRecord(value, expectedRunId) {
541
1042
  record.runId !== expectedRunId ||
542
1043
  !Number.isInteger(record.sequence) ||
543
1044
  typeof record.timestamp !== "string" ||
544
- !["start", "resume", "event", "checkpoint", "loop", "operation", "pause", "finish"].includes(record.kind ?? "")) {
1045
+ (record.eventId !== undefined &&
1046
+ (typeof record.eventId !== "string" || record.eventId.trim().length === 0)) ||
1047
+ ![
1048
+ "start",
1049
+ "resume",
1050
+ "telemetry_configuration",
1051
+ "telemetry_consent",
1052
+ "control",
1053
+ "delegation",
1054
+ "event",
1055
+ "checkpoint",
1056
+ "checkpoint_restore",
1057
+ "loop",
1058
+ "operation",
1059
+ "pause",
1060
+ "finish",
1061
+ ].includes(record.kind ?? "")) {
545
1062
  throw new CoreMindError("run_state_corrupt", `RunState ${expectedRunId} 包含非法记录`);
546
1063
  }
1064
+ if (record.kind === "event" &&
1065
+ record.payload !== null &&
1066
+ typeof record.payload === "object" &&
1067
+ "event" in record.payload) {
1068
+ tracePayload(record.payload, expectedRunId);
1069
+ }
547
1070
  return record;
548
1071
  }
549
1072
  /** 从 RunState 事件记录中找第一个 input_receipt 的指纹(恢复时输入收据联动校验用) */