@sema-agent/core 7.62.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 (193) hide show
  1. package/CHANGELOG.md +528 -0
  2. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  3. package/dist/agents/subagent-transcript-placement.js +14 -0
  4. package/dist/agents/subagent.js +82 -51
  5. package/dist/brain/route-adjudicator.js +9 -4
  6. package/dist/core/approval-object.js +1 -1
  7. package/dist/core/arg-summary.js +1 -1
  8. package/dist/core/ask-question.d.ts +2 -2
  9. package/dist/core/canonical-json.d.ts +23 -13
  10. package/dist/core/canonical-json.js +4 -4
  11. package/dist/core/checkpoint-queries.d.ts +47 -4
  12. package/dist/core/checkpoint-queries.js +36 -16
  13. package/dist/core/checkpoint-requirements.d.ts +3 -3
  14. package/dist/core/checkpoint-requirements.js +2 -1
  15. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  16. package/dist/core/checkpoint-row-verdict.js +22 -2
  17. package/dist/core/checkpoint-store.d.ts +23 -10
  18. package/dist/core/checkpoint-store.js +45 -4
  19. package/dist/core/compliance.d.ts +6 -2
  20. package/dist/core/compliance.js +3 -3
  21. package/dist/core/engine-attestation.d.ts +1 -1
  22. package/dist/core/engine-notice.d.ts +19 -4
  23. package/dist/core/git-worktree-env.d.ts +62 -3
  24. package/dist/core/git-worktree-env.js +91 -30
  25. package/dist/core/governance-codes.d.ts +7 -3
  26. package/dist/core/governance-codes.js +13 -3
  27. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  28. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  29. package/dist/core/memory-engine/consolidation.d.ts +73 -10
  30. package/dist/core/memory-engine/consolidation.js +167 -11
  31. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  32. package/dist/core/memory-engine/data-plane.js +11 -6
  33. package/dist/core/memory-engine/delegation-settlement.d.ts +37 -35
  34. package/dist/core/memory-engine/delegation-settlement.js +53 -59
  35. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  36. package/dist/core/memory-engine/dual-root.js +9 -5
  37. package/dist/core/memory-engine/engine.d.ts +98 -35
  38. package/dist/core/memory-engine/engine.js +477 -380
  39. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  40. package/dist/core/memory-engine/entry-scan.js +3 -0
  41. package/dist/core/memory-engine/file-backend.d.ts +29 -3
  42. package/dist/core/memory-engine/file-backend.js +66 -35
  43. package/dist/core/memory-engine/index.d.ts +7 -7
  44. package/dist/core/memory-engine/index.js +6 -6
  45. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  46. package/dist/core/memory-engine/landing-admission.js +3 -3
  47. package/dist/core/memory-engine/layout.d.ts +121 -45
  48. package/dist/core/memory-engine/layout.js +252 -102
  49. package/dist/core/memory-engine/memory-backend-contract.d.ts +19 -1
  50. package/dist/core/memory-engine/memory-backend-contract.js +320 -0
  51. package/dist/core/memory-engine/memory-deployment.d.ts +31 -8
  52. package/dist/core/memory-engine/memory-deployment.js +26 -12
  53. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  54. package/dist/core/memory-engine/scope-contract.js +68 -19
  55. package/dist/core/memory-engine/session-write-home.d.ts +3 -1
  56. package/dist/core/memory-engine/session-write-home.js +1 -1
  57. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  58. package/dist/core/memory-engine/sync-client.js +7 -0
  59. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  60. package/dist/core/memory-engine/sync-report.js +6 -2
  61. package/dist/core/memory-engine/tools.d.ts +2 -2
  62. package/dist/core/memory-engine/tools.js +10 -10
  63. package/dist/core/memory-engine/types.d.ts +118 -19
  64. package/dist/core/memory-engine/types.js +1 -0
  65. package/dist/core/memory.js +15 -6
  66. package/dist/core/mods/stations.d.ts +20 -1
  67. package/dist/core/mods/stations.js +21 -2
  68. package/dist/core/park-selfcheck.js +2 -2
  69. package/dist/core/pause-registry.d.ts +2 -0
  70. package/dist/core/pause-registry.js +3 -0
  71. package/dist/core/permission-rule-consent.d.ts +10 -3
  72. package/dist/core/permission-rule-consent.js +37 -24
  73. package/dist/core/permission-rule-store.d.ts +35 -1
  74. package/dist/core/permission-rule-store.js +27 -8
  75. package/dist/core/read-only-shell.js +3 -2
  76. package/dist/core/redaction-marks.d.ts +8 -0
  77. package/dist/core/redaction-marks.js +6 -0
  78. package/dist/core/remote-env.d.ts +12 -1
  79. package/dist/core/remote-env.js +3 -0
  80. package/dist/core/runner/child-tree.d.ts +29 -3
  81. package/dist/core/runner/child-tree.js +39 -16
  82. package/dist/core/runner/contracts.d.ts +18 -9
  83. package/dist/core/runner/gate-exit.js +2 -2
  84. package/dist/core/runner/inherited-ask-grants.js +1 -1
  85. package/dist/core/runner/memory-consolidation-driver.d.ts +6 -3
  86. package/dist/core/runner/memory-consolidation-driver.js +4 -4
  87. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  88. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  89. package/dist/core/runner/person-path-rows.d.ts +8 -3
  90. package/dist/core/runner/person-path-rows.js +5 -1
  91. package/dist/core/runner/placement-fence.d.ts +12 -0
  92. package/dist/core/runner/placement-fence.js +20 -6
  93. package/dist/core/runner/prepare-ask-lane.js +2 -2
  94. package/dist/core/runner/prepare-caps-and-workflow.d.ts +4 -1
  95. package/dist/core/runner/prepare-caps-and-workflow.js +5 -2
  96. package/dist/core/runner/prepare-execution-env.js +17 -6
  97. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  98. package/dist/core/runner/prepare-hands-readface.js +4 -3
  99. package/dist/core/runner/prepare-inherited-gate.d.ts +10 -8
  100. package/dist/core/runner/prepare-inherited-gate.js +8 -4
  101. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  102. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  103. package/dist/core/runner/prepare-memory.d.ts +3 -2
  104. package/dist/core/runner/prepare-memory.js +28 -20
  105. package/dist/core/runner/prepare-park-ask.js +4 -3
  106. package/dist/core/runner/prepare-task.js +15 -12
  107. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  108. package/dist/core/runner/run-leg.js +1 -1
  109. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  110. package/dist/core/runner/terminal-account.js +1 -1
  111. package/dist/core/runner-deps.d.ts +6 -2
  112. package/dist/core/secret-env.d.ts +1 -1
  113. package/dist/core/secret-env.js +4 -4
  114. package/dist/core/session-checkout.d.ts +108 -0
  115. package/dist/core/session-checkout.js +485 -0
  116. package/dist/core/session-store.d.ts +12 -4
  117. package/dist/core/session-store.js +23 -3
  118. package/dist/core/session.d.ts +16 -2
  119. package/dist/core/session.js +3 -0
  120. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  121. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  122. package/dist/core/store-contracts/session-store-contract.js +39 -0
  123. package/dist/core/task-event.d.ts +21 -0
  124. package/dist/core/task-notification.d.ts +9 -1
  125. package/dist/core/task-notification.js +6 -0
  126. package/dist/core/task-registry-agent.d.ts +14 -2
  127. package/dist/core/task-registry-agent.js +45 -19
  128. package/dist/core/task-registry-shared.d.ts +26 -11
  129. package/dist/core/task-registry.d.ts +15 -9
  130. package/dist/core/task-registry.js +9 -10
  131. package/dist/core/task-spec-members.js +1 -1
  132. package/dist/core/task-spec.d.ts +20 -0
  133. package/dist/core/tool-policy.d.ts +14 -12
  134. package/dist/core/tool-policy.js +11 -10
  135. package/dist/core/tool-spec.d.ts +38 -19
  136. package/dist/core/types.d.ts +1 -1
  137. package/dist/core/untrusted-egress.d.ts +15 -4
  138. package/dist/core/untrusted-egress.js +23 -22
  139. package/dist/core/workspace-snapshot.d.ts +3 -1
  140. package/dist/core/workspace-snapshot.js +1 -0
  141. package/dist/engine/harness/types.d.ts +66 -1
  142. package/dist/engine/harness/types.js +108 -0
  143. package/dist/engine/session/import-validate.js +6 -1
  144. package/dist/engine/session/session.d.ts +24 -1
  145. package/dist/engine/session/session.js +45 -1
  146. package/dist/index.d.ts +7 -4
  147. package/dist/index.js +7 -4
  148. package/dist/internal/harness-types.d.ts +1 -1
  149. package/dist/orchestration/run-workflow-tool.d.ts +4 -1
  150. package/dist/orchestration/run-workflow-tool.js +1 -0
  151. package/dist/orchestration/workflow.d.ts +3 -0
  152. package/dist/orchestration/workflow.js +3 -1
  153. package/dist/stores/file/session-store.js +2 -1
  154. package/dist/tools/fs/bash-program-position.js +3 -3
  155. package/dist/tools/fs/program-read-model.d.ts +34 -10
  156. package/dist/tools/fs/program-read-model.js +37 -7
  157. package/dist/tools/fs/program-read-model.rows.js +13 -2
  158. package/dist/tools/fs/read-deny.d.ts +13 -1
  159. package/dist/tools/fs/read-deny.js +10 -2
  160. package/dist/tools/fs/removal-targets.js +3 -3
  161. package/dist/tools/fs/safety.d.ts +2 -0
  162. package/dist/tools/fs/safety.js +1 -1
  163. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  164. package/dist/tools/fs/shell-read-argv.js +34 -29
  165. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  166. package/dist/tools/fs/shell-read-bindings.js +5 -1
  167. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  168. package/dist/tools/fs/shell-read-brace.js +79 -0
  169. package/dist/tools/fs/shell-read-check.js +10 -8
  170. package/dist/tools/fs/shell-read-establish.js +23 -16
  171. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  172. package/dist/tools/fs/shell-read-judge.js +3 -3
  173. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  174. package/dist/tools/fs/shell-read-plan.js +189 -93
  175. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  176. package/dist/tools/fs/shell-read-start.js +20 -12
  177. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  178. package/dist/tools/fs/shell-read-word.js +9 -5
  179. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  180. package/dist/tools/fs/shell-read-workdir.js +73 -12
  181. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  182. package/dist/tools/worktree.d.ts +3 -2
  183. package/dist/tools/worktree.js +7 -35
  184. package/package.json +3 -2
  185. package/test/export-surface.snapshot.json +73 -11
  186. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  187. package/wire-changes/core@7.63.0.json +3523 -0
  188. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  189. package/wire-changes/primitives@7.63.0.json +445 -0
  190. package/dist/core/credential-vocabulary.d.ts +0 -176
  191. package/dist/core/credential-vocabulary.js +0 -190
  192. package/dist/core/redaction-passes.d.ts +0 -82
  193. package/dist/core/redaction-passes.js +0 -377
