@sema-agent/core 7.61.0 → 7.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/CHANGELOG.md +840 -0
  2. package/dist/agents/cascade.d.ts +11 -3
  3. package/dist/agents/cascade.js +1 -1
  4. package/dist/agents/peer-held-queue.d.ts +27 -4
  5. package/dist/agents/peer-held-queue.js +81 -36
  6. package/dist/agents/peer-session-drain.js +13 -3
  7. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  8. package/dist/agents/subagent-transcript-placement.js +14 -0
  9. package/dist/agents/subagent.d.ts +6 -1
  10. package/dist/agents/subagent.js +143 -58
  11. package/dist/agents/suspend-guard.d.ts +38 -16
  12. package/dist/agents/suspend-guard.js +9 -4
  13. package/dist/agents/verify.js +4 -3
  14. package/dist/brain/route-adjudicator.js +9 -4
  15. package/dist/core/approval-object.js +1 -1
  16. package/dist/core/arg-summary.js +1 -1
  17. package/dist/core/ask-question.d.ts +2 -2
  18. package/dist/core/canonical-json.d.ts +23 -13
  19. package/dist/core/canonical-json.js +4 -4
  20. package/dist/core/checkpoint-features.d.ts +722 -0
  21. package/dist/core/checkpoint-features.js +98 -0
  22. package/dist/core/checkpoint-queries.d.ts +47 -4
  23. package/dist/core/checkpoint-queries.js +36 -16
  24. package/dist/core/checkpoint-requirements.d.ts +12 -5
  25. package/dist/core/checkpoint-requirements.js +11 -5
  26. package/dist/core/checkpoint-row-verdict.d.ts +110 -0
  27. package/dist/core/checkpoint-row-verdict.js +245 -0
  28. package/dist/core/checkpoint-store.d.ts +76 -753
  29. package/dist/core/checkpoint-store.js +83 -144
  30. package/dist/core/compliance.d.ts +6 -2
  31. package/dist/core/compliance.js +3 -3
  32. package/dist/core/engine-attestation.d.ts +1 -1
  33. package/dist/core/engine-notice.d.ts +38 -7
  34. package/dist/core/engine-notice.js +9 -2
  35. package/dist/core/gate-fold.js +2 -2
  36. package/dist/core/git-worktree-env.d.ts +62 -3
  37. package/dist/core/git-worktree-env.js +91 -30
  38. package/dist/core/governance-codes.d.ts +9 -3
  39. package/dist/core/governance-codes.js +16 -3
  40. package/dist/core/hooks.d.ts +13 -0
  41. package/dist/core/human-input-projection.d.ts +1 -0
  42. package/dist/core/human-input-projection.js +3 -0
  43. package/dist/core/image-admission.d.ts +1 -1
  44. package/dist/core/locked-config.d.ts +2 -2
  45. package/dist/core/mcp-host-seat.js +6 -1
  46. package/dist/core/memory-engine/consolidation-driver.d.ts +33 -18
  47. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  48. package/dist/core/memory-engine/consolidation.d.ts +73 -10
  49. package/dist/core/memory-engine/consolidation.js +167 -11
  50. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  51. package/dist/core/memory-engine/data-plane.js +11 -6
  52. package/dist/core/memory-engine/delegation-settlement.d.ts +37 -35
  53. package/dist/core/memory-engine/delegation-settlement.js +53 -59
  54. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  55. package/dist/core/memory-engine/dual-root.js +9 -5
  56. package/dist/core/memory-engine/engine.d.ts +98 -35
  57. package/dist/core/memory-engine/engine.js +477 -380
  58. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  59. package/dist/core/memory-engine/entry-scan.js +3 -0
  60. package/dist/core/memory-engine/file-backend.d.ts +29 -3
  61. package/dist/core/memory-engine/file-backend.js +66 -35
  62. package/dist/core/memory-engine/index.d.ts +7 -7
  63. package/dist/core/memory-engine/index.js +6 -6
  64. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  65. package/dist/core/memory-engine/landing-admission.js +3 -3
  66. package/dist/core/memory-engine/layout.d.ts +121 -45
  67. package/dist/core/memory-engine/layout.js +252 -102
  68. package/dist/core/memory-engine/memory-backend-contract.d.ts +19 -1
  69. package/dist/core/memory-engine/memory-backend-contract.js +320 -0
  70. package/dist/core/memory-engine/memory-deployment.d.ts +31 -8
  71. package/dist/core/memory-engine/memory-deployment.js +26 -12
  72. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  73. package/dist/core/memory-engine/scope-contract.js +68 -19
  74. package/dist/core/memory-engine/session-write-home.d.ts +3 -1
  75. package/dist/core/memory-engine/session-write-home.js +1 -1
  76. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  77. package/dist/core/memory-engine/sync-client.js +7 -0
  78. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  79. package/dist/core/memory-engine/sync-report.js +6 -2
  80. package/dist/core/memory-engine/tools.d.ts +2 -2
  81. package/dist/core/memory-engine/tools.js +10 -10
  82. package/dist/core/memory-engine/types.d.ts +118 -19
  83. package/dist/core/memory-engine/types.js +1 -0
  84. package/dist/core/memory-vector.d.ts +1 -1
  85. package/dist/core/memory.d.ts +10 -10
  86. package/dist/core/memory.js +15 -6
  87. package/dist/core/mode-policy.js +1 -1
  88. package/dist/core/mods/classic-events.d.ts +9 -1
  89. package/dist/core/mods/dollar.d.ts +32 -1
  90. package/dist/core/mods/dollar.js +13 -1
  91. package/dist/core/mods/kernel/events.d.ts +11 -3
  92. package/dist/core/mods/kernel/events.js +13 -10
  93. package/dist/core/mods/lifecycle-stations.d.ts +36 -4
  94. package/dist/core/mods/lifecycle-stations.js +44 -9
  95. package/dist/core/mods/session-append.d.ts +4 -1
  96. package/dist/core/mods/session-append.js +7 -0
  97. package/dist/core/mods/session-receive.js +12 -15
  98. package/dist/core/mods/stations.d.ts +70 -6
  99. package/dist/core/mods/stations.js +144 -1
  100. package/dist/core/own-property-receipt.d.ts +7 -0
  101. package/dist/core/own-property-receipt.js +3 -0
  102. package/dist/core/park-selfcheck.js +2 -2
  103. package/dist/core/pause-registry.d.ts +2 -0
  104. package/dist/core/pause-registry.js +3 -0
  105. package/dist/core/permission-rule-consent.d.ts +10 -3
  106. package/dist/core/permission-rule-consent.js +37 -24
  107. package/dist/core/permission-rule-store.d.ts +35 -1
  108. package/dist/core/permission-rule-store.js +27 -8
  109. package/dist/core/read-only-shell.js +3 -2
  110. package/dist/core/read-root-candidate.js +1 -1
  111. package/dist/core/redaction-marks.d.ts +8 -0
  112. package/dist/core/redaction-marks.js +6 -0
  113. package/dist/core/remote-env.d.ts +12 -1
  114. package/dist/core/remote-env.js +3 -0
  115. package/dist/core/resume-startup-cause.d.ts +5 -4
  116. package/dist/core/runner/child-tree.d.ts +29 -3
  117. package/dist/core/runner/child-tree.js +39 -16
  118. package/dist/core/runner/compact-session.js +5 -2
  119. package/dist/core/runner/contracts.d.ts +36 -17
  120. package/dist/core/runner/delegation-owner.d.ts +43 -0
  121. package/dist/core/runner/delegation-owner.js +59 -0
  122. package/dist/core/runner/gate-exit.js +2 -2
  123. package/dist/core/runner/inherited-ask-grants.js +1 -1
  124. package/dist/core/runner/lineage-reroot-view.d.ts +56 -0
  125. package/dist/core/runner/lineage-reroot-view.js +108 -0
  126. package/dist/core/runner/memory-consolidation-driver.d.ts +6 -3
  127. package/dist/core/runner/memory-consolidation-driver.js +4 -4
  128. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  129. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  130. package/dist/core/runner/permission-rule-lanes.d.ts +2 -1
  131. package/dist/core/runner/permission-rule-lanes.js +2 -2
  132. package/dist/core/runner/person-path-rows.d.ts +23 -3
  133. package/dist/core/runner/person-path-rows.js +31 -4
  134. package/dist/core/runner/placement-fence.d.ts +12 -0
  135. package/dist/core/runner/placement-fence.js +20 -6
  136. package/dist/core/runner/prepare-acquire-reconcile.d.ts +4 -1
  137. package/dist/core/runner/prepare-acquire-reconcile.js +7 -2
  138. package/dist/core/runner/prepare-ask-lane.js +2 -2
  139. package/dist/core/runner/prepare-caps-and-workflow.d.ts +5 -1
  140. package/dist/core/runner/prepare-caps-and-workflow.js +6 -3
  141. package/dist/core/runner/prepare-config-doors.d.ts +6 -6
  142. package/dist/core/runner/prepare-config-doors.js +3 -4
  143. package/dist/core/runner/prepare-execution-env.js +17 -6
  144. package/dist/core/runner/prepare-hands-readface.d.ts +3 -2
  145. package/dist/core/runner/prepare-hands-readface.js +32 -10
  146. package/dist/core/runner/prepare-inherited-gate.d.ts +12 -8
  147. package/dist/core/runner/prepare-inherited-gate.js +14 -6
  148. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  149. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  150. package/dist/core/runner/prepare-memory.d.ts +3 -2
  151. package/dist/core/runner/prepare-memory.js +28 -20
  152. package/dist/core/runner/prepare-park-ask.js +4 -3
  153. package/dist/core/runner/prepare-task.js +22 -16
  154. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  155. package/dist/core/runner/resume-admission.d.ts +3 -3
  156. package/dist/core/runner/resume-admission.js +6 -3
  157. package/dist/core/runner/resume-apply.d.ts +4 -0
  158. package/dist/core/runner/resume-apply.js +11 -4
  159. package/dist/core/runner/resume-checkpoint-screen.d.ts +9 -0
  160. package/dist/core/runner/resume-checkpoint-screen.js +4 -84
  161. package/dist/core/runner/run-git-lane.d.ts +2 -0
  162. package/dist/core/runner/run-git-lane.js +4 -1
  163. package/dist/core/runner/run-harness-handlers.d.ts +2 -0
  164. package/dist/core/runner/run-harness-handlers.js +3 -2
  165. package/dist/core/runner/run-leg.js +25 -8
  166. package/dist/core/runner/run-settle-and-teardown.js +6 -4
  167. package/dist/core/runner/run-stop-and-final-verify.js +2 -1
  168. package/dist/core/runner/run-turn-boundary.js +7 -4
  169. package/dist/core/runner/runtask.js +6 -6
  170. package/dist/core/runner/steering-preview.d.ts +9 -0
  171. package/dist/core/runner/steering-preview.js +5 -0
  172. package/dist/core/runner/stream-steer-verb.js +8 -0
  173. package/dist/core/runner/terminal-account.js +1 -1
  174. package/dist/core/runner/tool-face-overlay.js +2 -0
  175. package/dist/core/runner/turn-attachments.d.ts +5 -0
  176. package/dist/core/runner/turn-attachments.js +1 -1
  177. package/dist/core/runner-deps.d.ts +8 -4
  178. package/dist/core/secret-env.d.ts +9 -6
  179. package/dist/core/secret-env.js +41 -22
  180. package/dist/core/session-checkout.d.ts +108 -0
  181. package/dist/core/session-checkout.js +485 -0
  182. package/dist/core/session-store.d.ts +13 -5
  183. package/dist/core/session-store.js +28 -4
  184. package/dist/core/session.d.ts +29 -5
  185. package/dist/core/session.js +3 -0
  186. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +6 -12
  187. package/dist/core/store-contracts/checkpoint-store-contract.js +73 -6
  188. package/dist/core/store-contracts/session-store-contract.js +61 -8
  189. package/dist/core/task-event.d.ts +28 -1
  190. package/dist/core/task-notification.d.ts +9 -1
  191. package/dist/core/task-notification.js +8 -1
  192. package/dist/core/task-registry-agent.d.ts +40 -8
  193. package/dist/core/task-registry-agent.js +57 -24
  194. package/dist/core/task-registry-shared.d.ts +33 -11
  195. package/dist/core/task-registry-workflow.js +4 -3
  196. package/dist/core/task-registry.d.ts +27 -10
  197. package/dist/core/task-registry.js +19 -13
  198. package/dist/core/task-result.d.ts +5 -5
  199. package/dist/core/task-spec-members.js +1 -1
  200. package/dist/core/task-spec.d.ts +21 -1
  201. package/dist/core/terminal-cause.d.ts +6 -6
  202. package/dist/core/tool-face.d.ts +6 -2
  203. package/dist/core/tool-face.js +1 -1
  204. package/dist/core/tool-policy.d.ts +16 -13
  205. package/dist/core/tool-policy.js +11 -10
  206. package/dist/core/tool-roster.d.ts +4 -4
  207. package/dist/core/tool-spec.d.ts +42 -19
  208. package/dist/core/types.d.ts +2 -2
  209. package/dist/core/types.js +1 -1
  210. package/dist/core/untrusted-egress.d.ts +15 -4
  211. package/dist/core/untrusted-egress.js +23 -22
  212. package/dist/core/workspace-snapshot.d.ts +3 -1
  213. package/dist/core/workspace-snapshot.js +1 -0
  214. package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
  215. package/dist/engine/execution-env/node-execution-env.js +12 -5
  216. package/dist/engine/harness/types.d.ts +77 -1
  217. package/dist/engine/harness/types.js +108 -0
  218. package/dist/engine/session/import-validate.js +6 -1
  219. package/dist/engine/session/parent-chain-guard.d.ts +3 -3
  220. package/dist/engine/session/parent-chain-guard.js +1 -1
  221. package/dist/engine/session/path-to-root.d.ts +18 -3
  222. package/dist/engine/session/path-to-root.js +15 -1
  223. package/dist/engine/session/repo-utils.d.ts +12 -1
  224. package/dist/engine/session/repo-utils.js +41 -0
  225. package/dist/engine/session/session.d.ts +24 -1
  226. package/dist/engine/session/session.js +46 -2
  227. package/dist/engine/session/storage-base.d.ts +20 -0
  228. package/dist/engine/session/storage-base.js +28 -9
  229. package/dist/index.d.ts +16 -12
  230. package/dist/index.js +11 -8
  231. package/dist/internal/harness-types.d.ts +1 -1
  232. package/dist/internal/harness.d.ts +4 -3
  233. package/dist/internal/harness.js +3 -2
  234. package/dist/orchestration/run-workflow-tool.d.ts +7 -1
  235. package/dist/orchestration/run-workflow-tool.js +28 -11
  236. package/dist/orchestration/workflow-governance.d.ts +1 -1
  237. package/dist/orchestration/workflow.d.ts +6 -0
  238. package/dist/orchestration/workflow.js +5 -8
  239. package/dist/stores/file/checkpoint-store.d.ts +2 -0
  240. package/dist/stores/file/checkpoint-store.js +7 -6
  241. package/dist/stores/file/fs-atomic.d.ts +0 -22
  242. package/dist/stores/file/fs-atomic.js +0 -17
  243. package/dist/stores/file/index.d.ts +2 -9
  244. package/dist/stores/file/index.js +2 -4
  245. package/dist/stores/file/session-store.d.ts +13 -7
  246. package/dist/stores/file/session-store.js +42 -18
  247. package/dist/tools/fs/bash-program-position.d.ts +3 -2
  248. package/dist/tools/fs/bash-program-position.js +10 -10
  249. package/dist/tools/fs/program-read-model.d.ts +34 -10
  250. package/dist/tools/fs/program-read-model.js +37 -7
  251. package/dist/tools/fs/program-read-model.rows.js +13 -2
  252. package/dist/tools/fs/read-deny.d.ts +13 -1
  253. package/dist/tools/fs/read-deny.js +10 -2
  254. package/dist/tools/fs/removal-targets.js +5 -5
  255. package/dist/tools/fs/safety.d.ts +2 -0
  256. package/dist/tools/fs/safety.js +1 -1
  257. package/dist/tools/fs/shell-read-argv.d.ts +11 -2
  258. package/dist/tools/fs/shell-read-argv.js +45 -29
  259. package/dist/tools/fs/shell-read-bindings.d.ts +20 -2
  260. package/dist/tools/fs/shell-read-bindings.js +153 -69
  261. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  262. package/dist/tools/fs/shell-read-brace.js +79 -0
  263. package/dist/tools/fs/shell-read-check.js +29 -11
  264. package/dist/tools/fs/shell-read-establish.js +43 -22
  265. package/dist/tools/fs/shell-read-functions.js +2 -2
  266. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  267. package/dist/tools/fs/shell-read-judge.js +3 -3
  268. package/dist/tools/fs/shell-read-object-path.d.ts +59 -0
  269. package/dist/tools/fs/shell-read-object-path.js +119 -0
  270. package/dist/tools/fs/shell-read-plan.d.ts +18 -0
  271. package/dist/tools/fs/shell-read-plan.js +217 -104
  272. package/dist/tools/fs/shell-read-start.d.ts +76 -13
  273. package/dist/tools/fs/shell-read-start.js +97 -17
  274. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  275. package/dist/tools/fs/shell-read-word.js +9 -5
  276. package/dist/tools/fs/shell-read-workdir.d.ts +54 -14
  277. package/dist/tools/fs/shell-read-workdir.js +103 -19
  278. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  279. package/dist/tools/worktree.d.ts +3 -2
  280. package/dist/tools/worktree.js +7 -35
  281. package/package.json +3 -2
  282. package/test/export-surface.snapshot.json +93 -43
  283. package/wire-changes/core-stores-sql@7.62.0.json +30 -0
  284. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  285. package/wire-changes/core@7.62.0.json +2181 -0
  286. package/wire-changes/core@7.63.0.json +3523 -0
  287. package/wire-changes/mods-kernel@7.62.0.json +42 -0
  288. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  289. package/wire-changes/primitives@7.62.0.json +30 -0
  290. package/wire-changes/primitives@7.63.0.json +445 -0
  291. package/dist/core/consolidate-scope.d.ts +0 -93
  292. package/dist/core/consolidate-scope.js +0 -98
  293. package/dist/core/credential-vocabulary.d.ts +0 -176
  294. package/dist/core/credential-vocabulary.js +0 -190
  295. package/dist/core/redaction-passes.d.ts +0 -82
  296. package/dist/core/redaction-passes.js +0 -377
  297. package/dist/core/runner/memory-consolidation.d.ts +0 -109
  298. package/dist/core/runner/memory-consolidation.js +0 -251
