@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
@@ -1,7 +1,8 @@
1
- import { existsSync, readdirSync, renameSync } from "node:fs";
1
+ import { existsSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { uuidv7 } from "../../engine/session/uuid.js";
4
- import { atomicWriteFileSync, lockedStrictUpdate, readStrictSidecar, ControlPlaneCorruptError, ensureDirExists } from "./layout.js";
4
+ import { atomicWriteFileSync, fileGovernanceDocOf, lockedStrictUpdate, readStrictSidecar, ControlPlaneCorruptError, ensureDirExists } from "./layout.js";
5
+ import { deleteFileControlObject, getFileControlObject, listFileControlObjects, moveFileControlObject, putFileControlObject } from "./control-objects.js";
5
6
  import { thrownText } from "../thrown-value.js";
6
7
  import { optionKeys, receiveMembers } from "../own-property-receipt.js";
7
8
  export function deriveSupersededSet(headers, opts = {}) {
@@ -58,7 +59,7 @@ function coded(message, code) {
58
59
  e.code = code;
59
60
  return e;
60
61
  }
61
- export function screenConsolidationOptions(given, provenance) {
62
+ export function screenConsolidationOptions(given, provenance, durability) {
62
63
  if (provenance === "off") {
63
64
  throw coded(`MemoryEngineOptions.consolidation cannot be enabled under provenance: "off" — the consolidation fold law must be able to mint origin markers (a marked input's product would otherwise commit unmarked). Enable provenance "carry" or remove the consolidation options.`, "config.memory_consolidation_provenance_off");
64
65
  }
@@ -98,12 +99,23 @@ export function screenConsolidationOptions(given, provenance) {
98
99
  if (raw.lease !== undefined && typeof raw.lease.acquire !== "function") {
99
100
  throw coded(`MemoryEngineOptions.consolidation.lease.acquire must be a function.`, "config.memory_consolidation");
100
101
  }
102
+ if (screened.multiNode && durability === "replica-local") {
103
+ throw coded(`MemoryEngineOptions.consolidation.multiNode declared over a backend whose consolidation state is replica-local (memoryGovernanceDurability) — the challenge, settlement and lineage ledgers and the capture opt-out records a consolidation's eligibility reads stay in this replica's control plane, so another replica would consolidate entries this one excludes. Run consolidation on one node (remove the multiNode declaration) or use a backend whose state rides it.`, "config.memory_consolidation_replica_local");
104
+ }
101
105
  return screened;
102
106
  }
107
+ export const MEMORY_CHALLENGED_ENTRY_GUIDANCE = "If the fact is still needed, verify it with the user, record a fresh entry from their current statement, and delete the old entry.";
108
+ function fuseAllowance(n, ratio, floor) {
109
+ return Math.max(floor, Math.floor(ratio * n));
110
+ }
103
111
  export function supersessionFuseCeiling(activeSetSize, opts) {
104
112
  if (activeSetSize <= 1)
105
113
  return 0;
106
- return Math.min(activeSetSize - 1, Math.max(opts.supersedeAbsoluteFloor, Math.floor(opts.supersedeRatioCap * activeSetSize)));
114
+ return Math.min(activeSetSize - 1, fuseAllowance(activeSetSize, opts.supersedeRatioCap, opts.supersedeAbsoluteFloor));
115
+ }
116
+ export const DELETION_FUSE_FLOOR = 3;
117
+ export function deletionFuseCeiling(materialized, ratio) {
118
+ return fuseAllowance(materialized, ratio, DELETION_FUSE_FLOOR);
107
119
  }
108
120
  export function scanRefusalCeiling(submittedProducts, opts) {
109
121
  if (submittedProducts <= 0)
@@ -161,11 +173,11 @@ export function recommendationUnconsumed(row) {
161
173
  export function sessionsSinceExcludingCurrent(row) {
162
174
  return Math.max(0, (row?.sessions.count ?? 0) - 1);
163
175
  }
164
- export function recordConsolidationSession(controlDir, scope, sessionId, opts, now) {
165
- return updateConsolidationGate(controlDir, (file) => {
176
+ export function recordConsolidationSession(store, scope, sessionId, opts, now) {
177
+ return store.transact([], (file) => {
166
178
  const row = file.scopes[scope] ?? freshRow();
167
179
  if (row.sessions.ring.includes(sessionId)) {
168
- return { result: { recommended: false, sessionsSince: sessionsSinceExcludingCurrent(row) } };
180
+ return { writeGate: false, result: { recommended: false, sessionsSince: sessionsSinceExcludingCurrent(row) } };
169
181
  }
170
182
  row.sessions.count += 1;
171
183
  row.sessions.ring.push(sessionId);
@@ -182,17 +194,17 @@ export function recordConsolidationSession(controlDir, scope, sessionId, opts, n
182
194
  row.lastRecommendedAt = at;
183
195
  }
184
196
  file.scopes[scope] = row;
185
- return { next: file, result: { recommended, sessionsSince: banked } };
197
+ return { writeGate: true, result: { recommended, sessionsSince: banked } };
186
198
  });
187
199
  }
188
- export function recordActiveSetBaseline(controlDir, scope, size, ratioCap, _now) {
189
- return updateConsolidationGate(controlDir, (file) => {
200
+ export function recordActiveSetBaseline(store, scope, size, ratioCap) {
201
+ return store.transact([], (file) => {
190
202
  const row = file.scopes[scope] ?? freshRow();
191
203
  const prev = row.activeSetBaseline;
192
204
  row.activeSetBaseline = size;
193
205
  file.scopes[scope] = row;
194
206
  const collapsed = prev !== undefined && prev > 0 && size < prev && (prev - size) / prev > ratioCap ? { from: prev, to: size } : undefined;
195
- return { next: file, result: collapsed !== undefined ? { collapsed } : {} };
207
+ return { writeGate: true, result: collapsed !== undefined ? { collapsed } : {} };
196
208
  });
197
209
  }
198
210
  export function isValidConsolidationPlanId(value) {
@@ -362,6 +374,166 @@ export function readIntentCredentials(controlDir) {
362
374
  const raw = readStrictSidecar(controlDir, CONSOLIDATION_INTENTS_FILE, "memory consolidation intent-credential account");
363
375
  return coerceIntentFile(raw).rows;
364
376
  }
377
+ export const CONSOLIDATION_DRIVER_RUNS_FILE = "distiller-runs.json";
378
+ function coerceRunsFile(raw) {
379
+ if (raw === undefined)
380
+ return { v: 1, scopes: {} };
381
+ if (typeof raw !== "object" || raw === null || raw.v !== 1 || typeof raw.scopes !== "object" || raw.scopes === null) {
382
+ throw new ControlPlaneCorruptError("memory consolidation driver run account has an unrecognized shape (fail-closed sidecar)");
383
+ }
384
+ for (const [scope, rowRaw] of Object.entries(raw.scopes)) {
385
+ const r = rowRaw;
386
+ if (typeof r !== "object" || r === null || typeof r["runId"] !== "string" || (r["state"] !== "pending" && r["state"] !== "settled") || typeof r["cyclesDone"] !== "number") {
387
+ throw new ControlPlaneCorruptError(`memory consolidation driver run row for scope ${JSON.stringify(scope)} is malformed (fail-closed sidecar)`);
388
+ }
389
+ }
390
+ return raw;
391
+ }
392
+ export function distillerPlanArchiveName(runId, attempt) {
393
+ return `${runId}-a${attempt}.json`;
394
+ }
395
+ function mintPath(controlDir, name) {
396
+ return /^[A-Za-z0-9][A-Za-z0-9_-]{7,63}-a[0-9]{1,9}\.json$/.test(name) ? join(controlDir, CONSOLIDATION_DRIVER_PLANS_DIR, name) : undefined;
397
+ }
398
+ export function consolidationRunSuperseded(scope, cur) {
399
+ const e = new Error(`memory consolidation driver run seat for scope ${JSON.stringify(scope)} was taken over by a newer invocation${cur !== undefined ? ` (run ${cur.runId} attempt ${cur.attempt ?? 0})` : ""} — this worker stops without settling; the newer claim owns the account.`);
400
+ e.code = "memory.consolidation_driver_superseded";
401
+ return e;
402
+ }
403
+ export function memoryGovernanceDurability(backend) {
404
+ const root = Reflect.get(backend, "controlPlaneRoot");
405
+ return typeof root === "string" && root !== "" ? "backend" : "replica-local";
406
+ }
407
+ const FILE_GOVERNANCE_DIRS = new WeakMap();
408
+ export function fileGovernanceStoreDir(store) {
409
+ return FILE_GOVERNANCE_DIRS.get(store);
410
+ }
411
+ function isMintArchive(value) {
412
+ return typeof value === "object" && value !== null && Reflect.get(value, "kind") === "llm-consolidation-plan";
413
+ }
414
+ export function fileGovernanceStore(controlDir) {
415
+ const runsWhat = "memory consolidation driver run account";
416
+ const store = Object.freeze({
417
+ async readDoc(name) {
418
+ const doc = fileGovernanceDocOf(name);
419
+ return readStrictSidecar(controlDir, doc.file, doc.what);
420
+ },
421
+ async updateDoc(name, coerce, fn) {
422
+ const doc = fileGovernanceDocOf(name);
423
+ return lockedStrictUpdate(controlDir, doc.file, doc.what, coerce, fn);
424
+ },
425
+ async transact(planIds, fn) {
426
+ return updateConsolidationGate(controlDir, (file) => {
427
+ const reads = new Map(planIds.map((id) => [id, readConsolidationPlan(controlDir, id)]));
428
+ const staged = new Map();
429
+ const tx = {
430
+ scopes: file.scopes,
431
+ plan(planId) {
432
+ const read = reads.get(planId);
433
+ if (read === undefined)
434
+ throw new Error(`consolidation transaction: plan ${JSON.stringify(planId)} was not named when the transaction began, so it was not read under it`);
435
+ return read;
436
+ },
437
+ writePlan(plan) {
438
+ staged.set(plan.planId, plan);
439
+ },
440
+ };
441
+ const { writeGate, result } = fn(tx);
442
+ for (const plan of staged.values())
443
+ writeConsolidationPlan(controlDir, plan);
444
+ return writeGate ? { next: file, result } : { result };
445
+ });
446
+ },
447
+ async readGate() {
448
+ return readConsolidationGateFile(controlDir).scopes;
449
+ },
450
+ readPlan(planId) {
451
+ return readConsolidationPlan(controlDir, planId);
452
+ },
453
+ async listPlanIds() {
454
+ return listConsolidationPlanIds(controlDir);
455
+ },
456
+ async quarantinePlan(planId) {
457
+ return quarantineCorruptPlan(controlDir, planId);
458
+ },
459
+ async recordIntents(rows) {
460
+ return recordIntentCredentials(controlDir, rows);
461
+ },
462
+ async readIntents() {
463
+ return readIntentCredentials(controlDir);
464
+ },
465
+ async claimRun(scope, fresh) {
466
+ return lockedStrictUpdate(controlDir, CONSOLIDATION_DRIVER_RUNS_FILE, runsWhat, coerceRunsFile, (file) => {
467
+ const cur = file.scopes[scope];
468
+ if (cur !== undefined && cur.state === "pending") {
469
+ cur.attempt = (cur.attempt ?? 0) + 1;
470
+ file.scopes[scope] = cur;
471
+ return { next: file, result: { row: structuredClone(cur), resumed: true } };
472
+ }
473
+ const row = fresh();
474
+ file.scopes[scope] = row;
475
+ return { next: file, result: { row: structuredClone(row), resumed: false } };
476
+ });
477
+ },
478
+ async readRun(scope) {
479
+ return coerceRunsFile(readStrictSidecar(controlDir, CONSOLIDATION_DRIVER_RUNS_FILE, runsWhat)).scopes[scope];
480
+ },
481
+ async writeRun(row) {
482
+ lockedStrictUpdate(controlDir, CONSOLIDATION_DRIVER_RUNS_FILE, runsWhat, coerceRunsFile, (file) => {
483
+ const cur = file.scopes[row.scope];
484
+ if (cur === undefined || cur.runId !== row.runId || (cur.attempt ?? 0) !== row.attempt)
485
+ throw consolidationRunSuperseded(row.scope, cur);
486
+ file.scopes[row.scope] = row;
487
+ return { next: file, result: undefined };
488
+ });
489
+ },
490
+ async archiveMint(runId, attempt, plan) {
491
+ ensureDirExists(join(controlDir, CONSOLIDATION_DRIVER_PLANS_DIR));
492
+ const name = distillerPlanArchiveName(runId, attempt);
493
+ atomicWriteFileSync(join(controlDir, CONSOLIDATION_DRIVER_PLANS_DIR, name), `${JSON.stringify(plan, null, 2)}\n`);
494
+ return name;
495
+ },
496
+ async readMint(name) {
497
+ const path = mintPath(controlDir, name);
498
+ if (path === undefined || !existsSync(path))
499
+ return undefined;
500
+ let parsed;
501
+ try {
502
+ parsed = JSON.parse(readFileSync(path, "utf8"));
503
+ }
504
+ catch (err) {
505
+ throw new ControlPlaneCorruptError(`memory consolidation mint archive ${JSON.stringify(name)} is unreadable or unparseable: ${thrownText(err)}`, { cause: err });
506
+ }
507
+ if (!isMintArchive(parsed))
508
+ throw new ControlPlaneCorruptError(`memory consolidation mint archive ${JSON.stringify(name)} does not carry the mint's kind (fail-closed)`);
509
+ return parsed;
510
+ },
511
+ async eraseMint(name) {
512
+ const path = mintPath(controlDir, name);
513
+ if (path === undefined || !existsSync(path))
514
+ return false;
515
+ rmSync(path, { force: true });
516
+ return true;
517
+ },
518
+ async putObject(kind, name, bytes) {
519
+ return putFileControlObject(controlDir, kind, name, bytes);
520
+ },
521
+ async getObject(kind, name) {
522
+ return getFileControlObject(controlDir, kind, name);
523
+ },
524
+ async listObjects(kind) {
525
+ return listFileControlObjects(controlDir, kind);
526
+ },
527
+ async moveObject(from, to) {
528
+ return moveFileControlObject(controlDir, from, to);
529
+ },
530
+ async deleteObject(kind, name) {
531
+ return deleteFileControlObject(controlDir, kind, name);
532
+ },
533
+ });
534
+ FILE_GOVERNANCE_DIRS.set(store, controlDir);
535
+ return store;
536
+ }
365
537
  export function deriveProductSlug(name, fallback) {
366
538
  const base = (name ?? "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
367
539
  return base.length > 0 ? base : fallback;
@@ -0,0 +1,25 @@
1
+ import { type MemoryControlObjectKind } from "./types.js";
2
+ /** Where a File store stages an object's bytes before publishing them under the object's name. Never a kind's
3
+ * directory: a listing of a kind answers published names only. */
4
+ export declare const CONTROL_OBJECT_STAGE_DIR = ".control-object-stage";
5
+ /** A control-object kind's directory under a File store's control plane. A kind outside
6
+ * {@link MEMORY_CONTROL_OBJECT_KINDS} is refused (`memory.control_object_unknown`) — never given a directory of its own. */
7
+ export declare function fileControlObjectDirOf(kind: MemoryControlObjectKind): string;
8
+ /** A name a store keeps an object under: one opaque, non-empty segment — never `.` / `..`, never a separator or a NUL. */
9
+ export declare function isControlObjectName(name: unknown): name is string;
10
+ /** Write `(kind, name)` once ({@link import("./types.js").MemoryGovernanceStore.putObject}). */
11
+ export declare function putFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string, bytes: Uint8Array): "created" | "existed";
12
+ /** A control object's bytes ({@link import("./types.js").MemoryGovernanceStore.getObject}). */
13
+ export declare function getFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string): Uint8Array | undefined;
14
+ /** Every name of `kind`, sorted ({@link import("./types.js").MemoryGovernanceStore.listObjects}). */
15
+ export declare function listFileControlObjects(controlDir: string, kind: MemoryControlObjectKind): string[];
16
+ /** Move one object, never overwriting ({@link import("./types.js").MemoryGovernanceStore.moveObject}). */
17
+ export declare function moveFileControlObject(controlDir: string, from: {
18
+ readonly kind: MemoryControlObjectKind;
19
+ readonly name: string;
20
+ }, to: {
21
+ readonly kind: MemoryControlObjectKind;
22
+ readonly name: string;
23
+ }): "moved" | "already-moved";
24
+ /** Delete one object ({@link import("./types.js").MemoryGovernanceStore.deleteObject}). */
25
+ export declare function deleteFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string): boolean;
@@ -0,0 +1,151 @@
1
+ import { closeSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import { MEMORY_CONTROL_OBJECT_KINDS } from "./types.js";
5
+ import { ControlPlaneCorruptError, IMPORT_RECEIPTS_DIR, QUARANTINE_DIR, SESSION_CAPTURE_OPTOUT_DIR, SESSION_POLLUTION_DIR, ensureDirExists } from "./layout.js";
6
+ const FILE_CONTROL_OBJECT_DIRS = Object.freeze({
7
+ pollution: SESSION_POLLUTION_DIR,
8
+ "import-receipt": IMPORT_RECEIPTS_DIR,
9
+ quarantine: QUARANTINE_DIR,
10
+ hold: "hold",
11
+ "clearance-custody": "origin-clearance-custody",
12
+ capture: SESSION_CAPTURE_OPTOUT_DIR,
13
+ });
14
+ export const CONTROL_OBJECT_STAGE_DIR = ".control-object-stage";
15
+ function unknownObject(what) {
16
+ const e = new Error(`memory governance store: ${what} (a control object is one of ${MEMORY_CONTROL_OBJECT_KINDS.join(", ")}, named by one opaque segment)`);
17
+ e.code = "memory.control_object_unknown";
18
+ return e;
19
+ }
20
+ export function fileControlObjectDirOf(kind) {
21
+ if (typeof kind !== "string" || !Object.prototype.hasOwnProperty.call(FILE_CONTROL_OBJECT_DIRS, kind))
22
+ throw unknownObject(`${JSON.stringify(String(kind))} is not a control-object kind`);
23
+ return FILE_CONTROL_OBJECT_DIRS[kind];
24
+ }
25
+ export function isControlObjectName(name) {
26
+ return typeof name === "string" && name !== "" && name !== "." && name !== ".." && !/[/\\\0]/.test(name);
27
+ }
28
+ function objectPath(controlDir, kind, name) {
29
+ const dir = fileControlObjectDirOf(kind);
30
+ if (!isControlObjectName(name))
31
+ throw unknownObject(`${JSON.stringify(String(name))} is not a control-object name`);
32
+ return join(controlDir, dir, name);
33
+ }
34
+ function errnoOf(err) {
35
+ return typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined;
36
+ }
37
+ function stands(path) {
38
+ try {
39
+ lstatSync(path);
40
+ return true;
41
+ }
42
+ catch (err) {
43
+ if (errnoOf(err) === "ENOENT")
44
+ return false;
45
+ throw new ControlPlaneCorruptError(`memory control object at ${path} could not be probed (${errnoOf(err) ?? "io error"}) — whether it stands is unknown (fail-closed)`, { cause: err });
46
+ }
47
+ }
48
+ export function putFileControlObject(controlDir, kind, name, bytes) {
49
+ const path = objectPath(controlDir, kind, name);
50
+ if (stands(path))
51
+ return "existed";
52
+ ensureDirExists(join(controlDir, fileControlObjectDirOf(kind)));
53
+ const stageDir = join(controlDir, CONTROL_OBJECT_STAGE_DIR);
54
+ ensureDirExists(stageDir);
55
+ const staged = join(stageDir, randomUUID());
56
+ const fd = openSync(staged, "wx", 0o600);
57
+ try {
58
+ let written = 0;
59
+ while (written < bytes.byteLength) {
60
+ const n = writeSync(fd, bytes, written, bytes.byteLength - written);
61
+ if (n <= 0)
62
+ throw new Error(`memory control object ${kind}/${name}: write made no progress (${written}/${bytes.byteLength} bytes)`);
63
+ written += n;
64
+ }
65
+ fsyncSync(fd);
66
+ }
67
+ finally {
68
+ closeSync(fd);
69
+ }
70
+ try {
71
+ linkSync(staged, path);
72
+ return "created";
73
+ }
74
+ catch (err) {
75
+ if (errnoOf(err) === "EEXIST")
76
+ return "existed";
77
+ throw err;
78
+ }
79
+ finally {
80
+ rmSync(staged, { force: true });
81
+ }
82
+ }
83
+ export function getFileControlObject(controlDir, kind, name) {
84
+ const path = objectPath(controlDir, kind, name);
85
+ try {
86
+ return new Uint8Array(readFileSync(path));
87
+ }
88
+ catch (err) {
89
+ if ((errnoOf(err) === "ENOENT" || errnoOf(err) === "ENOTDIR") && !stands(path))
90
+ return undefined;
91
+ throw new ControlPlaneCorruptError(`memory control object ${kind}/${name} stands but cannot be read (${errnoOf(err) ?? "io error"}) — it is never read as missing (fail-closed)`, { cause: err });
92
+ }
93
+ }
94
+ export function listFileControlObjects(controlDir, kind) {
95
+ const dir = join(controlDir, fileControlObjectDirOf(kind));
96
+ try {
97
+ return readdirSync(dir).sort();
98
+ }
99
+ catch (err) {
100
+ if (errnoOf(err) === "ENOENT" && !stands(dir))
101
+ return [];
102
+ throw new ControlPlaneCorruptError(`memory control objects of kind ${kind} could not be enumerated (${errnoOf(err) ?? "io error"}) at ${dir} — an enumeration failure is not an empty kind (fail-closed)`, { cause: err });
103
+ }
104
+ }
105
+ function sameBytes(a, b) {
106
+ const sa = statSync(a);
107
+ const sb = statSync(b);
108
+ if (sa.dev === sb.dev && sa.ino === sb.ino)
109
+ return true;
110
+ return readFileSync(a).equals(readFileSync(b));
111
+ }
112
+ export function moveFileControlObject(controlDir, from, to) {
113
+ const src = objectPath(controlDir, from.kind, from.name);
114
+ const dst = objectPath(controlDir, to.kind, to.name);
115
+ const neither = () => new ControlPlaneCorruptError(`memory control object move ${from.kind}/${from.name} → ${to.kind}/${to.name}: neither the source nor the target stands — nothing to move or to resume (fail-closed)`);
116
+ if (src === dst) {
117
+ if (stands(src))
118
+ return "already-moved";
119
+ throw neither();
120
+ }
121
+ ensureDirExists(join(controlDir, fileControlObjectDirOf(to.kind)));
122
+ try {
123
+ linkSync(src, dst);
124
+ }
125
+ catch (err) {
126
+ const code = errnoOf(err);
127
+ if (code === "ENOENT" && !stands(src)) {
128
+ if (stands(dst))
129
+ return "already-moved";
130
+ throw neither();
131
+ }
132
+ if (code !== "EEXIST")
133
+ throw err;
134
+ if (!sameBytes(src, dst))
135
+ throw new ControlPlaneCorruptError(`memory control object move ${from.kind}/${from.name} → ${to.kind}/${to.name}: the target already stands with different bytes — refusing to overwrite it (fail-closed)`);
136
+ }
137
+ unlinkSync(src);
138
+ return "moved";
139
+ }
140
+ export function deleteFileControlObject(controlDir, kind, name) {
141
+ const path = objectPath(controlDir, kind, name);
142
+ try {
143
+ unlinkSync(path);
144
+ return true;
145
+ }
146
+ catch (err) {
147
+ if ((errnoOf(err) === "ENOENT" || errnoOf(err) === "ENOTDIR") && !stands(path))
148
+ return false;
149
+ throw err;
150
+ }
151
+ }
@@ -0,0 +1,48 @@
1
+ import { type MemoryControlObjectKind, type MemoryGovernanceDocName, type MemoryGovernanceStore } from "./types.js";
2
+ /** The carrier records a replica control plane still holds. */
3
+ export interface ReplicaControlPlaneStrays {
4
+ /** The governance documents with a file (or a journal) in the replica. */
5
+ readonly docs: readonly MemoryGovernanceDocName[];
6
+ /** How many control objects of each kind the replica holds (kinds it holds none of are absent). */
7
+ readonly objects: Readonly<Partial<Record<MemoryControlObjectKind, number>>>;
8
+ }
9
+ /** One record adoption handled: a document (`doc:<name>`) or an object (`<kind>/<name>`). */
10
+ export interface AdoptedControlRecord {
11
+ readonly record: string;
12
+ /** What the carrier holds now, never what became of the replica's copy (which stays): `"written"` ⇔ the carrier
13
+ * lacked the record and now holds the same value; `"converged"` ⇔ it already held the same value. */
14
+ readonly outcome: "written" | "converged";
15
+ /** sha-256 of the record as the replica held it: an object's bytes, a document's committed JSON value. */
16
+ readonly digest: string;
17
+ }
18
+ /** {@link adoptReplicaControlPlane}'s answer. */
19
+ export interface ControlPlaneAdoptionReport {
20
+ /** Records the carrier now holds with the replica's value (the replica keeps its copy). */
21
+ readonly adopted: readonly AdoptedControlRecord[];
22
+ /** Records whose adoption did not complete, each with why — a different value already in the carrier, a record that
23
+ * could not be read or verified, or a receipt row that could not be written (then the carrier may already hold the
24
+ * value, and a re-run converges it). */
25
+ readonly refused: readonly {
26
+ readonly record: string;
27
+ readonly reason: string;
28
+ }[];
29
+ }
30
+ /** The replica's body-less record of which of its records the carrier holds with the same value (one row per record and digest). */
31
+ export declare const CONTROL_PLANE_ADOPTION_FILE = "control-plane-adoption.json";
32
+ /** The carrier records `controlDir` holds — documents with a file or journal, objects by kind. An enumeration that
33
+ * fails throws `ControlPlaneCorruptError` (never an empty answer). */
34
+ export declare function replicaControlPlaneStrays(controlDir: string): ReplicaControlPlaneStrays;
35
+ /**
36
+ * Copy the replica control plane's carrier records into `carrier` (see the module note). Answers what the carrier now
37
+ * holds with the replica's value and what was refused; the replica's records are not removed either way. When `carrier`
38
+ * is the File store over `controlDir` itself there is nothing to hand over and the answer is empty.
39
+ */
40
+ export declare function adoptReplicaControlPlane(controlDir: string, carrier: MemoryGovernanceStore, opts?: {
41
+ readonly now?: () => number;
42
+ }): Promise<ControlPlaneAdoptionReport>;
43
+ /** The replica's adoption receipt: one body-less row per adopted record (what, the digest of its bytes, when). */
44
+ export declare function readControlPlaneAdoptionReceipt(controlDir: string): ReadonlyArray<{
45
+ readonly record: string;
46
+ readonly digest: string;
47
+ readonly at: number;
48
+ }>;
@@ -0,0 +1,159 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync, statSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { MEMORY_CONTROL_OBJECT_KINDS, MEMORY_GOVERNANCE_DOC_NAMES } from "./types.js";
6
+ import { ControlPlaneCorruptError, fileGovernanceDocOf, lockedStrictUpdate, readStrictSidecar } from "./layout.js";
7
+ import { getFileControlObject, listFileControlObjects } from "./control-objects.js";
8
+ import { fileGovernanceStoreDir } from "./consolidation.js";
9
+ import { moveOriginClearanceCustodyOut } from "./origin-clearance.js";
10
+ import { thrownText } from "../thrown-value.js";
11
+ export const CONTROL_PLANE_ADOPTION_FILE = "control-plane-adoption.json";
12
+ function coerceReceipt(raw) {
13
+ if (raw === undefined)
14
+ return { version: 1, adopted: [] };
15
+ if (typeof raw !== "object" || raw === null || Reflect.get(raw, "version") !== 1 || !Array.isArray(Reflect.get(raw, "adopted"))) {
16
+ throw new ControlPlaneCorruptError("memory control-plane adoption receipt has the wrong shape (fail-closed)");
17
+ }
18
+ return raw;
19
+ }
20
+ function sha256Hex(bytes) {
21
+ return createHash("sha256").update(bytes).digest("hex");
22
+ }
23
+ function standsAt(path) {
24
+ try {
25
+ lstatSync(path);
26
+ return true;
27
+ }
28
+ catch (err) {
29
+ if (Reflect.get(err, "code") === "ENOENT")
30
+ return false;
31
+ throw new ControlPlaneCorruptError(`memory control plane: ${path} could not be probed (${String(Reflect.get(err, "code") ?? "io error")}) (fail-closed)`, { cause: err });
32
+ }
33
+ }
34
+ export function replicaControlPlaneStrays(controlDir) {
35
+ const docs = MEMORY_GOVERNANCE_DOC_NAMES.filter((name) => {
36
+ const file = join(controlDir, fileGovernanceDocOf(name).file);
37
+ return standsAt(file) || standsAt(`${file}.journal`);
38
+ });
39
+ const objects = {};
40
+ for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
41
+ const n = listFileControlObjects(controlDir, kind).length;
42
+ if (n > 0)
43
+ objects[kind] = n;
44
+ }
45
+ return { docs, objects };
46
+ }
47
+ function carriesThisDirectory(carrier, controlDir) {
48
+ const dir = fileGovernanceStoreDir(carrier);
49
+ if (dir === undefined)
50
+ return false;
51
+ if (resolve(dir) === resolve(controlDir))
52
+ return true;
53
+ try {
54
+ const a = statSync(dir);
55
+ const b = statSync(controlDir);
56
+ return a.dev === b.dev && a.ino === b.ino;
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ export async function adoptReplicaControlPlane(controlDir, carrier, opts) {
63
+ const now = opts?.now ?? Date.now;
64
+ const adopted = [];
65
+ const refused = [];
66
+ if (carriesThisDirectory(carrier, controlDir))
67
+ return { adopted, refused };
68
+ const receipt = (record, digest) => {
69
+ lockedStrictUpdate(controlDir, CONTROL_PLANE_ADOPTION_FILE, "memory control-plane adoption receipt", coerceReceipt, (rec) => {
70
+ if (rec.adopted.some((r) => r.record === record && r.digest === digest))
71
+ return { result: undefined };
72
+ rec.adopted.push({ record, digest, at: now() });
73
+ return { next: rec, result: undefined };
74
+ });
75
+ };
76
+ const clearances = join(controlDir, fileGovernanceDocOf("origin-clearances").file);
77
+ if (standsAt(clearances) || standsAt(`${clearances}.journal`)) {
78
+ try {
79
+ moveOriginClearanceCustodyOut(controlDir);
80
+ }
81
+ catch (err) {
82
+ refused.push({ record: "doc:origin-clearances", reason: `its inline custody could not be moved out first: ${thrownText(err)}` });
83
+ }
84
+ }
85
+ for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
86
+ for (const name of listFileControlObjects(controlDir, kind)) {
87
+ const record = `${kind}/${name}`;
88
+ try {
89
+ const bytes = getFileControlObject(controlDir, kind, name);
90
+ if (bytes === undefined)
91
+ continue;
92
+ const digest = sha256Hex(bytes);
93
+ const outcome = (await carrier.putObject(kind, name, bytes)) === "created" ? "written" : "converged";
94
+ const held = await carrier.getObject(kind, name);
95
+ if (held === undefined || sha256Hex(held) !== digest) {
96
+ refused.push({ record, reason: outcome === "converged" ? "the carrier already holds an object of this name with different bytes" : "the carrier's copy does not read back the same" });
97
+ continue;
98
+ }
99
+ const again = getFileControlObject(controlDir, kind, name);
100
+ if (again === undefined || sha256Hex(again) !== digest) {
101
+ refused.push({ record, reason: "the replica's bytes changed while they were adopted" });
102
+ continue;
103
+ }
104
+ receipt(record, digest);
105
+ adopted.push({ record, outcome, digest });
106
+ }
107
+ catch (err) {
108
+ refused.push({ record, reason: thrownText(err) });
109
+ }
110
+ }
111
+ }
112
+ const before = refused.map((r) => r.record);
113
+ if (before.length > 0) {
114
+ for (const name of replicaControlPlaneStrays(controlDir).docs) {
115
+ if (!before.includes(`doc:${name}`))
116
+ refused.push({ record: `doc:${name}`, reason: `left in the replica until every record before it is adopted (refused: ${before.join(", ")})` });
117
+ }
118
+ return { adopted, refused };
119
+ }
120
+ for (const name of MEMORY_GOVERNANCE_DOC_NAMES) {
121
+ const record = `doc:${name}`;
122
+ const { file, what } = fileGovernanceDocOf(name);
123
+ const path = join(controlDir, file);
124
+ try {
125
+ if (!standsAt(path) && !standsAt(`${path}.journal`))
126
+ continue;
127
+ const value = readStrictSidecar(controlDir, file, what);
128
+ if (value === undefined)
129
+ continue;
130
+ const digest = sha256Hex(JSON.stringify(value));
131
+ const outcome = await carrier.updateDoc(name, (raw) => raw, (cur) => {
132
+ if (cur === undefined)
133
+ return { next: value, result: "written" };
134
+ return { result: isDeepStrictEqual(cur, value) ? "converged" : "different" };
135
+ });
136
+ if (outcome === "different") {
137
+ refused.push({ record, reason: "the carrier already holds a different document of this name" });
138
+ continue;
139
+ }
140
+ if (!isDeepStrictEqual(await carrier.readDoc(name), value)) {
141
+ refused.push({ record, reason: "the carrier's copy does not read back the same" });
142
+ continue;
143
+ }
144
+ if (!isDeepStrictEqual(readStrictSidecar(controlDir, file, what), value)) {
145
+ refused.push({ record, reason: "the replica's document changed while it was adopted" });
146
+ continue;
147
+ }
148
+ receipt(record, digest);
149
+ adopted.push({ record, outcome, digest });
150
+ }
151
+ catch (err) {
152
+ refused.push({ record, reason: thrownText(err) });
153
+ }
154
+ }
155
+ return { adopted, refused };
156
+ }
157
+ export function readControlPlaneAdoptionReceipt(controlDir) {
158
+ return coerceReceipt(readStrictSidecar(controlDir, CONTROL_PLANE_ADOPTION_FILE, "memory control-plane adoption receipt")).adopted;
159
+ }
@@ -2,7 +2,8 @@ import type { HarvestRejection, MemoryBackend, MemoryEntry, NotePatch, PatchRepo
2
2
  /** Default per-file byte cap — SAME value as the host engine's MAX_MEMORY_BYTES (独立轨 F3: a 60KB
3
3
  * entry legal on the host must not be re-rejected every remote round; one cap, one truth). */
4
4
  export declare const REMOTE_HARVEST_PER_FILE_BYTES: number;
5
- /** Missing-file ratio above which the harvest refuses wholesale (engine MASS_DELETION_FUSE_RATIO). */
5
+ /** The deletion fuse's ratio leg on the remote lane (engine MASS_DELETION_FUSE_RATIO): with the shared
6
+ * floor, more removals than max(floor, ⌊ratio × N⌋) refuses the harvest wholesale. */
6
7
  export declare const REMOTE_MASS_DELETION_FUSE_RATIO = 0.5;
7
8
  /** File-count cap per harvest (host DEFAULT_MAX_MEMORY_FILES parity). */
8
9
  export declare const REMOTE_HARVEST_MAX_FILES = 500;
@@ -52,7 +53,9 @@ export interface RemoteHarvestResult {
52
53
  /** Feed to `backend.applyPatches` (the deployment owns the call + the resulting PatchReport). */
53
54
  patches: NotePatch[];
54
55
  rejections: HarvestRejection[];
55
- /** Baseline files absent from the read-back set (info; NEVER a delete — tombstones only). */
56
+ /** Baseline files gone from the read-back set (absent, or blank). A writable one is the session's
57
+ * removal and rides `patches` as a delete (unless the fuse trips); a read-only one is only listed
58
+ * (no delete; any restore is the deployment's sandbox I/O). */
56
59
  missing: string[];
57
60
  /** Set instead of patches when the mass-deletion fuse trips (deployment surfaces it, human call). */
58
61
  incident?: {
@@ -71,8 +74,9 @@ export interface RemoteHarvestResult {
71
74
  /**
72
75
  * The pure gate+diff core over files read back from a remote sandbox. Same judgment order as the
73
76
  * host engine's harvest: readonly-layer tamper → rejection (restore is the deployment's I/O);
74
- * missing + fuse; per-file size cap → scan rule set (secret/injection/filename) → parse →
75
- * id-immutability (baseline id wins) → tombstone-only delete → CAS update / rename / add.
77
+ * removals + fuse (a removed writable file = a CAS'd delete); per-file size cap → scan rule set
78
+ * (secret/injection/filename) → parse → id-immutability (baseline id wins) → tombstone delete → CAS
79
+ * update / rename / add.
76
80
  */
77
81
  export declare function harvestFilesToPatches(baseline: RemoteMemoryBaseline, files: readonly RemoteMemoryFile[], opts?: {
78
82
  perFileBytes?: number;