@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
@@ -10,6 +10,9 @@ import { thrownLabel } from "./thrown-value.js";
10
10
  import { closestName } from "./closest-name.js";
11
11
  import { agentStateSourceOfHandle, agentStateSummary, readAgentState } from "./agent-state.js";
12
12
  export function activeDelegationHandlesLane(core, scope, rootSessionId) {
13
+ return activeDelegationOccupantsLane(core, scope, rootSessionId).map((o) => o.id);
14
+ }
15
+ export function activeDelegationOccupantsLane(core, scope, rootSessionId, caller) {
13
16
  const out = [];
14
17
  for (const h of core.handles.values()) {
15
18
  if (h.type !== "background_agent")
@@ -22,7 +25,7 @@ export function activeDelegationHandlesLane(core, scope, rootSessionId) {
22
25
  const root = bh.rootSessionId ?? bh.parentSessionId ?? (bh.sessionScoped ? bh.owner : undefined);
23
26
  if (root !== rootSessionId)
24
27
  continue;
25
- out.push(h.id);
28
+ out.push({ id: h.id, name: bh.name, reachable: caller !== undefined && canAccess(h, { ...caller, scope }) });
26
29
  }
27
30
  return out;
28
31
  }
@@ -312,29 +315,33 @@ export async function reapDurableAgentsLane(core, scope, deps, policy) {
312
315
  return { rowsReaped, sessionsReleased, skippedNoSessions, orphanPlacedReleased };
313
316
  }
314
317
  export function childSessionAnchorOf(handle) {
315
- return handle.type === "background_agent" ? handle.sessionId : undefined;
318
+ if (handle.type !== "background_agent" || handle.sessionId === undefined)
319
+ return undefined;
320
+ return { sessionId: handle.sessionId, store: handle.sessionStore };
316
321
  }
317
322
  export function releaseDurableTranscriptAnchorLane(core, id, sessionId) {
318
323
  const handle = core.handles.get(id);
319
324
  if (!handle || handle.type !== "background_agent")
320
325
  return;
321
- if (childSessionAnchorOf(handle) !== sessionId)
326
+ if (childSessionAnchorOf(handle)?.sessionId !== sessionId)
322
327
  return;
323
328
  delete handle.sessionId;
329
+ delete handle.sessionStore;
324
330
  durableAgentWriteLane(handle, {}, ["sessionId"]);
325
331
  }
326
- export function bindBackgroundAgentSessionLane(core, id, sessionId) {
332
+ export function bindBackgroundAgentSessionLane(core, id, sessionId, store) {
327
333
  if (typeof sessionId !== "string" || sessionId === "")
328
334
  throw new Error(`TaskRegistry: a background-agent session anchor must be a non-empty session id (got ${typeof sessionId === "string" ? "an empty string" : `a ${sessionId === null ? "null" : typeof sessionId}`})`);
329
335
  const handle = core.handles.get(id);
330
336
  if (!handle || handle.type !== "background_agent")
331
337
  return;
332
- const anchored = childSessionAnchorOf(handle);
338
+ const anchored = childSessionAnchorOf(handle)?.sessionId;
333
339
  if (anchored === sessionId)
334
340
  return;
335
341
  if (anchored !== undefined)
336
342
  throw new Error(`TaskRegistry: background-agent row ${id} is anchored to a session already — release that anchor before binding another (the row keeps its anchor)`);
337
343
  handle.sessionId = sessionId;
344
+ handle.sessionStore = store;
338
345
  durableAgentWriteLane(handle, { sessionId });
339
346
  }
340
347
  export function recordBackgroundAgentOrgAdmissionLane(core, id, verdict) {
@@ -365,6 +372,7 @@ export function registerBackgroundAgentLane(core, input) {
365
372
  throw new Error(`TaskRegistry: background-agent id ${JSON.stringify(input.id)} does not match the a<hex> handle form`);
366
373
  }
367
374
  const id = input.id ?? core.mintTaskId("background_agent");
375
+ let carriedCompletionSink;
368
376
  if (input.durableSeed !== undefined) {
369
377
  const prior = core.handles.get(id);
370
378
  if (prior !== undefined) {
@@ -375,6 +383,8 @@ export function registerBackgroundAgentLane(core, input) {
375
383
  const priorLane = prior.durable;
376
384
  if (priorLane !== undefined)
377
385
  priorLane.poisoned = true;
386
+ if (parkedHandoff)
387
+ carriedCompletionSink = prior.parkedCompletionSink;
378
388
  core.handles.delete(id);
379
389
  }
380
390
  }
@@ -391,6 +401,7 @@ export function registerBackgroundAgentLane(core, input) {
391
401
  status: input.initialStatus ?? "running",
392
402
  ...(input.parkedCheckpointToken !== undefined ? { parkedCheckpointToken: input.parkedCheckpointToken } : {}),
393
403
  ...(input.resolveParkedStop !== undefined ? { resolveParkedStop: input.resolveParkedStop } : {}),
404
+ ...(carriedCompletionSink !== undefined ? { parkedCompletionSink: carriedCompletionSink } : {}),
394
405
  ...(input.sessionScoped ? { sessionScoped: true } : {}),
395
406
  ...(input.description !== undefined ? { description: input.description } : {}),
396
407
  name,
@@ -467,6 +478,7 @@ export function parkBackgroundAgentLane(core, id, park) {
467
478
  handle.status = "parked";
468
479
  handle.parkedCheckpointToken = park.checkpointToken;
469
480
  handle.resolveParkedStop = park.resolveStop;
481
+ handle.parkedCompletionSink = park.completionSink;
470
482
  handle.notify = undefined;
471
483
  for (const [, , qResolve] of handle.preAttachQueue ?? [])
472
484
  qResolve?.({ ok: false, reason: "not_running" });
@@ -535,18 +547,18 @@ export async function reconcileParkedAgentsLane(core, stores, scope, now, opts)
535
547
  else {
536
548
  continue;
537
549
  }
538
- if (handle.status !== "parked")
539
- continue;
540
- if (handle.parkedCheckpointToken !== token)
550
+ const held = heldPark(core, handle.id, token);
551
+ if (held === undefined)
541
552
  continue;
542
- handle.status = "failed";
543
- handle.error = error;
544
- handle.parkedCheckpointToken = undefined;
545
- handle.resolveParkedStop = undefined;
546
- handle.updatedAt = now;
547
- mintCompletionId(handle);
548
- core.pokeBgQuiescence(handle.owner);
549
- durableAgentWriteLane(handle, { status: "failed", error: handle.error, settledAt: now, stoppedBy: "system", completionId: handle.completionId }, ["parkedCheckpointToken", "parkClaimId", "parkedAt"]);
553
+ held.status = "failed";
554
+ held.error = error;
555
+ held.parkedCheckpointToken = undefined;
556
+ held.resolveParkedStop = undefined;
557
+ held.updatedAt = now;
558
+ mintCompletionId(held);
559
+ core.pokeBgQuiescence(held.owner);
560
+ announceParkedEnding(core, held, { status: "failed", error });
561
+ durableAgentWriteLane(held, { status: "failed", error: held.error, settledAt: now, stoppedBy: "system", completionId: held.completionId }, ["parkedCheckpointToken", "parkClaimId", "parkedAt"]);
550
562
  liveFailed++;
551
563
  }
552
564
  const { reconcileParkedAgents: storeReconcile } = await import("./background-agent-store.js");
@@ -629,6 +641,8 @@ export async function rollbackParkedClaimLane(core, stores, ticket) {
629
641
  h.error = error;
630
642
  h.parkedCheckpointToken = undefined;
631
643
  h.resolveParkedStop = undefined;
644
+ h.parkedCompletionSink = undefined;
645
+ h.terminalNotifier = undefined;
632
646
  h.updatedAt = now;
633
647
  commitCompletionIdIfEmpty(h, rollbackCompletionIdCandidate);
634
648
  core.pokeBgQuiescence(h.owner);
@@ -782,6 +796,7 @@ export async function consumeParkedFlipLane(core, id, stores, ticket) {
782
796
  handle.status = "running";
783
797
  handle.parkedCheckpointToken = undefined;
784
798
  handle.resolveParkedStop = undefined;
799
+ handle.parkedCompletionSink = undefined;
785
800
  handle.updatedAt = Date.now();
786
801
  handle.completionId = undefined;
787
802
  handle.terminalNotified = undefined;
@@ -835,7 +850,7 @@ export function settleBackgroundAgentLane(core, id, outcome) {
835
850
  handle.status = outcome.status;
836
851
  mintCompletionId(handle);
837
852
  handle.notify = undefined;
838
- handle.onReapTerminal = undefined;
853
+ handle.terminalNotifier = undefined;
839
854
  for (const [, , qResolve] of handle.preAttachQueue ?? [])
840
855
  qResolve?.({ ok: false, reason: "not_running" });
841
856
  handle.preAttachQueue = undefined;
@@ -1134,7 +1149,7 @@ export function noteBackgroundAgentActivityLane(core, id, now = Date.now()) {
1134
1149
  return;
1135
1150
  handle.updatedAt = now;
1136
1151
  }
1137
- export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.now(), onTerminal) {
1152
+ export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.now()) {
1138
1153
  if (!Number.isFinite(staleMs) || staleMs <= 0) {
1139
1154
  throw new Error(`reapStaleSessionBackgroundAgents: staleMs must be a positive finite number of milliseconds (got ${String(staleMs)})`);
1140
1155
  }
@@ -1145,21 +1160,35 @@ export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.n
1145
1160
  if (now - handle.updatedAt <= staleMs)
1146
1161
  continue;
1147
1162
  core.markStopSource(handle.id, "system");
1148
- const reapTerminalNote = handle.onReapTerminal;
1163
+ const reapTerminalNote = handle.terminalNotifier;
1149
1164
  handle.abort.abort();
1150
1165
  settleBackgroundAgentLane(core, handle.id, {
1151
1166
  status: "killed",
1152
1167
  error: STALE_RUNNING_REAP_ATTRIBUTION,
1153
1168
  cycle: handle.reviveCycle ?? 0,
1154
1169
  });
1155
- if (reapTerminalNote !== undefined && handle.terminalNotified !== true) {
1156
- handle.terminalNotified = true;
1157
- onTerminal?.(reapTerminalNote);
1158
- }
1170
+ announceLandedAgentTerminal(core, handle, reapTerminalNote, { status: "killed" });
1159
1171
  reaped++;
1160
1172
  }
1161
1173
  return reaped;
1162
1174
  }
1175
+ export function announceLandedAgentTerminal(core, handle, notifier, ending) {
1176
+ if (notifier === undefined)
1177
+ return;
1178
+ core.notifyTerminalOnce(handle, () => notifier(ending));
1179
+ }
1180
+ function heldPark(core, id, token) {
1181
+ const h = core.handles.get(id);
1182
+ return h?.type === "background_agent" && h.status === "parked" && h.parkedCheckpointToken === token ? h : undefined;
1183
+ }
1184
+ function announceParkedEnding(core, handle, ending) {
1185
+ const parkLane = handle.parkedCompletionSink;
1186
+ const notifier = handle.terminalNotifier;
1187
+ handle.parkedCompletionSink = undefined;
1188
+ handle.terminalNotifier = undefined;
1189
+ if (parkLane !== undefined)
1190
+ announceLandedAgentTerminal(core, handle, notifier, { ...ending, parkLane });
1191
+ }
1163
1192
  export function unmarkRetainedContinuationLane(core, id) {
1164
1193
  const handle = core.handles.get(id);
1165
1194
  if (handle && handle.type === "background_agent")
@@ -1444,6 +1473,7 @@ export async function stopBackgroundAgentLane(core, handle) {
1444
1473
  }
1445
1474
  let stopWon = false;
1446
1475
  let arbiterUnreachable = false;
1476
+ const parkedToken = handle.parkedCheckpointToken;
1447
1477
  try {
1448
1478
  stopWon = await arbiter();
1449
1479
  }
@@ -1451,7 +1481,9 @@ export async function stopBackgroundAgentLane(core, handle) {
1451
1481
  stopWon = false;
1452
1482
  arbiterUnreachable = true;
1453
1483
  }
1454
- if (stopWon && handle.status === "parked") {
1484
+ const landed = stopWon ? heldPark(core, handle.id, parkedToken) : undefined;
1485
+ if (landed !== undefined) {
1486
+ handle = landed;
1455
1487
  core.markStopSource(handle.id, "parent");
1456
1488
  handle.status = "killed";
1457
1489
  handle.stoppedBy = handle.stopSource ?? "parent";
@@ -1460,6 +1492,7 @@ export async function stopBackgroundAgentLane(core, handle) {
1460
1492
  handle.parkedCheckpointToken = undefined;
1461
1493
  handle.resolveParkedStop = undefined;
1462
1494
  core.pokeBgQuiescence(handle.owner);
1495
+ announceParkedEnding(core, handle, { status: "killed" });
1463
1496
  {
1464
1497
  const lane = handle.durable;
1465
1498
  if (lane !== undefined) {
@@ -255,6 +255,9 @@ export interface DurableAgentLane {
255
255
  * flush success); past the ceiling the lane is abandoned loudly instead of retrying forever. */
256
256
  redrives?: number;
257
257
  }
258
+ /** What a background agent's row keeps of the store its child session lives in: that store's `acquire` (structural, so any
259
+ * session store fits — the type-only import is erased, the one-way import rule at the top is untouched). */
260
+ export type ChildSessionStore = Pick<import("./session.js").SessionStore, "acquire">;
258
261
  export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
259
262
  type: "background_agent";
260
263
  /** The spawning tree's cross-boundary token ({@link RegisterBackgroundAgentInput.crossBoundaryTree}), compared by identity. */
@@ -273,6 +276,10 @@ export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
273
276
  * durable record's copy — by the successful release of that session
274
277
  * ({@link TaskRegistry.releaseDurableTranscriptAnchor}). Read through `childSessionAnchorOf` only. */
275
278
  sessionId?: string;
279
+ /** The store the child's run holds that session through, written by the same bind and removed by the same release as
280
+ * `sessionId` — a reader of the child's transcript travels with its row, never with the runner that happens to read it.
281
+ * Process-local: the durable record keeps the id alone, and a revival's own bind brings its own runner's store. */
282
+ sessionStore?: ChildSessionStore;
276
283
  /** design/151 S1a — the durable write lane (present iff the registration wired a store). */
277
284
  durable?: DurableAgentLane;
278
285
  /** design/147 S2a — the RUNNING child run's notification injector (attached once its lane is
@@ -306,6 +313,12 @@ export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
306
313
  * Absent (cross-process row, no live park context) ⇒ TaskStop refuses honestly: the durable
307
314
  * approval inbox (server /decide) owns that arbitration. */
308
315
  resolveParkedStop?: () => Promise<boolean>;
316
+ /** #3334 — the completion sink the parked cycle's terminal frame is owed to (the lane its spawn or redemption completed
317
+ * into), recorded by the park beside {@link resolveParkedStop} and carried by the parked-resume handoff: the redemption
318
+ * completes there when its own call carries no lane. Absent ⇒ this process holds no park of the handle. */
319
+ parkedCompletionSink?: (n: import("./task-notification.js").TaskNotificationPayload, opts?: {
320
+ priority?: import("./task-notification.js").SystemInjectionPriority;
321
+ }) => unknown;
309
322
  /** S2b — resolvers of DIRECT (post-attach) deliveries currently awaiting the
310
323
  * injector; terminal settle/stop sweep these as not_running so a never-settling adapter can
311
324
  * never pin the sender's tool call. */
@@ -384,19 +397,28 @@ export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
384
397
  /** The LANDED attribution — set exactly when the handle goes `killed`, never rewritten afterwards
385
398
  * (first-writer-wins, same discipline as the terminal status itself). Absent on natural completion/failure. */
386
399
  stoppedBy?: StopSource;
387
- /** RB-375 A1 — the reap-time terminal notifier, hung by the spawn lanes (subagent.ts) right after
388
- * registration: composes and sends the SAME terminal faces (observer sink + parent notification)
389
- * the child's own unwind would, so {@link import("./task-registry.js").TaskRegistry.reapSessionBackground}
390
- * can emit the terminal news AT REAP TIME instead of waiting on the child's unwind (which blocks on
391
- * the in-flight tool actually honoring the abort — unbounded). The bash handle's `onTerminal` twin.
392
- * Cleared at the accepted settle (with `notify`); invoked at most once via {@link terminalNotified}. */
393
- onReapTerminal?: () => void;
400
+ /** The terminal notifier, hung by the spawn lanes (subagent.ts) right after registration: composes and sends the SAME
401
+ * terminal faces (observer sink + parent notification) the cycle's own unwind would, for a terminal the REGISTRY landed
402
+ * without that unwind — a reap of a running cycle (the unwind waits on the in-flight tool honoring the abort, unbounded),
403
+ * or a stop / an expiry of a parked one (its attempt returned at the park and reports nothing more). Called only through
404
+ * {@link import("./task-registry-agent.js").announceLandedAgentTerminal}; the bash handle's `onTerminal` twin. Cleared at
405
+ * the accepted settle and at every registry-landed terminal; invoked at most once via {@link terminalNotified}. */
406
+ terminalNotifier?: (ending: LandedAgentTerminal) => void;
394
407
  /** RB-375 A1 — terminal-notification once-latch (the bash/monitor `terminalNotified` twin): claimed
395
- * by whichever side reaches its emit point first — the session-release reap sweep (synchronous send)
396
- * or the child's own unwind (`TaskRegistry.claimAgentTerminalNotify`). The loser stays silent, so a
397
- * reaped child never double-announces. Cleared on revive (a new stop cycle owns its own terminal). */
408
+ * by whichever side reaches its emit point first — the registry announcing a terminal it landed (a reap, a parked
409
+ * stop or expiry) or the cycle's own unwind (`TaskRegistry.claimAgentTerminalNotify`). The loser stays silent, so a
410
+ * child never double-announces. Cleared on revive (a new stop cycle owns its own terminal). */
398
411
  terminalNotified?: true;
399
412
  }
413
+ /** A background agent's terminal the registry landed without its cycle's attempt, as {@link BackgroundAgentTaskHandle.terminalNotifier}
414
+ * receives it: the landed `status` (and `error`, for a failed one), and — when the ended cycle was PARKED — `parkLane`, the
415
+ * lane the park recorded its debt on ({@link BackgroundAgentTaskHandle.parkedCompletionSink}), where the parent face goes.
416
+ * Absent ⇔ the ended cycle was running: its attempt holds the lane. */
417
+ export interface LandedAgentTerminal {
418
+ status: "killed" | "failed";
419
+ error?: string;
420
+ parkLane?: NonNullable<BackgroundAgentTaskHandle["parkedCompletionSink"]>;
421
+ }
400
422
  /** design/135 G2 (Monitor): injectable timer/clock seam for the monitor watcher — the 200ms batch window
401
423
  * and the timeout/storm checks must be drivable by a test without real sleeps (design/87 discipline).
402
424
  * `setInterval` receives an ASYNC tick (the default adapter fires it void; a fake can await it). */
@@ -769,7 +791,7 @@ export interface RegistryCore {
769
791
  handles: Map<string, RegisteredTaskHandle>;
770
792
  mintTaskId(type: SemaTaskType): string;
771
793
  markStopSource(id: string, source: StopSource): void;
772
- notifyTerminalOnce(handle: BackgroundBashTaskHandle | MonitorTaskHandle, send: () => void): void;
794
+ notifyTerminalOnce(handle: BackgroundBashTaskHandle | MonitorTaskHandle | BackgroundAgentTaskHandle, send: () => void): void;
773
795
  pokeBgQuiescence(owner: string | undefined): void;
774
796
  }
775
797
  /** writer-lease renewal period for armed durable rows (see ensureDurableHeartbeat).
@@ -38,10 +38,11 @@ export function registerWorkflowLane(core, input) {
38
38
  }, (err) => {
39
39
  if (handle.status !== "cancelled")
40
40
  handle.status = "failed";
41
- handle.error = boundedRedactedSummary(thrownText(err), 500);
42
41
  const settledRun = settledRunOf(input.handle.done);
43
- if (settledRun?.completionId !== undefined)
44
- handle.completionId = settledRun.completionId;
42
+ const settleId = settledRun?.completionId;
43
+ handle.error = boundedRedactedSummary(thrownText(err), 500);
44
+ if (settleId !== undefined)
45
+ handle.completionId = settleId;
45
46
  handle.updatedAt = Date.now();
46
47
  });
47
48
  return id;
@@ -9,7 +9,9 @@ import { type TaskArtifactSeat } from "./tool-result-store.js";
9
9
  import { type SemaTaskType, type StopSource, type SemaTaskStatus, type TaskRetrievalStatus, type UnifiedTaskOutput, type UnifiedTaskResult, type SemaTaskHandle, type TaskAccess, type BackgroundAgentTaskHandle, type MonitorTimers, type RegisterMonitorInput, type RegisterWorkflowInput, canAccessWorkflowRun, clipTaskOutput, MONITOR_BATCH_WINDOW_MS, MONITOR_DEFAULT_TIMEOUT_MS, MONITOR_MAX_TIMEOUT_MS, MONITOR_MAX_BATCHES_PER_MINUTE } from "./task-registry-shared.js";
10
10
  export { normalizeAgentName, DURABLE_AGENT_HEARTBEAT_MS, DURABLE_AGENT_HANDLE_RE, BG_AGENT_REAP_STOP_ERROR, engineAgentName, chosenAgentName } from "./task-registry-shared.js";
11
11
  export type { ParkedClaimTicket, RegisterBackgroundAgentInput } from "./task-registry-shared.js";
12
- import type { RegisterBackgroundAgentInput, ParkedClaimTicket } from "./task-registry-shared.js";
12
+ import type { RegisterBackgroundAgentInput, ParkedClaimTicket, ChildSessionStore, LandedAgentTerminal } from "./task-registry-shared.js";
13
+ import type { ChildSessionAnchor } from "./task-registry-agent.js";
14
+ import { type DelegationOccupant } from "./task-registry-agent.js";
13
15
  import { type AgentStateSource } from "./agent-state.js";
14
16
  import type { CheckpointSeat } from "./checkpoint-seat.js";
15
17
  export type { SemaTaskType, StopSource, SemaTaskStatus, TaskRetrievalStatus, UnifiedTaskOutput, SemaTaskHandle, TaskAccess, MonitorTimers, RegisterMonitorInput, RegisterWorkflowInput, };
@@ -155,8 +157,8 @@ export declare class TaskRegistry {
155
157
  * (cap overflow dropped the watcher; the owner's tasks may still be running — the subscriber must
156
158
  * NOT treat this as quiescence). */
157
159
  private bgQuiescenceWatchers;
158
- /** One host-callback isolation scope for this registry's five notification seams (reap terminal
159
- * notifier, session-reap hooks, quiescence fire + cap-overflow eviction, terminal-once send). Same swallow
160
+ /** One host-callback isolation scope for this registry's notification seams (session-reap hooks, quiescence fire +
161
+ * cap-overflow eviction, the terminal-once send every background kind's terminal takes). Same swallow
160
162
  * as the five hand-written try/catches it replaced, now counted per site and readable for diagnostics. */
161
163
  private readonly notifier;
162
164
  /** The read face for this registry's CONTAINED host-callback failures (site → count).
@@ -218,7 +220,9 @@ export declare class TaskRegistry {
218
220
  /** The successful release of child session `sessionId` ends row `id`'s anchor on it — handle and durable
219
221
  * record together, and only while the row still names that session (see {@link releaseDurableTranscriptAnchorLane}). */
220
222
  releaseDurableTranscriptAnchor(id: string, sessionId: string): void;
221
- bindBackgroundAgentSession(id: string, sessionId: string): void;
223
+ /** Anchor row `id` to its child session `sessionId`, held through `store` — the store the child's run creates or resumes that
224
+ * session in (see {@link bindBackgroundAgentSessionLane}). */
225
+ bindBackgroundAgentSession(id: string, sessionId: string, store: ChildSessionStore): void;
222
226
  registerBackgroundAgent(input: RegisterBackgroundAgentInput): string;
223
227
  /** #22 — persist this leg's org-memory admission verdict on the durable row (the cross-process
224
228
  * revival's only carrier). See {@link recordBackgroundAgentOrgAdmissionLane}. */
@@ -227,7 +231,11 @@ export declare class TaskRegistry {
227
231
  checkpointToken: string;
228
232
  seq?: number;
229
233
  resolveStop?: () => Promise<boolean>;
234
+ completionSink?: BackgroundAgentTaskHandle["parkedCompletionSink"];
230
235
  }): "parked" | undefined;
236
+ /** #3334 — the completion sink a PARKED handle's cycle is still owed to in this process (the park's own lane), for the
237
+ * redemption to complete into when its call carries none; `undefined` when this process holds no park of `id`. */
238
+ parkedCompletionSink(id: string): BackgroundAgentTaskHandle["parkedCompletionSink"];
231
239
  reconcileParkedAgents(stores: {
232
240
  agentStore: import("./background-agent-store.js").BackgroundAgentStore;
233
241
  checkpointStore: Pick<import("./checkpoint-store.js").CheckpointStore, "get">;
@@ -312,6 +320,9 @@ export declare class TaskRegistry {
312
320
  * contract (the caps check and the registration form one atomic segment). See
313
321
  * {@link activeDelegationHandlesLane}. */
314
322
  activeDelegationHandles(scope: string, rootSessionId: string): string[];
323
+ /** The same rows as {@link activeDelegationHandles}, each with its addressing name and whether `caller` reaches it — what a refusal
324
+ * of one more child may tell its caller about who holds the tree's slots. See {@link activeDelegationOccupantsLane}. */
325
+ activeDelegationOccupants(scope: string, rootSessionId: string, caller?: TaskAccess): DelegationOccupant[];
315
326
  /** ASYNC (revive arbitration) — the durable half is a guarded ownership claim on the row (awaited before the
316
327
  * in-memory flip), so this leg and a cross-process claim arbitrate in one domain instead of both
317
328
  * believing they own the cycle. See {@link reviveBackgroundAgentLane}. */
@@ -334,10 +345,10 @@ export declare class TaskRegistry {
334
345
  }): "completed" | "failed" | "killed" | undefined;
335
346
  unmarkRetainedContinuation(id: string): void;
336
347
  attachAgentNotify(id: string, notify: NonNullable<BackgroundAgentTaskHandle["notify"]>, cycle?: number): void;
337
- /** RB-375 A1 — hang the reap-time terminal notifier on a live background-agent row (see
338
- * {@link BackgroundAgentTaskHandle.onReapTerminal}). No-op on unknown/terminal rows: a row that
339
- * already settled has its unwind (or the settle itself) owning the terminal story. */
340
- attachAgentTerminalNotifier(id: string, fn: () => void): void;
348
+ /** RB-375 A1 — hang the terminal notifier on a live background-agent row: what the registry calls, once, when it lands
349
+ * that row's terminal without the cycle's attempt (see {@link BackgroundAgentTaskHandle.terminalNotifier}). No-op on
350
+ * unknown/terminal rows: a row that already settled has its unwind (or the settle itself) owning the terminal story. */
351
+ attachAgentTerminalNotifier(id: string, fn: (ending: LandedAgentTerminal) => void): void;
341
352
  /** RB-375 A1 — the child-unwind side of the terminal-notification once-latch: returns `true` when
342
353
  * the CALLER now owns sending the terminal faces (and claims the latch), `false` when the reap
343
354
  * sweep already sent them (the caller must stay silent — the registry row still takes the settle's
@@ -535,7 +546,7 @@ export declare class TaskRegistry {
535
546
  * (`abortBackgroundAgentsForOwner` in the child's unwind) — this function never sees those rows,
536
547
  * so they are NOT counted here.
537
548
  * RB-375 A1 — a directly reaped `background_agent` row's terminal notification is sent
538
- * SYNCHRONOUSLY by this sweep (through the spawn-lane-hung {@link BackgroundAgentTaskHandle.onReapTerminal},
549
+ * SYNCHRONOUSLY by this sweep (through the spawn-lane-hung {@link BackgroundAgentTaskHandle.terminalNotifier},
539
550
  * once-latched against the child's own unwind), so consumers observe the terminal immediately
540
551
  * instead of after the in-flight tool honors the abort (unbounded). */
541
552
  reapSessionBackground(sessionId: string, scope?: string): number;
@@ -609,7 +620,9 @@ export declare class TaskRegistry {
609
620
  * running-row eviction). Cheap no-op without watchers; fires + removes the owner's whole set only
610
621
  * when the running count is zero (the LAST settling task's poke wins — count-zero judgement). */
611
622
  private pokeBgQuiescence;
612
- /** fidelity R1-3: the terminal-notification once-latch. Checks-and-sets BEFORE sending (single-threaded,
623
+ /** fidelity R1-3: the terminal-notification once-latch — every background kind's (an agent's terminal the registry
624
+ * lands without its cycle's attempt comes through here as well, `announceLandedAgentTerminal`; the attempt's own
625
+ * unwind claims the same latch with `claimAgentTerminalNotify`). Checks-and-sets BEFORE sending (single-threaded,
613
626
  * no await between check and set — atomic), so a racing producer pair (a teardown settle vs an in-flight
614
627
  * watcher tick that passed its status gate before the settle landed) emits exactly ONE terminal notice.
615
628
  * The latch stays set even if the sink throws — a faulty sink must not re-arm it. */
@@ -659,6 +672,10 @@ export declare class TaskRegistry {
659
672
  * cap ({@link list}'s): the one reading of a leg's live background tasks (its end's {@link owedDeliveries}, the post-compaction
660
673
  * listing and the resume's orphan diff, the suspend's snapshot), each consumer projecting its own columns from it. */
661
674
  liveTasks(access: TaskAccess): TaskListRow[];
675
+ /** The child session task `taskId`'s row is anchored to — its id and the store the child's run holds it through — when
676
+ * `access` reaches the row (the reach {@link list} reads with): `undefined` for an unknown or out-of-reach id, `null` for a
677
+ * reached row with no anchor (no background agent's row, not bound yet, or released). */
678
+ anchoredSession(taskId: string, access: TaskAccess): ChildSessionAnchor | null | undefined;
662
679
  /** Every row `access` reaches, newest first, in {@link list}'s projection — the one walk both readings take. */
663
680
  private rowsUnder;
664
681
  /** Throttled {@link gc} for hot-path callers (design/115 review B5): prepare-task runs once per task,
@@ -12,7 +12,7 @@ import { registerWorkflowLane, pollWorkflowLane, stopWorkflowLane } from "./task
12
12
  import { mintCompletionId, taskReadHandleText, canAccessWorkflowRun, formatWorkflowRun, clipTaskOutput, assertOwnership, sleepPollStep, statusFromBackground, rollSpoolText, accountDroppedBytes, renderSpoolBody, stdoutHeadingOf, REPLAY_FACE, SPOOL_REPLAY, INCREMENT_REPLAY, spoolDropNote, droppedGapNote, alreadyTerminalStopNote, terminalTaskSummary, TASK_OUTPUT_MAX_CHARS, MONITOR_BATCH_WINDOW_MS, MONITOR_DEFAULT_TIMEOUT_MS, MONITOR_MAX_TIMEOUT_MS, MONITOR_MAX_BATCHES_PER_MINUTE, canAccess, DURABLE_AGENT_HANDLE_RE, } from "./task-registry-shared.js";
13
13
  export { normalizeAgentName, DURABLE_AGENT_HEARTBEAT_MS, DURABLE_AGENT_HANDLE_RE, BG_AGENT_REAP_STOP_ERROR, engineAgentName, chosenAgentName } from "./task-registry-shared.js";
14
14
  import { TASK_STOP_TOOL_NAME, TASK_STOP_MISSING_ID_MESSAGE, TASK_STOP_PARAMS, TASK_STOP_DESCRIPTION, resolveTaskIdArg } from "./task-tool-shape.js";
15
- import { durableAgentArmedLane, durableAgentRowProbeLane, beginDurableClaimLane, endDurableClaimLane, reapDurableAgentsLane, noteBackgroundAgentActivityLane, reapStaleSessionBackgroundAgentsLane, releaseDurableTranscriptAnchorLane, bindBackgroundAgentSessionLane, childSessionAnchorOf, registerBackgroundAgentLane, recordBackgroundAgentOrgAdmissionLane, parkBackgroundAgentLane, reconcileParkedAgentsLane, claimParkedAgentLane, rollbackParkedClaimLane, consumeParkedFlipLane, finalizeParkedResumeLane, settleBackgroundAgentLane, abortBackgroundAgentsForOwnerLane, serveDurableAgentRowLane, resolveBackgroundAgentByNameLane, backgroundAgentCycleSeqLane, activeDelegationHandlesLane, markRetainedContinuationLane, reviveBackgroundAgentLane, settleRevivedAgentLane, unmarkRetainedContinuationLane, attachAgentNotifyLane, deliverToRunningAgentLane, runningBackgroundAgentLabelsLane, runningAgentFooterLane, notFoundRunningAgentsTail, pollBackgroundAgentLane, stopBackgroundAgentLane, } from "./task-registry-agent.js";
15
+ import { durableAgentArmedLane, durableAgentRowProbeLane, beginDurableClaimLane, endDurableClaimLane, reapDurableAgentsLane, noteBackgroundAgentActivityLane, reapStaleSessionBackgroundAgentsLane, announceLandedAgentTerminal, releaseDurableTranscriptAnchorLane, bindBackgroundAgentSessionLane, childSessionAnchorOf, registerBackgroundAgentLane, recordBackgroundAgentOrgAdmissionLane, parkBackgroundAgentLane, reconcileParkedAgentsLane, claimParkedAgentLane, rollbackParkedClaimLane, consumeParkedFlipLane, finalizeParkedResumeLane, settleBackgroundAgentLane, abortBackgroundAgentsForOwnerLane, serveDurableAgentRowLane, resolveBackgroundAgentByNameLane, backgroundAgentCycleSeqLane, activeDelegationHandlesLane, activeDelegationOccupantsLane, markRetainedContinuationLane, reviveBackgroundAgentLane, settleRevivedAgentLane, unmarkRetainedContinuationLane, attachAgentNotifyLane, deliverToRunningAgentLane, runningBackgroundAgentLabelsLane, runningAgentFooterLane, notFoundRunningAgentsTail, pollBackgroundAgentLane, stopBackgroundAgentLane, } from "./task-registry-agent.js";
16
16
  import { mountRuleFace, toolFace } from "./tool-catalog-entries.js";
17
17
  import { thrownText } from "./thrown-value.js";
18
18
  import { agentStateSourceOfHandle, agentStateSourceOfRecord, agentStateSummary, readAgentState } from "./agent-state.js";
@@ -168,8 +168,8 @@ export class TaskRegistry {
168
168
  releaseDurableTranscriptAnchor(id, sessionId) {
169
169
  return releaseDurableTranscriptAnchorLane(this.core, id, sessionId);
170
170
  }
171
- bindBackgroundAgentSession(id, sessionId) {
172
- return bindBackgroundAgentSessionLane(this.core, id, sessionId);
171
+ bindBackgroundAgentSession(id, sessionId, store) {
172
+ return bindBackgroundAgentSessionLane(this.core, id, sessionId, store);
173
173
  }
174
174
  registerBackgroundAgent(input) {
175
175
  return registerBackgroundAgentLane(this.core, input);
@@ -180,6 +180,10 @@ export class TaskRegistry {
180
180
  parkBackgroundAgent(id, park) {
181
181
  return parkBackgroundAgentLane(this.core, id, park);
182
182
  }
183
+ parkedCompletionSink(id) {
184
+ const handle = this.core.handles.get(id);
185
+ return handle?.type === "background_agent" && handle.status === "parked" ? handle.parkedCompletionSink : undefined;
186
+ }
183
187
  async reconcileParkedAgents(stores, scope, now, opts) {
184
188
  return reconcileParkedAgentsLane(this.core, stores, scope, now, opts);
185
189
  }
@@ -202,9 +206,7 @@ export class TaskRegistry {
202
206
  return noteBackgroundAgentActivityLane(this.core, id, now);
203
207
  }
204
208
  reapStaleSessionBackgroundAgents(staleMs, now) {
205
- return reapStaleSessionBackgroundAgentsLane(this.core, staleMs, now, (note) => {
206
- this.notifier.notify(() => note(), "taskRegistry.reapTerminalNote");
207
- });
209
+ return reapStaleSessionBackgroundAgentsLane(this.core, staleMs, now);
208
210
  }
209
211
  abortBackgroundAgentsForOwner(access, opts) {
210
212
  return abortBackgroundAgentsForOwnerLane(this.core, access, opts);
@@ -231,6 +233,9 @@ export class TaskRegistry {
231
233
  activeDelegationHandles(scope, rootSessionId) {
232
234
  return activeDelegationHandlesLane(this.core, scope, rootSessionId);
233
235
  }
236
+ activeDelegationOccupants(scope, rootSessionId, caller) {
237
+ return activeDelegationOccupantsLane(this.core, scope, rootSessionId, caller);
238
+ }
234
239
  reviveBackgroundAgent(id, access, abort) {
235
240
  return reviveBackgroundAgentLane(this.core, id, access, abort);
236
241
  }
@@ -249,7 +254,7 @@ export class TaskRegistry {
249
254
  return;
250
255
  if (handle.status !== "running" && handle.status !== "parked" && handle.status !== "pending")
251
256
  return;
252
- handle.onReapTerminal = fn;
257
+ handle.terminalNotifier = fn;
253
258
  }
254
259
  claimAgentTerminalNotify(id) {
255
260
  const handle = this.handles.get(id);
@@ -567,13 +572,10 @@ export class TaskRegistry {
567
572
  if (!canAccess(handle, access))
568
573
  continue;
569
574
  this.markStopSource(handle.id, "system");
570
- const reapTerminalNote = handle.onReapTerminal;
575
+ const reapTerminalNote = handle.terminalNotifier;
571
576
  handle.abort.abort();
572
577
  this.settleBackgroundAgent(handle.id, { status: "killed", error: "session released", cycle: handle.reviveCycle ?? 0 });
573
- if (reapTerminalNote !== undefined && handle.terminalNotified !== true) {
574
- handle.terminalNotified = true;
575
- this.notifier.notify(() => reapTerminalNote(), "taskRegistry.reapTerminalNote");
576
- }
578
+ announceLandedAgentTerminal(this.core, handle, reapTerminalNote, { status: "killed" });
577
579
  reaped++;
578
580
  }
579
581
  this.pokeBgQuiescence(sessionId);
@@ -1033,6 +1035,10 @@ The durable record is still marked running (last update ${new Date(row.updatedAt
1033
1035
  liveTasks(access) {
1034
1036
  return this.rowsUnder(access).filter((t) => t.status === "pending" || t.status === "running" || t.status === "parked");
1035
1037
  }
1038
+ anchoredSession(taskId, access) {
1039
+ const h = this.handles.get(taskId);
1040
+ return h !== undefined && canAccess(h, access) ? (childSessionAnchorOf(h) ?? null) : undefined;
1041
+ }
1036
1042
  rowsUnder(access) {
1037
1043
  const out = [];
1038
1044
  for (const h of this.handles.values()) {
@@ -1047,7 +1053,7 @@ The durable record is still marked running (last update ${new Date(row.updatedAt
1047
1053
  ...((h.type === "background_bash" || h.type === "monitor") && shellRowRetained(h) ? { retained: true } : {}),
1048
1054
  ...(h.description !== undefined ? { description: h.description } : {}),
1049
1055
  ...(h.toolUseId !== undefined ? { toolUseId: h.toolUseId } : {}),
1050
- ...(childSession !== undefined ? { sessionId: childSession } : {}),
1056
+ ...(childSession !== undefined ? { sessionId: childSession.sessionId } : {}),
1051
1057
  createdAt: h.createdAt,
1052
1058
  updatedAt: h.updatedAt,
1053
1059
  });
@@ -10,9 +10,9 @@ import type { NestedUsage } from "./tool-spec.js";
10
10
  /**
11
11
  * `"suspended"` (design/45) is a **non-terminal** outcome: the task hit a durable tool-policy gate
12
12
  * (`ask` with a `CheckpointStore` wired) and persisted a checkpoint instead of finishing — resume it
13
- * with `runner.resume(checkpointToken, outcome)`. v1 contract: it is only safe at the **top-level
14
- * `runTask` boundary**; the orchestrators (cascade/verify/repair-loop) map an unexpected `suspended`
15
- * to `failed` + `errorCode:"unexpected.suspended"` and pass the token up (§11 Q6, hard boundary).
13
+ * with `runner.resume(checkpointToken, outcome)`. A nested orchestrator's boundary turns the pause into a
14
+ * `failed` terminal that carries it (`mapNestedSuspend` in `src/agents/suspend-guard.ts` states which
15
+ * orchestrators do, and the entry that continues the pause).
16
16
  *
17
17
  * `"needs_review"` (design/76 §2.5, dry-run / shadow; design/80 D-B, plan-gate) is also a **non-terminal,
18
18
  * resumable** outcome, but a DISTINCT one: it is the REVIEW-PAUSE terminal a human/judge must clear. Two
@@ -22,8 +22,8 @@ import type { NestedUsage } from "./tool-spec.js";
22
22
  * profile's plan-gate produced a proposed PLAN a human must approve/edit/reject BEFORE any step runs, resumed
23
23
  * with a `plan_review` outcome. Both are DISJOINT from `"suspended"`: that is a PRE-ACTION approval of a TOOL
24
24
  * CALL (resumed with `policy_ask`); these are human REVIEWS (the distinct gate.kind picks the resume outcome).
25
- * Orchestrators that map an unexpected `suspended` should map an unexpected `needs_review` the same
26
- * hard-boundary way (it is, like `suspended`, only safe at the top-level `runTask` boundary).
25
+ * A `needs_review` pause meets the same nested boundary as a `suspended` one (`mapNestedSuspend`: code
26
+ * `unexpected.needs_review`).
27
27
  */
28
28
  /**
29
29
  * Terminal vs waiting. Three words are TERMINAL — the leg is over and nobody is expected to act: `completed`,
@@ -3,7 +3,7 @@ import { thrownText } from "./thrown-value.js";
3
3
  import { strayMembersOf } from "./own-property-receipt.js";
4
4
  export const TASK_SPEC_MEMBERS = Object.keys({
5
5
  taskId: 0, objective: 0, principal: 0, actor: 0, runOrigin: 0, interactionPosture: 0, approvalReach: 0, interactiveQuestionFallback: 0,
6
- images: 0, userAttachments: 0, sessionId: 0, projectId: 0, requireExistingSession: 0, oneShot: 0, clientContext: 0, resumeAt: 0,
6
+ images: 0, userAttachments: 0, sessionId: 0, projectId: 0, workspace: 0, requireExistingSession: 0, oneShot: 0, clientContext: 0, resumeAt: 0,
7
7
  resumeAtMode: 0, model: 0, modelRole: 0, roles: 0, compactionModel: 0, advisorModel: 0, thinking: 0, systemPrompt: 0,
8
8
  promptRole: 0, promptForm: 0, promptBinding: 0, appendSystemPrompt: 0, outputStyle: 0, memory: 0, suggestNextPrompts: 0, fileHistory: 0,
9
9
  projectMemory: 0, restoreFiles: 0, acceptPartialRestore: 0, rewindFilesTo: 0, tools: 0, allowTools: 0, excludeTools: 0, excludeAllTools: 0,
@@ -13,6 +13,7 @@ import type { A2aServerSpec, McpServerSpec } from "./mcp-server-spec.js";
13
13
  import type { ModelRef, ModelRole, ModelRoles } from "./model-seat.js";
14
14
  import type { TaskLimits } from "./task-limits.js";
15
15
  import type { ToolSpec } from "./tool-spec.js";
16
+ import type { WorkspaceDeclaration } from "./session-checkout.js";
16
17
  /** design/169-F — knobs for the opt-in stale tool-result offload (see
17
18
  * `TaskSpec.compaction.staleToolResultOffload`, where the semantics are documented). */
18
19
  export interface StaleToolResultOffloadOptions {
@@ -202,6 +203,25 @@ export interface TaskSpec {
202
203
  * `workspace_changed.project`; read it there rather than re-deriving it. Memory keys only by the marker.
203
204
  */
204
205
  projectId?: string;
206
+ /**
207
+ * The session's workspace — send the SAME declaration on every leg (a resumed leg's config included). The session's first
208
+ * leg turns it into the session's checkout, an immutable record every later leg is judged against:
209
+ * - `isolation: "worktree"`: the session works in its OWN managed tree of the task root's repository, minted on the first
210
+ * leg at `<repository root>/.sema/worktrees/<name>` on branch `sema/<name>` (`name` absent ⇒ derived from the session id;
211
+ * `baseRef`: `"fresh"` default, or `"head"`). Every leg's task root is the task root's place in that tree; the base
212
+ * checkout is outside the leg's write roots. The tree outlives every leg and env; `releaseSessionCheckout` removes it.
213
+ * - `sources`: the commit the session's code starts from, per root (`{ root, remote, sha, ref? }`): checked on the first
214
+ * leg (the checkout at that root must be at `sha`; with isolation the task root's tree is minted at it).
215
+ * Refusals, each before the leg starts: a malformed declaration ⇒ `config.session_workspace_invalid` (also: a writable
216
+ * `additionalDirectories` entry that reaches into the isolated base checkout, a remote carrying a credential); a declaration
217
+ * that differs from the first leg's, appears on a session that already ran without one, or goes missing ⇒
218
+ * `config.session_workspace_changed`; the tree cannot be made ⇒ `workspace.isolation_unavailable` (the reason named,
219
+ * `probeWorktreeCapability` judges the same); a checkout not at the declared commit ⇒ `workspace.source_mismatch`; the
220
+ * record cannot be read ⇒ `workspace.checkout_unavailable`; the tree is gone ⇒ `workspace.checkout_missing` (never a
221
+ * fallback to the base checkout). A fork does not inherit the checkout. Every leg's `workspace_changed` frame carries it
222
+ * (`session`).
223
+ */
224
+ workspace?: WorkspaceDeclaration;
205
225
  /**
206
226
  * design/114 Phase3 — with `sessionId` set, REQUIRE that session to already exist: if it is gone (e.g. a
207
227
  * non-durable store lost it across a restart, or a typo'd id), the run FAILS LOUD (`resume.session_not_found`)
@@ -700,7 +720,7 @@ export interface TaskSpec {
700
720
  * (same turn, no checkpoint) — this option is the durable FALLBACK for when no live approver can answer,
701
721
  * not an "always park" mandate. It is the cross-process / long / headless version of the `onAsk` gate.
702
722
  * **opt-in, default-off**: unset → the synchronous `onAsk`-only path (a headless ask then auto-denies).
703
- * Only safe at the top-level `runTask` (orchestrators fail-fast, §11 Q6).
723
+ * A nested orchestrator stops at such a pause and hands it back (`mapNestedSuspend` in `src/agents/suspend-guard.ts` states how it continues).
704
724
  *
705
725
  * **Precedence vs a live `onAsk`:** "live approver" means a FUNCTION-valued `spec.onAsk ?? deps.onAsk`.
706
726
  * With one wired, BOTH plain and SAFETY asks (egress/irreversibility tightens) resolve through it
@@ -79,8 +79,8 @@ export type TerminalCause = {
79
79
  * and the retry budget is spent (nothing ran for them).
80
80
  * - `"model.truncated_output_exhausted"` — the model's answer kept ending on the output cap and the
81
81
  * continue budget is spent (`result` holds the text it reached).
82
- * A NESTED orchestrator that met a durable pause it cannot drive stamps `"unexpected.suspended"` /
83
- * `"unexpected.needs_review"` and carries the pause on {@link nestedPause}.
82
+ * `"unexpected.suspended"` / `"unexpected.needs_review"` — a nested orchestrator stopped at a durable pause and
83
+ * carries it on {@link nestedPause} (`mapNestedSuspend` states which orchestrators, and how the pause continues).
84
84
  */
85
85
  code?: string;
86
86
  /** Human-readable failure text. */
@@ -100,10 +100,10 @@ export type TerminalCause = {
100
100
  detail?: TerminalFailureDetail;
101
101
  /**
102
102
  * The durable pause this failure STANDS IN FOR — set only by the nested hard boundary
103
- * (`mapNestedSuspend`): an orchestrator's nested leg paused on a durable gate, the orchestrator cannot
104
- * drive a resume from the inside, so at ITS boundary the pause is a failure — but the pause's own
105
- * cause travels here verbatim so the top-level caller keeps the recovery capability
106
- * (`nestedPause.token` → `runner.resume`). Absent on every failure the engine itself assembles.
103
+ * (`mapNestedSuspend`, which states which orchestrators map and the entry that continues the pause): an
104
+ * orchestrator's nested leg paused on a durable gate, so at ITS boundary the pause is a failure — but the
105
+ * pause's own cause travels here verbatim so the host keeps the recovery capability (`nestedPause.token`).
106
+ * Absent on every failure the engine itself assembles.
107
107
  */
108
108
  nestedPause?: PausedCause;
109
109
  /**