@sema-agent/core 7.62.0 → 7.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (320) hide show
  1. package/CHANGELOG.md +936 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent-transcript-placement.d.ts +23 -0
  23. package/dist/agents/subagent-transcript-placement.js +14 -0
  24. package/dist/agents/subagent.js +102 -54
  25. package/dist/brain/route-adjudicator.js +9 -4
  26. package/dist/core/allow-entry.d.ts +4 -0
  27. package/dist/core/approval-object.js +1 -1
  28. package/dist/core/arg-summary.js +1 -1
  29. package/dist/core/ask-origin.d.ts +1 -1
  30. package/dist/core/ask-origin.js +2 -2
  31. package/dist/core/ask-question.d.ts +2 -2
  32. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  33. package/dist/core/ask-unresolvable-notice.js +10 -3
  34. package/dist/core/auto-compaction.d.ts +7 -5
  35. package/dist/core/background-agent-store.d.ts +7 -0
  36. package/dist/core/background-agent-store.js +3 -0
  37. package/dist/core/canonical-json.d.ts +23 -13
  38. package/dist/core/canonical-json.js +4 -4
  39. package/dist/core/checkpoint-queries.d.ts +50 -4
  40. package/dist/core/checkpoint-queries.js +42 -17
  41. package/dist/core/checkpoint-requirements.d.ts +3 -3
  42. package/dist/core/checkpoint-requirements.js +2 -1
  43. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  44. package/dist/core/checkpoint-row-verdict.js +22 -2
  45. package/dist/core/checkpoint-store.d.ts +28 -11
  46. package/dist/core/checkpoint-store.js +45 -4
  47. package/dist/core/compliance.d.ts +6 -2
  48. package/dist/core/compliance.js +3 -3
  49. package/dist/core/context-settings.d.ts +40 -9
  50. package/dist/core/context-settings.js +32 -10
  51. package/dist/core/engine-attestation.d.ts +27 -7
  52. package/dist/core/engine-attestation.js +5 -1
  53. package/dist/core/engine-notice.d.ts +43 -5
  54. package/dist/core/extension-requester.d.ts +9 -0
  55. package/dist/core/extension-requester.js +7 -0
  56. package/dist/core/file-history-store.d.ts +28 -0
  57. package/dist/core/file-history-store.js +48 -5
  58. package/dist/core/fs-write-gate-policy.js +1 -1
  59. package/dist/core/gate-fold.js +2 -0
  60. package/dist/core/gate-lanes.js +2 -0
  61. package/dist/core/gate-outcome.d.ts +39 -2
  62. package/dist/core/gate-outcome.js +20 -1
  63. package/dist/core/git-worktree-env.d.ts +62 -3
  64. package/dist/core/git-worktree-env.js +91 -30
  65. package/dist/core/governance-codes.d.ts +9 -3
  66. package/dist/core/governance-codes.js +17 -3
  67. package/dist/core/leg-identity.d.ts +19 -1
  68. package/dist/core/leg-identity.js +12 -0
  69. package/dist/core/mailbox-store.d.ts +39 -4
  70. package/dist/core/mailbox-store.js +14 -2
  71. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  72. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  73. package/dist/core/memory-engine/consolidation.d.ts +74 -10
  74. package/dist/core/memory-engine/consolidation.js +183 -11
  75. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  76. package/dist/core/memory-engine/control-objects.js +151 -0
  77. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  78. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  79. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  80. package/dist/core/memory-engine/data-plane.js +11 -6
  81. package/dist/core/memory-engine/delegation-settlement.d.ts +58 -40
  82. package/dist/core/memory-engine/delegation-settlement.js +270 -85
  83. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  84. package/dist/core/memory-engine/dual-root.js +11 -7
  85. package/dist/core/memory-engine/engine.d.ts +136 -58
  86. package/dist/core/memory-engine/engine.js +491 -394
  87. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  88. package/dist/core/memory-engine/entry-scan.js +3 -0
  89. package/dist/core/memory-engine/file-backend.d.ts +62 -60
  90. package/dist/core/memory-engine/file-backend.js +122 -198
  91. package/dist/core/memory-engine/index.d.ts +8 -7
  92. package/dist/core/memory-engine/index.js +7 -6
  93. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  94. package/dist/core/memory-engine/landing-admission.js +3 -3
  95. package/dist/core/memory-engine/layout.d.ts +127 -46
  96. package/dist/core/memory-engine/layout.js +264 -109
  97. package/dist/core/memory-engine/memory-backend-contract.d.ts +26 -1
  98. package/dist/core/memory-engine/memory-backend-contract.js +476 -0
  99. package/dist/core/memory-engine/memory-deployment.d.ts +42 -11
  100. package/dist/core/memory-engine/memory-deployment.js +54 -15
  101. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  102. package/dist/core/memory-engine/origin-clearance.js +68 -9
  103. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  104. package/dist/core/memory-engine/scope-contract.js +68 -19
  105. package/dist/core/memory-engine/session-write-home.d.ts +37 -2
  106. package/dist/core/memory-engine/session-write-home.js +38 -11
  107. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  108. package/dist/core/memory-engine/sync-client.js +7 -0
  109. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  110. package/dist/core/memory-engine/sync-report.js +6 -2
  111. package/dist/core/memory-engine/tools.d.ts +2 -2
  112. package/dist/core/memory-engine/tools.js +10 -10
  113. package/dist/core/memory-engine/types.d.ts +155 -19
  114. package/dist/core/memory-engine/types.js +2 -0
  115. package/dist/core/memory.js +15 -6
  116. package/dist/core/mode-policy.js +3 -3
  117. package/dist/core/mods/agent-stations.d.ts +18 -0
  118. package/dist/core/mods/agent-stations.js +8 -6
  119. package/dist/core/mods/extension-call.d.ts +4 -0
  120. package/dist/core/mods/extension-call.js +8 -0
  121. package/dist/core/mods/stations.d.ts +20 -1
  122. package/dist/core/mods/stations.js +21 -2
  123. package/dist/core/mods/tool-call.js +3 -4
  124. package/dist/core/parent-spec-seat.d.ts +2 -2
  125. package/dist/core/park-selfcheck.js +2 -2
  126. package/dist/core/pause-registry.d.ts +2 -0
  127. package/dist/core/pause-registry.js +3 -0
  128. package/dist/core/peer-channel.d.ts +5 -0
  129. package/dist/core/permission-rule-consent.d.ts +26 -8
  130. package/dist/core/permission-rule-consent.js +76 -36
  131. package/dist/core/permission-rule-store.d.ts +72 -13
  132. package/dist/core/permission-rule-store.js +29 -8
  133. package/dist/core/read-only-shell.js +3 -2
  134. package/dist/core/redaction-marks.d.ts +8 -0
  135. package/dist/core/redaction-marks.js +6 -0
  136. package/dist/core/refusal-echo.d.ts +20 -0
  137. package/dist/core/refusal-echo.js +33 -0
  138. package/dist/core/remote-env.d.ts +12 -1
  139. package/dist/core/remote-env.js +3 -0
  140. package/dist/core/retention.d.ts +180 -10
  141. package/dist/core/retention.js +45 -0
  142. package/dist/core/retired-keys.d.ts +5 -0
  143. package/dist/core/retired-keys.js +3 -0
  144. package/dist/core/rule-offer-read.d.ts +0 -4
  145. package/dist/core/rule-offer-read.js +2 -18
  146. package/dist/core/runner/child-tree.d.ts +29 -3
  147. package/dist/core/runner/child-tree.js +39 -16
  148. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  149. package/dist/core/runner/classifier-ladder.js +4 -2
  150. package/dist/core/runner/compact-session.js +10 -7
  151. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  152. package/dist/core/runner/compaction-call-options.js +3 -2
  153. package/dist/core/runner/contracts.d.ts +39 -11
  154. package/dist/core/runner/delegation-owner.d.ts +10 -3
  155. package/dist/core/runner/delegation-owner.js +4 -1
  156. package/dist/core/runner/gate-exit.d.ts +6 -0
  157. package/dist/core/runner/gate-exit.js +13 -4
  158. package/dist/core/runner/inherited-ask-grants.js +1 -1
  159. package/dist/core/runner/memory-consolidation-driver.d.ts +10 -5
  160. package/dist/core/runner/memory-consolidation-driver.js +12 -9
  161. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  162. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  163. package/dist/core/runner/person-path-rows.d.ts +8 -3
  164. package/dist/core/runner/person-path-rows.js +5 -1
  165. package/dist/core/runner/placement-fence.d.ts +12 -0
  166. package/dist/core/runner/placement-fence.js +20 -6
  167. package/dist/core/runner/prepare-ask-lane.js +5 -5
  168. package/dist/core/runner/prepare-caps-and-workflow.d.ts +7 -2
  169. package/dist/core/runner/prepare-caps-and-workflow.js +7 -4
  170. package/dist/core/runner/prepare-config-doors.js +4 -0
  171. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  172. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  173. package/dist/core/runner/prepare-execution-env.js +17 -6
  174. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  175. package/dist/core/runner/prepare-gate-stations.js +5 -5
  176. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  177. package/dist/core/runner/prepare-hands-readface.js +5 -4
  178. package/dist/core/runner/prepare-inherited-gate.d.ts +13 -9
  179. package/dist/core/runner/prepare-inherited-gate.js +12 -6
  180. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  181. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  182. package/dist/core/runner/prepare-memory.d.ts +7 -2
  183. package/dist/core/runner/prepare-memory.js +41 -39
  184. package/dist/core/runner/prepare-park-ask.js +4 -3
  185. package/dist/core/runner/prepare-policy-chain.js +7 -7
  186. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  187. package/dist/core/runner/prepare-task.js +26 -18
  188. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  189. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  190. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  191. package/dist/core/runner/resume-admission.d.ts +2 -2
  192. package/dist/core/runner/resume-admission.js +2 -23
  193. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  194. package/dist/core/runner/role-resolution-table.js +62 -0
  195. package/dist/core/runner/run-compaction-machinery.js +2 -2
  196. package/dist/core/runner/run-identity-wiring.js +12 -9
  197. package/dist/core/runner/run-leg.js +9 -5
  198. package/dist/core/runner/run-notification-lane.js +22 -22
  199. package/dist/core/runner/run-recovery-lanes.js +3 -3
  200. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  201. package/dist/core/runner/run-terminal-adoption.js +1 -1
  202. package/dist/core/runner/run-turn-boundary.js +14 -15
  203. package/dist/core/runner/runtask.js +1 -1
  204. package/dist/core/runner/terminal-account.js +1 -1
  205. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  206. package/dist/core/runner/tool-occurrence.js +2 -2
  207. package/dist/core/runner-deps.d.ts +7 -3
  208. package/dist/core/secret-env.d.ts +1 -1
  209. package/dist/core/secret-env.js +4 -4
  210. package/dist/core/session-checkout.d.ts +168 -0
  211. package/dist/core/session-checkout.js +579 -0
  212. package/dist/core/session-store.d.ts +12 -4
  213. package/dist/core/session-store.js +23 -3
  214. package/dist/core/session.d.ts +16 -2
  215. package/dist/core/session.js +3 -0
  216. package/dist/core/shell-read-silence.js +8 -0
  217. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  218. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  219. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  220. package/dist/core/store-contracts/session-store-contract.js +39 -0
  221. package/dist/core/task-event.d.ts +30 -5
  222. package/dist/core/task-notification.d.ts +119 -32
  223. package/dist/core/task-notification.js +186 -100
  224. package/dist/core/task-registry-agent.d.ts +25 -2
  225. package/dist/core/task-registry-agent.js +56 -22
  226. package/dist/core/task-registry-shared.d.ts +33 -11
  227. package/dist/core/task-registry.d.ts +33 -9
  228. package/dist/core/task-registry.js +36 -18
  229. package/dist/core/task-spec-members.js +1 -1
  230. package/dist/core/task-spec.d.ts +27 -2
  231. package/dist/core/tool-errors.d.ts +14 -6
  232. package/dist/core/tool-errors.js +1 -1
  233. package/dist/core/tool-policy.d.ts +32 -13
  234. package/dist/core/tool-policy.js +27 -17
  235. package/dist/core/tool-result-store.d.ts +20 -0
  236. package/dist/core/tool-spec.d.ts +42 -19
  237. package/dist/core/trace.d.ts +3 -2
  238. package/dist/core/types.d.ts +1 -1
  239. package/dist/core/untrusted-egress.d.ts +15 -4
  240. package/dist/core/untrusted-egress.js +23 -22
  241. package/dist/core/workflow-journal-store.d.ts +11 -0
  242. package/dist/core/workflow-journal-store.js +7 -0
  243. package/dist/core/workflow-run-store.d.ts +9 -0
  244. package/dist/core/workflow-run-store.js +6 -0
  245. package/dist/core/workspace-snapshot.d.ts +3 -1
  246. package/dist/core/workspace-snapshot.js +1 -0
  247. package/dist/engine/compaction/compaction.d.ts +2 -1
  248. package/dist/engine/harness/types.d.ts +67 -1
  249. package/dist/engine/harness/types.js +108 -0
  250. package/dist/engine/session/import-validate.js +6 -1
  251. package/dist/engine/session/session.d.ts +30 -1
  252. package/dist/engine/session/session.js +48 -1
  253. package/dist/index.d.ts +12 -7
  254. package/dist/index.js +12 -7
  255. package/dist/internal/harness-types.d.ts +1 -1
  256. package/dist/orchestration/run-workflow-tool.d.ts +8 -1
  257. package/dist/orchestration/run-workflow-tool.js +8 -0
  258. package/dist/orchestration/workflow-types.d.ts +2 -1
  259. package/dist/orchestration/workflow.d.ts +6 -0
  260. package/dist/orchestration/workflow.js +5 -2
  261. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  262. package/dist/stores/file/checkpoint-store.js +4 -1
  263. package/dist/stores/file/file-history-store.d.ts +13 -0
  264. package/dist/stores/file/file-history-store.js +75 -13
  265. package/dist/stores/file/index.d.ts +11 -1
  266. package/dist/stores/file/index.js +7 -11
  267. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  268. package/dist/stores/file/permission-rule-store.js +75 -7
  269. package/dist/stores/file/session-store.js +2 -1
  270. package/dist/stores/file/tool-result-store.d.ts +14 -0
  271. package/dist/stores/file/tool-result-store.js +39 -2
  272. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  273. package/dist/stores/file/workflow-journal-store.js +17 -0
  274. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  275. package/dist/stores/file/workflow-run-store.js +15 -0
  276. package/dist/tools/fs/bash-program-position.js +3 -3
  277. package/dist/tools/fs/program-read-model.d.ts +34 -10
  278. package/dist/tools/fs/program-read-model.js +37 -7
  279. package/dist/tools/fs/program-read-model.rows.js +13 -2
  280. package/dist/tools/fs/read-deny.d.ts +28 -3
  281. package/dist/tools/fs/read-deny.js +18 -2
  282. package/dist/tools/fs/removal-targets.js +3 -3
  283. package/dist/tools/fs/safety.d.ts +2 -0
  284. package/dist/tools/fs/safety.js +1 -1
  285. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  286. package/dist/tools/fs/shell-read-argv.js +34 -29
  287. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  288. package/dist/tools/fs/shell-read-bindings.js +5 -1
  289. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  290. package/dist/tools/fs/shell-read-brace.js +79 -0
  291. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  292. package/dist/tools/fs/shell-read-check.js +16 -14
  293. package/dist/tools/fs/shell-read-establish.js +23 -16
  294. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  295. package/dist/tools/fs/shell-read-judge.js +3 -3
  296. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  297. package/dist/tools/fs/shell-read-plan.js +189 -93
  298. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  299. package/dist/tools/fs/shell-read-start.js +20 -12
  300. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  301. package/dist/tools/fs/shell-read-word.js +9 -5
  302. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  303. package/dist/tools/fs/shell-read-workdir.js +73 -12
  304. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  305. package/dist/tools/worktree.d.ts +3 -2
  306. package/dist/tools/worktree.js +7 -35
  307. package/package.json +3 -2
  308. package/test/export-surface.snapshot.json +135 -11
  309. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  310. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  311. package/wire-changes/core@7.63.0.json +3523 -0
  312. package/wire-changes/core@7.64.0.json +2653 -0
  313. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  314. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  315. package/wire-changes/primitives@7.63.0.json +445 -0
  316. package/wire-changes/primitives@7.64.0.json +30 -0
  317. package/dist/core/credential-vocabulary.d.ts +0 -176
  318. package/dist/core/credential-vocabulary.js +0 -190
  319. package/dist/core/redaction-passes.d.ts +0 -82
  320. package/dist/core/redaction-passes.js +0 -377
