@sema-agent/core 7.61.0 → 7.63.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 (298) hide show
  1. package/CHANGELOG.md +840 -0
  2. package/dist/agents/cascade.d.ts +11 -3
  3. package/dist/agents/cascade.js +1 -1
  4. package/dist/agents/peer-held-queue.d.ts +27 -4
  5. package/dist/agents/peer-held-queue.js +81 -36
  6. package/dist/agents/peer-session-drain.js +13 -3
  7. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  8. package/dist/agents/subagent-transcript-placement.js +14 -0
  9. package/dist/agents/subagent.d.ts +6 -1
  10. package/dist/agents/subagent.js +143 -58
  11. package/dist/agents/suspend-guard.d.ts +38 -16
  12. package/dist/agents/suspend-guard.js +9 -4
  13. package/dist/agents/verify.js +4 -3
  14. package/dist/brain/route-adjudicator.js +9 -4
  15. package/dist/core/approval-object.js +1 -1
  16. package/dist/core/arg-summary.js +1 -1
  17. package/dist/core/ask-question.d.ts +2 -2
  18. package/dist/core/canonical-json.d.ts +23 -13
  19. package/dist/core/canonical-json.js +4 -4
  20. package/dist/core/checkpoint-features.d.ts +722 -0
  21. package/dist/core/checkpoint-features.js +98 -0
  22. package/dist/core/checkpoint-queries.d.ts +47 -4
  23. package/dist/core/checkpoint-queries.js +36 -16
  24. package/dist/core/checkpoint-requirements.d.ts +12 -5
  25. package/dist/core/checkpoint-requirements.js +11 -5
  26. package/dist/core/checkpoint-row-verdict.d.ts +110 -0
  27. package/dist/core/checkpoint-row-verdict.js +245 -0
  28. package/dist/core/checkpoint-store.d.ts +76 -753
  29. package/dist/core/checkpoint-store.js +83 -144
  30. package/dist/core/compliance.d.ts +6 -2
  31. package/dist/core/compliance.js +3 -3
  32. package/dist/core/engine-attestation.d.ts +1 -1
  33. package/dist/core/engine-notice.d.ts +38 -7
  34. package/dist/core/engine-notice.js +9 -2
  35. package/dist/core/gate-fold.js +2 -2
  36. package/dist/core/git-worktree-env.d.ts +62 -3
  37. package/dist/core/git-worktree-env.js +91 -30
  38. package/dist/core/governance-codes.d.ts +9 -3
  39. package/dist/core/governance-codes.js +16 -3
  40. package/dist/core/hooks.d.ts +13 -0
  41. package/dist/core/human-input-projection.d.ts +1 -0
  42. package/dist/core/human-input-projection.js +3 -0
  43. package/dist/core/image-admission.d.ts +1 -1
  44. package/dist/core/locked-config.d.ts +2 -2
  45. package/dist/core/mcp-host-seat.js +6 -1
  46. package/dist/core/memory-engine/consolidation-driver.d.ts +33 -18
  47. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  48. package/dist/core/memory-engine/consolidation.d.ts +73 -10
  49. package/dist/core/memory-engine/consolidation.js +167 -11
  50. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  51. package/dist/core/memory-engine/data-plane.js +11 -6
  52. package/dist/core/memory-engine/delegation-settlement.d.ts +37 -35
  53. package/dist/core/memory-engine/delegation-settlement.js +53 -59
  54. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  55. package/dist/core/memory-engine/dual-root.js +9 -5
  56. package/dist/core/memory-engine/engine.d.ts +98 -35
  57. package/dist/core/memory-engine/engine.js +477 -380
  58. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  59. package/dist/core/memory-engine/entry-scan.js +3 -0
  60. package/dist/core/memory-engine/file-backend.d.ts +29 -3
  61. package/dist/core/memory-engine/file-backend.js +66 -35
  62. package/dist/core/memory-engine/index.d.ts +7 -7
  63. package/dist/core/memory-engine/index.js +6 -6
  64. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  65. package/dist/core/memory-engine/landing-admission.js +3 -3
  66. package/dist/core/memory-engine/layout.d.ts +121 -45
  67. package/dist/core/memory-engine/layout.js +252 -102
  68. package/dist/core/memory-engine/memory-backend-contract.d.ts +19 -1
  69. package/dist/core/memory-engine/memory-backend-contract.js +320 -0
  70. package/dist/core/memory-engine/memory-deployment.d.ts +31 -8
  71. package/dist/core/memory-engine/memory-deployment.js +26 -12
  72. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  73. package/dist/core/memory-engine/scope-contract.js +68 -19
  74. package/dist/core/memory-engine/session-write-home.d.ts +3 -1
  75. package/dist/core/memory-engine/session-write-home.js +1 -1
  76. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  77. package/dist/core/memory-engine/sync-client.js +7 -0
  78. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  79. package/dist/core/memory-engine/sync-report.js +6 -2
  80. package/dist/core/memory-engine/tools.d.ts +2 -2
  81. package/dist/core/memory-engine/tools.js +10 -10
  82. package/dist/core/memory-engine/types.d.ts +118 -19
  83. package/dist/core/memory-engine/types.js +1 -0
  84. package/dist/core/memory-vector.d.ts +1 -1
  85. package/dist/core/memory.d.ts +10 -10
  86. package/dist/core/memory.js +15 -6
  87. package/dist/core/mode-policy.js +1 -1
  88. package/dist/core/mods/classic-events.d.ts +9 -1
  89. package/dist/core/mods/dollar.d.ts +32 -1
  90. package/dist/core/mods/dollar.js +13 -1
  91. package/dist/core/mods/kernel/events.d.ts +11 -3
  92. package/dist/core/mods/kernel/events.js +13 -10
  93. package/dist/core/mods/lifecycle-stations.d.ts +36 -4
  94. package/dist/core/mods/lifecycle-stations.js +44 -9
  95. package/dist/core/mods/session-append.d.ts +4 -1
  96. package/dist/core/mods/session-append.js +7 -0
  97. package/dist/core/mods/session-receive.js +12 -15
  98. package/dist/core/mods/stations.d.ts +70 -6
  99. package/dist/core/mods/stations.js +144 -1
  100. package/dist/core/own-property-receipt.d.ts +7 -0
  101. package/dist/core/own-property-receipt.js +3 -0
  102. package/dist/core/park-selfcheck.js +2 -2
  103. package/dist/core/pause-registry.d.ts +2 -0
  104. package/dist/core/pause-registry.js +3 -0
  105. package/dist/core/permission-rule-consent.d.ts +10 -3
  106. package/dist/core/permission-rule-consent.js +37 -24
  107. package/dist/core/permission-rule-store.d.ts +35 -1
  108. package/dist/core/permission-rule-store.js +27 -8
  109. package/dist/core/read-only-shell.js +3 -2
  110. package/dist/core/read-root-candidate.js +1 -1
  111. package/dist/core/redaction-marks.d.ts +8 -0
  112. package/dist/core/redaction-marks.js +6 -0
  113. package/dist/core/remote-env.d.ts +12 -1
  114. package/dist/core/remote-env.js +3 -0
  115. package/dist/core/resume-startup-cause.d.ts +5 -4
  116. package/dist/core/runner/child-tree.d.ts +29 -3
  117. package/dist/core/runner/child-tree.js +39 -16
  118. package/dist/core/runner/compact-session.js +5 -2
  119. package/dist/core/runner/contracts.d.ts +36 -17
  120. package/dist/core/runner/delegation-owner.d.ts +43 -0
  121. package/dist/core/runner/delegation-owner.js +59 -0
  122. package/dist/core/runner/gate-exit.js +2 -2
  123. package/dist/core/runner/inherited-ask-grants.js +1 -1
  124. package/dist/core/runner/lineage-reroot-view.d.ts +56 -0
  125. package/dist/core/runner/lineage-reroot-view.js +108 -0
  126. package/dist/core/runner/memory-consolidation-driver.d.ts +6 -3
  127. package/dist/core/runner/memory-consolidation-driver.js +4 -4
  128. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  129. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  130. package/dist/core/runner/permission-rule-lanes.d.ts +2 -1
  131. package/dist/core/runner/permission-rule-lanes.js +2 -2
  132. package/dist/core/runner/person-path-rows.d.ts +23 -3
  133. package/dist/core/runner/person-path-rows.js +31 -4
  134. package/dist/core/runner/placement-fence.d.ts +12 -0
  135. package/dist/core/runner/placement-fence.js +20 -6
  136. package/dist/core/runner/prepare-acquire-reconcile.d.ts +4 -1
  137. package/dist/core/runner/prepare-acquire-reconcile.js +7 -2
  138. package/dist/core/runner/prepare-ask-lane.js +2 -2
  139. package/dist/core/runner/prepare-caps-and-workflow.d.ts +5 -1
  140. package/dist/core/runner/prepare-caps-and-workflow.js +6 -3
  141. package/dist/core/runner/prepare-config-doors.d.ts +6 -6
  142. package/dist/core/runner/prepare-config-doors.js +3 -4
  143. package/dist/core/runner/prepare-execution-env.js +17 -6
  144. package/dist/core/runner/prepare-hands-readface.d.ts +3 -2
  145. package/dist/core/runner/prepare-hands-readface.js +32 -10
  146. package/dist/core/runner/prepare-inherited-gate.d.ts +12 -8
  147. package/dist/core/runner/prepare-inherited-gate.js +14 -6
  148. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  149. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  150. package/dist/core/runner/prepare-memory.d.ts +3 -2
  151. package/dist/core/runner/prepare-memory.js +28 -20
  152. package/dist/core/runner/prepare-park-ask.js +4 -3
  153. package/dist/core/runner/prepare-task.js +22 -16
  154. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  155. package/dist/core/runner/resume-admission.d.ts +3 -3
  156. package/dist/core/runner/resume-admission.js +6 -3
  157. package/dist/core/runner/resume-apply.d.ts +4 -0
  158. package/dist/core/runner/resume-apply.js +11 -4
  159. package/dist/core/runner/resume-checkpoint-screen.d.ts +9 -0
  160. package/dist/core/runner/resume-checkpoint-screen.js +4 -84
  161. package/dist/core/runner/run-git-lane.d.ts +2 -0
  162. package/dist/core/runner/run-git-lane.js +4 -1
  163. package/dist/core/runner/run-harness-handlers.d.ts +2 -0
  164. package/dist/core/runner/run-harness-handlers.js +3 -2
  165. package/dist/core/runner/run-leg.js +25 -8
  166. package/dist/core/runner/run-settle-and-teardown.js +6 -4
  167. package/dist/core/runner/run-stop-and-final-verify.js +2 -1
  168. package/dist/core/runner/run-turn-boundary.js +7 -4
  169. package/dist/core/runner/runtask.js +6 -6
  170. package/dist/core/runner/steering-preview.d.ts +9 -0
  171. package/dist/core/runner/steering-preview.js +5 -0
  172. package/dist/core/runner/stream-steer-verb.js +8 -0
  173. package/dist/core/runner/terminal-account.js +1 -1
  174. package/dist/core/runner/tool-face-overlay.js +2 -0
  175. package/dist/core/runner/turn-attachments.d.ts +5 -0
  176. package/dist/core/runner/turn-attachments.js +1 -1
  177. package/dist/core/runner-deps.d.ts +8 -4
  178. package/dist/core/secret-env.d.ts +9 -6
  179. package/dist/core/secret-env.js +41 -22
  180. package/dist/core/session-checkout.d.ts +108 -0
  181. package/dist/core/session-checkout.js +485 -0
  182. package/dist/core/session-store.d.ts +13 -5
  183. package/dist/core/session-store.js +28 -4
  184. package/dist/core/session.d.ts +29 -5
  185. package/dist/core/session.js +3 -0
  186. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +6 -12
  187. package/dist/core/store-contracts/checkpoint-store-contract.js +73 -6
  188. package/dist/core/store-contracts/session-store-contract.js +61 -8
  189. package/dist/core/task-event.d.ts +28 -1
  190. package/dist/core/task-notification.d.ts +9 -1
  191. package/dist/core/task-notification.js +8 -1
  192. package/dist/core/task-registry-agent.d.ts +40 -8
  193. package/dist/core/task-registry-agent.js +57 -24
  194. package/dist/core/task-registry-shared.d.ts +33 -11
  195. package/dist/core/task-registry-workflow.js +4 -3
  196. package/dist/core/task-registry.d.ts +27 -10
  197. package/dist/core/task-registry.js +19 -13
  198. package/dist/core/task-result.d.ts +5 -5
  199. package/dist/core/task-spec-members.js +1 -1
  200. package/dist/core/task-spec.d.ts +21 -1
  201. package/dist/core/terminal-cause.d.ts +6 -6
  202. package/dist/core/tool-face.d.ts +6 -2
  203. package/dist/core/tool-face.js +1 -1
  204. package/dist/core/tool-policy.d.ts +16 -13
  205. package/dist/core/tool-policy.js +11 -10
  206. package/dist/core/tool-roster.d.ts +4 -4
  207. package/dist/core/tool-spec.d.ts +42 -19
  208. package/dist/core/types.d.ts +2 -2
  209. package/dist/core/types.js +1 -1
  210. package/dist/core/untrusted-egress.d.ts +15 -4
  211. package/dist/core/untrusted-egress.js +23 -22
  212. package/dist/core/workspace-snapshot.d.ts +3 -1
  213. package/dist/core/workspace-snapshot.js +1 -0
  214. package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
  215. package/dist/engine/execution-env/node-execution-env.js +12 -5
  216. package/dist/engine/harness/types.d.ts +77 -1
  217. package/dist/engine/harness/types.js +108 -0
  218. package/dist/engine/session/import-validate.js +6 -1
  219. package/dist/engine/session/parent-chain-guard.d.ts +3 -3
  220. package/dist/engine/session/parent-chain-guard.js +1 -1
  221. package/dist/engine/session/path-to-root.d.ts +18 -3
  222. package/dist/engine/session/path-to-root.js +15 -1
  223. package/dist/engine/session/repo-utils.d.ts +12 -1
  224. package/dist/engine/session/repo-utils.js +41 -0
  225. package/dist/engine/session/session.d.ts +24 -1
  226. package/dist/engine/session/session.js +46 -2
  227. package/dist/engine/session/storage-base.d.ts +20 -0
  228. package/dist/engine/session/storage-base.js +28 -9
  229. package/dist/index.d.ts +16 -12
  230. package/dist/index.js +11 -8
  231. package/dist/internal/harness-types.d.ts +1 -1
  232. package/dist/internal/harness.d.ts +4 -3
  233. package/dist/internal/harness.js +3 -2
  234. package/dist/orchestration/run-workflow-tool.d.ts +7 -1
  235. package/dist/orchestration/run-workflow-tool.js +28 -11
  236. package/dist/orchestration/workflow-governance.d.ts +1 -1
  237. package/dist/orchestration/workflow.d.ts +6 -0
  238. package/dist/orchestration/workflow.js +5 -8
  239. package/dist/stores/file/checkpoint-store.d.ts +2 -0
  240. package/dist/stores/file/checkpoint-store.js +7 -6
  241. package/dist/stores/file/fs-atomic.d.ts +0 -22
  242. package/dist/stores/file/fs-atomic.js +0 -17
  243. package/dist/stores/file/index.d.ts +2 -9
  244. package/dist/stores/file/index.js +2 -4
  245. package/dist/stores/file/session-store.d.ts +13 -7
  246. package/dist/stores/file/session-store.js +42 -18
  247. package/dist/tools/fs/bash-program-position.d.ts +3 -2
  248. package/dist/tools/fs/bash-program-position.js +10 -10
  249. package/dist/tools/fs/program-read-model.d.ts +34 -10
  250. package/dist/tools/fs/program-read-model.js +37 -7
  251. package/dist/tools/fs/program-read-model.rows.js +13 -2
  252. package/dist/tools/fs/read-deny.d.ts +13 -1
  253. package/dist/tools/fs/read-deny.js +10 -2
  254. package/dist/tools/fs/removal-targets.js +5 -5
  255. package/dist/tools/fs/safety.d.ts +2 -0
  256. package/dist/tools/fs/safety.js +1 -1
  257. package/dist/tools/fs/shell-read-argv.d.ts +11 -2
  258. package/dist/tools/fs/shell-read-argv.js +45 -29
  259. package/dist/tools/fs/shell-read-bindings.d.ts +20 -2
  260. package/dist/tools/fs/shell-read-bindings.js +153 -69
  261. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  262. package/dist/tools/fs/shell-read-brace.js +79 -0
  263. package/dist/tools/fs/shell-read-check.js +29 -11
  264. package/dist/tools/fs/shell-read-establish.js +43 -22
  265. package/dist/tools/fs/shell-read-functions.js +2 -2
  266. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  267. package/dist/tools/fs/shell-read-judge.js +3 -3
  268. package/dist/tools/fs/shell-read-object-path.d.ts +59 -0
  269. package/dist/tools/fs/shell-read-object-path.js +119 -0
  270. package/dist/tools/fs/shell-read-plan.d.ts +18 -0
  271. package/dist/tools/fs/shell-read-plan.js +217 -104
  272. package/dist/tools/fs/shell-read-start.d.ts +76 -13
  273. package/dist/tools/fs/shell-read-start.js +97 -17
  274. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  275. package/dist/tools/fs/shell-read-word.js +9 -5
  276. package/dist/tools/fs/shell-read-workdir.d.ts +54 -14
  277. package/dist/tools/fs/shell-read-workdir.js +103 -19
  278. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  279. package/dist/tools/worktree.d.ts +3 -2
  280. package/dist/tools/worktree.js +7 -35
  281. package/package.json +3 -2
  282. package/test/export-surface.snapshot.json +93 -43
  283. package/wire-changes/core-stores-sql@7.62.0.json +30 -0
  284. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  285. package/wire-changes/core@7.62.0.json +2181 -0
  286. package/wire-changes/core@7.63.0.json +3523 -0
  287. package/wire-changes/mods-kernel@7.62.0.json +42 -0
  288. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  289. package/wire-changes/primitives@7.62.0.json +30 -0
  290. package/wire-changes/primitives@7.63.0.json +445 -0
  291. package/dist/core/consolidate-scope.d.ts +0 -93
  292. package/dist/core/consolidate-scope.js +0 -98
  293. package/dist/core/credential-vocabulary.d.ts +0 -176
  294. package/dist/core/credential-vocabulary.js +0 -190
  295. package/dist/core/redaction-passes.d.ts +0 -82
  296. package/dist/core/redaction-passes.js +0 -377
  297. package/dist/core/runner/memory-consolidation.d.ts +0 -109
  298. package/dist/core/runner/memory-consolidation.js +0 -251
