@sema-agent/core 7.56.0 → 7.58.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 (319) hide show
  1. package/CHANGELOG.md +926 -0
  2. package/LICENSE +1 -1
  3. package/dist/agents/org-delivery-gate.js +3 -4
  4. package/dist/agents/peer-held-queue.d.ts +69 -49
  5. package/dist/agents/peer-held-queue.js +255 -106
  6. package/dist/agents/peer-session-drain.js +63 -43
  7. package/dist/agents/send-message-tool.js +3 -2
  8. package/dist/agents/subagent-steps.js +2 -4
  9. package/dist/agents/subagent.js +8 -8
  10. package/dist/brain/anthropic.js +16 -8
  11. package/dist/brain/open-responses.js +10 -8
  12. package/dist/brain/openai.js +11 -9
  13. package/dist/brain/provider-dialect.d.ts +3 -2
  14. package/dist/brain/provider-dialect.js +2 -2
  15. package/dist/brain/request-params.d.ts +6 -0
  16. package/dist/brain/request-params.js +14 -1
  17. package/dist/brain/route-adjudicator.js +2 -1
  18. package/dist/brain/stream-engine.d.ts +9 -0
  19. package/dist/brain/stream-engine.js +24 -10
  20. package/dist/brain/stream-shared.d.ts +5 -4
  21. package/dist/brain/stream-shared.js +4 -4
  22. package/dist/core/a2a.d.ts +2 -1
  23. package/dist/core/a2a.js +23 -10
  24. package/dist/core/allow-entry.d.ts +5 -11
  25. package/dist/core/allow-entry.js +19 -26
  26. package/dist/core/approval-object.d.ts +21 -5
  27. package/dist/core/approval-object.js +44 -17
  28. package/dist/core/ask-origin.d.ts +23 -4
  29. package/dist/core/ask-origin.js +5 -1
  30. package/dist/core/auto-compaction.d.ts +75 -6
  31. package/dist/core/auto-compaction.js +43 -27
  32. package/dist/core/auto-mode-directive.d.ts +29 -5
  33. package/dist/core/auto-mode-directive.js +38 -8
  34. package/dist/core/background-agent-store.d.ts +6 -2
  35. package/dist/core/background-agent-store.js +1 -1
  36. package/dist/core/checkpoint-requirements.d.ts +13 -1
  37. package/dist/core/checkpoint-requirements.js +4 -0
  38. package/dist/core/checkpoint-store.d.ts +44 -40
  39. package/dist/core/checkpoint-store.js +32 -14
  40. package/dist/core/cross-boundary-taint.js +4 -2
  41. package/dist/core/engine-notice.d.ts +4 -3
  42. package/dist/core/engine-notice.js +6 -0
  43. package/dist/core/file-history-store.d.ts +14 -8
  44. package/dist/core/file-history-store.js +14 -4
  45. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  46. package/dist/core/fs-write-gate-policy.js +7 -3
  47. package/dist/core/gate-fold.js +6 -3
  48. package/dist/core/gate-lanes.js +13 -5
  49. package/dist/core/git-worktree-env.d.ts +53 -11
  50. package/dist/core/git-worktree-env.js +96 -12
  51. package/dist/core/hooks.d.ts +6 -3
  52. package/dist/core/hooks.js +12 -5
  53. package/dist/core/human-input-projection.d.ts +1 -0
  54. package/dist/core/human-input-projection.js +3 -0
  55. package/dist/core/locked-config.d.ts +15 -1
  56. package/dist/core/locked-config.js +38 -2
  57. package/dist/core/mailbox-store.d.ts +62 -1
  58. package/dist/core/mailbox-store.js +59 -0
  59. package/dist/core/mcp-call-meta.d.ts +66 -0
  60. package/dist/core/mcp-call-meta.js +103 -0
  61. package/dist/core/mcp-connection-pool.d.ts +3 -1
  62. package/dist/core/mcp-connection-pool.js +3 -1
  63. package/dist/core/mcp-failure.d.ts +7 -1
  64. package/dist/core/mcp-failure.js +10 -0
  65. package/dist/core/mcp-name-judge.d.ts +46 -0
  66. package/dist/core/mcp-name-judge.js +61 -0
  67. package/dist/core/mcp-probe.d.ts +5 -1
  68. package/dist/core/mcp-probe.js +3 -6
  69. package/dist/core/mcp-server-link.d.ts +5 -2
  70. package/dist/core/mcp-server-spec.d.ts +46 -18
  71. package/dist/core/mcp-server-spec.js +1 -18
  72. package/dist/core/mcp.d.ts +6 -14
  73. package/dist/core/mcp.js +85 -65
  74. package/dist/core/memory-engine/consolidation-driver.js +4 -3
  75. package/dist/core/memory-engine/distiller.js +26 -17
  76. package/dist/core/memory-engine/layout.js +5 -2
  77. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  78. package/dist/core/memory-engine/scope-contract.js +80 -11
  79. package/dist/core/mode-policy.d.ts +8 -5
  80. package/dist/core/mode-policy.js +5 -4
  81. package/dist/core/mods/host.js +1 -1
  82. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  83. package/dist/core/mods/kernel/dispatch.js +10 -8
  84. package/dist/core/mods/kernel/events.d.ts +5 -1
  85. package/dist/core/mods/kernel/events.js +1 -1
  86. package/dist/core/mods/kernel/registration.d.ts +5 -1
  87. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  88. package/dist/core/mods/kernel/site-rules.js +10 -0
  89. package/dist/core/mods/package.d.ts +23 -0
  90. package/dist/core/mods/package.js +118 -0
  91. package/dist/core/mods/stations.d.ts +2 -2
  92. package/dist/core/mods/stations.js +1 -1
  93. package/dist/core/mods/tool-call.d.ts +5 -1
  94. package/dist/core/mods/tool-call.js +12 -3
  95. package/dist/core/park-selfcheck.js +2 -0
  96. package/dist/core/path-guard-rows.d.ts +20 -0
  97. package/dist/core/path-guard-rows.js +11 -0
  98. package/dist/core/peer-seat.d.ts +186 -0
  99. package/dist/core/peer-seat.js +307 -0
  100. package/dist/core/permission-rule-consent.d.ts +5 -3
  101. package/dist/core/permission-rule-consent.js +20 -15
  102. package/dist/core/permission-rule-model.d.ts +43 -2
  103. package/dist/core/permission-rule-model.js +52 -8
  104. package/dist/core/permission-rule-org.js +1 -1
  105. package/dist/core/present-plan-tool.d.ts +10 -1
  106. package/dist/core/present-plan-tool.js +46 -2
  107. package/dist/core/protocol-http-auth.d.ts +56 -31
  108. package/dist/core/protocol-http-auth.js +71 -42
  109. package/dist/core/protocol-naming.d.ts +20 -0
  110. package/dist/core/protocol-naming.js +20 -3
  111. package/dist/core/read-only-shell.d.ts +20 -5
  112. package/dist/core/read-only-shell.js +29 -14
  113. package/dist/core/redaction-marks.d.ts +16 -0
  114. package/dist/core/redaction-marks.js +16 -0
  115. package/dist/core/redaction-passes.js +8 -9
  116. package/dist/core/remote-env.d.ts +37 -1
  117. package/dist/core/remote-env.js +11 -0
  118. package/dist/core/resume-startup-cause.d.ts +24 -2
  119. package/dist/core/resume-startup-cause.js +20 -1
  120. package/dist/core/retention.d.ts +41 -15
  121. package/dist/core/retention.js +59 -12
  122. package/dist/core/rewrite-rejudge.d.ts +37 -0
  123. package/dist/core/rewrite-rejudge.js +40 -0
  124. package/dist/core/roles.js +50 -7
  125. package/dist/core/run-origin.d.ts +40 -0
  126. package/dist/core/run-origin.js +37 -0
  127. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  128. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  129. package/dist/core/runner/compact-session.d.ts +10 -0
  130. package/dist/core/runner/compact-session.js +202 -0
  131. package/dist/core/runner/compaction-call-options.d.ts +2 -2
  132. package/dist/core/runner/compaction-restate.d.ts +15 -6
  133. package/dist/core/runner/compaction-restate.js +28 -2
  134. package/dist/core/runner/compaction-seams.d.ts +21 -1
  135. package/dist/core/runner/compaction-seams.js +11 -8
  136. package/dist/core/runner/contracts.d.ts +36 -21
  137. package/dist/core/runner/derived-route-fallback.d.ts +13 -0
  138. package/dist/core/runner/derived-route-fallback.js +6 -0
  139. package/dist/core/runner/env-capability-census.d.ts +3 -2
  140. package/dist/core/runner/env-capability-census.js +9 -3
  141. package/dist/core/runner/gate-exit.d.ts +18 -4
  142. package/dist/core/runner/gate-exit.js +5 -1
  143. package/dist/core/runner/permission-rule-lanes.d.ts +7 -7
  144. package/dist/core/runner/permission-rule-lanes.js +17 -11
  145. package/dist/core/runner/prepare-acquire-reconcile.d.ts +3 -0
  146. package/dist/core/runner/prepare-acquire-reconcile.js +2 -1
  147. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  148. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  149. package/dist/core/runner/prepare-config-doors.d.ts +14 -5
  150. package/dist/core/runner/prepare-config-doors.js +16 -13
  151. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  152. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  153. package/dist/core/runner/prepare-gate-stations.js +1 -1
  154. package/dist/core/runner/prepare-hands-readface.d.ts +10 -4
  155. package/dist/core/runner/prepare-hands-readface.js +6 -1
  156. package/dist/core/runner/prepare-memory.d.ts +3 -0
  157. package/dist/core/runner/prepare-memory.js +19 -23
  158. package/dist/core/runner/prepare-park-ask.d.ts +2 -0
  159. package/dist/core/runner/prepare-park-ask.js +2 -2
  160. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  161. package/dist/core/runner/prepare-policy-chain.js +4 -6
  162. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  163. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  164. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  165. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  166. package/dist/core/runner/prepare-task.d.ts +4 -1
  167. package/dist/core/runner/prepare-task.js +46 -37
  168. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +13 -0
  169. package/dist/core/runner/prepare-tool-disclosure-mount.js +13 -7
  170. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  171. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  172. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  173. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  174. package/dist/core/runner/resume-admission.js +1 -1
  175. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  176. package/dist/core/runner/rewind-files.d.ts +2 -5
  177. package/dist/core/runner/rewind-files.js +9 -51
  178. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  179. package/dist/core/runner/run-harness-handlers.js +1 -8
  180. package/dist/core/runner/run-identity-wiring.js +1 -0
  181. package/dist/core/runner/run-leg.js +15 -22
  182. package/dist/core/runner/run-notification-lane.d.ts +2 -0
  183. package/dist/core/runner/run-notification-lane.js +5 -2
  184. package/dist/core/runner/run-recovery-lanes.js +3 -4
  185. package/dist/core/runner/run-settle-and-teardown.js +5 -11
  186. package/dist/core/runner/run-terminal-adoption.js +3 -4
  187. package/dist/core/runner/run-turn-boundary.js +3 -5
  188. package/dist/core/runner/runtask.d.ts +8 -1
  189. package/dist/core/runner/runtask.js +28 -34
  190. package/dist/core/runner/send-message-continuation.js +1 -1
  191. package/dist/core/runner/session-verb-doors.d.ts +28 -0
  192. package/dist/core/runner/session-verb-doors.js +48 -0
  193. package/dist/core/runner/session-write-ledger.d.ts +30 -0
  194. package/dist/core/runner/session-write-ledger.js +101 -0
  195. package/dist/core/runner/stream-settle-backstop.js +11 -14
  196. package/dist/core/runner/sub-agent-deny-lists.d.ts +25 -3
  197. package/dist/core/runner/sub-agent-deny-lists.js +21 -10
  198. package/dist/core/runner/teardown-bounded.d.ts +1 -0
  199. package/dist/core/runner/teardown-bounded.js +1 -0
  200. package/dist/core/runner/terminal-account.js +3 -3
  201. package/dist/core/runner/tool-end-body.js +1 -0
  202. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  203. package/dist/core/runner/tool-occurrence.js +2 -1
  204. package/dist/core/runner/write-protection-station.d.ts +8 -2
  205. package/dist/core/runner/write-protection-station.js +2 -0
  206. package/dist/core/runner-deps.d.ts +4 -4
  207. package/dist/core/secret-env.d.ts +4 -0
  208. package/dist/core/secret-env.js +3 -0
  209. package/dist/core/sensitive-path-policy.js +6 -7
  210. package/dist/core/session-log-transfer.d.ts +24 -0
  211. package/dist/core/session-log-transfer.js +166 -0
  212. package/dist/core/session-policy-store.d.ts +7 -2
  213. package/dist/core/session-policy-store.js +1 -1
  214. package/dist/core/session-store.d.ts +84 -19
  215. package/dist/core/session-store.js +162 -24
  216. package/dist/core/session.d.ts +92 -1
  217. package/dist/core/shell-read-silence.js +1 -0
  218. package/dist/core/shell-wrapper-projection.d.ts +1 -1
  219. package/dist/core/steer-replay.d.ts +4 -2
  220. package/dist/core/steer-replay.js +2 -1
  221. package/dist/core/store-contracts/background-agent-store-contract.js +1 -0
  222. package/dist/core/store-contracts/checkpoint-store-contract.js +19 -1
  223. package/dist/core/store-contracts/file-history-store-contract.js +9 -0
  224. package/dist/core/store-contracts/mailbox-store-contract.js +49 -1
  225. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  226. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  227. package/dist/core/store-contracts/session-store-contract.js +236 -2
  228. package/dist/core/task-event.d.ts +68 -8
  229. package/dist/core/task-registry-agent.d.ts +8 -4
  230. package/dist/core/task-registry-agent.js +14 -8
  231. package/dist/core/task-registry-shared.d.ts +36 -6
  232. package/dist/core/task-registry-shared.js +11 -0
  233. package/dist/core/task-registry.d.ts +1 -1
  234. package/dist/core/task-registry.js +1 -1
  235. package/dist/core/task-spec.d.ts +37 -0
  236. package/dist/core/task-stream.d.ts +2 -1
  237. package/dist/core/terminal-cause.d.ts +1 -1
  238. package/dist/core/tool-catalog-entries.d.ts +6 -0
  239. package/dist/core/tool-catalog-entries.js +2 -0
  240. package/dist/core/tool-name-aliases.d.ts +32 -2
  241. package/dist/core/tool-name-aliases.js +23 -0
  242. package/dist/core/tool-name-readings.d.ts +4 -0
  243. package/dist/core/tool-name-readings.js +1 -0
  244. package/dist/core/tool-policy.d.ts +10 -6
  245. package/dist/core/tool-policy.js +4 -7
  246. package/dist/core/tool-result-store.d.ts +17 -10
  247. package/dist/core/tool-result-store.js +3 -1
  248. package/dist/core/trace.d.ts +4 -1
  249. package/dist/core/trace.js +2 -1
  250. package/dist/core/types.d.ts +1 -1
  251. package/dist/core/untrusted-egress.d.ts +18 -0
  252. package/dist/core/untrusted-egress.js +82 -12
  253. package/dist/core/wiring-manifest.d.ts +12 -3
  254. package/dist/core/wiring-manifest.js +4 -3
  255. package/dist/core/workspace-snapshot.d.ts +44 -0
  256. package/dist/core/workspace-snapshot.js +34 -0
  257. package/dist/core/write-protect.d.ts +43 -3
  258. package/dist/core/write-protect.js +43 -16
  259. package/dist/engine/execution-env/node-execution-env.js +15 -11
  260. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  261. package/dist/engine/harness/agent-harness.d.ts +12 -5
  262. package/dist/engine/harness/agent-harness.js +13 -2
  263. package/dist/engine/harness/types.d.ts +48 -7
  264. package/dist/engine/harness/types.js +5 -1
  265. package/dist/engine/llm/types.d.ts +12 -3
  266. package/dist/engine/llm/types.js +1 -1
  267. package/dist/engine/loop/agent-loop.d.ts +1 -4
  268. package/dist/engine/loop/agent-loop.js +26 -4
  269. package/dist/engine/session/import-validate.js +3 -0
  270. package/dist/engine/session/memory-repo.d.ts +17 -9
  271. package/dist/engine/session/memory-repo.js +44 -34
  272. package/dist/engine/session/repo-utils.d.ts +22 -4
  273. package/dist/engine/session/repo-utils.js +49 -1
  274. package/dist/engine/session/storage-base.d.ts +10 -1
  275. package/dist/engine/session/storage-base.js +7 -1
  276. package/dist/index.d.ts +23 -11
  277. package/dist/index.js +15 -6
  278. package/dist/internal/harness-types.d.ts +1 -1
  279. package/dist/internal/harness.d.ts +4 -3
  280. package/dist/internal/harness.js +3 -2
  281. package/dist/stores/file/checkpoint-store.d.ts +0 -4
  282. package/dist/stores/file/checkpoint-store.js +0 -1
  283. package/dist/stores/file/file-history-store.js +12 -4
  284. package/dist/stores/file/index.d.ts +4 -1
  285. package/dist/stores/file/index.js +4 -1
  286. package/dist/stores/file/mailbox-store.d.ts +2 -1
  287. package/dist/stores/file/mailbox-store.js +26 -1
  288. package/dist/stores/file/session-store.d.ts +15 -8
  289. package/dist/stores/file/session-store.js +28 -13
  290. package/dist/tools/fs/bash-readonly-classifier.d.ts +15 -19
  291. package/dist/tools/fs/bash-readonly-classifier.js +5 -10
  292. package/dist/tools/fs/fs-bash.js +10 -3
  293. package/dist/tools/fs/fs-write.d.ts +6 -3
  294. package/dist/tools/fs/fs-write.js +8 -7
  295. package/dist/tools/fs/index.d.ts +3 -0
  296. package/dist/tools/fs/index.js +1 -1
  297. package/dist/tools/fs/pattern-kill-guard.d.ts +3 -2
  298. package/dist/tools/fs/pattern-kill-guard.js +68 -36
  299. package/dist/tools/fs/safety.js +40 -8
  300. package/dist/tools/fs/search.js +6 -24
  301. package/dist/tools/fs/shell-read-check.d.ts +18 -1
  302. package/dist/tools/fs/shell-read-check.js +66 -16
  303. package/dist/tools/fs/shell-read-establish.js +2 -1
  304. package/dist/tools/fs/shell-read-identity.d.ts +12 -9
  305. package/dist/tools/fs/shell-read-identity.js +10 -5
  306. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  307. package/dist/tools/web.js +9 -7
  308. package/dist/tools/worktree.d.ts +42 -15
  309. package/dist/tools/worktree.js +60 -32
  310. package/package.json +4 -2
  311. package/test/export-surface.snapshot.json +141 -3
  312. package/wire-changes/core-stores-sql@7.57.0.json +29 -0
  313. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  314. package/wire-changes/core@7.57.0.json +1487 -0
  315. package/wire-changes/core@7.58.0.json +2188 -0
  316. package/wire-changes/mods-kernel@7.57.0.json +29 -0
  317. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  318. package/wire-changes/primitives@7.57.0.json +245 -0
  319. package/wire-changes/primitives@7.58.0.json +29 -0
