@sema-agent/core 7.72.0 → 7.73.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 (256) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/dist/agents/inherited-tool-pool.d.ts +26 -1
  3. package/dist/agents/inherited-tool-pool.js +46 -2
  4. package/dist/agents/parked-resume-drive.d.ts +10 -0
  5. package/dist/agents/parked-resume-drive.js +9 -0
  6. package/dist/agents/retain-ledger.d.ts +3 -0
  7. package/dist/agents/send-message-tool.js +1 -0
  8. package/dist/agents/send-user-message-tool.d.ts +12 -0
  9. package/dist/agents/send-user-message-tool.js +67 -0
  10. package/dist/agents/subagent-steps.d.ts +9 -0
  11. package/dist/agents/subagent-steps.js +38 -0
  12. package/dist/agents/subagent.d.ts +2 -0
  13. package/dist/agents/subagent.js +43 -12
  14. package/dist/agents/verify.js +23 -8
  15. package/dist/agents/yield-adoption.js +3 -1
  16. package/dist/brain/anthropic.js +14 -9
  17. package/dist/brain/open-responses.js +4 -5
  18. package/dist/brain/openai.js +30 -23
  19. package/dist/brain/stream-engine.js +159 -151
  20. package/dist/core/actions-digest.d.ts +43 -0
  21. package/dist/core/actions-digest.js +22 -0
  22. package/dist/core/allow-entry.js +3 -3
  23. package/dist/core/auto-mode.d.ts +7 -9
  24. package/dist/core/auto-mode.js +114 -8
  25. package/dist/core/checkpoint-features.d.ts +3 -2
  26. package/dist/core/checkpoint-features.js +1 -1
  27. package/dist/core/checkpoint-rekey.d.ts +1 -1
  28. package/dist/core/checkpoint-rekey.js +6 -1
  29. package/dist/core/checkpoint-requirements.d.ts +23 -3
  30. package/dist/core/checkpoint-requirements.js +5 -1
  31. package/dist/core/checkpoint-row-verdict.js +7 -1
  32. package/dist/core/checkpoint-store.d.ts +24 -2
  33. package/dist/core/checkpoint-store.js +1 -0
  34. package/dist/core/child-clamp-seats.d.ts +15 -0
  35. package/dist/core/child-clamp-seats.js +15 -0
  36. package/dist/core/delegation-frames.d.ts +1 -0
  37. package/dist/core/delegation-frames.js +1 -1
  38. package/dist/core/engine-capabilities.d.ts +5 -1
  39. package/dist/core/engine-capabilities.js +1 -1
  40. package/dist/core/engine-notice.d.ts +30 -22
  41. package/dist/core/engine-version.js +1 -1
  42. package/dist/core/entries-not-applied.d.ts +19 -7
  43. package/dist/core/entries-not-applied.js +33 -1
  44. package/dist/core/governance-codes.d.ts +7 -1
  45. package/dist/core/governance-codes.js +13 -5
  46. package/dist/core/hooks.d.ts +3 -0
  47. package/dist/core/hooks.js +1 -0
  48. package/dist/core/host-instance.d.ts +23 -0
  49. package/dist/core/host-instance.js +69 -0
  50. package/dist/core/instruction-preview.d.ts +63 -0
  51. package/dist/core/instruction-preview.js +406 -0
  52. package/dist/core/leg-budget.d.ts +26 -0
  53. package/dist/core/leg-budget.js +9 -0
  54. package/dist/core/leg-identity.d.ts +51 -1
  55. package/dist/core/leg-identity.js +45 -2
  56. package/dist/core/manager-launch-check.d.ts +48 -0
  57. package/dist/core/manager-launch-check.js +64 -0
  58. package/dist/core/mcp-call-meta.d.ts +2 -2
  59. package/dist/core/mcp-injection-drop.d.ts +20 -10
  60. package/dist/core/mcp-injection-drop.js +9 -3
  61. package/dist/core/mcp-server-spec.d.ts +2 -1
  62. package/dist/core/member-outcome.d.ts +3 -2
  63. package/dist/core/member-outcome.js +1 -1
  64. package/dist/core/memory-engine/deletion-record.d.ts +46 -0
  65. package/dist/core/memory-engine/deletion-record.js +96 -0
  66. package/dist/core/memory-engine/engine.js +24 -16
  67. package/dist/core/memory-engine/file-backend.js +7 -5
  68. package/dist/core/memory-engine/projection-ledger.d.ts +1 -1
  69. package/dist/core/memory-engine/projection-ledger.js +1 -1
  70. package/dist/core/memory-engine/scope-contract.d.ts +18 -13
  71. package/dist/core/memory-engine/scope-contract.js +18 -18
  72. package/dist/core/memory-engine/sync-client.js +26 -6
  73. package/dist/core/memory-engine/sync.d.ts +20 -2
  74. package/dist/core/memory-engine/sync.js +18 -17
  75. package/dist/core/mode-policy.d.ts +21 -6
  76. package/dist/core/mode-policy.js +15 -6
  77. package/dist/core/own-property-receipt.js +11 -4
  78. package/dist/core/parent-spec-seat.d.ts +13 -11
  79. package/dist/core/parent-spec-seat.js +13 -9
  80. package/dist/core/peer-seat.js +3 -3
  81. package/dist/core/peer-task-store.d.ts +365 -0
  82. package/dist/core/peer-task-store.js +682 -0
  83. package/dist/core/permission-rule-consent.js +6 -11
  84. package/dist/core/permission-rule-model.d.ts +27 -0
  85. package/dist/core/permission-rule-model.js +33 -5
  86. package/dist/core/permission-rule-provider.d.ts +35 -33
  87. package/dist/core/permission-rule-provider.js +38 -295
  88. package/dist/core/permission-rule-store.d.ts +181 -8
  89. package/dist/core/permission-rule-store.js +420 -17
  90. package/dist/core/permission-rule-sync.js +15 -1
  91. package/dist/core/project-seat.d.ts +55 -0
  92. package/dist/core/project-seat.js +96 -0
  93. package/dist/core/protocol-http-auth.d.ts +3 -2
  94. package/dist/core/protocol-http-auth.js +26 -18
  95. package/dist/core/remote-env.d.ts +4 -4
  96. package/dist/core/retired-keys.js +1 -0
  97. package/dist/core/rule-offer-read.d.ts +1 -1
  98. package/dist/core/rule-offer-read.js +32 -4
  99. package/dist/core/run-ledger-seat.d.ts +66 -0
  100. package/dist/core/run-ledger-seat.js +70 -0
  101. package/dist/core/run-ledger.d.ts +332 -0
  102. package/dist/core/run-ledger.js +550 -0
  103. package/dist/core/runner/checkpoint-scope.d.ts +13 -3
  104. package/dist/core/runner/checkpoint-scope.js +12 -4
  105. package/dist/core/runner/construction-doors.js +6 -0
  106. package/dist/core/runner/contracts.d.ts +21 -5
  107. package/dist/core/runner/delegation-owner.d.ts +30 -0
  108. package/dist/core/runner/delegation-owner.js +20 -4
  109. package/dist/core/runner/finish-reason-seat.js +4 -2
  110. package/dist/core/runner/leg-frame.js +3 -0
  111. package/dist/core/runner/nested-memory-lane.d.ts +22 -5
  112. package/dist/core/runner/nested-memory-lane.js +91 -30
  113. package/dist/core/runner/person-path-rows.d.ts +21 -16
  114. package/dist/core/runner/person-path-rows.js +80 -15
  115. package/dist/core/runner/prepare-caps-and-workflow.js +98 -88
  116. package/dist/core/runner/prepare-config-doors.d.ts +1 -0
  117. package/dist/core/runner/prepare-config-doors.js +5 -3
  118. package/dist/core/runner/prepare-context-lane.js +1 -0
  119. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  120. package/dist/core/runner/prepare-delegation-surface.js +6 -0
  121. package/dist/core/runner/prepare-execution-env.d.ts +3 -3
  122. package/dist/core/runner/prepare-hands-readface.d.ts +5 -2
  123. package/dist/core/runner/prepare-hands-readface.js +12 -1
  124. package/dist/core/runner/prepare-inherited-gate.d.ts +6 -3
  125. package/dist/core/runner/prepare-inherited-gate.js +13 -5
  126. package/dist/core/runner/prepare-run-refs.d.ts +1 -1
  127. package/dist/core/runner/prepare-run-refs.js +3 -2
  128. package/dist/core/runner/prepare-suspend-saga.d.ts +6 -2
  129. package/dist/core/runner/prepare-suspend-saga.js +4 -2
  130. package/dist/core/runner/prepare-task.js +36 -27
  131. package/dist/core/runner/prepare-turn-wiring.d.ts +4 -3
  132. package/dist/core/runner/prepare-turn-wiring.js +2 -1
  133. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  134. package/dist/core/runner/prepare-wiring-manifest.js +5 -2
  135. package/dist/core/runner/resume-apply.js +11 -5
  136. package/dist/core/runner/resume-review-outcome.d.ts +3 -0
  137. package/dist/core/runner/resume-review-outcome.js +24 -1
  138. package/dist/core/runner/run-harness-handlers.js +3 -0
  139. package/dist/core/runner/run-identity-wiring.js +3 -2
  140. package/dist/core/runner/run-leg.js +3 -0
  141. package/dist/core/runner/run-notification-lane.js +20 -1
  142. package/dist/core/runner/run-settle-and-teardown.js +21 -12
  143. package/dist/core/runner/run-stop-and-final-verify.js +6 -0
  144. package/dist/core/runner/run-telemetry-and-budget-seats.js +1 -1
  145. package/dist/core/runner/runtask.d.ts +6 -2
  146. package/dist/core/runner/runtask.js +21 -9
  147. package/dist/core/runner/shell-env-withheld.d.ts +3 -2
  148. package/dist/core/runner/shell-env-withheld.js +1 -2
  149. package/dist/core/runner/stop-tail-notice.d.ts +10 -2
  150. package/dist/core/runner/stop-tail-notice.js +9 -2
  151. package/dist/core/runner/stream-settle-backstop.d.ts +1 -0
  152. package/dist/core/runner/stream-settle-backstop.js +1 -0
  153. package/dist/core/runner/task-start-doors.js +6 -3
  154. package/dist/core/runner/terminal-account.d.ts +6 -1
  155. package/dist/core/runner/terminal-account.js +16 -1
  156. package/dist/core/runner/unreadable-person-rows.d.ts +2 -1
  157. package/dist/core/runner-deps.d.ts +13 -10
  158. package/dist/core/secret-env.d.ts +53 -37
  159. package/dist/core/secret-env.js +44 -47
  160. package/dist/core/session-checkout.d.ts +3 -0
  161. package/dist/core/session-checkout.js +1 -0
  162. package/dist/core/session-store.d.ts +12 -6
  163. package/dist/core/session-store.js +26 -6
  164. package/dist/core/session.d.ts +31 -8
  165. package/dist/core/store-contracts/checkpoint-store-contract.js +10 -0
  166. package/dist/core/store-contracts/peer-task-store-contract.d.ts +21 -0
  167. package/dist/core/store-contracts/peer-task-store-contract.js +516 -0
  168. package/dist/core/store-contracts/session-store-contract.d.ts +15 -2
  169. package/dist/core/store-contracts/session-store-contract.js +87 -3
  170. package/dist/core/store-contracts/workflow-journal-store-contract.d.ts +19 -1
  171. package/dist/core/store-contracts/workflow-journal-store-contract.js +89 -1
  172. package/dist/core/task-event.d.ts +10 -3
  173. package/dist/core/task-notification.d.ts +96 -10
  174. package/dist/core/task-notification.js +129 -5
  175. package/dist/core/task-registry-shared.d.ts +12 -1
  176. package/dist/core/task-registry-shared.js +3 -1
  177. package/dist/core/task-registry-workflow.d.ts +1 -1
  178. package/dist/core/task-registry-workflow.js +9 -1
  179. package/dist/core/task-registry.d.ts +39 -2
  180. package/dist/core/task-registry.js +76 -12
  181. package/dist/core/task-result.d.ts +13 -0
  182. package/dist/core/task-spec-members.d.ts +3 -1
  183. package/dist/core/task-spec-members.js +11 -3
  184. package/dist/core/task-spec.d.ts +48 -22
  185. package/dist/core/tool-catalog-entries.js +2 -0
  186. package/dist/core/tool-mount-facts.d.ts +1 -1
  187. package/dist/core/tool-mount-facts.js +1 -0
  188. package/dist/core/tool-mount-plan.d.ts +3 -1
  189. package/dist/core/tool-mount-plan.js +6 -0
  190. package/dist/core/tool-mount-static.d.ts +1 -1
  191. package/dist/core/tool-mount-static.js +4 -2
  192. package/dist/core/tool-result-store.d.ts +19 -2
  193. package/dist/core/tool-result-store.js +51 -2
  194. package/dist/core/tool-spec.d.ts +9 -2
  195. package/dist/core/user-attachment.d.ts +5 -1
  196. package/dist/core/user-attachment.js +14 -7
  197. package/dist/core/wiring-manifest.d.ts +26 -20
  198. package/dist/core/wiring-manifest.js +7 -3
  199. package/dist/core/workflow-journal-store.d.ts +53 -10
  200. package/dist/core/workflow-journal-store.js +27 -4
  201. package/dist/core/workflow-run-store-contract.js +16 -0
  202. package/dist/core/workflow-run-store.d.ts +9 -7
  203. package/dist/core/workflow-run-store.js +4 -1
  204. package/dist/engine/execution-env/node-execution-env.js +3 -1
  205. package/dist/engine/harness/types.d.ts +24 -1
  206. package/dist/engine/harness/types.js +10 -0
  207. package/dist/engine/llm/types.d.ts +5 -7
  208. package/dist/engine/lsp/node-lsp-manager.js +2 -1
  209. package/dist/engine/session/import-validate.js +6 -1
  210. package/dist/engine/session/session.d.ts +15 -2
  211. package/dist/engine/session/session.js +34 -4
  212. package/dist/index.d.ts +18 -7
  213. package/dist/index.js +13 -4
  214. package/dist/orchestration/run-workflow-tool.js +40 -32
  215. package/dist/orchestration/workflow-park-adoption.d.ts +51 -12
  216. package/dist/orchestration/workflow-park-adoption.js +47 -12
  217. package/dist/orchestration/workflow-stop.d.ts +128 -0
  218. package/dist/orchestration/workflow-stop.js +156 -0
  219. package/dist/orchestration/workflow.d.ts +30 -6
  220. package/dist/orchestration/workflow.js +117 -55
  221. package/dist/prompts/manager-recipe.d.ts +18 -0
  222. package/dist/prompts/manager-recipe.js +24 -0
  223. package/dist/stores/file/permission-rule-store.d.ts +3 -1
  224. package/dist/stores/file/permission-rule-store.js +0 -1
  225. package/dist/stores/file/workflow-journal-store.d.ts +16 -3
  226. package/dist/stores/file/workflow-journal-store.js +93 -5
  227. package/dist/stores/file/workflow-run-store.d.ts +1 -1
  228. package/dist/tools/fs/file-write-check.js +9 -3
  229. package/dist/tools/fs/index.d.ts +8 -7
  230. package/dist/tools/fs/index.js +4 -4
  231. package/dist/tools/fs/read-deny-home.d.ts +1 -1
  232. package/dist/tools/fs/read-deny-home.js +5 -5
  233. package/dist/tools/fs/read-deny.d.ts +33 -8
  234. package/dist/tools/fs/read-deny.js +114 -25
  235. package/dist/tools/fs/safety.d.ts +4 -1
  236. package/dist/tools/fs/safety.js +4 -2
  237. package/dist/tools/fs/shell-read-check.d.ts +9 -2
  238. package/dist/tools/fs/shell-read-check.js +96 -14
  239. package/dist/tools/fs/shell-read-establish.d.ts +9 -0
  240. package/dist/tools/fs/shell-read-establish.js +21 -11
  241. package/dist/tools/fs/shell-read-judge.d.ts +13 -1
  242. package/dist/tools/fs/shell-read-judge.js +26 -7
  243. package/dist/tools/fs/shell-read-plan.d.ts +5 -0
  244. package/dist/tools/fs/shell-read-write-targets.js +17 -9
  245. package/package.json +2 -2
  246. package/test/export-surface.snapshot.json +131 -1
  247. package/wire-changes/answers/core-stores-sql@7.73.0.json +28 -0
  248. package/wire-changes/answers/core@7.73.0.json +216 -0
  249. package/wire-changes/answers/mods-kernel@7.73.0.json +7 -0
  250. package/wire-changes/answers/primitives@7.73.0.json +12 -0
  251. package/wire-changes/answers/wiki-gate@7.73.0.json +7 -0
  252. package/wire-changes/core-stores-sql@7.73.0.json +326 -0
  253. package/wire-changes/core@7.73.0.json +6480 -0
  254. package/wire-changes/mods-kernel@7.73.0.json +147 -0
  255. package/wire-changes/primitives@7.73.0.json +227 -0
  256. package/wire-changes/wiki-gate@7.73.0.json +145 -0