@@ -33,6 +33,11 @@ export interface SessionPlacement {
33
33
  rootSessionId?: string;
34
34
  /** The durable agent row key (`a…`) — the store-side join key for orphan GC. */
35
35
  handle?: string;
36
+ /** The delegation tree's owner: the owner of the tree root's row as the root run read it, carried unchanged to every descendant
37
+ * (`null` = the root is anonymous). The placing write records exactly it in the row's owner cell — never in the tuple
38
+ * ({@link SessionPlacementRecord} has no owner); a re-open ignores it (first-write immutable). A placed FORK takes the tuple
39
+ * without it ({@link SessionStore.fork}: the fork's own owner argument is the row's owner). */
40
+ owner: string | null;
36
41
  }
37
42
  /**
38
43
  * One row of {@link SessionStore.listPlaced}. The row-store join key is the FULL `(scope, handle)`
@@ -207,7 +212,10 @@ export interface SessionStore<S extends SessionStoreSummary = SessionStoreSummar
207
212
  * placement argument) returns the same session and never rewrites the tuple;
208
213
  * 6. a placed id cannot be CLAIMED: a later claim-form acquire (no `requireExisting`, no
209
214
  * creation placement) of an existing placed id refuses loudly
210
- * (`SessionError("placement_refused")`) instead of attaching.
215
+ * (`SessionError("placement_refused")`) instead of attaching;
216
+ * 7. the placing write records exactly `placement.owner` in the row's owner cell (no owner of its own derived), and the store
217
+ * answers {@link headOf} for every session it holds — with the row's `incarnation`, the same token the acquired session's
218
+ * metadata carries for a row this store created (a revived child reads its tree's owner off its own row through it).
211
219
  */
