@sema-agent/core 7.62.0 → 7.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/CHANGELOG.md +528 -0
  2. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  3. package/dist/agents/subagent-transcript-placement.js +14 -0
  4. package/dist/agents/subagent.js +82 -51
  5. package/dist/brain/route-adjudicator.js +9 -4
  6. package/dist/core/approval-object.js +1 -1
  7. package/dist/core/arg-summary.js +1 -1
  8. package/dist/core/ask-question.d.ts +2 -2
  9. package/dist/core/canonical-json.d.ts +23 -13
  10. package/dist/core/canonical-json.js +4 -4
  11. package/dist/core/checkpoint-queries.d.ts +47 -4
  12. package/dist/core/checkpoint-queries.js +36 -16
  13. package/dist/core/checkpoint-requirements.d.ts +3 -3
  14. package/dist/core/checkpoint-requirements.js +2 -1
  15. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  16. package/dist/core/checkpoint-row-verdict.js +22 -2
  17. package/dist/core/checkpoint-store.d.ts +23 -10
  18. package/dist/core/checkpoint-store.js +45 -4
  19. package/dist/core/compliance.d.ts +6 -2
  20. package/dist/core/compliance.js +3 -3
  21. package/dist/core/engine-attestation.d.ts +1 -1
  22. package/dist/core/engine-notice.d.ts +19 -4
  23. package/dist/core/git-worktree-env.d.ts +62 -3
  24. package/dist/core/git-worktree-env.js +91 -30
  25. package/dist/core/governance-codes.d.ts +7 -3
  26. package/dist/core/governance-codes.js +13 -3
  27. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  28. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  29. package/dist/core/memory-engine/consolidation.d.ts +73 -10
  30. package/dist/core/memory-engine/consolidation.js +167 -11
  31. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  32. package/dist/core/memory-engine/data-plane.js +11 -6
  33. package/dist/core/memory-engine/delegation-settlement.d.ts +37 -35
  34. package/dist/core/memory-engine/delegation-settlement.js +53 -59
  35. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  36. package/dist/core/memory-engine/dual-root.js +9 -5
  37. package/dist/core/memory-engine/engine.d.ts +98 -35
  38. package/dist/core/memory-engine/engine.js +477 -380
  39. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  40. package/dist/core/memory-engine/entry-scan.js +3 -0
  41. package/dist/core/memory-engine/file-backend.d.ts +29 -3
  42. package/dist/core/memory-engine/file-backend.js +66 -35
  43. package/dist/core/memory-engine/index.d.ts +7 -7
  44. package/dist/core/memory-engine/index.js +6 -6
  45. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  46. package/dist/core/memory-engine/landing-admission.js +3 -3
  47. package/dist/core/memory-engine/layout.d.ts +121 -45
  48. package/dist/core/memory-engine/layout.js +252 -102
  49. package/dist/core/memory-engine/memory-backend-contract.d.ts +19 -1
  50. package/dist/core/memory-engine/memory-backend-contract.js +320 -0
  51. package/dist/core/memory-engine/memory-deployment.d.ts +31 -8
  52. package/dist/core/memory-engine/memory-deployment.js +26 -12
  53. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  54. package/dist/core/memory-engine/scope-contract.js +68 -19
  55. package/dist/core/memory-engine/session-write-home.d.ts +3 -1
  56. package/dist/core/memory-engine/session-write-home.js +1 -1
  57. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  58. package/dist/core/memory-engine/sync-client.js +7 -0
  59. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  60. package/dist/core/memory-engine/sync-report.js +6 -2
  61. package/dist/core/memory-engine/tools.d.ts +2 -2
  62. package/dist/core/memory-engine/tools.js +10 -10
  63. package/dist/core/memory-engine/types.d.ts +118 -19
  64. package/dist/core/memory-engine/types.js +1 -0
  65. package/dist/core/memory.js +15 -6
  66. package/dist/core/mods/stations.d.ts +20 -1
  67. package/dist/core/mods/stations.js +21 -2
  68. package/dist/core/park-selfcheck.js +2 -2
  69. package/dist/core/pause-registry.d.ts +2 -0
  70. package/dist/core/pause-registry.js +3 -0
  71. package/dist/core/permission-rule-consent.d.ts +10 -3
  72. package/dist/core/permission-rule-consent.js +37 -24
  73. package/dist/core/permission-rule-store.d.ts +35 -1
  74. package/dist/core/permission-rule-store.js +27 -8
  75. package/dist/core/read-only-shell.js +3 -2
  76. package/dist/core/redaction-marks.d.ts +8 -0
  77. package/dist/core/redaction-marks.js +6 -0
  78. package/dist/core/remote-env.d.ts +12 -1
  79. package/dist/core/remote-env.js +3 -0
  80. package/dist/core/runner/child-tree.d.ts +29 -3
  81. package/dist/core/runner/child-tree.js +39 -16
  82. package/dist/core/runner/contracts.d.ts +18 -9
  83. package/dist/core/runner/gate-exit.js +2 -2
  84. package/dist/core/runner/inherited-ask-grants.js +1 -1
  85. package/dist/core/runner/memory-consolidation-driver.d.ts +6 -3
  86. package/dist/core/runner/memory-consolidation-driver.js +4 -4
  87. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  88. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  89. package/dist/core/runner/person-path-rows.d.ts +8 -3
  90. package/dist/core/runner/person-path-rows.js +5 -1
  91. package/dist/core/runner/placement-fence.d.ts +12 -0
  92. package/dist/core/runner/placement-fence.js +20 -6
  93. package/dist/core/runner/prepare-ask-lane.js +2 -2
  94. package/dist/core/runner/prepare-caps-and-workflow.d.ts +4 -1
  95. package/dist/core/runner/prepare-caps-and-workflow.js +5 -2
  96. package/dist/core/runner/prepare-execution-env.js +17 -6
  97. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  98. package/dist/core/runner/prepare-hands-readface.js +4 -3
  99. package/dist/core/runner/prepare-inherited-gate.d.ts +10 -8
  100. package/dist/core/runner/prepare-inherited-gate.js +8 -4
  101. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  102. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  103. package/dist/core/runner/prepare-memory.d.ts +3 -2
  104. package/dist/core/runner/prepare-memory.js +28 -20
  105. package/dist/core/runner/prepare-park-ask.js +4 -3
  106. package/dist/core/runner/prepare-task.js +15 -12
  107. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  108. package/dist/core/runner/run-leg.js +1 -1
  109. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  110. package/dist/core/runner/terminal-account.js +1 -1
  111. package/dist/core/runner-deps.d.ts +6 -2
  112. package/dist/core/secret-env.d.ts +1 -1
  113. package/dist/core/secret-env.js +4 -4
  114. package/dist/core/session-checkout.d.ts +108 -0
  115. package/dist/core/session-checkout.js +485 -0
  116. package/dist/core/session-store.d.ts +12 -4
  117. package/dist/core/session-store.js +23 -3
  118. package/dist/core/session.d.ts +16 -2
  119. package/dist/core/session.js +3 -0
  120. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  121. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  122. package/dist/core/store-contracts/session-store-contract.js +39 -0
  123. package/dist/core/task-event.d.ts +21 -0
  124. package/dist/core/task-notification.d.ts +9 -1
  125. package/dist/core/task-notification.js +6 -0
  126. package/dist/core/task-registry-agent.d.ts +14 -2
  127. package/dist/core/task-registry-agent.js +45 -19
  128. package/dist/core/task-registry-shared.d.ts +26 -11
  129. package/dist/core/task-registry.d.ts +15 -9
  130. package/dist/core/task-registry.js +9 -10
  131. package/dist/core/task-spec-members.js +1 -1
  132. package/dist/core/task-spec.d.ts +20 -0
  133. package/dist/core/tool-policy.d.ts +14 -12
  134. package/dist/core/tool-policy.js +11 -10
  135. package/dist/core/tool-spec.d.ts +38 -19
  136. package/dist/core/types.d.ts +1 -1
  137. package/dist/core/untrusted-egress.d.ts +15 -4
  138. package/dist/core/untrusted-egress.js +23 -22
  139. package/dist/core/workspace-snapshot.d.ts +3 -1
  140. package/dist/core/workspace-snapshot.js +1 -0
  141. package/dist/engine/harness/types.d.ts +66 -1
  142. package/dist/engine/harness/types.js +108 -0
  143. package/dist/engine/session/import-validate.js +6 -1
  144. package/dist/engine/session/session.d.ts +24 -1
  145. package/dist/engine/session/session.js +45 -1
  146. package/dist/index.d.ts +7 -4
  147. package/dist/index.js +7 -4
  148. package/dist/internal/harness-types.d.ts +1 -1
  149. package/dist/orchestration/run-workflow-tool.d.ts +4 -1
  150. package/dist/orchestration/run-workflow-tool.js +1 -0
  151. package/dist/orchestration/workflow.d.ts +3 -0
  152. package/dist/orchestration/workflow.js +3 -1
  153. package/dist/stores/file/session-store.js +2 -1
  154. package/dist/tools/fs/bash-program-position.js +3 -3
  155. package/dist/tools/fs/program-read-model.d.ts +34 -10
  156. package/dist/tools/fs/program-read-model.js +37 -7
  157. package/dist/tools/fs/program-read-model.rows.js +13 -2
  158. package/dist/tools/fs/read-deny.d.ts +13 -1
  159. package/dist/tools/fs/read-deny.js +10 -2
  160. package/dist/tools/fs/removal-targets.js +3 -3
  161. package/dist/tools/fs/safety.d.ts +2 -0
  162. package/dist/tools/fs/safety.js +1 -1
  163. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  164. package/dist/tools/fs/shell-read-argv.js +34 -29
  165. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  166. package/dist/tools/fs/shell-read-bindings.js +5 -1
  167. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  168. package/dist/tools/fs/shell-read-brace.js +79 -0
  169. package/dist/tools/fs/shell-read-check.js +10 -8
  170. package/dist/tools/fs/shell-read-establish.js +23 -16
  171. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  172. package/dist/tools/fs/shell-read-judge.js +3 -3
  173. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  174. package/dist/tools/fs/shell-read-plan.js +189 -93
  175. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  176. package/dist/tools/fs/shell-read-start.js +20 -12
  177. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  178. package/dist/tools/fs/shell-read-word.js +9 -5
  179. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  180. package/dist/tools/fs/shell-read-workdir.js +73 -12
  181. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  182. package/dist/tools/worktree.d.ts +3 -2
  183. package/dist/tools/worktree.js +7 -35
  184. package/package.json +3 -2
  185. package/test/export-surface.snapshot.json +73 -11
  186. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  187. package/wire-changes/core@7.63.0.json +3523 -0
  188. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  189. package/wire-changes/primitives@7.63.0.json +445 -0
  190. package/dist/core/credential-vocabulary.d.ts +0 -176
  191. package/dist/core/credential-vocabulary.js +0 -190
  192. package/dist/core/redaction-passes.d.ts +0 -82
  193. package/dist/core/redaction-passes.js +0 -377