@@ -5,6 +5,7 @@ import { judgeCheckpointRow } from "../checkpoint-row-verdict.js";
5
5
  import { memberPresent } from "../own-property-receipt.js";
6
6
  import { checkpointFrom } from "../pause-registry.js";
7
7
  import { beginContract } from "./contract-harness.js";
8
+ const unhashedCall = (call) => call;
8
9
  export function createCheckpointFixture(over = {}) {
9
10
  const token = over.token ?? mintCheckpointToken();
10
11
  return checkpointFrom({
@@ -13,17 +14,16 @@ export function createCheckpointFixture(over = {}) {
13
14
  sessionId: "sess-1",
14
15
  leafId: "leaf-1",
15
16
  gate: { kind: "human", reason: "approve", toolName: "Write" },
16
- pendingAction: {
17
+ pendingAction: unhashedCall({
17
18
  kind: "tool_approval",
18
19
  origin: "policy",
19
20
  toolCallId: "call-3",
20
21
  toolName: "Write",
21
22
  args: { path: "/x", content: "y" },
22
- boundInputHash: "h0",
23
23
  boundGrantAbsence: "not_bindable",
24
24
  batchToolCallIds: ["call-3"],
25
25
  completedCallIds: [],
26
- },
26
+ }),
27
27
  state: {
28
28
  activeTools: [],
29
29
  nestedStats: { tokens: 0, turns: 0, tasks: 0, costMicroUsd: 0, anyUnpriced: false },
@@ -286,7 +286,7 @@ export async function checkpointStoreContract(make, runAssertion, options = {})
286
286
  const store = make();
287
287
  const okRow = createCheckpointFixture({
288
288
  sessionId: "verdict-ok",
289
- pendingAction: { kind: "tool_approval", origin: "policy", toolCallId: "call-3", toolName: "Write", args: { path: "/x", content: "y" }, preview: { lines: ["a"] }, boundInputHash: "h0", boundGrantAbsence: "not_bindable", batchToolCallIds: ["call-3"], completedCallIds: [] },
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
290
  });
291
291
  const damagedRow = damagedWriteFaceFixture({ sessionId: "verdict-damaged" });
292
292
  for (const cp of [okRow, damagedRow])
@@ -720,7 +720,7 @@ export async function checkpointListByScopeSummaries(store) {
720
720
  toolName: "open_pr",
721
721
  riskDescriptor: { severity: 5, axes: { egress: true, irreversible: true }, toolName: "open_pr" },
722
722
  },
723
- pendingAction: {
723
+ pendingAction: unhashedCall({
724
724
  kind: "tool_approval",
725
725
  origin: "policy",
726
726
  mandated: true,
@@ -729,10 +729,9 @@ export async function checkpointListByScopeSummaries(store) {
729
729
  toolCallId: "call-pr",
730
730
  toolName: "open_pr",
731
731
  args: { repo: "x" },
732
- boundInputHash: "h0",
733
732
  batchToolCallIds: ["call-pr"],
734
733
  completedCallIds: [],
735
- },
734
+ }),
736
735
  });
737
736
  const resource = createCheckpointFixture({
738
737
  token: "tok-resource",
@@ -780,6 +780,45 @@ async function runSessionStoreContract(make, hooks) {
780
780
  assert.ok(scoped.includes(complete) && scoped.includes(incomplete) && !scoped.includes(elsewhere), "scope narrows to one tenant");
781
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");
782
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
+ });
783
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) => {
784
823
  const id = freshId();
785
824
  assert.equal(await headOf(store, id), undefined, "no row ⇒ undefined");
@@ -1285,6 +1285,27 @@ export type TaskEvent = ({
1285
1285
  dir: string;
1286
1286
  byPath?: true;
1287
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
+ }>;
1288
1309
  /** This leg's project identity, decided ONCE at leg start and fixed for the leg: `marker` = the checkout's
1289
1310
  * `.sema/project` (a `TaskSpec.projectId`, when given, equals it); `declared` = `TaskSpec.projectId` in a checkout
1290
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 —
@@ -387,6 +387,12 @@ export function retireTerminalDelivery(sink, task) {
387
387
  if (typeof sink === "function")
388
388
  LANE_OBLIGATIONS.get(sink)?.retire(task);
389
389
  }
390
+ export function moveTerminalDelivery(from, to, task) {
391
+ if (from === to)
392
+ return;
393
+ retireTerminalDelivery(from, task);
394
+ oweTerminalDelivery(to, task);
395
+ }
390
396
  export function createLiveNotificationLane(seat) {
391
397
  const handedOff = new Set();
392
398
  const enter = (admits) => (payload, priority, onDisposition) => {
@@ -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 ChildSessionStore, 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
  /**
@@ -193,6 +193,7 @@ export declare function parkBackgroundAgentLane(core: DurableAgentCore, id: stri
193
193
  checkpointToken: string;
194
194
  seq?: number;
195
195
  resolveStop?: () => Promise<boolean>;
196
+ completionSink?: BackgroundAgentTaskHandle["parkedCompletionSink"];
196
197
  }): "parked" | undefined;
197
198
  /**
198
199
  * design/153 §7.1 (件1 split-brain fence) — the registry-aware reconciliation entry an
@@ -444,7 +445,18 @@ export declare function noteBackgroundAgentActivityLane(core: DurableAgentCore,
444
445
  * stale-running sweep writes, so an operator reading either face sees one explanation, and its run is
445
446
  * aborted. Returns how many rows were collected.
446
447
  */
447
- 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;
448
460
  /** S2b — retention is REVOCABLE: every retain-ledger eviction path (TTL / LRU / abandon /
449
461
  * parent-teardown disposeAll) runs the entry's release closure, and the spawner wraps that closure
450
462
  * to call this — so a park can never be acknowledged against a continuation that was already
@@ -372,6 +372,7 @@ export function registerBackgroundAgentLane(core, input) {
372
372
  throw new Error(`TaskRegistry: background-agent id ${JSON.stringify(input.id)} does not match the a<hex> handle form`);
373
373
  }
374
374
  const id = input.id ?? core.mintTaskId("background_agent");
375
+ let carriedCompletionSink;
375
376
  if (input.durableSeed !== undefined) {
376
377
  const prior = core.handles.get(id);
377
378
  if (prior !== undefined) {
@@ -382,6 +383,8 @@ export function registerBackgroundAgentLane(core, input) {
382
383
  const priorLane = prior.durable;
383
384
  if (priorLane !== undefined)
384
385
  priorLane.poisoned = true;
386
+ if (parkedHandoff)
387
+ carriedCompletionSink = prior.parkedCompletionSink;
385
388
  core.handles.delete(id);
386
389
  }
387
390
  }
@@ -398,6 +401,7 @@ export function registerBackgroundAgentLane(core, input) {
398
401
  status: input.initialStatus ?? "running",
399
402
  ...(input.parkedCheckpointToken !== undefined ? { parkedCheckpointToken: input.parkedCheckpointToken } : {}),
400
403
  ...(input.resolveParkedStop !== undefined ? { resolveParkedStop: input.resolveParkedStop } : {}),
404
+ ...(carriedCompletionSink !== undefined ? { parkedCompletionSink: carriedCompletionSink } : {}),
401
405
  ...(input.sessionScoped ? { sessionScoped: true } : {}),
402
406
  ...(input.description !== undefined ? { description: input.description } : {}),
403
407
  name,
@@ -474,6 +478,7 @@ export function parkBackgroundAgentLane(core, id, park) {
474
478
  handle.status = "parked";
475
479
  handle.parkedCheckpointToken = park.checkpointToken;
476
480
  handle.resolveParkedStop = park.resolveStop;
481
+ handle.parkedCompletionSink = park.completionSink;
477
482
  handle.notify = undefined;
478
483
  for (const [, , qResolve] of handle.preAttachQueue ?? [])
479
484
  qResolve?.({ ok: false, reason: "not_running" });
@@ -542,18 +547,18 @@ export async function reconcileParkedAgentsLane(core, stores, scope, now, opts)
542
547
  else {
543
548
  continue;
544
549
  }
545
- if (handle.status !== "parked")
550
+ const held = heldPark(core, handle.id, token);
551
+ if (held === undefined)
546
552
  continue;
547
- if (handle.parkedCheckpointToken !== token)
548
- continue;
549
- handle.status = "failed";
550
- handle.error = error;
551
- handle.parkedCheckpointToken = undefined;
552
- handle.resolveParkedStop = undefined;
553
- handle.updatedAt = now;
554
- mintCompletionId(handle);
555
- core.pokeBgQuiescence(handle.owner);
556
- 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"]);
557
562
  liveFailed++;
558
563
  }
559
564
  const { reconcileParkedAgents: storeReconcile } = await import("./background-agent-store.js");
@@ -636,6 +641,8 @@ export async function rollbackParkedClaimLane(core, stores, ticket) {
636
641
  h.error = error;
637
642
  h.parkedCheckpointToken = undefined;
638
643
  h.resolveParkedStop = undefined;
644
+ h.parkedCompletionSink = undefined;
645
+ h.terminalNotifier = undefined;
639
646
  h.updatedAt = now;
640
647
  commitCompletionIdIfEmpty(h, rollbackCompletionIdCandidate);
641
648
  core.pokeBgQuiescence(h.owner);
@@ -789,6 +796,7 @@ export async function consumeParkedFlipLane(core, id, stores, ticket) {
789
796
  handle.status = "running";
790
797
  handle.parkedCheckpointToken = undefined;
791
798
  handle.resolveParkedStop = undefined;
799
+ handle.parkedCompletionSink = undefined;
792
800
  handle.updatedAt = Date.now();
793
801
  handle.completionId = undefined;
794
802
  handle.terminalNotified = undefined;
@@ -842,7 +850,7 @@ export function settleBackgroundAgentLane(core, id, outcome) {
842
850
  handle.status = outcome.status;
843
851
  mintCompletionId(handle);
844
852
  handle.notify = undefined;
845
- handle.onReapTerminal = undefined;
853
+ handle.terminalNotifier = undefined;
846
854
  for (const [, , qResolve] of handle.preAttachQueue ?? [])
847
855
  qResolve?.({ ok: false, reason: "not_running" });
848
856
  handle.preAttachQueue = undefined;
@@ -1141,7 +1149,7 @@ export function noteBackgroundAgentActivityLane(core, id, now = Date.now()) {
1141
1149
  return;
1142
1150
  handle.updatedAt = now;
1143
1151
  }
1144
- export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.now(), onTerminal) {
1152
+ export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.now()) {
1145
1153
  if (!Number.isFinite(staleMs) || staleMs <= 0) {
1146
1154
  throw new Error(`reapStaleSessionBackgroundAgents: staleMs must be a positive finite number of milliseconds (got ${String(staleMs)})`);
1147
1155
  }
@@ -1152,21 +1160,35 @@ export function reapStaleSessionBackgroundAgentsLane(core, staleMs, now = Date.n
1152
1160
  if (now - handle.updatedAt <= staleMs)
1153
1161
  continue;
1154
1162
  core.markStopSource(handle.id, "system");
1155
- const reapTerminalNote = handle.onReapTerminal;
1163
+ const reapTerminalNote = handle.terminalNotifier;
1156
1164
  handle.abort.abort();
1157
1165
  settleBackgroundAgentLane(core, handle.id, {
1158
1166
  status: "killed",
1159
1167
  error: STALE_RUNNING_REAP_ATTRIBUTION,
1160
1168
  cycle: handle.reviveCycle ?? 0,
1161
1169
  });
1162
- if (reapTerminalNote !== undefined && handle.terminalNotified !== true) {
1163
- handle.terminalNotified = true;
1164
- onTerminal?.(reapTerminalNote);
1165
- }
1170
+ announceLandedAgentTerminal(core, handle, reapTerminalNote, { status: "killed" });
1166
1171
  reaped++;
1167
1172
  }
1168
1173
  return reaped;
1169
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
+ }
1170
1192
  export function unmarkRetainedContinuationLane(core, id) {
1171
1193
  const handle = core.handles.get(id);
1172
1194
  if (handle && handle.type === "background_agent")
@@ -1451,6 +1473,7 @@ export async function stopBackgroundAgentLane(core, handle) {
1451
1473
  }
1452
1474
  let stopWon = false;
1453
1475
  let arbiterUnreachable = false;
1476
+ const parkedToken = handle.parkedCheckpointToken;
1454
1477
  try {
1455
1478
  stopWon = await arbiter();
1456
1479
  }
@@ -1458,7 +1481,9 @@ export async function stopBackgroundAgentLane(core, handle) {
1458
1481
  stopWon = false;
1459
1482
  arbiterUnreachable = true;
1460
1483
  }
1461
- if (stopWon && handle.status === "parked") {
1484
+ const landed = stopWon ? heldPark(core, handle.id, parkedToken) : undefined;
1485
+ if (landed !== undefined) {
1486
+ handle = landed;
1462
1487
  core.markStopSource(handle.id, "parent");
1463
1488
  handle.status = "killed";
1464
1489
  handle.stoppedBy = handle.stopSource ?? "parent";
@@ -1467,6 +1492,7 @@ export async function stopBackgroundAgentLane(core, handle) {
1467
1492
  handle.parkedCheckpointToken = undefined;
1468
1493
  handle.resolveParkedStop = undefined;
1469
1494
  core.pokeBgQuiescence(handle.owner);
1495
+ announceParkedEnding(core, handle, { status: "killed" });
1470
1496
  {
1471
1497
  const lane = handle.durable;
1472
1498
  if (lane !== undefined) {
@@ -313,6 +313,12 @@ export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
313
313
  * Absent (cross-process row, no live park context) ⇒ TaskStop refuses honestly: the durable
314
314
  * approval inbox (server /decide) owns that arbitration. */
315
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;
316
322
  /** S2b — resolvers of DIRECT (post-attach) deliveries currently awaiting the
317
323
  * injector; terminal settle/stop sweep these as not_running so a never-settling adapter can
318
324
  * never pin the sender's tool call. */
@@ -391,19 +397,28 @@ export interface BackgroundAgentTaskHandle extends SemaTaskHandle {
391
397
  /** The LANDED attribution — set exactly when the handle goes `killed`, never rewritten afterwards
392
398
  * (first-writer-wins, same discipline as the terminal status itself). Absent on natural completion/failure. */
393
399
  stoppedBy?: StopSource;
394
- /** RB-375 A1 — the reap-time terminal notifier, hung by the spawn lanes (subagent.ts) right after
395
- * registration: composes and sends the SAME terminal faces (observer sink + parent notification)
396
- * the child's own unwind would, so {@link import("./task-registry.js").TaskRegistry.reapSessionBackground}
397
- * can emit the terminal news AT REAP TIME instead of waiting on the child's unwind (which blocks on
398
- * the in-flight tool actually honoring the abort — unbounded). The bash handle's `onTerminal` twin.
399
- * Cleared at the accepted settle (with `notify`); invoked at most once via {@link terminalNotified}. */
400
- 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;
401
407
  /** RB-375 A1 — terminal-notification once-latch (the bash/monitor `terminalNotified` twin): claimed
402
- * by whichever side reaches its emit point first — the session-release reap sweep (synchronous send)
403
- * or the child's own unwind (`TaskRegistry.claimAgentTerminalNotify`). The loser stays silent, so a
404
- * 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). */
405
411
  terminalNotified?: true;
406
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
+ }
407
422
  /** design/135 G2 (Monitor): injectable timer/clock seam for the monitor watcher — the 200ms batch window
408
423
  * and the timeout/storm checks must be drivable by a test without real sleeps (design/87 discipline).
409
424
  * `setInterval` receives an ASYNC tick (the default adapter fires it void; a fake can await it). */
@@ -776,7 +791,7 @@ export interface RegistryCore {
776
791
  handles: Map<string, RegisteredTaskHandle>;
777
792
  mintTaskId(type: SemaTaskType): string;
778
793
  markStopSource(id: string, source: StopSource): void;
779
- notifyTerminalOnce(handle: BackgroundBashTaskHandle | MonitorTaskHandle, send: () => void): void;
794
+ notifyTerminalOnce(handle: BackgroundBashTaskHandle | MonitorTaskHandle | BackgroundAgentTaskHandle, send: () => void): void;
780
795
  pokeBgQuiescence(owner: string | undefined): void;
781
796
  }
782
797
  /** writer-lease renewal period for armed durable rows (see ensureDurableHeartbeat).
@@ -9,7 +9,7 @@ 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, ChildSessionStore } from "./task-registry-shared.js";
12
+ import type { RegisterBackgroundAgentInput, ParkedClaimTicket, ChildSessionStore, LandedAgentTerminal } from "./task-registry-shared.js";
13
13
  import type { ChildSessionAnchor } from "./task-registry-agent.js";
14
14
  import { type DelegationOccupant } from "./task-registry-agent.js";
15
15
  import { type AgentStateSource } from "./agent-state.js";
@@ -157,8 +157,8 @@ export declare class TaskRegistry {
157
157
  * (cap overflow dropped the watcher; the owner's tasks may still be running — the subscriber must
158
158
  * NOT treat this as quiescence). */
159
159
  private bgQuiescenceWatchers;
160
- /** One host-callback isolation scope for this registry's five notification seams (reap terminal
161
- * 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
162
162
  * as the five hand-written try/catches it replaced, now counted per site and readable for diagnostics. */
163
163
  private readonly notifier;
164
164
  /** The read face for this registry's CONTAINED host-callback failures (site → count).
@@ -231,7 +231,11 @@ export declare class TaskRegistry {
231
231
  checkpointToken: string;
232
232
  seq?: number;
233
233
  resolveStop?: () => Promise<boolean>;
234
+ completionSink?: BackgroundAgentTaskHandle["parkedCompletionSink"];
234
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"];
235
239
  reconcileParkedAgents(stores: {
236
240
  agentStore: import("./background-agent-store.js").BackgroundAgentStore;
237
241
  checkpointStore: Pick<import("./checkpoint-store.js").CheckpointStore, "get">;
@@ -341,10 +345,10 @@ export declare class TaskRegistry {
341
345
  }): "completed" | "failed" | "killed" | undefined;
342
346
  unmarkRetainedContinuation(id: string): void;
343
347
  attachAgentNotify(id: string, notify: NonNullable<BackgroundAgentTaskHandle["notify"]>, cycle?: number): void;
344
- /** RB-375 A1 — hang the reap-time terminal notifier on a live background-agent row (see
345
- * {@link BackgroundAgentTaskHandle.onReapTerminal}). No-op on unknown/terminal rows: a row that
346
- * already settled has its unwind (or the settle itself) owning the terminal story. */
347
- 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;
348
352
  /** RB-375 A1 — the child-unwind side of the terminal-notification once-latch: returns `true` when
349
353
  * the CALLER now owns sending the terminal faces (and claims the latch), `false` when the reap
350
354
  * sweep already sent them (the caller must stay silent — the registry row still takes the settle's
@@ -542,7 +546,7 @@ export declare class TaskRegistry {
542
546
  * (`abortBackgroundAgentsForOwner` in the child's unwind) — this function never sees those rows,
543
547
  * so they are NOT counted here.
544
548
  * RB-375 A1 — a directly reaped `background_agent` row's terminal notification is sent
545
- * 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},
546
550
  * once-latched against the child's own unwind), so consumers observe the terminal immediately
547
551
  * instead of after the in-flight tool honors the abort (unbounded). */
548
552
  reapSessionBackground(sessionId: string, scope?: string): number;
@@ -616,7 +620,9 @@ export declare class TaskRegistry {
616
620
  * running-row eviction). Cheap no-op without watchers; fires + removes the owner's whole set only
617
621
  * when the running count is zero (the LAST settling task's poke wins — count-zero judgement). */
618
622
  private pokeBgQuiescence;
619
- /** 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,
620
626
  * no await between check and set — atomic), so a racing producer pair (a teardown settle vs an in-flight
621
627
  * watcher tick that passed its status gate before the settle landed) emits exactly ONE terminal notice.
622
628
  * The latch stays set even if the sink throws — a faulty sink must not re-arm it. */
@@ -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, activeDelegationOccupantsLane, 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";
@@ -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);
@@ -252,7 +254,7 @@ export class TaskRegistry {
252
254
  return;
253
255
  if (handle.status !== "running" && handle.status !== "parked" && handle.status !== "pending")
254
256
  return;
255
- handle.onReapTerminal = fn;
257
+ handle.terminalNotifier = fn;
256
258
  }
257
259
  claimAgentTerminalNotify(id) {
258
260
  const handle = this.handles.get(id);
@@ -570,13 +572,10 @@ export class TaskRegistry {
570
572
  if (!canAccess(handle, access))
571
573
  continue;
572
574
  this.markStopSource(handle.id, "system");
573
- const reapTerminalNote = handle.onReapTerminal;
575
+ const reapTerminalNote = handle.terminalNotifier;
574
576
  handle.abort.abort();
575
577
  this.settleBackgroundAgent(handle.id, { status: "killed", error: "session released", cycle: handle.reviveCycle ?? 0 });
576
- if (reapTerminalNote !== undefined && handle.terminalNotified !== true) {
577
- handle.terminalNotified = true;
578
- this.notifier.notify(() => reapTerminalNote(), "taskRegistry.reapTerminalNote");
579
- }
578
+ announceLandedAgentTerminal(this.core, handle, reapTerminalNote, { status: "killed" });
580
579
  reaped++;
581
580
  }
582
581
  this.pokeBgQuiescence(sessionId);
@@ -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`)