212
220
  readonly placements?: {
213
221
  subagent?: {
@@ -312,8 +320,18 @@ export interface SessionStore<S extends SessionStoreSummary = SessionStoreSummar
312
320
  * string is refused, with no row left behind) records that owner.
313
321
  * MUST copy the COMMITTED leaf (an in-flight uncommitted turn of an active source is not included — a fork is a
314
322
  * snapshot at the fork point).
323
+ *
324
+ * `opts.placement` (subagent transcript persistence): fork INTO the placement partition — the fork's creating write lays the
325
+ * tuple down exactly as a placed `acquire` does (first-write immutable, `placedAt` stamped by the store), so the forked row owes
326
+ * every placement obligation above and the row's placement reads back that tuple. The tuple carries no owner: the row's
327
+ * owner cell is the `owner` argument's, by the rule above (a background fork records its delegation tree's owner, which is its
328
+ * source row's). Trusted-internals channel only, as for `acquire`. On a store that declares {@link placements}, a fork whose
329
+ * row comes back without the declared tuple (a repo that dropped it) is refused `SessionError("placement_refused")` and the row
330
+ * is removed — the same mirror judgement a placed `acquire` takes.
315
331
  */
316
- fork?(sourceId: string, owner?: string | null): Promise<string | null>;
332
+ fork?(sourceId: string, owner?: string | null, opts?: {
333
+ placement?: Omit<SessionPlacement, "owner">;
334
+ }): Promise<string | null>;
317
335
  /**
318
336
  * The row's {@link SessionHead} for `sessionId` — owner, occupant and active leaf — in ONE read of the row, never assembled from
319
337
  * separate reads (a delete and re-create of the id between two reads would pair one generation's owner with the next one's
@@ -323,9 +341,12 @@ export interface SessionStore<S extends SessionStoreSummary = SessionStoreSummar
323
341
  * from `acquire`, only a session of the occupant it names — a cached view of an occupant the row no longer holds (the row deleted,
324
342
  * or deleted and created again, through another writer — on the File lane a writer in another process too) is not served — so its `incarnation` and the acquired session's metadata agree (the kit pins both); a run's own memory seat reads the session it ACQUIRED instead, never this lookup. The owner is a cell of the row: `null` = anonymous (admitted to every principal) — a row created
325
343
  * with no owner (`acquire` names none), or a row written before the cell existed; a principal name = owned (a cell holding a blank string
326
- * names nobody and is a read fault, never an owner). A placed row carries the owner its placing write recorded: the bundled stores'
327
- * placing write names none (`acquire`'s options and {@link SessionPlacement} carry no principal), so their placed rows read `null`; a
328
- * store's own placing write may record a principal (e.g. a delegation tree's owner), and a reader takes the row's owner as it reads. **Optional**: absent ⇒ no by-id read,
344
+ * names nobody and is a read fault, never an owner). A placed row carries the owner of its delegation tree: the placing write records
345
+ * exactly `placement.owner` ({@link SessionPlacement.owner} — minted by the engine from the tree root's row, as the root run read it, and
346
+ * carried unchanged down the tree), and no store derives an owner of its own; the child's owner VALUE is its root's (`null` when the
347
+ * root is anonymous) — a deployment's gate may still admit an ownerless placed row more narrowly than an ownerless root row, because a
348
+ * row placed before 7.62.0 keeps what its placing write recorded (`null` on the bundled stores, whatever its root's owner), and a
349
+ * descendant spawned from such a row after a revival records that `null` too. **Optional**: absent ⇒ no by-id read,
329
350
  * and a deployment's authorizer, which needs this and {@link register} together, takes its fail-closed arm.
330
351
  */
331
352
  headOf?(sessionId: string): Promise<SessionHead | undefined>;
@@ -442,6 +463,9 @@ export interface SessionStoreHooks {
442
463
  export declare function hasSessionFork(store: SessionStore): store is SessionStore & {
443
464
  fork: NonNullable<SessionStore["fork"]>;
444
465
  };
466
+ /** Does this store declare the subagent placement partition ({@link SessionStore.placements})? The opt-in a placing write needs: the
467
+ * store that CREATES a row is handed a placement only when it declares, so no store holds tuples it never opted into. */
468
+ export declare function declaresSubagentPlacement(store: Pick<SessionStore, "placements">): boolean;
445
469
  /**
446
470
  * F3 bounded-wake recipe, packaged. Given the **path-ordered** entries of a branch
447
471
  * (root→leaf, e.g. `await session.getBranch(leafId)` or a durable store's leaf-walk),
@@ -63,6 +63,9 @@ function readListCursor(raw) {
63
63
  export function hasSessionFork(store) {
64
64
  return typeof store.fork === "function";
65
65
  }
66
+ export function declaresSubagentPlacement(store) {
67
+ return store.placements?.subagent !== undefined;
68
+ }
66
69
  export function boundedTail(pathEntries) {
67
70
  let lastCompaction;
68
71
  for (const e of pathEntries) {
@@ -2,18 +2,6 @@ import { type Checkpoint, type CheckpointStore, type ResumeOutcome } from "../ch
2
2
  import type { GateOutcome } from "../gate-outcome.js";
3
3
  import { type CheckpointFields } from "../pause-registry.js";
4
4
  import { type ContractAssertionRunner } from "./contract-harness.js";
5
- /**
6
- * design/159 S1 — the cross-backend {@link CheckpointStore} contract, extracted VERBATIM from
7
- * `test/cross-backend-shared.ts` (design/87 §3 gap [cross-backend-enforce], the anti-drift guard
8
- * born in design/80 §6.3) into a vitest-free kit a third-party backend implementor can import and
9
- * run under any harness (or none — see {@link ContractAssertionRunner}).
10
- *
11
- * `make()` must return a FRESH, empty store each call. Core binds this to InMemory + File
12
- * (`test/cross-backend-inmem-file.test.ts`) and Pg via pg-mem (`test/pg-cross-backend.test.ts`);
13
- * a third-party durable backend passes its own factory.
14
- *
15
- * Version lockstep: see `contract-kit-version.ts` (`CONTRACT_KIT_ENGINE_VERSION`).
16
- */
17
5
  /** Build a {@link Checkpoint} fixture. `createdAt` is FIXED (not wall-clock) so summary projections
18
6
  * are deterministic and cross-backend byte-comparable; override via `over` for ordering tests. */
19
7
  export declare function createCheckpointFixture(over?: Partial<CheckpointFields>): Checkpoint;
@@ -57,6 +45,9 @@ export declare function checkpointListByScopeSummaries(store: CheckpointStore):
57
45
  /** The canonical expected summary projection (what `summarizeCheckpoint` must yield for the fixture above). */
58
46
  export declare const EXPECTED_LISTBYSCOPE_SUMMARIES: ({
59
47
  token: string;
48
+ rowVerdict: {
49
+ kind: string;
50
+ };
60
51
  sessionId: string;
61
52
  scope: string;
62
53
  gateKind: string;
@@ -75,6 +66,9 @@ export declare const EXPECTED_LISTBYSCOPE_SUMMARIES: ({
75
66
  spentMicroUsd?: undefined;
76
67
  } | {
77
68
  token: string;
69
+ rowVerdict: {
70
+ kind: string;
71
+ };
78
72
  sessionId: string;
79
73
  scope: string;
80
74
  gateKind: string;
@@ -1,8 +1,11 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { executionVerdict } from "../checkpoint-execution-record.js";
3
3
  import { MAX_PENDING_STEER_ENTRIES, checkpointIndexFacts, mintCheckpointToken, readPendingSteerQueue, } from "../checkpoint-store.js";
4
+ import { judgeCheckpointRow } from "../checkpoint-row-verdict.js";
5
+ import { memberPresent } from "../own-property-receipt.js";
4
6
  import { checkpointFrom } from "../pause-registry.js";
5
7
  import { beginContract } from "./contract-harness.js";
8
+ const unhashedCall = (call) => call;
6
9
  export function createCheckpointFixture(over = {}) {
7
10
  const token = over.token ?? mintCheckpointToken();
8
11
  return checkpointFrom({
@@ -11,17 +14,16 @@ export function createCheckpointFixture(over = {}) {
11
14
  sessionId: "sess-1",
12
15
  leafId: "leaf-1",
13
16
  gate: { kind: "human", reason: "approve", toolName: "Write" },
14
- pendingAction: {
17
+ pendingAction: unhashedCall({
15
18
  kind: "tool_approval",
16
19
  origin: "policy",
17
20
  toolCallId: "call-3",
18
21
  toolName: "Write",
19
22
  args: { path: "/x", content: "y" },
20
- boundInputHash: "h0",
21
23
  boundGrantAbsence: "not_bindable",
22
24
  batchToolCallIds: ["call-3"],
23
25
  completedCallIds: [],
24
- },
26
+ }),
25
27
  state: {
26
28
  activeTools: [],
27
29
  nestedStats: { tokens: 0, turns: 0, tasks: 0, costMicroUsd: 0, anyUnpriced: false },
@@ -31,6 +33,11 @@ export function createCheckpointFixture(over = {}) {
31
33
  ...over,
32
34
  });
33
35
  }
36
+ function damagedWriteFaceFixture(over) {
37
+ const cp = createCheckpointFixture(over);
38
+ Reflect.set(cp.state, "writeFace", { face: "neither" });
39
+ return cp;
40
+ }
34
41
  export const ALLOW = {
35
42
  gate: "policy_ask",
36
43
  decision: "allow",
@@ -275,6 +282,48 @@ export async function checkpointStoreContract(make, runAssertion, options = {})
275
282
  assert.equal(list[0].token, pending.token);
276
283
  assert.equal((await store.get(pending.token)).status, "pending");
277
284
  });
285
+ run("rowVerdict: every listed summary's verdict equals judgeCheckpointRow of the row get hands back (an ok row, a damaged row), and editing a listed summary's preview leaves the stored row as it was", async () => {
286
+ const store = make();
287
+ const okRow = createCheckpointFixture({
288
+ sessionId: "verdict-ok",
289
+ pendingAction: unhashedCall({ kind: "tool_approval", origin: "policy", toolCallId: "call-3", toolName: "Write", args: { path: "/x", content: "y" }, preview: { lines: ["a"] }, boundGrantAbsence: "not_bindable", batchToolCallIds: ["call-3"], completedCallIds: [] }),
290
+ });
291
+ const damagedRow = damagedWriteFaceFixture({ sessionId: "verdict-damaged" });
292
+ for (const cp of [okRow, damagedRow])
293
+ await store.put(cp.token, cp);
294
+ const listed = await store.listByScope("tenant-a");
295
+ assert.equal(listed.length, 2);
296
+ assert.equal(judgeCheckpointRow(okRow).kind, "ok");
297
+ assert.equal(judgeCheckpointRow(damagedRow).kind, "damaged");
298
+ for (const s of listed)
299
+ assert.deepEqual(s.rowVerdict, judgeCheckpointRow((await store.get(s.token))), `the listing and the get judge one row (${s.sessionId})`);
300
+ const byId = new Map(listed.map((s) => [s.sessionId, s]));
301
+ byId.get("verdict-ok").preview.lines.push("edited on the summary");
302
+ const stored = (await store.get(okRow.token)).pendingAction;
303
+ assert.deepEqual(stored.preview, { lines: ["a"] }, "a summary's preview is a copy: editing it does not edit the stored row");
304
+ const relisted = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
305
+ assert.deepEqual(relisted.get("verdict-ok").preview, { lines: ["a"] });
306
+ });
307
+ run("rowVerdict: a listed verdict is the verdict judged now — on a second listing, and (deleteSessionCheckpoints offered) after a token's row is replaced by a damaged one", async () => {
308
+ const store = make();
309
+ const row = createCheckpointFixture({ sessionId: "memo-row" });
310
+ await store.put(row.token, row);
311
+ const first = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
312
+ const second = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
313
+ assert.deepEqual(first.rowVerdict, judgeCheckpointRow((await store.get(row.token))));
314
+ assert.deepEqual(second.rowVerdict, first.rowVerdict);
315
+ const heads = options.sessionHeads;
316
+ if (store.deleteSessionCheckpoints === undefined || heads === undefined)
317
+ return;
318
+ heads.set("memo-row", { owner: null });
319
+ if ((await store.deleteSessionCheckpoints("memo-row", { owner: null })) !== 1)
320
+ return;
321
+ const replaced = damagedWriteFaceFixture({ token: row.token, sessionId: "memo-row" });
322
+ await store.put(replaced.token, replaced);
323
+ const after = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
324
+ assert.equal(after.rowVerdict.kind, "damaged", "a replaced row is judged again, never answered from the verdict its predecessor had");
325
+ assert.deepEqual(after.rowVerdict, judgeCheckpointRow((await store.get(row.token))));
326
+ });
278
327
  run("#438 hasBidiControls three-form matrix: a row's `true` survives + projects; absent stays absent (clean args); an out-of-contract `false` reads as absent; a bit-less marked row backfills at projection", async () => {
279
328
  const store = make();
280
329
  const RLO = String.fromCodePoint(0x202e);
@@ -460,6 +509,23 @@ export async function checkpointStoreContract(make, runAssertion, options = {})
460
509
  assert.equal((await store.get(bogus.token)).state.runOrigin, "weekly", "a word outside the set must be kept on the row verbatim");
461
510
  assert.equal("runOrigin" in byId.get("ro-bogus"), false, "a word outside the closed set must read as absent in the listing, never project verbatim");
462
511
  });
512
+ run("member presence: a row whose top level and `state` carry members holding undefined reads them absent — the value undefined (`memberPresent` false), the listing without them — and judges as its twin without the keys", async () => {
513
+ const store = make();
514
+ const holding = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mp-holding" });
515
+ Object.assign(holding, { deadline: undefined, humanReview: undefined });
516
+ Object.assign(holding.state, { compositionLeg: undefined, rowTaskId: undefined });
517
+ const omitted = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mp-omitted" });
518
+ for (const cp of [holding, omitted])
519
+ await store.put(cp.token, cp);
520
+ const got = (await store.get(holding.token));
521
+ for (const name of ["deadline", "humanReview"])
522
+ assert.equal(memberPresent(got, name), false, `a top-level ${name} holding undefined must read absent`);
523
+ for (const name of ["compositionLeg", "rowTaskId"])
524
+ assert.equal(memberPresent(got.state, name), false, `a state.${name} holding undefined must read absent`);
525
+ const listed = (await store.listByScope("tenant-a")).find((s) => s.sessionId === "mp-holding");
526
+ assert.equal("deadline" in listed, false, "the listing must leave out a deadline that holds undefined");
527
+ assert.deepEqual(judgeCheckpointRow(got), judgeCheckpointRow((await store.get(omitted.token))), "a member holding undefined must judge as the member left out");
528
+ });
463
529
  run("decider pair: a policy-decided allow resolves like a person's — its `policy_allowed` record (party `policy`, the attribution) round-trips verbatim on the resolved winner and as the execution record; the same record is already_recorded, a person's record for that row conflicts", async () => {
464
530
  const store = make();
465
531
  const cp = createCheckpointFixture();
@@ -654,7 +720,7 @@ export async function checkpointListByScopeSummaries(store) {
654
720
  toolName: "open_pr",
655
721
  riskDescriptor: { severity: 5, axes: { egress: true, irreversible: true }, toolName: "open_pr" },
656
722
  },
657
- pendingAction: {
723
+ pendingAction: unhashedCall({
658
724
  kind: "tool_approval",
659
725
  origin: "policy",
660
726
  mandated: true,
@@ -663,10 +729,9 @@ export async function checkpointListByScopeSummaries(store) {
663
729
  toolCallId: "call-pr",
664
730
  toolName: "open_pr",
665
731
  args: { repo: "x" },
666
- boundInputHash: "h0",
667
732
  batchToolCallIds: ["call-pr"],
668
733
  completedCallIds: [],
669
- },
734
+ }),
670
735
  });
671
736
  const resource = createCheckpointFixture({
672
737
  token: "tok-resource",
@@ -688,6 +753,7 @@ export async function checkpointListByScopeSummaries(store) {
688
753
  export const EXPECTED_LISTBYSCOPE_SUMMARIES = [
689
754
  {
690
755
  token: "tok-escalation",
756
+ rowVerdict: { kind: "ok" },
691
757
  sessionId: "needs-approval",
692
758
  scope: "tenant-a",
693
759
  gateKind: "human",
@@ -706,6 +772,7 @@ export const EXPECTED_LISTBYSCOPE_SUMMARIES = [
706
772
  },
707
773
  {
708
774
  token: "tok-resource",
775
+ rowVerdict: { kind: "ok" },
709
776
  sessionId: "out-of-budget",
710
777
  scope: "tenant-a",
711
778
  gateKind: "resource_limit",
@@ -22,8 +22,8 @@ function compactionEntry(id, parentId, firstKeptEntryId) {
22
22
  return { id, parentId, type: "compaction", timestamp: AT, summary: "summary of the turns above the floor", firstKeptEntryId, tokensBefore: 1000 };
23
23
  }
24
24
  const freshId = () => uuidv7();
25
- function placementFor(scope, handle = `a${uuidv7().slice(-12)}`) {
26
- return { kind: "subagent", scope: scope ?? `kit-${uuidv7().slice(-12)}`, ...(handle !== null ? { handle } : {}) };
25
+ function placementFor(scope, handle = `a${uuidv7().slice(-12)}`, owner = null) {
26
+ return { kind: "subagent", scope: scope ?? `kit-${uuidv7().slice(-12)}`, ...(handle !== null ? { handle } : {}), owner };
27
27
  }
28
28
  const tick = () => new Promise((resolve) => setTimeout(resolve, 20));
29
29
  async function append(session, entry, opts) {
@@ -73,7 +73,7 @@ async function refusedAsLoop(storage, leafId, loopMembers, what) {
73
73
  const outcome = await Promise.race([settled, expiry]).finally(() => clearTimeout(timer));
74
74
  if ("path" in outcome)
75
75
  assert.fail(`${what}: a parent chain that loops back on itself answered a path of ${outcome.path.length} entries instead of refusing`);
76
- assert.equal(readMember(outcome.err, "code"), "invalid_session", `${what}: the refusal must carry code invalid_session`);
76
+ assert.equal(readMember(outcome.err, "code"), "corrupt_session", `${what}: the refusal must carry code corrupt_session`);
77
77
  const sentence = String(readMember(outcome.err, "message"));
78
78
  assert.ok(loopMembers.some((id) => sentence.includes(id)), `${what}: the refusal must name an entry of the loop (${loopMembers.join(" / ")}), got "${sentence}"`);
79
79
  }
@@ -290,7 +290,7 @@ async function runSessionStoreContract(make, hooks) {
290
290
  assert.equal(await storage.getLeafId(), "e1", "a refused setLeafId leaves the leaf where it was");
291
291
  await rejectsWithCode(() => storage.getPathToRoot("kit-never-written"), "not_found", "getPathToRoot from an id the session never held");
292
292
  });
293
- run("[tree] a path stops at a root or at the storage's declared floor; a parent missing above the floor reads invalid_session, never a truncated path", async (store) => {
293
+ run("[tree] a path stops at a root or at the storage's declared floor; a parent missing above the floor reads corrupt_session, never a truncated path", async (store) => {
294
294
  const { session } = await store.acquire(freshId());
295
295
  await append(session, userEntry("e1", null));
296
296
  let accepted = true;
@@ -301,12 +301,12 @@ async function runSessionStoreContract(make, hooks) {
301
301
  accepted = false;
302
302
  }
303
303
  if (accepted) {
304
- await rejectsWithCode(() => session.getStorage().getPathToRoot("orphan"), "invalid_session", "the path through an entry whose parent was never written");
304
+ await rejectsWithCode(() => session.getStorage().getPathToRoot("orphan"), "corrupt_session", "the path through an entry whose parent was never written");
305
305
  }
306
306
  const head = (await session.getStorage().getPathToRoot("e1"))[0];
307
307
  assert.ok(head.parentId === null || head.id === session.getStorage().getFloorId?.(), "a path's head is a root or the declared floor");
308
308
  });
309
- run("[tree] a parent chain that loops back on itself — an entry that is its own parent, two entries that parent each other, a leaf that walks into such a pair — reads invalid_session naming an entry of the loop, and the walk ends (also for a ring of three)", async (store) => {
309
+ run("[tree] a parent chain that loops back on itself — an entry that is its own parent, two entries that parent each other, a leaf that walks into such a pair — reads corrupt_session naming an entry of the loop, and the walk ends (also for a ring of three)", async (store) => {
310
310
  const { session } = await store.acquire(freshId());
311
311
  await append(session, userEntry("e1", null));
312
312
  const accepted = async (...entries) => {
@@ -743,6 +743,20 @@ async function runSessionStoreContract(make, hooks) {
743
743
  await append(acquired.session, userEntry("e1", null));
744
744
  assert.deepEqual(await entryIds((await readBack(store, id))), ["e1"]);
745
745
  });
746
+ faceRun("[placements] the placing write records exactly placement.owner as the row's owner, and headOf answers the placed row with the occupant the acquired session carries — before and after a restart", ["placements"], async (store, open) => {
747
+ assert.ok(hasHead(store), "a store that declares placements answers headOf (obligation 7): a revived child reads its tree's owner off its own row through it");
748
+ const named = freshId();
749
+ const anonymous = freshId();
750
+ const owner = `kit-tree-${freshId()}`;
751
+ const acquired = await store.acquire(named, { placement: placementFor(undefined, undefined, owner) });
752
+ await store.acquire(anonymous, { placement: placementFor() });
753
+ const token = await tokenOf(store, named, "a placed row this store created");
754
+ assert.equal((await acquired.session.getMetadata()).incarnation, token, "the placed session handed out is the occupant the head names");
755
+ assert.equal(await ownerOf(store, named, "a placed row"), owner, "the placing write recorded the placement's owner");
756
+ assert.equal(await ownerOf(store, anonymous, "a placed row of an anonymous tree"), null, "a null placement owner is an anonymous row");
757
+ const second = await open(hooks.reopen(store));
758
+ assert.deepEqual(await headOf(second, named), await headOf(store, named), "the owner lives in the row, not in an instance");
759
+ });
746
760
  faceRun("[placements] listPlaced returns each placed session with its full (scope, handle) tuple or the honest tupleIncomplete, filters by scope and age, and never lists an ordinary session", ["listPlaced"], async (store) => {
747
761
  const scope = `kit-${uuidv7().slice(-12)}`;
748
762
  const full = placementFor(scope);
@@ -766,6 +780,45 @@ async function runSessionStoreContract(make, hooks) {
766
780
  assert.ok(scoped.includes(complete) && scoped.includes(incomplete) && !scoped.includes(elsewhere), "scope narrows to one tenant");
767
781
  assert.ok(!(await store.listPlaced("subagent", { olderThanMs: 60 * 60 * 1000 })).some((r) => r.sessionId === complete), "a session placed just now is not an hour old");
768
782
  });
783
+ faceRun("[placements] a fork carrying a placement is created into the partition — the tuple reads back on the forked row, which stays off the host list, refuses a claim-form acquire, is listed placed and is deleted by its release, while its source stays ordinary — before and after a restart", ["placements", "fork"], async (store, open) => {
784
+ const src = freshId();
785
+ await append((await store.acquire(src)).session, userEntry("e1", null));
786
+ const { owner: _treeOwner, ...tuple } = placementFor(`kit-${uuidv7().slice(-12)}`);
787
+ const forkedId = await store.fork(src, null, { placement: { ...tuple, parentSessionId: src, rootSessionId: src } });
788
+ assert.ok(forkedId !== null && forkedId !== src, "a placed fork of an existing session is a new id");
789
+ const meta = await (await readBack(store, forkedId)).getMetadata();
790
+ assert.equal(meta.forkedFrom, src, "a placed fork still names its source");
791
+ assert.deepEqual({ kind: meta.placement?.kind, scope: meta.placement?.scope, handle: meta.placement?.handle, parentSessionId: meta.placement?.parentSessionId, rootSessionId: meta.placement?.rootSessionId }, { kind: "subagent", scope: tuple.scope, handle: tuple.handle, parentSessionId: src, rootSessionId: src }, "the fork's creating write laid the tuple down");
792
+ assert.equal(typeof meta.placement?.placedAt, "number", "the store stamped placedAt");
793
+ assert.deepEqual(await pathIds(await readBack(store, forkedId)), ["e1"], "the placed fork carries the source's committed history");
794
+ await rejectsWithCode(() => store.acquire(forkedId), "placement_refused", "obligation 6: a placed fork is not claimable");
795
+ await store.acquire(src);
796
+ if (typeof store.list === "function") {
797
+ const rows = await store.list();
798
+ assert.equal(rowOf(rows, forkedId), undefined, "obligation 2: a placed fork is not a host session");
799
+ assert.ok(rowOf(rows, src) !== undefined, "its source stays an ordinary, listed session");
800
+ }
801
+ if (typeof store.listPlaced === "function") {
802
+ const listed = (await store.listPlaced("subagent", { scope: tuple.scope })).find((r) => r.sessionId === forkedId);
803
+ assert.ok(listed !== undefined && !("tupleIncomplete" in listed) && listed.handle === tuple.handle, "the placed listing carries the fork with its join tuple");
804
+ }
805
+ const second = await open(hooks.reopen(store));
806
+ assert.equal((await readBack(second, forkedId).then((s) => s.getMetadata())).placement?.handle, tuple.handle, "the tuple lives in the row, not in an instance");
807
+ await rejectsWithCode(() => second.acquire(forkedId), "placement_refused", "obligation 6 after a restart");
808
+ await second.release(forkedId);
809
+ await rejectsWithCode(() => second.acquire(forkedId, { requireExisting: true }), "not_found", "obligation 4: the placed fork's release is a real deletion");
810
+ assert.deepEqual(await pathIds(await readBack(second, src)), ["e1"], "the source is untouched");
811
+ });
812
+ run("[placements] a store that does not declare placements still forks for a fork carrying a placement (ignoring it is legal, refusing the fork is not)", async (store) => {
813
+ if (declaresPlacements(store) || !hasSessionFork(store))
814
+ return;
815
+ const src = freshId();
816
+ await append((await store.acquire(src)).session, userEntry("e1", null));
817
+ const { owner: _treeOwner, ...tuple } = placementFor();
818
+ const forkedId = await store.fork(src, null, { placement: tuple });
819
+ assert.ok(forkedId !== null && forkedId !== src);
820
+ assert.deepEqual(await pathIds(await readBack(store, forkedId)), ["e1"]);
821
+ });
769
822
  faceRun("[head] headOf answers undefined for an id with no row; for a row, its owner, its occupant and its active leaf — the leaf follows appends and a branch switch", ["headOf"], async (store) => {
770
823
  const id = freshId();
771
824
  assert.equal(await headOf(store, id), undefined, "no row ⇒ undefined");
@@ -843,13 +896,13 @@ async function runSessionStoreContract(make, hooks) {
843
896
  if (declaresPlacements(store)) {
844
897
  for (const owner of [`kit-claimant-${freshId()}`, null]) {
845
898
  const placed = freshId();
846
- await store.acquire(placed, { placement: placementFor() });
899
+ await store.acquire(placed, { placement: placementFor(undefined, undefined, `kit-tree-${freshId()}`) });
847
900
  const recorded = await ownerOf(store, placed, "a placed row");
848
901
  await store.register(placed, owner);
849
902
  assert.equal(await ownerOf(store, placed, "a placed row after a register"), recorded, `a register carrying ${owner === null ? "null" : "an owner"} left the placed row's owner as its placing write recorded it`);
850
903
  }
851
904
  const sequenced = freshId();
852
- await store.acquire(sequenced, { placement: placementFor() });
905
+ await store.acquire(sequenced, { placement: placementFor(undefined, undefined, `kit-tree-${freshId()}`) });
853
906
  const recordedSeq = await ownerOf(store, sequenced, "a placed row (sequence)");
854
907
  await store.register(sequenced, null);
855
908
  await store.register(sequenced, `kit-claimant-${freshId()}`);
@@ -928,7 +928,8 @@ export type TaskEvent = ({
928
928
  * or the design/130 P2 graceful-finalize instruction) into the model's next turn. Previously these
929
929
  * went through `harness.steer()` with no stream echo — a consumer literally could not tell whether
930
930
  * the finalize fired (the refute-130 attribution blind spot). Echo only; the model-facing message
931
- * is unchanged. `preview` is the injected text clipped to a display bound.
931
+ * is unchanged. `preview` is the injected text clipped to a display bound (220 characters; the post-compaction
932
+ * `background_tasks` table, a list its renderer already bounds, is echoed whole up to the per-boundary attachment cap).
932
933
  *
933
934
  * design/133 (LOW-11/F11): the turn-boundary attachment producers ride the same echo — sources
934
935
  * `todo_reminder` / `task_reminder` / `changed_files` and the G1/续批 members
@@ -1053,6 +1054,11 @@ export type TaskEvent = ({
1053
1054
  * render it as the scheduler's, not as someone typing): the objective's `TaskSpec.runOrigin`, a parked or waking
1054
1055
  * message's `runOrigin`. Absent ⇒ the host said nothing (never "a person sent it"). Attribution only. */
1055
1056
  runOrigin?: import("./run-origin.js").RunOrigin;
1057
+ /** Present when the leg's prompt screen (`prompt.submit`) rewrote THIS input's text before it was delivered: the extensions
1058
+ * that changed it, in the order they did. The model saw the rewritten text (the caller's own words are not delivered);
1059
+ * rides the account the screening entrance mints — the `"applied"` frame of an objective, a parked steer or a wake's
1060
+ * message, the `"queued"` frame of a live steer. Absent ⇒ the text went as it came. */
1061
+ rewrittenBy?: readonly string[];
1056
1062
  } & TaskEventIdentity) | ({
1057
1063
  /**
1058
1064
  * design/99 §E3/§E10 — a live BRAIN-LAYER status the brain would otherwise absorb
@@ -1279,6 +1285,27 @@ export type TaskEvent = ({
1279
1285
  dir: string;
1280
1286
  byPath?: true;
1281
1287
  };
1288
+ /** The session's checkout (`TaskSpec.workspace`), one entry per repository, fixed by the session's first leg:
1289
+ * `repository` = the repository's root; `root` = which declared root lives there; `baseSha` = the commit the session's
1290
+ * code starts from. `dir` / `name` / `branch` / `baseRef` (present together) = the session's own tree of that
1291
+ * repository — with `root: "taskRoot"`, this leg's `root` is the task root's place in it. `source` = the declared
1292
+ * code source for that repository. ABSENT = the session declared no workspace. */
1293
+ session?: ReadonlyArray<{
1294
+ repository: string;
1295
+ root: "taskRoot" | {
1296
+ directory: string;
1297
+ };
1298
+ baseSha: string;
1299
+ dir?: string;
1300
+ name?: string;
1301
+ branch?: string;
1302
+ baseRef?: "fresh" | "head" | "source";
1303
+ source?: {
1304
+ remote: string;
1305
+ sha: string;
1306
+ ref?: string;
1307
+ };
1308
+ }>;
1282
1309
  /** This leg's project identity, decided ONCE at leg start and fixed for the leg: `marker` = the checkout's
1283
1310
  * `.sema/project` (a `TaskSpec.projectId`, when given, equals it); `declared` = `TaskSpec.projectId` in a checkout
1284
1311
  * that carries no marker. ABSENT = no marker and no declaration, or the marker could not be read (the deployment's
@@ -629,7 +629,8 @@ export declare function isTerminalTaskNotification(n: Pick<TaskNotificationPaylo
629
629
  * agent, a workflow run: the run lane the call carries (`ToolExecuteContext.onTaskNotification`) when there is one, else
630
630
  * the mount's own sink. One value per launch: the producer judges "will a completion reach the model" by it, delivers
631
631
  * through it, and owes its terminal frame to it ({@link oweTerminalDelivery}) — never one sink for the judgment and
632
- * another for the delivery.
632
+ * another for the delivery. A parked agent's redemption is the cycle its park left owed: its lane is the one that park
633
+ * recorded (`TaskRegistry.parkedCompletionSink`) when the call carries none of its own.
633
634
  */
634
635
  export declare function resolveCompletionSink<C, M>(callSink: C | undefined, mountSink: M | undefined): C | M | undefined;
635
636
  /**
@@ -656,6 +657,10 @@ export declare function admitsBackgroundLaunch(sink: unknown, deploymentChannel:
656
657
  * task by the frame it delivers, so a frame of another lane carrying the same `task_id` settles nothing here. A background
657
658
  * command or a Monitor watch never enters: its lifetime is its process's (it may never end), and a one-shot ending treats
658
659
  * it by the run's teardown rules without waiting. A sink no lane bound (a host's own) owes nothing.
660
+ *
661
+ * A cycle that PARKS on an approval sends no frame: its debt stays where it was booked, and the redemption that resumes
662
+ * it is the same cycle continuing — it books nothing new, and its frame settles that debt. Where the redemption completes
663
+ * into another lane, the debt moves there when the approval is consumed ({@link moveTerminalDelivery}) — one handle, one debt.
659
664
  */
660
665
  export declare class DeliveryObligations {
661
666
  /** lane key → admitted cycles whose terminal frame has not reached the sink. */
@@ -693,6 +698,9 @@ export declare function bindDeliveryObligations(sink: object, book: DeliveryObli
693
698
  export declare function oweTerminalDelivery(sink: unknown, task: Pick<TaskNotificationPayload, "task_id" | "task_type">): void;
694
699
  /** A cycle whose terminal frame will never reach `sink` (it was voided) releases its debt there (no-op for an unbound sink). */
695
700
  export declare function retireTerminalDelivery(sink: unknown, task: Pick<TaskNotificationPayload, "task_id" | "task_type">): void;
701
+ /** A parked cycle's debt follows its redemption: released on the lane the park left it owed to (`from`, absent when this
702
+ * process holds no park of it), owed on the lane the redemption completes into (`to`) — nothing moves when they are one. */
703
+ export declare function moveTerminalDelivery(from: unknown, to: unknown, task: Pick<TaskNotificationPayload, "task_id" | "task_type">): void;
696
704
  export interface DrainedPendingNotifications {
697
705
  /** Payloads still held when the session's next run drained. design/373 §3.5: batch order is
698
706
  * PRIORITY-MAJOR (now < next < later; a record with no carried priority ranks AS later —
@@ -1,6 +1,7 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { escapeEnvelopeTag, inlineUntrusted, sanitizeUntrustedText } from "./untrusted-text.js";
3
3
  import { egressText } from "./untrusted-egress.js";
4
+ import { redactThenCut } from "../agents/subagent-steps.js";
4
5
  import { PEER_MESSAGE_NOTICE } from "../agents/peer-admission.js";
5
6
  import { buildCrossSessionEnvelope, CROSS_PRINCIPAL_MESSAGE_NOTICE, CROSS_SESSION_MESSAGE_NOTICE, neutralizePeerBody } from "../agents/cross-session-envelope.js";
6
7
  export const TASK_NOTIFICATION_TERMINAL_STATUSES = Object.freeze(["completed", "failed", "killed", "cancelled"]);
@@ -386,6 +387,12 @@ export function retireTerminalDelivery(sink, task) {
386
387
  if (typeof sink === "function")
387
388
  LANE_OBLIGATIONS.get(sink)?.retire(task);
388
389
  }
390
+ export function moveTerminalDelivery(from, to, task) {
391
+ if (from === to)
392
+ return;
393
+ retireTerminalDelivery(from, task);
394
+ oweTerminalDelivery(to, task);
395
+ }
389
396
  export function createLiveNotificationLane(seat) {
390
397
  const handedOff = new Set();
391
398
  const enter = (admits) => (payload, priority, onDisposition) => {
@@ -820,7 +827,7 @@ export function renderBackgroundTaskTable(tasks) {
820
827
  : t.status === "parked"
821
828
  ? "parked awaiting an out-of-band approval — do NOT re-issue the gated call"
822
829
  : t.status;
823
- return `- [${t.id}] Task "${(t.description ?? "background task").slice(0, BACKGROUND_TASK_TABLE_DESCRIPTION_MAX)}" ${phrase}${t.read !== undefined ? ` — ${t.read}` : ""}`;
830
+ return `- [${t.id}] Task "${redactThenCut(t.description ?? "background task", BACKGROUND_TASK_TABLE_DESCRIPTION_MAX)}" ${phrase}${t.read !== undefined ? ` — ${t.read}` : ""}`;
824
831
  });
825
832
  return lines.join("\n") + (unlisted > 0 ? `\n(+${unlisted} more background tasks, not listed here)` : "");
826
833
  }
@@ -1,5 +1,5 @@
1
1
  import { type BackgroundAgentRecord, type BackgroundAgentStore } from "./background-agent-store.js";
2
- import { type StopSource, type TaskAccess, type TaskRetrievalStatus, type UnifiedTaskOutput, type UnifiedTaskResult, type BackgroundAgentTaskHandle, type RegisteredTaskHandle, type DurableAgentCore, type ParkedClaimTicket, type RegisterBackgroundAgentInput } from "./task-registry-shared.js";
2
+ import { type StopSource, type TaskAccess, type TaskRetrievalStatus, type UnifiedTaskOutput, type UnifiedTaskResult, type BackgroundAgentTaskHandle, type ChildSessionStore, type RegisteredTaskHandle, type DurableAgentCore, type ParkedClaimTicket, type RegisterBackgroundAgentInput, type LandedAgentTerminal } from "./task-registry-shared.js";
3
3
  import { type AgentState } from "./agent-state.js";
4
4
  import type { CheckpointSeat } from "./checkpoint-seat.js";
5
5
  /**
@@ -13,6 +13,17 @@ import type { CheckpointSeat } from "./checkpoint-seat.js";
13
13
  * segment, which is what makes the reservation race-free in-process.
14
14
  */
15
15
  export declare function activeDelegationHandlesLane(core: DurableAgentCore, scope: string, rootSessionId: string): string[];
16
+ /** One running or pending row of a delegation tree, as its occupant is told of it: the task id every addressing tool takes, the row's
17
+ * addressing name, and whether the caller asked for can address it (the registry's access predicate — a nested agent does not reach
18
+ * its siblings' rows, so their ids and names are not its to be told). */
19
+ export interface DelegationOccupant {
20
+ readonly id: string;
21
+ readonly name: string;
22
+ readonly reachable: boolean;
23
+ }
24
+ /** The rows {@link activeDelegationHandlesLane} counts, with the name each is addressed by — the one selection, read in the same
25
+ * synchronous segment. `caller` is the access the asking leg's own tools hold (`scope` is the pool's); without one no row is reachable. */
26
+ export declare function activeDelegationOccupantsLane(core: DurableAgentCore, scope: string, rootSessionId: string, caller?: TaskAccess): DelegationOccupant[];
16
27
  export declare function ensureDurableHeartbeatLane(core: DurableAgentCore): void;
17
28
  /** design/151 S1a — enqueue one durable-row write (see {@link DurableAgentLane} for the lane
18
29
  * contract). `patch` is captured at CALL time (the settle-site values), applied in chain order.
@@ -116,11 +127,18 @@ export declare function reapDurableAgentsLane(core: DurableAgentCore, scope: str
116
127
  skippedNoSessions: number;
117
128
  orphanPlacedReleased: number;
118
129
  }>;
130
+ /** A background-agent row's child session: its id and the store the child's run holds it through (`undefined` when a
131
+ * caller outside the bind's types bound the id without one). */
132
+ export interface ChildSessionAnchor {
133
+ readonly sessionId: string;
134
+ readonly store: ChildSessionStore | undefined;
135
+ }
119
136
  /** The child session a background-agent row is anchored to right now — the session its child runs on
120
- * or keeps (transcript / resume anchor) — or `undefined` before the bind, after the anchor's release,
121
- * and on every other task type. The ONE reading of the anchor: the list row's `sessionId` and the
122
- * release match below both read it here. */
123
- export declare function childSessionAnchorOf(handle: RegisteredTaskHandle): string | undefined;
137
+ * or keeps (transcript / resume anchor), with the store that holds it — or `undefined` before the bind,
138
+ * after the anchor's release, and on every other task type. The ONE reading of the anchor: the list
139
+ * row's `sessionId`, the transcript read ({@link TaskRegistry.anchoredSession}) and the release and bind
140
+ * matches below all read it here. */
141
+ export declare function childSessionAnchorOf(handle: RegisteredTaskHandle): ChildSessionAnchor | undefined;
124
142
  /** A successful release of the child session `sessionId` ends the row's claim on it: both copies of
125
143
  * the anchor go — the handle's (the list row reads it) and the durable record's (the heartbeat's F-1
126
144
  * arm keeps re-driving a flush-failed lane, so a later successful flush would otherwise persist a row
@@ -133,8 +151,10 @@ export declare function releaseDurableTranscriptAnchorLane(core: DurableAgentCor
133
151
  * A row already anchored to that session is left as it is (one fact, no second durable write). A row anchored to ANOTHER session
134
152
  * is refused: an anchor changes only by its release ({@link releaseDurableTranscriptAnchorLane}) and a fresh bind, never by being
135
153
  * written over, so the earlier session is never silently left unowned. An id that is no non-empty string is no anchor and is
136
- * refused whatever the row holds. */
137
- export declare function bindBackgroundAgentSessionLane(core: DurableAgentCore, id: string, sessionId: string): void;
154
+ * refused whatever the row holds. `store` is the store the child's run holds that session through, bound with the id (the
155
+ * store is process-local; the durable record keeps the id alone). The store is judged where it is read: the transcript read
156
+ * (`$.session.messages`) refuses, naming why, one it cannot read through. */
157
+ export declare function bindBackgroundAgentSessionLane(core: DurableAgentCore, id: string, sessionId: string, store: ChildSessionStore): void;
138
158
  /**
139
159
  * #22 — record the org-memory admission verdict THIS leg adjudicated onto the durable row, so the
140
160
  * next CROSS-PROCESS revival (which rebuilds the spec from the reviving caller's mount and cannot
@@ -173,6 +193,7 @@ export declare function parkBackgroundAgentLane(core: DurableAgentCore, id: stri
173
193
  checkpointToken: string;
174
194
  seq?: number;
175
195
  resolveStop?: () => Promise<boolean>;
196
+ completionSink?: BackgroundAgentTaskHandle["parkedCompletionSink"];
176
197
  }): "parked" | undefined;
177
198
  /**
178
199
  * design/153 §7.1 (件1 split-brain fence) — the registry-aware reconciliation entry an
@@ -424,7 +445,18 @@ export declare function noteBackgroundAgentActivityLane(core: DurableAgentCore,
424
445
  * stale-running sweep writes, so an operator reading either face sees one explanation, and its run is
425
446
  * aborted. Returns how many rows were collected.
426
447
  */
427
- export declare function reapStaleSessionBackgroundAgentsLane(core: DurableAgentCore, staleMs: number, now?: number, onTerminal?: (note: () => void) => void): number;
448
+ export declare function reapStaleSessionBackgroundAgentsLane(core: DurableAgentCore, staleMs: number, now?: number): number;
449
+ /**
450
+ * THE announcement of a background agent's terminal the REGISTRY landed without the cycle's attempt — the session or stale
451
+ * reap of a running cycle (its attempt's unwind would report only once the in-flight tool honored the abort), a TaskStop
452
+ * that won a parked cycle's arbitration, a parked cycle's approval found expired or decided elsewhere (the attempt that
453
+ * parked returned at the park; nothing else would report it). Sent now, once: through the notifier the spawn lane hung on
454
+ * the handle, under the one terminal once-latch the attempt's own unwind claims too (`claimAgentTerminalNotify`) — the
455
+ * first sender wins, the other stays silent. A lane that hung no notifier (direct registry use) keeps its unwind's
456
+ * announcement. A parked cycle's ending names the lane its park recorded the debt on (`ending.parkLane`); a park that
457
+ * recorded none owes nothing in this process, and its caller announces nothing.
458
+ */
459
+ export declare function announceLandedAgentTerminal(core: DurableAgentCore, handle: BackgroundAgentTaskHandle, notifier: BackgroundAgentTaskHandle["terminalNotifier"], ending: LandedAgentTerminal): void;
428
460
  /** S2b — retention is REVOCABLE: every retain-ledger eviction path (TTL / LRU / abandon /
429
461
  * parent-teardown disposeAll) runs the entry's release closure, and the spawner wraps that closure
430
462
  * to call this — so a park can never be acknowledged against a continuation that was already