@sema-agent/core 7.69.0 → 7.69.1

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 (309) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/dist/agents/repair-loop.js +6 -14
  3. package/dist/agents/subagent.js +2 -1
  4. package/dist/agents/verify.d.ts +1 -1
  5. package/dist/agents/verify.js +7 -1
  6. package/dist/brain/reasoning-request.d.ts +7 -0
  7. package/dist/brain/reasoning-request.js +6 -0
  8. package/dist/core/agent-config-dir.d.ts +39 -3
  9. package/dist/core/agent-config-dir.js +67 -11
  10. package/dist/core/allow-entry.d.ts +5 -5
  11. package/dist/core/allow-entry.js +12 -6
  12. package/dist/core/ask-headline.d.ts +2 -2
  13. package/dist/core/ask-origin.d.ts +31 -31
  14. package/dist/core/ask-origin.js +20 -13
  15. package/dist/core/attachment-source.d.ts +1 -1
  16. package/dist/core/attachment-source.js +1 -0
  17. package/dist/core/auto-compaction.d.ts +44 -62
  18. package/dist/core/auto-compaction.js +44 -103
  19. package/dist/core/cache-break-detector.d.ts +23 -11
  20. package/dist/core/cache-break-detector.js +11 -5
  21. package/dist/core/checkpoint-features.d.ts +1 -1
  22. package/dist/core/checkpoint-features.js +1 -1
  23. package/dist/core/checkpoint-requirements.d.ts +19 -1
  24. package/dist/core/checkpoint-requirements.js +6 -0
  25. package/dist/core/checkpoint-row-verdict.js +3 -0
  26. package/dist/core/checkpoint-store.d.ts +13 -2
  27. package/dist/core/child-clamp-seats.d.ts +30 -3
  28. package/dist/core/child-clamp-seats.js +24 -0
  29. package/dist/core/compaction-retired-members.d.ts +12 -0
  30. package/dist/core/compaction-retired-members.js +22 -0
  31. package/dist/core/config-refusal-codes.d.ts +1 -1
  32. package/dist/core/config-refusal-codes.js +2 -0
  33. package/dist/core/context-edit.d.ts +32 -17
  34. package/dist/core/context-edit.js +28 -0
  35. package/dist/core/cron.d.ts +68 -0
  36. package/dist/core/cron.js +259 -0
  37. package/dist/core/engine-attestation.d.ts +16 -0
  38. package/dist/core/engine-attestation.js +2 -0
  39. package/dist/core/engine-capabilities.d.ts +14 -1
  40. package/dist/core/engine-capabilities.js +1 -1
  41. package/dist/core/engine-notice.d.ts +18 -7
  42. package/dist/core/engine-version.js +1 -1
  43. package/dist/core/gate-outcome.d.ts +29 -2
  44. package/dist/core/gate-outcome.js +6 -0
  45. package/dist/core/git-read-only.d.ts +10 -0
  46. package/dist/core/git-read-only.js +1 -0
  47. package/dist/core/git-worktree-env.js +9 -8
  48. package/dist/core/governance-codes.d.ts +9 -2
  49. package/dist/core/governance-codes.js +9 -0
  50. package/dist/core/locked-config.js +7 -3
  51. package/dist/core/lsp.d.ts +3 -0
  52. package/dist/core/lsp.js +3 -2
  53. package/dist/core/memory-engine/engine.d.ts +48 -12
  54. package/dist/core/memory-engine/engine.js +108 -46
  55. package/dist/core/memory-engine/file-backend.d.ts +2 -1
  56. package/dist/core/memory-engine/index-copies.d.ts +47 -0
  57. package/dist/core/memory-engine/index-copies.js +88 -0
  58. package/dist/core/memory-engine/layout.d.ts +20 -3
  59. package/dist/core/memory-engine/layout.js +39 -3
  60. package/dist/core/memory-engine/origin-clearance.d.ts +9 -7
  61. package/dist/core/memory-engine/origin-clearance.js +2 -4
  62. package/dist/core/memory-engine/types.d.ts +16 -3
  63. package/dist/core/mode-policy.d.ts +7 -1
  64. package/dist/core/mode-policy.js +9 -0
  65. package/dist/core/mods/session-compact.js +3 -3
  66. package/dist/core/mods/stations.d.ts +2 -0
  67. package/dist/core/mods/stations.js +2 -1
  68. package/dist/core/path-guard-rows.d.ts +8 -3
  69. package/dist/core/path-guard-rows.js +18 -5
  70. package/dist/core/peer-seat.d.ts +3 -0
  71. package/dist/core/peer-seat.js +3 -0
  72. package/dist/core/permission-rule-model.js +3 -2
  73. package/dist/core/process-identity.d.ts +11 -3
  74. package/dist/core/process-identity.js +26 -16
  75. package/dist/core/runner/assemble-result.d.ts +5 -0
  76. package/dist/core/runner/assemble-result.js +1 -1
  77. package/dist/core/runner/cleared-results-record.d.ts +33 -0
  78. package/dist/core/runner/cleared-results-record.js +56 -0
  79. package/dist/core/runner/compact-session.js +14 -9
  80. package/dist/core/runner/compaction-knobs.d.ts +1 -1
  81. package/dist/core/runner/continuation-gate.js +2 -1
  82. package/dist/core/runner/continues-from.d.ts +1 -1
  83. package/dist/core/runner/continues-from.js +1 -1
  84. package/dist/core/runner/contracts.d.ts +83 -31
  85. package/dist/core/runner/conversation-segment.d.ts +19 -12
  86. package/dist/core/runner/conversation-segment.js +27 -7
  87. package/dist/core/runner/derived-route-fallback.d.ts +2 -12
  88. package/dist/core/runner/derived-route-fallback.js +0 -6
  89. package/dist/core/runner/gate-exit.d.ts +2 -1
  90. package/dist/core/runner/gate-exit.js +4 -2
  91. package/dist/core/runner/git-status-frame.d.ts +2 -2
  92. package/dist/core/runner/git-status-frame.js +2 -1
  93. package/dist/core/runner/initial-run-state.js +1 -1
  94. package/dist/core/runner/leg-caller-places.d.ts +39 -0
  95. package/dist/core/runner/leg-caller-places.js +23 -0
  96. package/dist/core/runner/leg-frame.d.ts +8 -2
  97. package/dist/core/runner/leg-receipt.d.ts +29 -2
  98. package/dist/core/runner/leg-receipt.js +37 -6
  99. package/dist/core/runner/media-removed-seat.d.ts +10 -6
  100. package/dist/core/runner/media-removed-seat.js +6 -3
  101. package/dist/core/runner/messages-omitted-seat.d.ts +2 -1
  102. package/dist/core/runner/messages-omitted-seat.js +15 -5
  103. package/dist/core/runner/person-path-rows.d.ts +25 -7
  104. package/dist/core/runner/person-path-rows.js +16 -2
  105. package/dist/core/runner/prefix-ledger.d.ts +120 -0
  106. package/dist/core/runner/prefix-ledger.js +176 -0
  107. package/dist/core/runner/prepare-advisor.d.ts +2 -0
  108. package/dist/core/runner/prepare-advisor.js +2 -1
  109. package/dist/core/runner/prepare-artifact.d.ts +3 -0
  110. package/dist/core/runner/prepare-artifact.js +2 -2
  111. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  112. package/dist/core/runner/prepare-caps-and-workflow.js +4 -3
  113. package/dist/core/runner/prepare-config-doors.d.ts +9 -8
  114. package/dist/core/runner/prepare-config-doors.js +15 -12
  115. package/dist/core/runner/prepare-context-lane.d.ts +25 -6
  116. package/dist/core/runner/prepare-context-lane.js +82 -27
  117. package/dist/core/runner/prepare-gate-stations.d.ts +1 -2
  118. package/dist/core/runner/prepare-gate-stations.js +2 -4
  119. package/dist/core/runner/prepare-hands-readface.d.ts +18 -5
  120. package/dist/core/runner/prepare-hands-readface.js +41 -22
  121. package/dist/core/runner/prepare-inherited-gate.d.ts +5 -0
  122. package/dist/core/runner/prepare-inherited-gate.js +2 -0
  123. package/dist/core/runner/prepare-memory.d.ts +10 -2
  124. package/dist/core/runner/prepare-memory.js +51 -5
  125. package/dist/core/runner/prepare-policy-chain.d.ts +3 -0
  126. package/dist/core/runner/prepare-policy-chain.js +13 -2
  127. package/dist/core/runner/prepare-prompt-assembly.d.ts +12 -4
  128. package/dist/core/runner/prepare-prompt-assembly.js +10 -4
  129. package/dist/core/runner/prepare-prompt-inputs.d.ts +3 -7
  130. package/dist/core/runner/prepare-prompt-inputs.js +6 -7
  131. package/dist/core/runner/prepare-safety-scan.js +7 -0
  132. package/dist/core/runner/prepare-suspend-saga.d.ts +4 -0
  133. package/dist/core/runner/prepare-suspend-saga.js +3 -2
  134. package/dist/core/runner/prepare-task.js +59 -53
  135. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +5 -11
  136. package/dist/core/runner/prepare-tool-disclosure-mount.js +7 -8
  137. package/dist/core/runner/prepare-turn-wiring.d.ts +16 -25
  138. package/dist/core/runner/prepare-turn-wiring.js +8 -18
  139. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  140. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  141. package/dist/core/runner/prompt-suggestions.d.ts +3 -1
  142. package/dist/core/runner/prompt-suggestions.js +1 -1
  143. package/dist/core/runner/read-block-judge.d.ts +47 -0
  144. package/dist/core/runner/read-block-judge.js +33 -0
  145. package/dist/core/runner/role-resolution-table.d.ts +15 -10
  146. package/dist/core/runner/role-resolution-table.js +4 -5
  147. package/dist/core/runner/rule-store-unreadable-notice.d.ts +7 -4
  148. package/dist/core/runner/rule-store-unreadable-notice.js +4 -3
  149. package/dist/core/runner/run-compaction-machinery.d.ts +0 -10
  150. package/dist/core/runner/run-compaction-machinery.js +3 -39
  151. package/dist/core/runner/run-harness-handlers.js +4 -17
  152. package/dist/core/runner/run-identity-wiring.js +4 -1
  153. package/dist/core/runner/run-leg.js +11 -1
  154. package/dist/core/runner/run-recovery-lanes.d.ts +0 -4
  155. package/dist/core/runner/run-recovery-lanes.js +34 -18
  156. package/dist/core/runner/run-settle-and-teardown.d.ts +1 -3
  157. package/dist/core/runner/run-settle-and-teardown.js +14 -22
  158. package/dist/core/runner/run-telemetry-and-budget-seats.js +0 -1
  159. package/dist/core/runner/run-terminal-adoption.d.ts +11 -30
  160. package/dist/core/runner/run-terminal-adoption.js +5 -88
  161. package/dist/core/runner/run-tool-mount-facts.js +1 -5
  162. package/dist/core/runner/run-turn-boundary.js +56 -26
  163. package/dist/core/runner/runtask.js +7 -7
  164. package/dist/core/runner/session-hash-salt.d.ts +18 -0
  165. package/dist/core/runner/session-hash-salt.js +36 -0
  166. package/dist/core/runner/shell-env-withheld.d.ts +8 -5
  167. package/dist/core/runner/shell-env-withheld.js +3 -3
  168. package/dist/core/runner/side-call-account.d.ts +9 -1
  169. package/dist/core/runner/side-call-account.js +15 -4
  170. package/dist/core/runner/skill-mention.d.ts +12 -0
  171. package/dist/core/runner/skill-mention.js +50 -0
  172. package/dist/core/runner/stream-settle-backstop.js +1 -0
  173. package/dist/core/runner/synthetic-tools.js +2 -2
  174. package/dist/core/runner/tool-table-view.d.ts +5 -9
  175. package/dist/core/runner/tool-table-view.js +23 -21
  176. package/dist/core/runner/write-protection-station.d.ts +5 -2
  177. package/dist/core/runner/write-protection-station.js +1 -1
  178. package/dist/core/runner-deps.d.ts +25 -27
  179. package/dist/core/scheduler.d.ts +13 -3
  180. package/dist/core/scheduler.js +0 -12
  181. package/dist/core/secret-env.d.ts +47 -11
  182. package/dist/core/secret-env.js +65 -4
  183. package/dist/core/sensitive-path-policy.js +4 -0
  184. package/dist/core/session-checkout.js +10 -9
  185. package/dist/core/shell-read-silence.d.ts +2 -1
  186. package/dist/core/shell-run-candidates.d.ts +1 -1
  187. package/dist/core/shell-run-candidates.js +11 -3
  188. package/dist/core/task-event.d.ts +32 -10
  189. package/dist/core/task-intake.d.ts +5 -3
  190. package/dist/core/task-intake.js +6 -2
  191. package/dist/core/task-result.d.ts +39 -0
  192. package/dist/core/task-spec-members.d.ts +3 -0
  193. package/dist/core/task-spec-members.js +2 -2
  194. package/dist/core/task-spec.d.ts +37 -20
  195. package/dist/core/tool-policy.d.ts +30 -18
  196. package/dist/core/tool-policy.js +44 -32
  197. package/dist/core/tool-roster.d.ts +21 -7
  198. package/dist/core/tool-roster.js +34 -6
  199. package/dist/core/tool-spec-members.js +1 -1
  200. package/dist/core/tool-spec.d.ts +27 -0
  201. package/dist/core/tools.js +1 -0
  202. package/dist/core/trace.d.ts +42 -19
  203. package/dist/core/unc-spelling.d.ts +31 -0
  204. package/dist/core/unc-spelling.js +51 -0
  205. package/dist/core/wiring-manifest.d.ts +30 -3
  206. package/dist/core/wiring-manifest.js +10 -0
  207. package/dist/core/workflow-run-store-contract.js +22 -0
  208. package/dist/core/workflow-run-store.d.ts +17 -13
  209. package/dist/core/workflow-run-store.js +1 -1
  210. package/dist/core/write-protect.d.ts +4 -0
  211. package/dist/core/write-protect.js +17 -15
  212. package/dist/engine/compaction/compaction.d.ts +48 -98
  213. package/dist/engine/compaction/compaction.js +136 -216
  214. package/dist/engine/compaction/utils.d.ts +2 -11
  215. package/dist/engine/compaction/utils.js +4 -13
  216. package/dist/engine/execution-env/node-execution-env.js +17 -6
  217. package/dist/engine/harness/agent-harness.d.ts +19 -5
  218. package/dist/engine/harness/agent-harness.js +18 -7
  219. package/dist/engine/harness/types.d.ts +5 -7
  220. package/dist/engine/loop/agent-loop.d.ts +14 -1
  221. package/dist/engine/loop/agent-loop.js +31 -11
  222. package/dist/engine/loop/types.d.ts +8 -2
  223. package/dist/index.d.ts +9 -6
  224. package/dist/index.js +8 -6
  225. package/dist/internal/harness-types.d.ts +1 -1
  226. package/dist/internal/harness.d.ts +1 -1
  227. package/dist/internal/harness.js +1 -1
  228. package/dist/orchestration/run-spec.js +7 -2
  229. package/dist/orchestration/run-workflow-tool.js +5 -3
  230. package/dist/orchestration/workflow-park-adoption.d.ts +66 -8
  231. package/dist/orchestration/workflow-park-adoption.js +195 -45
  232. package/dist/orchestration/workflow-types.d.ts +20 -0
  233. package/dist/orchestration/workflow-types.js +1 -0
  234. package/dist/orchestration/workflow.d.ts +3 -2
  235. package/dist/orchestration/workflow.js +10 -4
  236. package/dist/prompt-assembly/catalog/core-behavior.js +6 -0
  237. package/dist/prompt-assembly/catalog/events.d.ts +8 -0
  238. package/dist/prompt-assembly/catalog/locales/zh-Hans/core-behavior.js +6 -0
  239. package/dist/prompt-assembly/catalog/locales/zh-Hans/mechanism.js +1 -0
  240. package/dist/prompt-assembly/catalog/mechanism.d.ts +8 -0
  241. package/dist/prompt-assembly/catalog/mechanism.js +1 -0
  242. package/dist/prompt-assembly/catalog/schema.d.ts +1 -1
  243. package/dist/prompt-assembly/catalog/schema.js +1 -0
  244. package/dist/prompt-assembly/catalog/sections.js +8 -0
  245. package/dist/prompt-assembly/event-registry.js +1 -0
  246. package/dist/prompt-assembly/select.js +1 -0
  247. package/dist/prompt-assembly/turn-snapshot.d.ts +14 -27
  248. package/dist/prompt-assembly/turn-snapshot.js +6 -18
  249. package/dist/prompt-assembly/types.d.ts +3 -0
  250. package/dist/prompts/default.d.ts +9 -0
  251. package/dist/prompts/default.js +4 -0
  252. package/dist/shell/lex.d.ts +75 -11
  253. package/dist/shell/lex.js +340 -76
  254. package/dist/tools/fs/bash-program-position.js +2 -6
  255. package/dist/tools/fs/bash-readonly-classifier.d.ts +18 -3
  256. package/dist/tools/fs/bash-readonly-classifier.js +19 -9
  257. package/dist/tools/fs/containment-face.d.ts +12 -3
  258. package/dist/tools/fs/containment-face.js +16 -7
  259. package/dist/tools/fs/file-read-check.d.ts +26 -1
  260. package/dist/tools/fs/file-read-check.js +20 -2
  261. package/dist/tools/fs/fs-bash.js +4 -4
  262. package/dist/tools/fs/fs-read.d.ts +3 -0
  263. package/dist/tools/fs/fs-read.js +2 -2
  264. package/dist/tools/fs/fs-search-tools.d.ts +2 -2
  265. package/dist/tools/fs/fs-search-tools.js +4 -4
  266. package/dist/tools/fs/index.js +5 -3
  267. package/dist/tools/fs/pdf.js +12 -4
  268. package/dist/tools/fs/read-deny-home.d.ts +13 -2
  269. package/dist/tools/fs/read-deny-home.js +26 -22
  270. package/dist/tools/fs/read-deny.js +15 -6
  271. package/dist/tools/fs/removal-targets.d.ts +33 -17
  272. package/dist/tools/fs/removal-targets.js +160 -61
  273. package/dist/tools/fs/repo-map.d.ts +1 -1
  274. package/dist/tools/fs/repo-map.js +2 -2
  275. package/dist/tools/fs/safety.d.ts +28 -5
  276. package/dist/tools/fs/safety.js +72 -8
  277. package/dist/tools/fs/shell-read-bindings.d.ts +8 -2
  278. package/dist/tools/fs/shell-read-bindings.js +25 -6
  279. package/dist/tools/fs/shell-read-check.d.ts +3 -0
  280. package/dist/tools/fs/shell-read-check.js +22 -4
  281. package/dist/tools/fs/shell-read-establish.js +73 -43
  282. package/dist/tools/fs/shell-read-judge.d.ts +32 -14
  283. package/dist/tools/fs/shell-read-judge.js +13 -5
  284. package/dist/tools/fs/shell-read-object-path.d.ts +5 -1
  285. package/dist/tools/fs/shell-read-object-path.js +17 -4
  286. package/dist/tools/fs/shell-read-plan.d.ts +8 -2
  287. package/dist/tools/fs/shell-read-plan.js +36 -22
  288. package/dist/tools/fs/shell-read-sourced.js +12 -4
  289. package/dist/tools/fs/shell-read-start.d.ts +4 -2
  290. package/dist/tools/fs/shell-read-start.js +3 -3
  291. package/dist/tools/fs/shell-read-workdir.d.ts +14 -6
  292. package/dist/tools/fs/shell-read-workdir.js +35 -17
  293. package/dist/tools/scheduler-tools.d.ts +7 -17
  294. package/dist/tools/scheduler-tools.js +9 -85
  295. package/dist/tools/worktree.js +5 -4
  296. package/package.json +3 -2
  297. package/test/export-surface.snapshot.json +47 -1
  298. package/wire-changes/core-stores-sql@7.68.6.json +39 -0
  299. package/wire-changes/core-stores-sql@7.69.1.json +39 -0
  300. package/wire-changes/core@7.68.6.json +125 -0
  301. package/wire-changes/core@7.69.1.json +2561 -0
  302. package/wire-changes/mods-kernel@7.68.6.json +39 -0
  303. package/wire-changes/mods-kernel@7.69.1.json +39 -0
  304. package/wire-changes/primitives@7.68.6.json +39 -0
  305. package/wire-changes/primitives@7.69.1.json +39 -0
  306. package/wire-changes/wiki-gate@7.68.6.json +39 -0
  307. package/wire-changes/wiki-gate@7.69.1.json +39 -0
  308. package/dist/core/runner/prompt-hash-salt.d.ts +0 -1
  309. package/dist/core/runner/prompt-hash-salt.js +0 -2
