@sema-agent/core 7.63.0 → 7.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +408 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent.js +20 -3
  23. package/dist/core/allow-entry.d.ts +4 -0
  24. package/dist/core/ask-origin.d.ts +1 -1
  25. package/dist/core/ask-origin.js +2 -2
  26. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  27. package/dist/core/ask-unresolvable-notice.js +10 -3
  28. package/dist/core/auto-compaction.d.ts +7 -5
  29. package/dist/core/background-agent-store.d.ts +7 -0
  30. package/dist/core/background-agent-store.js +3 -0
  31. package/dist/core/checkpoint-queries.d.ts +9 -6
  32. package/dist/core/checkpoint-queries.js +8 -3
  33. package/dist/core/checkpoint-store.d.ts +5 -1
  34. package/dist/core/context-settings.d.ts +40 -9
  35. package/dist/core/context-settings.js +32 -10
  36. package/dist/core/engine-attestation.d.ts +26 -6
  37. package/dist/core/engine-attestation.js +5 -1
  38. package/dist/core/engine-notice.d.ts +24 -1
  39. package/dist/core/extension-requester.d.ts +9 -0
  40. package/dist/core/extension-requester.js +7 -0
  41. package/dist/core/file-history-store.d.ts +28 -0
  42. package/dist/core/file-history-store.js +48 -5
  43. package/dist/core/fs-write-gate-policy.js +1 -1
  44. package/dist/core/gate-fold.js +2 -0
  45. package/dist/core/gate-lanes.js +2 -0
  46. package/dist/core/gate-outcome.d.ts +39 -2
  47. package/dist/core/gate-outcome.js +20 -1
  48. package/dist/core/governance-codes.d.ts +3 -1
  49. package/dist/core/governance-codes.js +4 -0
  50. package/dist/core/leg-identity.d.ts +19 -1
  51. package/dist/core/leg-identity.js +12 -0
  52. package/dist/core/mailbox-store.d.ts +39 -4
  53. package/dist/core/mailbox-store.js +14 -2
  54. package/dist/core/memory-engine/consolidation.d.ts +3 -2
  55. package/dist/core/memory-engine/consolidation.js +16 -0
  56. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  57. package/dist/core/memory-engine/control-objects.js +151 -0
  58. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  59. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  60. package/dist/core/memory-engine/delegation-settlement.d.ts +21 -5
  61. package/dist/core/memory-engine/delegation-settlement.js +217 -26
  62. package/dist/core/memory-engine/dual-root.js +2 -2
  63. package/dist/core/memory-engine/engine.d.ts +38 -23
  64. package/dist/core/memory-engine/engine.js +14 -14
  65. package/dist/core/memory-engine/file-backend.d.ts +41 -65
  66. package/dist/core/memory-engine/file-backend.js +59 -166
  67. package/dist/core/memory-engine/index.d.ts +3 -2
  68. package/dist/core/memory-engine/index.js +2 -1
  69. package/dist/core/memory-engine/layout.d.ts +6 -1
  70. package/dist/core/memory-engine/layout.js +12 -7
  71. package/dist/core/memory-engine/memory-backend-contract.d.ts +10 -3
  72. package/dist/core/memory-engine/memory-backend-contract.js +158 -2
  73. package/dist/core/memory-engine/memory-deployment.d.ts +11 -3
  74. package/dist/core/memory-engine/memory-deployment.js +31 -6
  75. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  76. package/dist/core/memory-engine/origin-clearance.js +68 -9
  77. package/dist/core/memory-engine/session-write-home.d.ts +34 -1
  78. package/dist/core/memory-engine/session-write-home.js +37 -10
  79. package/dist/core/memory-engine/types.d.ts +44 -7
  80. package/dist/core/memory-engine/types.js +2 -1
  81. package/dist/core/mode-policy.js +3 -3
  82. package/dist/core/mods/agent-stations.d.ts +18 -0
  83. package/dist/core/mods/agent-stations.js +8 -6
  84. package/dist/core/mods/extension-call.d.ts +4 -0
  85. package/dist/core/mods/extension-call.js +8 -0
  86. package/dist/core/mods/tool-call.js +3 -4
  87. package/dist/core/parent-spec-seat.d.ts +2 -2
  88. package/dist/core/peer-channel.d.ts +5 -0
  89. package/dist/core/permission-rule-consent.d.ts +21 -10
  90. package/dist/core/permission-rule-consent.js +50 -23
  91. package/dist/core/permission-rule-store.d.ts +41 -16
  92. package/dist/core/permission-rule-store.js +2 -0
  93. package/dist/core/refusal-echo.d.ts +20 -0
  94. package/dist/core/refusal-echo.js +33 -0
  95. package/dist/core/retention.d.ts +180 -10
  96. package/dist/core/retention.js +45 -0
  97. package/dist/core/retired-keys.d.ts +5 -0
  98. package/dist/core/retired-keys.js +3 -0
  99. package/dist/core/rule-offer-read.d.ts +0 -4
  100. package/dist/core/rule-offer-read.js +2 -18
  101. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  102. package/dist/core/runner/classifier-ladder.js +4 -2
  103. package/dist/core/runner/compact-session.js +10 -7
  104. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  105. package/dist/core/runner/compaction-call-options.js +3 -2
  106. package/dist/core/runner/contracts.d.ts +21 -2
  107. package/dist/core/runner/delegation-owner.d.ts +10 -3
  108. package/dist/core/runner/delegation-owner.js +4 -1
  109. package/dist/core/runner/gate-exit.d.ts +6 -0
  110. package/dist/core/runner/gate-exit.js +11 -2
  111. package/dist/core/runner/memory-consolidation-driver.d.ts +4 -2
  112. package/dist/core/runner/memory-consolidation-driver.js +8 -5
  113. package/dist/core/runner/prepare-ask-lane.js +3 -3
  114. package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -1
  115. package/dist/core/runner/prepare-caps-and-workflow.js +2 -2
  116. package/dist/core/runner/prepare-config-doors.js +4 -0
  117. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  118. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  119. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  120. package/dist/core/runner/prepare-gate-stations.js +5 -5
  121. package/dist/core/runner/prepare-hands-readface.js +1 -1
  122. package/dist/core/runner/prepare-inherited-gate.d.ts +3 -1
  123. package/dist/core/runner/prepare-inherited-gate.js +4 -2
  124. package/dist/core/runner/prepare-memory.d.ts +4 -0
  125. package/dist/core/runner/prepare-memory.js +14 -20
  126. package/dist/core/runner/prepare-policy-chain.js +7 -7
  127. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  128. package/dist/core/runner/prepare-task.js +15 -10
  129. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  130. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  131. package/dist/core/runner/resume-admission.d.ts +2 -2
  132. package/dist/core/runner/resume-admission.js +2 -23
  133. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  134. package/dist/core/runner/role-resolution-table.js +62 -0
  135. package/dist/core/runner/run-compaction-machinery.js +2 -2
  136. package/dist/core/runner/run-identity-wiring.js +12 -9
  137. package/dist/core/runner/run-leg.js +8 -4
  138. package/dist/core/runner/run-notification-lane.js +22 -22
  139. package/dist/core/runner/run-recovery-lanes.js +3 -3
  140. package/dist/core/runner/run-terminal-adoption.js +1 -1
  141. package/dist/core/runner/run-turn-boundary.js +14 -15
  142. package/dist/core/runner/runtask.js +1 -1
  143. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  144. package/dist/core/runner/tool-occurrence.js +2 -2
  145. package/dist/core/runner-deps.d.ts +1 -1
  146. package/dist/core/session-checkout.d.ts +63 -3
  147. package/dist/core/session-checkout.js +152 -58
  148. package/dist/core/shell-read-silence.js +8 -0
  149. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  150. package/dist/core/task-event.d.ts +9 -5
  151. package/dist/core/task-notification.d.ts +110 -31
  152. package/dist/core/task-notification.js +180 -100
  153. package/dist/core/task-registry-agent.d.ts +11 -0
  154. package/dist/core/task-registry-agent.js +11 -3
  155. package/dist/core/task-registry-shared.d.ts +7 -0
  156. package/dist/core/task-registry.d.ts +18 -0
  157. package/dist/core/task-registry.js +27 -8
  158. package/dist/core/task-spec.d.ts +7 -2
  159. package/dist/core/tool-errors.d.ts +14 -6
  160. package/dist/core/tool-errors.js +1 -1
  161. package/dist/core/tool-policy.d.ts +18 -1
  162. package/dist/core/tool-policy.js +16 -7
  163. package/dist/core/tool-result-store.d.ts +20 -0
  164. package/dist/core/tool-spec.d.ts +4 -0
  165. package/dist/core/trace.d.ts +3 -2
  166. package/dist/core/workflow-journal-store.d.ts +11 -0
  167. package/dist/core/workflow-journal-store.js +7 -0
  168. package/dist/core/workflow-run-store.d.ts +9 -0
  169. package/dist/core/workflow-run-store.js +6 -0
  170. package/dist/engine/compaction/compaction.d.ts +2 -1
  171. package/dist/engine/harness/types.d.ts +1 -0
  172. package/dist/engine/session/session.d.ts +7 -1
  173. package/dist/engine/session/session.js +5 -2
  174. package/dist/index.d.ts +7 -5
  175. package/dist/index.js +7 -5
  176. package/dist/orchestration/run-workflow-tool.d.ts +4 -0
  177. package/dist/orchestration/run-workflow-tool.js +7 -0
  178. package/dist/orchestration/workflow-types.d.ts +2 -1
  179. package/dist/orchestration/workflow.d.ts +3 -0
  180. package/dist/orchestration/workflow.js +2 -1
  181. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  182. package/dist/stores/file/checkpoint-store.js +4 -1
  183. package/dist/stores/file/file-history-store.d.ts +13 -0
  184. package/dist/stores/file/file-history-store.js +75 -13
  185. package/dist/stores/file/index.d.ts +11 -1
  186. package/dist/stores/file/index.js +7 -11
  187. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  188. package/dist/stores/file/permission-rule-store.js +75 -7
  189. package/dist/stores/file/tool-result-store.d.ts +14 -0
  190. package/dist/stores/file/tool-result-store.js +39 -2
  191. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  192. package/dist/stores/file/workflow-journal-store.js +17 -0
  193. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  194. package/dist/stores/file/workflow-run-store.js +15 -0
  195. package/dist/tools/fs/read-deny.d.ts +15 -2
  196. package/dist/tools/fs/read-deny.js +10 -2
  197. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  198. package/dist/tools/fs/shell-read-check.js +7 -7
  199. package/package.json +2 -2
  200. package/test/export-surface.snapshot.json +63 -1
  201. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  202. package/wire-changes/core@7.64.0.json +2653 -0
  203. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  204. package/wire-changes/primitives@7.64.0.json +30 -0