@@ -20,6 +20,7 @@ import { enterConfigDoor } from "./config-refusal-input.js";
20
20
  import { readCallerSpec } from "./task-spec-members.js";
21
21
  import { PROJECT_MARKER_UNREADABLE_REASONS } from "./memory-engine/scope-contract.js";
22
22
  import { codedDetailStringOf } from "./runner/terminal-account.js";
23
+ import { readLegInstanceFact, receiveHostInstance } from "./host-instance.js";
23
24
  export function wiringLegKindOf(resumed, internals) {
24
25
  return resumed ? "resume" : engineLaneLegOf(internals) ? "child" : "root";
25
26
  }
@@ -266,8 +267,8 @@ function readProjectMarkerUnreadableFact(fact) {
266
267
  return shown !== undefined ? { reason: reason, markerPath: shown } : { reason: reason };
267
268
  }
268
269
  export function deriveWiringManifest(facts) {
269
- if (facts.half === "static" && (facts.leg !== undefined || facts.runOrigin !== undefined)) {
270
- throw new Error("a static wiring manifest has no leg — leg identity (its kind and its run origin) is an effective-half fact");
270
+ if (facts.half === "static" && (facts.leg !== undefined || facts.legInstance !== undefined || facts.runOrigin !== undefined)) {
271
+ throw new Error("a static wiring manifest has no leg — leg identity (its kind, its instance and its run origin) is an effective-half fact");
271
272
  }
272
273
  if (facts.half === "effective" && facts.leg === undefined) {
273
274
  throw new Error("an effective wiring manifest requires its leg kind");
@@ -290,7 +291,8 @@ export function deriveWiringManifest(facts) {
290
291
  : "absent";
291
292
  const manifest = {
292
293
  schemaVersion: 1,
293
- ...(facts.leg !== undefined ? { leg: { kind: facts.leg, ...(facts.runOrigin !== undefined ? { runOrigin: readWordFact(facts.runOrigin, RUN_ORIGINS, "run origin") } : {}) } } : {}),
294
+ ...(facts.leg !== undefined ? { leg: { kind: facts.leg, ...(facts.legInstance !== undefined ? { instance: readLegInstanceFact(facts.legInstance) } : {}), ...(facts.runOrigin !== undefined ? { runOrigin: readWordFact(facts.runOrigin, RUN_ORIGINS, "run origin") } : {}) } } : {}),
295
+ ...(facts.host !== undefined ? { host: receiveHostInstance(facts.host, "WiringFacts.host") } : {}),
294
296
  ask: {
295
297
  form: facts.askForm,
296
298
  ...(facts.askProvenance !== undefined ? { provenance: facts.askProvenance } : {}),
@@ -459,12 +461,14 @@ export function describeStaticWiring(deps, handed = {}, statement = {}) {
459
461
  if (read.refusal !== undefined)
460
462
  throw read.refusal;
461
463
  const spec = read.spec;
464
+ const host = receiveHostInstance(deps.host, "RunnerDeps.host");
462
465
  const ask = resolveAskSeamForm(spec, deps);
463
466
  const question = resolveQuestionSeam(spec, deps);
464
467
  const checkpointStore = resolveCheckpointStore(spec, deps);
465
468
  const capable = checkpointStore !== undefined;
466
469
  return deriveWiringManifest({
467
470
  half: "static",
471
+ ...(host !== undefined ? { host } : {}),
468
472
  askForm: ask.form,
469
473
  ...(ask.provenance !== undefined ? { askProvenance: ask.provenance } : {}),
470
474
  ...(ask.answeredClasses !== undefined ? { askAnsweredClasses: ask.answeredClasses } : {}),
@@ -284,7 +284,32 @@ export interface ResumeClaimAnswer {
284
284
  * not read (0 or less: refused while expired is a contradiction; not a safe integer; over the bound) names no instant and
285
285
  * says the store's answer does not read. */
286
286
  remainingMs?: number;
287
+ /** On a refusal because the key carries a permanent stop tombstone ({@link WorkflowJournalStore.stopResumeClaim}): who stopped
288
+ * the workflow tree. Reported explicitly by the store, never guessed by a caller from a prefix on `holder`. */
289
+ stopped?: {
290
+ readonly by: string;
291
+ };
292
+ }
293
+ /** Input to {@link WorkflowJournalStore.stopResumeClaim} (#5156 R1). */
294
+ export interface StopResumeClaimArgs {
295
+ /** The claim key (the workflow tree's root or tree id — opaque to the store, keyed verbatim as in {@link ResumeClaimArgs}). */
296
+ sourceRunId: string;
297
+ scope: string;
298
+ /** Non-empty identifier of who stopped the workflow tree (e.g. `"user"`, `"parent"`, `"system"`), echoed on
299
+ * {@link ResumeClaimAnswer.stopped}. */
300
+ stoppedBy: string;
301
+ /** When given, a binding claim currently held by THIS holder (arm (c): the caller's own in-process run, or a terminal run
302
+ * whose release failed) is rewritten into a tombstone in place; any other binding holder refuses without writing. */
303
+ holder?: string;
287
304
  }
305
+ /** What {@link WorkflowJournalStore.stopResumeClaim} answers: `{ stopped: true }` once a tombstone stands on `(sourceRunId, scope)`,
306
+ * or `{ stopped: false, holder? }` when another binding holder owns the claim (nothing written). */
307
+ export type StopResumeClaimAnswer = {
308
+ readonly stopped: true;
309
+ } | {
310
+ readonly stopped: false;
311
+ readonly holder?: string;
312
+ };
288
313
  /**
289
314
  * The seam a resume reads/writes its journal through. Core ships {@link InMemoryWorkflowJournalStore}; a durable
290
315
  * deployment provides a Postgres-backed one (service SVC-2) so a workflow survives a replica crash. The owner of
@@ -446,6 +471,21 @@ export interface WorkflowJournalStore {
446
471
  * rely on the engine waiting indefinitely for cleanup.
447
472
  */
448
473
  releaseResumeClaim?(input: ResumeClaimArgs): Promise<void>;
474
+ /**
475
+ * Write a permanent stop tombstone on `(sourceRunId, scope)` in one compare-and-write (#5156 R1):
476
+ * - (a) row absent ⇒ write tombstone, answer `{ stopped: true }`;
477
+ * - (b) row no longer binds (expired, or holder process proven gone on a store that checks it) ⇒ replace with tombstone,
478
+ * answer `{ stopped: true }`;
479
+ * - (c) `holder` given and matches the current holder ⇒ rewrite in place into a tombstone (dropping any holder process),
480
+ * answer `{ stopped: true }`;
481
+ * - (d) already a tombstone ⇒ idempotent, preserve the existing tombstone as stored, answer `{ stopped: true }`;
482
+ * - held by another and still binding ⇒ write nothing, answer `{ stopped: false, holder }`.
483
+ *
484
+ * A tombstone never expires, is never taken over, is never deleted by {@link releaseResumeClaim} (for any holder string),
485
+ * sweep or {@link deleteRun}, and makes {@link resumeClaim} answer `{ granted: false, stopped: { by } }`.
486
+ * OPTIONAL: a store without this verb is legal.
487
+ */
488
+ stopResumeClaim?(input: StopResumeClaimArgs): Promise<StopResumeClaimAnswer>;
449
489
  }
450
490
  export declare const MAX_JOURNAL_RESULT_BYTES: number;
451
491
  /** True when a serialized journal result is too large to store (UTF-8 byte length over {@link MAX_JOURNAL_RESULT_BYTES}). */
@@ -524,21 +564,24 @@ export declare const IN_MEMORY_RESUME_CLAIM_TTL_MS: number;
524
564
  * this one process. */
525
565
  export declare class InMemoryWorkflowJournalStore implements WorkflowJournalStore {
526
566
  private readonly runs;
527
- /** RB-367 resume claims, nested by scope then sourceRunId (rather than a single string-concatenated key) so
528
- * untrusted-length `scope`/`sourceRunId` text (`sourceRunId` is `resumeFromRunId` — LLM-controlled) can never
529
- * collide across the boundary between the two fields. */
567
+ /** RB-367 resume claims and #5156 R1 native tombstones, nested by scope then sourceRunId (rather than a single
568
+ * string-concatenated key) so untrusted-length `scope`/`sourceRunId` text (`sourceRunId` is `resumeFromRunId` — LLM-controlled)
569
+ * can never collide across the boundary between the two fields. Tombstones are a distinct variant — never a sentinel holder
570
+ * string — so `releaseResumeClaim` for any string can never delete one. */
530
571
  private readonly resumeClaims;
531
572
  private claimsForScope;
532
- /** Contract parity with the file store: keyed by `(sourceRunId, scope)`; idempotent re-grant to the
533
- * SAME holder; an unexpired claim held by someone else refuses (naming the holder); an expired or absent
534
- * claim is free to take. Acquisition is a single synchronous Map read-then-write with no `await` between
535
- * the check and the publish — there is no window (matching the atomicity RB-354 requires of a durable
536
- * implementation) in which a concurrent caller could observe the key as free mid-acquire. Both answers say how long the
537
- * claim has left by this process's clock (a re-claim by its holder starts the lease again). */
573
+ /** Contract parity with the file store: keyed by `(sourceRunId, scope)`; a tombstone always refuses with `stopped: { by }`;
574
+ * idempotent re-grant to the SAME holder; an unexpired claim held by someone else refuses (naming the holder); an expired or
575
+ * absent claim is free to take. Acquisition is a single synchronous Map read-then-write with no `await` between the check and
576
+ * the publish — there is no window (matching the atomicity RB-354 requires of a durable implementation) in which a concurrent
577
+ * caller could observe the key as free mid-acquire. Both answers say how long the claim has left by this process's clock (a
578
+ * re-claim by its holder starts the lease again). */
538
579
  resumeClaim(input: ResumeClaimArgs): Promise<ResumeClaimAnswer>;
539
- /** Release ONLY a claim `newRunId` still holds (a missing/foreign/already-taken-over claim is a
580
+ /** Release ONLY a claim `newRunId` still holds (a missing/foreign/already-taken-over claim or a tombstone is a
540
581
  * no-op, never an error — matches the file store's contract). */
541
582
  releaseResumeClaim(input: ResumeClaimArgs): Promise<void>;
583
+ /** #5156 R1 — compare-and-write a native tombstone on `(sourceRunId, scope)` (single synchronous Map step). */
584
+ stopResumeClaim(input: StopResumeClaimArgs): Promise<StopResumeClaimAnswer>;
542
585
  deleteRun(runId: string, scope: string): Promise<boolean>;
543
586
  /** Launch records by run id, each with the scope it was kept under. */
544
587
  private readonly launches;
@@ -312,11 +312,16 @@ export class InMemoryWorkflowJournalStore {
312
312
  const table = this.claimsForScope(input.scope);
313
313
  const now = Date.now();
314
314
  const existing = table.get(input.sourceRunId);
315
- if (existing !== undefined && existing.expiresAt > now && existing.holder !== input.newRunId) {
316
- return { granted: false, holder: existing.holder, ...resumeClaimRemainingMember(existing.expiresAt, now) };
315
+ if (existing !== undefined) {
316
+ if (existing.kind === "tombstone") {
317
+ return { granted: false, stopped: { by: existing.stoppedBy } };
318
+ }
319
+ if (existing.expiresAt > now && existing.holder !== input.newRunId) {
320
+ return { granted: false, holder: existing.holder, ...resumeClaimRemainingMember(existing.expiresAt, now) };
321
+ }
317
322
  }
318
323
  const expiresAt = now + IN_MEMORY_RESUME_CLAIM_TTL_MS;
319
- table.set(input.sourceRunId, { holder: input.newRunId, expiresAt });
324
+ table.set(input.sourceRunId, { kind: "claim", holder: input.newRunId, expiresAt });
320
325
  return { granted: true, ...resumeClaimRemainingMember(expiresAt, now) };
321
326
  }
322
327
  async releaseResumeClaim(input) {
@@ -324,9 +329,27 @@ export class InMemoryWorkflowJournalStore {
324
329
  if (table === undefined)
325
330
  return;
326
331
  const existing = table.get(input.sourceRunId);
327
- if (existing !== undefined && existing.holder === input.newRunId)
332
+ if (existing !== undefined && existing.kind === "claim" && existing.holder === input.newRunId)
328
333
  table.delete(input.sourceRunId);
329
334
  }
335
+ async stopResumeClaim(input) {
336
+ if (typeof input.stoppedBy !== "string" || input.stoppedBy === "") {
337
+ throw new TypeError("workflow journal: stopResumeClaim requires a non-empty stoppedBy string");
338
+ }
339
+ const table = this.claimsForScope(input.scope);
340
+ const now = Date.now();
341
+ const existing = table.get(input.sourceRunId);
342
+ if (existing !== undefined) {
343
+ if (existing.kind === "tombstone")
344
+ return { stopped: true };
345
+ const binds = existing.expiresAt > now;
346
+ if (binds && (input.holder === undefined || existing.holder !== input.holder)) {
347
+ return { stopped: false, holder: existing.holder };
348
+ }
349
+ }
350
+ table.set(input.sourceRunId, { kind: "tombstone", stoppedBy: input.stoppedBy, stoppedAt: now });
351
+ return { stopped: true };
352
+ }
330
353
  async deleteRun(runId, scope) {
331
354
  const launch = this.launches.get(runId);
332
355
  if (launch !== undefined && launch.scope === scope)
@@ -155,6 +155,22 @@ export async function workflowRunStoreContract(make, runAssertion = defaultSeque
155
155
  assert.equal(await store.update("fin", "tenant-a", { ...passed, parks: [{ ...entry, passedTo: "fin-other" }] }, { rev: got.rev ?? 0 }), false, "the same expectation loses once the row moved");
156
156
  assert.deepEqual((await store.get("fin")).parks, [{ ...entry, passedTo: "fin-next" }], "a lost write changes nothing");
157
157
  });
158
+ run("update never moves a terminal run (completed or failed) back to running: the write loses and changes nothing", async () => {
159
+ const store = make();
160
+ for (const status of ["completed", "failed"]) {
161
+ const id = `term-${status}`;
162
+ await store.put(id, createWorkflowRun({ id, status, creationId: `c-${status}` }));
163
+ const before = (await store.get(id));
164
+ const backToRunning = { ...before, status: "running", endedAt: undefined };
165
+ assert.equal(await store.update(id, "tenant-a", backToRunning, { rev: before.rev ?? 0 }), false, `${status} -> running loses with matching rev`);
166
+ assert.equal(await store.update(id, "tenant-a", backToRunning, { rev: before.rev ?? 0, creationId: `c-${status}` }), false, `${status} -> running loses with matching rev and creationId`);
167
+ assert.equal(await store.update(id, "tenant-a", backToRunning), false, `${status} -> running loses without expect`);
168
+ for (const cause of WORKFLOW_RUN_UPDATE_CAUSES) {
169
+ assert.equal(await store.update(id, "tenant-a", backToRunning, { rev: before.rev ?? 0, creationId: `c-${status}` }, { cause }), false, `${status} -> running loses with cause ${cause}`);
170
+ }
171
+ assert.deepEqual(await store.get(id), before, `${status} row is untouched after refused writes`);
172
+ }
173
+ });
158
174
  run("an update stating a cause persists the same row as one stating none, and wins and loses on rev, scope and a missing row the same way", async () => {
159
175
  const store = make();
160
176
  for (const cause of WORKFLOW_RUN_UPDATE_CAUSES) {
@@ -267,9 +267,11 @@ export interface WorkflowRunStore {
267
267
  * Atomic CAS update of an EXISTING run (`UPDATE … SET … WHERE id=? AND scope=?` [`AND rev=?`] [`AND` the creation id]). Returns
268
268
  * `true` for the winner, `false` when the row is missing, the `scope` does not match (multi-tenant
269
269
  * isolation — a wrong-scope update must not win), `expect.rev` does not match the live row's `rev`
270
- * (an intervening update bumped it), or `expect.creationId` is given and the live row is another creation of the id
270
+ * (an intervening update bumped it), `expect.creationId` is given and the live row is another creation of the id
271
271
  * ({@link WorkflowRunUpdateExpect}: a string must equal the row's member, `null` matches only a row whose member is not a string —
272
- * a SQL twin compares "is the extracted value a string", never "IS NULL", since a stored JSON null reads differently per dialect).
272
+ * a SQL twin compares "is the extracted value a string", never "IS NULL", since a stored JSON null reads differently per dialect),
273
+ * or the live row is terminal (`completed` / `failed`) and the candidate would move it back to `running` (a finished run never moves
274
+ * back to running; updates that keep a terminal row terminal — `park_pass`, `park_decision_settled`, `tree_id_stamp` — still apply).
273
275
  * A write that loses changes nothing. On success the store bumps the row's `rev` (monotonic) and persists
274
276
  * the new `run`. The workflow owner writes its record while it runs (best-effort progress recording — design/97 §F);
275
277
  * once the run has finished, a later continuation of its chain may write it again to take over a park it holds
@@ -337,8 +339,8 @@ export interface WorkflowRunStore {
337
339
  /**
338
340
  * REF-A5 — THE optimistic-concurrency guard for {@link WorkflowRunStore.update}, shared by every backend:
339
341
  * scope in the WHERE (multi-tenant isolation — a wrong-scope update never wins), row must exist, an
340
- * `expect.rev` that no longer matches the LIVE row loses (an intervening update bumped it), and an `expect.creationId` the live row is
341
- * not loses ({@link WorkflowRunUpdateExpect}). Returns the
342
+ * `expect.rev` that no longer matches the LIVE row loses (an intervening update bumped it), an `expect.creationId` the live row is
343
+ * not loses ({@link WorkflowRunUpdateExpect}), and a terminal row never moves back to a non-terminal state. Returns the
342
344
  * row to persist, or `null` when the CAS lost; PURE — it neither reads nor writes any store state, so
343
345
  * each backend keeps its own persistence mechanism (in-memory `Map.set` vs ledger commit) around it.
344
346
  * RB-59 (a cross-instance CAS both instances won) landed on this predicate.
@@ -400,9 +402,9 @@ export interface WorkflowRunReapFault {
400
402
  * erases its runs ({@link import("./retention.js").RETENTION_CASCADE}): its journal, then its persisted script, then its row
401
403
  * ({@link WorkflowRunStore.deleteRun}) — so nothing a run id keys outlives the row it is found through. Before a run's first leg its
402
404
  * record is read again and the selection re-judged on it (gone, no longer a terminal run of the scope, or — doomed by age — ended
403
- * since: skipped, nothing of it erased). A run's three parts are all there or its row is gone — save when another writer turns its
404
- * terminal row back to running between that re-judgment and the deletes: the journal and script go, the row stays (#5231, KL-4019-a;
405
- * no engine path writes that). Once its first leg has run, every
405
+ * since: skipped, nothing of it erased). A run's three parts are all there or its row is gone (a conforming store refuses moving a
406
+ * terminal row back to running; only an id deleted and recreated as running between that re-judgment and the row step leaves the
407
+ * new running row in `kept`). Once its first leg has run, every
406
408
  * leg runs, the row's last, whatever the ones before it answered — a row left beside an erased journal is a run a resume would run
407
409
  * again from its start. A leg that throws is one entry of `kept` (its part stays in that store; a run whose row's own leg threw keeps
408
410
  * its row, and the next sweep finds it again); a row that is no longer a terminal run when its own turn comes is reported the same
@@ -124,7 +124,10 @@ export function nextWorkflowRunOnUpdate(cur, id, scope, run, expect, disclose) {
124
124
  next.id = id;
125
125
  next.scope = scope;
126
126
  next.rev = (live.rev ?? 0) + 1;
127
- return admitWorkflowRun(next, id);
127
+ const admitted = admitWorkflowRun(next, id);
128
+ if (isTerminalWorkflowStatus(live.status) && !isTerminalWorkflowStatus(admitted.status))
129
+ return null;
130
+ return admitted;
128
131
  }
129
132
  function orderKey(value) {
130
133
  return typeof value === "number" && Number.isFinite(value) ? value : -Infinity;
@@ -9,7 +9,7 @@ import { basename, dirname, isAbsolute, join, sep } from "node:path";
9
9
  import { createInterface } from "node:readline";
10
10
  import { ExecutionError, err, FileError, ok, toError, } from "../harness/types.js";
11
11
  import { killProcessTree, shutdownDebug } from "./kill-tree.js";
12
- import { __resetSecretEnvScrubNoticeAnnouncement, announceSecretEnvScrub, declaredInheritEntry, hostChildEnv, hostChildEnvProblem, inheritEnvPolicyProblem, inheritedHostEnv } from "../../core/secret-env.js";
12
+ import { __resetSecretEnvScrubNoticeAnnouncement, announceSecretEnvScrub, declaredInheritEntry, hostChildEnv, hostChildEnvProblem, inheritEnvPolicyProblem, inheritedHostEnv, noteChildSpawned } from "../../core/secret-env.js";
13
13
  import { deliverEngineNotice } from "../../core/engine-notice.js";
14
14
  import { confineShellStart, SANDBOX_EXEC, SEATBELT_PROBE_PROFILE } from "../../core/shell-confinement.js";
15
15
  import { physicalPathOfAsync } from "../../core/physical-path.js";
@@ -846,6 +846,7 @@ export class NodeExecutionEnv {
846
846
  ...shellChildStdio(execSpoolFds, input !== undefined),
847
847
  windowsHide: true,
848
848
  });
849
+ noteChildSpawned(this.inheritEnv);
849
850
  }
850
851
  catch (error) {
851
852
  closeSpoolFds();
@@ -1711,6 +1712,7 @@ export class NodeExecutionEnv {
1711
1712
  ...shellChildStdio(spoolFds, false),
1712
1713
  windowsHide: true,
1713
1714
  });
1715
+ noteChildSpawned(this.inheritEnv);
1714
1716
  }
1715
1717
  catch (error) {
1716
1718
  if (spoolFds) {
@@ -1059,6 +1059,24 @@ export interface ReminderMarkEntry extends SessionTreeEntryBase {
1059
1059
  /** The opaque mark token (bounded; scheme-verified by the consumer, never by the store). */
1060
1060
  mark: string;
1061
1061
  }
1062
+ /**
1063
+ * A run's MEMBER LEDGER as one delivery carried it (`TaskSpec.runLedger`): written beside each report the run's report tool
1064
+ * delivered and once at the run's end, so a session reopened later replays the engine's half of every delivery exactly as it was.
1065
+ * Never rendered into the model's context. The ledger is an open record (`RunLedger`, `v` its shape version); the log keeps it as
1066
+ * written and a reader judges the members it knows.
1067
+ */
1068
+ export interface RunLedgerEntry extends SessionTreeEntryBase {
1069
+ type: "run_ledger";
1070
+ /** The ledger snapshot (`RunLedger`) — plain data. */
1071
+ ledger: {
1072
+ readonly v: number;
1073
+ readonly seq: number;
1074
+ readonly final: boolean;
1075
+ readonly rows: readonly unknown[];
1076
+ };
1077
+ }
1078
+ /** The shape gate of a {@link RunLedgerEntry}'s ledger (the append's and the import door's one check). */
1079
+ export declare function isRunLedgerRecord(v: unknown): v is RunLedgerEntry["ledger"];
1062
1080
  /**
1063
1081
  * design/319: strict shape gate for the reminder-mark entry — the SINGLE normalization the read
1064
1082
  * walk, the public append, and the import-validate door all use (the {@link normalizeAnnouncedListing}
@@ -1236,7 +1254,7 @@ export declare function isSyntheticApiErrorMessage(m: unknown): boolean;
1236
1254
  export declare function isOptionalDisplayString(v: unknown, max?: number): boolean;
1237
1255
  export declare function normalizeAnnouncedListing(v: unknown): AnnouncedListingSnapshot | undefined;
1238
1256
  /** All persisted session tree entry variants. */
1239
- export type SessionTreeEntry = MessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry | LeafEntry | PromptEpochEntry | AnnouncedListingEntry | GitAnnouncementEntry | WorkspaceStateEntry | SessionCheckoutEntry | ReminderMarkEntry;
1257
+ export type SessionTreeEntry = MessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry | LeafEntry | PromptEpochEntry | AnnouncedListingEntry | GitAnnouncementEntry | WorkspaceStateEntry | SessionCheckoutEntry | ReminderMarkEntry | RunLedgerEntry;
1240
1258
  export interface SessionContext {
1241
1259
  messages: AgentMessage[];
1242
1260
  thinkingLevel: string;
@@ -1452,6 +1470,11 @@ export interface Session<TMetadata extends SessionMetadata = SessionMetadata> {
1452
1470
  * mark restore ladder — the checkpoint seed stays first, the trusted fork channel second).
1453
1471
  * Undefined ⇒ no entry visible. OPTIONAL, same posture as `appendReminderMark`. */
1454
1472
  getReminderMark?(): Promise<string | undefined>;
1473
+ /** Persist a run's member ledger snapshot as a first-class {@link RunLedgerEntry} (see `Session.appendRunLedger`). OPTIONAL on
1474
+ * the interface — an implementer without it records none (the result and the report tool's own result still carry it). */
1475
+ appendRunLedger?(ledger: RunLedgerEntry["ledger"]): Promise<string>;
1476
+ /** The run-ledger entries on the active branch, oldest first — a reopened session's replay of every delivery's engine half. OPTIONAL, same posture. */
1477
+ getRunLedgers?(): Promise<RunLedgerEntry["ledger"][]>;
1455
1478
  /** The branch's current prompt-epoch descriptor (semantics: `Session.getPromptEpoch`). OPTIONAL on
1456
1479
  * the interface (typecheck 车 2026-07-24): the built-in `Session` class always implements it;
1457
1480
  * optionality keeps external `Session` implementers compatible. The consumer (`maybeCompact`'s
@@ -92,6 +92,16 @@ export class NothingQueuedError extends AgentHarnessError {
92
92
  }
93
93
  export const ANNOUNCED_LANGUAGE_MAX_CHARS = 256;
94
94
  export const REMINDER_MARK_MAX_CHARS = 64;
95
+ export function isRunLedgerRecord(v) {
96
+ if (v === null || typeof v !== "object" || Array.isArray(v))
97
+ return false;
98
+ const l = v;
99
+ const posInt = (x) => typeof x === "number" && Number.isSafeInteger(x) && x > 0;
100
+ const t = l["trigger"];
101
+ const kind = t !== null && typeof t === "object" ? t["kind"] : undefined;
102
+ const consistent = t === undefined || (typeof kind === "string" && (kind === "run_end") === l["final"]);
103
+ return posInt(l["v"]) && posInt(l["seq"]) && typeof l["final"] === "boolean" && Array.isArray(l["rows"]) && consistent;
104
+ }
95
105
  export function normalizeReminderMark(v) {
96
106
  if (typeof v !== "object" || v === null)
97
107
  return undefined;
@@ -947,13 +947,11 @@ export type AssistantMessageEvent = {
947
947
  partial: AssistantMessage;
948
948
  }
949
949
  /**
950
- * design/124 tier B contract note: after a mid-stream failure with only thinking streamed, the
951
- * brain seals the block (`thinking_end`) and RE-SENDS the whole turn WITHOUT a second `start` —
952
- * the retry attempt may then legally reopen a thinking block at the SAME contentIndex (the openai
953
- * parser hardcodes thinking at index 0; the anthropic wire restarts block indexing per attempt).
954
- * Consumers that render by `partial` snapshot are naturally correct (each retry event carries a
955
- * fresh snapshot that REPLACES the previous attempt's content — CC's "drop the thinking" semantics);
956
- * a consumer keying blocks by index gets exactly the intended replacement.
950
+ * design/124 tier B: after a thinking-only mid-stream cut, the brain seals (`thinking_end`) and
951
+ * re-sends without a second `start`, reopening thinking at the same `contentIndex` (each retry
952
+ * carries a fresh `partial` snapshot replacing the previous attempt's thinking). For a turn whose
953
+ * reasoning is interleaved with text, a live event's `contentIndex` is the order of arrival and
954
+ * is not an index into the saved message's `content`.
957
955
  */
958
956
  | {
959
957
  type: "thinking_start";
@@ -11,7 +11,7 @@ import { TransportLspSession } from "../../core/lsp-session.js";
11
11
  import { StdioLspTransport } from "./stdio-lsp-transport.js";
12
12
  import { MAX_LSP_FILE_BYTES, SharedAbortScope, settleOnAbort } from "../../core/lsp.js";
13
13
  import { asThrownError, thrownText } from "../../core/thrown-value.js";
14
- import { announceSecretEnvScrub, hostChildEnv, hostChildEnvProblem } from "../../core/secret-env.js";
14
+ import { announceSecretEnvScrub, hostChildEnv, hostChildEnvProblem, noteChildSpawned } from "../../core/secret-env.js";
15
15
  export const DEFAULT_LSP_SERVERS = {
16
16
  typescript: "typescript-language-server --stdio",
17
17
  javascript: "typescript-language-server --stdio",
@@ -364,6 +364,7 @@ const lspSpawnWithEnv = (grant, onNotice) => (command, args, cwd, signal) => new
364
364
  const { env, withheld } = hostChildEnv("scrub", grant);
365
365
  announceSecretEnvScrub(onNotice, withheld);
366
366
  child = spawn(command, args, { ...lspSpawnOptions(cwd), env });
367
+ noteChildSpawned("scrub");
367
368
  }
368
369
  catch (e) {
369
370
  return reject(asThrownError(e));
@@ -1,4 +1,4 @@
1
- import { SessionError, normalizeAnnouncedListing, normalizeReminderMark, normalizeGitAnnouncement, isSessionCheckoutStand, normalizeSessionCheckoutFact, normalizeSessionCheckoutStatement, normalizeWorkspaceState, normalizeCompactionStateCarrier, isValidThinkingLevelChange, isValidModelChange, isOptionalDisplayString, } from "../harness/types.js";
1
+ import { SessionError, normalizeAnnouncedListing, normalizeReminderMark, isRunLedgerRecord, normalizeGitAnnouncement, isSessionCheckoutStand, normalizeSessionCheckoutFact, normalizeSessionCheckoutStatement, normalizeWorkspaceState, normalizeCompactionStateCarrier, isValidThinkingLevelChange, isValidModelChange, isOptionalDisplayString, } from "../harness/types.js";
2
2
  import { leafIdAfterEntry } from "./storage-base.js";
3
3
  import { parseSessionTimestampMs } from "./timestamps.js";
4
4
  import { flattenableUserText, normalizeEngineSegments } from "../../core/untrusted-text.js";
@@ -127,6 +127,11 @@ export class StreamingImportValidator {
127
127
  throw new SessionError("invalid_session", `reminder_mark entry "${e.id}" is structurally invalid`);
128
128
  }
129
129
  }
130
+ else if (e.type === "run_ledger") {
131
+ if (!isRunLedgerRecord(e.ledger)) {
132
+ throw new SessionError("invalid_session", `run_ledger entry "${e.id}" is structurally invalid`);
133
+ }
134
+ }
130
135
  else if (e.type === "git_announcement") {
131
136
  if (!normalizeGitAnnouncement(e)) {
132
137
  throw new SessionError("invalid_session", `git_announcement entry "${e.id}" is structurally invalid`);
@@ -1,6 +1,6 @@
1
1
  import type { ImageContent, TextContent } from "../llm/index.js";
2
2
  import type { AgentMessage } from "../loop/types.js";
3
- import type { AnnouncedListingSnapshot, AnnouncedListingSnapshotInput, GitAnnouncementState, Session, SessionCheckoutRecord, SessionCheckoutStand, SessionCheckoutStatement, SessionContext, SessionMetadata, SessionStorage, SessionTreeEntry, WorkspaceState } from "../harness/types.js";
3
+ import type { AnnouncedListingSnapshot, AnnouncedListingSnapshotInput, GitAnnouncementState, RunLedgerEntry, Session, SessionCheckoutRecord, SessionCheckoutStand, SessionCheckoutStatement, SessionContext, SessionMetadata, SessionStorage, SessionTreeEntry, WorkspaceState } from "../harness/types.js";
4
4
  import type { BuildContextOptions } from "../harness/types.js";
5
5
  import type { PromptEpochDescriptor, StoredPromptEpoch } from "../../prompt-assembly/epoch.js";
6
6
  /** Which entry types the branch renders into the model's context — the one table, read twice: by the renderer below (a type
@@ -95,6 +95,14 @@ export declare class StoredSession<TMetadata extends SessionMetadata = SessionMe
95
95
  * verify port on the value it is persisting.
96
96
  */
97
97
  appendReminderMark(mark: string): Promise<string>;
98
+ /**
99
+ * Persist a run's member ledger snapshot (`TaskSpec.runLedger`) as a first-class {@link RunLedgerEntry} — written beside each
100
+ * delivery of the run's report tool and once at the run's end. The ledger is kept as plain data (a structured copy: nothing the
101
+ * caller holds afterwards can change what was written); a value that is not a ledger record refuses.
102
+ */
103
+ appendRunLedger(ledger: RunLedgerEntry["ledger"]): Promise<string>;
104
+ /** The run-ledger entries on the ACTIVE branch, oldest first (malformed ones skipped) — what a reopened session replays. */
105
+ getRunLedgers(): Promise<RunLedgerEntry["ledger"][]>;
98
106
  /**
99
107
  * design/319: recover the session's reminder provenance mark for the ACTIVE branch — the nearest
100
108
  * `reminder_mark` entry walking back from the leaf (SNAPSHOT semantics: first hit wins).
@@ -225,8 +233,13 @@ export type SessionCheckoutRead = {
225
233
  * reads (a window cut along the branch alone does not load other branches: KNOWN-LIMITS KL-3468-b). Never
226
234
  * best-effort: a store read that throws, an own entry or restatement that is not structurally valid, a restatement that says
227
235
  * unreadable, two different allocations, or a release that names another allocation answers `unreadable`.
236
+ *
237
+ * A package-root export (#4898): a host reads with it whether a session has a checkout record before it releases or admits a leg.
238
+ * `sessionId` absent ⇒ the session row's own id (`getMetadata().id`), the id the release door reads — a row that cannot be read answers
239
+ * `unreadable`, never `none` (an explicit `sessionId` reads the log directly without reading metadata). Zero writes: no entry appended,
240
+ * no environment opened, no git run; every read or fold failure answers `unreadable` rather than rejecting.
228
241
  */
229
- export declare function readSessionCheckout(session: Session, sessionId: string): Promise<SessionCheckoutRead>;
242
+ export declare function readSessionCheckout(session: Session, sessionId?: string): Promise<SessionCheckoutRead>;
230
243
  /** #3468: what a compaction restates of `sessionId`'s checkout — only a fact of the log later entries add to but never overturn: what the
231
244
  * reader vouches for (no `window`: not the view's), and a `none` only where no declaration can follow (`closed`:
232
245
  * {@link checkoutDeclarationClosed} as the compaction lands). Else nothing. */
@@ -1,5 +1,5 @@
1
1
  import { asAgentMessage, createCompactionSummaryMessage, createCustomMessage, } from "../harness/messages.js";
2
- import { SessionError, isSessionCheckoutStand, isSyntheticApiErrorMessage, isValidModelChange, normalizeAnnouncedListing, normalizeCompactionStateCarrier, normalizeGitAnnouncement, normalizeReminderMark, normalizeSessionCheckoutFact, normalizeSessionCheckoutStatement, normalizeWorkspaceState } from "../harness/types.js";
2
+ import { SessionError, isRunLedgerRecord, isSessionCheckoutStand, isSyntheticApiErrorMessage, isValidModelChange, normalizeAnnouncedListing, normalizeCompactionStateCarrier, normalizeGitAnnouncement, normalizeReminderMark, normalizeSessionCheckoutFact, normalizeSessionCheckoutStatement, normalizeWorkspaceState } from "../harness/types.js";
3
3
  import { readStoredPromptEpoch, walkPromptEpochCarriers } from "../../prompt-assembly/epoch.js";
4
4
  import { budgetInvokedSkillsRetention, readElidedMessages, readRetainedInvokedSkills, readUnsummarizedMessages, renderInvokedSkillsRetention, } from "../compaction/utils.js";
5
5
  import { thrownText } from "../../core/thrown-value.js";
@@ -21,6 +21,7 @@ export const ENTRY_RENDERS_INTO_CONTEXT = {
21
21
  reminder_mark: false,
22
22
  git_announcement: false,
23
23
  session_checkout: false,
24
+ run_ledger: false,
24
25
  };
25
26
  export function entryRendersIntoContext(entry) {
26
27
  return ENTRY_RENDERS_INTO_CONTEXT[entry.type] ?? true;
@@ -264,6 +265,28 @@ export class StoredSession {
264
265
  mark: shaped,
265
266
  });
266
267
  }
268
+ async appendRunLedger(ledger) {
269
+ let copy;
270
+ try {
271
+ copy = structuredClone(ledger);
272
+ }
273
+ catch {
274
+ copy = undefined;
275
+ }
276
+ if (!isRunLedgerRecord(copy))
277
+ throw new SessionError("invalid_entry", "appendRunLedger: the ledger is not a plain ledger record");
278
+ return this.appendTypedEntry({
279
+ type: "run_ledger",
280
+ id: await this.storage.createEntryId(),
281
+ parentId: await this.storage.getLeafId(),
282
+ timestamp: new Date().toISOString(),
283
+ ledger: copy,
284
+ });
285
+ }
286
+ async getRunLedgers() {
287
+ const branch = await this.getBranch();
288
+ return branch.flatMap((e) => (e.type === "run_ledger" && isRunLedgerRecord(e.ledger) ? [e.ledger] : []));
289
+ }
267
290
  async getReminderMark() {
268
291
  const branch = await this.getBranch();
269
292
  for (let i = branch.length - 1; i >= 0; i--) {
@@ -427,14 +450,21 @@ export function gitFrameContextVisible(branch, entryId) {
427
450
  return keptIdx !== -1 && frameIdx >= keptIdx;
428
451
  }
429
452
  export async function readSessionCheckout(session, sessionId) {
430
- let copies;
453
+ let id = sessionId;
454
+ if (id === undefined) {
455
+ try {
456
+ id = (await session.getMetadata()).id;
457
+ }
458
+ catch (err) {
459
+ return { kind: "unreadable", detail: `the session row could not be read (${thrownText(err)})` };
460
+ }
461
+ }
431
462
  try {
432
- copies = await sessionCheckoutCopiesOf(session.getStorage());
463
+ return foldSessionCheckout(await sessionCheckoutCopiesOf(session.getStorage()), id);
433
464
  }
434
465
  catch (err) {
435
466
  return { kind: "unreadable", detail: `the session log could not be read (${thrownText(err)})` };
436
467
  }
437
- return foldSessionCheckout(copies, sessionId);
438
468
  }
439
469
  async function sessionCheckoutCopiesOf(storage) {
440
470
  const floor = storage.getFloorId?.() ?? null;