@sema-agent/core 7.62.0 → 7.64.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 (320) hide show
  1. package/CHANGELOG.md +936 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  23. package/dist/agents/subagent-transcript-placement.js +14 -0
  24. package/dist/agents/subagent.js +102 -54
  25. package/dist/brain/route-adjudicator.js +9 -4
  26. package/dist/core/allow-entry.d.ts +4 -0
  27. package/dist/core/approval-object.js +1 -1
  28. package/dist/core/arg-summary.js +1 -1
  29. package/dist/core/ask-origin.d.ts +1 -1
  30. package/dist/core/ask-origin.js +2 -2
  31. package/dist/core/ask-question.d.ts +2 -2
  32. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  33. package/dist/core/ask-unresolvable-notice.js +10 -3
  34. package/dist/core/auto-compaction.d.ts +7 -5
  35. package/dist/core/background-agent-store.d.ts +7 -0
  36. package/dist/core/background-agent-store.js +3 -0
  37. package/dist/core/canonical-json.d.ts +23 -13
  38. package/dist/core/canonical-json.js +4 -4
  39. package/dist/core/checkpoint-queries.d.ts +50 -4
  40. package/dist/core/checkpoint-queries.js +42 -17
  41. package/dist/core/checkpoint-requirements.d.ts +3 -3
  42. package/dist/core/checkpoint-requirements.js +2 -1
  43. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  44. package/dist/core/checkpoint-row-verdict.js +22 -2
  45. package/dist/core/checkpoint-store.d.ts +28 -11
  46. package/dist/core/checkpoint-store.js +45 -4
  47. package/dist/core/compliance.d.ts +6 -2
  48. package/dist/core/compliance.js +3 -3
  49. package/dist/core/context-settings.d.ts +40 -9
  50. package/dist/core/context-settings.js +32 -10
  51. package/dist/core/engine-attestation.d.ts +27 -7
  52. package/dist/core/engine-attestation.js +5 -1
  53. package/dist/core/engine-notice.d.ts +43 -5
  54. package/dist/core/extension-requester.d.ts +9 -0
  55. package/dist/core/extension-requester.js +7 -0
  56. package/dist/core/file-history-store.d.ts +28 -0
  57. package/dist/core/file-history-store.js +48 -5
  58. package/dist/core/fs-write-gate-policy.js +1 -1
  59. package/dist/core/gate-fold.js +2 -0
  60. package/dist/core/gate-lanes.js +2 -0
  61. package/dist/core/gate-outcome.d.ts +39 -2
  62. package/dist/core/gate-outcome.js +20 -1
  63. package/dist/core/git-worktree-env.d.ts +62 -3
  64. package/dist/core/git-worktree-env.js +91 -30
  65. package/dist/core/governance-codes.d.ts +9 -3
  66. package/dist/core/governance-codes.js +17 -3
  67. package/dist/core/leg-identity.d.ts +19 -1
  68. package/dist/core/leg-identity.js +12 -0
  69. package/dist/core/mailbox-store.d.ts +39 -4
  70. package/dist/core/mailbox-store.js +14 -2
  71. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  72. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  73. package/dist/core/memory-engine/consolidation.d.ts +74 -10
  74. package/dist/core/memory-engine/consolidation.js +183 -11
  75. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  76. package/dist/core/memory-engine/control-objects.js +151 -0
  77. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  78. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  79. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  80. package/dist/core/memory-engine/data-plane.js +11 -6
  81. package/dist/core/memory-engine/delegation-settlement.d.ts +58 -40
  82. package/dist/core/memory-engine/delegation-settlement.js +270 -85
  83. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  84. package/dist/core/memory-engine/dual-root.js +11 -7
  85. package/dist/core/memory-engine/engine.d.ts +136 -58
  86. package/dist/core/memory-engine/engine.js +491 -394
  87. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  88. package/dist/core/memory-engine/entry-scan.js +3 -0
  89. package/dist/core/memory-engine/file-backend.d.ts +62 -60
  90. package/dist/core/memory-engine/file-backend.js +122 -198
  91. package/dist/core/memory-engine/index.d.ts +8 -7
  92. package/dist/core/memory-engine/index.js +7 -6
  93. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  94. package/dist/core/memory-engine/landing-admission.js +3 -3
  95. package/dist/core/memory-engine/layout.d.ts +127 -46
  96. package/dist/core/memory-engine/layout.js +264 -109
  97. package/dist/core/memory-engine/memory-backend-contract.d.ts +26 -1
  98. package/dist/core/memory-engine/memory-backend-contract.js +476 -0
  99. package/dist/core/memory-engine/memory-deployment.d.ts +42 -11
  100. package/dist/core/memory-engine/memory-deployment.js +54 -15
  101. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  102. package/dist/core/memory-engine/origin-clearance.js +68 -9
  103. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  104. package/dist/core/memory-engine/scope-contract.js +68 -19
  105. package/dist/core/memory-engine/session-write-home.d.ts +37 -2
  106. package/dist/core/memory-engine/session-write-home.js +38 -11
  107. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  108. package/dist/core/memory-engine/sync-client.js +7 -0
  109. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  110. package/dist/core/memory-engine/sync-report.js +6 -2
  111. package/dist/core/memory-engine/tools.d.ts +2 -2
  112. package/dist/core/memory-engine/tools.js +10 -10
  113. package/dist/core/memory-engine/types.d.ts +155 -19
  114. package/dist/core/memory-engine/types.js +2 -0
  115. package/dist/core/memory.js +15 -6
  116. package/dist/core/mode-policy.js +3 -3
  117. package/dist/core/mods/agent-stations.d.ts +18 -0
  118. package/dist/core/mods/agent-stations.js +8 -6
  119. package/dist/core/mods/extension-call.d.ts +4 -0
  120. package/dist/core/mods/extension-call.js +8 -0
  121. package/dist/core/mods/stations.d.ts +20 -1
  122. package/dist/core/mods/stations.js +21 -2
  123. package/dist/core/mods/tool-call.js +3 -4
  124. package/dist/core/parent-spec-seat.d.ts +2 -2
  125. package/dist/core/park-selfcheck.js +2 -2
  126. package/dist/core/pause-registry.d.ts +2 -0
  127. package/dist/core/pause-registry.js +3 -0
  128. package/dist/core/peer-channel.d.ts +5 -0
  129. package/dist/core/permission-rule-consent.d.ts +26 -8
  130. package/dist/core/permission-rule-consent.js +76 -36
  131. package/dist/core/permission-rule-store.d.ts +72 -13
  132. package/dist/core/permission-rule-store.js +29 -8
  133. package/dist/core/read-only-shell.js +3 -2
  134. package/dist/core/redaction-marks.d.ts +8 -0
  135. package/dist/core/redaction-marks.js +6 -0
  136. package/dist/core/refusal-echo.d.ts +20 -0
  137. package/dist/core/refusal-echo.js +33 -0
  138. package/dist/core/remote-env.d.ts +12 -1
  139. package/dist/core/remote-env.js +3 -0
  140. package/dist/core/retention.d.ts +180 -10
  141. package/dist/core/retention.js +45 -0
  142. package/dist/core/retired-keys.d.ts +5 -0
  143. package/dist/core/retired-keys.js +3 -0
  144. package/dist/core/rule-offer-read.d.ts +0 -4
  145. package/dist/core/rule-offer-read.js +2 -18
  146. package/dist/core/runner/child-tree.d.ts +29 -3
  147. package/dist/core/runner/child-tree.js +39 -16
  148. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  149. package/dist/core/runner/classifier-ladder.js +4 -2
  150. package/dist/core/runner/compact-session.js +10 -7
  151. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  152. package/dist/core/runner/compaction-call-options.js +3 -2
  153. package/dist/core/runner/contracts.d.ts +39 -11
  154. package/dist/core/runner/delegation-owner.d.ts +10 -3
  155. package/dist/core/runner/delegation-owner.js +4 -1
  156. package/dist/core/runner/gate-exit.d.ts +6 -0
  157. package/dist/core/runner/gate-exit.js +13 -4
  158. package/dist/core/runner/inherited-ask-grants.js +1 -1
  159. package/dist/core/runner/memory-consolidation-driver.d.ts +10 -5
  160. package/dist/core/runner/memory-consolidation-driver.js +12 -9
  161. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  162. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  163. package/dist/core/runner/person-path-rows.d.ts +8 -3
  164. package/dist/core/runner/person-path-rows.js +5 -1
  165. package/dist/core/runner/placement-fence.d.ts +12 -0
  166. package/dist/core/runner/placement-fence.js +20 -6
  167. package/dist/core/runner/prepare-ask-lane.js +5 -5
  168. package/dist/core/runner/prepare-caps-and-workflow.d.ts +7 -2
  169. package/dist/core/runner/prepare-caps-and-workflow.js +7 -4
  170. package/dist/core/runner/prepare-config-doors.js +4 -0
  171. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  172. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  173. package/dist/core/runner/prepare-execution-env.js +17 -6
  174. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  175. package/dist/core/runner/prepare-gate-stations.js +5 -5
  176. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  177. package/dist/core/runner/prepare-hands-readface.js +5 -4
  178. package/dist/core/runner/prepare-inherited-gate.d.ts +13 -9
  179. package/dist/core/runner/prepare-inherited-gate.js +12 -6
  180. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  181. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  182. package/dist/core/runner/prepare-memory.d.ts +7 -2
  183. package/dist/core/runner/prepare-memory.js +41 -39
  184. package/dist/core/runner/prepare-park-ask.js +4 -3
  185. package/dist/core/runner/prepare-policy-chain.js +7 -7
  186. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  187. package/dist/core/runner/prepare-task.js +26 -18
  188. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  189. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  190. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  191. package/dist/core/runner/resume-admission.d.ts +2 -2
  192. package/dist/core/runner/resume-admission.js +2 -23
  193. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  194. package/dist/core/runner/role-resolution-table.js +62 -0
  195. package/dist/core/runner/run-compaction-machinery.js +2 -2
  196. package/dist/core/runner/run-identity-wiring.js +12 -9
  197. package/dist/core/runner/run-leg.js +9 -5
  198. package/dist/core/runner/run-notification-lane.js +22 -22
  199. package/dist/core/runner/run-recovery-lanes.js +3 -3
  200. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  201. package/dist/core/runner/run-terminal-adoption.js +1 -1
  202. package/dist/core/runner/run-turn-boundary.js +14 -15
  203. package/dist/core/runner/runtask.js +1 -1
  204. package/dist/core/runner/terminal-account.js +1 -1
  205. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  206. package/dist/core/runner/tool-occurrence.js +2 -2
  207. package/dist/core/runner-deps.d.ts +7 -3
  208. package/dist/core/secret-env.d.ts +1 -1
  209. package/dist/core/secret-env.js +4 -4
  210. package/dist/core/session-checkout.d.ts +168 -0
  211. package/dist/core/session-checkout.js +579 -0
  212. package/dist/core/session-store.d.ts +12 -4
  213. package/dist/core/session-store.js +23 -3
  214. package/dist/core/session.d.ts +16 -2
  215. package/dist/core/session.js +3 -0
  216. package/dist/core/shell-read-silence.js +8 -0
  217. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  218. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  219. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  220. package/dist/core/store-contracts/session-store-contract.js +39 -0
  221. package/dist/core/task-event.d.ts +30 -5
  222. package/dist/core/task-notification.d.ts +119 -32
  223. package/dist/core/task-notification.js +186 -100
  224. package/dist/core/task-registry-agent.d.ts +25 -2
  225. package/dist/core/task-registry-agent.js +56 -22
  226. package/dist/core/task-registry-shared.d.ts +33 -11
  227. package/dist/core/task-registry.d.ts +33 -9
  228. package/dist/core/task-registry.js +36 -18
  229. package/dist/core/task-spec-members.js +1 -1
  230. package/dist/core/task-spec.d.ts +27 -2
  231. package/dist/core/tool-errors.d.ts +14 -6
  232. package/dist/core/tool-errors.js +1 -1
  233. package/dist/core/tool-policy.d.ts +32 -13
  234. package/dist/core/tool-policy.js +27 -17
  235. package/dist/core/tool-result-store.d.ts +20 -0
  236. package/dist/core/tool-spec.d.ts +42 -19
  237. package/dist/core/trace.d.ts +3 -2
  238. package/dist/core/types.d.ts +1 -1
  239. package/dist/core/untrusted-egress.d.ts +15 -4
  240. package/dist/core/untrusted-egress.js +23 -22
  241. package/dist/core/workflow-journal-store.d.ts +11 -0
  242. package/dist/core/workflow-journal-store.js +7 -0
  243. package/dist/core/workflow-run-store.d.ts +9 -0
  244. package/dist/core/workflow-run-store.js +6 -0
  245. package/dist/core/workspace-snapshot.d.ts +3 -1
  246. package/dist/core/workspace-snapshot.js +1 -0
  247. package/dist/engine/compaction/compaction.d.ts +2 -1
  248. package/dist/engine/harness/types.d.ts +67 -1
  249. package/dist/engine/harness/types.js +108 -0
  250. package/dist/engine/session/import-validate.js +6 -1
  251. package/dist/engine/session/session.d.ts +30 -1
  252. package/dist/engine/session/session.js +48 -1
  253. package/dist/index.d.ts +12 -7
  254. package/dist/index.js +12 -7
  255. package/dist/internal/harness-types.d.ts +1 -1
  256. package/dist/orchestration/run-workflow-tool.d.ts +8 -1
  257. package/dist/orchestration/run-workflow-tool.js +8 -0
  258. package/dist/orchestration/workflow-types.d.ts +2 -1
  259. package/dist/orchestration/workflow.d.ts +6 -0
  260. package/dist/orchestration/workflow.js +5 -2
  261. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  262. package/dist/stores/file/checkpoint-store.js +4 -1
  263. package/dist/stores/file/file-history-store.d.ts +13 -0
  264. package/dist/stores/file/file-history-store.js +75 -13
  265. package/dist/stores/file/index.d.ts +11 -1
  266. package/dist/stores/file/index.js +7 -11
  267. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  268. package/dist/stores/file/permission-rule-store.js +75 -7
  269. package/dist/stores/file/session-store.js +2 -1
  270. package/dist/stores/file/tool-result-store.d.ts +14 -0
  271. package/dist/stores/file/tool-result-store.js +39 -2
  272. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  273. package/dist/stores/file/workflow-journal-store.js +17 -0
  274. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  275. package/dist/stores/file/workflow-run-store.js +15 -0
  276. package/dist/tools/fs/bash-program-position.js +3 -3
  277. package/dist/tools/fs/program-read-model.d.ts +34 -10
  278. package/dist/tools/fs/program-read-model.js +37 -7
  279. package/dist/tools/fs/program-read-model.rows.js +13 -2
  280. package/dist/tools/fs/read-deny.d.ts +28 -3
  281. package/dist/tools/fs/read-deny.js +18 -2
  282. package/dist/tools/fs/removal-targets.js +3 -3
  283. package/dist/tools/fs/safety.d.ts +2 -0
  284. package/dist/tools/fs/safety.js +1 -1
  285. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  286. package/dist/tools/fs/shell-read-argv.js +34 -29
  287. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  288. package/dist/tools/fs/shell-read-bindings.js +5 -1
  289. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  290. package/dist/tools/fs/shell-read-brace.js +79 -0
  291. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  292. package/dist/tools/fs/shell-read-check.js +16 -14
  293. package/dist/tools/fs/shell-read-establish.js +23 -16
  294. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  295. package/dist/tools/fs/shell-read-judge.js +3 -3
  296. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  297. package/dist/tools/fs/shell-read-plan.js +189 -93
  298. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  299. package/dist/tools/fs/shell-read-start.js +20 -12
  300. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  301. package/dist/tools/fs/shell-read-word.js +9 -5
  302. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  303. package/dist/tools/fs/shell-read-workdir.js +73 -12
  304. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  305. package/dist/tools/worktree.d.ts +3 -2
  306. package/dist/tools/worktree.js +7 -35
  307. package/package.json +3 -2
  308. package/test/export-surface.snapshot.json +135 -11
  309. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  310. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  311. package/wire-changes/core@7.63.0.json +3523 -0
  312. package/wire-changes/core@7.64.0.json +2653 -0
  313. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  314. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  315. package/wire-changes/primitives@7.63.0.json +445 -0
  316. package/wire-changes/primitives@7.64.0.json +30 -0
  317. package/dist/core/credential-vocabulary.d.ts +0 -176
  318. package/dist/core/credential-vocabulary.js +0 -190
  319. package/dist/core/redaction-passes.d.ts +0 -82
  320. package/dist/core/redaction-passes.js +0 -377
