@sema-agent/core 7.61.0 → 7.62.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 (176) hide show
  1. package/CHANGELOG.md +312 -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.d.ts +6 -1
  8. package/dist/agents/subagent.js +66 -12
  9. package/dist/agents/suspend-guard.d.ts +38 -16
  10. package/dist/agents/suspend-guard.js +9 -4
  11. package/dist/agents/verify.js +4 -3
  12. package/dist/core/checkpoint-features.d.ts +722 -0
  13. package/dist/core/checkpoint-features.js +98 -0
  14. package/dist/core/checkpoint-requirements.d.ts +9 -2
  15. package/dist/core/checkpoint-requirements.js +9 -4
  16. package/dist/core/checkpoint-row-verdict.d.ts +99 -0
  17. package/dist/core/checkpoint-row-verdict.js +225 -0
  18. package/dist/core/checkpoint-store.d.ts +55 -745
  19. package/dist/core/checkpoint-store.js +39 -141
  20. package/dist/core/engine-notice.d.ts +19 -3
  21. package/dist/core/engine-notice.js +9 -2
  22. package/dist/core/gate-fold.js +2 -2
  23. package/dist/core/governance-codes.d.ts +3 -1
  24. package/dist/core/governance-codes.js +3 -0
  25. package/dist/core/hooks.d.ts +13 -0
  26. package/dist/core/human-input-projection.d.ts +1 -0
  27. package/dist/core/human-input-projection.js +3 -0
  28. package/dist/core/image-admission.d.ts +1 -1
  29. package/dist/core/locked-config.d.ts +2 -2
  30. package/dist/core/mcp-host-seat.js +6 -1
  31. package/dist/core/memory-engine/consolidation-driver.d.ts +1 -1
  32. package/dist/core/memory-vector.d.ts +1 -1
  33. package/dist/core/memory.d.ts +10 -10
  34. package/dist/core/mode-policy.js +1 -1
  35. package/dist/core/mods/classic-events.d.ts +9 -1
  36. package/dist/core/mods/dollar.d.ts +32 -1
  37. package/dist/core/mods/dollar.js +13 -1
  38. package/dist/core/mods/kernel/events.d.ts +11 -3
  39. package/dist/core/mods/kernel/events.js +13 -10
  40. package/dist/core/mods/lifecycle-stations.d.ts +36 -4
  41. package/dist/core/mods/lifecycle-stations.js +44 -9
  42. package/dist/core/mods/session-append.d.ts +4 -1
  43. package/dist/core/mods/session-append.js +7 -0
  44. package/dist/core/mods/session-receive.js +12 -15
  45. package/dist/core/mods/stations.d.ts +51 -6
  46. package/dist/core/mods/stations.js +124 -0
  47. package/dist/core/own-property-receipt.d.ts +7 -0
  48. package/dist/core/own-property-receipt.js +3 -0
  49. package/dist/core/read-root-candidate.js +1 -1
  50. package/dist/core/resume-startup-cause.d.ts +5 -4
  51. package/dist/core/runner/compact-session.js +5 -2
  52. package/dist/core/runner/contracts.d.ts +18 -8
  53. package/dist/core/runner/delegation-owner.d.ts +43 -0
  54. package/dist/core/runner/delegation-owner.js +59 -0
  55. package/dist/core/runner/lineage-reroot-view.d.ts +56 -0
  56. package/dist/core/runner/lineage-reroot-view.js +108 -0
  57. package/dist/core/runner/permission-rule-lanes.d.ts +2 -1
  58. package/dist/core/runner/permission-rule-lanes.js +2 -2
  59. package/dist/core/runner/person-path-rows.d.ts +15 -0
  60. package/dist/core/runner/person-path-rows.js +26 -3
  61. package/dist/core/runner/prepare-acquire-reconcile.d.ts +4 -1
  62. package/dist/core/runner/prepare-acquire-reconcile.js +7 -2
  63. package/dist/core/runner/prepare-caps-and-workflow.d.ts +1 -0
  64. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  65. package/dist/core/runner/prepare-config-doors.d.ts +6 -6
  66. package/dist/core/runner/prepare-config-doors.js +3 -4
  67. package/dist/core/runner/prepare-hands-readface.d.ts +1 -1
  68. package/dist/core/runner/prepare-hands-readface.js +28 -7
  69. package/dist/core/runner/prepare-inherited-gate.d.ts +2 -0
  70. package/dist/core/runner/prepare-inherited-gate.js +7 -3
  71. package/dist/core/runner/prepare-task.js +10 -7
  72. package/dist/core/runner/resume-admission.d.ts +3 -3
  73. package/dist/core/runner/resume-admission.js +6 -3
  74. package/dist/core/runner/resume-apply.d.ts +4 -0
  75. package/dist/core/runner/resume-apply.js +11 -4
  76. package/dist/core/runner/resume-checkpoint-screen.d.ts +9 -0
  77. package/dist/core/runner/resume-checkpoint-screen.js +4 -84
  78. package/dist/core/runner/run-git-lane.d.ts +2 -0
  79. package/dist/core/runner/run-git-lane.js +4 -1
  80. package/dist/core/runner/run-harness-handlers.d.ts +2 -0
  81. package/dist/core/runner/run-harness-handlers.js +3 -2
  82. package/dist/core/runner/run-leg.js +24 -7
  83. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  84. package/dist/core/runner/run-stop-and-final-verify.js +2 -1
  85. package/dist/core/runner/run-turn-boundary.js +7 -4
  86. package/dist/core/runner/runtask.js +6 -6
  87. package/dist/core/runner/steering-preview.d.ts +9 -0
  88. package/dist/core/runner/steering-preview.js +5 -0
  89. package/dist/core/runner/stream-steer-verb.js +8 -0
  90. package/dist/core/runner/tool-face-overlay.js +2 -0
  91. package/dist/core/runner/turn-attachments.d.ts +5 -0
  92. package/dist/core/runner/turn-attachments.js +1 -1
  93. package/dist/core/runner-deps.d.ts +2 -2
  94. package/dist/core/secret-env.d.ts +8 -5
  95. package/dist/core/secret-env.js +37 -18
  96. package/dist/core/session-store.d.ts +1 -1
  97. package/dist/core/session-store.js +5 -1
  98. package/dist/core/session.d.ts +14 -4
  99. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +6 -0
  100. package/dist/core/store-contracts/checkpoint-store-contract.js +68 -0
  101. package/dist/core/store-contracts/session-store-contract.js +22 -8
  102. package/dist/core/task-event.d.ts +7 -1
  103. package/dist/core/task-notification.js +2 -1
  104. package/dist/core/task-registry-agent.d.ts +27 -7
  105. package/dist/core/task-registry-agent.js +12 -5
  106. package/dist/core/task-registry-shared.d.ts +7 -0
  107. package/dist/core/task-registry-workflow.js +4 -3
  108. package/dist/core/task-registry.d.ts +13 -2
  109. package/dist/core/task-registry.js +11 -4
  110. package/dist/core/task-result.d.ts +5 -5
  111. package/dist/core/task-spec.d.ts +1 -1
  112. package/dist/core/terminal-cause.d.ts +6 -6
  113. package/dist/core/tool-face.d.ts +6 -2
  114. package/dist/core/tool-face.js +1 -1
  115. package/dist/core/tool-policy.d.ts +2 -1
  116. package/dist/core/tool-roster.d.ts +4 -4
  117. package/dist/core/tool-spec.d.ts +4 -0
  118. package/dist/core/types.d.ts +1 -1
  119. package/dist/core/types.js +1 -1
  120. package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
  121. package/dist/engine/execution-env/node-execution-env.js +12 -5
  122. package/dist/engine/harness/types.d.ts +11 -0
  123. package/dist/engine/session/parent-chain-guard.d.ts +3 -3
  124. package/dist/engine/session/parent-chain-guard.js +1 -1
  125. package/dist/engine/session/path-to-root.d.ts +18 -3
  126. package/dist/engine/session/path-to-root.js +15 -1
  127. package/dist/engine/session/repo-utils.d.ts +12 -1
  128. package/dist/engine/session/repo-utils.js +41 -0
  129. package/dist/engine/session/session.js +1 -1
  130. package/dist/engine/session/storage-base.d.ts +20 -0
  131. package/dist/engine/session/storage-base.js +28 -9
  132. package/dist/index.d.ts +9 -8
  133. package/dist/index.js +4 -4
  134. package/dist/internal/harness.d.ts +4 -3
  135. package/dist/internal/harness.js +3 -2
  136. package/dist/orchestration/run-workflow-tool.d.ts +3 -0
  137. package/dist/orchestration/run-workflow-tool.js +27 -11
  138. package/dist/orchestration/workflow-governance.d.ts +1 -1
  139. package/dist/orchestration/workflow.d.ts +3 -0
  140. package/dist/orchestration/workflow.js +2 -7
  141. package/dist/stores/file/checkpoint-store.d.ts +2 -0
  142. package/dist/stores/file/checkpoint-store.js +7 -6
  143. package/dist/stores/file/fs-atomic.d.ts +0 -22
  144. package/dist/stores/file/fs-atomic.js +0 -17
  145. package/dist/stores/file/index.d.ts +2 -9
  146. package/dist/stores/file/index.js +2 -4
  147. package/dist/stores/file/session-store.d.ts +13 -7
  148. package/dist/stores/file/session-store.js +40 -17
  149. package/dist/tools/fs/bash-program-position.d.ts +3 -2
  150. package/dist/tools/fs/bash-program-position.js +7 -7
  151. package/dist/tools/fs/removal-targets.js +2 -2
  152. package/dist/tools/fs/shell-read-argv.d.ts +4 -2
  153. package/dist/tools/fs/shell-read-argv.js +14 -3
  154. package/dist/tools/fs/shell-read-bindings.d.ts +18 -2
  155. package/dist/tools/fs/shell-read-bindings.js +148 -68
  156. package/dist/tools/fs/shell-read-check.js +20 -4
  157. package/dist/tools/fs/shell-read-establish.js +22 -8
  158. package/dist/tools/fs/shell-read-functions.js +2 -2
  159. package/dist/tools/fs/shell-read-object-path.d.ts +59 -0
  160. package/dist/tools/fs/shell-read-object-path.js +119 -0
  161. package/dist/tools/fs/shell-read-plan.d.ts +8 -0
  162. package/dist/tools/fs/shell-read-plan.js +47 -30
  163. package/dist/tools/fs/shell-read-start.d.ts +66 -13
  164. package/dist/tools/fs/shell-read-start.js +89 -17
  165. package/dist/tools/fs/shell-read-workdir.d.ts +29 -8
  166. package/dist/tools/fs/shell-read-workdir.js +31 -8
  167. package/package.json +2 -2
  168. package/test/export-surface.snapshot.json +21 -33
  169. package/wire-changes/core-stores-sql@7.62.0.json +30 -0
  170. package/wire-changes/core@7.62.0.json +2181 -0
  171. package/wire-changes/mods-kernel@7.62.0.json +42 -0
  172. package/wire-changes/primitives@7.62.0.json +30 -0
  173. package/dist/core/consolidate-scope.d.ts +0 -93
  174. package/dist/core/consolidate-scope.js +0 -98
  175. package/dist/core/runner/memory-consolidation.d.ts +0 -109
  176. package/dist/core/runner/memory-consolidation.js +0 -251