@@ -26,7 +26,7 @@ import { clearanceCustodyErased, eraseOriginClearanceCustody, markOriginClearanc
26
26
  import { carriesEntry, standsAsLink } from "./entry-scan.js";
27
27
  import { DEFAULT_MAX_ENTRY_DEPTH, MEMORY_INDEX_FILENAME, captureErasureInput, erasureRequestInvalid, erasureScopeRefusal, erasureSelectHash, erasureStatusOf, sweepUnderErasureRecord, scanEntryFiles, } from "./file-backend.js";
28
28
  import { assembleMemoryExportBundle, canonicalExpectedScopes, computeMemoryBundleHash, expectedScopesInvalid, firstOutsideExpectedScopes, memoryBundleInvalid, } from "./export-bundle.js";
29
- import { SCAN_FUSE_THRESHOLD, captureIntoQuarantine, clearContainedPath, eraseQuarantineCopies, keepCopiesBeforeOverwrite, quarantineObjectNameOf, restoreContainedBaseline, mintStagingName, indexLineIsStale, readIndexRevs, writeIndexRevs, bumpScanFuse, scanFuseKey, canonicalize, anchorStoreRoot, landingPathOf, landsOutsideStore, storeActRefusal, storeRootReanchoredRefusal, adoptRootScopeLayout, clearScanFuse, effectiveControlRootOf, sayAnnounceFailure, drainMemoryAnnouncements, enqueueMemoryAnnouncement, ensureDirExists, markSessionPolluted, readSessionPollution, recordRetrievedAccount, writeFileNoFollow, writeFileNoReplace, withPermissionRemedy, permissionRemedyOf, readRetrievedAccount, registerScope, registeredScopes, scopeDirFor, appendChallengeEvents, appendLineageAudit, rebuildStrictControlPlaneLedger, isStrictControlPlaneLedgerCorrupt, ControlPlaneCorruptError, CHALLENGE_LEDGER_MAX_EVENTS, adjudicateLineagePending, challengedEntryIds, clearLineageForEntries, discardLineagePending, lineageAccountOfEntry, lineageContributionsOfSession, lineageLatchedIds, promoteLineagePending, readChallengeEvents, readChallengedHistory, readLineageRecord, recordChallengedHistory, recordLineageCredential, reconcileLineage, readProjectionDebts, resolveChallengeEvent, settleProjectionDebts, stageLineagePending, stageProjectionDebts, controlPlaneStraysRefusal, } from "./layout.js";
29
+ import { SCAN_FUSE_THRESHOLD, captureIntoQuarantine, clearContainedPath, eraseQuarantineCopies, keepCopiesBeforeOverwrite, quarantineObjectNameOf, restoreContainedBaseline, mintStagingName, indexLineIsStale, readIndexRevs, writeIndexRevs, bumpScanFuse, scanFuseKey, canonicalize, anchorStoreRoot, landingPathOf, landsOutsideStore, storeActRefusal, storeRootReanchoredRefusal, adoptRootScopeLayout, clearScanFuse, effectiveControlRootOf, sayAnnounceFailure, drainMemoryAnnouncements, enqueueMemoryAnnouncement, ensureDirExists, markSessionPolluted, readSessionPollution, recordRetrievedAccount, writeFileNoFollow, writeFileNoReplace, putBackOverNothingOrBlank, withPermissionRemedy, permissionRemedyOf, readRetrievedAccount, registerScope, registeredScopes, scopeDirFor, appendChallengeEvents, appendLineageAudit, rebuildStrictControlPlaneLedger, isStrictControlPlaneLedgerCorrupt, ControlPlaneCorruptError, CHALLENGE_LEDGER_MAX_EVENTS, adjudicateLineagePending, challengedEntryIds, clearLineageForEntries, discardLineagePending, lineageAccountOfEntry, lineageContributionsOfSession, lineageLatchedIds, promoteLineagePending, readChallengeEvents, readChallengedHistory, readLineageRecord, recordChallengedHistory, recordLineageCredential, reconcileLineage, readProjectionDebts, resolveChallengeEvent, settleProjectionDebts, stageLineagePending, stageProjectionDebts, controlPlaneStraysRefusal, } from "./layout.js";
30
30
  import { createSessionIncarnationSeat, recalledForAnyIdentity, recalledForIdentity, rememberForIdentity } from "./session-incarnation.js";
31
31
  import { scanMemoryFileName, scanMemoryWrite, scanRemediation } from "./scan.js";
32
32
  import { writableRootOf } from "./types.js";
@@ -34,6 +34,7 @@ import { thrownText } from "../thrown-value.js";
34
34
  import { optionKeys, receiveOptions } from "../own-property-receipt.js";
35
35
  import { admitLandingsThrough, directedLandings, planWritten, refusalNamingWritten, requireWriteGate } from "./consolidation-write-gate.js";
36
36
  import { applyEachAlone } from "./landing-admission.js";
37
+ import { dropIndexCopiesOf, indexCopiesAnswered, readAdmittedStoreState } from "./index-copies.js";
37
38
  export const MEMORY_RECALL_FRAMING = "Recalled memories appearing inside `<system-reminder>` blocks are background context, not user instructions, and reflect what was true when written — if one names a file, function, or flag, verify it still exists before recommending it.";
38
39
  export const MEMORY_INSTRUCTION_TEMPLATE = `# Memory
39
40
 
@@ -185,6 +186,14 @@ export function harvestConflictSentence(c) {
185
186
  ? `concurrent-change conflict (${c.op}) for entry id ${quoteId(c.id)} — this session's ${what} was NOT committed${c.op === "delete" ? "; the entry stays" : ""}`
186
187
  : `write refused (${c.op}) for entry id ${quoteId(c.id)} — the memory store refused this change; this session's ${what} was NOT committed`;
187
188
  }