@@ -6,9 +6,12 @@ import type { MemoryBackend } from "./types.js";
6
6
  * judgment across stores and the executions it admits run as one critical section. */
7
7
  export declare const MEMORY_DEPLOYMENT_ERASURE_LOCK_DIR = ".memory-erasure-judge";
8
8
  export interface MemoryDeploymentInput {
9
- /** The deployment's backend — the instance given as `RunnerDeps.memoryBackend`. It must own its control
10
- * plane (`controlPlaneRoot`, a non-empty string): a backend without one keeps a session's memory facts in
11
- * per-project control planes no deployment-wide reading can name, and is refused (`config.memory_scope_key`). */
9
+ /** The deployment's backend — the instance given as `RunnerDeps.memoryBackend`. It must publish its own control
10
+ * plane (`controlPlaneRoot`): the scope registry and the capture records a session's memory status reads live
11
+ * there, and a backend without one keeps them in per-project control planes no deployment-wide reading can name —
12
+ * refused (`config.memory_scope_key`). This is the deployment's own question, not consolidation's
13
+ * (`memoryGovernanceDurability`). A backend that carries only `governance` stays refused here: its session accounts
14
+ * ride its store, its scope registry and capture records do not. */
12
15
  backend: MemoryBackend;
13
16
  /** The value given as `RunnerDeps.memoryEngineDir` — a required key, judged as `resolveMemoryScopeStore`
14
17
  * judges it (`undefined` written out reads the Runner's same fallback). */
@@ -35,23 +38,48 @@ export interface MemoryDeploymentStore {
35
38
  type FoldedStatusKey = "captureOptedOut" | "committedCount" | "foldedCount" | "optOutSource" | "lastCaptureAt";
36
39
  /**
37
40
  * A session's memory status across every store of the deployment ({@link MemoryDeployment.sessionMemoryStatus}):
38
- * the session keys folded by {@link foldSessionMemoryStatuses}, plus each store's own answer.
41
+ * the session keys folded by {@link foldSessionMemoryStatuses}, the session's write home, plus each store's own answer.
39
42
  */
40
43
  export interface DeploymentSessionMemoryStatus extends Pick<SessionMemoryStatus, FoldedStatusKey> {
44
+ /** The directory of the session's write home: the `writeHome` of the one `planes[]` row {@link chooseSessionWriteHome}
45
+ * names, handed back unchanged — its contract states when the key is absent. The path is a directory on the engine's
46
+ * disk: a host decides whether it is the caller's to see. */
47
+ writeHome?: string;
41
48
  /** Always present: one row per store of the deployment, in store order (project plane first) — each store's
42
49
  * answer exactly as its engine gave it. The folded keys are read from these rows; a store whose answer made a
43
50
  * folded key absent is the row whose key is absent; a store-bound key (`writeHome`, the directory of the
44
- * session's write home IN that store) is answered here only. A store that could not be opened answers
45
- * `{ optOutSource: "fault" }` (every source unreadable). */
51
+ * session's write home IN that store) is answered here as that store's own value, and the session-level
52
+ * `writeHome` above is one of them. A store that could not be opened answers
53
+ * `{ optOutSource: "fault" }` (every source unreadable). With the host's capture record carrier
54
+ * (`memoryCaptureRecordStore`) the personal plane of a directory-pinned deployment also has a row while its
55
+ * store is not in the set, whenever its engine answers a capture fact for the session — a standing record or a
56
+ * fault (`optOutSource` present): that carrier keeps the record off the mount, where the set cannot see it. */
46
57
  planes: ReadonlyArray<{
47
58
  readonly plane: "project" | "personal";
48
59
  readonly status: SessionMemoryStatus;
49
60
  }>;
50
61
  }
51
62
  export interface MemoryDeployment {
52
- /** The deployment's stores, read at each call: the project plane (the deployment's backend), then — on a
53
- * directory-pinned deployment — the personal plane's store once its mount exists under the engine root
54
- * (opened on first use and kept). A store this face opened for a request stays in the set. */
63
+ /**
64
+ * The deployment's stores, read from the disk at each call: the project plane (the deployment's backend), then —
65
+ * on a directory-pinned deployment — the personal plane's store when a write left a record on its mount (the
66
+ * store opened on first use and kept as an engine instance, never as a reason to stay in the set).
67
+ *
68
+ * @contract memory.deployment.store_set — on a directory-pinned deployment the personal plane's store is in the
69
+ * set exactly when its mount holds a record: a file under `<engine root>/personal/.engine` or
70
+ * `<engine root>/personal/memory` other than the named artifacts an open or a read leaves, matched at that place
71
+ * and by that name only (`*` = any rest of the name): control plane top level, files `root-anchor.json` ·
72
+ * `scopes.json` · `scopes.json.journal` · `.tmp-*`; control plane top level, directories as whole trees
73
+ * `root-anchor.json.lock` · `scopes.json.lock` · `txn.lock` · `root-anchor.json.lock.stale-*` ·
74
+ * `scopes.json.lock.stale-*` · `txn.lock.stale-*`; memory directory top level, files `.casefold-probe-*`. A
75
+ * directory that cannot be read, for any reason but absence (a link that leads nowhere, at it or above it, is no
76
+ * absence), counts as holding one, and so does an anchor, a scope registry or a registry journal that stands there
77
+ * damaged (a link, no regular file, unreadable, not JSON or out of shape). Opening, reading and a refused request
78
+ * add no store, and every deployment object over one engine root answers the same. A store in the set that cannot be
79
+ * opened is not a store of the list: the call throws `ControlPlaneCorruptError` (a bare system error is carried by one
80
+ * that names its errno, the original as its `cause`), and the session status answers that plane
81
+ * `optOutSource: "fault"`.
82
+ */
55
83
  stores(): readonly MemoryDeploymentStore[];
56
84
  /**
57
85
  * Erase across the deployment — the input and the receipt of `MemoryEngine.eraseMemoryEntries`, judged as one
@@ -73,7 +101,10 @@ export interface MemoryDeployment {
73
101
  * order, and their receipts merge into one (`mergeErasureAttestations`: `complete` only when every store's
74
102
  * receipt is; one store ⇒ its receipt as given). A
75
103
  * failure in a later store throws after an earlier store executed: that store keeps its anchor and a replay
76
- * of the same requestId converges every store.
104
+ * of the same requestId converges every store. The thrown error is the refusing store's own (class, code and cause
105
+ * unchanged); its message opens with the sentence that says which stores had executed and how many entries they had
106
+ * erased, and what follows is that store's own sentence about itself — so "nothing was deleted" in it is never read
107
+ * as the request's. A refusal in the first store executed nothing and says only its own sentence.
77
108
  *
78
109
  * @contract memory.erasure.request_per_deployment — an erasure requestId names one request in the whole
79
110
  * deployment: its record is the anchor of the store that executed it, every store is read for that anchor
@@ -105,6 +136,6 @@ export interface MemoryDeployment {
105
136
  */
106
137
  export declare function foldSessionMemoryStatuses(statuses: readonly SessionMemoryStatus[]): Pick<SessionMemoryStatus, FoldedStatusKey>;
107
138
  /** The deployment-wide memory face over `input` (see {@link MemoryDeployment}). Input keys are judged as
108
- * `resolveMemoryScopeStore` judges them; a backend without its own control plane is refused. */
139
+ * `resolveMemoryScopeStore` judges them; a backend whose control-plane state is replica-local is refused. */
109
140
  export declare function createMemoryDeployment(input: MemoryDeploymentInput): MemoryDeployment;
110
141
  export {};
@@ -1,10 +1,11 @@
1
- import { lstatSync } from "node:fs";
2
1
  import { join } from "node:path";
3
2
  import { MemoryEngine } from "./engine.js";
4
3
  import { derivePersonalControlDir, derivePersonalMemoryDir, directoryPinOf, judgeMemoryStoreSeat, memoryPlaneStore, memoryScopePlaneOf, mergeErasureAttestations, refuseMemoryStoreInput } from "./dual-root.js";
5
- import { acquireStoreTxnLock, assertStoreTxnLockOwnership, ControlPlaneCorruptError, renewStoreTxnLock, resolveMemoryEngineRoot, TXN_LOCK_STALE_MS } from "./layout.js";
4
+ import { acquireStoreTxnLock, assertStoreTxnLockOwnership, ControlPlaneCorruptError, renewStoreTxnLock, resolveMemoryEngineRoot, storeHoldsRecord, TXN_LOCK_STALE_MS } from "./layout.js";
6
5
  import { captureErasureInput, erasureRequestInvalid, erasureSelectHash } from "./file-backend.js";
7
6
  import { canonicalExpectedScopes } from "./export-bundle.js";
7
+ import { thrownLabel, thrownText } from "../thrown-value.js";
8
+ import { chooseSessionWriteHome } from "./session-write-home.js";
8
9
  const FACE = "createMemoryDeployment";
9
10
  export const MEMORY_DEPLOYMENT_ERASURE_LOCK_DIR = ".memory-erasure-judge";
10
11
  const STATUS_KEYS_DECIDED = true;
@@ -44,7 +45,7 @@ export function createMemoryDeployment(input) {
44
45
  return typeof root === "string" && root !== "" ? root : undefined;
45
46
  };
46
47
  if (controlOf(backend) === undefined) {
47
- refuseMemoryStoreInput(FACE, "the backend owns no control plane (controlPlaneRoot) — a session's memory facts then live in per-project control planes no deployment-wide reading can name", backend);
48
+ refuseMemoryStoreInput(FACE, "the backend publishes no control plane (controlPlaneRoot) — a session's memory facts then live in per-project control planes no deployment-wide reading can name", backend);
48
49
  }
49
50
  const engineRoot = resolveMemoryEngineRoot(input.memoryEngineDir);
50
51
  const pinned = directoryPinOf(backend) !== undefined;
@@ -60,16 +61,18 @@ export function createMemoryDeployment(input) {
60
61
  };
61
62
  const project = seatOf("project", backend);
62
63
  let personal;
63
- const personalStore = () => (personal ??= seatOf("personal", memoryPlaneStore("personal", backend, engineRoot, onIncident)));
64
- const personalMountExists = () => [derivePersonalMemoryDir(engineRoot), derivePersonalControlDir(engineRoot)].some((p) => {
64
+ const personalStore = () => {
65
+ if (personal !== undefined)
66
+ return personal;
65
67
  try {
66
- return lstatSync(p, { throwIfNoEntry: false }) !== undefined;
68
+ personal = seatOf("personal", memoryPlaneStore("personal", backend, engineRoot, onIncident));
67
69
  }
68
- catch {
69
- return true;
70
+ catch (err) {
71
+ throw personalOpenFault(err, derivePersonalMemoryDir(engineRoot));
70
72
  }
71
- });
72
- const hasPersonalStore = () => pinned && (personal !== undefined || personalMountExists());
73
+ return personal;
74
+ };
75
+ const hasPersonalStore = () => pinned && storeHoldsRecord(derivePersonalMemoryDir(engineRoot), derivePersonalControlDir(engineRoot));
73
76
  const stores = () => (hasPersonalStore() ? [project, personalStore()] : [project]);
74
77
  const storeOfPlane = (plane) => (plane === "personal" && pinned ? personalStore() : project);
75
78
  const planeOf = (scope) => memoryScopePlaneOf(FACE, scope, scopeContract);
@@ -136,9 +139,17 @@ export function createMemoryDeployment(input) {
136
139
  throw coded(`eraseMemoryEntries: requestId ${JSON.stringify(req.requestId)} was first executed ${anchor.selectHash === selectHash ? "in another of this deployment's memory stores" : "with a DIFFERENT selector"} — a requestId names ONE request in the deployment; use a new requestId for a new selector (nothing was deleted, nothing was recorded)`, "memory.erasure_selector_mismatch");
137
140
  }
138
141
  let receipt;
142
+ const executed = [];
139
143
  for (const store of reach) {
140
144
  fence(receipt === undefined ? "before any store executed" : "between two stores' executions");
141
- const part = await store.engine.eraseMemoryEntries(req);
145
+ let part;
146
+ try {
147
+ part = await store.engine.eraseMemoryEntries(req);
148
+ }
149
+ catch (err) {
150
+ throw receipt === undefined ? err : refusedAfterExecuting(err, executed, store.plane, receipt.erased.length);
151
+ }
152
+ executed.push(store.plane);
142
153
  receipt = receipt === undefined ? part : mergeErasureAttestations(receipt, part);
143
154
  }
144
155
  fence("while a store executed");
@@ -152,8 +163,9 @@ export function createMemoryDeployment(input) {
152
163
  }
153
164
  },
154
165
  async sessionMemoryStatus(sessionId) {
155
- const planes = [{ plane: "project", status: await project.engine.sessionMemoryStatus(sessionId) }];
156
- if (hasPersonalStore()) {
166
+ const rows = [{ plane: "project", ...(await project.engine.sessionMemoryStatusRead(sessionId)) }];
167
+ const inSet = hasPersonalStore();
168
+ if (inSet || (pinned && memoryCaptureRecordStore !== undefined)) {
157
169
  let seat;
158
170
  try {
159
171
  seat = personalStore();
@@ -161,12 +173,30 @@ export function createMemoryDeployment(input) {
161
173
  catch {
162
174
  seat = undefined;
163
175
  }
164
- planes.push({ plane: "personal", status: seat !== undefined ? await seat.engine.sessionMemoryStatus(sessionId) : { optOutSource: "fault" } });
176
+ const read = seat !== undefined ? await seat.engine.sessionMemoryStatusRead(sessionId) : { status: { optOutSource: "fault" }, writeHome: { state: "unreadable" } };
177
+ if (inSet || read.status.optOutSource !== undefined)
178
+ rows.push({ plane: "personal", ...read });
165
179
  }
166
- return { ...foldSessionMemoryStatuses(planes.map((p) => p.status)), planes };
180
+ const planes = rows.map(({ plane, status }) => ({ plane, status }));
181
+ const writeHome = chooseSessionWriteHome(rows.map((r) => r.writeHome));
182
+ return { ...foldSessionMemoryStatuses(planes.map((p) => p.status)), ...(writeHome !== undefined ? { writeHome } : {}), planes };
167
183
  },
168
184
  };
169
185
  }
186
+ function refusedAfterExecuting(err, executed, refusing, erased) {
187
+ if (!(err instanceof Error))
188
+ return err;
189
+ const done = executed.map((plane) => `the ${plane} store`).join(" and ");
190
+ const sentence = `eraseMemoryEntries: this request had already executed in ${done} (${erased} ${erased === 1 ? "entry" : "entries"} erased there; each keeps its anchor and a replay of the same requestId converges every store) when the ${refusing} store refused it — what follows describes the refusing store alone: ${err.message}`;
191
+ try {
192
+ const copy = Object.create(Object.getPrototypeOf(err), Object.getOwnPropertyDescriptors(err));
193
+ Object.defineProperty(copy, "message", { value: sentence, writable: true, configurable: true, enumerable: false });
194
+ return copy;
195
+ }
196
+ catch {
197
+ return err;
198
+ }
199
+ }
170
200
  async function anchorOf(store, requestId) {
171
201
  const face = store;
172
202
  if (typeof face.erasureAnchorOf === "function")
@@ -175,6 +205,15 @@ async function anchorOf(store, requestId) {
175
205
  return undefined;
176
206
  throw coded("eraseMemoryEntries: another store of this deployment has an erasure-evidence face but no anchor read (erasureAnchorOf), so whether it already executed this requestId cannot be judged — nothing was deleted", "memory.erasure_evidence_unavailable");
177
207
  }
208
+ const ERRNO_CODE = /^E[A-Z0-9]+$/;
209
+ function personalOpenFault(err, mount) {
210
+ if (err instanceof ControlPlaneCorruptError)
211
+ return err;
212
+ const code = err?.code;
213
+ if (typeof code === "string" && !ERRNO_CODE.test(code))
214
+ return err;
215
+ return new ControlPlaneCorruptError(`the personal plane's memory store at ${mount} could not be opened (${typeof code === "string" ? code : thrownLabel(err)}): ${thrownText(err)}`, { cause: err });
216
+ }
178
217
  function coded(message, code) {
179
218
  const e = new Error(message);
180
219
  e.code = code;
@@ -1,5 +1,8 @@
1
1
  import type { MemoryEntryOrigin } from "./types.js";
2
- export declare const ORIGIN_CLEARANCES_FILE = "origin-clearances.json";
2
+ export declare const ORIGIN_CLEARANCES_FILE: string;
3
+ /** The custody object a clearance's cleared-entry text is kept as (kind `clearance-custody`): named by the row, so the
4
+ * row alone finds it again. */
5
+ export declare function clearanceCustodyName(clearanceId: string): string;
3
6
  /** One clearance's terminal event (appended, never rewritten). */
4
7
  export interface OriginClearanceEvent {
5
8
  eventId: string;
@@ -29,7 +32,9 @@ export interface OriginClearanceRow {
29
32
  status: "pending" | "done" | "failed";
30
33
  /** CUSTODY: the full serialized cleared-entry file text. A crash between the tombstone batch and
31
34
  * the re-record batch leaves this as the only copy — the pending row is the loud recovery seat
32
- * (a later clearEntryOrigin call for the same entry resumes from it). */
35
+ * (a later clearEntryOrigin call for the same entry resumes from it). Kept as the row's custody
36
+ * object ({@link clearanceCustodyName}), never inside the account: the stored row carries the
37
+ * text's sha-256 (`custodyDigest`) and every read answers the text, checked against it. */
33
38
  entryText: string;
34
39
  /** Set the moment THIS clearance's tombstone commits ({@link markOriginClearanceTombstoned}) —
35
40
  * the resume arm's arbiter for an absent entry: with it, absence is the known crash window
@@ -68,7 +73,11 @@ export interface OriginClearanceShadow {
68
73
  requestId: string;
69
74
  settledAt: number;
70
75
  }
71
- /** Lock-free strict read of the whole account (host audit face; journal-aware, corrupt = throw). */
76
+ /** Move every custody text the account still carries inline out into its custody object, under the account's lock;
77
+ * writes nothing when there is none. */
78
+ export declare function moveOriginClearanceCustodyOut(controlDir: string): void;
79
+ /** Lock-free strict read of the whole account (host audit face; journal-aware, corrupt = throw). Each row answers its
80
+ * custody text, wherever the account keeps it. */
72
81
  export declare function readOriginClearances(controlDir: string): OriginClearanceRow[];
73
82
  /**
74
83
  * WRITE-AHEAD open: append the pending row (custody included) before any store mutation. Refuses a
@@ -1,6 +1,57 @@
1
- import { ControlPlaneCorruptError, lockedStrictUpdate, readStrictSidecar } from "./layout.js";
1
+ import { createHash } from "node:crypto";
2
+ import { ControlPlaneCorruptError, fileGovernanceDocOf, lockedStrictUpdate, readStrictSidecar } from "./layout.js";
3
+ import { getFileControlObject, putFileControlObject } from "./control-objects.js";
2
4
  import { MEMORY_ORIGIN_CAUSES } from "./types.js";
3
- export const ORIGIN_CLEARANCES_FILE = "origin-clearances.json";
5
+ const CLEARANCES = fileGovernanceDocOf("origin-clearances");
6
+ export const ORIGIN_CLEARANCES_FILE = CLEARANCES.file;
7
+ export function clearanceCustodyName(clearanceId) {
8
+ return `${clearanceId}.md`;
9
+ }
10
+ function sha256Hex(bytes) {
11
+ return createHash("sha256").update(bytes).digest("hex");
12
+ }
13
+ function custodyTextOf(controlDir, row) {
14
+ if (row.entryText !== undefined)
15
+ return row.entryText;
16
+ const name = clearanceCustodyName(row.clearanceId);
17
+ const bytes = getFileControlObject(controlDir, "clearance-custody", name);
18
+ if (bytes === undefined)
19
+ throw new ControlPlaneCorruptError(`memory origin-clearance ledger: clearance ${JSON.stringify(row.clearanceId)} names custody ${JSON.stringify(name)} that is not there (fail-closed)`);
20
+ if (sha256Hex(bytes) !== row.custodyDigest)
21
+ throw new ControlPlaneCorruptError(`memory origin-clearance ledger: clearance ${JSON.stringify(row.clearanceId)}'s custody does not match the digest its row records (fail-closed)`);
22
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
23
+ }
24
+ function keepCustody(controlDir, clearanceId, text) {
25
+ const bytes = new TextEncoder().encode(text);
26
+ const digest = sha256Hex(bytes);
27
+ const name = clearanceCustodyName(clearanceId);
28
+ if (putFileControlObject(controlDir, "clearance-custody", name, bytes) === "existed") {
29
+ const standing = getFileControlObject(controlDir, "clearance-custody", name);
30
+ if (standing === undefined || sha256Hex(standing) !== digest)
31
+ throw new ControlPlaneCorruptError(`memory origin-clearance ledger: custody ${JSON.stringify(name)} already stands with other bytes — refusing to keep a second text under it (fail-closed)`);
32
+ }
33
+ return digest;
34
+ }
35
+ function moveInlineCustody(controlDir, rec) {
36
+ let moved = false;
37
+ for (const row of rec.rows) {
38
+ if (row.entryText === undefined)
39
+ continue;
40
+ const custodyDigest = keepCustody(controlDir, row.clearanceId, row.entryText);
41
+ const r = row;
42
+ delete r.entryText;
43
+ r.custodyDigest = custodyDigest;
44
+ moved = true;
45
+ }
46
+ return moved;
47
+ }
48
+ function lockedClearanceUpdate(controlDir, fn) {
49
+ lockedStrictUpdate(controlDir, CLEARANCES.file, CLEARANCES.what, coerceClearances, (rec) => {
50
+ const moved = moveInlineCustody(controlDir, rec);
51
+ const out = fn(rec);
52
+ return out.next === undefined && moved ? { next: rec, result: out.result } : out;
53
+ });
54
+ }
4
55
  function reqStr(v) {
5
56
  return typeof v === "string" && v.length > 0;
6
57
  }
@@ -24,6 +75,8 @@ function coerceClearances(raw) {
24
75
  if (rec.version !== 1)
25
76
  throw new ControlPlaneCorruptError(`memory origin-clearance ledger has an unrecognized version (${String(rec.version)}) — refusing (fail-closed)`);
26
77
  for (const r of rec.rows) {
78
+ const custodyInline = typeof r?.entryText === "string" && r.entryText.length > 0 && r.custodyDigest === undefined;
79
+ const custodyKept = r?.entryText === undefined && typeof r?.custodyDigest === "string" && /^[0-9a-f]{64}$/.test(r.custodyDigest);
27
80
  if (typeof r !== "object" ||
28
81
  r === null ||
29
82
  !reqStr(r.clearanceId) ||
@@ -35,8 +88,7 @@ function coerceClearances(raw) {
35
88
  !reqStr(r.reason) ||
36
89
  typeof r.at !== "number" ||
37
90
  !Number.isFinite(r.at) ||
38
- typeof r.entryText !== "string" ||
39
- r.entryText.length === 0 ||
91
+ !(custodyInline || custodyKept) ||
40
92
  (r.tombstonedAt !== undefined && (typeof r.tombstonedAt !== "number" || !Number.isFinite(r.tombstonedAt))) ||
41
93
  (r.status !== "pending" && r.status !== "done" && r.status !== "failed") ||
42
94
  !Array.isArray(r.events)) {
@@ -51,22 +103,29 @@ function coerceClearances(raw) {
51
103
  }
52
104
  return rec;
53
105
  }
106
+ export function moveOriginClearanceCustodyOut(controlDir) {
107
+ lockedClearanceUpdate(controlDir, () => ({ result: undefined }));
108
+ }
54
109
  export function readOriginClearances(controlDir) {
55
- return coerceClearances(readStrictSidecar(controlDir, ORIGIN_CLEARANCES_FILE, "memory origin-clearance ledger")).rows.map((r) => ({ ...r, events: [...r.events] }));
110
+ return coerceClearances(readStrictSidecar(controlDir, CLEARANCES.file, CLEARANCES.what)).rows.map((r) => {
111
+ const { custodyDigest: _digest, entryText: _inline, ...row } = r;
112
+ return { ...row, entryText: custodyTextOf(controlDir, r), events: [...r.events] };
113
+ });
56
114
  }
57
115
  export function openOriginClearance(controlDir, row) {
58
- lockedStrictUpdate(controlDir, ORIGIN_CLEARANCES_FILE, "memory origin-clearance ledger", coerceClearances, (rec) => {
116
+ lockedClearanceUpdate(controlDir, (rec) => {
59
117
  if (rec.rows.some((r) => r.entryId === row.entryId && r.status === "pending")) {
60
118
  const e = new Error(`origin clearance for entry ${JSON.stringify(row.entryId)} is already pending — resume it (call clearEntryOrigin again) instead of opening a second row.`);
61
119
  e.code = "memory.origin_clear_pending";
62
120
  throw e;
63
121
  }
64
- rec.rows.push({ ...row, status: "pending", events: [] });
122
+ const { entryText, ...rest } = row;
123
+ rec.rows.push({ ...rest, custodyDigest: keepCustody(controlDir, row.clearanceId, entryText), status: "pending", events: [] });
65
124
  return { next: rec, result: undefined };
66
125
  });
67
126
  }
68
127
  export function markOriginClearanceTombstoned(controlDir, input) {
69
- lockedStrictUpdate(controlDir, ORIGIN_CLEARANCES_FILE, "memory origin-clearance ledger", coerceClearances, (rec) => {
128
+ lockedClearanceUpdate(controlDir, (rec) => {
70
129
  const r = rec.rows.find((x) => x.clearanceId === input.clearanceId);
71
130
  if (r === undefined || r.status !== "pending" || r.tombstonedAt !== undefined)
72
131
  return { result: undefined };
@@ -75,7 +134,7 @@ export function markOriginClearanceTombstoned(controlDir, input) {
75
134
  });
76
135
  }
77
136
  export function settleOriginClearance(controlDir, input) {
78
- lockedStrictUpdate(controlDir, ORIGIN_CLEARANCES_FILE, "memory origin-clearance ledger", coerceClearances, (rec) => {
137
+ lockedClearanceUpdate(controlDir, (rec) => {
79
138
  const r = rec.rows.find((x) => x.clearanceId === input.clearanceId);
80
139
  if (r === undefined) {
81
140
  const e = new Error(`origin clearance ${JSON.stringify(input.clearanceId)} is unknown`);
@@ -15,12 +15,18 @@ export declare function encodeScopeSegment(raw: string): string;
15
15
  * exactly what the encoder produces — safe chars stay bare (so `%41` for `A` is refused: two
16
16
  * spellings of one identity must not mint two keys), `%XX` sequences must decode as valid UTF-8
17
17
  * (fatal decoder — no U+FFFD smoothing), and the 64-char cap holds here too (parse side enforces
18
- * what the format side promised).
18
+ * what the format side promised). Every refusal carries `config.memory_scope_key`.
19
19
  */
20
20
  export declare function decodeScopeSegment(encoded: string): string;
21
21
  export type ParsedScopeKey = {
22
22
  kind: "user";
23
23
  principal: string;
24
+ }
25
+ /** A principal's layer that never leaves the store it is written in: personal plane, never replicated
26
+ * ({@link isReplicableScope}). */
27
+ | {
28
+ kind: "userlocal";
29
+ principal: string;
24
30
  } | {
25
31
  kind: "org";
26
32
  tenant: string;
@@ -39,14 +45,18 @@ export type ParsedScopeKey = {
39
45
  raw: string;
40
46
  };
41
47
  export declare function formatUserScope(principal: string): string;
48
+ export declare function formatUserLocalScope(principal: string): string;
42
49
  export declare function formatOrgScope(tenant: string): string;
43
50
  export declare function formatProjScope(tenant: string, projectId: string): string;
44
51
  export declare function formatUserProjScope(principal: string, projectId: string): string;
45
52
  /**
46
53
  * Parse a scope key under the v2 contract. A key carrying a recognized prefix MUST be well-formed
47
54
  * (fail-loud — a malformed `proj:` key under an explicit opt-in is a config error, not an opaque
48
- * scope); anything without a recognized prefix parses as `{ kind: "legacy" }` and keeps today's
49
- * opaque behavior. NEVER call this on a deployment that has not opted in (see module header).
55
+ * scope), and so must a key that spells one of the five without carrying it exactly — another case,
56
+ * a full-width colon, surrounding whitespace: the prefixes are reserved, so such a spelling is neither
57
+ * read as the kind it imitates nor left to pass as an opaque scope (`config.memory_scope_key`).
58
+ * Anything else parses as `{ kind: "legacy" }` and keeps today's opaque behavior. NEVER call this on a
59
+ * deployment that has not opted in (see module header).
50
60
  */
51
61
  export declare function parseScopeKey(key: string): ParsedScopeKey;
52
62
  /**
@@ -59,25 +69,56 @@ export declare function parseScopeKey(key: string): ParsedScopeKey;
59
69
  * pattern restated outside core answers a different question and disagrees on exactly those inputs.
60
70
  */
61
71
  export declare function isOrgScopeKey(key: string): boolean;
62
- /** True when a v2-parsed key belongs to a PERSONAL plane (`user:` / `userproj:`). */
72
+ /** True when a v2-parsed key is a principal's own layer (`user:` / `userlocal:` / `userproj:`). */
63
73
  export declare function isPersonalScope(parsed: ParsedScopeKey): boolean;
64
- /** True when the key's AUTHORITY is central (design/142 §2 表: user/userproj/org rows) — these keys
65
- * must never project into an in-repo memory dir (they would leak to every collaborator AND enter
66
- * commit history; extended the F9 gate from personal to org). `proj:`/legacy stay
67
- * repo-planed.
74
+ /** True when the key's layer lives on the PERSONAL plane (the home mount, design/142 §2 表: the
75
+ * user/userproj/org rows, and `userlocal:`) — these keys must never project into an in-repo memory dir (they
76
+ * would leak to every collaborator AND enter commit history; extended the F9 gate from personal to org).
77
+ * `proj:`/legacy stay repo-planed. The plane says where a layer may NOT be projected, not where its
78
+ * authority is: `org:` is owned by the center, `userlocal:` by the store it is written in
79
+ * ({@link isReplicableScope}).
68
80
  *
69
81
  * @contract memory.identity_absence.opaque_key — the memory of an owner with no identity is keyed by an opaque,
70
82
  * unprefixed key the deployment chooses (such as `local`) and never by a sentinel principal: no `user:` key stands for
71
83
  * identity absence (a `user:local` key is the key of a principal named `local`), so this function answers `false`
72
- * for that layer — its authority is not central. The engine mints no key for identity absence. Read as an
84
+ * for that layer — it stays on the project plane. The engine mints no key for identity absence. Read as an
73
85
  * owner, it is the `local-owner` arm of `RuleOwner` (core/rule-owner.ts), not a principal. A principal's memory is
74
86
  * keyed by that principal's keys (`user:<P>` and the principal's project layers); moving this layer to a principal
75
87
  * is a re-keying of its entries (`migrateScope`), and the engine never reads the opaque name as a principal.
76
88
  * Admission authorizes by the caller's principal (`MemoryScopeAdmissionInput`), never by a layer's owner. */
77
- export declare function isCentralAuthorityScope(parsed: ParsedScopeKey): boolean;
89
+ export declare function isPersonalPlaneScope(parsed: ParsedScopeKey): boolean;
90
+ /** Who owns a memory layer, for a question asked of its owner rather than of whoever acts on it: a principal (its own
91
+ * layers), a tenant (the organization's layers), or the deployment itself (an opaque key). */
92
+ export type MemoryScopeOwner = {
93
+ kind: "principal";
94
+ principal: string;
95
+ } | {
96
+ kind: "tenant";
97
+ tenant: string;
98
+ } | {
99
+ kind: "deployment";
100
+ };
101
+ /**
102
+ * THE owner reading of a scope key: `user:` / `userlocal:` / `userproj:` are a principal's own layers, `org:` / `proj:` a
103
+ * tenant's, and an opaque key the deployment's — every key of a session without the v2 contract (where `user:42` is an
104
+ * opaque spelling, never principal `42`), and an unprefixed key under it. Under v2 a malformed reserved key throws
105
+ * `config.memory_scope_key`, as {@link parseScopeKey} does. A kind the switch does not handle is a compile error.
106
+ */
107
+ export declare function memoryScopeOwnerOf(scope: string, scopeContract: "v2" | undefined): MemoryScopeOwner;
108
+ /**
109
+ * THE replication judge: may a sync carry `key`'s entries to another store? Every key may, except the
110
+ * `userlocal:` family — read as the parser reads a key's reserved prefix ({@link reservedPrefixOf}: exactly, else
111
+ * folded — another case, a full-width colon, compatibility letters, surrounding whitespace), well-formed or not,
112
+ * and under any scope contract: the prefix is reserved, so a deployment that never opted in to v2 is
113
+ * answered by the spelling too (the safe direction for a layer its owner keeps off every other store). A key
114
+ * the parser refuses as a `userlocal:` spelling is therefore never replicable: one reading, two askers.
115
+ * `syncMemoryScope` refuses such a scope before any read or request (`config.memory_scope_key`), and
116
+ * `memoryTravelGapOf` reports it `local_only`. A value that is not a string is not a key and throws.
117
+ */
118
+ export declare function isReplicableScope(key: string): boolean;
78
119
  /**
79
120
  * design/142 §7 S1 hard gate (复审 F9): until S1b per-scope physical roots land, ALL scopes of a
80
- * session materialize under ONE root — so a v2 session mixing `user:*`/`userproj:*` keys with an
121
+ * session materialize under ONE root — so a v2 session mixing personal-plane keys ({@link isPersonalPlaneScope}) with an
81
122
  * IN-REPO memory dir would project personal memory into the repo (the exact §2.7 leak shape:
82
123
  * personal notes committed to a shared/open repo). Fail-loud, never fail-open: this throws a
83
124
  * `config.`-coded error the prepare path must NOT swallow.
@@ -49,12 +49,17 @@ function isWellFormedString(s) {
49
49
  return true;
50
50
  }
51
51
  const FATAL_UTF8 = new TextDecoder("utf-8", { fatal: true });
52
+ function scopeKeyRefusal(message) {
53
+ const e = new Error(message);
54
+ e.code = "config.memory_scope_key";
55
+ return e;
56
+ }
52
57
  export function decodeScopeSegment(encoded) {
53
58
  if (encoded.length > SCOPE_SEGMENT_MAX_ENCODED) {
54
- throw new Error(`scope segment exceeds ${SCOPE_SEGMENT_MAX_ENCODED} encoded chars (${encoded.length})`);
59
+ throw scopeKeyRefusal(`scope segment exceeds ${SCOPE_SEGMENT_MAX_ENCODED} encoded chars (${encoded.length})`);
55
60
  }
56
61
  if (!/^(?:[A-Za-z0-9._-]|%[0-9A-F]{2})*$/.test(encoded)) {
57
- throw new Error(`malformed scope segment: ${encoded}`);
62
+ throw scopeKeyRefusal(`malformed scope segment: ${encoded}`);
58
63
  }
59
64
  const bytes = [];
60
65
  for (let i = 0; i < encoded.length; i++) {
@@ -71,16 +76,26 @@ export function decodeScopeSegment(encoded) {
71
76
  decoded = FATAL_UTF8.decode(Uint8Array.from(bytes));
72
77
  }
73
78
  catch {
74
- throw new Error(`malformed scope segment (invalid UTF-8 in %XX sequence): ${encoded}`);
79
+ throw scopeKeyRefusal(`malformed scope segment (invalid UTF-8 in %XX sequence): ${encoded}`);
80
+ }
81
+ let reencoded;
82
+ try {
83
+ reencoded = encodeScopeSegment(decoded);
84
+ }
85
+ catch (e) {
86
+ throw scopeKeyRefusal(`non-canonical scope segment (${thrownText(e)}): ${encoded}`);
75
87
  }
76
- if (encodeScopeSegment(decoded) !== encoded) {
77
- throw new Error(`non-canonical scope segment (re-encode mismatch): ${encoded}`);
88
+ if (reencoded !== encoded) {
89
+ throw scopeKeyRefusal(`non-canonical scope segment (re-encode mismatch): ${encoded}`);
78
90
  }
79
91
  return decoded;
80
92
  }
81
93
  export function formatUserScope(principal) {
82
94
  return `user:${encodeScopeSegment(principal)}`;
83
95
  }
96
+ export function formatUserLocalScope(principal) {
97
+ return `${USERLOCAL_PREFIX}${encodeScopeSegment(principal)}`;
98
+ }
84
99
  export function formatOrgScope(tenant) {
85
100
  return `org:${encodeScopeSegment(tenant)}`;
86
101
  }
@@ -90,13 +105,23 @@ export function formatProjScope(tenant, projectId) {
90
105
  export function formatUserProjScope(principal, projectId) {
91
106
  return `userproj:${encodeScopeSegment(principal)}/${encodeScopeSegment(projectId)}`;
92
107
  }
93
- const ONE_SEGMENT = /^(user|org):((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)$/;
108
+ const USERLOCAL_PREFIX = "userlocal:";
109
+ const ONE_SEGMENT = /^(user|userlocal|org):((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)$/;
94
110
  const TWO_SEGMENT = /^(proj|userproj):((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)\/((?:[A-Za-z0-9._-]|%[0-9A-F]{2})+)$/;
111
+ const RESERVED_PREFIX = /^(user|userlocal|org|proj|userproj):/;
112
+ const foldedSpelling = (key) => String(key).trim().normalize("NFKC").toLowerCase();
113
+ function reservedPrefixOf(key) {
114
+ const exact = RESERVED_PREFIX.exec(key);
115
+ if (exact)
116
+ return { kind: exact[1], exact: true };
117
+ const folded = RESERVED_PREFIX.exec(foldedSpelling(key));
118
+ return folded ? { kind: folded[1], exact: false } : undefined;
119
+ }
95
120
  export function parseScopeKey(key) {
96
121
  const m1 = ONE_SEGMENT.exec(key);
97
122
  if (m1) {
98
123
  const seg = decodeScopeSegment(m1[2]);
99
- return m1[1] === "user" ? { kind: "user", principal: seg } : { kind: "org", tenant: seg };
124
+ return m1[1] === "org" ? { kind: "org", tenant: seg } : { kind: m1[1], principal: seg };
100
125
  }
101
126
  const m2 = TWO_SEGMENT.exec(key);
102
127
  if (m2) {
@@ -104,13 +129,12 @@ export function parseScopeKey(key) {
104
129
  const b = decodeScopeSegment(m2[3]);
105
130
  return m2[1] === "proj" ? { kind: "proj", tenant: a, projectId: b } : { kind: "userproj", principal: a, projectId: b };
106
131
  }
107
- const prefix = /^(user|org|proj|userproj):/.exec(key);
108
- if (prefix) {
109
- const e = new Error(`malformed v2 scope key "${key}": prefix "${prefix[1]}:" is reserved by the scope contract ` +
110
- `(design/142 §1.2) — segments must be encoded with encodeScopeSegment (charset [A-Za-z0-9._-] + %XX), ` +
111
- `"${prefix[1]}" takes ${prefix[1] === "proj" || prefix[1] === "userproj" ? "two segments (a/b)" : "one segment"}.`);
112
- e.code = "config.memory_scope_key";
113
- throw e;
132
+ const reserved = reservedPrefixOf(key);
133
+ if (reserved) {
134
+ throw scopeKeyRefusal(`malformed v2 scope key "${key}": prefix "${reserved.kind}:" is reserved by the scope contract ` +
135
+ `(design/142 §1.2) — ${reserved.exact ? "" : "the key spells it with another case, a full-width colon or surrounding whitespace; the prefix is matched exactly, never folded to its kind — "}` +
136
+ `segments must be encoded with encodeScopeSegment (charset [A-Za-z0-9._-] + %XX), ` +
137
+ `"${reserved.kind}" takes ${reserved.kind === "proj" || reserved.kind === "userproj" ? "two segments (a/b)" : "one segment"}.`);
114
138
  }
115
139
  return { kind: "legacy", raw: key };
116
140
  }
@@ -123,24 +147,49 @@ export function isOrgScopeKey(key) {
123
147
  }
124
148
  }
125
149
  export function isPersonalScope(parsed) {
126
- return parsed.kind === "user" || parsed.kind === "userproj";
150
+ return parsed.kind === "user" || parsed.kind === "userlocal" || parsed.kind === "userproj";
127
151
  }
128
- export function isCentralAuthorityScope(parsed) {
152
+ export function isPersonalPlaneScope(parsed) {
129
153
  return isPersonalScope(parsed) || parsed.kind === "org";
130
154
  }
155
+ export function memoryScopeOwnerOf(scope, scopeContract) {
156
+ if (scopeContract !== "v2")
157
+ return { kind: "deployment" };
158
+ const parsed = parseScopeKey(scope);
159
+ switch (parsed.kind) {
160
+ case "user":
161
+ case "userlocal":
162
+ case "userproj":
163
+ return { kind: "principal", principal: parsed.principal };
164
+ case "org":
165
+ case "proj":
166
+ return { kind: "tenant", tenant: parsed.tenant };
167
+ case "legacy":
168
+ return { kind: "deployment" };
169
+ default: {
170
+ const unhandled = parsed;
171
+ return unhandled;
172
+ }
173
+ }
174
+ }
175
+ export function isReplicableScope(key) {
176
+ if (typeof key !== "string")
177
+ throw new TypeError(`isReplicableScope: a scope key is a string (got ${key === null ? "null" : typeof key})`);
178
+ return reservedPrefixOf(key)?.kind !== "userlocal";
179
+ }
131
180
  export function assertScopeContractPlacement(args) {
132
181
  if (!args.repoRoot)
133
182
  return;
134
- const personal = args.parsedScopes.filter(isCentralAuthorityScope);
183
+ const personal = args.parsedScopes.filter(isPersonalPlaneScope);
135
184
  if (personal.length === 0)
136
185
  return;
137
186
  const rootSegs = pathSegmentsDualFamily(canonicalize(resolve(args.repoRoot))).map(foldPathCase);
138
187
  const dirSegs = pathSegmentsDualFamily(canonicalize(resolve(args.memoryDir))).map(foldPathCase);
139
188
  if (rootSegs.length <= dirSegs.length && rootSegs.every((s, i) => s === dirSegs[i])) {
140
- const e = new Error(`memory scope contract v2: central-authority scope(s) ${personal
189
+ const e = new Error(`memory scope contract v2: personal-plane scope(s) ${personal
141
190
  .map((p) => `"${p.kind}"`)
142
191
  .join(", ")} cannot materialize into an IN-REPO memory dir (${args.memoryDir}) — ` +
143
- `a user/userproj/org layer projected under the repo root would leak non-repo memory to every ` +
192
+ `a user/userlocal/userproj/org layer projected under the repo root would leak non-repo memory to every ` +
144
193
  `collaborator (and into commit history). Move the memory dir out of the repo, or drop those scopes.`);
145
194
  e.code = "config.memory_scope_placement";
146
195
  throw e;