@@ -564,11 +564,13 @@ export interface AskRuleEvidence {
564
564
  }
565
565
  /** The human/model-readable text of a decision. */
566
566
  export declare function decisionText(d: PermissionResult): string | undefined;
567
- /** Does a license (a record's `inputDigest`) cover the bytes that `runs`? The ONE judge — the gate's ledger keeps a settlement for
568
- * the bytes it licensed by it, and the unstated question asks whether an answer was given for these bytes by it. A license for
569
- * bytes covers what the tool reads them as ({@link argsReadFrom}: the one recorded step a reading took to `runs`). Compared by
570
- * the EXACT digest only: bytes outside the bindable domain have none and are covered by no license. */
571
- export declare function licenseCovers(licensed: string | undefined, runs: unknown): boolean;
567
+ /** Does a license (a record's `inputDigest`, a park row's `boundInputHash`) cover the call of `tool` over the bytes that `runs`? The
568
+ * ONE judge — the gate's ledger keeps a settlement for the bytes it licensed by it, and the unstated question asks whether an
569
+ * answer was given for these bytes by it. A license binds the tool and the bytes together ({@link exactBoundInputHashOf}), so a
570
+ * license for one tool covers no call of another. A license for bytes covers what the tool reads them as ({@link argsReadFrom}:
571
+ * the one recorded step a reading took to `runs`). Compared by the EXACT digest only: bytes outside the bindable domain have
572
+ * none and are covered by no license. */
573
+ export declare function licenseCovers(licensed: string | undefined, tool: string, runs: unknown): boolean;
572
574
  /**
573
575
  * THE judge of whether an approval can be bound to arguments, and the arguments it binds — asked wherever an approval is about to
574
576
  * be asked or adopted, and nowhere else: the ask resolver (its no-approver arm too) and the approval policy before anyone is asked,
@@ -1298,14 +1300,14 @@ export interface AskRequest {
1298
1300
  * bidi bit's two faces can.
1299
1301
  */
1300
1302
  readonly previewWithheld?: "oversize" | "unavailable";