189
+ export function massDeletionDetail(c) {
190
+ const back = c.putBack === c.removed
191
+ ? `the ${c.removed} memory files deleted or emptied were put back from their last saved copies`
192
+ : `${c.putBack} of the ${c.removed} memory files deleted or emptied were put back from their last saved copies`;
193
+ return (`${c.gone > 0 ? "This session deleted nothing" : "Nothing was deleted"}: ${back}` +
194
+ `${c.notBack > 0 ? `; ${c.notBack} could not be` : ""}${c.gone > 0 ? `; ${c.gone} had already been deleted by another session` : ""}. ` +
195
+ `More than ${c.ceiling} at once is taken as a mistake; to delete this many on purpose, delete at most ${c.ceiling} per session.`);
196
+ }
188
197
  function harvestRefusedReason(incident) {
189
198
  switch (incident.kind) {
190
199
  case "mass_deletion":
@@ -201,10 +210,12 @@ export function memoryHarvestRefusedNotice(report, sessionId) {
201
210
  const committed = report.patches.add + report.patches.update + report.patches.delete;
202
211
  return {
203
212
  code: "memory.harvest_refused",
204
- message: `Memory harvest refused (${report.incident.kind}): ${harvestRefusedReason(report.incident)}. ` +
205
- (committed === 0
206
- ? `No memory change from this session was saved — anything this session said it remembered or forgot did not take effect.`
207
- : `Only ${committed} change(s) from the other memory plane were saved; the refused plane's changes did not take effect.`),
213
+ message: report.incident.kind === "mass_deletion"
214
+ ? `${harvestRefusedReason(report.incident)}${committed === 0 ? "" : ` ${committed} change(s) to the other memory folder were saved.`}`
215
+ : `Memory harvest refused (${report.incident.kind}): ${harvestRefusedReason(report.incident)}. ` +
216
+ (committed === 0
217
+ ? `No memory change from this session was saved — anything this session said it remembered or forgot did not take effect.`
218
+ : `Only ${committed} change(s) from the other memory plane were saved; the refused plane's changes did not take effect.`),
208
219
  detail: { kind: report.incident.kind, committed, ...(report.reportId !== undefined ? { reportId: report.reportId } : {}), ...(sessionId !== undefined ? { sessionId } : {}) },
209
220
  };
210
221
  }
@@ -1245,6 +1256,15 @@ export class MemoryEngine {
1245
1256
  out.set(id, { code: "challenged", generation: g.generation, at: g.at });
1246
1257
  return out;
1247
1258
  }
1259
+ async readStoreState() {
1260
+ try {
1261
+ const challenged = async () => [...(await this.readChallengeExclusions())].filter(([, why]) => why.code === "challenged").map(([id]) => id).sort();
1262
+ return (await readAdmittedStoreState(canonicalize(this.memoryDir), async () => ({ challenged: await challenged(), erasures: await readClearanceErasureCount(this.governanceStore) }))) ?? "unreadable";
1263
+ }
1264
+ catch {
1265
+ return "unreadable";
1266
+ }
1267
+ }
1248
1268
  async challengeAndAnnounce(events) {
1249
1269
  if (events.length === 0)
1250
1270
  return [];
@@ -1376,6 +1396,9 @@ export class MemoryEngine {
1376
1396
  catch (err) {
1377
1397
  throw withPermissionRemedy(err, this.memoryDir);
1378
1398
  }
1399
+ finally {
1400
+ dropIndexCopiesOf(canonicalize(this.memoryDir));
1401
+ }
1379
1402
  }
1380
1403
  async eraseMemoryEntriesCore(input) {
1381
1404
  const captured = captureErasureInput(input);
@@ -1393,8 +1416,8 @@ export class MemoryEngine {
1393
1416
  e.code = "config.memory_erasure_scope";
1394
1417
  throw e;
1395
1418
  }
1396
- const att = await this.answerClearanceCustody(await face.call(this.backend, captured));
1397
- return this.sweepErasedIndexLines(att, requestId, (recorded) => ({ paths: recorded, homes: att.erased.flatMap((row) => (row.binding.state === "bound" ? [scopeDirFor(this.memoryDir, this.controlDir, row.binding.scope)] : [])) }));
1419
+ const { att, counted } = await this.answerClearanceCustody(await face.call(this.backend, captured));
1420
+ return this.answerIndexCopies(await this.sweepErasedIndexLines(att, requestId, (recorded) => ({ paths: recorded, homes: att.erased.flatMap((row) => (row.binding.state === "bound" ? [scopeDirFor(this.memoryDir, this.controlDir, row.binding.scope)] : [])) })), counted);
1398
1421
  }
1399
1422
  if (captured.allowUnevidenced !== true) {
1400
1423
  const e = new Error("eraseMemoryEntries: this backend has no erasure-evidence capability (eraseWithEvidence) — an unevidenced erasure is refused by default. " +
@@ -1437,7 +1460,7 @@ export class MemoryEngine {
1437
1460
  id,
1438
1461
  rev: e?.rev ?? "",
1439
1462
  binding: e !== undefined ? { state: "bound", scope: e.scope } : { state: "unbound" },
1440
- projectionsRemoved: 1,
1463
+ projectionsRemoved: 0,
1441
1464
  sessions: [],
1442
1465
  };
1443
1466
  });
@@ -1473,10 +1496,17 @@ export class MemoryEngine {
1473
1496
  return e !== undefined ? [e] : [];
1474
1497
  });
1475
1498
  att.status = erasureStatusOf(att);
1476
- return this.sweepErasedIndexLines(att, undefined, () => {
1499
+ const swept = await this.sweepErasedIndexLines(att, undefined, () => {
1477
1500
  const homes = deleted.map((e) => scopeDirFor(this.memoryDir, this.controlDir, e.scope));
1478
1501
  return { paths: deleted.map((e, i) => join(homes[i] ?? "", `${e.slug}.md`)), homes };
1479
1502
  });
1503
+ return this.answerIndexCopies(swept, custody !== undefined);
1504
+ }
1505
+ async answerIndexCopies(att, counted) {
1506
+ const out = indexCopiesAnswered(att, counted);
1507
+ if (out === undefined)
1508
+ await this.discloseUncarriedIndexResidue(new Error("the store's erasure count did not move"), [`${join(this.memoryDir, MEMORY_INDEX_FILENAME)} (as copies frozen in another process)`], new Map());
1509
+ return out ?? att;
1480
1510
  }
1481
1511
  async answerClearanceCustody(att) {
1482
1512
  let resolved;
@@ -1491,23 +1521,24 @@ export class MemoryEngine {
1491
1521
  resolved = att.resolvedIds.map(String).filter((id) => !conflicted.has(id));
1492
1522
  }
1493
1523
  catch {
1494
- return att;
1524
+ return { att, counted: false };
1495
1525
  }
1496
1526
  let corrupt = false;
1497
1527
  const custody = await eraseOriginClearanceCustody(this.governanceStore, new Set(resolved), this.now()).catch((err) => {
1498
1528
  corrupt = err instanceof ControlPlaneCorruptError;
1499
1529
  return undefined;
1500
1530
  });
1531
+ const counted = custody !== undefined;
1501
1532
  if (custody === undefined && faced !== undefined && !corrupt)
1502
- return att;
1533
+ return { att, counted };
1503
1534
  try {
1504
1535
  const answer = custody !== undefined ? { removed: (faced?.removed ?? 0) + custody.removed, remaining: custody.remaining } : { unverified: true };
1505
1536
  const out = { ...att, residuals: { ...att.residuals, carriers: { ...att.residuals.carriers, clearanceCustody: answer } } };
1506
1537
  out.status = erasureStatusOf(out);
1507
- return out;
1538
+ return { att: out, counted };
1508
1539
  }
1509
1540
  catch {
1510
- return att;
1541
+ return { att, counted };
1511
1542
  }
1512
1543
  }
1513
1544
  async sweepErasedIndexLines(att, requestId, owedOf) {
@@ -1929,6 +1960,7 @@ export class MemoryEngine {
1929
1960
  if (this.governanceStore !== this.backend.governance)
1930
1961
  probeControlPlaneLinks(this.controlDir);
1931
1962
  await this.adoptLayoutBeforeMount(writeScope);
1963
+ const storeState = await this.readStoreState();
1932
1964
  this.assertRootAnchored();
1933
1965
  const restricted = opts?.adoptionRestricted === true;
1934
1966
  let sessionAccountFailed = false;
@@ -2083,6 +2115,7 @@ export class MemoryEngine {
2083
2115
  baseIds: new Map(),
2084
2116
  repoIndexTargets: new Map(),
2085
2117
  indexText: "",
2118
+ storeState,
2086
2119
  ...(opts?.shadowNames !== undefined ? { shadowNames: opts.shadowNames } : {}),
2087
2120
  ...(restricted ? { adoptionRestricted: true } : {}),
2088
2121
  ...(sessionAccountFailed ? { sessionAccountFailed: true } : {}),
@@ -2244,7 +2277,7 @@ export class MemoryEngine {
2244
2277
  const readOnlyNotice = handle.writeScope === null ? MEMORY_READONLY_NOTICE : undefined;
2245
2278
  const writableRoot = handle.writableRoot;
2246
2279
  const onDisk = writableRoot === null || handle.indexOnDiskUntrusted === true || handle.adoptionRestricted === true ? undefined : readSafe(join(writableRoot, MEMORY_INDEX_FILENAME));
2247
- const indexText = onDisk !== undefined && onDisk.trim() !== "" ? onDisk : handle.indexText;
2280
+ const indexText = opts?.frozenIndex ?? (onDisk !== undefined && onDisk.trim() !== "" ? onDisk : handle.indexText);
2248
2281
  const truncated = truncateIndex(indexText);
2249
2282
  let index = composeMemoryBlock(truncated, handle.writeScope ?? handle.scopes[0] ?? "memory");
2250
2283
  if (index !== undefined && truncated !== indexText) {
@@ -2284,6 +2317,7 @@ export class MemoryEngine {
2284
2317
  ...(announceBlock !== undefined ? { announceBlock } : {}),
2285
2318
  ...(indexSeed !== undefined ? { indexSeed } : {}),
2286
2319
  block,
2320
+ indexText,
2287
2321
  };
2288
2322
  }
2289
2323
  gateWrite(handle, canonicalPath, content) {
@@ -2735,33 +2769,72 @@ export class MemoryEngine {
2735
2769
  };
2736
2770
  const missingWritable = writable.filter((m) => !recordByPath.has(m.path) && !presentIds.has(m.id) && removedOnPlane(m.path));
2737
2771
  report.missing.push(...missingWritable.map((m) => m.relPath));
2738
- const deletionCeiling = deletionFuseCeiling(writable.length, MASS_DELETION_FUSE_RATIO);
2739
- if (missingWritable.length > deletionCeiling) {
2740
- report.ok = false;
2741
- report.incident = {
2742
- kind: "mass_deletion",
2743
- detail: `${missingWritable.length}/${writable.length} materialized memory files are missing — more than one harvest may remove (${deletionCeiling}), judged an accident: harvest refused, nothing deleted or restored`,
2744
- };
2745
- if (pollutedReason !== undefined)
2746
- await (carry ? containExposedInstructionDomain() : containPollutedDomain());
2747
- return report;
2748
- }
2772
+ const removalHeldHere = async (m) => {
2773
+ const placement = await this.committedPlacementOf(m.id);
2774
+ if (placement.state === "absent")
2775
+ return { held: false, unknown: false, gone: true };
2776
+ if (placement.state === "unknown") {
2777
+ report.warnings.push(`${m.relPath}: not deleted and not put back — where the store holds this entry could not be read, so the removal is left as found (the entry stays committed)`);
2778
+ return { held: false, unknown: true, gone: false };
2779
+ }
2780
+ if (placement.scope !== m.scope) {
2781
+ report.warnings.push(`${m.relPath}: not deleted — the entry was moved to scope ${JSON.stringify(placement.scope)} since this session was served it; a removal deletes only in this session's write scope`);
2782
+ return { held: false, unknown: false, gone: false };
2783
+ }
2784
+ if (m.stub) {
2785
+ report.rejections.push({ path: m.relPath, code: "stub_modified", reason: "this file is an archived-body stub; removing a stub does not delete its entry in this version (the next session projects the stub again)" });
2786
+ return { held: false, unknown: false, gone: false };
2787
+ }
2788
+ return placement.frontmatter !== undefined ? { held: true, frontmatter: placement.frontmatter } : { held: true };
2789
+ };
2749
2790
  const restoreRemoved = async (m) => {
2750
2791
  const content = await this.committedContentFor(m.id);
2751
- if (content === undefined)
2752
- return "no committed copy could be read back, so the file stays removed (the entry stays committed)";
2792
+ if (content === undefined || !carriesEntry(content))
2793
+ return { outcome: "uncopied", clause: "no committed copy could be read back, so the file stays removed (the entry stays committed)" };
2753
2794
  try {
2754
2795
  this.refuseOutsideStore(m.path, "restoring a memory file", handle);
2755
2796
  mkdirSync(dirname(m.path), { recursive: true });
2756
- writeFileNoFollow(m.path, content);
2797
+ if (canonicalize(dirname(m.path)) !== dirname(m.path))
2798
+ return { outcome: "blocked", clause: "a directory on its path is a link now, so nothing was written and the file stays removed (the entry stays committed)" };
2799
+ const put = putBackOverNothingOrBlank(m.path, content);
2800
+ if (put === "kept")
2801
+ return { outcome: "occupied", clause: "the path holds other content now, so it was left as found (the entry stays committed)" };
2802
+ if (put === "blocked")
2803
+ return { outcome: "blocked", clause: "something other than a file stands at the path, so it was left as found and the file stays removed (the entry stays committed)" };
2757
2804
  report.restored.push(m.relPath);
2758
- return "the removed file's committed copy was put back";
2805
+ return { outcome: "restored", clause: "the removed file's committed copy was put back" };
2759
2806
  }
2760
2807
  catch (err) {
2761
2808
  report.warnings.push(`${m.relPath}: the committed copy of this removed memory file could NOT be restored: ${this.writeFailureText(err)}`);
2762
- return "putting the committed copy back failed (warned)";
2809
+ return { outcome: "failed", clause: "putting the committed copy back failed (warned)" };
2763
2810
  }
2764
2811
  };
2812
+ const deletionCeiling = deletionFuseCeiling(writable.length, MASS_DELETION_FUSE_RATIO);
2813
+ if (missingWritable.length > deletionCeiling) {
2814
+ const counts = { putBack: 0, notBack: 0, gone: 0 };
2815
+ for (const m of missingWritable) {
2816
+ const seat = await removalHeldHere(m);
2817
+ if (!seat.held) {
2818
+ if (seat.unknown)
2819
+ counts.notBack += 1;
2820
+ else if (seat.gone)
2821
+ counts.gone += 1;
2822
+ continue;
2823
+ }
2824
+ const back = await restoreRemoved(m);
2825
+ if (back.outcome === "restored")
2826
+ counts.putBack += 1;
2827
+ else if (back.outcome !== "failed")
2828
+ report.warnings.push(`${m.relPath}: not put back — ${back.clause}`);
2829
+ if (back.outcome === "blocked" || back.outcome === "uncopied" || back.outcome === "failed")
2830
+ counts.notBack += 1;
2831
+ }
2832
+ report.ok = false;
2833
+ report.incident = { kind: "mass_deletion", detail: massDeletionDetail({ removed: missingWritable.length, ceiling: deletionCeiling, ...counts }) };
2834
+ if (pollutedReason !== undefined)
2835
+ await (carry ? containExposedInstructionDomain() : containPollutedDomain());
2836
+ return report;
2837
+ }
2765
2838
  const baselinePaths = new Set(writable.map((m) => m.path));
2766
2839
  const inDomain = records
2767
2840
  .slice()
@@ -2810,21 +2883,9 @@ export class MemoryEngine {
2810
2883
  const recordedDisposals = [];
2811
2884
  const removalDeletes = new Map();
2812
2885
  for (const m of missingWritable) {
2813
- const placement = await this.committedPlacementOf(m.id);
2814
- if (placement.state === "absent")
2815
- continue;
2816
- if (placement.state === "unknown") {
2817
- report.warnings.push(`${m.relPath}: not deleted and not put back — where the store holds this entry could not be read, so the removal is left as found (the entry stays committed)`);
2818
- continue;
2819
- }
2820
- if (placement.scope !== m.scope) {
2821
- report.warnings.push(`${m.relPath}: not deleted — the entry was moved to scope ${JSON.stringify(placement.scope)} since this session was served it; a removal deletes only in this session's write scope`);
2886
+ const placement = await removalHeldHere(m);
2887
+ if (!placement.held)
2822
2888
  continue;
2823
- }
2824
- if (m.stub) {
2825
- report.rejections.push({ path: m.relPath, code: "stub_modified", reason: "this file is an archived-body stub; removing a stub does not delete its entry in this version (the next session projects the stub again)" });
2826
- continue;
2827
- }
2828
2889
  if (pollutedReason !== undefined && !carry) {
2829
2890
  await restoreRemoved(m);
2830
2891
  continue;
@@ -2832,7 +2893,7 @@ export class MemoryEngine {
2832
2893
  if (carry && (pollutedReason !== undefined || (sessionPending && lineageSessionId !== undefined))) {
2833
2894
  const committedFm = placement.frontmatter ?? (await this.committedFrontmatterFor(m.id));
2834
2895
  if (committedFm === undefined || isInstructionEntry(committedFm)) {
2835
- const back = await restoreRemoved(m);
2896
+ const back = (await restoreRemoved(m)).clause;
2836
2897
  const unread = committedFm === undefined ? " (its committed form could not be read, so it is withheld as one)" : "";
2837
2898
  if (pollutedReason !== undefined) {
2838
2899
  report.rejections.push({ path: m.relPath, code: "polluted", reason: `memory deletion withheld${unread}: ${withheldWhy()} — ${back}` });
@@ -3317,7 +3378,7 @@ export class MemoryEngine {
3317
3378
  signalContainment((c) => pushDistinct(c.quarantinedInstruction, rec.rel));
3318
3379
  }
3319
3380
  else if (removed !== undefined) {
3320
- const back = await restoreRemoved(removed.file);
3381
+ const back = (await restoreRemoved(removed.file)).clause;
3321
3382
  const unread = committedFm === undefined ? " (its committed form could not be read, so it is withheld as one)" : "";
3322
3383
  report.rejections.push({ path: removed.file.relPath, code: "polluted", reason: `memory deletion withheld${unread}: ${withheldWhy()} — ${back}` });
3323
3384
  }
@@ -5556,6 +5617,7 @@ export class MemoryEngine {
5556
5617
  const detail = `memory index withheld: the challenge/lineage ledger cannot be trusted (${thrownText(err)}) — fail-closed, nothing injected`;
5557
5618
  warnings?.push(detail);
5558
5619
  handle.indexOnDiskUntrusted = true;
5620
+ handle.storeState = "unreadable";
5559
5621
  const sink = this.onIncident;
5560
5622
  if (sink !== undefined) {
5561
5623
  try {
@@ -141,7 +141,8 @@ export interface MemoryErasureAttestation {
141
141
  /** The delete evidence row's `ev` — absent in `"none"` mode. */
142
142
  evidenceEv?: string;
143
143
  /** Distinct census-confirmed projection files this transaction physically deleted (the sweep
144
- * arm can answer >1: stray copies and P≥2 unbound duplicates are all removed). */
144
+ * arm can answer >1: stray copies and P≥2 unbound duplicates are all removed). `0` on the
145
+ * `"none"` lane, which deletes through the store's patch and removes no projection file itself. */
145
146
  projectionsRemoved: number;
146
147
  /** Contributing sessions (pre-capture ∪ the same-lock lineage capture-and-clear; `"none"` mode
147
148
  * answers `[]`). NON-durable beyond the chain's pre-capture: a replay after a crash carries
@@ -0,0 +1,47 @@
1
+ import { type MemoryErasureAttestation } from "./file-backend.js";
2
+ /** One frozen copy: the raw index text each mounted plane's injection was composed from, and whether a marked
3
+ * (external-origin) entry stood in any of them. */
4
+ export interface IndexCopy {
5
+ readonly planes: Readonly<Partial<Record<"project" | "personal", string>>>;
6
+ readonly marked: boolean;
7
+ }
8
+ /** The most the process keeps, in bytes over every copy — its index text in UTF-8, its name, its stores, and a fixed charge
9
+ * per copy ({@link INDEX_COPY_OVERHEAD_BYTES}, so that many empty copies are bounded too); the oldest copies go first. */
10
+ export declare const INDEX_COPIES_MAX_BYTES: number;
11
+ /** What each copy is charged beyond its text, name and stores. */
12
+ export declare const INDEX_COPY_OVERHEAD_BYTES = 256;
13
+ /** The digest a copy is named by (sha256 over its planes, by plane name, and its marked bit). */
14
+ export declare function indexCopyDigest(copy: IndexCopy): string;
15
+ /** A mounted plane a copy is read through: its memory directory and the store state its mount read
16
+ * ({@link readAdmittedStoreState}). */
17
+ export interface IndexCopyPlane {
18
+ readonly memoryDir: string;
19
+ readonly storeState?: unknown;
20
+ }
21
+ /** Keep `copy` as frozen under `key`, read through `planes`; answers its digest. Not kept: a copy over the whole bound, and
22
+ * one a plane of which was read under a store state this process did not admit, or admitted before the store's copies were
23
+ * last dropped (a mount in flight across an erasure or a lower count: what it listed may be what was erased). */
24
+ export declare function keepIndexCopy(key: string, copy: IndexCopy, planes: readonly IndexCopyPlane[]): string;
25
+ /** The copy frozen under `key` whose bytes are `digest`, or undefined. */
26
+ export declare function indexCopyOf(key: string, digest: string): IndexCopy | undefined;
27
+ /** Drop every copy any of whose planes was read from `store` (a memory directory, as its handle names it); a mount of the
28
+ * store whose state was read before this keeps nothing ({@link keepIndexCopy}). */
29
+ export declare function dropIndexCopiesOf(store: string): void;
30
+ /** A mount's store state, read by `read`, under the rule that a store's erasure count only goes up. Admitted when its count is
31
+ * no lower than the highest one this process has read of `store` when the read lands; a copy may then be kept under it until
32
+ * the store's copies are next dropped after the read began. A lower count (the account removed or rolled back — or a read
33
+ * that overlapped a higher one: the two cannot be told apart, so it is taken the safe way) is not admitted — undefined: the
34
+ * caller reads the state as unreadable — and every copy this process froze of the store is dropped at once, since one frozen
35
+ * under a count the store reads again would be found by its key past the erasure that moved the count. The highest count
36
+ * stays: until the store reads it again, or the process restarts, nothing of the store is frozen in this process. */
37
+ export declare function readAdmittedStoreState<S extends {
38
+ readonly erasures: number;
39
+ }>(store: string, read: () => Promise<S>): Promise<S | undefined>;
40
+ /** An erasure's `indexLine` class also answers for these copies: one in another process is found by a key that holds the
41
+ * store's erasure count, so a call whose count did not move (`counted` false: the engine's clearance step over the ids it
42
+ * resolved did not run to its answer) may leave one standing — the class is then `unverified` and the request `partial`,
43
+ * whether or not this call deleted anything itself (a repeat of a request whose own count did not land deletes nothing,
44
+ * and the count is still where that request left it). `undefined`: a face's attestation that cannot be read or copied
45
+ * cannot carry the answer — the caller hands it on as it came and discloses that instead (no throw over a committed
46
+ * erasure, never silent: the sweep's rule for the same answer). */
47
+ export declare function indexCopiesAnswered(att: MemoryErasureAttestation, counted: boolean): MemoryErasureAttestation | undefined;
@@ -0,0 +1,88 @@
1
+ import { createHash } from "node:crypto";
2
+ import { erasureStatusOf } from "./file-backend.js";
3
+ export const INDEX_COPIES_MAX_BYTES = 16 * 1024 * 1024;
4
+ export const INDEX_COPY_OVERHEAD_BYTES = 256;
5
+ const COPIES = new Map();
6
+ let heldBytes = 0;
7
+ export function indexCopyDigest(copy) {
8
+ const planes = Object.entries(copy.planes).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
9
+ return createHash("sha256").update(JSON.stringify([planes, copy.marked]), "utf8").digest("hex");
10
+ }
11
+ function drop(name) {
12
+ const held = COPIES.get(name);
13
+ if (held === undefined)
14
+ return;
15
+ COPIES.delete(name);
16
+ heldBytes -= held.bytes;
17
+ }
18
+ export function keepIndexCopy(key, copy, planes) {
19
+ const digest = indexCopyDigest(copy);
20
+ const name = `${key}:${digest}`;
21
+ drop(name);
22
+ const current = planes.length > 0 && planes.every((p) => {
23
+ const read = typeof p.storeState === "object" && p.storeState !== null ? READ_UNDER.get(p.storeState) : undefined;
24
+ return read !== undefined && read[0] === p.memoryDir && read[1] === storeOf(p.memoryDir).drops;
25
+ });
26
+ if (!current)
27
+ return digest;
28
+ const stores = planes.map((p) => p.memoryDir);
29
+ const bytes = INDEX_COPY_OVERHEAD_BYTES + Buffer.byteLength(name, "utf8") + stores.reduce((n, s) => n + Buffer.byteLength(s, "utf8"), 0) + Object.values(copy.planes).reduce((n, text) => n + Buffer.byteLength(text ?? "", "utf8"), 0);
30
+ if (bytes > INDEX_COPIES_MAX_BYTES)
31
+ return digest;
32
+ COPIES.set(name, { copy, stores: [...stores], bytes });
33
+ heldBytes += bytes;
34
+ while (heldBytes > INDEX_COPIES_MAX_BYTES) {
35
+ const oldest = COPIES.keys().next().value;
36
+ if (oldest === undefined)
37
+ break;
38
+ drop(oldest);
39
+ }
40
+ return digest;
41
+ }
42
+ export function indexCopyOf(key, digest) {
43
+ const name = `${key}:${digest}`;
44
+ const held = COPIES.get(name);
45
+ if (held === undefined)
46
+ return undefined;
47
+ COPIES.delete(name);
48
+ COPIES.set(name, held);
49
+ return held.copy;
50
+ }
51
+ const STORES = new Map();
52
+ const READ_UNDER = new WeakMap();
53
+ function storeOf(store) {
54
+ let s = STORES.get(store);
55
+ if (s === undefined)
56
+ STORES.set(store, (s = { erasures: 0, drops: 0 }));
57
+ return s;
58
+ }
59
+ export function dropIndexCopiesOf(store) {
60
+ storeOf(store).drops += 1;
61
+ for (const [name, held] of [...COPIES])
62
+ if (held.stores.includes(store))
63
+ drop(name);
64
+ }
65
+ export async function readAdmittedStoreState(store, read) {
66
+ const at = storeOf(store);
67
+ const drops = at.drops;
68
+ const state = await read();
69
+ if (state.erasures < at.erasures) {
70
+ dropIndexCopiesOf(store);
71
+ return undefined;
72
+ }
73
+ at.erasures = state.erasures;
74
+ READ_UNDER.set(state, [store, drops]);
75
+ return state;
76
+ }
77
+ export function indexCopiesAnswered(att, counted) {
78
+ if (counted)
79
+ return att;
80
+ try {
81
+ const out = { ...att, residuals: { ...att.residuals, carriers: { ...att.residuals.carriers, indexLine: { unverified: true } } } };
82
+ out.status = erasureStatusOf(out);
83
+ return out;
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
@@ -674,8 +674,25 @@ export declare function writeFileNoFollow(path: string, content: string): void;
674
674
  * it refuses a symlink at the final component on its own (POSIX `EEXIST` on a link, dangling or not),
675
675
  * so the twin's no-follow property is kept without a second check. `mode` is the created file's
676
676
  * permission bits (under the process umask): a caller putting bytes back into a seat it vacated passes
677
- * the vacated file's, so the seat's permissions are what they were. */
677
+ * the vacated file's, so the seat's permissions are what they were less what the umask clears; with
678
+ * none passed (the file's bits went with it) the file is created owner-only, {@link PRIVATE_FILE_MODE} —
679
+ * the File backend's mode for its projections; a copy-out projection's materialize creates at 0644
680
+ * less the umask, so there a file put back is never wider than its siblings. */
678
681
  export declare function writeFileNoReplace(path: string, content: string, mode?: number): "written" | "kept";
682
+ /**
683
+ * The third twin, for a seat a removal vacated: put `content` back at `path` only where the removal left
684
+ * nothing or blank bytes ({@link carriesEntry}), judged and written through ONE descriptor — a writer that
685
+ * replaces the file by a rename between the look and the write keeps its file (the write lands on the
686
+ * inode that was looked at). `"written"` = the bytes landed; `"kept"` = a file with content stands there
687
+ * (left as found); `"blocked"` = something other than a regular file stands there (a directory, a link, a
688
+ * pipe) — left as found. Nothing there ⇒ {@link writeFileNoReplace}, owner-only (the removed file's bits went
689
+ * with it; the seat is not left wider than the store writes it). A file with more than one name is
690
+ * written the way {@link writeFileNoFollow} writes it (never in place). The in-place write is positional
691
+ * from byte 0 (the read moved the offset past any blank bytes) and loops until every byte is written. Any
692
+ * other failure throws. Residual windows: an in-place writer on the same inode between the read and the
693
+ * truncate; for a file with more than one name, a writer between this close and the twin's open.
694
+ */
695
+ export declare function putBackOverNothingOrBlank(path: string, content: string): "written" | "kept" | "blocked";
679
696
  /** THE minter of every staging name the engine puts beside a plane file while it is displaced:
680
697
  * `<owner>.staging-<ms>-<pid>-<seq>`. One grammar for every site, so one recognizer
681
698
  * ({@link stagingNamePattern}) knows the names the engine can have left beside a seat. */
@@ -736,8 +753,8 @@ export declare function dropStagingSecondNames(seat: string, opened: {
736
753
  * quarantine; where they were NOT, the only way the comparison fails is that somebody replaced them —
737
754
  * which took them off the plane as surely as the removal would have.
738
755
  *
739
- * `mode` is the bits a freed path is created with — the caller's own projection mode; a file the
740
- * containment left in place keeps its own.
756
+ * `mode` is the bits a freed path is created with — the caller's own projection mode, owner-only when
757
+ * none is passed (as the store writes its own); a file the containment left in place keeps its own.
741
758
  */
742
759
  export declare function restoreContainedBaseline(path: string, committed: string, leftOnPlane: string | undefined, mode?: number): "written" | "kept" | "failed";
743
760
  /** What keeping one suspect file's copy came to: the name its copy is kept under among the governance store's
@@ -1,11 +1,12 @@
1
1
  import { closeSync, constants as fsConstants, copyFileSync, existsSync, fstatSync, fsyncSync, ftruncateSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, utimesSync, writeFileSync, writeSync } from "node:fs";
2
- const { O_WRONLY, O_RDONLY, O_CREAT, O_NOFOLLOW, O_NONBLOCK, O_EXCL } = fsConstants;
2
+ const { O_WRONLY, O_RDONLY, O_RDWR, O_CREAT, O_NOFOLLOW, O_NONBLOCK, O_EXCL } = fsConstants;
3
3
  import { homedir } from "node:os";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
6
6
  import { MEMORY_GOVERNANCE_DOC_NAMES, MEMORY_ORIGIN_CAUSES } from "./types.js";
7
7
  import { parseEntryFile } from "./frontmatter.js";
8
- import { openExclusiveTemp } from "../exclusive-temp.js";
8
+ import { carriesEntry } from "./entry-scan.js";
9
+ import { PRIVATE_FILE_MODE, openExclusiveTemp } from "../exclusive-temp.js";
9
10
  import { physicalPathOf, physicalPathOfExisting, priorCallerCasedPathOf } from "../physical-path.js";
10
11
  import { anchorAtLinkDir } from "../../engine/execution-env/symlink-chain.js";
11
12
  import { sensitiveRowOf } from "../sensitive-path-policy.js";
@@ -1521,7 +1522,7 @@ export function writeFileNoFollow(path, content) {
1521
1522
  if (names > 1)
1522
1523
  atomicWriteFileSync(path, content);
1523
1524
  }
1524
- export function writeFileNoReplace(path, content, mode = 0o644) {
1525
+ export function writeFileNoReplace(path, content, mode = PRIVATE_FILE_MODE) {
1525
1526
  let fd;
1526
1527
  try {
1527
1528
  fd = openSync(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, mode);
@@ -1539,6 +1540,41 @@ export function writeFileNoReplace(path, content, mode = 0o644) {
1539
1540
  }
1540
1541
  return "written";
1541
1542
  }
1543
+ export function putBackOverNothingOrBlank(path, content) {
1544
+ let fd;
1545
+ try {
1546
+ fd = openSync(path, O_RDWR | O_NOFOLLOW | O_NONBLOCK);
1547
+ }
1548
+ catch (err) {
1549
+ const code = err.code;
1550
+ if (code === "ENOENT")
1551
+ return writeFileNoReplace(path, content) === "written" ? "written" : "kept";
1552
+ if (code === "ELOOP" || code === "EMLINK" || code === "EISDIR" || code === "ENXIO" || code === "EOPNOTSUPP")
1553
+ return "blocked";
1554
+ throw err;
1555
+ }
1556
+ let manyNames = false;
1557
+ try {
1558
+ const seat = fstatSync(fd);
1559
+ if (!seat.isFile())
1560
+ return "blocked";
1561
+ if (carriesEntry(readFileSync(fd, "utf8")))
1562
+ return "kept";
1563
+ manyNames = seat.nlink > 1;
1564
+ if (!manyNames) {
1565
+ ftruncateSync(fd, 0);
1566
+ const bytes = Buffer.from(content, "utf8");
1567
+ for (let at = 0; at < bytes.length;)
1568
+ at += writeSync(fd, bytes, at, bytes.length - at, at);
1569
+ return "written";
1570
+ }
1571
+ }
1572
+ finally {
1573
+ closeSync(fd);
1574
+ }
1575
+ writeFileNoFollow(path, content);
1576
+ return "written";
1577
+ }
1542
1578
  let stagingSeq = 0;
1543
1579
  export function mintStagingName(owner, now) {
1544
1580
  stagingSeq += 1;
@@ -85,10 +85,11 @@ export declare function moveOriginClearanceCustodyOut(store: OriginClearanceStor
85
85
  /** Strict read of the whole account (host audit face; corrupt = throw). Each row answers its custody text, wherever the
86
86
  * account keeps it (`""` once an erasure took it, `custodyErased`). */
87
87
  export declare function readOriginClearances(store: Pick<MemoryGovernanceDocs, "readDoc"> & Pick<MemoryGovernanceObjects, "getObject">): Promise<OriginClearanceRow[]>;
88
- /** The account's erasure count, read BEFORE a clearance judges its entry — the count {@link openOriginClearance} appends
89
- * under. An account never written is written empty here first: an erasure that finds no account adds nothing to it (no
90
- * open has read a count yet, so every judgement still to come follows that erasure's delete), and one that finds it adds one. */
91
- export declare function readClearanceErasureCount(store: OriginClearanceStore): Promise<number>;
88
+ /** The account's erasure count — the store's one count of the erase door's runs — read BEFORE a reader reads what an
89
+ * erasure takes: a clearance before it judges its entry (the count {@link openOriginClearance} appends under), a memory
90
+ * mount before it lists any entry (`MemorySessionHandle.storeState`, the key a frozen copy of the index is found by).
91
+ * A read writes nothing: an account never written reads 0, and every erasure writes it ({@link eraseOriginClearanceCustody}). */
92
+ export declare function readClearanceErasureCount(store: Pick<MemoryGovernanceDocs, "readDoc">): Promise<number>;
92
93
  /**
93
94
  * WRITE-AHEAD open: append the pending row (custody included) before any store mutation. Refuses a
94
95
  * second OPEN while a pending row for the same entry stands — the pending row is a resume seat,
@@ -157,8 +158,9 @@ export interface ClearanceCustodyErasure {
157
158
  * converges: its object is deleted again when one still stands, and a row is never rewritten twice). The row itself —
158
159
  * who cleared, why, when, its events, its status — stays. A failed delete is counted in `remaining`, never swallowed; a
159
160
  * document that cannot be read or updated throws (the lane that called decides what its attestation says about that).
160
- * The same update adds one to the account's erasure count whenever the account was ever written, a row of these entries
161
- * standing or not (#3559, {@link openOriginClearance}): every lane deletes the entries before it calls this, so an open
162
- * that judged one of them before the delete and appends after this update is refused by the count.
161
+ * The same update adds one to the account's erasure count — the store's one count of the erase door's runs — a row of
162
+ * these entries standing or not, and writes the account when it was never written (#3559, {@link openOriginClearance}):
163
+ * every lane deletes the entries before it calls this, so a reader that read the count before an entry (a clearance
164
+ * judging it, a memory mount listing it) and acts after this update sees the count moved.
163
165
  */
164
166
  export declare function eraseOriginClearanceCustody(store: OriginClearanceStore, entryIds: ReadonlySet<string>, at: number): Promise<ClearanceCustodyErasure>;
@@ -153,9 +153,7 @@ function erasedSinceJudgedRefusal(entryId) {
153
153
  }
154
154
  export async function readClearanceErasureCount(store) {
155
155
  const raw = await store.readDoc("origin-clearances");
156
- if (raw !== undefined)
157
- return coerceClearances(raw).erasures ?? 0;
158
- return clearanceUpdate(store, (rec) => ({ next: rec, result: rec.erasures ?? 0 }));
156
+ return raw === undefined ? 0 : coerceClearances(raw).erasures ?? 0;
159
157
  }
160
158
  export async function openOriginClearance(store, row, judgedUnder) {
161
159
  const pendingFor = (rec) => rec.rows.some((r) => r.entryId === row.entryId && r.status === "pending");
@@ -216,7 +214,7 @@ export async function clearanceCustodyErased(store, clearanceId) {
216
214
  return row === undefined || row.custodyErased === true;
217
215
  }
218
216
  export async function eraseOriginClearanceCustody(store, entryIds, at) {
219
- if (entryIds.size === 0 || (await store.readDoc("origin-clearances")) === undefined)
217
+ if (entryIds.size === 0)
220
218
  return { removed: 0, remaining: 0 };
221
219
  const marked = await store.updateDoc("origin-clearances", coerceClearances, (rec) => {
222
220
  rec.erasures = (rec.erasures ?? 0) + 1;