@@ -0,0 +1,108 @@
1
+ import { LineageBreak, entryParentLinks, pathToRoot, replayLossText } from "../../internal/harness.js";
2
+ import { deliverEngineNotice } from "../engine-notice.js";
3
+ const LINEAGE_REROOTED = "session.lineage_rerooted";
4
+ export function viewThroughReplayLoss(storage, found) {
5
+ return new Proxy(storage, {
6
+ get(target, prop, receiver) {
7
+ if (prop === "getPathToRoot")
8
+ return (leafId) => branchReadingLoss(target, leafId, found);
9
+ const value = Reflect.get(target, prop, receiver);
10
+ return typeof value === "function" ? value.bind(target) : value;
11
+ },
12
+ });
13
+ }
14
+ async function branchReadingLoss(storage, leafId, found) {
15
+ let path;
16
+ try {
17
+ path = await storage.getPathToRoot(leafId);
18
+ }
19
+ catch (err) {
20
+ if (!(err instanceof LineageBreak) || err.replayLoss === undefined || err.replayLoss.dropped === 0 || leafId === null)
21
+ throw err;
22
+ const entries = await storage.getEntries();
23
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
24
+ const leaf = byId.get(leafId);
25
+ if (leaf === undefined)
26
+ throw err;
27
+ const rerooted = pathToRoot(leaf, entryParentLinks(byId), err.childId);
28
+ found({
29
+ break: true,
30
+ missingParentId: err.missingParentId,
31
+ rootedAt: err.childId,
32
+ recordsDropped: err.replayLoss.dropped,
33
+ recordsTotal: err.replayLoss.total,
34
+ leaf: leafId,
35
+ entriesOnPath: rerooted.length,
36
+ entriesCut: entries.length - descendantsOf(entries, err.childId),
37
+ });
38
+ return rerooted;
39
+ }
40
+ const loss = storage.getReplayLoss?.();
41
+ if (loss !== undefined && loss.dropped > 0)
42
+ found({ break: false, recordsDropped: loss.dropped, recordsTotal: loss.total, leaf: leafId, entriesOnPath: path.length });
43
+ return path;
44
+ }
45
+ function descendantsOf(entries, rootId) {
46
+ const children = new Map();
47
+ for (const entry of entries) {
48
+ const parent = entry.parentId || null;
49
+ if (parent === null)
50
+ continue;
51
+ const list = children.get(parent);
52
+ if (list === undefined)
53
+ children.set(parent, [entry.id]);
54
+ else
55
+ list.push(entry.id);
56
+ }
57
+ const seen = new Set([rootId]);
58
+ const todo = [rootId];
59
+ for (let id = todo.pop(); id !== undefined; id = todo.pop()) {
60
+ for (const child of children.get(id) ?? []) {
61
+ if (seen.has(child))
62
+ continue;
63
+ seen.add(child);
64
+ todo.push(child);
65
+ }
66
+ }
67
+ return seen.size;
68
+ }
69
+ const WHOLE_BRANCH = "\0whole";
70
+ function lossSentence(finding) {
71
+ const count = replayLossText({ dropped: finding.recordsDropped, total: finding.recordsTotal });
72
+ if (finding.break) {
73
+ return (`This session's log is damaged: entry ${finding.missingParentId}, the parent of ${finding.rootedAt}, is not in it (${count}). ` +
74
+ `The run continues from ${finding.rootedAt}: ${finding.entriesOnPath} entries of the conversation are kept, and ${finding.entriesCut} entries the log holds above the damage are not in its context.`);
75
+ }
76
+ if (finding.leaf === null)
77
+ return `This session's log is damaged: ${count}, and none of it is readable. The run starts from an empty conversation.`;
78
+ return (`This session's log is damaged: ${count}. The run continues from entry ${finding.leaf}, where the records the log still holds leave the conversation: ` +
79
+ `${finding.entriesOnPath} entries of it are kept, and what the unreadable records said — possibly its latest turns — is not in its context.`);
80
+ }
81
+ export function replayLossSeat(ids) {
82
+ const said = new Set();
83
+ return (finding, sessionId) => {
84
+ const key = finding.break ? `${finding.missingParentId}\n${finding.rootedAt}` : WHOLE_BRANCH;
85
+ if (said.has(key))
86
+ return;
87
+ said.add(key);
88
+ if (finding.break)
89
+ said.add(WHOLE_BRANCH);
90
+ deliverEngineNotice(ids.onNotice, { code: LINEAGE_REROOTED, message: lossSentence(finding), detail: { ...finding, sessionId, runId: ids.runId } });
91
+ };
92
+ }
93
+ export function replayLossLeg(ids) {
94
+ const say = replayLossSeat(ids);
95
+ let held = [];
96
+ return {
97
+ view: (storage, sessionId) => viewThroughReplayLoss(storage, (finding) => (held !== undefined ? void held.push({ finding, sessionId }) : say(finding, sessionId))),
98
+ discard: () => {
99
+ held = [];
100
+ },
101
+ settle: () => {
102
+ const found = [...(held ?? [])].sort((a, b) => Number(b.finding.break) - Number(a.finding.break));
103
+ held = undefined;
104
+ for (const { finding, sessionId } of found)
105
+ say(finding, sessionId);
106
+ },
107
+ };
108
+ }
@@ -179,9 +179,10 @@ export declare function createPermissionRuleLanes(cfg: {
179
179
  /** Sink for a judgment against the rows that threw, and for the org lane's degraded-snapshot line. */
180
180
  onDisclosure: (message: string) => void;
181
181
  /** The run's one reader of the person's rules: the call's ONE read of the bytes judged, pinned, that the read station, the
182
- * org lane and the personal lane all take (the lanes consume a reader; they do not make one). */
182
+ * org lane and the personal lane all take, and a request's read the whole-tool readings take (the lanes consume a reader). */
183
183
  rows: {
184
184
  pin(toolCallId: string, judged?: unknown): Promise<PersonRowsRead>;
185
+ forRequest(): Promise<PersonRowsRead>;
185
186
  };
186
187
  /** The allow layer's auto strip over a stored ALLOW row (true ⇒ out of this call's table BEFORE the coverage is chosen). */
187
188
  stripsAllow?: (rule: PersistedRule, req: ToolCallRequest) => boolean;
@@ -1,4 +1,4 @@
1
- import { REFUSES_NO_WHOLE_TOOL, TOOL_TABLE_VIEW_READ, toolPolicyWholeToolRefusals } from "../tool-policy.js";
1
+ import { REFUSES_NO_WHOLE_TOOL, toolPolicyWholeToolRefusals } from "../tool-policy.js";
2
2
  import { persistedRuleMandateOf, ruleClearanceOf } from "../ask-origin.js";
3
3
  import {} from "../hooks.js";
4
4
  import { adjudicatePersistedDomainRules, adjudicatePersistedNameRules, adjudicatePersistedPathRules, adjudicatePersistedRules, adjudicatePersistedToolRules, callPathFaceOf, cardRuleFormOf, eligiblePersisted, escapeForDisclosure, faceRowsSpeakFor, parseRuleText, ruleWordsOf, nameRuleSubjectOf, ruleToolGrammarOf, segmentCoverageOf, suggestRuleForHost, suggestRuleForName, suggestRuleForTool, suggestRulesForCommand, wholeToolRuleReaches } from "../permission-rule-model.js";
@@ -191,7 +191,7 @@ export function createPermissionRuleLanes(cfg) {
191
191
  };
192
192
  const personal = provider.partitions.durable ? { adjudicate: personalAdjudicate } : undefined;
193
193
  let inFlight;
194
- const viewRead = () => (inFlight ??= reader.pin(TOOL_TABLE_VIEW_READ).finally(() => (inFlight = undefined)));
194
+ const viewRead = () => (inFlight ??= reader.forRequest().finally(() => (inFlight = undefined)));
195
195
  const wholeToolRefusals = toolPolicyWholeToolRefusals([
196
196
  personal !== undefined ? { wholeToolRefusals: async () => personalRefusesWholeOver((await viewRead()).rules) } : undefined,
197
197
  org !== undefined ? { wholeToolRefusals: async () => ((read) => (read.org !== undefined ? org.refusesWholeOver(read.org) : REFUSES_NO_WHOLE_TOOL))(await viewRead()) } : undefined,
@@ -11,6 +11,17 @@
11
11
  * table no longer holds that attempt. A judgment that is no call of the leg (a visibility probe's fixed id, a gate with no
12
12
  * leg) keeps nothing: its rule lanes take a read of their own, its read station the run's latest tables.
13
13
  *
14
+ * ## One read per request
15
+ *
16
+ * A model request's view of the tool table stands on one read per request ({@link PersonPathRows.forRequest}), asked when the
17
+ * request is sent: a read asked earlier may have been asked before a tool the request follows wrote a rule (a call's read
18
+ * always is; a visibility probe's may be — a changed-files scan outlives its turn's boundary). Two reads stand for a request
19
+ * instead, and ask the store nothing new: the prepare read, for the first request while no read has started after it (no
20
+ * call has been judged before it); and the newest read the store has left unanswered past its bound, asked since the
21
+ * previous request, while no read started after it has been answered — its verdict is the failure law's, the one a new read
22
+ * of the silent store would give. A store that answers slowly, or not at all, so costs a request at most one bound beyond its
23
+ * calls' own reads.
24
+ *
14
25
  * ## The run's unit, one entry per partition
15
26
  *
16
27
  * Every read's outcome lands in the run's unit, per personal partition (the durable one — its user and project rows — and
@@ -113,6 +124,10 @@ export interface PersonPathRows {
113
124
  * holds — a judgment reads the store, as the session rules' does. Any other judgment (no leg, or an id the table does not
114
125
  * hold — a visibility probe) takes a read of its own, kept by nobody. Bounded ({@link PERSON_READ_BOUND_MS}); never rejects. */
115
126
  pin(toolCallId: string, judged?: unknown): Promise<PersonRowsRead>;
127
+ /** The read one model request's view of the tool table stands on, which the request then holds: a read asked now — or,
128
+ * asking the store nothing new, the prepare read for the first request, and the newest read asked since the previous
129
+ * request that the store has left unanswered past its bound. Bounded ({@link PERSON_READ_BOUND_MS}); never rejects. */
130
+ forRequest(): Promise<PersonRowsRead>;
116
131
  /** Settles once the tables a reader takes are compiled: a pinned call's own; any other reader's (no id, or a call holding
117
132
  * no pin), the unit's newest — through every change that lands meanwhile, within {@link PATH_TABLES_READY_BOUND_MS} —
118
133
  * or at `signal` or the run's cut ({@link PersonPathRowsConfig.signal}). Never rejects: a reader whose wait was cut
@@ -29,6 +29,10 @@ export function createPersonPathRows(cfg) {
29
29
  const unit = { durable: { failedSeq: 0 }, session: { failedSeq: 0 } };
30
30
  let seqs = 0;
31
31
  const pins = new Map();
32
+ let prepared;
33
+ let silent;
34
+ let answeredSeq = 0;
35
+ let requestSeq = 0;
32
36
  let compile;
33
37
  const compiled = new Map();
34
38
  let unitTables;
@@ -72,22 +76,40 @@ export function createPersonPathRows(cfg) {
72
76
  raw = Promise.reject(err);
73
77
  }
74
78
  const outcomeOf = (view) => ({ seq, view: holdsPersonRows ? view : { ...view, rules: [] }, failed: holdsPersonRows ? failedOf(view) : new Set() });
79
+ const answer = () => void (answeredSeq = Math.max(answeredSeq, seq));
75
80
  void raw.then((view) => {
81
+ answer();
76
82
  for (const line of view.disclosures)
77
83
  cfg.onDisclosure(line);
78
84
  cfg.onRowsDropped(view.droppedRows);
79
85
  if (holdsPersonRows && view.unreadable !== undefined)
80
86
  announce(at, view.unreadable, view.unreadableSources);
81
87
  land(outcomeOf(view));
82
- }, () => undefined);
83
- return withGateTimeout(raw, PERSON_READ_BOUND_MS, cfg.signal, "personRules").then((view) => readOf(outcomeOf(view)), (err) => {
84
- const cut = gateWaitFailureOf(err) === "aborted";
88
+ }, answer);
89
+ const read = withGateTimeout(raw, PERSON_READ_BOUND_MS, cfg.signal, "personRules").then((view) => readOf(outcomeOf(view)), (err) => {
90
+ const failure = gateWaitFailureOf(err);
91
+ const cut = failure === "aborted";
85
92
  const outcome = { seq, failed: new Set(partitions), why: thrownText(err), ...(cut ? { cut: true } : {}) };
86
93
  land(outcome);
87
94
  if (holdsPersonRows && !cut)
88
95
  announce(at, outcome.why);
96
+ if (failure === "timeout" && seq > (silent?.seq ?? 0))
97
+ silent = { seq, read };
89
98
  return readOf(outcome);
90
99
  });
100
+ if (at === "prepare")
101
+ prepared = { seq, read };
102
+ return read;
103
+ };
104
+ const forRequest = () => {
105
+ const first = prepared;
106
+ prepared = undefined;
107
+ const s = silent;
108
+ const read = first !== undefined && first.seq === seqs ? first.read
109
+ : s !== undefined && s.seq > requestSeq && s.seq > answeredSeq ? s.read
110
+ : readOnce("call");
111
+ requestSeq = seqs;
112
+ return read;
91
113
  };
92
114
  const failedOf = (view) => view.unreadable !== undefined && (view.unreadableSources ?? []).length === 0 ? new Set(partitions) : new Set((view.unreadableSources ?? []).map(partitionOf).filter((p) => partitions.includes(p)));
93
115
  const defect = (message) => {
@@ -245,6 +267,7 @@ export function createPersonPathRows(cfg) {
245
267
  ? readOnce("prepare").then(() => undefined)
246
268
  : undefined,
247
269
  pin,
270
+ forRequest,
248
271
  tablesReady: (toolCallId, signal) => {
249
272
  const p = pinOf(toolCallId);
250
273
  const cut = signal === undefined || cfg.signal === undefined ? (signal ?? cfg.signal) : AbortSignal.any([signal, cfg.signal]);
@@ -14,7 +14,7 @@
14
14
  * cached view and never hands out a half-acquired resource.
15
15
  *
16
16
  * Throws pass through unchanged: `resume.session_not_found` (requireExisting fail-loud mapping),
17
- * the `resume_at.*` target-validation refusals, `invalid_session` for a log whose parent links loop back, and — after the
17
+ * the `resume_at.*` target-validation refusals, `corrupt_session` for a log whose parent links loop back, and — after the
18
18
  * bounded re-wake budget — the session conflict itself. A throw after a `resumeAt` branch landed first writes that branch
19
19
  * back (`settleBranchWriteBack`); on success the branch is handed over with the session.
20
20
  */
@@ -25,6 +25,7 @@ import type { TaskSpec, ToolEffect } from "../types.js";
25
25
  import type { PrepareResume } from "./contracts.js";
26
26
  import { type ResumeAtBranch } from "./branch-writeback.js";
27
27
  import { type LegWrites } from "./session-write-ledger.js";
28
+ import { replayLossLeg } from "./lineage-reroot-view.js";
28
29
  export interface PrepareAcquireReconcileInput {
29
30
  /** borrowed-mutable (service port) — the deployment's session store. This phase's verbs on it are
30
31
  * the acquire/forget half of the session resource protocol: `acquire` per attempt, `forget` to
@@ -57,6 +58,8 @@ export interface PrepareAcquireReconcileInput {
57
58
  report?: (err: Error, sessionId: string) => void;
58
59
  /** borrowed-mutable (the Runner's) — this leg's view of the session write ledger, every storage write issued through it ({@link writesThroughLeg}); absent for a standalone prepare. */
59
60
  legWrites?: LegWrites;
61
+ /** borrowed-readonly — where the leg says what the log's replay dropped, and re-rooted a branch at it ({@link replayLossLeg}): absent ⇒ nothing said and no re-root (a break is refused). */
62
+ replayLossNotice?: Parameters<typeof replayLossLeg>[0];
60
63
  }
61
64
  /** The phase's outputs (four-class form). All six are fresh bindings —
62
65
  * the driver destructures them into consts, so a consumer moved ahead of this call is a lexical
@@ -7,6 +7,7 @@ import { reconcileInterruptedSession } from "../session-reconcile.js";
7
7
  import { detectConflicts, settleBranchWriteBack } from "./branch-writeback.js";
8
8
  import { settleTeardownLeg } from "./teardown-bounded.js";
9
9
  import { writesThroughLeg } from "./session-write-ledger.js";
10
+ import { replayLossLeg } from "./lineage-reroot-view.js";
10
11
  const RECONCILE_MAX_RETRIES = 3;
11
12
  export async function prepareAcquireReconcile(input) {
12
13
  const { sessions, spec, resume, wakeEffects } = input;
@@ -15,6 +16,7 @@ export async function prepareAcquireReconcile(input) {
15
16
  let conflictRef;
16
17
  let wakeRecovered = [];
17
18
  let branch;
19
+ const lossLeg = input.replayLossNotice !== undefined ? replayLossLeg(input.replayLossNotice) : undefined;
18
20
  for (let attempt = 0;; attempt++) {
19
21
  try {
20
22
  acquired = await sessions.acquire(spec.sessionId, spec.requireExistingSession ? { requireExisting: true } : input.placement !== undefined ? { placement: input.placement } : undefined);
@@ -30,14 +32,15 @@ export async function prepareAcquireReconcile(input) {
30
32
  }
31
33
  conflictRef = { hit: false };
32
34
  const own = { ids: undefined };
33
- session = new StoredSession(detectConflicts(input.legWrites !== undefined ? writesThroughLeg(acquired.session.getStorage(), input.legWrites, acquired.sessionId) : acquired.session.getStorage(), conflictRef, own));
35
+ const legStorage = input.legWrites !== undefined ? writesThroughLeg(acquired.session.getStorage(), input.legWrites, acquired.sessionId) : acquired.session.getStorage();
36
+ session = new StoredSession(detectConflicts(lossLeg !== undefined ? lossLeg.view(legStorage, acquired.sessionId) : legStorage, conflictRef, own));
34
37
  if (!spec.sessionId) {
35
38
  break;
36
39
  }
37
40
  try {
38
41
  if (resume) {
39
42
  await session.getStorage().setLeafId(resume.leafId).catch((cut) => {
40
- throw readMember(cut, "code") === "not_found" ? new SessionError("invalid_session", `session "${spec.sessionId}" no longer holds the entry its checkpoint was cut at ("${resume.leafId}")`, cut) : cut;
43
+ throw readMember(cut, "code") === "not_found" ? new SessionError("corrupt_session", `session "${spec.sessionId}" no longer holds the entry its checkpoint was cut at ("${resume.leafId}")`, cut) : cut;
41
44
  });
42
45
  }
43
46
  else if (spec.resumeAt !== undefined) {
@@ -113,6 +116,7 @@ export async function prepareAcquireReconcile(input) {
113
116
  await settleTeardownLeg(() => Promise.resolve(forget(id)).catch(() => undefined), "forget (acquire-reconcile re-wake leg)", (e) => input.report?.(e, id));
114
117
  }
115
118
  branch = undefined;
119
+ lossLeg?.discard();
116
120
  continue;
117
121
  }
118
122
  if (branch !== undefined)
@@ -121,5 +125,6 @@ export async function prepareAcquireReconcile(input) {
121
125
  throw err;
122
126
  }
123
127
  }
128
+ lossLeg?.settle();
124
129
  return { acquired, session, conflictRef, wakeRecovered, branch };
125
130
  }
@@ -59,6 +59,7 @@ export interface PrepareCapsAndWorkflowInput {
59
59
  * the chain's auto-mode face (`inheritedGate.autoModeFace`). */
60
60
  internals: Pick<RunInternals, "rootSessionId" | "placementRoot" | "onTaskNotification" | "workflowDepth" | "memoryCaptureAncestors" | "workflowParkedResume" | "holder" | "questionFaceStripped" | "inheritedGate"> | undefined;
61
61
  /** borrowed-readonly — the tree's cross-boundary token (inherited or minted), which the Workflow mount hands to its children. */ crossBoundaryTree: import("../cross-boundary-taint.js").CrossBoundaryTreeToken;
62
+ /** borrowed-readonly — the tree's owner seat, which the Workflow mount hands to its children (by reference). */ delegationOwner: import("./delegation-owner.js").DelegationOwnerSeat;
62
63
  /** borrowed-readonly — the acquired session; the classifier leg rebuilds its transcript window from `buildContext`. */
63
64
  session: Pick<StoredSession, "buildContext">;
64
65
  /** borrowed-readonly — the acquired session id (operator-line context, the refusal codes' phase record). */
@@ -331,7 +331,7 @@ export async function prepareCapsAndWorkflow(input) {
331
331
  scope: taskScope,
332
332
  notifier: deps.workflowCompletionNotifier,
333
333
  originatingSessionId: sessionId,
334
- rootSessionId: internals?.rootSessionId ?? sessionId, ...(internals?.placementRoot !== undefined ? { placementRoot: internals.placementRoot } : {}), crossBoundaryTree: input.crossBoundaryTree,
334
+ rootSessionId: internals?.rootSessionId ?? sessionId, ...(internals?.placementRoot !== undefined ? { placementRoot: internals.placementRoot } : {}), crossBoundaryTree: input.crossBoundaryTree, delegationOwner: input.delegationOwner,
335
335
  taskRegistry: defaultTaskRegistry,
336
336
  taskNotification: internals?.onTaskNotification, ...(taskArtifacts !== undefined ? { taskArtifacts } : {}),
337
337
  taskOwner: hostTaskId,
@@ -24,7 +24,6 @@ import type { ThinkingLevel } from "../../internal/harness.js";
24
24
  import { type MicroCompactMachine } from "../context-edit.js";
25
25
  import { type CrossBoundaryPosture } from "../cross-boundary-taint.js";
26
26
  import { type HostFloor } from "../host-floor.js";
27
- import { type CheckpointState } from "../checkpoint-store.js";
28
27
  import { runOriginOfLeg, type RunOrigin } from "../run-origin.js";
29
28
  import { type ConfigDoorEntry, type LockedPreflight, type ReceivedPeerDeclarations } from "../locked-config.js";
30
29
  import { type ResolvedRole } from "../roles.js";
@@ -269,15 +268,16 @@ export declare function configValueDoors(input: {
269
268
  * The doors a RESUMED leg's prepare refuses at, run as one screen BEFORE the claim — prepare's own functions, so a refusal carries
270
269
  * the very sentence and code prepare throws: the mode doors (`refusePermissionModeDoors`), the output-style seat, the approval
271
270
  * reach, the skills invoked by name (the part no roster changes), the attachments (a resume sends no new human message, so any
272
- * entry is refused), the leg declarations of the tools it re-supplies (this phase's first door), this phase's value doors over the config, the deployment's deps and the session store the Runner holds
273
- * ({@link configValueDoors}, the retention capability door and the run-origin door over the row's recorded word included) and the mode
274
- * words the row recorded (`recordedModeSeed`). It leaves by the resume's ONE refusal channel (`asResumeConfigRefusal`:
271
+ * entry is refused), the leg declarations of the tools it re-supplies (this phase's first door), and this phase's value doors over the config, the deployment's deps and the session store the Runner holds
272
+ * ({@link configValueDoors}, the retention capability door and the run-origin door over the config's word included). The words the
273
+ * row recorded (its mode seed, its run origin) are not this door's: the row's own verdict judged them before it (`judgeCheckpointRow`,
274
+ * checkpoint-row-verdict.ts), so this door reads nothing off the row. It leaves by the resume's ONE refusal channel (`asResumeConfigRefusal`:
275
275
  * `checkpoint.config_refused`, `detail.code` = prepare's code, `detail.field` = `"taskConfig"`, `"deps"` or `"inheritedGate"`)
276
276
  * where prepare would end the leg `failed` after the claim — the row consumed on a store without `reopen`, replayed as a system
277
277
  * retry on one with it, which a configuration fix cannot reach. Before the claim the row stays `pending` and byte-identical and the
278
278
  * corrected resume redeems the same token. A throw that is none of prepare's codes leaves as it was thrown. Returns the config the
279
- * leg is handed: the caller's, its MCP servers and A2A peers the frozen entries the lock layer judged (read once, dialed as judged).
279
+ * leg is handed: the caller's, its MCP servers and A2A peers the lock layer's judged copies of the lists THIS resume handed (read once, dialed as judged; the row records none).
280
280
  */
281
- export declare function refuseResumeDoors<C extends ValueDoorSpec & Pick<TaskSpec, "userAttachments">>(config: C, recorded: Pick<CheckpointState, "inheritedGate" | "runOrigin"> | undefined, deps: RunnerDeps, sessions: SessionStore, holder?: string): C;
281
+ export declare function refuseResumeDoors<C extends ValueDoorSpec & Pick<TaskSpec, "userAttachments">>(config: C, deps: RunnerDeps, sessions: SessionStore, holder?: string): C;
282
282
  export declare function prepareConfigDoors(input: PrepareConfigDoorsInput): PrepareConfigDoorsResult;
283
283
  export {};
@@ -5,7 +5,7 @@ import { assertAddOnlySeats } from "../child-clamp-seats.js";
5
5
  import { CROSS_BOUNDARY_POSTURES } from "../cross-boundary-taint.js";
6
6
  import { compileHostFloor } from "../host-floor.js";
7
7
  import { assertNoRetiredRunnerDeps } from "./retired-runner-deps.js";
8
- import { recordedModeSeed, resolveCheckpointStore } from "../checkpoint-store.js";
8
+ import { resolveCheckpointStore } from "../checkpoint-store.js";
9
9
  import { runOriginOfLeg, screenRecordedRunOrigin } from "../run-origin.js";
10
10
  import { assertCheckpointStoreJudgesHolder, assertHolderValue } from "../checkpoint-generation.js";
11
11
  import { asResumeConfigRefusal, refusePermissionModeDoors } from "../mode-policy.js";
@@ -346,7 +346,7 @@ export function configValueDoors(input, enter = ENTER_AS_IS) {
346
346
  enter("taskConfig", () => assertRetentionWords({ ...retention, stores: [{ name: "checkpointStore", store: taskStore }] }));
347
347
  return { toolFaceLists, promptHost, promptBinding, promptLean, lockedPreflight, skillListingSeats, skills, projectMemory, microCompactKnob, memoryDelegationEvidence, memoryProvenance, memoryCapturePolicy, usageWindows, brainCallGuardrailMs, crossBoundaryPosture, advisorTool, hostFloor, runOrigin, deploymentRoles, taskRoles };
348
348
  }
349
- export function refuseResumeDoors(config, recorded, deps, sessions, holder) {
349
+ export function refuseResumeDoors(config, deps, sessions, holder) {
350
350
  asResumeConfigRefusal("taskConfig", () => {
351
351
  refusePermissionModeDoors(config);
352
352
  resolveOutputStyleFrame(config.outputStyle);
@@ -356,8 +356,7 @@ export function refuseResumeDoors(config, recorded, deps, sessions, holder) {
356
356
  assertToolBoundaryLegs(config.tools);
357
357
  assertToolCardDeclarations(config.tools);
358
358
  });
359
- const { lockedPreflight, skills } = configValueDoors({ spec: config, deps, resumeLeg: true, sessions, holder, ...(recorded !== undefined ? { resumedRow: { recorded: recorded.runOrigin } } : {}) }, asResumeConfigRefusal);
360
- asResumeConfigRefusal("inheritedGate", () => void recordedModeSeed(recorded?.inheritedGate));
359
+ const { lockedPreflight, skills } = configValueDoors({ spec: config, deps, resumeLeg: true, sessions, holder, resumedRow: { recorded: undefined } }, asResumeConfigRefusal);
361
360
  return { ...config, ...(config.mcp !== undefined ? { mcp: lockedPreflight.mcp ?? [] } : {}), ...(config.a2a !== undefined ? { a2a: lockedPreflight.a2a ?? [] } : {}), skills };
362
361
  }
363
362
  export function prepareConfigDoors(input) {
@@ -6,7 +6,7 @@ import { type ShellReadAdmission, type ShellReadCheck, type ShellReadLandings }
6
6
  import { type ReadFloorSeat } from "../../tools/fs/read-floor.js";
7
7
  import type { ShellReadBoundary } from "../../tools/fs/shell-read-judge.js";
8
8
  import type { RunnerDeps, ShellGateDoctrine, TaskSpec } from "../types.js";
9
- import type { Model } from "../../internal/llm.js";
9
+ import { type Model } from "../../internal/llm.js";
10
10
  import type { AgentHarness, AgentTool, ExecutionEnv, WorkspaceState } from "../../internal/harness.js";
11
11
  import type { AdvertisedWritableDirs } from "./advertised-writable-dirs.js";
12
12
  import { type ArtifactStoreRef, type GrantReadRoot } from "./read-root-grant.js";
@@ -15,10 +15,11 @@ import { isShellFaceToolName, predictMountedToolNames, readTargetToolNames } fro
15
15
  import { normalizeFileText } from "../../tools/fs/encoding.js";
16
16
  import { wholeFileRecordsFromTranscript } from "./session-file-state-replay.js";
17
17
  import { deliverEngineNotice } from "../types.js";
18
+ import { toolNameIndex } from "../../internal/llm.js";
18
19
  import { readRootGrantOver } from "./read-root-grant.js";
19
20
  import { sessionSeatAnchorHolds } from "./session-read-file-states.js";
20
21
  import { rebaseWorkspacePath } from "./workspace-path.js";
21
- import { RosterBuilder } from "../tool-roster.js";
22
+ import { RosterBuilder, survivorsByName } from "../tool-roster.js";
22
23
  import { unionAddOnly } from "../child-clamp-seats.js";
23
24
  import { assertStringArraySeat, screenReadDenySeat } from "../read-face-seats.js";
24
25
  import { modePolicyOf } from "../mode-policy.js";
@@ -346,6 +347,7 @@ export async function prepareHandsMount(input) {
346
347
  exempt: (key) => bgOutputExempt?.(key) === true,
347
348
  });
348
349
  }
350
+ const valveLeft = valveLeaves(spec, toolFaceSnapshot.selector);
349
351
  const band = createHandsToolkit(executionEnv, readFileState, rootCanonical, {
350
352
  ...(additionalRootsCanonical.length > 0 ? { additionalRoots: additionalRootsCanonical } : {}),
351
353
  writeRoot: input.writeLocation,
@@ -388,14 +390,33 @@ export async function prepareHandsMount(input) {
388
390
  return memoryWriteGate?.(w);
389
391
  },
390
392
  mountBackgroundTaskTools: false,
391
- monitorToolActive: backgroundTaskToolsActive && valveLeaves(spec, toolFaceSnapshot.selector)({ name: "Monitor" }),
393
+ monitorToolActive: backgroundTaskToolsActive && valveLeft({ name: "Monitor" }),
392
394
  });
393
395
  {
394
- const bandNames = new Set(band.flatMap((t) => [t.name, ...(t.aliases ?? [])]));
395
- const shadowed = (spec.tools ?? []).filter((t) => [t.name, ...(t.aliases ?? [])].some((n) => bandNames.has(n)));
396
- if (shadowed.length > 0) {
397
- const names = shadowed.map((t) => `"${t.name}"`).join(", ");
398
- deps.onError?.(new Error(`spec.tools ${shadowed.length > 1 ? "entries" : "entry"} ${names} collide${shadowed.length > 1 ? "" : "s"} with the built-in hands tool band — the built-in wins (registered later; the harness tool Map is last-write-wins) and the caller tool never dispatches this task. Rename the caller tool, or don't inject executionEnv if you intend to replace the band.`), { phase: "config", sessionId });
396
+ const callerLeft = (spec.tools ?? []).filter((t) => valveLeft(t));
397
+ const bandLeft = band.filter((t) => valveLeft(t));
398
+ const bandTools = new Set(bandLeft);
399
+ const serves = toolNameIndex([...survivorsByName([...callerLeft, ...bandLeft]).values()]);
400
+ const lostTo = (name, tool) => {
401
+ const holder = serves(name);
402
+ return holder !== undefined && holder !== tool && bandTools.has(holder) ? holder : undefined;
403
+ };
404
+ const collisions = [];
405
+ for (const t of callerLeft) {
406
+ const replacedBy = lostTo(t.name, t);
407
+ if (replacedBy !== undefined) {
408
+ collisions.push(`"${t.name}" is replaced by the built-in "${replacedBy.name}", which serves that name (the caller tool never dispatches)`);
409
+ continue;
410
+ }
411
+ const aliases = (t.aliases ?? []).flatMap((a) => {
412
+ const holder = lostTo(a, t);
413
+ return holder === undefined ? [] : [`"${a}" serves the built-in "${holder.name}"`];
414
+ });
415
+ if (aliases.length > 0)
416
+ collisions.push(`"${t.name}" stays mounted under its own name, but its ${aliases.length > 1 ? "aliases" : "alias"} ${aliases.join(" and ")}`);
417
+ }
418
+ if (collisions.length > 0) {
419
+ deps.onError?.(new Error(`spec.tools ${collisions.length > 1 ? "entries collide" : "entry collides"} with the built-in hands tool band — the built-in wins each contested name: ${collisions.join("; ")}. Rename the colliding name, or don't inject executionEnv if you intend to replace the band.`), { phase: "config", sessionId });
399
420
  }
400
421
  }
401
422
  roster.mountAll(band.map((t) => (envHandToolNames.add(t.name), firstPartyOffload(afterCallTables(input.personRows, t)))), { source: "builtin", mountedBy: "hands" });
@@ -74,6 +74,8 @@ export interface PrepareInheritedGateInput {
74
74
  askSeat: import("../wiring-manifest.js").AskSeat;
75
75
  /** borrowed-readonly — the tree's cross-boundary token (the leg's lane: inherited, or minted by a root leg), handed to children. */
76
76
  crossBoundaryTree: import("../cross-boundary-taint.js").CrossBoundaryTreeToken;
77
+ /** borrowed-readonly — the run's delegation tree owner seat (the spawner's, or one over the row this run acquired). */
78
+ delegationOwner: import("./delegation-owner.js").DelegationOwnerSeat;
77
79
  /** borrowed-readonly — the trusted spawn-side channel: `inheritedGate` (the LIVE half of the chain fold), `ownOrgAdmissionRef`
78
80
  * (the same-session continuation's freeze), `delegationProvenance` (the F-012 stamp), and the identity / peer / notification
79
81
  * seats the ctx enrichment forwards. Never mutated. */
@@ -1,4 +1,4 @@
1
- import { principalNameOf } from "../principal-name.js";
1
+ import { delegationOwnerUnbound } from "./delegation-owner.js";
2
2
  import { forkGovernanceDenial, resolveDelegationEntryCaps } from "../../agents/subagent.js";
3
3
  import { isLiveQuestionFace } from "../ask-question.js";
4
4
  import { parentSpecSeatOf } from "../parent-spec-seat.js";
@@ -11,7 +11,7 @@ import { chainAnchorRecords } from "./child-tree.js";
11
11
  import { deliverEngineNotice } from "../types.js";
12
12
  import { PermissionModeController, autoModeFaceOf, modeRequestAfterResume } from "../mode-policy.js";
13
13
  import { SessionModeSeats } from "./session-mode-seats.js";
14
- import { recordedModeSeed } from "../checkpoint-store.js";
14
+ import { recordedModeSeed } from "../checkpoint-row-verdict.js";
15
15
  import { frozenSkillGrants } from "../skill-grant.js";
16
16
  import { attachRebuiltDenialTrackers, createDenialLimitStop } from "./denial-limit-arms.js";
17
17
  import { valveLeaves } from "../../agents/tool-filter.js";
@@ -249,6 +249,7 @@ export function prepareInheritedGate(input) {
249
249
  ...(internals?.parentTaskId !== undefined ? { parentTaskId: internals.parentTaskId } : {}),
250
250
  ...(internals?.parentSessionId !== undefined ? { parentSessionId: internals.parentSessionId } : {}),
251
251
  ...(internals?.rootSessionId !== undefined ? { rootSessionId: internals.rootSessionId } : {}), ...(internals?.placementRoot !== undefined ? { placementRoot: internals.placementRoot } : {}),
252
+ delegationOwner: input.delegationOwner,
252
253
  ...(internals?.explicitAgentName !== undefined ? { spawnedAgentName: internals.explicitAgentName } : {}),
253
254
  ...(internals?.peerSelfRef !== undefined ? { peerSelfRef: internals.peerSelfRef } : {}),
254
255
  ...(internals?.peerInboundChainRef !== undefined ? { peerInboundChainRef: internals.peerInboundChainRef } : {}),
@@ -256,7 +257,10 @@ export function prepareInheritedGate(input) {
256
257
  ...(sessions.fork !== undefined
257
258
  ? {
258
259
  hostSessionFork: async () => {
259
- const forked = (await sessions.fork(sessionId, principalNameOf(spec.principal) ?? null)) ?? null;
260
+ const tree = await input.delegationOwner.read();
261
+ if (!tree.bound)
262
+ throw delegationOwnerUnbound(tree.reason);
263
+ const forked = (await sessions.fork(sessionId, tree.owner)) ?? null;
260
264
  if (forked === null)
261
265
  return null;
262
266
  return {