1301
- /** Canonical digest of {@link args} as presented in THIS ask, computed by the engine's one
1302
- * `boundInputHashOf` — the same digest a durable park binds its checkpoint to, so an aggregating
1303
+ /** Canonical digest of the call's tool ({@link toolName}) and {@link args} as presented in THIS ask, computed by the engine's
1304
+ * one call binding (`exactBoundInputHashOf`) — the same digest a durable park binds its checkpoint to, so an aggregating
1303
1305
  * approver can reconcile a synchronous ask row against a parked checkpoint row for the same call
1304
- * by `(toolCallId, hash)` equality. RECONCILIATION metadata only, never adjudication input: it
1305
- * repeats for two asks over identical args, and an `updatedInput` edit round re-mints it over the
1306
- * edited args. Filled at the `resolveAsk` chokepoint (present for every wired-approver call, so a
1307
- * mint site added later is covered by construction); optional on the type because a deployment may
1308
- * invoke its approver function directly. */
1306
+ * by `(toolCallId, hash)` equality, and two calls of different tools over identical args under one id do not reconcile.
1307
+ * RECONCILIATION metadata only, never adjudication input: it repeats for two asks of one tool over identical args, and an
1308
+ * `updatedInput` edit round re-mints it over the edited args. Filled at the `resolveAsk` chokepoint (present for every
1309
+ * wired-approver call, so a mint site added later is covered by construction); optional on the type because a deployment
1310
+ * may invoke its approver function directly. */
1309
1311
  readonly boundInputHash?: string;
1310
1312
  /** A call to the engine's `Skill` tool: the hash of {@link boundGrants} — the digest a parked approval of the same card is judged by, so a live card reconciles against its parked row by `(toolCallId, boundGrantDigest)` and an answer is remembered by "this tool + this binding". Present exactly on that call (whoever asked, however the question was worded); every other card carries {@link boundGrantAbsence} instead; `message` renders the same lists narrowed to what releases in the leg's mode. Reconciliation metadata, never adjudication input. */
1311
1313
  readonly boundGrantDigest?: string;
@@ -16,7 +16,7 @@ import { readOnlyShellVerdict } from "./read-only-shell.js";
16
16
  import { DEFAULT_GATE_AWAIT_TIMEOUT_MS, withGateTimeout } from "./gate-bounded-await.js";
17
17
  import { protectivePathTargetOf, shellFaceToolNames } from "./tool-registry.js";
18
18
  import { heldBy } from "./tool-name-readings.js";
19
- import { bindableValueOf, boundInputHashOf, describeBindingFault, exactBoundInputHashOf } from "./canonical-json.js";
19
+ import { bindableValueOf, describeBindingFault, exactBoundInputHashOf } from "./canonical-json.js";
20
20
  import { delimitUntrusted, inlineUntrusted, REVIEWER_NOTE_MAX_BODY } from "./untrusted-text.js";
21
21
  import { describeRejectedValue } from "./tool-search-setting.js";
22
22
  import { egressText, egressThrownText } from "./untrusted-egress.js";