@@ -9,7 +9,7 @@ export type { InvokedSkillRetention } from "../engine/compaction/utils.js";
9
9
  export type { AgentCoreRuntimeDeps } from "../engine/loop/runtime-deps.js";
10
10
  export type { LoopTerminalReason } from "../engine/loop/agent-loop.js";
11
11
  export type { AgentMessage, AgentTool, AgentToolResult, AgentToolUpdateCallback, ThinkingLevel, ToolExecutionMode, ToolInputValidationContext, ToolInputVerdict, } from "../engine/loop/types.js";
12
- export type { AgentHarnessEvent, CompactionSettings, ExecutionEnv, ExecutionErrorCode, FileError, FileKind, FileErrorCode, FileInfo, Result, WriteExpectation, WriteReceipt, SymlinkChain, BoundFileObject, Session, SessionMetadata, SessionRepo, SessionStorage, SessionTreeEntry, Skill, } from "../engine/harness/types.js";
12
+ export type { AgentHarnessEvent, CompactionSettings, ExecutionEnv, ExecutionErrorCode, FileError, FileKind, FileErrorCode, FileInfo, Result, WriteExpectation, WriteReceipt, SymlinkChain, BoundFileObject, Session, SessionCheckoutCell, SessionCheckoutDeclared, SessionCheckoutRecord, SessionCheckoutSource, SessionMetadata, SessionRepo, SessionStorage, SessionTreeEntry, Skill, } from "../engine/harness/types.js";
13
13
  export type { ExecutionEnvExecOptions, ExecResult, ReadFloor, ExecutionEnvCapabilities } from "../engine/harness/types.js";
