coremind-runtime 0.3.1 → 0.7.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 (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 +40 -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 +11 -0
  97. package/dist/internal.d.ts.map +1 -0
  98. package/dist/internal.js +11 -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 +972 -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 +65 -4
  153. package/dist/run-state.d.ts.map +1 -1
  154. package/dist/run-state.js +502 -76
  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 +83 -2
  164. package/dist/runtime.d.ts.map +1 -1
  165. package/dist/runtime.js +2048 -348
  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,21 @@
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, 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";
7
14
  export class FileRunStore {
8
15
  directory;
9
16
  options;
17
+ supportedDurability = ["ordinary", "critical"];
18
+ durabilityBoundary = "process_crash";
10
19
  constructor(directory, options = {}) {
11
20
  this.directory = directory;
12
21
  this.options = options;
@@ -19,23 +28,7 @@ export class FileRunStore {
19
28
  }
20
29
  async append(record) {
21
30
  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
- });
31
+ await this.writeRecord(record, "ordinary");
39
32
  }
40
33
  catch (error) {
41
34
  if (error instanceof CoreMindError)
@@ -43,6 +36,42 @@ export class FileRunStore {
43
36
  throw new CoreMindError("run_state_failed", `RunState 写入失败:${error instanceof Error ? error.message : String(error)}`);
44
37
  }
45
38
  }
39
+ async commit(record, durability) {
40
+ assertSupportedDurability(this, durability);
41
+ try {
42
+ await this.writeRecord(record, durability);
43
+ return durabilityAcknowledgement(this, durability);
44
+ }
45
+ catch (error) {
46
+ if (error instanceof CoreMindError)
47
+ throw error;
48
+ const code = durability === "critical" ? "durability_barrier_failed" : "run_state_failed";
49
+ throw new CoreMindError(code, `RunState ${record.runId} 的 ${durability} commit 失败:${error instanceof Error ? error.message : String(error)}`);
50
+ }
51
+ }
52
+ async barrier(runId, requested) {
53
+ assertSupportedDurability(this, requested);
54
+ if (requested === "ordinary")
55
+ return durabilityAcknowledgement(this, requested);
56
+ const destination = this.pathFor(runId);
57
+ try {
58
+ return await this.withWriterLock(destination, async () => {
59
+ let handle;
60
+ try {
61
+ handle = await open(destination, "r+");
62
+ await this.options.beforeBarrier?.({ destination, runId, requested });
63
+ await handle.sync();
64
+ return durabilityAcknowledgement(this, requested);
65
+ }
66
+ finally {
67
+ await handle?.close().catch(() => undefined);
68
+ }
69
+ });
70
+ }
71
+ catch (error) {
72
+ throw new CoreMindError("durability_barrier_failed", `RunState ${runId} 的 critical barrier 失败:${error instanceof Error ? error.message : String(error)}`);
73
+ }
74
+ }
46
75
  async read(runId) {
47
76
  try {
48
77
  const destination = this.pathFor(runId);
@@ -100,30 +129,97 @@ export class FileRunStore {
100
129
  }
101
130
  return { records };
102
131
  }
103
- async publishAtomically(destination, text, record) {
132
+ async publishAtomically(destination, text, record, durability = "ordinary") {
104
133
  const temporary = `${destination}.${process.pid}.${randomUUID()}.tmp`;
105
134
  try {
106
135
  await writeFile(temporary, text, { encoding: "utf8", flag: "wx" });
107
136
  await this.options.beforeCommit?.({ destination, temporary, record });
108
- await rename(temporary, destination);
137
+ if (durability === "critical") {
138
+ let handle;
139
+ try {
140
+ handle = await open(temporary, "r+");
141
+ await this.options.beforeBarrier?.({
142
+ destination,
143
+ runId: record.runId,
144
+ requested: durability,
145
+ record,
146
+ });
147
+ await handle.sync();
148
+ }
149
+ finally {
150
+ await handle?.close().catch(() => undefined);
151
+ }
152
+ }
153
+ await renameAtomically(temporary, destination);
109
154
  }
110
155
  finally {
111
156
  await rm(temporary, { force: true }).catch(() => undefined);
112
157
  }
113
158
  }
159
+ async writeRecord(record, durability) {
160
+ const destination = this.pathFor(record.runId);
161
+ validateRecord(record, record.runId);
162
+ await this.withWriterLock(destination, async () => {
163
+ const parsed = await this.readUnlocked(record.runId, destination);
164
+ const duplicate = parsed.records.find((item) => item.sequence === record.sequence);
165
+ if (duplicate) {
166
+ if (stableJson(duplicate) === stableJson(record)) {
167
+ if (durability === "critical") {
168
+ let handle;
169
+ try {
170
+ handle = await open(destination, "r+");
171
+ await this.options.beforeBarrier?.({
172
+ destination,
173
+ runId: record.runId,
174
+ requested: durability,
175
+ record,
176
+ });
177
+ await handle.sync();
178
+ }
179
+ finally {
180
+ await handle?.close().catch(() => undefined);
181
+ }
182
+ }
183
+ return;
184
+ }
185
+ throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 的 sequence ${record.sequence} 已由另一条记录占用`);
186
+ }
187
+ const expectedSequence = (parsed.records.at(-1)?.sequence ?? 0) + 1;
188
+ if (record.sequence !== expectedSequence) {
189
+ throw new CoreMindError("run_state_conflict", `RunState ${record.runId} 期望 sequence ${expectedSequence},实际为 ${record.sequence}`);
190
+ }
191
+ const text = `${parsed.records.map((item) => JSON.stringify(item)).join("\n")}${parsed.records.length > 0 ? "\n" : ""}${JSON.stringify(record)}\n`;
192
+ await this.publishAtomically(destination, text, record, durability);
193
+ });
194
+ }
114
195
  async withWriterLock(destination, operation) {
115
196
  await mkdir(this.directory, { recursive: true });
116
197
  const lockPath = `${destination}.lock`;
117
- const deadline = Date.now() + (this.options.lockTimeoutMs ?? 2_000);
118
- let handle;
119
- while (!handle) {
198
+ const deadline = Date.now() + (this.options.lockTimeoutMs ?? 10_000);
199
+ const owner = {
200
+ pid: process.pid,
201
+ createdAt: new Date().toISOString(),
202
+ nonce: randomUUID(),
203
+ };
204
+ let acquired = false;
205
+ let transientPermissionError;
206
+ while (!acquired) {
120
207
  try {
121
- handle = await open(lockPath, "wx");
208
+ await publishWriterLock(lockPath, owner);
209
+ acquired = true;
122
210
  }
123
211
  catch (error) {
124
- if (error.code !== "EEXIST")
212
+ const contention = await classifyWriterLockContention(error, lockPath);
213
+ if (contention === "not_contention")
125
214
  throw error;
215
+ if (contention === "transient_missing")
216
+ transientPermissionError ??= error;
217
+ if (await this.reclaimStaleWriterLock(lockPath))
218
+ continue;
126
219
  if (Date.now() >= deadline) {
220
+ if (contention === "transient_missing" && transientPermissionError) {
221
+ throw transientPermissionError;
222
+ }
127
223
  throw new CoreMindError("run_state_locked", `RunState ${path.basename(destination)} 正由另一 writer 使用`);
128
224
  }
129
225
  await new Promise((resolve) => setTimeout(resolve, 5));
@@ -133,14 +229,128 @@ export class FileRunStore {
133
229
  return await operation();
134
230
  }
135
231
  finally {
136
- await handle.close();
137
232
  await rm(lockPath, { force: true });
138
233
  }
139
234
  }
235
+ async reclaimStaleWriterLock(lockPath) {
236
+ const inspected = await inspectWriterLock(lockPath);
237
+ if (inspected.state !== "valid" || isProcessAlive(inspected.owner.pid))
238
+ return false;
239
+ const claimPath = `${lockPath}.reclaim-${inspected.owner.nonce}`;
240
+ const tombstonePath = `${claimPath}.tombstone-${randomUUID()}`;
241
+ let claimHandle;
242
+ try {
243
+ claimHandle = await open(claimPath, "wx");
244
+ }
245
+ catch (error) {
246
+ if (error.code === "EEXIST")
247
+ return false;
248
+ throw error;
249
+ }
250
+ try {
251
+ await claimHandle.writeFile(JSON.stringify({ pid: process.pid, ownerNonce: inspected.owner.nonce }), "utf8");
252
+ const current = await inspectWriterLock(lockPath);
253
+ if (current.state !== "valid" ||
254
+ current.owner.nonce !== inspected.owner.nonce ||
255
+ isProcessAlive(current.owner.pid)) {
256
+ return false;
257
+ }
258
+ // 固定 claim 文件由 wx 原子选出唯一回收者;只移动已复核的旧锁,随后只删 tombstone,
259
+ // 永远不对可能已由新 writer 重建的 lockPath 执行删除。
260
+ await rename(lockPath, tombstonePath);
261
+ return true;
262
+ }
263
+ finally {
264
+ await claimHandle.close().catch(() => undefined);
265
+ await rm(tombstonePath, { force: true }).catch(() => undefined);
266
+ await rm(claimPath, { force: true }).catch(() => undefined);
267
+ }
268
+ }
269
+ }
270
+ async function publishWriterLock(lockPath, owner) {
271
+ const candidatePath = `${lockPath}.candidate-${owner.nonce}`;
272
+ try {
273
+ // 先完整并持久化候选文件,再通过 hard link 原子发布,避免崩溃留下无 owner 的空锁。
274
+ await writeFile(candidatePath, JSON.stringify(owner), {
275
+ encoding: "utf8",
276
+ flag: "wx",
277
+ flush: true,
278
+ });
279
+ await link(candidatePath, lockPath);
280
+ }
281
+ finally {
282
+ await rm(candidatePath, { force: true }).catch(() => undefined);
283
+ }
284
+ }
285
+ const ATOMIC_RENAME_RETRY_DELAYS_MS = [5, 10, 20, 40, 80, 160, 320, 640, 1_280];
286
+ /** Windows 扫描器可能短暂占用新文件;只重试可恢复的 rename 错误。 */
287
+ async function renameAtomically(temporary, destination) {
288
+ for (let attempt = 0;; attempt += 1) {
289
+ try {
290
+ await rename(temporary, destination);
291
+ return;
292
+ }
293
+ catch (error) {
294
+ const delay = ATOMIC_RENAME_RETRY_DELAYS_MS[attempt];
295
+ if (delay === undefined || !isTransientRenameError(error))
296
+ throw error;
297
+ await new Promise((resolve) => setTimeout(resolve, delay));
298
+ }
299
+ }
300
+ }
301
+ function isTransientRenameError(error) {
302
+ const code = error?.code;
303
+ return code === "EPERM" || code === "EACCES" || code === "EBUSY";
304
+ }
305
+ async function classifyWriterLockContention(error, lockPath) {
306
+ const code = error.code;
307
+ if (code === "EEXIST") {
308
+ return (await inspectWriterLock(lockPath)).state === "valid"
309
+ ? "valid_contention"
310
+ : "path_contention";
311
+ }
312
+ if (process.platform !== "win32" || (code !== "EPERM" && code !== "EACCES")) {
313
+ return "not_contention";
314
+ }
315
+ const inspected = await inspectWriterLock(lockPath);
316
+ if (inspected.state === "valid")
317
+ return "valid_contention";
318
+ // 锁刚好消失时允许短暂重试,但若截止前从未观察到有效 owner,调用方保留原权限异常。
319
+ return inspected.state === "missing" ? "transient_missing" : "not_contention";
320
+ }
321
+ async function inspectWriterLock(lockPath) {
322
+ try {
323
+ const owner = JSON.parse(await readFile(lockPath, "utf8"));
324
+ if (typeof owner.pid === "number" &&
325
+ Number.isInteger(owner.pid) &&
326
+ owner.pid > 0 &&
327
+ typeof owner.nonce === "string" &&
328
+ owner.nonce.length > 0) {
329
+ return { state: "valid", owner: { pid: owner.pid, nonce: owner.nonce } };
330
+ }
331
+ return { state: "invalid" };
332
+ }
333
+ catch (error) {
334
+ return error.code === "ENOENT"
335
+ ? { state: "missing" }
336
+ : { state: "invalid" };
337
+ }
338
+ }
339
+ function isProcessAlive(pid) {
340
+ try {
341
+ process.kill(pid, 0);
342
+ return true;
343
+ }
344
+ catch (error) {
345
+ return error.code !== "ESRCH";
346
+ }
140
347
  }
141
348
  export class MemoryRunStore {
349
+ supportedDurability = ["ordinary"];
350
+ durabilityBoundary = "process_memory";
142
351
  records = new Map();
143
352
  async append(record) {
353
+ validateRecord(record, record.runId);
144
354
  const items = this.records.get(record.runId) ?? [];
145
355
  const duplicate = items.find((item) => item.sequence === record.sequence);
146
356
  if (duplicate) {
@@ -155,23 +365,35 @@ export class MemoryRunStore {
155
365
  items.push(structuredClone(record));
156
366
  this.records.set(record.runId, items);
157
367
  }
368
+ async commit(record, durability) {
369
+ assertSupportedDurability(this, durability);
370
+ await this.append(record);
371
+ return durabilityAcknowledgement(this, durability);
372
+ }
158
373
  async read(runId) {
159
374
  return structuredClone(this.records.get(runId) ?? []);
160
375
  }
376
+ async barrier(_runId, requested) {
377
+ assertSupportedDurability(this, requested);
378
+ return durabilityAcknowledgement(this, requested);
379
+ }
161
380
  }
162
381
  /** 把同步事件串行化为 RunStore 的有序异步写入。 */
163
382
  export class RunStateJournal {
164
383
  runId;
165
384
  store;
166
- sequence;
167
- pending = Promise.resolve();
385
+ ledger;
168
386
  aborted = false;
169
387
  rejectedAfterAbortCount = 0;
170
388
  knownTurnIds;
389
+ durabilityCounters = {
390
+ ordinary: { succeeded: 0, failed: 0 },
391
+ critical: { succeeded: 0, failed: 0 },
392
+ };
171
393
  constructor(runId, store, initialSequence = 0) {
172
394
  this.runId = runId;
173
395
  this.store = store;
174
- this.sequence = initialSequence;
396
+ this.ledger = new FactLedger(runId, store, initialSequence);
175
397
  }
176
398
  /**
177
399
  * 取消收敛:设置事件准入分界点(规格 03 §3)。
@@ -204,8 +426,7 @@ export class RunStateJournal {
204
426
  return true;
205
427
  }
206
428
  async start(payload) {
207
- this.enqueue("start", payload);
208
- await this.flush();
429
+ await this.appendFact("start", payload);
209
430
  }
210
431
  event(payload) {
211
432
  this.enqueue("event", payload);
@@ -228,8 +449,37 @@ export class RunStateJournal {
228
449
  finish(payload) {
229
450
  this.enqueue("finish", payload);
230
451
  }
231
- async flush() {
232
- await this.pending;
452
+ async flush(durability = "ordinary") {
453
+ try {
454
+ const acknowledgement = await flushFactLedgerWith(this.ledger, async () => {
455
+ assertSupportedDurability(this.store, durability);
456
+ return this.store.barrier
457
+ ? this.store.barrier(this.runId, durability)
458
+ : legacyDurabilityAcknowledgement(this.store, durability);
459
+ });
460
+ validateDurabilityAcknowledgement(this.store, durability, acknowledgement);
461
+ this.durabilityCounters[durability].succeeded += 1;
462
+ return acknowledgement;
463
+ }
464
+ catch (error) {
465
+ this.durabilityCounters[durability].failed += 1;
466
+ throw error;
467
+ }
468
+ }
469
+ durabilityMetrics() {
470
+ return structuredClone(this.durabilityCounters);
471
+ }
472
+ appendFact(kind, payload, options = {}) {
473
+ return this.ledger.append(kind, payload, options);
474
+ }
475
+ factMetrics() {
476
+ return this.ledger.metrics();
477
+ }
478
+ factStatus() {
479
+ return this.ledger.status();
480
+ }
481
+ pendingFactCount() {
482
+ return this.ledger.metrics().pending;
233
483
  }
234
484
  enqueue(kind, payload) {
235
485
  // 事件准入(规格 03 §3):分界点后的终态类事件拒绝写入,静默不抛错
@@ -237,39 +487,45 @@ export class RunStateJournal {
237
487
  this.rejectedAfterAbortCount += 1;
238
488
  return;
239
489
  }
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));
490
+ void this.appendFact(kind, payload);
252
491
  }
253
492
  }
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);
493
+ function assertSupportedDurability(store, requested) {
494
+ const supported = store.supportedDurability ?? ["ordinary"];
495
+ if (supported.includes(requested))
496
+ return;
497
+ throw new CoreMindError("durability_unsupported", `RunStore 仅支持 ${supported.join(", ")},不能满足 ${requested}`);
498
+ }
499
+ function durabilityAcknowledgement(store, requested) {
500
+ return {
501
+ requested,
502
+ achieved: requested,
503
+ boundary: store.durabilityBoundary ?? "process_memory",
504
+ };
505
+ }
506
+ function legacyDurabilityAcknowledgement(store, requested) {
507
+ assertSupportedDurability(store, requested);
508
+ if (requested === "critical") {
509
+ throw new CoreMindError("durability_unsupported", "旧 RunStore 未实现 critical barrier acknowledgement");
510
+ }
511
+ return durabilityAcknowledgement(store, requested);
262
512
  }
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);
513
+ function validateDurabilityAcknowledgement(store, requested, acknowledgement) {
514
+ const supported = store.supportedDurability ?? ["ordinary"];
515
+ const boundary = store.durabilityBoundary ?? "process_memory";
516
+ const achievedSatisfiesRequest = acknowledgement.achieved === "critical" || requested === "ordinary";
517
+ if (acknowledgement.requested === requested &&
518
+ achievedSatisfiesRequest &&
519
+ supported.includes(acknowledgement.achieved) &&
520
+ acknowledgement.boundary === boundary &&
521
+ !(requested === "critical" && boundary === "process_memory")) {
522
+ return;
523
+ }
524
+ throw new CoreMindError("durability_barrier_failed", `RunStore 返回了与 ${requested}/${boundary} 不一致的 durability acknowledgement`);
269
525
  }
270
526
  /** journal 是否仍有未落盘的写入(规格 03 §5:静止条件之一) */
271
527
  export function hasPendingJournalFlush(journal) {
272
- return (journalPendingWrites.get(journal) ?? 0) > 0;
528
+ return journal.pendingFactCount() > 0;
273
529
  }
274
530
  /**
275
531
  * 准入判定:分界点后到达的终态类事件(规格 03 §3)。
@@ -295,15 +551,72 @@ export function isRejectedAfterAbort(payload, knownTurnIds) {
295
551
  }
296
552
  return false;
297
553
  }
298
- const REPLAY_SAFE_TOOLS = new Set(["read", "ls", "find", "grep", "web-fetch", "web-search"]);
299
554
  /**
300
555
  * resumable 安全门单点实现(缺口 G-1):
301
556
  * 找出第一个副作用状态无法证明为 not_started 的非 replay-safe 工具调用。
302
557
  * 快照 resumable 标志与恢复计划共用此判定,避免双实现漂移。
303
558
  */
304
559
  export function findUnsafeToolCall(trace) {
560
+ const replayCandidateKeys = new Set(collectToolReplayCandidates(trace).map((candidate) => toolCapabilityCallKey(candidate.agent, candidate.stepId, candidate.previousCallId)));
561
+ const completedSteps = new Set(trace
562
+ .map((entry) => entry.event)
563
+ .filter((event) => event.type === "step_output")
564
+ .map((event) => event.stepId));
565
+ const lifecycleFacts = trace
566
+ .map((entry) => entry.event)
567
+ .filter((event) => event.type === "tool_lifecycle");
568
+ const lifecycleStates = projectToolCallLifecycles(lifecycleFacts);
569
+ const receiptByIdempotencyKey = new Map();
570
+ const receiptByLifecycleCall = new Map();
571
+ for (const entry of trace) {
572
+ const event = entry.event;
573
+ if (event.type === "effect_receipt") {
574
+ receiptByIdempotencyKey.set(event.idempotencyKey, event);
575
+ }
576
+ }
577
+ for (const entry of trace) {
578
+ const event = entry.event;
579
+ if (event.type !== "tool_call" || !event.callId || !event.idempotencyKey)
580
+ continue;
581
+ const receipt = receiptByIdempotencyKey.get(event.idempotencyKey);
582
+ if (receipt) {
583
+ receiptByLifecycleCall.set(toolCapabilityCallKey(event.agent, event.stepId, event.callId), receipt);
584
+ }
585
+ }
586
+ const lifecycleCallKeys = new Set(lifecycleStates.map((state) => toolCapabilityCallKey(state.agent, state.stepId, state.callId)));
587
+ if (lifecycleFacts.length > 0) {
588
+ for (const state of lifecycleStates) {
589
+ if (state.stepId && completedSteps.has(state.stepId))
590
+ continue;
591
+ const receipt = receiptByLifecycleCall.get(toolCapabilityCallKey(state.agent, state.stepId, state.callId));
592
+ const effectState = state.result.effectState === "not_started" && receipt?.status === "started"
593
+ ? "unknown"
594
+ : state.result.effectState === "not_started" &&
595
+ (receipt?.status === "committed" || receipt?.status === "unknown")
596
+ ? receipt.status
597
+ : state.result.effectState;
598
+ if (effectState === "not_started")
599
+ continue;
600
+ if (state.result.recoveryDisposition === "replay_safe")
601
+ continue;
602
+ if (replayCandidateKeys.has(toolCapabilityCallKey(state.agent, state.stepId, state.callId))) {
603
+ continue;
604
+ }
605
+ return {
606
+ tool: state.tool,
607
+ ...(state.stepId ? { stepId: state.stepId } : {}),
608
+ ...(receipt?.idempotencyKey ? { idempotencyKey: receipt.idempotencyKey } : {}),
609
+ receiptStatus: effectState,
610
+ };
611
+ }
612
+ }
305
613
  const receipts = new Map();
306
- const completedSteps = new Set();
614
+ const capabilities = new Map(projectToolCapabilities(trace.map((entry) => entry.event))
615
+ .filter((projection) => projection.callId !== undefined)
616
+ .map((projection) => [
617
+ toolCapabilityCallKey(projection.agent, projection.stepId, projection.callId),
618
+ projection,
619
+ ]));
307
620
  for (const entry of trace) {
308
621
  const event = entry.event;
309
622
  if (event.type === "effect_receipt")
@@ -315,13 +628,24 @@ export function findUnsafeToolCall(trace) {
315
628
  const event = entry.event;
316
629
  if (event.type !== "tool_call")
317
630
  continue;
318
- if (REPLAY_SAFE_TOOLS.has(event.tool))
631
+ if (event.callId &&
632
+ lifecycleCallKeys.has(toolCapabilityCallKey(event.agent, event.stepId, event.callId))) {
319
633
  continue;
634
+ }
320
635
  if (event.stepId && completedSteps.has(event.stepId))
321
636
  continue;
322
637
  const receipt = event.idempotencyKey ? receipts.get(event.idempotencyKey) : undefined;
323
638
  if (receipt?.status === "not_started")
324
639
  continue;
640
+ const capability = event.callId
641
+ ? capabilities.get(toolCapabilityCallKey(event.agent, event.stepId, event.callId))
642
+ : undefined;
643
+ if (capability?.recoveryDisposition === "replay_safe")
644
+ continue;
645
+ if (event.callId &&
646
+ replayCandidateKeys.has(toolCapabilityCallKey(event.agent, event.stepId, event.callId))) {
647
+ continue;
648
+ }
325
649
  return {
326
650
  tool: event.tool,
327
651
  ...(event.stepId ? { stepId: event.stepId } : {}),
@@ -331,6 +655,62 @@ export function findUnsafeToolCall(trace) {
331
655
  }
332
656
  return undefined;
333
657
  }
658
+ export function collectToolReplayCandidates(trace) {
659
+ const events = trace.map((entry) => entry.event);
660
+ const completedSteps = new Set(events.filter((event) => event.type === "step_output").map((event) => event.stepId));
661
+ const bindings = events.some((event) => event.type === "effect_receipt" && event.binding !== undefined)
662
+ ? validateEffectReceiptBindingsAgainstFacts(trace[0]?.runId ?? "", events)
663
+ : [];
664
+ const bindingByReceipt = new Map(bindings.map((binding) => [binding.idempotencyKey, binding]));
665
+ const capabilityByCall = new Map(projectToolCapabilities(events)
666
+ .filter((projection) => projection.callId !== undefined)
667
+ .map((projection) => [
668
+ toolCapabilityCallKey(projection.agent, projection.stepId, projection.callId),
669
+ projection,
670
+ ]));
671
+ const priorAttemptByCall = new Map(events.flatMap((event) => event.type === "tool_attempt"
672
+ ? [[toolCapabilityCallKey(event.agent, event.stepId, event.callId), event.attempt]]
673
+ : []));
674
+ const candidates = [];
675
+ for (const event of events) {
676
+ if (event.type !== "tool_call" ||
677
+ !event.callId ||
678
+ !event.idempotencyKey ||
679
+ (event.stepId && completedSteps.has(event.stepId))) {
680
+ continue;
681
+ }
682
+ const callKey = toolCapabilityCallKey(event.agent, event.stepId, event.callId);
683
+ const capability = capabilityByCall.get(callKey);
684
+ const receipt = bindingByReceipt.get(event.idempotencyKey);
685
+ if (capability?.capability.replay !== "idempotent" ||
686
+ capability.recoveryDisposition !== "requires_proof" ||
687
+ receipt?.provenance !== "bound" ||
688
+ !receipt.binding ||
689
+ (receipt.status !== "started" && receipt.status !== "unknown")) {
690
+ continue;
691
+ }
692
+ candidates.push({
693
+ previousReceiptId: event.idempotencyKey,
694
+ previousCallId: event.callId,
695
+ attempt: (priorAttemptByCall.get(callKey) ?? 1) + 1,
696
+ agent: event.agent,
697
+ tool: event.tool,
698
+ ...(event.stepId ? { stepId: event.stepId } : {}),
699
+ argumentsFingerprint: receipt.binding.argumentsFingerprint,
700
+ capabilityFingerprint: receipt.binding.capabilityFingerprint,
701
+ });
702
+ }
703
+ return candidates;
704
+ }
705
+ /** 由 Runtime 单点判断持久化运行是否满足自动恢复的安全前提。 */
706
+ export function isRunStateResumable(records) {
707
+ if (records.length === 0 || records.some((record) => record.kind === "finish"))
708
+ return false;
709
+ const trace = records
710
+ .filter((record) => record.kind === "event")
711
+ .map((record) => tracePayload(record.payload, record.runId));
712
+ return inputReceiptsAreResumable(trace) && findUnsafeToolCall(trace) === undefined;
713
+ }
334
714
  /** 从中断的 append-only RunState 构造安全恢复计划。 */
335
715
  export function prepareRunResume(records, configFingerprint, requestedPrompt) {
336
716
  if (records.length === 0)
@@ -405,6 +785,9 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
405
785
  }
406
786
  }
407
787
  const operationSnapshot = operationSnapshotFromRecords(ordered);
788
+ if (!inputReceiptsAreResumable(previousTrace)) {
789
+ throw new CoreMindError("run_already_finished", "输入已到终态,不能自动恢复");
790
+ }
408
791
  const unsafe = findUnsafeToolCall(previousTrace);
409
792
  if (unsafe) {
410
793
  if (unsafe.receiptStatus === "committed") {
@@ -419,12 +802,22 @@ export function prepareRunResume(records, configFingerprint, requestedPrompt) {
419
802
  nextTraceSequence,
420
803
  completedSteps,
421
804
  effectReceipts,
805
+ toolReplayCandidates: collectToolReplayCandidates(previousTrace),
422
806
  previousTrace,
423
807
  operationRecords,
424
808
  ...(loopSnapshot ? { loopSnapshot } : {}),
425
809
  ...(operationSnapshot ? { operationSnapshot } : {}),
426
810
  };
427
811
  }
812
+ function inputReceiptsAreResumable(trace) {
813
+ try {
814
+ const statuses = foldInputReceipts(trace.map((entry) => entry.event));
815
+ return [...statuses.values()].every((status) => status === "pending" || status === "claimed");
816
+ }
817
+ catch (error) {
818
+ throw new CoreMindError("run_state_corrupt", `输入收据无法安全折叠:${error instanceof Error ? error.message : String(error)}`);
819
+ }
820
+ }
428
821
  /** 从 RunState 中校验并提取最新 operation 快照,供 CLI/SDK/Worker 共用。 */
429
822
  export function operationSnapshotFromRecords(records) {
430
823
  const operationRecords = records
@@ -436,7 +829,10 @@ export function operationSnapshotFromRecords(records) {
436
829
  }
437
830
  /** 配置指纹只落 hash,不把配置或凭据复制进 RunState。 */
438
831
  export function fingerprintRunConfig(config) {
439
- return createHash("sha256").update(stableJson(config)).digest("hex");
832
+ const resumeConfig = config !== null && typeof config === "object" && !Array.isArray(config)
833
+ ? Object.fromEntries(Object.entries(config).filter(([key]) => key !== "telemetry"))
834
+ : config;
835
+ return createHash("sha256").update(stableJson(resumeConfig)).digest("hex");
440
836
  }
441
837
  function tracePayload(payload, expectedRunId) {
442
838
  if (payload === null || typeof payload !== "object") {
@@ -476,18 +872,26 @@ function tracePayload(payload, expectedRunId) {
476
872
  (event.stepId !== undefined && typeof event.stepId !== "string"))) {
477
873
  throw new CoreMindError("run_state_corrupt", "RunState 包含非法 effect_receipt");
478
874
  }
875
+ if (event.type === "capability_resolved" &&
876
+ (typeof event.agent !== "string" ||
877
+ typeof event.tool !== "string" ||
878
+ typeof event.callId !== "string" ||
879
+ (event.stepId !== undefined && typeof event.stepId !== "string") ||
880
+ !isResolvedToolCapability(event.capability, event.tool) ||
881
+ !RECOVERY_DISPOSITIONS.includes(event.recoveryDisposition) ||
882
+ recoveryDispositionFor(event.capability) !== event.recoveryDisposition)) {
883
+ throw new CoreMindError("run_state_corrupt", "RunState 包含非法 capability_resolved");
884
+ }
885
+ if (event.type === "tool_lifecycle") {
886
+ try {
887
+ validateToolCallLifecycleFact(event);
888
+ }
889
+ catch {
890
+ throw new CoreMindError("run_state_corrupt", "RunState 包含非法 tool_lifecycle");
891
+ }
892
+ }
479
893
  return trace;
480
894
  }
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(",")}}`;
490
- }
491
895
  const LOOP_PHASES = new Set([
492
896
  "idle",
493
897
  "planning",
@@ -541,9 +945,31 @@ function validateRecord(value, expectedRunId) {
541
945
  record.runId !== expectedRunId ||
542
946
  !Number.isInteger(record.sequence) ||
543
947
  typeof record.timestamp !== "string" ||
544
- !["start", "resume", "event", "checkpoint", "loop", "operation", "pause", "finish"].includes(record.kind ?? "")) {
948
+ (record.eventId !== undefined &&
949
+ (typeof record.eventId !== "string" || record.eventId.trim().length === 0)) ||
950
+ ![
951
+ "start",
952
+ "resume",
953
+ "telemetry_configuration",
954
+ "telemetry_consent",
955
+ "control",
956
+ "delegation",
957
+ "event",
958
+ "checkpoint",
959
+ "checkpoint_restore",
960
+ "loop",
961
+ "operation",
962
+ "pause",
963
+ "finish",
964
+ ].includes(record.kind ?? "")) {
545
965
  throw new CoreMindError("run_state_corrupt", `RunState ${expectedRunId} 包含非法记录`);
546
966
  }
967
+ if (record.kind === "event" &&
968
+ record.payload !== null &&
969
+ typeof record.payload === "object" &&
970
+ "event" in record.payload) {
971
+ tracePayload(record.payload, expectedRunId);
972
+ }
547
973
  return record;
548
974
  }
549
975
  /** 从 RunState 事件记录中找第一个 input_receipt 的指纹(恢复时输入收据联动校验用) */