@@ -1,6 +1,10 @@
1
- import { InMemorySessionRepo, ParentChainGuard, SessionError, findUnansweredToolBatch, compareOccupants, ownerCell, uuidv7, } from "../internal/harness.js";
1
+ import { InMemorySessionRepo, ParentChainGuard, SessionError, findUnansweredToolBatch, compareOccupants, ownerCell, sessionLogMarkOf, uuidv7, } from "../internal/harness.js";
2
2
  import { isSessionConflict, readSessionListQuery } from "./session.js";
3
+ import { readRetentionDeclaration } from "./retention.js";
3
4
  import { readMember } from "./thrown-value.js";
5
+ import { principalNameFault, principalNameOf } from "./principal-name.js";
6
+ import { receiptRefusal, receiveOwnProperties } from "./own-property-receipt.js";
7
+ import { repoLogTransfer } from "./session-log-transfer.js";
4
8
  const DAY_MS = 24 * 60 * 60 * 1000;
5
9
  import { SESSION_DEFAULT_TTL_DAYS } from "../config/defaults.js";
6
10
  export { SESSION_DEFAULT_TTL_DAYS };
@@ -19,22 +23,28 @@ export function admitSessionPlacement(sessionId, persisted, request, capability)
19
23
  }
20
24
  }
21
25
  export class TtlSessionStore {
22
- retention = "none";
26
+ retention;
23
27
  durability;
24
28
  placements;
25
29
  listPlaced;
26
30
  headOf;
27
31
  repoHead;
32
+ logTransfer;
33
+ delete;
34
+ judgesRows = false;
35
+ beforeRowDelete;
28
36
  repo;
29
37
  entries = new Map();
30
38
  pending = new Map();
31
39
  pendingPlacedDeletes = new Set();
32
40
  releasing = new Map();
41
+ resolutions = new Map();
33
42
  pinned = new Set();
34
43
  defaultTtlMs;
35
44
  evictPolicy;
36
45
  sweepTimer;
37
46
  constructor(opts = {}) {
47
+ this.retention = readRetentionDeclaration("TtlSessionStoreOptions.retention", opts.retention);
38
48
  this.repo = opts.repo ?? new InMemorySessionRepo();
39
49
  const durability = opts.durability ?? (opts.repo === undefined ? "process-local" : undefined);
40
50
  if (durability !== undefined)
@@ -49,9 +59,28 @@ export class TtlSessionStore {
49
59
  }
50
60
  const repoHeadOf = this.repo.headOf;
51
61
  if (typeof repoHeadOf === "function") {
52
- this.repoHead = (sessionId) => repoHeadOf.call(this.repo, sessionId);
53
- this.headOf = this.repoHead;
62
+ const repoHead = (sessionId) => repoHeadOf.call(this.repo, sessionId);
63
+ this.repoHead = repoHead;
64
+ this.headOf = repoHead;
65
+ const { readRow, importEntries } = this.repo;
66
+ if (typeof readRow === "function") {
67
+ this.judgesRows = true;
68
+ this.delete = (sessionId, guard) => this.deleteOwned(sessionId, guard);
69
+ }
70
+ if (typeof readRow === "function" && typeof importEntries === "function") {
71
+ this.logTransfer = repoLogTransfer({
72
+ readRow: (id) => readRow.call(this.repo, id),
73
+ importEntries: (id, owner, entries, options) => importEntries.call(this.repo, id, owner, entries, options),
74
+ holding: (id, work) => this.holdingId(id, () => {
75
+ this.entries.delete(id);
76
+ return work();
77
+ }),
78
+ });
79
+ }
54
80
  }
81
+ const beforeRowDelete = readStoreHooks(opts.hooks);
82
+ if (beforeRowDelete !== undefined)
83
+ this.beforeRowDelete = (sessionId) => Reflect.apply(beforeRowDelete, opts.hooks, [sessionId]);
55
84
  if (opts.sweepIntervalMs !== undefined && opts.sweepIntervalMs > 0) {
56
85
  this.sweepTimer = setInterval(() => this.sweep(), opts.sweepIntervalMs);
57
86
  this.sweepTimer.unref?.();
@@ -60,12 +89,10 @@ export class TtlSessionStore {
60
89
  async acquire(sessionId, opts) {
61
90
  this.sweep();
62
91
  if (sessionId) {
63
- const inflightRelease = this.releasing.get(sessionId);
64
- if (inflightRelease !== undefined)
65
- await inflightRelease;
92
+ await this.settledHolds(sessionId);
66
93
  const existing = this.entries.get(sessionId);
67
94
  if (existing) {
68
- if (await this.cachedViewStands(sessionId, existing)) {
95
+ if ((await this.standingRow(sessionId, existing)) !== undefined) {
69
96
  this.assertPlacementAdmission(sessionId, existing.placement, opts);
70
97
  existing.lastActiveAt = Date.now();
71
98
  return { session: existing.session, sessionId };
@@ -105,11 +132,11 @@ export class TtlSessionStore {
105
132
  return false;
106
133
  return this.repoHead === undefined;
107
134
  }
108
- async cachedViewStands(sessionId, cached) {
135
+ async standingRow(sessionId, cached) {
109
136
  if (this.repoHead === undefined)
110
- return true;
111
- const [shown, row] = await Promise.all([cached.session.getMetadata(), this.repoHead(sessionId)]);
112
- return this.viewStandsFor(shown, row);
137
+ return null;
138
+ const [shown, leaf, row] = await Promise.all([cached.session.getMetadata(), cached.session.getStorage().getLeafId(), this.repoHead(sessionId)]);
139
+ return this.viewStandsFor(shown, row) && row !== undefined && row.leafId === leaf ? row : undefined;
113
140
  }
114
141
  assertPlacementAdmission(sessionId, placement, opts) {
115
142
  const store = this;
@@ -120,6 +147,28 @@ export class TtlSessionStore {
120
147
  });
121
148
  }
122
149
  async openOrCreate(id, requireExisting = false, placement) {
150
+ for (;;) {
151
+ const watch = { overtaken: this.releasing.has(id) };
152
+ const watching = this.resolutions.get(id) ?? new Set();
153
+ watching.add(watch);
154
+ this.resolutions.set(id, watching);
155
+ let session;
156
+ try {
157
+ session = await this.resolveRow(id, requireExisting, placement);
158
+ }
159
+ finally {
160
+ watching.delete(watch);
161
+ if (watching.size === 0 && this.resolutions.get(id) === watching)
162
+ this.resolutions.delete(id);
163
+ }
164
+ if (!watch.overtaken)
165
+ return session;
166
+ if (this.entries.get(id)?.session === session)
167
+ this.entries.delete(id);
168
+ await this.settledHolds(id);
169
+ }
170
+ }
171
+ async resolveRow(id, requireExisting, placement) {
123
172
  try {
124
173
  const session = await this.repo.open({ id, createdAt: "" });
125
174
  const meta = await session.getMetadata();
@@ -234,7 +283,14 @@ export class TtlSessionStore {
234
283
  return;
235
284
  return this.holdingId(sessionId, () => this.releaseRow(sessionId, cached));
236
285
  }
286
+ async settledHolds(sessionId) {
287
+ const held = this.releasing.get(sessionId);
288
+ if (held !== undefined)
289
+ await held;
290
+ }
237
291
  async holdingId(sessionId, work) {
292
+ for (const watch of this.resolutions.get(sessionId) ?? [])
293
+ watch.overtaken = true;
238
294
  const prior = this.releasing.get(sessionId);
239
295
  let settle;
240
296
  const gate = new Promise((r) => (settle = r));
@@ -242,7 +298,7 @@ export class TtlSessionStore {
242
298
  try {
243
299
  if (prior !== undefined)
244
300
  await prior;
245
- await work();
301
+ return await work();
246
302
  }
247
303
  finally {
248
304
  if (this.releasing.get(sessionId) === gate)
@@ -253,17 +309,75 @@ export class TtlSessionStore {
253
309
  async releaseRow(sessionId, cached) {
254
310
  if (cached?.placement !== undefined)
255
311
  this.pendingPlacedDeletes.add(sessionId);
256
- const view = cached !== undefined && (await this.cachedViewStands(sessionId, cached)) ? cached : undefined;
312
+ const standing = cached !== undefined ? await this.standingRow(sessionId, cached) : undefined;
313
+ const view = standing !== undefined ? cached : undefined;
314
+ const judged = view === undefined && this.repoHead !== undefined && this.rowReadMatters(sessionId) ? await this.repoHead(sessionId) : undefined;
257
315
  const placed = view !== undefined ? view.placement !== undefined : await this.rowIsPlaced(sessionId);
258
316
  if (view === undefined && !placed)
259
317
  return;
318
+ if (!placed) {
319
+ await this.deleteRow(await view.session.getMetadata(), this.idleViewExpectation(standing, view));
320
+ return;
321
+ }
260
322
  const meta = view !== undefined ? await view.session.getMetadata() : { id: sessionId, createdAt: "" };
261
- if (!placed)
262
- return this.repo.delete(meta);
323
+ const occupant = view !== undefined ? standing : (judged ?? null);
263
324
  this.pendingPlacedDeletes.add(sessionId);
264
- await this.repo.delete(meta);
325
+ await this.deleteRow(meta, this.judgesRows ? async () => ({ row: occupant }) : undefined);
265
326
  this.pendingPlacedDeletes.delete(sessionId);
266
327
  }
328
+ idleViewExpectation(standing, view) {
329
+ if (!this.judgesRows || standing === null)
330
+ return undefined;
331
+ return async () => ({ row: standing, log: sessionLogMarkOf(await view.session.getStorage().getEntries()) });
332
+ }
333
+ async deleteRow(meta, expect) {
334
+ if (this.beforeRowDelete !== undefined)
335
+ await this.beforeRowDelete(meta.id);
336
+ if (expect === undefined) {
337
+ await this.repo.delete(meta);
338
+ return true;
339
+ }
340
+ try {
341
+ await this.repo.delete(meta, await expect());
342
+ }
343
+ catch (err) {
344
+ if (isSessionConflict(err))
345
+ return false;
346
+ throw err;
347
+ }
348
+ return true;
349
+ }
350
+ async deleteOwned(sessionId, guard) {
351
+ const want = readDeleteGuard(guard);
352
+ return this.holdingId(sessionId, async () => {
353
+ this.entries.delete(sessionId);
354
+ const head = await this.repoHead(sessionId);
355
+ if (head === undefined || head.owner !== want)
356
+ return false;
357
+ if ((await this.readPlacement(sessionId)) !== undefined)
358
+ return false;
359
+ if (!(await this.deleteRow({ id: sessionId, createdAt: "" }, async () => ({ row: head }))))
360
+ return false;
361
+ this.pinned.delete(sessionId);
362
+ return true;
363
+ });
364
+ }
365
+ async rowMetadata(sessionId) {
366
+ try {
367
+ return await (await this.repo.open({ id: sessionId, createdAt: "" })).getMetadata();
368
+ }
369
+ catch (err) {
370
+ if (isNotFound(err))
371
+ return undefined;
372
+ throw err;
373
+ }
374
+ }
375
+ async readPlacement(sessionId) {
376
+ const probe = this.placementProbe();
377
+ if (probe !== undefined)
378
+ return probe(sessionId);
379
+ return (await this.rowMetadata(sessionId))?.placement;
380
+ }
267
381
  placementProbe() {
268
382
  const probe = this.repo.placementOf;
269
383
  return typeof probe === "function" ? probe.bind(this.repo) : undefined;
@@ -274,10 +388,9 @@ export class TtlSessionStore {
274
388
  async rowIsPlaced(sessionId) {
275
389
  if (!this.rowReadMatters(sessionId))
276
390
  return false;
277
- const probe = this.placementProbe();
278
391
  let placement;
279
392
  try {
280
- placement = probe !== undefined ? await probe(sessionId) : (await (await this.repo.open({ id: sessionId, createdAt: "" })).getMetadata()).placement;
393
+ placement = await this.readPlacement(sessionId);
281
394
  }
282
395
  catch (err) {
283
396
  if (!isNotFound(err))
@@ -296,9 +409,7 @@ export class TtlSessionStore {
296
409
  this.pinned.delete(sessionId);
297
410
  }
298
411
  async register(sessionId, owner) {
299
- const inflightRelease = this.releasing.get(sessionId);
300
- if (inflightRelease !== undefined)
301
- await inflightRelease;
412
+ await this.settledHolds(sessionId);
302
413
  if (await this.hasRow(sessionId))
303
414
  return;
304
415
  if (owner === undefined)
@@ -335,8 +446,9 @@ export class TtlSessionStore {
335
446
  this.entries.delete(id);
336
447
  if (this.evictPolicy === "delete" && e.placement === undefined) {
337
448
  void this.holdingId(id, async () => {
338
- if (await this.cachedViewStands(id, e))
339
- await this.repo.delete({ id, createdAt: "" });
449
+ const standing = await this.standingRow(id, e);
450
+ if (standing !== undefined)
451
+ await this.deleteRow({ id, createdAt: "" }, this.idleViewExpectation(standing, e));
340
452
  }).catch(() => { });
341
453
  }
342
454
  }
@@ -379,6 +491,32 @@ function newestFirst(a, b) {
379
491
  return b.lastActiveAt - a.lastActiveAt;
380
492
  return a.sessionId < b.sessionId ? 1 : a.sessionId > b.sessionId ? -1 : 0;
381
493
  }
494
+ function readStoreHooks(hooks) {
495
+ if (hooks === undefined)
496
+ return undefined;
497
+ if (typeof hooks !== "object" || hooks === null)
498
+ throw receiptRefusal(`TtlSessionStoreOptions.hooks must be an object when given, got ${hooks === null ? "null" : typeof hooks}`);
499
+ const got = receiveOwnProperties(hooks, { subject: "TtlSessionStoreOptions.hooks", unit: "hook", moment: "at construction" });
500
+ for (const name of Object.keys(got)) {
501
+ if (name !== "beforeSessionDelete")
502
+ throw receiptRefusal(`TtlSessionStoreOptions.hooks.${name} is not a hook this store runs (it runs beforeSessionDelete)`);
503
+ }
504
+ const hook = got["beforeSessionDelete"];
505
+ if (hook !== undefined && typeof hook !== "function")
506
+ throw receiptRefusal(`TtlSessionStoreOptions.hooks.beforeSessionDelete must be a function when given, got ${hook === null ? "null" : typeof hook}`);
507
+ return hook;
508
+ }
509
+ function readDeleteGuard(guard) {
510
+ if (typeof guard !== "object" || guard === null)
511
+ throw new TypeError(`SessionStore.delete: the guard must be an object { owner }, got ${guard === null ? "null" : typeof guard}`);
512
+ const owner = readMember(guard, "owner");
513
+ if (owner === null)
514
+ return null;
515
+ const name = principalNameOf(owner);
516
+ if (name === undefined)
517
+ throw new TypeError(`SessionStore.delete: guard.owner must be a principal name or null (anonymous), got ${principalNameFault(owner)}`);
518
+ return name;
519
+ }
382
520
  function isNotFound(err) {
383
521
  return readMember(err, "code") === "not_found";
384
522
  }
@@ -8,7 +8,7 @@ export type { SessionWriteOptions } from "../internal/harness.js";
8
8
  import type { Session } from "../internal/harness.js";
9
9
  import type { SessionHead, SessionTreeEntry } from "../internal/harness.js";
10
10
  export type { SessionPlacementRecord } from "../internal/harness.js";
11
- export type { SessionHead } from "../internal/harness.js";
11
+ export type { SessionHead, SessionLogMark, SessionRowExpectation, SessionRowRead } from "../internal/harness.js";
12
12
  /** True when `err` is a session optimistic-lock conflict (a concurrent writer won the branch leaf). Both
13
13
  * halves read what a HOST `SessionStorage` threw, so both are guarded — unreadable is not a conflict,
14
14
  * never a raise inside the classify-and-rethrow guard. The class test is KEPT: widening the verdict to
@@ -340,11 +340,102 @@ export interface SessionStore<S extends SessionStoreSummary = SessionStoreSummar
340
340
  * authorization decision — the caller re-reads {@link headOf} and judges there. The owner lives and dies with its row.
341
341
  */
342
342
  register?(sessionId: string, owner: string | null): Promise<void>;
343
+ /**
344
+ * The storage half of moving a session's log between backends (session-sync): read it out ({@link SessionLogTransfer.listEntryIds},
345
+ * {@link SessionLogTransfer.exportStream}) and replace it whole through a staging the readers never see
346
+ * ({@link SessionLogTransfer.beginReplace}). One write law for every store: a commit onto an existing row keeps that row's occupant and
347
+ * owner and lands only on a row that is already the committer's (compared null-safe; another owner's row is refused `conflict`, a placed
348
+ * row `placement_refused`, nothing written); onto an absent id it creates the row recording the committer and a fresh occupant; every
349
+ * entry passes the engine's import gate ({@link StreamingImportValidator}); and the owner check, the relation the committer judges, the
350
+ * write and the head the commit answers are one step — against every writer of the row, not only this instance's: the commit reads the
351
+ * row once (owner, log and head of one generation), `decide` weighs that log, and the write lands only while the row is still that
352
+ * generation with that log (a write through another instance or the repo since then refuses the commit `conflict`, nothing written);
353
+ * the head answered is the one the write committed (on `"keep"`, the one read). A refusal, or a throw from `decide`, writes nothing.
354
+ * **Optional**: absent = this store does not take part in a cross-backend move.
355
+ */
356
+ readonly logTransfer?: SessionLogTransfer;
357
+ /**
358
+ * Delete a session at its owner's request — the row and its whole log. Only when the row's owner equals `guard.owner` (null-safe:
359
+ * `null` deletes only an anonymous row); a placed row is not deleted here (its deletion is `release`'s, through the joint reap). `true`
360
+ * = this call deleted the row; `false` = there was no row, the guard did not hold, or the row is placed — nothing was deleted, so a
361
+ * repeat is harmless. The id answers nothing afterwards, and a later create under it is a new occupant. A store wired with
362
+ * {@link SessionStoreHooks.beforeSessionDelete} runs it first and deletes nothing when it rejects (the call rejects with it).
363
+ * **Optional**: absent = this store has no owner-guarded delete.
364
+ */
365
+ delete?(sessionId: string, guard: {
366
+ owner: string | null;
367
+ }): Promise<boolean>;
343
368
  /** Number of live/cached sessions (best-effort). */
344
369
  readonly size: number;
345
370
  /** Release resources (timers, connections). Best-effort; must not throw. */
346
371
  dispose(): void | Promise<void>;
347
372
  }
373
+ /** What {@link SessionLogTransfer.exportStream} reads: `afterSeq` resumes after that 0-based position of the oldest-first log (absent
374
+ * = from the first entry; an integer ≥ -1); `batchSize` is how many entries a store reads per page (an integer ≥ 1; absent = the store's
375
+ * own page) — a store holding the log whole reads it once whatever the page, the stream is the same. A bad value is refused. */
376
+ export interface SessionLogExportOptions {
377
+ afterSeq?: number;
378
+ batchSize?: number;
379
+ }
380
+ /** The read and replace halves of {@link SessionStore.logTransfer}. */
381
+ export interface SessionLogTransfer {
382
+ /** The ids of the session's whole log, oldest-first (no compaction floor applied); `null` = no such session. */
383
+ listEntryIds(sessionId: string): Promise<readonly string[] | null>;
384
+ /** The session's whole log, oldest-first, as a stream; `null` = no such session (see {@link SessionLogExportOptions}). */
385
+ exportStream(sessionId: string, opts?: SessionLogExportOptions): Promise<AsyncIterable<SessionTreeEntry> | null>;
386
+ /** Open a staging for a replacement of `sessionId`'s log: entries appended to it are invisible to every reader until its commit.
387
+ * `preserveActorAssertions` is the import gate's trusted-source declaration (see {@link StreamingImportValidator}), read here
388
+ * because the gate reads each batch as it is appended. */
389
+ beginReplace(sessionId: string, opts?: {
390
+ preserveActorAssertions?: boolean;
391
+ }): SessionLogReplace;
392
+ }
393
+ /** What a commit's `decide` sees, inside the commit's one step: the destination's entry ids as they stand now (`null` = no row) and the
394
+ * staged ids, and a read of either side's entries by id. */
395
+ export interface SessionLogCommitView {
396
+ readonly current: readonly string[] | null;
397
+ readonly staged: readonly string[];
398
+ read(side: "current" | "staged", ids: readonly string[]): Promise<SessionTreeEntry[]>;
399
+ }
400
+ /** A commit of a staged replacement. */
401
+ export interface SessionLogCommit {
402
+ /** The committing principal (`null` = anonymous) — the authenticated importer, never a value read from the staged log. */
403
+ owner: string | null;
404
+ /** The committer's judgement of the relation between the two logs, inside the commit's one step: `"replace"` writes the staged log,
405
+ * `"keep"` leaves the destination's log as it is (an identical push); a throw writes nothing and the commit rejects with it. */
406
+ decide(view: SessionLogCommitView): "replace" | "keep" | Promise<"replace" | "keep">;
407
+ }
408
+ /** One staging opened by {@link SessionLogTransfer.beginReplace}. After its commit settles (either way) or its abort, it takes nothing more. */
409
+ export interface SessionLogReplace {
410
+ /** An opaque name of this staging. */
411
+ readonly stagingId: string;
412
+ /** Stage a batch, after the batches before it; each entry passes the import gate here, and a refused batch refuses the staging. */
413
+ append(entries: readonly SessionTreeEntry[]): Promise<void>;
414
+ /** The commit point: the write law of {@link SessionStore.logTransfer}, then `decide`, then the write and the head the row holds
415
+ * after it, in one step. Before it settles, no reader sees the staged log; a refusal, or a throw from `decide`, writes nothing; a row
416
+ * written by anyone else since the commit read it refuses it `conflict` (read the row again and stage again). The first commit call
417
+ * ends the staging, whatever its outcome. */
418
+ commit(input: SessionLogCommit): Promise<{
419
+ outcome: "replaced" | "kept";
420
+ head: SessionHead;
421
+ }>;
422
+ /** Drop the staging; nothing is written. Idempotent. */
423
+ abort(): Promise<void>;
424
+ }
425
+ /**
426
+ * A deployment's hooks on a session store's row deletions — the cleanup of the deployment's own records keyed by session id (a title, a
427
+ * pin, an instruction baseline). `beforeSessionDelete` runs, and is awaited, before every deletion of a row the store makes (an owner's
428
+ * {@link SessionStore.delete}, a placed `release`, an `evict: "delete"` release or idle sweep); when it rejects the row is not deleted and
429
+ * the deletion fails with it — an owner's `delete` or a placed `release` called again runs both again, while an ordinary release has
430
+ * dropped its view and, like any failed ordinary release, has nothing more to delete. The deletion after the hook lands only on the row
431
+ * the store judged (the repo judges it in the step that removes the row — another writer may have deleted the row, created another under
432
+ * the id, or written it while the hook ran); a row that is no longer the one judged is not deleted. The row is still there while the hook
433
+ * runs, so no create under the same id can meet the deployment's records for the occupant being deleted. Called with the id only; it
434
+ * must be idempotent.
435
+ */
436
+ export interface SessionStoreHooks {
437
+ beforeSessionDelete?(sessionId: string): void | Promise<void>;
438
+ }
348
439
  /** Structural detection: does this store expose the optional {@link SessionStore.fork}? Mounts the fork
349
440
  * capability only when true (INERT otherwise — mirrors `hasScheduler`/`hasBackgroundShell`). */
350
441
  export declare function hasSessionFork(store: SessionStore): store is SessionStore & {
@@ -17,6 +17,7 @@ const MEMBER_KINDS = {
17
17
  unestablished: "mark",
18
18
  writesPlaced: "mark",
19
19
  writeProtected: "mark",
20
+ writeProtectedOnDisk: "mark",
20
21
  targetUnresolved: "mark",
21
22
  unplacedOptions: "record",
22
23
  admit: "admission",
@@ -1,6 +1,6 @@
1
1
  import type { ShellWrapperRow } from "./shell-wrapper-table.js";
2
2
  /**
3
- * The PROJECTION {@link import("./shell-wrapper-table.js").SHELL_WRAPPER_TABLE} is: the second lexer's view of the program read model's rows (`program-read-model.ts`
3
+ * The PROJECTION {@link import("./shell-wrapper-table.js").SHELL_WRAPPER_TABLE} is: the tightening reader's peel view of the program read model's rows (`program-read-model.ts`
4
4
  * — one table of program facts, read through the binary gate). A launcher row's options by arity (a value word, a
5
5
  * switch or an attached-only value, a command string), its required operand (a duration, or the spelling it must have),
6
6
  * its bare-dash switch and its `NAME=value` operands; a row that runs its operands, or a code body, as shell input
@@ -3,14 +3,15 @@
3
3
  * steer under its key — the parked queue (`appendPendingSteer`) and the live verb's accepted-input domain — and that
4
4
  * one answer feeds the replay decision, the refusal's machine-readable `detail.differs` and its sentence.
5
5
  *
6
- * Both seats compare the record the CALLER sent (text, trusted, tier, actor) — never the delivered bytes: the live
6
+ * Both seats compare the record the CALLER sent (text, trusted, tier, actor, run origin) — never the delivered bytes: the live
7
7
  * delivery folds `trusted` (the framing) and the actor (the speaker label) into its payload, so comparing payloads
8
8
  * would report one changed facet as two.
9
9
  */
10
10
  import type { ActorAssertion } from "../internal/llm.js";
11
11
  import { type SystemInjectionPriority } from "./task-notification.js";
12
+ import type { RunOrigin } from "./run-origin.js";
12
13
  /** The facets a steer's replay identity is made of, in the order a refusal lists them. Closed. */
13
- export declare const STEER_REPLAY_FACETS: readonly ["text", "trusted", "priority", "actor"];
14
+ export declare const STEER_REPLAY_FACETS: readonly ["text", "trusted", "priority", "actor", "runOrigin"];
14
15
  export type SteerReplayFacet = (typeof STEER_REPLAY_FACETS)[number];
15
16
  /** What a seat remembers a steer by: the caller's own statement, as validated. The parked entry and the live park
16
17
  * record both are this shape. An absent `priority` reads as `"next"` ({@link steerPriorityOf}). */
@@ -19,6 +20,7 @@ export interface SteerReplayRecord {
19
20
  readonly trusted: boolean;
20
21
  readonly priority?: SystemInjectionPriority;
21
22
  readonly actor?: ActorAssertion;
23
+ readonly runOrigin?: RunOrigin;
22
24
  }
23
25
  /** The facets `repeat` differs from `held` in, in {@link STEER_REPLAY_FACETS} order. Empty = the idempotent replay. */
24
26
  export declare function steerReplayDiffers(held: SteerReplayRecord, repeat: SteerReplayRecord): SteerReplayFacet[];
@@ -1,10 +1,11 @@
1
1
  import { steerPriorityOf } from "./task-notification.js";
2
- export const STEER_REPLAY_FACETS = Object.freeze(["text", "trusted", "priority", "actor"]);
2
+ export const STEER_REPLAY_FACETS = Object.freeze(["text", "trusted", "priority", "actor", "runOrigin"]);
3
3
  const FACET_IS_SAME = {
4
4
  text: (a, b) => a.text === b.text,
5
5
  trusted: (a, b) => a.trusted === b.trusted,
6
6
  priority: (a, b) => steerPriorityOf(a) === steerPriorityOf(b),
7
7
  actor: (a, b) => a.actor?.id === b.actor?.id && a.actor?.hostAsserted === b.actor?.hostAsserted && a.actor?.issuer === b.actor?.issuer,
8
+ runOrigin: (a, b) => a.runOrigin === b.runOrigin,
8
9
  };
9
10
  export function steerReplayDiffers(held, repeat) {
10
11
  return STEER_REPLAY_FACETS.filter((facet) => !FACET_IS_SAME[facet](held, repeat));
@@ -9,6 +9,7 @@ function record(over = {}) {
9
9
  owner: "task-1",
10
10
  sessionScoped: false,
11
11
  parentSessionId: "sess-1",
12
+ name: "contract-agent",
12
13
  writerId: "writer-1",
13
14
  spawnedAt: 1_000,
14
15
  updatedAt: 1_000,
@@ -308,7 +308,7 @@ export async function checkpointStoreContract(make, runAssertion, options = {})
308
308
  const stored = (await store.get(bitless.token)).pendingAction;
309
309
  assert.equal("hasBidiControls" in stored, false, "projection backfill must not write back to the row");
310
310
  });
311
- run("the approval object's members: a row's identity + face group and its targets (capabilityId/contractId/shapeDigest/implementationRevision + family/pathTarget/hostTarget/names + targets + engineMounted) survive the round-trip verbatim; an absent group stays absent", async () => {
311
+ run("the approval object's members: a row's identity + face group and its targets (capabilityId/contractId/shapeDigest/implementationRevision + family/pathTarget/hostTarget/names + targets + targetReads + engineMounted) survive the round-trip verbatim; an absent group stays absent", async () => {
312
312
  const store = make();
313
313
  const carried = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "id-carried" });
314
314
  const group = {
@@ -320,6 +320,7 @@ export async function checkpointStoreContract(make, runAssertion, options = {})
320
320
  pathTarget: { param: "destination", aliases: ["path"], access: "create", skillScopeEligible: true },
321
321
  names: ["AcmeWrite", "acme_write"],
322
322
  targets: { protective: "/srv/work/out.txt", declared: "/srv/work/out.txt" },
323
+ targetReads: { ["0123456789abcdef".repeat(4)]: "fedcba9876543210".repeat(4) },
323
324
  engineMounted: true,
324
325
  };
325
326
  Object.assign(carried.pendingAction, group);
@@ -428,6 +429,23 @@ export async function checkpointStoreContract(make, runAssertion, options = {})
428
429
  const bareBack = (await store.get(bare.token));
429
430
  assert.equal("requires" in bareBack || "requirementsDigest" in bareBack, false, "a row without a list or digest must stay without (never [] / null / \"\")");
430
431
  });
432
+ run("run origin: a row's `state.runOrigin` survives the round-trip verbatim and rides the listing; absent stays absent; a word outside the set is kept on the row and reads as absent in the listing", async () => {
433
+ const store = make();
434
+ const member = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ro-member" });
435
+ Object.assign(member.state, { runOrigin: "scheduled" });
436
+ const absent = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ro-absent" });
437
+ const bogus = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "ro-bogus" });
438
+ Object.assign(bogus.state, { runOrigin: "weekly" });
439
+ for (const cp of [member, absent, bogus])
440
+ await store.put(cp.token, cp);
441
+ const byId = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
442
+ assert.equal((await store.get(member.token)).state.runOrigin, "scheduled", "the row's runOrigin must survive the round-trip verbatim");
443
+ assert.equal(byId.get("ro-member")?.runOrigin, "scheduled", "the listing must echo the row's runOrigin");
444
+ assert.equal("runOrigin" in (await store.get(absent.token)).state, false, "an absent runOrigin must stay OMITTED on the row, never a fabricated member");
445
+ assert.equal("runOrigin" in byId.get("ro-absent"), false, "absent must project the key OMITTED, not null / empty");
446
+ assert.equal((await store.get(bogus.token)).state.runOrigin, "weekly", "a word outside the set must be kept on the row verbatim");
447
+ assert.equal("runOrigin" in byId.get("ro-bogus"), false, "a word outside the closed set must read as absent in the listing, never project verbatim");
448
+ });
431
449
  run("decider pair: a policy-decided allow resolves like a person's — its `policy_allowed` record (party `policy`, the attribution) round-trips verbatim on the resolved winner and as the execution record; the same record is already_recorded, a person's record for that row conflicts", async () => {
432
450
  const store = make();
433
451
  const cp = createCheckpointFixture();
@@ -473,9 +473,18 @@ export async function fileHistoryStoreContract(make, runAssertion) {
473
473
  throw Object.assign(new Error("source blob unreadable"), { code: "EACCES" });
474
474
  });
475
475
  assert.equal(thrown.ok, false);
476
+ if (!thrown.ok)
477
+ assert.equal(thrown.error.code, "adopt_failed", "a source whose read throws cannot supply a referenced blob");
476
478
  if (!thrown.ok)
477
479
  assertPermanenceWord(thrown.error, "importHistory whose source fetch threw");
478
480
  assert.equal(await store.canRestore("sc", "b2"), false);
481
+ const wrongBytes = await store.importHistory("sc", missingBlob, async () => new TextEncoder().encode("bytes that are not the content this address names"));
482
+ assert.equal(wrongBytes.ok, false);
483
+ if (!wrongBytes.ok)
484
+ assert.equal(wrongBytes.error.code, "adopt_failed", "a source whose bytes fail their content address cannot supply a referenced blob");
485
+ if (!wrongBytes.ok)
486
+ assertPermanenceWord(wrongBytes.error, "importHistory whose source served the wrong bytes");
487
+ assert.equal(await store.canRestore("sc", "b2"), false);
479
488
  const duplicated = wireEnvelope({
480
489
  formatVersion: "file-history/1",
481
490
  tracked: [
@@ -1,5 +1,5 @@
1
1
  import { strict as assert } from "node:assert";
2
- import { MAILBOX_INVALID_PEER_META_CODE, MAILBOX_TOMBSTONED_RECIPIENT_CODE } from "../mailbox-store.js";
2
+ import { MAILBOX_INVALID_PEER_META_CODE, MAILBOX_INVALID_DECISION_MOVE_CODE, MAILBOX_TOMBSTONED_RECIPIENT_CODE } from "../mailbox-store.js";
3
3
  import { beginContract } from "./contract-harness.js";
4
4
  import { PRINCIPAL_INBOX_HANDLE } from "../../agents/cross-session-ref.js";
5
5
  import { mintCrossPrincipalRecord } from "../../agents/org-delivery-gate.js";
@@ -183,6 +183,54 @@ export async function mailboxStoreContract(mk, runAssertion) {
183
183
  const again = await s.claimLease(S, "a1", "w2", 1_000, 20_000);
184
184
  assert.deepEqual(again.messages[0].peerMeta, { fromMode: "bypass", fromSession: "sess_1" }, "重投的记录必须是原样");
185
185
  });
186
+ run("#972b hold decision:CAS 一胜一负、负者拿到真值;不受租约围栏;每个租约快照都带它", async (make) => {
187
+ const s = make();
188
+ await s.append(S, "a1", msg("m1"));
189
+ await s.append(S, "a1", msg("m2"));
190
+ const held = await s.claimLease(S, "a1", "holder", 60_000, 10_000);
191
+ assert.equal(held.messages[0].decision, undefined, "从未 held 的记录没有 decision");
192
+ assert.deepEqual(await s.moveDecision(S, "a1", 1, undefined, "held"), { ok: true });
193
+ assert.deepEqual(await s.moveDecision(S, "a1", 1, undefined, "held"), { ok: false, current: "held" }, "同一步再走一次:负者拿到当前值");
194
+ assert.deepEqual(await s.moveDecision(S, "a1", 1, "held", "denied"), { ok: true }, "不持租约的一方也能落人的决定");
195
+ assert.deepEqual(await s.moveDecision(S, "a1", 1, "held", "approved"), { ok: false, current: "denied" }, "后到的答复输给先到的决定");
196
+ assert.deepEqual(await s.moveDecision(S, "a1", 2, "held", "approved"), { ok: false, current: "unset" }, "未 held 的记录答 unset");
197
+ const snap = await s.claimLease(S, "a1", "holder", 60_000, 11_000);
198
+ assert.deepEqual(snap.messages.map((m) => [m.seq, m.decision]), [[1, "denied"], [2, undefined]], "租约快照带每条记录的 decision");
199
+ await s.ack(S, "a1", "holder", 1);
200
+ assert.deepEqual(await s.moveDecision(S, "a1", 1, "denied", "denied").catch((e) => e.code), MAILBOX_INVALID_DECISION_MOVE_CODE, "终局不再移动(先于存在性判)");
201
+ assert.deepEqual(await s.moveDecision(S, "a1", 1, "held", "approved"), { ok: false, current: "gone" }, "ack 掉的记录答 gone");
202
+ });
203
+ run("#972b decision 律:只向前走,终局不动;坏词 / 坏 seq / 非法边先于任何副作用被拒(带码)", async (make) => {
204
+ const s = make();
205
+ await s.append(S, "a1", msg("m1"));
206
+ const codeOf = async (p) => {
207
+ try {
208
+ await p;
209
+ return undefined;
210
+ }
211
+ catch (e) {
212
+ return e.code;
213
+ }
214
+ };
215
+ for (const [label, seq, expect, next] of [
216
+ ["unset → approved", 1, undefined, "approved"],
217
+ ["unset → delivered", 1, undefined, "delivered"],
218
+ ["held → held", 1, "held", "held"],
219
+ ["held → dropped", 1, "held", "dropped"],
220
+ ["delivered → denied", 1, "delivered", "denied"],
221
+ ["denied → approved", 1, "denied", "approved"],
222
+ ["unknown word", 1, undefined, "consumed"],
223
+ ["seq 0", 0, undefined, "held"],
224
+ ["seq 1.5", 1.5, undefined, "held"],
225
+ ]) {
226
+ assert.equal(await codeOf(s.moveDecision(S, "a1", seq, expect, next)), MAILBOX_INVALID_DECISION_MOVE_CODE, label);
227
+ }
228
+ const snap = await s.claimLease(S, "a1", "w", 60_000, 10_000);
229
+ assert.equal(snap.messages[0].decision, undefined, "被拒的调用零副作用");
230
+ for (const [from, to] of [[undefined, "held"], ["held", "approved"], ["approved", "delivered"], ["delivered", "dropped"]]) {
231
+ assert.deepEqual(await s.moveDecision(S, "a1", 1, from, to), { ok: true }, `${String(from)} → ${to}`);
232
+ }
233
+ });
186
234
  await settle();
187
235
  }
188
236
  export async function mailboxAckOwnershipContract(mk, runAssertion) {