14
14
  export type { SessionWriteOptions, CompactionEntry } from "../engine/harness/types.js";
15
15
  export type { RowAdmission, RowRaising } from "../engine/harness/types.js";
@@ -175,6 +175,10 @@ export interface RunWorkflowToolDeps {
175
175
  * root MUST ride deps; `ctx.rootSessionId` stays first for a deployment-composed mount that
176
176
  * does get the enriched ctx. */
177
177
  rootSessionId?: string;
178
+ /** The occupant (`SessionMetadata.incarnation`) of {@link rootSessionId}'s row as this host tree holds it — read at call
179
+ * time (the host leg learns its own occupant after the mount is wired). Rides beside the root anchor for the same
180
+ * auto-mounted-ctx reason; a workflow-spawned agent addresses an escalated terminal frame to (root, occupant). */
181
+ rootSessionIncarnation?: () => string | undefined;
178
182
  /** design/380 O1② (C12) — the host run's EXPLICIT placement fixed point
179
183
  * (`RunInternals.placementRoot`), riding deps for the same auto-mounted-ctx reason as
180
184
  * `rootSessionId` above; threaded into the workflow run so every workflow-spawned agent keeps
@@ -258,9 +262,12 @@ export interface RunWorkflowToolDeps {
258
262
  /** TRUSTED nesting depth from the run's internals (NOT a tool param) — passed to `startWorkflow` so a
259
263
  * cross-process child workflow is rejected by the one-level guard. */
260
264
  workflowDepth?: number;
261
- /** The HOST task's effective working root — threaded into every spawned agent's trusted internals so a
265
+ /** Where the HOST task writes (read at the spawn) — threaded into every spawned agent's trusted internals so a
262
266
  * TOC env factory can root the child at the parent's cwd (CC parity, 2026-07-03). */
263
267
  parentCwd?: string;
268
+ /** The HOST task's own task root — threaded beside {@link parentCwd} as `RunInternals.callerRoot`, the checkout a child's
269
+ * placement is judged against (whichever tree the host has switched to inside it). */
270
+ callerRoot?: string;
264
271
  /** The HOST task's own placement target (what its env reported as its workspace settled) — the fence every agent the
265
272
  * workflow spawns is minted under (`RunInternals.placementTarget`). Rides deps for the auto-mounted form (whose
266
273
  * execute ctx carries none); a rich ctx's own `placementTarget` wins. */
@@ -60,6 +60,12 @@ function completionSummary(name, run) {
60
60
  return (`workflow${cleanName ? ` "${cleanName}"` : ""} completed${elapsed} — agents ${done}/${run.agents.length} done` +
61
61
  `${failed > 0 ? ` (${failed} failed)` : ""}${resumeClause}`);
62
62
  }
63
+ function rootOccupantSeat(rootId, ctx, d) {
64
+ if (rootId === undefined)
65
+ return {};
66
+ const occupant = (rootId === (ctx.rootSessionId ?? ctx.sessionId) ? ctx.rootSessionIncarnation : undefined) ?? (rootId === d.rootSessionId ? d.rootSessionIncarnation?.() : undefined);
67
+ return occupant !== undefined ? { rootSessionIncarnation: occupant } : {};
68
+ }
63
69
  const WORKFLOW_NOTIFY_ROWS_MAX = 5;
64
70
  function workflowRecordTeach(run, artifact) {
65
71
  const notDone = run.agents.filter((a) => a.status !== "completed");
@@ -516,6 +522,7 @@ async function mountRunWorkflowTool(d) {
516
522
  ...(sourceTaskId !== undefined ? { sourceTaskId } : {}),
517
523
  ...(d.originatingSessionId !== undefined ? { originatingSessionId: d.originatingSessionId } : {}),
518
524
  ...((ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId) !== undefined ? { rootSessionId: ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId } : {}),
525
+ ...rootOccupantSeat(ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId, ctx, d),
519
526
  ...((ctx.placementRoot ?? d.placementRoot) !== undefined ? { placementRoot: ctx.placementRoot ?? d.placementRoot } : {}),
520
527
  ...((ctx.placementTarget ?? d.placementTarget) !== undefined ? { placementTarget: ctx.placementTarget ?? d.placementTarget } : {}),
521
528
  ...((ctx.crossBoundaryTreeForChildren ?? d.crossBoundaryTree) !== undefined ? { crossBoundaryTree: ctx.crossBoundaryTreeForChildren ?? d.crossBoundaryTree } : {}),
@@ -531,6 +538,7 @@ async function mountRunWorkflowTool(d) {
531
538
  maxResultChars: lim.maxResultChars ?? DEFAULTS.maxResultChars,
532
539
  maxLogChars: lim.maxLogChars ?? DEFAULTS.maxLogChars,
533
540
  ...(d.parentCwd !== undefined ? { parentCwd: d.parentCwd } : {}),
541
+ ...(d.callerRoot !== undefined ? { callerRoot: d.callerRoot } : {}),
534
542
  parentToolCallId: ctx.toolCallId,
535
543
  ...(sourceTaskId !== undefined ? { parentTaskId: sourceTaskId } : {}),
536
544
  ...((ctx.interactionPosture ?? d.parentInteractionPosture) !== undefined ? { interactionPosture: (ctx.interactionPosture ?? d.parentInteractionPosture) } : {}),
@@ -5,7 +5,8 @@ export type WorkflowRunStatus = "running" | "completed" | "failed";
5
5
  * {@link WorkflowAgentRun.parkedCheckpointToken}); a phase or group never parks (a parked agent ends the run). */
6
6
  export type WorkflowItemStatus = "running" | "completed" | "failed" | "parked";
7
7
  /** The arm a `workflow.park_truth_unreadable` resume refusal fired on (`detail.reason`): the prior run's record could not
8
- * be read (`store_threw`), is absent under this scope (`record_missing`), is not terminal (`record_not_terminal`),
8
+ * be read (`store_threw`), is absent under this scope (`record_missing` — never recorded under it, reaped, or deleted with
9
+ * the session that started it: one word, because after a deletion the three are the same absence), is not terminal (`record_not_terminal`),
9
10
  * carries no `parks` array and nothing to derive one from — an empty journal, or an empty derived union
10
11
  * (`parks_unreadable`) — or says its OWN resume admission never completed
11
12
  * ({@link WorkflowRun.resumeAdmissionIncomplete} — nothing on it describes a settled park set, so it is not a
@@ -342,6 +342,9 @@ export interface RunWorkflowOptions {
342
342
  * `ctx.rootSessionId ?? originatingSessionId`); rides the wa* observer frames so a recovery face
343
343
  * groups workflow-agent rows under the root host session too. */
344
344
  rootSessionId?: string;
345
+ /** The occupant (`SessionMetadata.incarnation`) of {@link rootSessionId}'s row as the host tree holds it; rides the
346
+ * shared internals base beside the root anchor (`RunInternals.rootSessionIncarnation`). Absent = unknown. */
347
+ rootSessionIncarnation?: string;
345
348
  /** design/380 O1② (C12) — the host run's EXPLICIT placement fixed point
346
349
  * (`RunInternals.placementRoot`, threaded by the run-workflow tool when the host carried one):
347
350
  * every workflow-spawned agent inherits it verbatim so descendants of a cascade/verify leg stay
@@ -438,6 +441,9 @@ export interface RunWorkflowOptions {
438
441
  * (`RunInternals.parentCwd`) so a TOC env factory roots children at the parent's cwd (CC parity;
439
442
  * `isolation: "worktree"` on an individual agent wins over it). */
440
443
  parentCwd?: string;
444
+ /** The HOST task's own task root — `RunInternals.callerRoot` on both spawn legs, the checkout a child's placement is judged
445
+ * against (the host's {@link parentCwd} can sit in a tree inside it). Absent: the host's root is where it works ({@link parentCwd}). */
446
+ callerRoot?: string;
441
447
  /**
442
448
  * The SPAWNING tool call's id (`run_workflow`'s own `ToolExecuteContext.toolCallId`) — threaded into every
443
449
  * spawned agent's trusted internals (`RunInternals.parentToolCallId`) so each child's frames carry this id
@@ -26,6 +26,7 @@ import { namesEveryTool } from "../agents/tool-filter.js";
26
26
  import { definitionAllowTools, withDefinitionServers } from "../agents/inherited-tool-pool.js";
27
27
  import { snapshotAndValidateMcpEntries } from "../core/locked-config.js";
28
28
  import { compileOutputSchema } from "../core/runner/strict-output-schema.js";
29
+ import { callerPlacementSeats } from "../core/runner/child-tree.js";
29
30
  import { WorkflowBudgetExceededError, WorkflowNestingError, WorkflowAgentBlockedError, WorkflowAgentParkedError, WorkflowAgentSchemaError, WorkflowAgentStalledError, WorkflowMaxAgentsError, WORKFLOW_SPAWN_BLOCKED_ERROR_CODE } from "./workflow-types.js";
30
31
  import { WorkflowScriptError } from "./workflow-meta.js";
31
32
  import { firstByteLaneKnobMs, STALL_FIRST_BYTE_MS, STALL_FIRST_TOKEN_MS } from "../brain/timeout.js";
@@ -739,6 +740,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
739
740
  ...(opts.inheritedGate !== undefined ? { inheritedGate: opts.inheritedGate } : {}),
740
741
  ...(agentCeiling !== undefined ? { toolCeiling: agentCeiling } : {}),
741
742
  ...((opts.rootSessionId ?? opts.originatingSessionId) !== undefined ? { rootSessionId: opts.rootSessionId ?? opts.originatingSessionId } : {}),
743
+ ...(opts.rootSessionId !== undefined && opts.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: opts.rootSessionIncarnation } : {}),
742
744
  ...(opts.placementRoot !== undefined ? { placementRoot: opts.placementRoot } : {}),
743
745
  ...(opts.placementTarget !== undefined ? { placementTarget: opts.placementTarget } : {}),
744
746
  ...(opts.crossBoundaryTree !== undefined ? { crossBoundaryTree: opts.crossBoundaryTree } : {}),
@@ -1893,7 +1895,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
1893
1895
  opts.onForwardEvent(e.type === "task_progress" || e.type === "task_started" ? { ...e, workflowRunId: runId, workflowAgentLabel: label } : e);
1894
1896
  }
1895
1897
  : undefined;
1896
- const baseInternals = { ...(agentOpts.isolation ? { isolation: agentOpts.isolation } : {}), ...(opts.parentCwd !== undefined ? { parentCwd: opts.parentCwd, callerRoot: opts.parentCwd } : {}), ...spawnAttribution, ...(await captureFloorSeatsNow()), ...(enrichedForward !== undefined ? { onForwardEvent: enrichedForward } : {}), delegationTaskType: "workflow", agentName: label, onWorkspaceResolved: createWorkspaceObserver(rec) };
1898
+ const baseInternals = { ...(agentOpts.isolation ? { isolation: agentOpts.isolation } : {}), ...(opts.parentCwd !== undefined ? { parentCwd: opts.parentCwd } : {}), ...callerPlacementSeats(opts.parentCwd, opts.callerRoot), ...spawnAttribution, ...(await captureFloorSeatsNow()), ...(enrichedForward !== undefined ? { onForwardEvent: enrichedForward } : {}), delegationTaskType: "workflow", agentName: label, onWorkspaceResolved: createWorkspaceObserver(rec) };
1897
1899
  let attempts = 0;
1898
1900
  let throttleRetried = false;
1899
1901
  let lastAttemptReason;
@@ -2285,6 +2287,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
2285
2287
  ...(inheritedModelRef !== undefined ? { inheritedModelRef } : {}),
2286
2288
  ...(agentOpts.isolation ? { isolation: agentOpts.isolation } : {}),
2287
2289
  ...(opts.parentCwd !== undefined ? { parentCwd: opts.parentCwd } : {}),
2290
+ ...callerPlacementSeats(opts.parentCwd, opts.callerRoot),
2288
2291
  ...spawnAttribution,
2289
2292
  ...(await captureFloorSeatsNow()),
2290
2293
  ...(enrichedForwardS !== undefined ? { onForwardEvent: enrichedForwardS } : {}),
@@ -2610,7 +2613,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
2610
2613
  prior = null;
2611
2614
  }
2612
2615
  if (opts.store !== undefined && prior === null)
2613
- throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record is not in the run store under this scope, so its parks cannot be proven.`, { reason: "record_missing" });
2616
+ throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record is not in the run store under this scope (never recorded under it, reaped, or deleted with the session that started it), so its parks cannot be proven.`, { reason: "record_missing" });
2614
2617
  if (parkSeat !== undefined && prior !== null && prior.status === "running")
2615
2618
  throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run is still recorded as running; a run that could park must have finished before it is resumed (a crashed park-capable run is decided through the deployment's approval channel, not resumed).`, { reason: "record_not_terminal" });
2616
2619
  if (prior?.resumeAdmissionIncomplete === true)
@@ -1,3 +1,4 @@
1
+ import { type RetentionDeclaration } from "../../core/retention.js";
1
2
  import { type ExecutionOutcomeRecordWord } from "../../core/checkpoint-execution-record.js";
2
3
  import { type HolderJudge } from "../../core/checkpoint-generation.js";
3
4
  import { type Checkpoint, type PendingSteerEntry, type PendingSteerInput, type CheckpointFaultMode, type CheckpointStore, type CheckpointSummary, type CheckpointToken, type ReopenReason, type ResolveExpectation, type ResumeOutcome } from "../../core/checkpoint-store.js";
@@ -102,6 +103,9 @@ export interface FileCheckpointStoreOptions {
102
103
  } | undefined>;
103
104
  /** The judge of a resolve's claim holder ({@link HolderJudge}); with it the store declares `fence = { holder: true }`. */
104
105
  holderIsCurrent?: HolderJudge;
106
+ /** The store's managed-retention declaration ({@link import("../../core/checkpoint-store.js").CheckpointStore.retention}), stated by
107
+ * the party that runs the sweep; default `"none"`, a third word refused (`config.retention_capability`). */
108
+ retention?: RetentionDeclaration;
105
109
  }
106
110
  /**
107
111
  * Every event kind this reader understands — the ledger's CLOSED SET, exported so a program that reads a `checkpoints.jsonl` itself judges
@@ -153,6 +157,8 @@ export declare class FileCheckpointStore implements CheckpointStore {
153
157
  * directory's writer fence and refuses a second OS process by name (see the class header). Serving
154
158
  * many writers at once remains Pg/TiDB's job — this refuses the second one, it does not coordinate it. */
155
159
  readonly durability: "durable";
160
+ /** {@link FileCheckpointStoreOptions.retention}, as read at construction. */
161
+ readonly retention: RetentionDeclaration;
156
162
  /** Honest declaration on the fidelity axis: the ledger is JSONL, so what this backend holds is the JSON
157
163
  * PROJECTION of the row — a `Date` reads as its ISO string, a `Map`/`Set` as `{}`, `NaN` as `null`, an
158
164
  * `undefined`-valued key not at all — before a restart and after it alike (the live map is filled from the
@@ -2,13 +2,14 @@ import { join } from "node:path";
2
2
  import { assertAdoptionBootGate } from "./adoption/marker.js";
3
3
  import { memberPresent, optionKeys, receiveOptions } from "../../core/own-property-receipt.js";
4
4
  import { readLedgerTuning } from "./ledger-tuning.js";
5
+ import { readRetentionDeclaration } from "../../core/retention.js";
5
6
  import { checkpointExecutionRecorded, executionRecordDisposition, ExecutionOutcomeConflictError, } from "../../core/checkpoint-execution-record.js";
6
7
  import { checkpointHolderMatches, checkpointOccMatches, checkpointRevOf } from "../../core/checkpoint-generation.js";
7
8
  import { appendPendingSteer, CheckpointError, checkpointRowMatches, encodeAtFidelity, summarizeStoredCheckpoint, validatePendingSteer, winnerFromOutcome, } from "../../core/checkpoint-store.js";
8
9
  import { checkpointDeadlinePassed, deleteSessionRowsAtStart, readCheckpointOverdueQuery, readCheckpointSessionQuery, selectOverduePage, selectSessionPage, } from "../../core/checkpoint-queries.js";
9
10
  import { readLedgerSettled, SharedLedgerTable } from "./shared-ledger.js";
10
11
  import { guardCorruptSink } from "./corrupt-read-sink.js";
11
- const FILE_CHECKPOINT_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, fsync: 0, compactEvery: 0, sessionHeadOf: 0, holderIsCurrent: 0 });
12
+ const FILE_CHECKPOINT_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, fsync: 0, compactEvery: 0, sessionHeadOf: 0, holderIsCurrent: 0, retention: 0 });
12
13
  export const CHECKPOINT_LEDGER_EVENT_KINDS = Object.freeze(["put", "resolve", "reopen", "execution", "expire", "delete", "steer_append"]);
13
14
  const KNOWN_CHECKPOINT_LEDGER_EVENTS = new Set(CHECKPOINT_LEDGER_EVENT_KINDS);
14
15
  function applyCheckpointEvent(cps, ev) {
@@ -93,6 +94,7 @@ export function readCheckpointLedger(root, opts = {}) {
93
94
  }
94
95
  export class FileCheckpointStore {
95
96
  durability = "durable";
97
+ retention;
96
98
  fidelity = "json";
97
99
  execution = { outcome: true };
98
100
  holderIsCurrent;
@@ -109,6 +111,7 @@ export class FileCheckpointStore {
109
111
  ledgerPath;
110
112
  constructor(root, options) {
111
113
  const opts = receiveOptions(options, "FileCheckpointStore", FILE_CHECKPOINT_STORE_OPTION_KEYS);
114
+ this.retention = readRetentionDeclaration("FileCheckpointStore.retention", opts.retention);
112
115
  assertAdoptionBootGate(root, "FileCheckpointStore");
113
116
  const tuning = readLedgerTuning(opts, "FileCheckpointStore", "FileCheckpointStore options");
114
117
  this.fsyncEnabled = tuning.fsync;
@@ -118,6 +118,10 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
118
118
  * and a capture by an entry id, and one map holding both would be a key space where two unrelated
119
119
  * vocabularies have to promise never to spell the same string. */
120
120
  private readonly activeImports;
121
+ /** scope → how many of the verbs that write its history (`trackEdit`, `annulTrack`, `snapshot`, `importHistory`) are running in
122
+ * this store, counted from the call to its settle — before any await, so a write parked at its first read is counted. The two
123
+ * maps above answer which journals lease blobs; this answers whether `deleteBySession` may erase the scope now. */
124
+ private readonly writers;
121
125
  /**
122
126
  * The CONSUMED-ID ledger's in-process view — a CACHE over `scopes/<scope>/reaped.log`, not the
123
127
  * record itself (design/381 slice 3, closing the residual slice 2 registered here by name).
@@ -308,11 +312,15 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
308
312
  private boundaryOrderOf;
309
313
  /** Publish a blob write-ONCE (EEXIST = the identical bytes are already stored — dedup no-op). */
310
314
  private putBlob;
315
+ /** Run one history write of `scope` counted in {@link writers}. */
316
+ private writing;
311
317
  trackEdit(scope: string, absPath: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryTrackResult>;
318
+ private trackEditCounted;
312
319
  annulTrack(scope: string, absPath: string, root: string, verify?: {
313
320
  env: ExecutionEnv;
314
321
  signal?: AbortSignal;
315
322
  }): Promise<FileHistoryResult>;
323
+ private annulTrackCounted;
316
324
  /**
317
325
  * Is this scope free of history RIGHT NOW? Synchronous on purpose (adversarial round 1): the
318
326
  * empty-target law is only sound if the observation and the publish happen with no await between
@@ -342,10 +350,12 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
342
350
  * unreadable ≠ empty (a file gone since the listing cannot be judged either). ENOENT is no boundary yet. */
343
351
  private listBoundaryIds;
344
352
  snapshot(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryResult>;
353
+ private snapshotCounted;
345
354
  restore(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryRestoreResult>;
346
355
  canRestore(scope: string, entryId: string): Promise<boolean>;
347
356
  diffStats(scope: string, entryId: string, env: ExecutionEnv, root: string): Promise<FileHistoryDiffStats | null>;
348
357
  reap(scope: string, keepEntryIds: string[]): Promise<number>;
358
+ deleteBySession(scope: string): Promise<number>;
349
359
  /**
350
360
  * Blob GC across EVERY scope — FAIL-SAFE by construction: build the COMPLETE live set or keep
351
361
  * every blob. An incomplete live set (a swallowed scan error) would delete still-live bytes, so
@@ -354,11 +364,14 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
354
364
  * await; the live set additionally unions the staging journals of THIS process's in-flight
355
365
  * attempts (bytes published but not yet chained), while every OTHER journal is dead-attempt
356
366
  * residue: it is removed here, and the blobs it was protecting become collectable in this pass.
367
+ * Answers why it did not collect every unreferenced blob (undefined = it did): `reap` has no error
368
+ * channel and discards it; `deleteBySession` throws it.
357
369
  */
358
370
  private collectBlobs;
359
371
  adoptScope(fromScope: string, toScope: string): Promise<FileHistoryResult>;
360
372
  exportHistory(scope: string): Promise<FileHistoryExportResult>;
361
373
  importHistory(scope: string, data: FileHistoryExport, srcGetBlob: (hash: string) => Promise<Uint8Array | undefined>): Promise<FileHistoryResult>;
374
+ private importHistoryCounted;
362
375
  /** The import's body, so EVERY exit (typed refusal, thrown fault, success) passes one `finally`
363
376
  * that releases the journal + lease — an early return used to leak both, and a leaked lease is
364
377
  * permanent liveness for blobs nothing references (adversarial round 2). */
@@ -134,6 +134,7 @@ export class FileFileHistoryStore {
134
134
  spentAttempts = new Map();
135
135
  activeCaptures = new Map();
136
136
  activeImports = new Map();
137
+ writers = new Map();
137
138
  reapedCache = new Map();
138
139
  boundaryKeep;
139
140
  lastCommittedAt = 0;
@@ -405,7 +406,23 @@ export class FileFileHistoryStore {
405
406
  throw err;
406
407
  }
407
408
  }
408
- async trackEdit(scope, absPath, env, root, signal) {
409
+ async writing(scope, write) {
410
+ this.writers.set(scope, (this.writers.get(scope) ?? 0) + 1);
411
+ try {
412
+ return await write();
413
+ }
414
+ finally {
415
+ const left = (this.writers.get(scope) ?? 1) - 1;
416
+ if (left === 0)
417
+ this.writers.delete(scope);
418
+ else
419
+ this.writers.set(scope, left);
420
+ }
421
+ }
422
+ trackEdit(scope, absPath, env, root, signal) {
423
+ return this.writing(scope, () => this.trackEditCounted(scope, absPath, env, root, signal));
424
+ }
425
+ async trackEditCounted(scope, absPath, env, root, signal) {
409
426
  try {
410
427
  const { key, kind, family } = describeTrackKey(root, absPath);
411
428
  const before = this.readTrackedState(scope);
@@ -456,7 +473,10 @@ export class FileFileHistoryStore {
456
473
  return { ok: false, error: { code: "track_failed", message: `first-touch record for ${absPath} could not be persisted: ${thrownText(err)}`, ...caughtFault(err) } };
457
474
  }
458
475
  }
459
- async annulTrack(scope, absPath, root, verify) {
476
+ annulTrack(scope, absPath, root, verify) {
477
+ return this.writing(scope, () => this.annulTrackCounted(scope, absPath, root, verify));
478
+ }
479
+ async annulTrackCounted(scope, absPath, root, verify) {
460
480
  try {
461
481
  const key = trackKeyOf(root, absPath);
462
482
  const state = this.readTrackedState(scope);
@@ -573,7 +593,10 @@ export class FileFileHistoryStore {
573
593
  return ids;
574
594
  return { fault: worstFault(faults), what: `boundaries that cannot be used (${unusable.slice(0, 3).map((i) => JSON.stringify(i)).join(", ")}${unusable.length > 3 ? ", …" : ""})` };
575
595
  }
576
- async snapshot(scope, entryId, env, root, signal) {
596
+ snapshot(scope, entryId, env, root, signal) {
597
+ return this.writing(scope, () => this.snapshotCounted(scope, entryId, env, root, signal));
598
+ }
599
+ async snapshotCounted(scope, entryId, env, root, signal) {
577
600
  const bpath = this.tryBoundaryPath(scope, entryId);
578
601
  if (bpath === null)
579
602
  return { ok: false, error: { code: "snapshot_failed", message: `unsafe boundary key ${JSON.stringify(entryId)}` } };
@@ -913,6 +936,40 @@ export class FileFileHistoryStore {
913
936
  this.collectBlobs();
914
937
  return removed;
915
938
  }
939
+ async deleteBySession(scope) {
940
+ if (this.writers.has(scope)) {
941
+ throw Object.assign(new Error(`file history scope "${scope}" has a write in flight in this store (a capture, a first-touch record, a retraction or an import) — a session's history is erased when no leg of it runs`), { code: "conflict" });
942
+ }
943
+ const sdir = this.scopeDir(scope);
944
+ const ledger = this.reapedLogPath(scope);
945
+ let removed = 0;
946
+ if (existsSync(sdir)) {
947
+ try {
948
+ removed += readdirSync(this.boundaryDir(scope)).filter((f) => f.endsWith(".json")).length;
949
+ }
950
+ catch (err) {
951
+ if (err.code !== "ENOENT")
952
+ removed += 1;
953
+ }
954
+ const read = this.readTrackedState(scope);
955
+ if (read.corrupt)
956
+ removed += 1;
957
+ else
958
+ for (const rec of read.tracked.values())
959
+ removed += rec.versions.length;
960
+ rmSync(sdir, { recursive: true, force: true });
961
+ }
962
+ rmSync(ledger, { force: true });
963
+ this.reapedCache.delete(scope);
964
+ this.spentAttempts.delete(scope);
965
+ this.seededScopes.delete(scope);
966
+ this.activeCaptures.delete(scope);
967
+ this.activeImports.delete(scope);
968
+ const kept = this.collectBlobs();
969
+ if (kept !== undefined)
970
+ throw new Error(`file history scope "${scope}" is erased but its blobs are not: ${kept}`);
971
+ return removed;
972
+ }
916
973
  collectBlobs() {
917
974
  const live = new Set();
918
975
  let complete = true;
@@ -922,9 +979,9 @@ export class FileFileHistoryStore {
922
979
  }
923
980
  catch (err) {
924
981
  if (err.code === "ENOENT")
925
- return;
982
+ return undefined;
926
983
  this.disclose(this.scopesDir, `scope root unreadable (${err.code ?? "unknown"}) — blob GC aborted, every blob kept`);
927
- return;
984
+ return "the scope root could not be read, so every blob was kept";
928
985
  }
929
986
  const liveJournals = new Set([...[...this.activeCaptures.values()].flatMap((m) => [...m.values()]), ...[...this.activeImports.values()].flatMap((set) => [...set])]);
930
987
  for (const name of scopeDirs) {
@@ -1009,20 +1066,22 @@ export class FileFileHistoryStore {
1009
1066
  break;
1010
1067
  }
1011
1068
  if (!complete)
1012
- return;
1069
+ return "a scope's history or staging could not be judged during the live-set scan, so every blob was kept";
1013
1070
  let blobs;
1014
1071
  try {
1015
1072
  blobs = readdirSync(this.blobsDir);
1016
1073
  }
1017
1074
  catch (err) {
1018
- if (err.code !== "ENOENT") {
1019
- this.disclose(this.blobsDir, `blob directory unreadable (${err.code ?? "unknown"}) — blob GC skipped, every blob kept`);
1020
- }
1021
- return;
1075
+ if (err.code === "ENOENT")
1076
+ return undefined;
1077
+ this.disclose(this.blobsDir, `blob directory unreadable (${err.code ?? "unknown"}) — blob GC skipped, every blob kept`);
1078
+ return "the blob directory could not be read, so every blob was kept";
1022
1079
  }
1080
+ let stuck = 0;
1023
1081
  for (const blob of blobs)
1024
- if (!live.has(blob))
1025
- safeRm(join(this.blobsDir, blob));
1082
+ if (!live.has(blob) && !safeRm(join(this.blobsDir, blob)))
1083
+ stuck++;
1084
+ return stuck === 0 ? undefined : `${stuck} unreferenced blob(s) could not be removed`;
1026
1085
  }
1027
1086
  async adoptScope(fromScope, toScope) {
1028
1087
  try {
@@ -1145,7 +1204,10 @@ export class FileFileHistoryStore {
1145
1204
  };
1146
1205
  return { ok: true, history };
1147
1206
  }
1148
- async importHistory(scope, data, srcGetBlob) {
1207
+ importHistory(scope, data, srcGetBlob) {
1208
+ return this.writing(scope, () => this.importHistoryCounted(scope, data, srcGetBlob));
1209
+ }
1210
+ async importHistoryCounted(scope, data, srcGetBlob) {
1149
1211
  try {
1150
1212
  const shaped = validateFileHistoryExport(data);
1151
1213
  if (!shaped.ok)
@@ -15,6 +15,7 @@ import { type SessionPolicyStore } from "../../core/session-policy-store.js";
15
15
  import type { WorkflowJournalStore } from "../../core/workflow-journal-store.js";
16
16
  import type { UsageWindowStore } from "../../core/usage-window-store.js";
17
17
  import type { EngineStorageBackend } from "../../core/engine-storage-backend.js";
18
+ import { type RetentionDeclaration } from "../../core/retention.js";
18
19
  export { FileCheckpointStore, CHECKPOINT_LEDGER_EVENT_KINDS, readCheckpointLedger, type CheckpointLedgerEventKind, type CheckpointLedgerReading, type FileCheckpointStoreOptions, type ReadCheckpointLedgerOptions, } from "./checkpoint-store.js";
19
20
  export { FileMemoryStore } from "./memory-store.js";
20
21
  export { FileSessionRepo, type FileSessionRepoOptions } from "./session-store.js";
@@ -70,7 +71,16 @@ export interface FileStorageBackendOptions {
70
71
  /** Checkpoint store tuning (fsync cadence for `put`/`setPendingSteer`, ledger compaction threshold, the holder judge). The
71
72
  * corrupt-read sink and the session head read are the backend's own — the sink is {@link FileStorageBackendOptions.onCorruptRead}
72
73
  * (one failure grammar, one sink) and the head read is its session store's — so neither is accepted here. */
73
- checkpoint?: Omit<FileCheckpointStoreOptions, "onCorruptRead" | "sessionHeadOf">;
74
+ checkpoint?: Omit<FileCheckpointStoreOptions, "onCorruptRead" | "sessionHeadOf" | "retention">;
75
+ /**
76
+ * The managed-retention declaration of this backend's three declaring stores — {@link FileStorageBackend.sessionStore},
77
+ * {@link FileStorageBackend.checkpointStore} and {@link FileStorageBackend.toolResultStore} — stated by the party that runs the sweep
78
+ * (`"managed"`: an executor deletes their rows on schedule; default `"none"`; a third word refused, `config.retention_capability`).
79
+ * The backend carries no executor of its own: a deployment that says `"managed"` runs one over these stores (the legs it calls are
80
+ * `RETENTION_CASCADE`'s) and hands it to `assertRetentionCapability` as `executor`, which refuses `"managed"` beside `executor: null`.
81
+ * One word for the three, because one sweep covers them; it is not a per-store choice, so the `checkpoint` record does not take it.
82
+ */
83
+ retention?: RetentionDeclaration;
74
84
  /**
75
85
  * design/381 §片2 — file-history tuning, today just the boundary RETENTION bound (omitted ⇒ the
76
86
  * engine default; `{ retention: { keep: "unbounded" } }` hands the GC schedule to the deployment).
@@ -16,8 +16,9 @@ import { FileMailboxStore } from "./mailbox-store.js";
16
16
  import { FileRosterStore } from "../../agents/roster-store.js";
17
17
  import { FileFileHistoryStore } from "./file-history-store.js";
18
18
  import { readMountedToolNames } from "../../core/session-policy-store.js";
19
- import { optionKeys, receiveMembers, receiveOptions, refuseProxy, refuseStrayMembers } from "../../core/own-property-receipt.js";
19
+ import { optionKeys, receiveMembers, receiveOptions, refuseStrayMembers } from "../../core/own-property-receipt.js";
20
20
  import { receiveFileHistoryRetention } from "../../core/file-history-retention.js";
21
+ import { readRetentionDeclaration } from "../../core/retention.js";
21
22
  function nestedOptions(value, member, keys) {
22
23
  return value === undefined ? undefined : receiveMembers(value, { subject: `FileStorageBackendOptions.${member}`, unit: "option", moment: "at new FileStorageBackend" }, keys);
23
24
  }
@@ -36,7 +37,7 @@ export { atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog
36
37
  export { processFingerprint, isProcessLive } from "./fs-atomic.js";
37
38
  export { AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootAdoptionFile, ROOT_ADOPTION_FILE, } from "./adoption/marker.js";
38
39
  export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, } from "./adoption/adopt.js";
39
- const FILE_STORAGE_BACKEND_OPTION_KEYS = optionKeys()({ root: 0, utilityGate: 0, evict: 0, checkpoint: 0, fileHistory: 0, sessionPolicy: 0, embedder: 0, onCorruptRead: 0, sessions: 0 });
40
+ const FILE_STORAGE_BACKEND_OPTION_KEYS = optionKeys()({ root: 0, utilityGate: 0, evict: 0, checkpoint: 0, retention: 0, fileHistory: 0, sessionPolicy: 0, embedder: 0, onCorruptRead: 0, sessions: 0 });
40
41
  const NESTED_FILE_HISTORY_OPTION_KEYS = optionKeys()({ retention: 0 });
41
42
  const NESTED_SESSION_POLICY_OPTION_KEYS = optionKeys()({ mountedToolNames: 0 });
42
43
  const NESTED_CHECKPOINT_OPTION_KEYS = optionKeys()({ fsync: 0, compactEvery: 0, holderIsCurrent: 0 });
@@ -62,13 +63,8 @@ export class FileStorageBackend {
62
63
  fileSessions;
63
64
  fileWorkflowJournal;
64
65
  constructor(options) {
65
- if (options !== undefined && options !== null && typeof options === "object") {
66
- refuseProxy(options, { subject: "FileStorageBackend options", unit: "option", moment: "at new FileStorageBackend" });
67
- if (Object.hasOwn(options, "retention")) {
68
- throw Object.assign(new Error(`FileStorageBackend runs no retention executor, so its options take no \`retention\` word: its stores declare "none".`), { code: "config.retention_capability" });
69
- }
70
- }
71
66
  const opts = receiveOptions(options, "FileStorageBackend", FILE_STORAGE_BACKEND_OPTION_KEYS);
67
+ const retention = readRetentionDeclaration("FileStorageBackendOptions.retention", opts.retention);
72
68
  const checkpointRecord = nestedOptions(opts.checkpoint, "checkpoint", NESTED_CHECKPOINT_OPTION_KEYS);
73
69
  const checkpointOptions = checkpointRecord === undefined ? undefined : { ...checkpointRecord, ...readLedgerTuning(checkpointRecord, "FileCheckpointStore", "FileStorageBackendOptions.checkpoint") };
74
70
  const sessionPolicyRecord = nestedOptions(opts.sessionPolicy, "sessionPolicy", NESTED_SESSION_POLICY_OPTION_KEYS);
@@ -86,16 +82,16 @@ export class FileStorageBackend {
86
82
  const corruptRead = opts.onCorruptRead !== undefined ? { onCorruptRead: opts.onCorruptRead } : undefined;
87
83
  const repo = new FileSessionRepo(this.root, corruptRead);
88
84
  this.fileSessions = repo;
89
- this.ttl = new TtlSessionStore({ repo, evict: opts.evict ?? "forget", durability: "durable", placements: { subagent: { durability: "durable" } }, ...(opts.sessions !== undefined ? { hooks: opts.sessions } : {}) });
85
+ this.ttl = new TtlSessionStore({ repo, evict: opts.evict ?? "forget", durability: "durable", placements: { subagent: { durability: "durable" } }, retention, ...(opts.sessions !== undefined ? { hooks: opts.sessions } : {}) });
90
86
  this.sessionStore = this.ttl;
91
87
  const sessionHeadOf = this.ttl.headOf;
92
- this.fileCheckpoints = new FileCheckpointStore(this.root, { ...checkpointOptions, ...corruptRead, ...(sessionHeadOf !== undefined ? { sessionHeadOf } : {}) });
88
+ this.fileCheckpoints = new FileCheckpointStore(this.root, { ...checkpointOptions, ...corruptRead, retention, ...(sessionHeadOf !== undefined ? { sessionHeadOf } : {}) });
93
89
  built.push(() => this.fileCheckpoints.close());
94
90
  this.checkpointStore = this.fileCheckpoints;
95
91
  this.fileMemory = new FileMemoryStore(this.root, opts.embedder ? { embedder: opts.embedder } : {});
96
92
  built.push(() => this.fileMemory.close());
97
93
  this.memoryStore = guardedMemoryStore(this.fileMemory, opts.utilityGate);
98
- this.toolResultStore = new FileToolResultStore(this.root, corruptRead);
94
+ this.toolResultStore = new FileToolResultStore(this.root, { ...corruptRead, retention });
99
95
  this.sessionPolicyStore = new FileSessionPolicyStore(this.root, { ...sessionPolicyOptions, ...corruptRead });
100
96
  this.fileWorkflowJournal = new FileWorkflowJournalStore(this.root, true, corruptRead);
101
97
  built.push(() => this.fileWorkflowJournal.dispose());
@@ -251,6 +251,29 @@ export declare class FileDurableRulePartitionProvider implements DurableRulePart
251
251
  * into a retired bucket. A corrupt marker throws (fail-closed) rather than guessing an owner.
252
252
  */
253
253
  forLocalOwner(): DurableRulePartition;
254
+ /**
255
+ * The owners this directory can NAME that hold a bucket here, and how many buckets it cannot name — the one listing a host
256
+ * that must visit every bucket (a one-time migration over the rules of every owner) reads, so a bucket no record points at is
257
+ * not skipped. Names only: no rule, tombstone or revision is read, and no bucket file is opened.
258
+ *
259
+ * A bucket's file is named by a one-way digest of its owner (`principalRuleFileName`) and holds no owner name, so the
260
+ * directory names an owner only by what it records: `local-owner` when the local-owner bucket file is present, and the principals
261
+ * the adoption marker names (the adopted principal, and a principal source) when their bucket file is present. After an adoption
262
+ * the renamed bucket is the adopted principal's, so it is listed under that name whether or not any approval record ever named it.
263
+ * Every other digest-named bucket file is counted in `unnamedBuckets` — present, unreadable as to whose, and never silently
264
+ * dropped. A host reads `owners` through {@link forPrincipal} / {@link forLocalOwner} like any owner it knows; `unnamedBuckets > 0`
265
+ * says its census of owners is incomplete by that many, not that they are empty.
266
+ *
267
+ * Reading takes no lock and writes nothing. A directory this engine refuses to use refuses with
268
+ * {@link PERMISSION_RULES_DAMAGED_BUCKET_CODE}, as the read faces refuse it; a listing that failed to read refuses with
269
+ * {@link PERMISSION_RULES_UNREADABLE_BUCKET_CODE} and the system error's name in `errno`; an adoption marker that does not read
270
+ * refuses as {@link forPrincipal} refuses it (the marker is the truth of whose bucket is whose, so a listing never guesses
271
+ * past it). An absent directory lists nothing.
272
+ */
273
+ listBucketOwners(): {
274
+ readonly owners: readonly RuleOwner[];
275
+ readonly unnamedBuckets: number;
276
+ };
254
277
  /** Release the writer lock. A long-lived deployment holds it for its lifetime; a test or a short-lived
255
278
  * tool releases so the next holder is not told a live process owns the directory. */
256
279
  dispose(): void;