@@ -1,5 +1,6 @@
1
1
  import type { SubagentEditedFile, SubagentStep } from "../agents/subagent-steps.js";
2
2
  import type { SubagentTranscriptTier } from "./wiring-manifest.js";
3
+ import type { ExtensionRequester } from "./task-event.js";
3
4
  /** Terminal/live usage rollup persisted on the row (mirror of the task_notification/BCE fields). */
4
5
  export interface BackgroundAgentUsage {
5
6
  totalTokens?: number;
@@ -44,6 +45,11 @@ export interface BackgroundAgentRecord {
44
45
  * earlier version wrote without one derives it from `handle` with the same function. */
45
46
  name: string;
46
47
  agentType?: string;
48
+ /** Who started the agent when an extension did: the extension, by its registration name (`$.agent.spawn`). Written once, by the
49
+ * registration that creates the row; a revival keeps it (the row's origin, not the waker's). ABSENT = not an extension's spawn
50
+ * (the model's own, the host's) — and every row an earlier release wrote: the one reading, with no word for either. A display and
51
+ * audit fact only — it decides nothing. */
52
+ requestedBy?: ExtensionRequester;
47
53
  description?: string;
48
54
  /** Revival lookup key (CC meta-sidecar parity); populated when known, never required. The team
49
55
  * key is {@link rootSessionId} — one implicit team per session, no column of its own. */
@@ -208,6 +214,7 @@ export interface BackgroundAgentRowSummary {
208
214
  rootSessionId?: string;
209
215
  name: string;
210
216
  agentType?: string;
217
+ requestedBy?: ExtensionRequester;
211
218
  status: BackgroundAgentRecord["status"];
212
219
  spawnedAt: number;
213
220
  updatedAt: number;
@@ -1,5 +1,6 @@
1
1
  import { uuidv7 } from "../internal/harness.js";
2
2
  import { receiveRetentionPolicy } from "./retention-policy.js";
3
+ import { readExtensionRequester } from "./extension-requester.js";
3
4
  export const REVIVED_ROW_CLEARED_FIELDS = Object.freeze([
4
5
  "settledAt",
5
6
  "stoppedBy",
@@ -178,6 +179,7 @@ export async function reconcileParkedAgents(stores, scope, now, opts) {
178
179
  return out;
179
180
  }
180
181
  function toSummary(r) {
182
+ const requestedBy = readExtensionRequester(r.requestedBy);
181
183
  return {
182
184
  handle: r.handle,
183
185
  owner: r.owner,
@@ -187,6 +189,7 @@ function toSummary(r) {
187
189
  ...(r.rootSessionId !== undefined ? { rootSessionId: r.rootSessionId } : {}),
188
190
  name: r.name,
189
191
  ...(r.agentType !== undefined ? { agentType: r.agentType } : {}),
192
+ ...(requestedBy !== undefined ? { requestedBy } : {}),
190
193
  status: r.status,
191
194
  spawnedAt: r.spawnedAt,
192
195
  updatedAt: r.updatedAt,
@@ -174,18 +174,21 @@ interface RowMembers {
174
174
  readonly deadline: unknown;
175
175
  readonly state: unknown;
176
176
  readonly checkpointId: unknown;
177
+ readonly resourceLedger: unknown;
177
178
  }
178
179
  /** The members {@link ROW_MEMBER_SHAPES} reads — no other (none a store's own transitions rewrite). */
179
- type ShapeMembers = Pick<RowMembers, "gate" | "pendingAction" | "state" | "createdAt" | "deadline">;
180
+ type ShapeMembers = Pick<RowMembers, "gate" | "pendingAction" | "state" | "createdAt" | "deadline" | "resourceLedger" | "checkpointId">;
180
181
  /**
181
182
  * THE ROW'S MEMBER SHAPES — the reading every reader of a stored row makes of the members it reaches into, written once: the row
182
183
  * judge (`judgeCheckpointRow`, the resume's first rung), the listing projection (`summarizeCheckpoint`) and the listing faces read
183
184
  * this table and no shape test of their own, so over these members no face answers `ok` for a row another cannot read. The gate a
184
- * record of a registered gate kind; the pending action a record of a registered pending kind, a tool approval carrying a tool call
185
- * id; the state a record; `createdAt` a finite number; `deadline` absent or a finite number. Each entry names the member by its
186
- * shape, never its value; `undefined` = it reads.
185
+ * record of a registered gate kind; the pending action a record of a registered pending kind — the one the gate's kind pairs with in
186
+ * the pause registry — a tool approval carrying a tool call id; the state a record; `createdAt` a finite number; `deadline` absent or a finite number; the resource ledger absent or a record
187
+ * (the summary reads its spend); the checkpoint id absent or a non-empty string (the summary echoes it and names the row by it: an
188
+ * empty one names no row, and no writer mints one). Each entry names the member by its shape, never a particular value; `undefined`
189
+ * = it reads.
187
190
  */
188
- declare const ROW_MEMBER_SHAPES: readonly [readonly ["gate", (m: ShapeMembers) => string | undefined], readonly ["pendingAction", (m: ShapeMembers) => string | undefined], readonly ["state", (m: ShapeMembers) => string | undefined], readonly ["createdAt", (m: ShapeMembers) => string | undefined], readonly ["deadline", (m: ShapeMembers) => string | undefined]];
191
+ declare const ROW_MEMBER_SHAPES: readonly [readonly ["gate", (m: ShapeMembers) => string | undefined], readonly ["pendingAction", (m: ShapeMembers) => string | undefined], readonly ["state", (m: ShapeMembers) => string | undefined], readonly ["createdAt", (m: ShapeMembers) => string | undefined], readonly ["deadline", (m: ShapeMembers) => string | undefined], readonly ["resourceLedger", (m: ShapeMembers) => string | undefined], readonly ["checkpointId", (m: ShapeMembers) => string | undefined]];
189
192
  /** A member {@link ROW_MEMBER_SHAPES} names. */
190
193
  export type RowMemberName = (typeof ROW_MEMBER_SHAPES)[number][0];
191
194
  /** The first member of a row that does not read as {@link ROW_MEMBER_SHAPES} says, and the table's words for it. */
@@ -195,7 +198,7 @@ export interface RowMemberProblem {
195
198
  }
196
199
  /**
197
200
  * Where a row's members fail {@link ROW_MEMBER_SHAPES} — the one reading the row judge, the summary projection and the listing faces
198
- * make of them: the first member that does not read and the table's words for it; `undefined` = every member reads. Reads the five
201
+ * make of them: the first member that does not read and the table's words for it; `undefined` = every member reads. Reads the seven
199
202
  * members the table names, each once. May throw (a member that throws when read); the caller is total.
200
203
  */
201
204
  export declare function rowMemberProblem(cp: Checkpoint): RowMemberProblem | undefined;
@@ -1,5 +1,5 @@
1
1
  import { types } from "node:util";
2
- import { facetOf, isGateKind, isPendingKind } from "./pause-registry.js";
2
+ import { facetOf, isGateKind, isPendingKind, PAUSE_REGISTRY } from "./pause-registry.js";
3
3
  import { receiptRefusal, receiveOwnProperties } from "./own-property-receipt.js";
4
4
  import { principalNameOf } from "./principal-name.js";
5
5
  export const CHECKPOINT_LIST_LIMITS = Object.freeze({
@@ -132,7 +132,7 @@ function orderKey(value) {
132
132
  return typeof value === "number" && Number.isFinite(value) ? value : -Infinity;
133
133
  }
134
134
  function membersOf(key, cp) {
135
- return { key, token: cp.token, sessionId: cp.sessionId, scope: cp.scope, status: cp.status, gate: cp.gate, pendingAction: cp.pendingAction, createdAt: cp.createdAt, deadline: cp.deadline, state: cp.state, checkpointId: cp.checkpointId };
135
+ return { key, token: cp.token, sessionId: cp.sessionId, scope: cp.scope, status: cp.status, gate: cp.gate, pendingAction: cp.pendingAction, createdAt: cp.createdAt, deadline: cp.deadline, state: cp.state, checkpointId: cp.checkpointId, resourceLedger: cp.resourceLedger };
136
136
  }
137
137
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
138
138
  function memberOf(value, key) {
@@ -149,12 +149,17 @@ const ROW_MEMBER_SHAPES = Object.freeze([
149
149
  const kind = memberOf(m.pendingAction, "kind");
150
150
  if (!isPendingKind(kind))
151
151
  return "its pending action is not an object of a registered pending kind";
152
+ const gateKind = memberOf(m.gate, "kind");
153
+ if (isGateKind(gateKind) && PAUSE_REGISTRY[gateKind].pending !== kind)
154
+ return "its pending action is not the one its gate kind pairs with";
152
155
  return kind === "tool_approval" && typeof memberOf(m.pendingAction, "toolCallId") !== "string" ? "its tool approval carries no tool call id" : undefined;
153
156
  },
154
157
  ],
155
158
  ["state", (m) => (isRecord(m.state) ? undefined : "its state is not an object")],
156
159
  ["createdAt", (m) => (isFiniteNumber(m.createdAt) ? undefined : "its createdAt is not a finite number")],
157
160
  ["deadline", (m) => (m.deadline === undefined || isFiniteNumber(m.deadline) ? undefined : "its deadline is not a finite number")],
161
+ ["resourceLedger", (m) => (m.resourceLedger === undefined || isRecord(m.resourceLedger) ? undefined : "its resource ledger is not an object")],
162
+ ["checkpointId", (m) => (m.checkpointId === undefined || (typeof m.checkpointId === "string" && m.checkpointId !== "") ? undefined : "its checkpoint id is not a non-empty string")],
158
163
  ]);
159
164
  function shapeProblemOf(m) {
160
165
  for (const [member, shape] of ROW_MEMBER_SHAPES) {
@@ -177,7 +182,7 @@ function listingDamage(m) {
177
182
  return placementDamage(m) ?? shapeProblemOf(m)?.problem;
178
183
  }
179
184
  export function rowMemberProblem(cp) {
180
- return shapeProblemOf({ gate: cp.gate, pendingAction: cp.pendingAction, state: cp.state, createdAt: cp.createdAt, deadline: cp.deadline });
185
+ return shapeProblemOf({ gate: cp.gate, pendingAction: cp.pendingAction, state: cp.state, createdAt: cp.createdAt, deadline: cp.deadline, resourceLedger: cp.resourceLedger, checkpointId: cp.checkpointId });
181
186
  }
182
187
  function thrownName(e) {
183
188
  return e instanceof Error ? e.constructor.name : typeof e;
@@ -1964,7 +1964,11 @@ export interface CheckpointSummary {
1964
1964
  * {@link toolCallId} absence-shape note applies). It names the call that PRESENTED the plan, not a call the pause
1965
1965
  * gates: `toolCallId` stays omitted on a plan_review row. */
1966
1966
  requestedByCallId?: string;
1967
- /** The pending tool's name ({@link PendingAction} `tool_approval.toolName`) when this is an approval suspend.
1967
+ /** The pending tool's name ({@link PendingAction} `tool_approval.toolName`) when this is an approval suspend — the very name
1968
+ * the row's `boundInputHash` was minted over (`exactBoundInputHashOf(toolName, args)`), as the row records it (an alias call
1969
+ * records the tool's own name). With {@link toolCallId} it is the listing's half of the approval binding: two parks of one
1970
+ * call id over the same arguments by two tools list two names and hold two hashes. The hash itself stays on the drilled-in
1971
+ * row, opaque, echoed and never re-derived by a host.
1968
1972
  * OMITTED (not `null`) for a non-`tool_approval` pendingAction — see {@link toolCallId}'s absence-shape note. */
1969
1973
  toolName?: string;
1970
1974
  /** Which approval card the pending call renders under — the gate's {@link CheckpointGate} `approvalCard` echoed when
@@ -29,17 +29,34 @@ import type { ModelRef } from "./model-seat.js";
29
29
  * · `autoCompactTokens` — the trigger-side window (dual-window semantics: lowers the compaction trigger and
30
30
  * the context-editing frontier without touching the physical request budget). Clamped to the physical
31
31
  * window by the one resolver, exactly as a model-card declaration is.
32
- * · `enabled` — compaction for legs on this model, the deployment's twin of `TaskSpec.compaction.enabled`
33
- * and with the same reach (the routine boundary pass, the recovery pass and the end-of-task summary —
34
- * one gate, inside `maybeCompact`, fed by one settings assembly). A request that states its own
35
- * `compaction.enabled` outranks it: the request is the author, this seat is the deployment's default —
36
- * the same "the spec's own value wins, the deployment fills an unset one" law every other seat follows.
32
+ * · `autoCompact` / `manualCompact` — the deployment's twins of the task's two compaction seats, each with its
33
+ * seat's reach and each the default for its own seat only ({@link compactionEnabled}).
37
34
  */
38
35
  export interface ContextWindowOverlay {
39
36
  readonly contextTokens?: number;
40
37
  readonly autoCompactTokens?: number;
41
- readonly enabled?: boolean;
38
+ readonly autoCompact?: boolean;
39
+ readonly manualCompact?: boolean;
42
40
  }
41
+ /**
42
+ * The two compaction seats, one per kind of pass — which pass reads which seat is {@link compactionEnabled}'s
43
+ * contract. A task's `compaction`, a `Runner.compactSession` request's `compaction` (which takes `manualCompact`
44
+ * only — a pass outside a run is a requested one) and a deployment's overlay carry them, and every one of those
45
+ * doors judges them with {@link compactionSeatsDefect}.
46
+ */
47
+ declare const COMPACTION_SEATS: readonly ["autoCompact", "manualCompact"];
48
+ export type CompactionSeat = (typeof COMPACTION_SEATS)[number];
49
+ /**
50
+ * The seats' ONE judgment, for every bag that carries them (a task's `compaction`, a `Runner.compactSession` request's
51
+ * `compaction`, a deployment overlay): the retired single seat `enabled` is refused by name with the sentence that names
52
+ * the two ({@link RETIRED_COMPACTION_SEAT_KEYS}; never read as either), then a seat present (a defined value) that is not
53
+ * a boolean. `subject` is the bag in the door's own words (`TaskSpec.compaction`, `compaction`,
54
+ * `RunnerDeps: contextSettings["w"]`). Answers which and the sentence; each door throws it with its own code.
55
+ */
56
+ export declare function compactionSeatsDefect(bag: object, subject: string): {
57
+ readonly kind: "retired" | "value";
58
+ readonly sentence: string;
59
+ } | undefined;
43
60
  /**
44
61
  * The seat: catalog word → overlay. Words absent from the table are "nothing declared".
45
62
  *
@@ -84,9 +101,22 @@ export declare function assertContextSettingsWords<T extends ContextSettings | u
84
101
  * moments an operator can get it wrong.
85
102
  */
86
103
  export declare function assertContextSettingsValue(v: unknown, where: string): ContextSettings | undefined;
87
- /** Does a REQUEST's own `compaction.enabled` stand, or does the deployment's overlay decide? One law, stated
88
- * once: the request is the author, the deployment fills an unset one, and nothing declared means ON. */
89
- export declare function compactionEnabled(specEnabled: boolean | undefined, overlay: ContextWindowOverlay | undefined): boolean;
104
+ /**
105
+ * Is THIS seat on for a pass?
106
+ *
107
+ * @contract compaction.two_seats — every compaction pass asks exactly one seat, through this function, and the seat
108
+ * is fixed by who starts the pass. `autoCompact` holds the three lanes the engine starts by itself: the turn-boundary
109
+ * pass at the window threshold (with the trim-pressure pass it forces), the recovery pass (a provider's
110
+ * prompt-too-long rejection, the request guard's compaction arm) and the end-of-task summary. `manualCompact` holds
111
+ * the passes a caller asks for: `TaskStream.compact`, an extension's `$.session.compact` and `Runner.compactSession`.
112
+ * One law per seat: the request's own value for the seat is the author, the deployment overlay's twin of the same seat
113
+ * fills an unset one, nothing declared means ON — and switching one seat off never switches off the other. With
114
+ * `autoCompact` off no recovery pass runs: a request the provider rejects as too long is neither summarized nor
115
+ * retried, and the rejection ends the run as the terminal failure it is (the provider's code and sentence), never a
116
+ * silent retry. With `manualCompact` off a requested pass is answered `"disabled"` with its `compaction_outcome` frame
117
+ * (`trigger: "manual"`) and no model call, and the boundary goes on with its own pass.
118
+ */
119
+ export declare function compactionEnabled(seat: CompactionSeat, requested: Readonly<Partial<Record<CompactionSeat, boolean>>> | undefined, overlay: ContextWindowOverlay | undefined): boolean;
90
120
  /**
91
121
  * The overlay's view of a model's PHYSICAL window — the model card's chain with the deployment's live
92
122
  * declaration CLAMPED over it. The single expression `guardBudget` and `resolveTriggerWindow` share.
@@ -101,3 +131,4 @@ export declare function compactionEnabled(specEnabled: boolean | undefined, over
101
131
  * number there is.
102
132
  */
103
133
  export declare function physicalWindowOf(model: Model, overlay: ContextWindowOverlay | undefined): number;
134
+ export {};
@@ -1,6 +1,26 @@
1
1
  import { tierAliasVia } from "./roles.js";
2
2
  import { optionKeys, receiveMembers } from "./own-property-receipt.js";
3
- const OVERLAY_KEYS = optionKeys()({ contextTokens: 0, autoCompactTokens: 0, enabled: 0 });
3
+ import { RETIRED_COMPACTION_SEAT_KEYS, retiredKeyOf, retiredKeyRefusal } from "./retired-keys.js";
4
+ import { describeRejectedValue } from "./tool-search-setting.js";
5
+ const OVERLAY_KEYS = optionKeys()({ contextTokens: 0, autoCompactTokens: 0, autoCompact: 0, manualCompact: 0 });
6
+ const OVERLAY_READ_NAMES = Object.freeze([...OVERLAY_KEYS, ...Object.keys(RETIRED_COMPACTION_SEAT_KEYS)]);
7
+ const COMPACTION_SEATS = Object.freeze(["autoCompact", "manualCompact"]);
8
+ const SEAT_REACH = Object.freeze({
9
+ autoCompact: "false switches off the passes the engine starts by itself",
10
+ manualCompact: "false refuses the passes a caller asks for",
11
+ });
12
+ export function compactionSeatsDefect(bag, subject) {
13
+ const retired = retiredKeyOf(bag, RETIRED_COMPACTION_SEAT_KEYS);
14
+ if (retired !== undefined)
15
+ return { kind: "retired", sentence: retiredKeyRefusal(retired, subject).message };
16
+ for (const seat of COMPACTION_SEATS) {
17
+ const value = Reflect.get(bag, seat);
18
+ if (value !== undefined && typeof value !== "boolean") {
19
+ return { kind: "value", sentence: `${subject}.${seat} must be a boolean when given (got ${describeRejectedValue(value)}) — ${SEAT_REACH[seat]}; omit it for the default (on)` };
20
+ }
21
+ }
22
+ return undefined;
23
+ }
4
24
  export function contextOverlayFor(settings, ref, catalog) {
5
25
  if (settings === undefined || typeof ref !== "string")
6
26
  return undefined;
@@ -21,33 +41,35 @@ export function assertContextSettingsValue(v, where) {
21
41
  if (v === undefined)
22
42
  return undefined;
23
43
  if (v === null || typeof v !== "object" || Array.isArray(v)) {
24
- throw new Error(`${where}: contextSettings must be a plain Record<string, {contextTokens?, autoCompactTokens?, enabled?}> (got ${v === null ? "null" : Array.isArray(v) ? "array" : typeof v})`);
44
+ throw new Error(`${where}: contextSettings must be a plain Record<string, {contextTokens?, autoCompactTokens?, autoCompact?, manualCompact?}> (got ${v === null ? "null" : Array.isArray(v) ? "array" : typeof v})`);
25
45
  }
26
46
  const out = {};
27
47
  for (const [word, raw] of Object.entries(v)) {
28
48
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
29
49
  throw new Error(`${where}: contextSettings[${JSON.stringify(word)}] must be a plain object (got ${raw === null ? "null" : Array.isArray(raw) ? "array" : typeof raw})`);
30
50
  }
31
- const o = receiveMembers(raw, { subject: `${where}: contextSettings[${JSON.stringify(word)}]`, unit: "member", moment: "when the overlay is read" }, OVERLAY_KEYS, (_, unknown) => new Error(`${where}: contextSettings[${JSON.stringify(word)}] carries ${unknown.map((k) => JSON.stringify(String(k))).join(", ")} — this seat declares window geometry only (contextTokens | autoCompactTokens | enabled); routing, pricing and fencing stay on the model card`));
51
+ const subject = `${where}: contextSettings[${JSON.stringify(word)}]`;
52
+ const o = receiveMembers(raw, { subject, unit: "member", moment: "when the overlay is read" }, OVERLAY_READ_NAMES, (_, unknown) => new Error(`${subject} carries ${unknown.map((k) => JSON.stringify(String(k))).join(", ")} — this seat declares window geometry and the compaction seats only (contextTokens | autoCompactTokens | autoCompact | manualCompact); routing, pricing and fencing stay on the model card`));
32
53
  for (const k of ["contextTokens", "autoCompactTokens"]) {
33
54
  const n = o[k];
34
55
  if (n !== undefined && (typeof n !== "number" || !Number.isFinite(n) || n <= 0)) {
35
- throw new Error(`${where}: contextSettings[${JSON.stringify(word)}].${k} must be a positive finite number (got ${JSON.stringify(n)}) — an unusable window is a configuration defect, not a request to fall back to the model's own`);
56
+ throw new Error(`${subject}.${k} must be a positive finite number (got ${JSON.stringify(n)}) — an unusable window is a configuration defect, not a request to fall back to the model's own`);
36
57
  }
37
58
  }
38
- if (o.enabled !== undefined && typeof o.enabled !== "boolean") {
39
- throw new Error(`${where}: contextSettings[${JSON.stringify(word)}].enabled must be a boolean (got ${JSON.stringify(o.enabled)})`);
40
- }
59
+ const seatDefect = compactionSeatsDefect(o, subject);
60
+ if (seatDefect !== undefined)
61
+ throw new Error(seatDefect.sentence);
41
62
  out[word] = Object.freeze({
42
63
  ...(o.contextTokens !== undefined ? { contextTokens: o.contextTokens } : {}),
43
64
  ...(o.autoCompactTokens !== undefined ? { autoCompactTokens: o.autoCompactTokens } : {}),
44
- ...(o.enabled !== undefined ? { enabled: o.enabled } : {}),
65
+ ...(o.autoCompact !== undefined ? { autoCompact: o.autoCompact } : {}),
66
+ ...(o.manualCompact !== undefined ? { manualCompact: o.manualCompact } : {}),
45
67
  });
46
68
  }
47
69
  return Object.freeze(out);
48
70
  }
49
- export function compactionEnabled(specEnabled, overlay) {
50
- return specEnabled ?? overlay?.enabled ?? true;
71
+ export function compactionEnabled(seat, requested, overlay) {
72
+ return requested?.[seat] ?? overlay?.[seat] ?? true;
51
73
  }
52
74
  export function physicalWindowOf(model, overlay) {
53
75
  const card = model.contextTokens ?? model.contextWindow;
@@ -21,6 +21,17 @@ import type { AutoModeClassifierRound } from "./auto-mode.js";
21
21
  import type { AskUnresolvableCause } from "./ask-unresolvable-notice.js";
22
22
  import type { PathDenialEvidence } from "../tools/fs/safety.js";
23
23
  import type { AskGuard } from "./tool-policy.js";
24
+ import type { RefusalEcho } from "./refusal-echo.js";
25
+ /** The engine's own account of a sentence it composed for a decision's `message`: the sentence (`text`); whether it is the
26
+ * engine's generic question for the call, naming no asker's reason (`generic` — a write gate's default question, the plan
27
+ * mode's); and the literals it quotes, in the order it quotes them (`echoed`, the refusal list's own form). The station that
28
+ * composed the sentence is its only writer, and freezes each listed literal itself. Read through {@link engineSentenceOf} alone,
29
+ * which answers only while the decision's `message` IS `text`. */
30
+ export interface EngineSentence {
31
+ readonly text: string;
32
+ readonly generic?: true;
33
+ readonly echoed?: readonly RefusalEcho[];
34
+ }
24
35
  export interface EngineAttestation {
25
36
  readonly toolCallId: string;
26
37
  readonly toolName: string;
@@ -56,12 +67,13 @@ export interface EngineAttestation {
56
67
  /** A seat refused the call's arguments because no approval can be bound to them: the refusal's sentence, carried by the
57
68
  * refusal itself — the gate's deny exit reads it (the remedy it gives) instead of judging again. */
58
69
  readonly bindingRefusal?: string;
59
- /** The engine's own generic question the ask was composed with (the write gate's default "approve write to" sentence, the
60
- * permission mode's own question) — not anyone's reason. The chain's entry mint ({@link
61
- * import("./ask-origin.js").chainAskReasonsOf}) writes no entry while the ask's `message` IS this sentence; a later layer
62
- * that spread the ask and put its own words in `message` keeps them. Written only by the station that composed that
63
- * sentence, for that sentence; a composer cannot state it (an unbranded record is refused). */
64
- readonly genericQuestion?: string;
70
+ /** The engine's own account of the decision's `message` ({@link EngineSentence}): the sentence a station composed, whether it
71
+ * is the engine's generic question (the chain's entry mint, {@link import("./ask-origin.js").chainAskReasonsOf}, writes no
72
+ * entry for one), and the literals it quotes. Valid only while the decision's `message` is still that sentence — a later
73
+ * layer that spread the decision and put its own words in `message` keeps them, and the account then reads as absent.
74
+ * Written only by the station that composed the sentence, for that sentence (the write gate's and the plan mode's questions;
75
+ * the ask resolver's refusal that quotes one of them); a composer cannot state it (an unbranded record is refused). */
76
+ readonly sentence?: EngineSentence;
65
77
  /** The askers a station read off this ask where it first received it, before it narrated the sentence (an inherited station
66
78
  * floating an ancestor's ask back into this leg's fold: its mark frames, its denial-limit fallback's sentence). The chain's
67
79
  * entry mint takes these instead of the sentence; empty = the station read no asker. Written only by that float. */
@@ -83,6 +95,14 @@ export declare function attestationOf(d: unknown, call: {
83
95
  toolCallId: string;
84
96
  toolName: string;
85
97
  }): EngineAttestation | undefined;
98
+ /** THE read of the engine's account of `d`'s sentence for `call` ({@link EngineAttestation.sentence}): present only while `d`'s
99
+ * `message` is that sentence, byte for byte — a layer that rewrote the message, appended to it or put its own words over it
100
+ * carries the record along (a spread keeps it) but no longer carries its account. `message` is read as every reader of the
101
+ * decision's text reads it. */
102
+ export declare function engineSentenceOf(d: unknown, call: {
103
+ toolCallId: string;
104
+ toolName: string;
105
+ }): EngineSentence | undefined;
86
106
  /**
87
107
  * Combine two records for `call`, member GROUP by group: the later record's group stands where it has one, the earlier's
88
108
  * fills a group the later lacks. A record not bound to `call` contributes nothing. `answer` scope is the veto's merge: the
@@ -10,7 +10,7 @@ const ATTESTATION_GROUP_OF = {
10
10
  guards: "guards",
11
11
  pathDenial: "pathDenial",
12
12
  bindingRefusal: "bindingRefusal",
13
- genericQuestion: "genericQuestion",
13
+ sentence: "sentence",
14
14
  receivedAskReasons: "receivedAskReasons",
15
15
  };
16
16
  const ATTESTATION_MEMBERS = Object.keys(ATTESTATION_GROUP_OF);
@@ -41,6 +41,10 @@ export function attestationOf(d, call) {
41
41
  return undefined;
42
42
  return boundTo(Object.getOwnPropertyDescriptor(d, "attestation")?.value, call);
43
43
  }
44
+ export function engineSentenceOf(d, call) {
45
+ const sentence = attestationOf(d, call)?.sentence;
46
+ return sentence !== undefined && d.message === sentence.text ? sentence : undefined;
47
+ }
44
48
  export function mergeAttestation(call, earlier, later, scope = "all") {
45
49
  const a = boundTo(earlier, call);
46
50
  const b = boundTo(later, call);
@@ -637,7 +637,8 @@ export interface EngineNotice {
637
637
  * alone must not mistake a stranded follow-up for a stranded steer — same split as the settled
638
638
  * frame's two count keys). They are NOT redelivered (a steer aimed at a finished run must not
639
639
  * fire at the next one — unlike ENGINE notes, which pend per session); the loud half of the
640
- * #257 contract's "accepted = enqueued, not consumed" sentence;
640
+ * #257 contract's "accepted = enqueued, not consumed" sentence; what a host that re-sends one reads back is
641
+ * `notice.user_input_undrained.handoff` ({@link undrainedUserInputNotices});
641
642
  * The words a person wrote on an approval card (a durable `policy_ask` allow's `feedback`) that did not reach the
642
643
  * model are counted in the SAME account under the steer code — one more row of that family, `detail.kind:
643
644
  * "approval_feedback"` (absent on every other row) — when the message carrying them never committed and the row did not come back
@@ -1070,6 +1071,14 @@ export interface EngineNotice {
1070
1071
  * - `"delegation.resume_lane_missing"` (#3334) — a parked agent resumed by a lane-less drive in a process holding no park of it:
1071
1072
  * its completion takes the mount's sink, settling no waiting submission elsewhere; the resume proceeds. Once per drive, at
1072
1073
  * the consume, to the process default seat. `detail: { taskId, rootSessionId? }`. Audience `"operator"`.
1074
+ * - `"delegation.delivery_discarded"` (#3431) — a frame (a background task's completion, a monitor event, a child's message)
1075
+ * addressed to an earlier occupant of a session id — the id deleted and created again, by another principal or the same
1076
+ * one — was discarded instead of delivered to the occupant the id holds now. Once per frame, by the Runner's per-session
1077
+ * notification store (`PendingSessionNotifications`), the one place the occupant comparison answers "another".
1078
+ * `detail: { taskId, taskType, sessionId, path, addressed, current }` — `path` = the seat the frame would have reached
1079
+ * under the current occupant (`"live"` its running conversation, `"box"` its durable box, `"drain"` its next run's
1080
+ * turn-open delivery); `addressed` / `current` = whether each side's occupant carried a token (`"known"` / `"unknown"`),
1081
+ * never the token. The frame's text never rides it. Audience `"operator"`.
1073
1082
  *
1074
1083
  * - `"memory.consolidation_recommended"` (design/339 §2.2/§6.2) — the engine-minted per-scope
1075
1084
  * session count crossed the consolidation thresholds (time gate open ∧ enough distinct
@@ -1364,6 +1373,20 @@ export declare function parentLegIds(internals: {
1364
1373
  * no `runId`: the account is per run and nothing carries the parent's. Only the DIRECT parent hears: a grandchild's
1365
1374
  * row reaches its parent's session (the middle leg), not the root's. A parent that is no addressee — null, no or an empty session, or the leg's own session (which already
1366
1375
  * hears the row) — gets no copy, and the call never throws on it.
1376
+ *
1377
+ * @contract notice.user_input_undrained.handoff — a row's `detail.inputIds` names exactly the unread inputs it counts (present
1378
+ * when the list covers the count; a row of approval words carries none): each input's `inputId` — the one its caller handed the
1379
+ * steer verb (or the parked-steer append, `CheckpointStore.setPendingSteer`), else the one the engine minted at acceptance. An
1380
+ * input parked on a checkpoint keeps its id (the entry freezes it), so a resume's `applied` frame and a resumed leg's row name the
1381
+ * same one. A minted id is published only on the input's `human_input` frames, which carry no text, and neither call returns it —
1382
+ * so it is no key a caller can tie back to its own call: a host that means to re-send sends every steer with its own `inputId`,
1383
+ * and the row hands its ids back. The engine keeps no state across runs and never carries an unread input to a later run itself (a durable park is the one
1384
+ * carrier: the resume delivers it with no row — or, when the deployment's prompt screen withholds it on redelivery, tells it by
1385
+ * `steering.parked_input_blocked` under the same `detail.inputId`, not by this row). A host that re-sends an input under the same
1386
+ * `inputId` to a later run gets that run's own answer — read (its `applied` frame, no row) or not read (a row of that run, the
1387
+ * same id, that run's `runId`) — so the leg's own rows naming one `inputId` count the runs that ended with it unread (a parent's
1388
+ * copy, the row carrying `childSessionId`, repeats its child's row and is not another time). The row's sentence states the
1389
+ * engine's part only ("NOT redelivered" by the engine); whether to re-send, and what the person is shown, is the host's.
1367
1390
  */
1368
1391
  export declare function undrainedUserInputNotices(counts: {
1369
1392
  steer: number;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The one reading of who an extension-started agent row says started it. The row carries `requestedBy?: ExtensionRequester`
3
+ * (`{ kind: "extension", name }`): written once, by the registration that creates the row, from the extension's own `$.agent.spawn`
4
+ * call; absent on every other row — the model's own spawn, the host's, and every row an earlier release wrote. Rows come back from a
5
+ * store the engine did not just write, so every reader takes the member through this function: a value that is not exactly an
6
+ * extension's requester (another `kind`, a blank or non-string name) is no requester — never a half-read one.
7
+ */
8
+ import type { ExtensionRequester } from "./task-event.js";
9
+ export declare function readExtensionRequester(raw: unknown): ExtensionRequester | undefined;
@@ -0,0 +1,7 @@
1
+ export function readExtensionRequester(raw) {
2
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
3
+ return undefined;
4
+ const kind = raw.kind;
5
+ const name = raw.name;
6
+ return kind === "extension" && typeof name === "string" && name.trim() !== "" ? Object.freeze({ kind: "extension", name }) : undefined;
7
+ }
@@ -523,6 +523,21 @@ export interface FileHistoryStore {
523
523
  * reference — the arm the commit paths already validate for.
524
524
  */
525
525
  reap(scope: string, keepEntryIds: string[]): Promise<number>;
526
+ /**
527
+ * Erase the WHOLE scope — every boundary, every version record INCLUDING the v1 pristine baselines `reap` keeps while a scope
528
+ * lives, its consumed-id ledger — and the blobs no other scope references: the session-tree cascade's leg for a deleted session
529
+ * (the scope is the session id; {@link import("./retention.js").RETENTION_CASCADE}). Answers how many boundaries and version
530
+ * records it removed (a damaged record is erased all the same and counts once; a scope with no history answers 0, so a repeat
531
+ * is harmless). The scope then reads as one that never had
532
+ * history: an id registered again later starts a new one. Refused (thrown, `conflict`) while THIS store runs a write of the scope
533
+ * — a capture, a first-touch record, a retraction or an import, counted from the call, so one parked before its first record is
534
+ * counted — since a cascade runs on a session with no leg running; another process's writes are the caller's precondition to
535
+ * hold. A store fault throws: a deletion face that cannot delete is loud, never a quiet 0 — the blob pass included, so a backend
536
+ * that cannot collect every blob only the scope referenced (another scope's history it cannot judge, a blob that will not unlink)
537
+ * throws after the records are gone, and a repeat runs that pass again. OPTIONAL: absent ⇒ this store cannot complete a session
538
+ * deletion (only `reap` remains, which keeps the baselines), and the deployment owns that gap.
539
+ */
540
+ deleteBySession?(scope: string): Promise<number>;
526
541
  /**
527
542
  * Cross-session carry (CC copyFileHistoryForResume): make `toScope` see `fromScope`'s boundaries
528
543
  * + versions (content-addressed backends copy references, zero bytes). Same-scope call is a
@@ -882,6 +897,9 @@ export declare class InMemoryFileHistoryStore implements FileHistoryStore {
882
897
  * (adversarial round): two concurrent captures can lease the same new hash, and the first
883
898
  * attempt's release must not strip the second attempt's liveness. */
884
899
  private readonly inFlightBlobs;
900
+ /** Per scope, the history writes (`trackEdit`, `annulTrack`, `snapshot`, `importHistory`) this store is running, from call to
901
+ * settle: `deleteBySession` refuses while a scope has one, an import still fetching its blobs included. */
902
+ private readonly writers;
885
903
  constructor(options?: InMemoryFileHistoryStoreOptions);
886
904
  /**
887
905
  * The RETENTION pass, run after a boundary commits (design/381 §片2 — see {@link FileHistoryStore.reap}
@@ -902,22 +920,32 @@ export declare class InMemoryFileHistoryStore implements FileHistoryStore {
902
920
  /** PROTECTED COMMIT SEAM (fault-injectable): publish a captured boundary in ONE synchronous step
903
921
  * — version records + mapping become visible together or not at all (atomic visibility). */
904
922
  protected publishBoundary(scope: string, entryId: string, staged: Map<string, StagedFileCapture>): void;
923
+ /** One history write of `scope`, counted in {@link writers} for its whole run. */
924
+ private writing;
905
925
  trackEdit(scope: string, absPath: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryTrackResult>;
926
+ private trackEditCounted;
906
927
  annulTrack(scope: string, absPath: string, root: string, verify?: {
907
928
  env: ExecutionEnv;
908
929
  signal?: AbortSignal;
909
930
  }): Promise<FileHistoryResult>;
931
+ private annulTrackCounted;
910
932
  snapshot(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryResult>;
933
+ private snapshotCounted;
911
934
  restore(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryRestoreResult>;
912
935
  canRestore(scope: string, entryId: string): Promise<boolean>;
913
936
  diffStats(scope: string, entryId: string, env: ExecutionEnv, root: string): Promise<FileHistoryDiffStats | null>;
914
937
  reap(scope: string, keepEntryIds: string[]): Promise<number>;
938
+ deleteBySession(scope: string): Promise<number>;
939
+ /** Blob GC: live = referenced by ANY scope's retained version records, or in-flight. Synchronous (no await), so it runs
940
+ * atomically vs an in-flight capture parked at an await. */
941
+ private collectBlobs;
915
942
  adoptScope(fromScope: string, toScope: string): Promise<FileHistoryResult>;
916
943
  exportHistory(scope: string): Promise<FileHistoryExportResult>;
917
944
  /** The export projection as a SYNCHRONOUS function — the import's final claim needs to compare a
918
945
  * target's identity without yielding (see the publish step). */
919
946
  private exportOf;
920
947
  importHistory(scope: string, data: FileHistoryExport, srcGetBlob: (hash: string) => Promise<Uint8Array | undefined>): Promise<FileHistoryResult>;
948
+ private importHistoryCounted;
921
949
  /** The import body inside the blob lease (see {@link importHistory}). */
922
950
  private importStaged;
923
951
  }
@@ -445,6 +445,7 @@ export class InMemoryFileHistoryStore {
445
445
  boundaryKeep;
446
446
  blobs = new Map();
447
447
  inFlightBlobs = new Map();
448
+ writers = new Map();
448
449
  constructor(options) {
449
450
  const opts = receiveOptions(options, "InMemoryFileHistoryStore", IN_MEMORY_FILE_HISTORY_STORE_OPTION_KEYS);
450
451
  this.boundaryKeep = resolveFileHistoryRetention("InMemoryFileHistoryStore", opts.retention);
@@ -513,7 +514,23 @@ export class InMemoryFileHistoryStore {
513
514
  }
514
515
  sc.boundaries.set(entryId, mapping);
515
516
  }
516
- async trackEdit(scope, absPath, env, root, signal) {
517
+ async writing(scope, write) {
518
+ this.writers.set(scope, (this.writers.get(scope) ?? 0) + 1);
519
+ try {
520
+ return await write();
521
+ }
522
+ finally {
523
+ const left = (this.writers.get(scope) ?? 1) - 1;
524
+ if (left === 0)
525
+ this.writers.delete(scope);
526
+ else
527
+ this.writers.set(scope, left);
528
+ }
529
+ }
530
+ trackEdit(scope, absPath, env, root, signal) {
531
+ return this.writing(scope, () => this.trackEditCounted(scope, absPath, env, root, signal));
532
+ }
533
+ async trackEditCounted(scope, absPath, env, root, signal) {
517
534
  try {
518
535
  const { key, ...keyDesc } = describeTrackKey(root, absPath);
519
536
  const sc = this.scope(scope);
@@ -562,7 +579,10 @@ export class InMemoryFileHistoryStore {
562
579
  return { ok: false, error: { code: "track_failed", message: `first-touch record for ${absPath} could not be persisted: ${thrownText(err)}`, ...caughtFault(err) } };
563
580
  }
564
581
  }
565
- async annulTrack(scope, absPath, root, verify) {
582
+ annulTrack(scope, absPath, root, verify) {
583
+ return this.writing(scope, () => this.annulTrackCounted(scope, absPath, root, verify));
584
+ }
585
+ async annulTrackCounted(scope, absPath, root, verify) {
566
586
  try {
567
587
  const key = trackKeyOf(root, absPath);
568
588
  const sc = this.scopes.get(scope);
@@ -602,7 +622,10 @@ export class InMemoryFileHistoryStore {
602
622
  return { ok: false, error: { code: "track_failed", message: `annulling the first-touch record for ${absPath} failed: ${thrownText(err)}`, ...caughtFault(err) } };
603
623
  }
604
624
  }
605
- async snapshot(scope, entryId, env, root, signal) {
625
+ snapshot(scope, entryId, env, root, signal) {
626
+ return this.writing(scope, () => this.snapshotCounted(scope, entryId, env, root, signal));
627
+ }
628
+ async snapshotCounted(scope, entryId, env, root, signal) {
606
629
  const sc = this.scope(scope);
607
630
  if (sc.boundaries.has(entryId))
608
631
  return { ok: true };
@@ -824,6 +847,24 @@ export class InMemoryFileHistoryStore {
824
847
  const refs = referenced.get(key);
825
848
  t.versions = t.versions.filter((v) => v.version === 1 || (refs?.has(v.version) ?? false));
826
849
  }
850
+ this.collectBlobs();
851
+ return removed;
852
+ }
853
+ async deleteBySession(scope) {
854
+ if (this.writers.has(scope)) {
855
+ throw Object.assign(new Error(`file history scope "${scope}" has a write in flight in this store (a capture, a first-touch record, a retraction or an import) — a session's history is erased when no leg of it runs`), { code: "conflict" });
856
+ }
857
+ const sc = this.scopes.get(scope);
858
+ if (sc === undefined)
859
+ return 0;
860
+ let removed = sc.boundaries.size;
861
+ for (const t of sc.tracked.values())
862
+ removed += t.versions.length;
863
+ this.scopes.delete(scope);
864
+ this.collectBlobs();
865
+ return removed;
866
+ }
867
+ collectBlobs() {
827
868
  const live = new Set(this.inFlightBlobs.keys());
828
869
  for (const s of this.scopes.values()) {
829
870
  for (const t of s.tracked.values())
@@ -834,7 +875,6 @@ export class InMemoryFileHistoryStore {
834
875
  for (const h of [...this.blobs.keys()])
835
876
  if (!live.has(h))
836
877
  this.blobs.delete(h);
837
- return removed;
838
878
  }
839
879
  async adoptScope(fromScope, toScope) {
840
880
  try {
@@ -886,7 +926,10 @@ export class InMemoryFileHistoryStore {
886
926
  .map(([entryId, mapping]) => ({ entryId, files: [...mapping.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([relOrAbsPath, version]) => ({ relOrAbsPath, version })) })),
887
927
  };
888
928
  }
889
- async importHistory(scope, data, srcGetBlob) {
929
+ importHistory(scope, data, srcGetBlob) {
930
+ return this.writing(scope, () => this.importHistoryCounted(scope, data, srcGetBlob));
931
+ }
932
+ async importHistoryCounted(scope, data, srcGetBlob) {
890
933
  try {
891
934
  const shaped = validateFileHistoryExport(data);
892
935
  if (!shaped.ok)
@@ -134,7 +134,7 @@ export function createFsWriteGatePolicy(opts) {
134
134
  if (note !== undefined)
135
135
  return ask(`approve write to "${path}"?${note}`);
136
136
  const generic = `approve write to "${path}"?`;
137
- return attest(ask(generic), req, { genericQuestion: generic });
137
+ return attest(ask(generic), req, { sentence: { text: generic, generic: true, echoed: [Object.freeze({ kind: "path", value: path })] } });
138
138
  },
139
139
  };
140
140
  }
@@ -225,6 +225,8 @@ function applyShellReadVerdict(pass, answer, toolName, shellGated) {
225
225
  pass.deniedBy = "read_boundary";
226
226
  if (verdict.details !== undefined)
227
227
  pass.denyDetails = verdict.details;
228
+ if (verdict.echoed !== undefined)
229
+ pass.denyEchoed = verdict.echoed;
228
230
  return;
229
231
  }
230
232
  if (reading.kind === "silence") {