@@ -667,6 +667,8 @@ export interface ExecutionEnv extends FileSystem, Shell {
667
667
  * re-supply — names and rules, never a value. `[]` = none withheld, or none inherited (a shell environment built
668
668
  * rather than inherited from this process); `"unknown"` = the adapter cannot say. A read: it announces nothing. */
669
669
  readonly withheldEnv: readonly SecretEnvFinding[] | "unknown";
670
+ /** #1726 — the NAMES (never a value) of the environment the shell child receives; omitted ⇒ the adapter cannot say, every name may be there. */
671
+ readonly receivedEnvNames?: readonly string[];
670
672
  }
671
673
  /** Base fields shared by append-only session tree entries. */
672
674
  export interface SessionTreeEntryBase {
@@ -849,6 +851,63 @@ export interface WorkspaceState {
849
851
  export interface WorkspaceStateEntry extends SessionTreeEntryBase, WorkspaceState {
850
852
  type: "workspace_state";
851
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
+ }
852
911
  /** Bounded cap for {@link normalizeReminderMark}: the current scheme's value is 22 chars; the bound
853
912
  * is deliberately looser (an opaque bounded token) so the STORE never learns the scheme — the real
854
913
  * value-shape verify lives in the mint home (core/reminder-mint.ts `isValidReminderMark`), applied
@@ -940,6 +999,14 @@ export declare const WORKSPACE_STATE_MAX_PATH_CHARS = 4096;
940
999
  * undefined when the value is not structurally valid.
941
1000
  */
942
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;
943
1010
  /** Bounded caps for {@link normalizeAnnouncedListing} — a roster is dozens of names, never thousands;
944
1011
  * a "name" is a short identifier, never a document. Oversize ⇒ structurally invalid (forgery signal). */
945
1012
  export declare const ANNOUNCED_LISTING_MAX_NAMES = 500;
@@ -1008,7 +1075,7 @@ export declare function isSyntheticApiErrorMessage(m: unknown): boolean;
1008
1075
  export declare function isOptionalDisplayString(v: unknown, max?: number): boolean;
1009
1076
  export declare function normalizeAnnouncedListing(v: unknown): AnnouncedListingSnapshot | undefined;
1010
1077
  /** All persisted session tree entry variants. */
1011
- 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;
1012
1079
  export interface SessionContext {
1013
1080
  messages: AgentMessage[];
1014
1081
  thinkingLevel: string;
@@ -1096,6 +1163,11 @@ export interface SessionWriteOptions {
1096
1163
  */
1097
1164
  expectedLeafId?: string | null;
1098
1165
  }
1166
+ /** What the replay that loaded a stored log dropped: `dropped` of its `total` records could not be read and are not in the log. */
1167
+ export interface ReplayLoss {
1168
+ readonly dropped: number;
1169
+ readonly total: number;
1170
+ }
1099
1171
  export interface SessionStorage<TMetadata extends SessionMetadata = SessionMetadata> {
1100
1172
  getMetadata(): Promise<TMetadata>;
1101
1173
  getLeafId(): Promise<string | null>;
@@ -1127,6 +1199,10 @@ export interface SessionStorage<TMetadata extends SessionMetadata = SessionMetad
1127
1199
  * from a CORRUPT log (a head whose parent is simply missing); the two look identical byte-wise and
1128
1200
  * must not be treated alike. `BaseSessionStorage` implements it for the bundled backends. */
1129
1201
  getFloorId?(): string | null;
1202
+ /** What the replay that loaded this log dropped, or `undefined` when it dropped nothing (or the backend has no replay to lose from). A run
1203
+ * that continues the session tells the person when it is there. Fixed at the load: a later write does not change it.
1204
+ * `BaseSessionStorage` implements it for the bundled backends. */
1205
+ getReplayLoss?(): ReplayLoss | undefined;
1130
1206
  getEpochAnchor?(): Promise<unknown>;
1131
1207
  }
1132
1208
  /**
@@ -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,11 +1,11 @@
1
1
  /**
2
2
  * The memory of one walk up a session log's parent chain, shared by `getPathToRoot`, the resume-at ancestry scan and the fork-point judge `settledForkOptions` (the import validator still keeps its own loop — #2253). An entry the
3
- * walk stands on twice means the parent links loop, which no ancestry can contain: the walk is refused
4
- * `invalid_session` naming that entry instead of being followed again, and saying what a person can do (start a new session, or fork from an entry the
3
+ * walk stands on twice means the parent links loop, which no ancestry can contain: the stored log does not hold together, so the walk is refused
4
+ * `corrupt_session` naming that entry instead of being followed again, and saying what a person can do (start a new session, or fork from an entry the
5
5
  * loop does not touch). One guard per walk.
6
6
  */
7
7
  export declare class ParentChainGuard {
8
8
  private readonly stepped;
9
- /** Records that the walk now stands on `id`; throws `invalid_session` when it already stood there. */
9
+ /** Records that the walk now stands on `id`; throws `corrupt_session` when it already stood there. */
10
10
  stepOnto(id: string): void;
11
11
  }
@@ -3,7 +3,7 @@ export class ParentChainGuard {
3
3
  stepped = new Set();
4
4
  stepOnto(id) {
5
5
  if (this.stepped.has(id)) {
6
- throw new SessionError("invalid_session", `Entry ${id} is its own ancestor (parent chain cycles at ${id}) — start a new session, or fork from an entry above the loop`);
6
+ throw new SessionError("corrupt_session", `Entry ${id} is its own ancestor (parent chain cycles at ${id}) — start a new session, or fork from an entry above the loop`);
7
7
  }
8
8
  this.stepped.add(id);
9
9
  }
@@ -1,3 +1,5 @@
1
+ import { SessionError, type ReplayLoss } from "../harness/types.js";
2
+ export type { ReplayLoss };
1
3
  /** The fork point a store copies up to: `{}` is the whole log, `{ entryId, position: "at" }` the path from the root down to that entry. It is the answer
2
4
  * `settledForkOptions` gives, and the question `selectForkRows` takes. */
3
5
  export interface ForkPoint {
@@ -10,10 +12,23 @@ export interface ParentLinks<T> {
10
12
  idOf(row: T): string;
11
13
  parentOf(row: T): string | null | undefined;
12
14
  }
15
+ /** The one sentence of a {@link ReplayLoss}, for every refusal and notice that states it. */
16
+ export declare function replayLossText(loss: ReplayLoss): string;
17
+ /**
18
+ * The refusal of a walk that met a parent the log does not hold: `childId` names `missingParentId` as its parent. The stored log does not hold
19
+ * together, so it is `corrupt_session`; it says where it broke, and `replayLoss` — what the replay that loaded the log dropped, when it dropped
20
+ * any — is the evidence that the missing parent may be one of the records the replay could not read.
21
+ */
22
+ export declare class LineageBreak extends SessionError {
23
+ readonly missingParentId: string;
24
+ readonly childId: string;
25
+ readonly replayLoss?: ReplayLoss | undefined;
26
+ constructor(missingParentId: string, childId: string, replayLoss?: ReplayLoss | undefined);
27
+ }
13
28
  /**
14
29
  * The one walk up a log's parent chain: the rows from the root down to `start`, root first. The chain ends at a row with no parent, or at `floorId`
15
- * (a bounded window's root — its parent is not required to exist). A parent the log does not hold is `invalid_session` naming it, a chain that
16
- * returns to a row it already stood on is refused by the shared guard; neither is followed.
30
+ * (a bounded window's root — its parent is not required to exist). A parent the log does not hold is a {@link LineageBreak} naming it, a chain that
31
+ * returns to a row it already stood on is refused by the shared guard — both `corrupt_session`; neither is followed.
17
32
  */
18
33
  export declare function pathToRoot<T>(start: T, links: ParentLinks<T>, floorId?: string | null): T[];
19
34
  /** How a log row is read by `selectForkRows`: its entry id and its parent's (`null` = a root). */
@@ -28,7 +43,7 @@ export interface ForkRowShape<R> {
28
43
  * branches stay behind) and the leaf is that entry. The rows keep their order.
29
44
  *
30
45
  * Refusals are the engine's, word for word: a fork point the log does not hold is `invalid_fork_target`, a parent missing part-way up the path (an empty
31
- * parent id included) or a chain that returns to a row it stood on is `invalid_session` (the sentence `getPathToRoot` gives), and a fork point that
46
+ * parent id included) or a chain that returns to a row it stood on is `corrupt_session` (the sentence `getPathToRoot` gives), and a fork point that
32
47
  * names an entry with a `position` other than `at` is refused `invalid_fork_target` — rows are copied only for the point the judge answers. A point with
33
48
  * no entry id is the whole-log form whatever else it carries, as `getEntriesToFork` reads it.
34
49
  */
@@ -1,5 +1,19 @@
1
1
  import { SessionError } from "../harness/types.js";
2
2
  import { ParentChainGuard } from "./parent-chain-guard.js";
3
+ export function replayLossText(loss) {
4
+ return `${loss.dropped} of ${loss.total} records skipped as corrupt`;
5
+ }
6
+ export class LineageBreak extends SessionError {
7
+ missingParentId;
8
+ childId;
9
+ replayLoss;
10
+ constructor(missingParentId, childId, replayLoss) {
11
+ super("corrupt_session", `Entry ${missingParentId} not found — ${childId} names it as its parent and the log does not hold it${replayLoss !== undefined ? ` (${replayLossText(replayLoss)})` : ""}`);
12
+ this.missingParentId = missingParentId;
13
+ this.childId = childId;
14
+ this.replayLoss = replayLoss;
15
+ }
16
+ }
3
17
  export function pathToRoot(start, links, floorId) {
4
18
  const path = [];
5
19
  const chain = new ParentChainGuard();
@@ -15,7 +29,7 @@ export function pathToRoot(start, links, floorId) {
15
29
  break;
16
30
  const parent = parentId === "" ? undefined : links.read(parentId);
17
31
  if (parent === undefined) {
18
- throw new SessionError("invalid_session", `Entry ${parentId} not found`);
32
+ throw new LineageBreak(parentId, id);
19
33
  }
20
34
  current = parent;
21
35
  }
@@ -1,4 +1,4 @@
1
- import { SessionError, type SessionHead, type SessionLogMark, type SessionMetadata, type SessionRowExpectation, type SessionStorage, type SessionTreeEntry } from "../harness/types.js";
1
+ import { SessionError, type SessionHead, type SessionLogMark, type SessionMetadata, type SessionPlacementRecord, type SessionRowExpectation, type SessionStorage, type SessionTreeEntry } from "../harness/types.js";
2
2
  import type { Session } from "../harness/types.js";
3
3
  export declare function createSessionId(): string;
4
4
  /** The {@link SessionMetadata.incarnation} cell for a write laying a row's metadata down — the bundled repos' ONE mint point.
@@ -52,6 +52,17 @@ export declare function importRowCells(sessionId: string, owner: unknown, existi
52
52
  * there but is neither (a blank string included) cannot be read as anyone's, and reading it as anonymous would admit every
53
53
  * principal — the row is refused as `corrupt_session` instead (a read fault, never an answer). */
54
54
  export declare function readOwnerCell(raw: unknown, sessionId: string): string | null;
55
+ /** The one decoding of a stored {@link SessionMetadata.placement} cell read back by a backend (header line, SQL column): `undefined` is no
56
+ * placement; an object whose `kind` is a placement kind, whose `placedAt` is a finite number and whose `scope`, `handle`, `rootSessionId`
57
+ * and `parentSessionId` are each a string when there is the tuple, answered as stored (a tuple missing a join half is a legal tuple,
58
+ * read by consumers as incomplete; a member this reader does not know is an additive one an older reader tolerates). Anything else —
59
+ * no object, `null` (a backend whose absent cell reads `null` maps it to `undefined` first), a kind outside the set, a member of the
60
+ * wrong form — is neither a placement nor none: the row is refused `corrupt_session`, naming the cell and never the value. */
61
+ export declare function readPlacementCell(raw: unknown, sessionId: string): SessionPlacementRecord | undefined;
62
+ /** The placement cell a write that lays a row down records: `given` (`undefined` is none), its `placedAt` stamped with `now` when it names
63
+ * none, judged by the very judgment {@link readPlacementCell} reads back with — so no row is written that a reader would refuse. A tuple
64
+ * that fails it is refused before anything is written, `config.invalid_argument`, naming the cell and never the value. */
65
+ export declare function placementCellToWrite(given: unknown, sessionId: string, now: number): SessionPlacementRecord | undefined;
55
66
  /** A fork lands on a row OTHER than its source: onto its own id it would mint a new occupant over the source's transcript and erase the lineage that carries the source's records. */
56
67
  export declare function assertForkTarget(sourceId: string, targetId: string | undefined): void;
57
68
  /** A fork row's cells, minted from the SOURCE row as it stands at fork time — the same row the fork copies its history from: the lineage
@@ -2,6 +2,7 @@ import { SessionError, } from "../harness/types.js";
2
2
  import { StoredSession } from "./session.js";
3
3
  import { uuidv7 } from "./uuid.js";
4
4
  import { principalNameFault, principalNameOf } from "../../core/principal-name.js";
5
+ import { receiptRefusal } from "../../core/own-property-receipt.js";
5
6
  import { randomUUID } from "node:crypto";
6
7
  export function createSessionId() {
7
8
  return uuidv7();
@@ -107,6 +108,46 @@ export function readOwnerCell(raw, sessionId) {
107
108
  return name;
108
109
  throw new SessionError("corrupt_session", `session ${sessionId}'s owner cell holds ${notAnOwnerShape(raw)} — neither an owner nor anonymous; refusing to read the row`);
109
110
  }
111
+ const PLACEMENT_KINDS = ["subagent"];
112
+ const PLACEMENT_STRING_MEMBERS = ["scope", "parentSessionId", "rootSessionId", "handle"];
113
+ function isPlacementKind(raw) {
114
+ return PLACEMENT_KINDS.some((kind) => kind === raw);
115
+ }
116
+ function placementFaultSentence(sessionId, fault) {
117
+ const { cell, held, expected } = fault;
118
+ const shape = held === null ? "null" : Array.isArray(held) ? "an array" : held === "" ? "an empty string" : `a ${typeof held}`;
119
+ return `session ${sessionId}'s ${cell} ${held === undefined ? "is not there" : `holds ${shape}`} — ${expected}`;
120
+ }
121
+ function judgePlacementCell(raw) {
122
+ if (raw === undefined)
123
+ return { placement: undefined };
124
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
125
+ return { fault: { cell: "placement cell", held: raw, expected: "a placement is a tuple (an object) or not there at all" } };
126
+ const cell = { ...raw };
127
+ const { kind, placedAt } = cell;
128
+ if (!isPlacementKind(kind))
129
+ return { fault: { cell: "placement.kind", held: kind, expected: `a placement names one of its kinds (${PLACEMENT_KINDS.join(", ")})` } };
130
+ for (const member of PLACEMENT_STRING_MEMBERS) {
131
+ if (cell[member] !== undefined && typeof cell[member] !== "string")
132
+ return { fault: { cell: `placement.${member}`, held: cell[member], expected: "a string when there" } };
133
+ }
134
+ if (typeof placedAt !== "number" || !Number.isFinite(placedAt))
135
+ return { fault: { cell: "placement.placedAt", held: placedAt, expected: "a finite number (epoch ms)" } };
136
+ return { placement: { ...cell, kind, placedAt } };
137
+ }
138
+ export function readPlacementCell(raw, sessionId) {
139
+ const judged = judgePlacementCell(raw);
140
+ if ("fault" in judged)
141
+ throw new SessionError("corrupt_session", `${placementFaultSentence(sessionId, judged.fault)}; refusing to read the row`);
142
+ return judged.placement;
143
+ }
144
+ export function placementCellToWrite(given, sessionId, now) {
145
+ const tuple = typeof given === "object" && given !== null && !Array.isArray(given);
146
+ const judged = judgePlacementCell(tuple ? { ...given, placedAt: given["placedAt"] ?? now } : given);
147
+ if ("fault" in judged)
148
+ throw receiptRefusal(`${placementFaultSentence(sessionId, judged.fault)}; refused before anything was written`);
149
+ return judged.placement;
150
+ }
110
151
  export function assertForkTarget(sourceId, targetId) {
111
152
  if (targetId === sourceId)
112
153
  throw new SessionError("invalid_fork_target", `cannot fork session ${sourceId} onto its own id — fork into a new id`);
@@ -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>;
@@ -1,7 +1,8 @@
1
1
  import { asAgentMessage, createCompactionSummaryMessage, createCustomMessage, } from "../harness/messages.js";
2
- import { SessionError, isSyntheticApiErrorMessage, isValidModelChange, normalizeAnnouncedListing, normalizeCompactionStateCarrier, normalizeGitAnnouncement, normalizeReminderMark, normalizeWorkspaceState } from "../harness/types.js";
2
+ import { SessionError, isSyntheticApiErrorMessage, isValidModelChange, normalizeAnnouncedListing, normalizeCompactionStateCarrier, normalizeGitAnnouncement, normalizeReminderMark, normalizeSessionCheckout, normalizeWorkspaceState } from "../harness/types.js";
3
3
  import { readStoredPromptEpoch } from "../../prompt-assembly/epoch.js";
4
4
  import { budgetInvokedSkillsRetention, readElidedMessages, readRetainedInvokedSkills, readUnsummarizedMessages, renderInvokedSkillsRetention, } from "../compaction/utils.js";
5
+ import { thrownText } from "../../core/thrown-value.js";
5
6
  const RETENTION_CLAMP_DEFAULT_CHARS_PER_TOKEN = 3;
6
7
  const RETENTION_CLAMP_WINDOW_FRACTION = 0.5;
7
8
  export function buildSessionContext(pathEntries, opts) {
@@ -81,7 +82,7 @@ export function buildSessionContext(pathEntries, opts) {
81
82
  }
82
83
  }
83
84
  if (!foundFirstKept) {
84
- throw new SessionError("invalid_session", `Compaction ${compaction.id} firstKeptEntryId (${compaction.firstKeptEntryId}) not found before the compaction entry — session may be corrupt or need migration`);
85
+ throw new SessionError("corrupt_session", `Compaction ${compaction.id} firstKeptEntryId (${compaction.firstKeptEntryId}) not found before the compaction entry — session may be corrupt or need migration`);
85
86
  }
86
87
  for (let i = compactionIdx + 1; i < pathEntries.length; i++) {
87
88
  appendMessage(pathEntries[i]);
@@ -395,3 +396,46 @@ export function gitFrameContextVisible(branch, entryId) {
395
396
  const keptIdx = branch.findIndex((e) => e.id === firstKeptId);
396
397
  return keptIdx !== -1 && frameIdx >= keptIdx;
397
398
  }
399
+ export async function readSessionCheckout(session, sessionId) {
400
+ let entries;
401
+ try {
402
+ entries = await session.getStorage().findEntries("session_checkout");
403
+ }
404
+ catch (err) {
405
+ return { kind: "unreadable", detail: `the session log could not be read (${thrownText(err)})` };
406
+ }
407
+ let allocation;
408
+ const releases = [];
409
+ for (const entry of entries) {
410
+ const shaped = normalizeSessionCheckout(entry);
411
+ if (shaped === undefined) {
412
+ const owner = entry.sessionId;
413
+ if (typeof owner === "string" && owner !== sessionId)
414
+ continue;
415
+ return { kind: "unreadable", detail: `session_checkout entry "${entry.id}" is not a valid checkout record` };
416
+ }
417
+ if (shaped.sessionId !== sessionId)
418
+ continue;
419
+ if (shaped.released === true)
420
+ releases.push(shaped);
421
+ else if (allocation !== undefined)
422
+ return { kind: "unreadable", detail: `the session holds two checkout allocations (${allocation.allocationId}, ${shaped.allocationId})` };
423
+ else
424
+ allocation = shaped;
425
+ }
426
+ if (allocation === undefined)
427
+ return releases.length === 0 ? { kind: "none" } : { kind: "unreadable", detail: "the session holds a checkout release with no allocation" };
428
+ if (releases.some((r) => r.allocationId !== allocation.allocationId))
429
+ return { kind: "unreadable", detail: "a checkout release names another allocation" };
430
+ return { kind: "record", record: releases.length > 0 ? { ...allocation, released: true } : allocation };
431
+ }
432
+ export async function appendSessionCheckout(session, record, observedLeafId) {
433
+ const shaped = normalizeSessionCheckout(record);
434
+ if (shaped === undefined)
435
+ throw new SessionError("invalid_entry", "appendSessionCheckout: the record is not a structurally valid session checkout");
436
+ const storage = session.getStorage();
437
+ const parentId = observedLeafId !== undefined ? observedLeafId : await storage.getLeafId();
438
+ const entry = { type: "session_checkout", id: await storage.createEntryId(), parentId, timestamp: new Date().toISOString(), ...shaped };
439
+ await storage.appendEntry(entry, { expectedLeafId: entry.parentId });
440
+ return entry.id;
441
+ }
@@ -1,4 +1,10 @@
1
1
  import { type LeafEntry, type SessionLogMark, type SessionMetadata, type SessionStorage, type SessionTreeEntry, type SessionWriteOptions } from "../harness/types.js";
2
+ import { type ParentLinks, type ReplayLoss } from "./path-to-root.js";
3
+ /** How a session log's entries link to their parents — one reading for every walk over a storage's entries: an empty parent id reads as "no
4
+ * parent" here, as it always has (#2244 tracks reading it as a refusal). */
5
+ export declare function entryParentLinks(byId: {
6
+ get(id: string): SessionTreeEntry | undefined;
7
+ }): ParentLinks<SessionTreeEntry>;
2
8
  /** Return the effective branch leaf after applying a session tree entry. */
3
9
  export declare function leafIdAfterEntry(entry: SessionTreeEntry): string | null;
4
10
  /** A log's {@link SessionLogMark}: its length and its last entry's id — the one reading of the mark, for the reader that marks a log it
@@ -14,11 +20,25 @@ export declare abstract class BaseSessionStorage<TMetadata extends SessionMetada
14
20
  private readonly labelsById;
15
21
  private leafId;
16
22
  private readonly floorId;
23
+ private readonly replayLoss;
24
+ /**
25
+ * The storage of one loaded log. Its leaf (`leafId`, the leaf after the log's last entry unless the backend states its head) and its floor
26
+ * (`opts.floorEntryId`) must name entries the log holds: a load that does not is a stored log that does not hold together, refused
27
+ * `corrupt_session`. `opts.replayLoss` = what the replay that read the log dropped (absent = it dropped nothing): the refusals of this storage
28
+ * state it, and a walk that breaks at a parent the log does not hold carries it ({@link LineageBreak}).
29
+ */
17
30
  protected constructor(metadata: TMetadata, entries: SessionTreeEntry[], leafId?: string | null, opts?: {
18
31
  floorEntryId?: string | null;
32
+ replayLoss?: ReplayLoss;
19
33
  });
34
+ /** ` (N of M records skipped as corrupt)` when the replay that read this log dropped records, else empty. */
35
+ private lostText;
36
+ /** The log's leaf must name an entry the log holds — at load, and after a leaf entry a write appended (the same stored fact either way). */
37
+ private assertLeafHeld;
20
38
  /** The bounded-window root this storage was woken with, or null for a full-tree load (F3). */
21
39
  getFloorId(): string | null;
40
+ /** What the replay that read this log dropped (`undefined` = it dropped nothing): the account a run that continues the session gives the person. */
41
+ getReplayLoss(): ReplayLoss | undefined;
22
42
  getMetadata(): Promise<TMetadata>;
23
43
  getLeafId(): Promise<string | null>;
24
44
  /** The log's mark ({@link sessionLogMarkOf}) as it stands at this instant, read synchronously: for a repo judging a row and writing it in
@@ -1,6 +1,9 @@
1
1
  import { SessionError, } from "../harness/types.js";
2
- import { pathToRoot } from "./path-to-root.js";
2
+ import { LineageBreak, pathToRoot, replayLossText } from "./path-to-root.js";
3
3
  import { uuidv7 } from "./uuid.js";
4
+ export function entryParentLinks(byId) {
5
+ return { read: (id) => byId.get(id), idOf: (entry) => entry.id, parentOf: (entry) => entry.parentId || null };
6
+ }
4
7
  function updateLabelCache(labelsById, entry) {
5
8
  if (entry.type !== "label") {
6
9
  return;
@@ -49,6 +52,7 @@ export class BaseSessionStorage {
49
52
  labelsById;
50
53
  leafId;
51
54
  floorId;
55
+ replayLoss;
52
56
  constructor(metadata, entries, leafId = resolveLeafId(entries), opts) {
53
57
  this.metadata = metadata;
54
58
  this.entries = entries;
@@ -56,23 +60,31 @@ export class BaseSessionStorage {
56
60
  this.labelsById = buildLabelsById(entries);
57
61
  this.leafId = leafId;
58
62
  this.floorId = opts?.floorEntryId ?? null;
59
- if (this.leafId !== null && !this.byId.has(this.leafId)) {
60
- throw new SessionError("invalid_session", `Entry ${this.leafId} not found`);
61
- }
63
+ this.replayLoss = opts?.replayLoss !== undefined && opts.replayLoss.dropped > 0 ? opts.replayLoss : undefined;
64
+ this.assertLeafHeld();
62
65
  if (this.floorId !== null && !this.byId.has(this.floorId)) {
63
- throw new SessionError("invalid_session", `Floor entry ${this.floorId} not loaded`);
66
+ throw new SessionError("corrupt_session", `Floor entry ${this.floorId} not loaded — the bounded window names a floor the loaded log does not hold${this.lostText()}`);
67
+ }
68
+ }
69
+ lostText() {
70
+ return this.replayLoss !== undefined ? ` (${replayLossText(this.replayLoss)})` : "";
71
+ }
72
+ assertLeafHeld() {
73
+ if (this.leafId !== null && !this.byId.has(this.leafId)) {
74
+ throw new SessionError("corrupt_session", `Entry ${this.leafId} not found — the log's leaf names an entry the log does not hold${this.lostText()}`);
64
75
  }
65
76
  }
66
77
  getFloorId() {
67
78
  return this.floorId;
68
79
  }
80
+ getReplayLoss() {
81
+ return this.replayLoss;
82
+ }
69
83
  async getMetadata() {
70
84
  return this.metadata;
71
85
  }
72
86
  async getLeafId() {
73
- if (this.leafId !== null && !this.byId.has(this.leafId)) {
74
- throw new SessionError("invalid_session", `Entry ${this.leafId} not found`);
75
- }
87
+ this.assertLeafHeld();
76
88
  return this.leafId;
77
89
  }
78
90
  logMarkNow() {
@@ -121,7 +133,14 @@ export class BaseSessionStorage {
121
133
  if (!leaf) {
122
134
  throw new SessionError("not_found", `Entry ${leafId} not found`);
123
135
  }
124
- return pathToRoot(leaf, { read: (id) => this.byId.get(id), idOf: (entry) => entry.id, parentOf: (entry) => entry.parentId || null }, this.floorId);
136
+ try {
137
+ return pathToRoot(leaf, entryParentLinks(this.byId), this.floorId);
138
+ }
139
+ catch (err) {
140
+ if (err instanceof LineageBreak && this.replayLoss !== undefined)
141
+ throw new LineageBreak(err.missingParentId, err.childId, this.replayLoss);
142
+ throw err;
143
+ }
125
144
  }
126
145
  async getEntries() {
127
146
  return [...this.entries];