@@ -98,8 +98,8 @@ export const ASK_EVIDENCE_ABSENCE_VALUES = ["not_wired", "not_adjudicated", "una
98
98
  export function decisionText(d) {
99
99
  return d.message;
100
100
  }
101
- export function licenseCovers(licensed, runs) {
102
- return licensed !== undefined && (licensed === exactBoundInputHashOf(runs) || licensed === exactBoundInputHashOf(argsReadFrom(runs)));
101
+ export function licenseCovers(licensed, tool, runs) {
102
+ return licensed !== undefined && (licensed === exactBoundInputHashOf(tool, runs) || licensed === exactBoundInputHashOf(tool, argsReadFrom(runs)));
103
103
  }
104
104
  export function bindableArgsOf(toolName, args) {
105
105
  const bound = bindableValueOf(args);
@@ -118,7 +118,7 @@ export function bindingRefusalOf(toolName, args, fault) {
118
118
  }
119
119
  export function answeredFor(d, call, runs) {
120
120
  const record = attestationOf(d, call);
121
- return record?.settlement !== undefined && licenseCovers(record.inputDigest, runs);
121
+ return record?.settlement !== undefined && licenseCovers(record.inputDigest, call.toolName, runs);
122
122
  }
123
123
  export const REFUSES_NO_WHOLE_TOOL = () => false;
124
124
  export const TOOL_TABLE_VIEW_READ = "tool-table-view";
@@ -499,9 +499,9 @@ export function createApprovalPolicy(opts) {
499
499
  if (!bound.ok)
500
500
  return attestOver(undefined)({ action: "deny", message: bound.refusal }, settledByNobody("presentation_failed"), bound.refusal);
501
501
  const shown = { value: structuredClone(bound.value) };
502
- const askedDigest = exactBoundInputHashOf(shown.value);
502
+ const askedDigest = exactBoundInputHashOf(req.toolName, shown.value);
503
503
  const attest = attestOver(askedDigest);
504
- const heldWhileWaiting = () => licenseCovers(askedDigest, req.args);
504
+ const heldWhileWaiting = () => licenseCovers(askedDigest, req.toolName, req.args);
505
505
  const changedWhilePending = () => attest({
506
506
  action: "deny",
507
507
  message: `the arguments of "${req.toolName}" changed while its approval was pending — denied fail-closed ` +
@@ -1131,11 +1131,11 @@ export function carriesBidiControls(value, limits) {
1131
1131
  }
1132
1132
  }
1133
1133
  export async function resolveAsk(req, onAsk, signal, onLateSettlement) {
1134
- const askedDigest = exactBoundInputHashOf(req.args);
1134
+ const askedDigest = exactBoundInputHashOf(req.toolName, req.args);
1135
1135
  const { settlement, bindingRefusal, ...r } = await resolveAskArms(req, onAsk, signal, onLateSettlement);
1136
1136
  if (settlement === undefined)
1137
1137
  return r;
1138
- const licensedDigest = r.action === "allow" && r.updatedInput !== undefined ? exactBoundInputHashOf(r.updatedInput) : r.presentedInput !== undefined ? exactBoundInputHashOf(r.presentedInput) : askedDigest;
1138
+ const licensedDigest = r.action === "allow" && r.updatedInput !== undefined ? exactBoundInputHashOf(req.toolName, r.updatedInput) : r.presentedInput !== undefined ? exactBoundInputHashOf(req.toolName, r.presentedInput) : askedDigest;
1139
1139
  return attest(r, req, { settlement, ...(req.origin !== undefined ? { origin: req.origin } : {}), ...(req.classes !== undefined ? { classes: req.classes } : {}), ...(licensedDigest !== undefined ? { inputDigest: licensedDigest } : {}), ...(bindingRefusal !== undefined ? { bindingRefusal } : {}) });
1140
1140
  }
1141
1141
  function raceAskWaitAgainstSignal(wait, signal) {
@@ -1290,11 +1290,12 @@ async function resolveAskArms(req, onAsk, signal, onLateSettlement) {
1290
1290
  let ok;
1291
1291
  try {
1292
1292
  const approverView = { value: structuredClone(presented.value) };
1293
+ const reconciliationHash = exactBoundInputHashOf(req.toolName, presented.value);
1293
1294
  const bidi = carriesBidiControls(presented.value) || carriesBidiControls(req.preview);
1294
- const { hasBidiControls: _carried, ...bare } = req;
1295
+ const { hasBidiControls: _carried, boundInputHash: _claimed, ...bare } = req;
1295
1296
  const wait = Promise.resolve(onAsk({
1296
1297
  ...bare,
1297
- boundInputHash: boundInputHashOf(presented.value),
1298
+ ...(reconciliationHash !== undefined ? { boundInputHash: reconciliationHash } : {}),
1298
1299
  args: approverView.value,
1299
1300
  ...(bidi ? { hasBidiControls: true } : {}),
1300
1301
  ...(offered !== undefined ? { readRootCandidate: { ...offered } } : {}),
@@ -16,6 +16,7 @@ import type { TaskSpec } from "./task-spec.js";
16
16
  import type { BackgroundChildEvent } from "./delegation-frames.js";
17
17
  import type { ModelRef } from "./model-seat.js";
18
18
  import type { ToolFamily, ToolHostTarget, ToolPathTarget, ToolRenderHints, ToolRuleFace } from "./tool-face.js";
19
+ import type { MemoryGovernanceDocs } from "./memory-engine/types.js";
19
20
  /**
20
21
  * Side-effect class of a tool. Used by wake/resume reconciliation: when a call was interrupted
21
22
  * before its result was recorded, the outcome is unknown, so core must decide whether re-doing it
@@ -672,6 +673,14 @@ export interface NestedUsageAccum {
672
673
  * carry knownness alongside the number it qualifies. */
673
674
  anyUnpriced: boolean;
674
675
  }
676
+ /** {@link ToolExecuteContext.delegationSettlement}'s answer: where a delegation's settlement rows are kept (the WRITE
677
+ * plane's governance store), that plane's control-plane directory (the pollution marker and the hold custody files a
678
+ * settled delegation's effects reach), and the session whose rows they are. */
679
+ export interface DelegationSettlementSeat {
680
+ readonly governance: MemoryGovernanceDocs;
681
+ readonly controlDir: string;
682
+ readonly sessionId: string;
683
+ }
675
684
  export interface ToolExecuteContext {
676
685
  toolCallId: string;
677
686
  signal?: AbortSignal;
@@ -817,18 +826,31 @@ export interface ToolExecuteContext {
817
826
  * session backing, the child run fails LOUD ("refusing a silent fresh run") instead of silently
818
827
  * running an empty session under the forked id. Split-runner deployments must share session backing
819
828
  * (same store instance or same durable backend) for fork to complete.
820
- */
821
- hostSessionFork?: () => Promise<{
829
+ *
830
+ * The one argument is the store's own fork placement ({@link import("./session.js").SessionStore.fork}'s `opts`): a background
831
+ * fork's delegation tuple, laid down by the branch's creating write. It names no owner and no source — those stay bound here. It
832
+ * is handed on only when the host store declares the partition (the store creating the branch is the one that opts in); otherwise
833
+ * the branch is an ordinary fork.
834
+ */
835
+ hostSessionFork?: (opts?: {
836
+ placement?: Omit<import("./session.js").SessionPlacement, "owner">;
837
+ }) => Promise<{
822
838
  sessionId: string;
823
839
  release: () => Promise<void>;
824
840
  } | null>;
825
841
  /**
826
- * The RUNNING task's effective working root (worktree-aware), Runner-filled — read-only context a
827
- * delegation tool threads into its child's trusted internals so the child's env can inherit the
828
- * parent's cwd (CC parity: a Task sub-agent works in the main session's directory). Undefined when
829
- * the tool runs outside a Runner task.
842
+ * The RUNNING task's WRITE LOCATION (worktree-aware: the EnterWorktree tree while one is active, the task root otherwise —
843
+ * `currentCheckoutOf`, read at the call), Runner-filled — read-only context a delegation tool threads into its child's
844
+ * trusted internals so the child's env can inherit where the parent works (CC parity: a Task sub-agent works in the main
845
+ * session's directory). Undefined when the tool runs outside a Runner task.
830
846
  */
831
847
  parentCwd?: string;
848
+ /**
849
+ * The RUNNING task's own task root, Runner-filled beside {@link parentCwd}: the checkout a delegated child placed in "the
850
+ * caller's tree" would be writing into, whichever tree the caller has switched to inside it — what the child's placement
851
+ * judgment compares against (`RunInternals.callerRoot`). Absent on a ctx a caller outside the Runner built: its root is then where it works ({@link parentCwd}).
852
+ */
853
+ callerRoot?: string;
832
854
  /**
833
855
  * The RUNNING task's own placement target (Runner-filled, read-only, never a model argument): what its execution
834
856
  * environment reported as its workspace settled. A delegation tool hands it, as is, to every agent it spawns or wakes
@@ -1226,19 +1248,16 @@ export interface ToolExecuteContext {
1226
1248
  */
1227
1249
  delegationProvenanceForChildren?: () => import("./memory-engine/delegation-provenance.js").DelegationContentSafety | undefined;
1228
1250
  /**
1229
- * design/336 §3.3 — the delegation-settlement account's coordinates (the WRITE plane's memory
1230
- * control dir + this session's id), Runner-filled when the run mounts a memory session under
1231
- * `memoryProvenance: "carry"`. A delegation tool's BACKGROUND lane writes its launch write-ahead
1232
- * (pending row BEFORE registration and invoke) and its terminal settle through these — as pure
1233
- * data, because the terminal observation can run after this task leg returned and must rebuild
1234
- * its write handle from the coordinates alone. Undefined ⇒ no settlement account (memory-less
1235
- * run, or `"off"`): the background lane launches without rows, the pre-336 accepted-cost shape.
1236
- * Same trust posture as {@link delegationProvenanceForChildren}: never a model/tool argument.
1237
- */
1238
- delegationSettlement?: () => {
1239
- controlDir: string;
1240
- sessionId: string;
1241
- } | undefined;
1251
+ * design/336 §3.3 — the delegation-settlement account's coordinates (the WRITE plane's governance
1252
+ * store + its memory control dir + this session's id), Runner-filled when the run mounts a memory
1253
+ * session under `memoryProvenance: "carry"`. A delegation tool's BACKGROUND lane writes its launch
1254
+ * write-ahead (pending row BEFORE registration and invoke) and its terminal settle through these —
1255
+ * never through a live engine or session, because the terminal observation can run after this task
1256
+ * leg returned. Undefined ⇒ no settlement account (memory-less run, or `"off"`): the background lane
1257
+ * launches without rows, the pre-336 accepted-cost shape. Same trust posture as
1258
+ * {@link delegationProvenanceForChildren}: never a model/tool argument.
1259
+ */
1260
+ delegationSettlement?: () => DelegationSettlementSeat | undefined;
1242
1261
  /**
1243
1262
  * RB-201 FO-3 (form-one audit) — the auto-mode classifier decider ARMED
1244
1263
  * for THIS task (auto-mode intent ∧ `RunnerDeps.autoMode` present ∧ `RuntimeCaps.autoMode !== false`
@@ -15,7 +15,7 @@ export type { ModelRef, ModelRole, RoleSpec, ModelRoles, Brain } from "./model-s
15
15
  export { MODEL_ROLES } from "./model-seat.js";
16
16
  export type { StaleToolResultOffloadOptions, ImageInput, TaskSpec, ShellGateDoctrine, UserAttachment } from "./task-spec.js";
17
17
  export type { PermissionMode } from "./ask-origin.js";
18
- export type { ToolEffect, ToolContentOrigin, ReversibilityVerdict, ReadRootGrantCandidate, ToolSpec, ToolReturn, NestedUsage, NestedUsageAccum, ToolExecuteContext } from "./tool-spec.js";
18
+ export type { ToolEffect, ToolContentOrigin, ReversibilityVerdict, ReadRootGrantCandidate, ToolSpec, ToolReturn, NestedUsage, NestedUsageAccum, ToolExecuteContext, DelegationSettlementSeat } from "./tool-spec.js";
19
19
  export type { BeforeWriteRequest, BeforeWriteResult, BeforeWriteHook, TrackEditRequest, TrackEditResult, TrackFileEditHook, FileEditedNotice, FileEditedHook, HandsBandOptions } from "./hands-band.js";
20
20
  export type { AgentDefinition, SkillSpec } from "./agent-definition.js";
21
21
  export type { McpServerSpec, A2aServerSpec, McpElicitRequest, McpElicitResponse, OnElicit, McpRevocationLedger, McpMountIdentity, McpTransportKind, DeclarationFault, DeclarationPathRule, DeclarationRead, ToolAxesRead, ToolAxesSurface } from "./mcp-server-spec.js";
@@ -1,6 +1,16 @@
1
- import { type RedactionReport } from "./redaction-passes.js";
2
- export type { RedactionFinding, RedactionReport, RedactionConfidence, RedactionSource, SummarizableFinding, } from "./redaction-passes.js";
3
- export { summarizeRedactions } from "./redaction-passes.js";
1
+ import { type RedactionReport, type SummarizableFinding } from "@sema-agent/primitives";
2
+ export type { RedactionFinding, RedactionReport, RedactionConfidence, RedactionSource, SummarizableFinding } from "@sema-agent/primitives";
3
+ /** Render findings as ONE human-readable line, e.g. `"3 redactions: prefixed-token (high) x1, url (medium) x1, fs-path (low)
4
+ * x1"`, so an upper layer can declare to its consumer how much was removed and how confidently.
5
+ *
6
+ * PURE, and deliberately only that: it reads the array, returns a string, and injects nothing anywhere. Attaching this
7
+ * line to an output is the caller's decision — a redaction pipeline that silently appended prose to the very text it was
8
+ * asked to bound would break both the size contract (`boundedString`) and the byte-invariance the whole channel is built
9
+ * on.
10
+ *
11
+ * Grouping is by kind AND confidence together: collapsing on kind alone would report whichever confidence happened to
12
+ * arrive first for the rest of that group, a silent mis-statement of how sure the removals were. */
13
+ export declare function summarizeRedactions(findings: readonly SummarizableFinding[]): string;
4
14
  /**
5
15
  * Every exit that redacts — into a model's context, a host's event or error lane, a log line, a person's screen — does it
6
16
  * with ONE pass, its tier's, and nothing else redacts: a text through {@link egressText}, a thrown value's text through
@@ -27,7 +37,8 @@ declare const EGRESS_TIER: unique symbol;
27
37
  export type Egress<T extends EgressTier> = string & {
28
38
  readonly [EGRESS_TIER]: T;
29
39
  };
30
- /** Tier `tier`'s one pass over a text. */
40
+ /** Tier `tier`'s one pass over a text. A report's `preexistingMarkers` counts the engine's own marks ({@link REDACTION_MARKS})
41
+ * already in the text. */
31
42
  export declare function egressText<T extends EgressTier>(tier: T, text: string, report?: RedactionReport): Egress<T>;
32
43
  /** The text a thrown value reads as (`thrownText`), through tier `tier`'s pass: the one form a thrown value's words take
33
44
  * on their way out of the engine. */
@@ -1,34 +1,35 @@
1
1
  import { types } from "node:util";
2
+ import { isSensitiveRecordKey, renderSecrets, URL_OF_ANY_SCHEME } from "@sema-agent/primitives";
2
3
  import { delimitUntrusted, inlineUntrusted, neutralizeForFence } from "./untrusted-text.js";
3
- import { egressPasses, runRedactionPasses } from "./redaction-passes.js";
4
- import { REDACTION_MARK, REDACTION_MARKS, redactionMarkerSpans } from "./redaction-marks.js";
5
- import { CREDENTIAL_VOCABULARY, egressPassGroups, isSensitiveRecordKey, URI_SCHEME_SOURCE } from "./credential-vocabulary.js";
4
+ import { REDACTION_MARK, REDACTION_MARKS, REDACTION_NOTATION, redactionMarkerSpans } from "./redaction-marks.js";
6
5
  import { isErrorLike, readMember, thrownText } from "./thrown-value.js";
7
6
  import { sliceHeadSafe } from "./surrogate-safe-slice.js";
8
- export { summarizeRedactions } from "./redaction-passes.js";
9
- const URL_OF_ANY_PROTOCOL = new RegExp(String.raw `${URI_SCHEME_SOURCE}:\/\/[^\s"'\`]+`, "gi");
10
- const BARE_USERNAME_MAX_LEN = 20;
11
- function redactUserinfo(scheme, userinfoWithAt) {
12
- const userinfo = userinfoWithAt.slice(0, -1);
13
- if (CREDENTIAL_VOCABULARY.policy.urlUserinfo === "whole" || userinfo.includes("@"))
14
- return `${scheme}${REDACTION_MARKS.credentials}@`;
15
- const colonIdx = userinfo.indexOf(":");
16
- if (colonIdx === -1) {
17
- return userinfo.length >= BARE_USERNAME_MAX_LEN ? `${scheme}${REDACTION_MARKS.credentials}@` : `${scheme}${userinfo}@`;
7
+ export function summarizeRedactions(findings) {
8
+ if (findings.length === 0)
9
+ return "no redactions";
10
+ const counts = new Map();
11
+ for (const f of findings) {
12
+ const label = `${f.kind} (${f.confidence})`;
13
+ counts.set(label, (counts.get(label) ?? 0) + 1);
18
14
  }
19
- return `${scheme}${userinfo.slice(0, colonIdx)}:${REDACTION_MARKS.credentials}@`;
15
+ const parts = [...counts].map(([label, n]) => `${label} x${n}`);
16
+ return `${findings.length} redaction${findings.length === 1 ? "" : "s"}: ${parts.join(", ")}`;
20
17
  }
21
- const SECRET_TIER_PASSES = egressPasses(egressPassGroups(CREDENTIAL_VOCABULARY), {
22
- "url-credentials": (_m, scheme, userinfo) => redactUserinfo(scheme, userinfo),
18
+ const EGRESS_POLICY = Object.freeze({
19
+ grade: "wide",
20
+ readings: Object.freeze([Object.freeze({ kind: "raw" }), Object.freeze({ kind: "format-free" })]),
21
+ urlUserinfo: "keep-username",
22
+ onUnresolvedReading: "secret",
23
23
  });
24
- const HOST_LEAK_PASSES = [
25
- ...SECRET_TIER_PASSES,
26
- { kind: "url", confidence: "medium", marker: REDACTION_MARKS.url, source: "untrusted-egress", re: URL_OF_ANY_PROTOCOL, replace: REDACTION_MARKS.url },
24
+ const HOST_LEAK_PASSES = Object.freeze([
25
+ { kind: "url", confidence: "medium", marker: REDACTION_MARKS.url, source: "untrusted-egress", re: new RegExp(URL_OF_ANY_SCHEME.source, URL_OF_ANY_SCHEME.flags), replace: REDACTION_MARKS.url },
27
26
  { kind: "fs-path", confidence: "low", marker: REDACTION_MARKS.path, source: "untrusted-egress", re: /(?:\/[A-Za-z0-9_.-]+){2,}/g, replace: REDACTION_MARKS.path },
28
- ];
29
- const TIER_PASSES = { "same-principal": SECRET_TIER_PASSES, human: HOST_LEAK_PASSES };
27
+ ]);
28
+ const TIER_PASSES = { "same-principal": Object.freeze([]), human: HOST_LEAK_PASSES };
30
29
  export function egressText(tier, text, report) {
31
- return runRedactionPasses(text, TIER_PASSES[tier], report);
30
+ if (report !== undefined && report.preexistingMarkers === undefined)
31
+ report.preexistingMarkers = redactionMarkerSpans(text).length;
32
+ return renderSecrets(text, EGRESS_POLICY, REDACTION_NOTATION, { passes: TIER_PASSES[tier], report });
32
33
  }
33
34
  export function egressThrownText(tier, err) {
34
35
  return egressText(tier, thrownText(err));
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * The seat sends the leg-start snapshot when the leg binds its sink, and afterwards a frame only when the snapshot's digest
6
6
  * differs from the last frame it sent — the digest is the snapshot's canonical JSON, so every member the projection carries
7
- * takes part in the comparison with no second list to keep in step. The fixed members (root, project, remote) are leg
7
+ * takes part in the comparison with no second list to keep in step. The fixed members (root, session, project, remote) are leg
8
8
  * facts handed in at prepare; the two live ones are read off the leg's own seats at each observation (the tracked cwd, the
9
9
  * active EnterWorktree switch), never copied.
10
10
  */
@@ -29,6 +29,8 @@ export interface WorkspaceFacts {
29
29
  };
30
30
  /** The leg's project verdict (`resolveSessionProject`); absent ⇒ the leg has no project identity. */
31
31
  readonly project?: SessionProject;
32
+ /** The session's checkout as the frame reports it (`sessionFrameOf`); absent ⇒ the session declared no workspace. */
33
+ readonly session?: WorkspaceSnapshot["session"];
32
34
  /** The leg's one remoteness reading (the restore phase's, the same value `ResolvedWorkspace.remote` carries). */
33
35
  readonly remote: boolean;
34
36
  }
@@ -5,6 +5,7 @@ export function workspaceSnapshotOf(facts) {
5
5
  cwd: facts.cwdRef?.current ?? facts.root,
6
6
  root: facts.root,
7
7
  ...(active !== undefined ? { entered: { dir: active.worktreeDir, ...(active.entered === true ? { byPath: true } : {}) } } : {}),
8
+ ...(facts.session !== undefined ? { session: facts.session } : {}),
8
9
  ...(facts.project !== undefined ? { project: { id: facts.project.id, source: facts.project.source } } : {}),
9
10
  remote: facts.remote,
10
11
  };
@@ -851,6 +851,63 @@ export interface WorkspaceState {
851
851
  export interface WorkspaceStateEntry extends SessionTreeEntryBase, WorkspaceState {
852
852
  type: "workspace_state";
853
853
  }
854
+ /** A declared code source, as a session checkout records it: the root it answers for (the task root, or an
855
+ * `additionalDirectories` entry in its declared spelling), the repository URL in its normalized `https` form, the full
856
+ * commit id, and the display label the host gave. */
857
+ export interface SessionCheckoutSource {
858
+ root: "taskRoot" | {
859
+ directory: string;
860
+ };
861
+ remote: string;
862
+ sha: string;
863
+ ref?: string;
864
+ }
865
+ /** The workspace declaration a session checkout was opened under, normalized — what every later leg's declaration is
866
+ * compared with (`config.session_workspace_changed` when they differ). */
867
+ export interface SessionCheckoutDeclared {
868
+ isolation?: "worktree";
869
+ baseRef?: "fresh" | "head";
870
+ name?: string;
871
+ sources?: SessionCheckoutSource[];
872
+ }
873
+ /** One repository of a session checkout. `dir` / `name` / `branch` / `baseRef` are present together iff the repository is
874
+ * isolated (the session's own tree); `source` iff a declared source names this repository. */
875
+ export interface SessionCheckoutCell {
876
+ /** The repository's main worktree root (canonical) — the repository this cell answers for. */
877
+ repository: string;
878
+ /** Which declared root lives in this cell. */
879
+ root: "taskRoot" | {
880
+ directory: string;
881
+ };
882
+ /** The commit this session's code starts from: the tree's base commit, or the declared source's commit. */
883
+ baseSha: string;
884
+ dir?: string;
885
+ name?: string;
886
+ branch?: string;
887
+ baseRef?: "fresh" | "head" | "source";
888
+ source?: {
889
+ remote: string;
890
+ sha: string;
891
+ ref?: string;
892
+ };
893
+ }
894
+ /**
895
+ * design/1456 R1′ (#2292): a session's checkout — an IMMUTABLE allocation, minted ONCE by the session's first leg from its
896
+ * workspace declaration, and written once more only by `releaseSessionCheckout` (the same record with `released: true`).
897
+ * Session-scoped, not branch-scoped: readers scan the whole log, and only an entry whose `sessionId` is the reader's own
898
+ * session counts (a fork's copied entry is the parent's, so a fork does not inherit the checkout). A list of repositories
899
+ * from the start (multi-root sessions add cells, never change the shape).
900
+ */
901
+ export interface SessionCheckoutRecord {
902
+ allocationId: string;
903
+ sessionId: string;
904
+ declared: SessionCheckoutDeclared;
905
+ checkouts: SessionCheckoutCell[];
906
+ released?: true;
907
+ }
908
+ export interface SessionCheckoutEntry extends SessionTreeEntryBase, SessionCheckoutRecord {
909
+ type: "session_checkout";
910
+ }
854
911
  /** Bounded cap for {@link normalizeReminderMark}: the current scheme's value is 22 chars; the bound
855
912
  * is deliberately looser (an opaque bounded token) so the STORE never learns the scheme — the real
856
913
  * value-shape verify lives in the mint home (core/reminder-mint.ts `isValidReminderMark`), applied
@@ -942,6 +999,14 @@ export declare const WORKSPACE_STATE_MAX_PATH_CHARS = 4096;
942
999
  * undefined when the value is not structurally valid.
943
1000
  */
944
1001
  export declare function normalizeWorkspaceState(value: unknown): WorkspaceState | undefined;
1002
+ /** Bounds of a session checkout record: one repository per cell, one source per repository. */
1003
+ export declare const SESSION_CHECKOUT_MAX_CELLS = 64;
1004
+ /**
1005
+ * design/1456 (#2292): the strict shape gate of a {@link SessionCheckoutRecord} — the ONE normalization the record's read, its
1006
+ * append and the import door use. `undefined` = not a structurally valid record (the reader REFUSES it, never skips it:
1007
+ * a checkout that cannot be read is a checkout the session cannot use).
1008
+ */
1009
+ export declare function normalizeSessionCheckout(value: unknown): SessionCheckoutRecord | undefined;
945
1010
  /** Bounded caps for {@link normalizeAnnouncedListing} — a roster is dozens of names, never thousands;
946
1011
  * a "name" is a short identifier, never a document. Oversize ⇒ structurally invalid (forgery signal). */
947
1012
  export declare const ANNOUNCED_LISTING_MAX_NAMES = 500;
@@ -1010,7 +1075,7 @@ export declare function isSyntheticApiErrorMessage(m: unknown): boolean;
1010
1075
  export declare function isOptionalDisplayString(v: unknown, max?: number): boolean;
1011
1076
  export declare function normalizeAnnouncedListing(v: unknown): AnnouncedListingSnapshot | undefined;
1012
1077
  /** All persisted session tree entry variants. */
1013
- export type SessionTreeEntry = MessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry | LeafEntry | PromptEpochEntry | AnnouncedListingEntry | GitAnnouncementEntry | WorkspaceStateEntry | ReminderMarkEntry;
1078
+ export type SessionTreeEntry = MessageEntry | ThinkingLevelChangeEntry | ModelChangeEntry | CompactionEntry | CustomEntry | CustomMessageEntry | LabelEntry | SessionInfoEntry | LeafEntry | PromptEpochEntry | AnnouncedListingEntry | GitAnnouncementEntry | WorkspaceStateEntry | SessionCheckoutEntry | ReminderMarkEntry;
1014
1079
  export interface SessionContext {
1015
1080
  messages: AgentMessage[];
1016
1081
  thinkingLevel: string;
@@ -136,6 +136,114 @@ export function normalizeWorkspaceState(value) {
136
136
  }
137
137
  return out;
138
138
  }
139
+ export const SESSION_CHECKOUT_MAX_CELLS = 64;
140
+ const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
141
+ const CHECKOUT_TOKEN = /^[A-Za-z0-9._:-]{1,128}$/;
142
+ function normalizeCheckoutRoot(value) {
143
+ if (value === "taskRoot")
144
+ return "taskRoot";
145
+ if (value === null || typeof value !== "object" || Array.isArray(value))
146
+ return undefined;
147
+ const keys = Object.keys(value);
148
+ const directory = value.directory;
149
+ if (keys.length !== 1 || typeof directory !== "string" || !directory.startsWith("/") || directory.length > WORKSPACE_STATE_MAX_PATH_CHARS)
150
+ return undefined;
151
+ return { directory };
152
+ }
153
+ function normalizeCheckoutSource(value) {
154
+ if (value === null || typeof value !== "object" || Array.isArray(value))
155
+ return undefined;
156
+ const v = value;
157
+ const root = normalizeCheckoutRoot(v.root);
158
+ if (root === undefined)
159
+ return undefined;
160
+ if (typeof v.remote !== "string" || !v.remote.startsWith("https://") || v.remote.length > 2048)
161
+ return undefined;
162
+ if (typeof v.sha !== "string" || !FULL_SHA.test(v.sha))
163
+ return undefined;
164
+ if (v.ref !== undefined && (typeof v.ref !== "string" || v.ref.length === 0 || v.ref.length > 256))
165
+ return undefined;
166
+ return { root, remote: v.remote, sha: v.sha, ...(v.ref !== undefined ? { ref: v.ref } : {}) };
167
+ }
168
+ export function normalizeSessionCheckout(value) {
169
+ if (value === null || typeof value !== "object")
170
+ return undefined;
171
+ const v = value;
172
+ const okPath = (p) => typeof p === "string" && p.startsWith("/") && p.length <= WORKSPACE_STATE_MAX_PATH_CHARS;
173
+ if (typeof v.allocationId !== "string" || !CHECKOUT_TOKEN.test(v.allocationId))
174
+ return undefined;
175
+ if (typeof v.sessionId !== "string" || v.sessionId.length === 0 || v.sessionId.length > 512)
176
+ return undefined;
177
+ if (v.released !== undefined && v.released !== true)
178
+ return undefined;
179
+ if (v.declared === null || typeof v.declared !== "object" || Array.isArray(v.declared))
180
+ return undefined;
181
+ const d = v.declared;
182
+ if (d.isolation !== undefined && d.isolation !== "worktree")
183
+ return undefined;
184
+ if (d.baseRef !== undefined && d.baseRef !== "fresh" && d.baseRef !== "head")
185
+ return undefined;
186
+ if (d.name !== undefined && (typeof d.name !== "string" || !/^[A-Za-z0-9._/-]{1,64}$/.test(d.name)))
187
+ return undefined;
188
+ let sources;
189
+ if (d.sources !== undefined) {
190
+ if (!Array.isArray(d.sources) || d.sources.length === 0 || d.sources.length > SESSION_CHECKOUT_MAX_CELLS)
191
+ return undefined;
192
+ sources = [];
193
+ for (const s of d.sources) {
194
+ const shaped = normalizeCheckoutSource(s);
195
+ if (shaped === undefined)
196
+ return undefined;
197
+ sources.push(shaped);
198
+ }
199
+ }
200
+ const declared = {
201
+ ...(d.isolation !== undefined ? { isolation: "worktree" } : {}),
202
+ ...(d.baseRef !== undefined ? { baseRef: d.baseRef } : {}),
203
+ ...(d.name !== undefined ? { name: d.name } : {}),
204
+ ...(sources !== undefined ? { sources } : {}),
205
+ };
206
+ if (!Array.isArray(v.checkouts) || v.checkouts.length > SESSION_CHECKOUT_MAX_CELLS)
207
+ return undefined;
208
+ const checkouts = [];
209
+ for (const c of v.checkouts) {
210
+ if (c === null || typeof c !== "object" || Array.isArray(c))
211
+ return undefined;
212
+ const cell = c;
213
+ const root = normalizeCheckoutRoot(cell.root);
214
+ if (!okPath(cell.repository) || root === undefined || typeof cell.baseSha !== "string" || !FULL_SHA.test(cell.baseSha))
215
+ return undefined;
216
+ const tree = [cell.dir, cell.name, cell.branch, cell.baseRef];
217
+ const isolated = tree.every((x) => x !== undefined);
218
+ if (!isolated && !tree.every((x) => x === undefined))
219
+ return undefined;
220
+ if (isolated) {
221
+ if (!okPath(cell.dir) || typeof cell.name !== "string" || !/^[A-Za-z0-9._/-]{1,64}$/.test(cell.name))
222
+ return undefined;
223
+ if (typeof cell.branch !== "string" || !/^sema\/[A-Za-z0-9._+-]{1,64}$/.test(cell.branch))
224
+ return undefined;
225
+ if (cell.baseRef !== "fresh" && cell.baseRef !== "head" && cell.baseRef !== "source")
226
+ return undefined;
227
+ }
228
+ let source;
229
+ if (cell.source !== undefined) {
230
+ const s = cell.source;
231
+ if (s === null || typeof s !== "object" || typeof s.remote !== "string" || !s.remote.startsWith("https://") || typeof s.sha !== "string" || !FULL_SHA.test(s.sha))
232
+ return undefined;
233
+ if (s.ref !== undefined && (typeof s.ref !== "string" || s.ref.length === 0 || s.ref.length > 256))
234
+ return undefined;
235
+ source = { remote: s.remote, sha: s.sha, ...(s.ref !== undefined ? { ref: s.ref } : {}) };
236
+ }
237
+ checkouts.push({
238
+ repository: cell.repository,
239
+ root,
240
+ baseSha: cell.baseSha,
241
+ ...(isolated ? { dir: cell.dir, name: cell.name, branch: cell.branch, baseRef: cell.baseRef } : {}),
242
+ ...(source !== undefined ? { source } : {}),
243
+ });
244
+ }
245
+ return { allocationId: v.allocationId, sessionId: v.sessionId, declared, checkouts, ...(v.released === true ? { released: true } : {}) };
246
+ }
139
247
  export const ANNOUNCED_LISTING_MAX_NAMES = 500;
140
248
  export const ANNOUNCED_LISTING_MAX_NAME_CHARS = 200;
141
249
  export const ANNOUNCED_MCP_ERROR_MAX_CHARS = 400;
@@ -1,4 +1,4 @@
1
- import { SessionError, normalizeAnnouncedListing, normalizeReminderMark, normalizeGitAnnouncement, normalizeWorkspaceState, normalizeCompactionStateCarrier, isValidThinkingLevelChange, isValidModelChange, isOptionalDisplayString, } from "../harness/types.js";
1
+ import { SessionError, normalizeAnnouncedListing, normalizeReminderMark, normalizeGitAnnouncement, normalizeSessionCheckout, normalizeWorkspaceState, normalizeCompactionStateCarrier, isValidThinkingLevelChange, isValidModelChange, isOptionalDisplayString, } from "../harness/types.js";
2
2
  import { leafIdAfterEntry } from "./storage-base.js";
3
3
  import { parseSessionTimestampMs } from "./timestamps.js";
4
4
  import { flattenableUserText, normalizeEngineSegments } from "../../core/untrusted-text.js";
@@ -81,6 +81,11 @@ export class StreamingImportValidator {
81
81
  throw new SessionError("invalid_session", `workspace_state entry "${e.id}" is structurally invalid`);
82
82
  }
83
83
  }
84
+ else if (e.type === "session_checkout") {
85
+ if (normalizeSessionCheckout(e) === undefined) {
86
+ throw new SessionError("invalid_session", `session_checkout entry "${e.id}" is structurally invalid`);
87
+ }
88
+ }
84
89
  else if (e.type === "reminder_mark") {
85
90
  if (normalizeReminderMark(e) === undefined) {
86
91
  throw new SessionError("invalid_session", `reminder_mark entry "${e.id}" is structurally invalid`);
@@ -1,6 +1,6 @@
1
1
  import type { ImageContent, TextContent } from "../llm/index.js";
2
2
  import type { AgentMessage } from "../loop/types.js";
3
- import type { AnnouncedListingSnapshot, AnnouncedListingSnapshotInput, GitAnnouncementState, Session, SessionContext, SessionMetadata, SessionStorage, SessionTreeEntry, WorkspaceState } from "../harness/types.js";
3
+ import type { AnnouncedListingSnapshot, AnnouncedListingSnapshotInput, GitAnnouncementState, Session, SessionCheckoutRecord, SessionContext, SessionMetadata, SessionStorage, SessionTreeEntry, WorkspaceState } from "../harness/types.js";
4
4
  import type { BuildContextOptions } from "../harness/types.js";
5
5
  import type { PromptEpochDescriptor, StoredPromptEpoch } from "../../prompt-assembly/epoch.js";
6
6
  /** Build model context from the active session branch and its latest state markers.
@@ -163,3 +163,26 @@ export declare class StoredSession<TMetadata extends SessionMetadata = SessionMe
163
163
  * rule, both readers). Conservative on damage: an unresolvable firstKeptEntryId reads as invisible.
164
164
  */
165
165
  export declare function gitFrameContextVisible(branch: SessionTreeEntry[], entryId: string): boolean;
166
+ /** What reading a session's checkout answered: none minted by this session, the one it minted (with `released` when it was
167
+ * released), or a log the reader cannot vouch for — NOT "none" (a checkout that cannot be read is one the session cannot use). */
168
+ export type SessionCheckoutRead = {
169
+ readonly kind: "none";
170
+ } | {
171
+ readonly kind: "record";
172
+ readonly record: SessionCheckoutRecord;
173
+ } | {
174
+ readonly kind: "unreadable";
175
+ readonly detail: string;
176
+ };
177
+ /**
178
+ * design/1456 R1′ (#2292): THE reader of a session's checkout. Scans the whole log (`findEntries`, never the branch: a rewind
179
+ * to before the allocation must not drop the tree) for `session_checkout` entries minted by THIS session (`sessionId`), so a
180
+ * fork's copied entries — the parent's — are not its own. Never best-effort: a store read that throws, an own entry that is not
181
+ * a structurally valid record, a second allocation, or a release that names another allocation answers `unreadable`.
182
+ */
183
+ export declare function readSessionCheckout(session: Session, sessionId: string): Promise<SessionCheckoutRead>;
184
+ /** Append a session checkout entry (the allocation, or its one release), shape-gated by {@link normalizeSessionCheckout} and
185
+ * conditioned on a leaf like every typed append: `observedLeafId` (the leaf read BEFORE the caller judged the session had no
186
+ * allocation — so a writer that appended since, another leg allocating at the same time, makes this append fail instead of
187
+ * leaving two allocations), else the current one. */
188
+ export declare function appendSessionCheckout(session: Session, record: SessionCheckoutRecord, observedLeafId?: string | null): Promise<string>;