@sema-agent/core 7.64.0 → 7.66.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 (192) hide show
  1. package/CHANGELOG.md +571 -0
  2. package/dist/agents/delegation-registry-seat.d.ts +15 -0
  3. package/dist/agents/delegation-registry-seat.js +13 -0
  4. package/dist/agents/org-delivery-gate.d.ts +8 -1
  5. package/dist/agents/org-delivery-gate.js +9 -3
  6. package/dist/agents/peer-held-queue.js +1 -1
  7. package/dist/agents/peer-idle.js +1 -1
  8. package/dist/agents/peer-session-drain.d.ts +51 -12
  9. package/dist/agents/peer-session-drain.js +47 -34
  10. package/dist/agents/read-inbox-tool.d.ts +6 -2
  11. package/dist/agents/read-inbox-tool.js +18 -5
  12. package/dist/agents/subagent.d.ts +3 -1
  13. package/dist/agents/subagent.js +84 -77
  14. package/dist/brain/reasoning.d.ts +2 -0
  15. package/dist/brain/reasoning.js +1 -0
  16. package/dist/core/allow-entry.d.ts +9 -0
  17. package/dist/core/allow-entry.js +7 -1
  18. package/dist/core/ask-origin.d.ts +23 -3
  19. package/dist/core/ask-origin.js +11 -1
  20. package/dist/core/auto-promote.d.ts +3 -2
  21. package/dist/core/background-agent-store.d.ts +7 -0
  22. package/dist/core/checkpoint-store.d.ts +2 -3
  23. package/dist/core/context-settings.d.ts +1 -2
  24. package/dist/core/context-settings.js +1 -1
  25. package/dist/core/engine-attestation.d.ts +2 -2
  26. package/dist/core/engine-notice.d.ts +13 -1
  27. package/dist/core/engine-notice.js +3 -1
  28. package/dist/core/file-history-store.d.ts +2 -2
  29. package/dist/core/file-history-store.js +0 -4
  30. package/dist/core/gate-fold.js +3 -1
  31. package/dist/core/governance-codes.d.ts +6 -4
  32. package/dist/core/governance-codes.js +5 -3
  33. package/dist/core/human-input-projection.d.ts +9 -0
  34. package/dist/core/human-input-projection.js +13 -0
  35. package/dist/core/input-author.d.ts +66 -6
  36. package/dist/core/input-author.js +21 -3
  37. package/dist/core/leg-identity.d.ts +18 -2
  38. package/dist/core/leg-identity.js +5 -7
  39. package/dist/core/mailbox-store.d.ts +1 -1
  40. package/dist/core/memory-engine/consolidation.d.ts +30 -10
  41. package/dist/core/memory-engine/consolidation.js +41 -6
  42. package/dist/core/memory-engine/control-objects.d.ts +36 -3
  43. package/dist/core/memory-engine/control-objects.js +134 -12
  44. package/dist/core/memory-engine/control-plane-adoption.d.ts +13 -9
  45. package/dist/core/memory-engine/control-plane-adoption.js +58 -31
  46. package/dist/core/memory-engine/delegation-settlement.d.ts +75 -52
  47. package/dist/core/memory-engine/delegation-settlement.js +211 -228
  48. package/dist/core/memory-engine/dual-root.d.ts +3 -2
  49. package/dist/core/memory-engine/dual-root.js +5 -1
  50. package/dist/core/memory-engine/engine.d.ts +33 -16
  51. package/dist/core/memory-engine/engine.js +213 -177
  52. package/dist/core/memory-engine/file-backend.d.ts +21 -12
  53. package/dist/core/memory-engine/file-backend.js +58 -104
  54. package/dist/core/memory-engine/index.d.ts +2 -2
  55. package/dist/core/memory-engine/index.js +2 -2
  56. package/dist/core/memory-engine/layout.d.ts +184 -83
  57. package/dist/core/memory-engine/layout.js +267 -172
  58. package/dist/core/memory-engine/memory-age.d.ts +12 -0
  59. package/dist/core/memory-engine/memory-age.js +17 -0
  60. package/dist/core/memory-engine/memory-backend-contract.js +12 -11
  61. package/dist/core/memory-engine/memory-deployment.d.ts +4 -3
  62. package/dist/core/memory-engine/memory-deployment.js +6 -3
  63. package/dist/core/memory-engine/origin-clearance.d.ts +43 -15
  64. package/dist/core/memory-engine/origin-clearance.js +142 -58
  65. package/dist/core/memory-engine/tools.d.ts +2 -2
  66. package/dist/core/memory-engine/tools.js +7 -7
  67. package/dist/core/memory-engine/types.d.ts +16 -10
  68. package/dist/core/memory-vector.d.ts +6 -14
  69. package/dist/core/memory.d.ts +0 -462
  70. package/dist/core/memory.js +0 -333
  71. package/dist/core/model-receipt.d.ts +2 -1
  72. package/dist/core/model-receipt.js +5 -0
  73. package/dist/core/mods/dollar.d.ts +12 -0
  74. package/dist/core/mods/kernel/dispatch.d.ts +3 -1
  75. package/dist/core/mods/kernel/dispatch.js +5 -2
  76. package/dist/core/mods/kernel/events.d.ts +3 -1
  77. package/dist/core/mods/kernel/events.js +2 -2
  78. package/dist/core/mods/prompt-submit.d.ts +4 -0
  79. package/dist/core/mods/prompt-submit.js +24 -0
  80. package/dist/core/mods/stations.d.ts +23 -4
  81. package/dist/core/mods/stations.js +14 -7
  82. package/dist/core/permission-rule-consent.d.ts +49 -18
  83. package/dist/core/permission-rule-consent.js +59 -38
  84. package/dist/core/permission-rule-store.d.ts +24 -14
  85. package/dist/core/retention.d.ts +2 -7
  86. package/dist/core/retention.js +0 -1
  87. package/dist/core/retired-host-table-account.d.ts +19 -0
  88. package/dist/core/retired-host-table-account.js +28 -0
  89. package/dist/core/retired-tool-name-account.d.ts +60 -0
  90. package/dist/core/retired-tool-name-account.js +32 -0
  91. package/dist/core/roles.d.ts +3 -1
  92. package/dist/core/roles.js +5 -2
  93. package/dist/core/runner/classifier-ladder.d.ts +3 -1
  94. package/dist/core/runner/classifier-ladder.js +2 -2
  95. package/dist/core/runner/compact-session.js +2 -1
  96. package/dist/core/runner/contracts.d.ts +9 -9
  97. package/dist/core/runner/delegation-owner.d.ts +0 -8
  98. package/dist/core/runner/delegation-owner.js +1 -3
  99. package/dist/core/runner/gate-exit.js +9 -2
  100. package/dist/core/runner/memory-consolidation-driver.js +2 -2
  101. package/dist/core/runner/prepare-config-doors.js +1 -1
  102. package/dist/core/runner/prepare-delegation-surface.d.ts +1 -1
  103. package/dist/core/runner/prepare-delegation-surface.js +5 -3
  104. package/dist/core/runner/prepare-gate-stations.d.ts +8 -5
  105. package/dist/core/runner/prepare-gate-stations.js +13 -5
  106. package/dist/core/runner/prepare-inherited-gate.js +2 -0
  107. package/dist/core/runner/prepare-memory-engine-session.js +1 -1
  108. package/dist/core/runner/prepare-memory.js +35 -14
  109. package/dist/core/runner/prepare-policy-chain.js +12 -3
  110. package/dist/core/runner/prepare-project-context.js +2 -2
  111. package/dist/core/runner/prepare-task.d.ts +9 -1
  112. package/dist/core/runner/prepare-task.js +6 -5
  113. package/dist/core/runner/prepare-wiring-manifest.js +5 -4
  114. package/dist/core/runner/prompt-suggestions.js +1 -1
  115. package/dist/core/runner/run-identity-wiring.js +2 -2
  116. package/dist/core/runner/run-leg.js +3 -3
  117. package/dist/core/runner/run-notification-lane.d.ts +3 -0
  118. package/dist/core/runner/run-notification-lane.js +2 -2
  119. package/dist/core/runner/runtask.js +6 -3
  120. package/dist/core/runner/steer-admission.d.ts +11 -2
  121. package/dist/core/runner/stream-steer-verb.d.ts +5 -2
  122. package/dist/core/runner/stream-steer-verb.js +67 -14
  123. package/dist/core/runner/sub-agent-deny-lists.d.ts +8 -8
  124. package/dist/core/runner/sub-agent-deny-lists.js +22 -8
  125. package/dist/core/runner-deps.d.ts +4 -4
  126. package/dist/core/secret-env.d.ts +2 -2
  127. package/dist/core/secret-env.js +6 -20
  128. package/dist/core/session-store.d.ts +6 -6
  129. package/dist/core/session-store.js +3 -3
  130. package/dist/core/shell-run-candidates.js +3 -3
  131. package/dist/core/side-query.js +1 -1
  132. package/dist/core/skill-grant.d.ts +7 -0
  133. package/dist/core/skill-grant.js +14 -5
  134. package/dist/core/store-contracts/background-agent-store-contract.js +13 -0
  135. package/dist/core/task-event.d.ts +14 -0
  136. package/dist/core/task-notification.d.ts +35 -8
  137. package/dist/core/task-notification.js +31 -13
  138. package/dist/core/task-registry-agent.js +1 -0
  139. package/dist/core/task-registry-shared.d.ts +4 -0
  140. package/dist/core/tool-errors.d.ts +3 -3
  141. package/dist/core/tool-policy.js +2 -3
  142. package/dist/core/tool-spec.d.ts +20 -10
  143. package/dist/core/user-attachment.d.ts +5 -1
  144. package/dist/core/user-attachment.js +11 -5
  145. package/dist/core/write-protect.d.ts +16 -0
  146. package/dist/core/write-protect.js +10 -0
  147. package/dist/engine/harness/agent-harness.d.ts +19 -11
  148. package/dist/engine/harness/agent-harness.js +7 -4
  149. package/dist/engine/llm/types.d.ts +22 -10
  150. package/dist/engine/session/repo-utils.d.ts +14 -4
  151. package/dist/engine/session/repo-utils.js +5 -4
  152. package/dist/index.d.ts +10 -8
  153. package/dist/index.js +9 -7
  154. package/dist/prompts/default.d.ts +1 -2
  155. package/dist/scenarios/full-body.d.ts +1 -1
  156. package/dist/shell/lex.d.ts +50 -15
  157. package/dist/shell/lex.js +43 -9
  158. package/dist/stores/file/adoption/adopt.d.ts +1 -1
  159. package/dist/stores/file/index.d.ts +1 -15
  160. package/dist/stores/file/index.js +1 -15
  161. package/dist/stores/file/permission-rule-store.d.ts +12 -1
  162. package/dist/stores/file/permission-rule-store.js +31 -4
  163. package/dist/stores/file/session-store.js +1 -1
  164. package/dist/tools/fs/fs-bash.js +3 -3
  165. package/dist/tools/fs/removal-targets.d.ts +8 -2
  166. package/dist/tools/fs/removal-targets.js +31 -4
  167. package/dist/tools/fs/shell-read-argv.js +7 -1
  168. package/dist/tools/fs/shell-read-bindings.d.ts +21 -5
  169. package/dist/tools/fs/shell-read-bindings.js +130 -44
  170. package/dist/tools/fs/shell-read-plan.js +95 -29
  171. package/dist/tools/fs/shell-read-sourced.d.ts +25 -0
  172. package/dist/tools/fs/shell-read-sourced.js +119 -0
  173. package/dist/tools/fs/shell-read-word.d.ts +2 -2
  174. package/dist/tools/fs/shell-read-word.js +4 -5
  175. package/dist/tools/fs/shell-read-workdir.d.ts +19 -3
  176. package/dist/tools/fs/shell-read-workdir.js +60 -15
  177. package/dist/tools/fs/shell-reentry-text.d.ts +10 -2
  178. package/dist/tools/fs/shell-reentry-text.js +11 -4
  179. package/package.json +2 -2
  180. package/test/export-surface.snapshot.json +21 -79
  181. package/wire-changes/core-stores-sql@7.65.0.json +30 -0
  182. package/wire-changes/core-stores-sql@7.66.0.json +30 -0
  183. package/wire-changes/core@7.65.0.json +1650 -0
  184. package/wire-changes/core@7.66.0.json +1218 -0
  185. package/wire-changes/mods-kernel@7.65.0.json +30 -0
  186. package/wire-changes/mods-kernel@7.66.0.json +65 -0
  187. package/wire-changes/primitives@7.65.0.json +337 -0
  188. package/wire-changes/primitives@7.66.0.json +30 -0
  189. package/dist/core/memory-recall.d.ts +0 -208
  190. package/dist/core/memory-recall.js +0 -136
  191. package/dist/stores/file/memory-store.d.ts +0 -124
  192. package/dist/stores/file/memory-store.js +0 -353
@@ -8,7 +8,8 @@
8
8
  * they land) — a second implementation would be a drift seam, exactly the class the challenge
9
9
  * exclusion view closed.
10
10
  */
11
- import type { MemoryBackend, MemoryEntry, MemoryEntryHeader, MemoryEntryOrigin, MemoryGovernanceStore, NotePatch } from "./types.js";
11
+ import { type SessionCaptureRecordStore } from "./layout.js";
12
+ import type { MemoryBackend, MemoryEntry, MemoryEntryHeader, MemoryEntryOrigin, MemoryGovernanceObjects, MemoryGovernanceStore, NotePatch } from "./types.js";
12
13
  import type { ConsolidationDriverRunRow } from "./consolidation-driver.js";
13
14
  /**
14
15
  * Derive the SUPERSEDED set from a committed header listing: superseded entry id → the standing
@@ -544,19 +545,29 @@ export type MemoryGovernanceDurability = "backend" | "replica-local";
544
545
  * consolidation asks here, never of a backend member it probes itself. A deployment-wide memory face asks a different
545
546
  * fact — whether the backend publishes a control plane — and does not ask here.
546
547
  *
547
- * `"backend"` ⇔ the backend publishes its own control plane (`controlPlaneRoot`, a non-empty string — the File backend:
548
- * every control-plane record, the consolidation store and the governance ledgers alike, sits in its directory). A
549
- * backend that carries `MemoryBackend.governance` but no control plane still answers `"replica-local"`: the
550
- * consolidation state and the governance documents (lineage, challenges, settlements, session accounts and the
551
- * announcement queue a consolidation writes) ride its store, but the instruction holds (each beside its captured bytes)
552
- * are still kept in the replica's control plane, and the answer changes only when they ride the store too. Eligibility also reads the capture opt-out records
553
- * (`MemoryEngineOptions.captureRecordStore`: a carrier the host injects is its declaration of a store every replica
554
- * reads; the default is a file in the engine's control plane — the store's own directory on the File backend): an
555
- * answer that turns `"backend"` for a backend without a control plane must hold for the default carrier as well.
548
+ * `"backend"` ⇔ the backend carries a governance store (`MemoryBackend.governance` — the File backend's is the File store
549
+ * over its own control plane): every record a consolidation reads and writes rides that store — the consolidation
550
+ * state, the governance documents (lineage, challenges, settlements, session accounts, the announcement queue, the
551
+ * holds and the origin clearances), the control objects (pollution markers, quarantine copies, holds' captures,
552
+ * clearance custody) and the capture opt-out records the eligibility reads (#3484: the default capture carrier is the
553
+ * store's `capture` objects; a carrier the host injects, `MemoryEngineOptions.captureRecordStore`, is its declaration
554
+ * of a store every replica reads). A backend that carries none answers `"replica-local"`: the engine then keeps those
555
+ * records in the File store over the replica's own control plane.
556
556
  */
557
557
  export declare function memoryGovernanceDurability(backend: MemoryBackend): MemoryGovernanceDurability;
558
558
  /** The control plane a File governance store keeps its documents in; `undefined` for any other store. */
559
559
  export declare function fileGovernanceStoreDir(store: MemoryGovernanceStore): string | undefined;
560
+ /** `true` ⇔ `store` is the File governance store over `controlDir` itself (the same directory, however it is spelled —
561
+ * the same path once resolved, or the same device and inode): that plane's records are the store's own. The one reading
562
+ * of "this control plane is its own carrier" — adoption has nothing to hand over, the engine converts its own v1 documents
563
+ * in place and refuses no strays, and an ancestor coordinate at that plane names this carrier (#3484). */
564
+ export declare function governanceStoreIsFileOver(store: MemoryGovernanceStore, controlDir: string): boolean;
565
+ /** A store's control objects as a reader that must see damage rather than be spared it reads them — an erasure's count,
566
+ * an export's roster: for a File store the listing names every entry standing in the kind's directory
567
+ * (`standingFileControlObjectNames`) — a subdirectory, a dangling link, a name no writer could have used — so the verbs
568
+ * that meet it refuse it by name and the reader counts it; any other store's listing is its own (KL-3466-c). The other
569
+ * verbs are the store's. */
570
+ export declare function standingControlObjectsOf(store: MemoryGovernanceStore): MemoryGovernanceObjects;
560
571
  /**
561
572
  * The consolidation state's File store over one control plane — the gate file, the plan workbook, the intent
562
573
  * credentials, the run account and the mint archive exactly as they have always been laid out (same names, same
@@ -565,6 +576,15 @@ export declare function fileGovernanceStoreDir(store: MemoryGovernanceStore): st
565
576
  * whose backend carries no store keeps its state with this over the replica's control plane.
566
577
  */
567
578
  export declare function fileGovernanceStore(controlDir: string): MemoryGovernanceStore;
579
+ /** The capture opt-out records ({@link SessionCaptureRecordStore}) kept as the `capture` objects of a governance store
580
+ * (#3484): the engine's default carrier — the store its backend carries, else the File store over its control plane.
581
+ * Read through the store's damage-visible view ({@link standingControlObjectsOf}), so a record that stands unreadable
582
+ * reads as one, and a store that cannot answer is the indeterminate fault axis. */
583
+ export declare function governanceCaptureRecordStore(store: MemoryGovernanceStore): SessionCaptureRecordStore;
584
+ /** The {@link SessionCaptureRecordStore} of the File store over `controlDir` — the `capture` objects under
585
+ * `<controlDir>/session-capture-optout/`, the names and bytes the File form has always had. A host that keeps a
586
+ * replica's records in its own durable control plane declares it with this. */
587
+ export declare function fileSessionCaptureRecordStore(controlDir: string): SessionCaptureRecordStore;
568
588
  /** Derive a product's slug from its proposed name (memory filename charset; collisions are the
569
589
  * backend's deterministic -n suffix). */
570
590
  export declare function deriveProductSlug(name: string | undefined, fallback: string): string;
@@ -1,8 +1,8 @@
1
- import { existsSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
3
  import { uuidv7 } from "../../engine/session/uuid.js";
4
- import { atomicWriteFileSync, fileGovernanceDocOf, lockedStrictUpdate, readStrictSidecar, ControlPlaneCorruptError, ensureDirExists } from "./layout.js";
5
- import { deleteFileControlObject, getFileControlObject, listFileControlObjects, moveFileControlObject, putFileControlObject } from "./control-objects.js";
4
+ import { atomicWriteFileSync, fileGovernanceDocOf, listSessionCaptureObjects, lockedStrictUpdate, markSessionCaptureObjects, readSessionCaptureObjects, readStrictSidecar, ControlPlaneCorruptError, ensureDirExists } from "./layout.js";
5
+ import { deleteFileControlObject, getFileControlObject, listFileControlObjects, moveFileControlObject, putFileControlObject, standingFileControlObjectNames } from "./control-objects.js";
6
6
  import { thrownText } from "../thrown-value.js";
7
7
  import { optionKeys, receiveMembers } from "../own-property-receipt.js";
8
8
  export function deriveSupersededSet(headers, opts = {}) {
@@ -401,13 +401,37 @@ export function consolidationRunSuperseded(scope, cur) {
401
401
  return e;
402
402
  }
403
403
  export function memoryGovernanceDurability(backend) {
404
- const root = Reflect.get(backend, "controlPlaneRoot");
405
- return typeof root === "string" && root !== "" ? "backend" : "replica-local";
404
+ return backend.governance !== undefined ? "backend" : "replica-local";
406
405
  }
407
406
  const FILE_GOVERNANCE_DIRS = new WeakMap();
408
407
  export function fileGovernanceStoreDir(store) {
409
408
  return FILE_GOVERNANCE_DIRS.get(store);
410
409
  }
410
+ export function governanceStoreIsFileOver(store, controlDir) {
411
+ const dir = fileGovernanceStoreDir(store);
412
+ if (dir === undefined)
413
+ return false;
414
+ if (resolve(dir) === resolve(controlDir))
415
+ return true;
416
+ try {
417
+ const a = statSync(dir);
418
+ const b = statSync(controlDir);
419
+ return a.dev === b.dev && a.ino === b.ino;
420
+ }
421
+ catch {
422
+ return false;
423
+ }
424
+ }
425
+ export function standingControlObjectsOf(store) {
426
+ const dir = fileGovernanceStoreDir(store);
427
+ return {
428
+ putObject: (kind, name, bytes, meta) => store.putObject(kind, name, bytes, meta),
429
+ getObject: (kind, name) => store.getObject(kind, name),
430
+ listObjects: dir === undefined ? (kind) => store.listObjects(kind) : async (kind) => standingFileControlObjectNames(dir, kind),
431
+ moveObject: (from, to) => store.moveObject(from, to),
432
+ deleteObject: (kind, name) => store.deleteObject(kind, name),
433
+ };
434
+ }
411
435
  function isMintArchive(value) {
412
436
  return typeof value === "object" && value !== null && Reflect.get(value, "kind") === "llm-consolidation-plan";
413
437
  }
@@ -534,6 +558,17 @@ export function fileGovernanceStore(controlDir) {
534
558
  FILE_GOVERNANCE_DIRS.set(store, controlDir);
535
559
  return store;
536
560
  }
561
+ export function governanceCaptureRecordStore(store) {
562
+ const objects = standingControlObjectsOf(store);
563
+ return {
564
+ mark: (sessionId, record) => markSessionCaptureObjects(objects, sessionId, record),
565
+ read: (sessionId, identity) => readSessionCaptureObjects(objects, sessionId, identity),
566
+ list: () => listSessionCaptureObjects(objects),
567
+ };
568
+ }
569
+ export function fileSessionCaptureRecordStore(controlDir) {
570
+ return governanceCaptureRecordStore(fileGovernanceStore(controlDir));
571
+ }
537
572
  export function deriveProductSlug(name, fallback) {
538
573
  const base = (name ?? "").toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
539
574
  return base.length > 0 ? base : fallback;
@@ -1,17 +1,43 @@
1
1
  import { type MemoryControlObjectKind } from "./types.js";
2
+ import { type QuarantineCapture } from "./layout.js";
2
3
  /** Where a File store stages an object's bytes before publishing them under the object's name. Never a kind's
3
4
  * directory: a listing of a kind answers published names only. */
4
5
  export declare const CONTROL_OBJECT_STAGE_DIR = ".control-object-stage";
5
6
  /** A control-object kind's directory under a File store's control plane. A kind outside
6
7
  * {@link MEMORY_CONTROL_OBJECT_KINDS} is refused (`memory.control_object_unknown`) — never given a directory of its own. */
7
8
  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
+ /** A name a store keeps an object under: one opaque, non-empty segment of at most 255 UTF-8 bytes — never `.` / `..`, never a
10
+ * separator or a NUL. */
9
11
  export declare function isControlObjectName(name: unknown): name is string;
10
- /** Write `(kind, name)` once ({@link import("./types.js").MemoryGovernanceStore.putObject}). */
12
+ /** The filesystem code behind a File control-object refusal: the refusal's own `code` when it is the filesystem's, else
13
+ * the code of the filesystem error it was raised over (`cause`) — `undefined` when neither names one. */
14
+ export declare function fileControlObjectFaultCode(err: unknown): string | undefined;
15
+ /**
16
+ * The open judge of a File governance store over `controlDir` (#3512): the store publishes every object with `link`
17
+ * ({@link putFileControlObject}, {@link moveFileControlObject}), so on a file system that cannot make a hard link every
18
+ * object write would fail — and a containment whose copy fails still takes the suspect off the plane (its copy is
19
+ * lost, not kept). One link is tried, at the open, between two files at the control plane's top level (named with
20
+ * `LINK_PROBE_PREFIX`), and both are removed; a link the file system refuses is refused here
21
+ * (`memory.control_plane_links_unsupported`, `controlPlaneLinksRefusal`, `detail.path` = `controlDir`). Not judged — the
22
+ * open proceeds as before — when the first file cannot be created (a control plane that is read-only, full or not
23
+ * writable: what was not tried is not claimed) or when the link's name already stands. Asked at each open, never
24
+ * cached. The callers are the two holders of a File store: the File backend's construction and an engine whose backend
25
+ * carries no store of its own. `controlDir` stands when it is asked.
26
+ */
27
+ export declare function probeControlPlaneLinks(controlDir: string): void;
28
+ /** Write `(kind, name)` once ({@link import("./types.js").MemoryGovernanceStore.putObject}): `"existed"` only when the name already
29
+ * holds these same bytes; a name holding other bytes is refused, never answered as written. */
11
30
  export declare function putFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string, bytes: Uint8Array): "created" | "existed";
12
31
  /** A control object's bytes ({@link import("./types.js").MemoryGovernanceStore.getObject}). */
13
32
  export declare function getFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string): Uint8Array | undefined;
14
- /** Every name of `kind`, sorted ({@link import("./types.js").MemoryGovernanceStore.listObjects}). */
33
+ /** Every name standing in a kind's directory, sorted — the objects and whatever else stands there (a subdirectory, a dangling link,
34
+ * a name no writer could have used). For the readers that must see damage rather than be spared it: the adoption of a replica
35
+ * refuses each such entry by name and withholds the documents behind it, and the strays reader counts them — an entry standing
36
+ * where an object's record belongs is a fact, never an absence. {@link listFileControlObjects} is the store's verb: objects only. */
37
+ export declare function standingFileControlObjectNames(controlDir: string, kind: MemoryControlObjectKind): string[];
38
+ /** Every name of `kind`, sorted ({@link import("./types.js").MemoryGovernanceStore.listObjects}): the regular files under a legal
39
+ * name — the entries {@link getFileControlObject} reads. A subdirectory or a dangling link in a kind's directory is no object and
40
+ * is not named here; the verbs that meet it refuse it, and {@link standingFileControlObjectNames} still names it. */
15
41
  export declare function listFileControlObjects(controlDir: string, kind: MemoryControlObjectKind): string[];
16
42
  /** Move one object, never overwriting ({@link import("./types.js").MemoryGovernanceStore.moveObject}). */
17
43
  export declare function moveFileControlObject(controlDir: string, from: {
@@ -21,5 +47,12 @@ export declare function moveFileControlObject(controlDir: string, from: {
21
47
  readonly kind: MemoryControlObjectKind;
22
48
  readonly name: string;
23
49
  }): "moved" | "already-moved";
50
+ /** {@link putFileControlObject} for a writer whose record is the first one under the name — the synchronous twin of
51
+ * `putControlObjectOnce` (`layout.ts`), one law: `"existed"` ⇔ an object stands there that reads back (the same bytes,
52
+ * or other bytes the put refused); a refusal no readable object explains is the put's own and is thrown. */
53
+ export declare function putFileControlObjectOnce(controlDir: string, kind: MemoryControlObjectKind, name: string, bytes: Uint8Array): "created" | "existed";
54
+ /** The File store's capture of one suspect file's copy into its `quarantine` objects — the synchronous twin of
55
+ * `captureIntoQuarantine` (`layout.ts`) for the File backend's own synchronous read paths, under the same names. */
56
+ export declare function captureIntoFileQuarantine(controlDir: string, path: string, content: string, now: () => number): QuarantineCapture;
24
57
  /** Delete one object ({@link import("./types.js").MemoryGovernanceStore.deleteObject}). */
25
58
  export declare function deleteFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string): boolean;
@@ -2,7 +2,8 @@ import { closeSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, read
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
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";
5
+ import { ControlPlaneCorruptError, IMPORT_RECEIPTS_DIR, LINK_PROBE_PREFIX, QUARANTINE_DIR, SESSION_CAPTURE_OPTOUT_DIR, SESSION_POLLUTION_DIR, controlPlaneLinksRefusal, ensureDirExists, quarantineCaptureBase, quarantineCaptureName } from "./layout.js";
6
+ import { thrownText } from "../thrown-value.js";
6
7
  const FILE_CONTROL_OBJECT_DIRS = Object.freeze({
7
8
  pollution: SESSION_POLLUTION_DIR,
8
9
  "import-receipt": IMPORT_RECEIPTS_DIR,
@@ -22,8 +23,9 @@ export function fileControlObjectDirOf(kind) {
22
23
  throw unknownObject(`${JSON.stringify(String(kind))} is not a control-object kind`);
23
24
  return FILE_CONTROL_OBJECT_DIRS[kind];
24
25
  }
26
+ const CONTROL_OBJECT_NAME_MAX_BYTES = 255;
25
27
  export function isControlObjectName(name) {
26
- return typeof name === "string" && name !== "" && name !== "." && name !== ".." && !/[/\\\0]/.test(name);
28
+ return typeof name === "string" && name !== "" && name !== "." && name !== ".." && !/[/\\\0]/.test(name) && Buffer.byteLength(name, "utf8") <= CONTROL_OBJECT_NAME_MAX_BYTES;
27
29
  }
28
30
  function objectPath(controlDir, kind, name) {
29
31
  const dir = fileControlObjectDirOf(kind);
@@ -34,21 +36,87 @@ function objectPath(controlDir, kind, name) {
34
36
  function errnoOf(err) {
35
37
  return typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined;
36
38
  }
37
- function stands(path) {
39
+ export function fileControlObjectFaultCode(err) {
40
+ if (err instanceof ControlPlaneCorruptError)
41
+ return errnoOf(err.cause);
42
+ return errnoOf(err);
43
+ }
44
+ function unprobeable(path, err) {
45
+ return 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
+ function entryAt(path) {
48
+ let found;
38
49
  try {
39
- lstatSync(path);
40
- return true;
50
+ found = lstatSync(path);
41
51
  }
42
52
  catch (err) {
43
53
  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 });
54
+ return "absent";
55
+ throw unprobeable(path, err);
56
+ }
57
+ if (found.isFile())
58
+ return "object";
59
+ if (!found.isSymbolicLink())
60
+ return "other";
61
+ try {
62
+ return statSync(path).isFile() ? "object" : "other";
63
+ }
64
+ catch (err) {
65
+ const code = errnoOf(err);
66
+ if (code === "ENOENT" || code === "ELOOP" || code === "ENOTDIR")
67
+ return "other";
68
+ throw unprobeable(path, err);
69
+ }
70
+ }
71
+ function stands(path) {
72
+ return entryAt(path) !== "absent";
73
+ }
74
+ function notAnObject(kind, name, refusal) {
75
+ return new ControlPlaneCorruptError(`memory control object ${kind}/${name} stands but is not a control object (a regular file under a legal name) — ${refusal} (fail-closed)`);
76
+ }
77
+ function otherBytesStand(kind, name) {
78
+ return new ControlPlaneCorruptError(`memory control object put ${kind}/${name}: the name already stands with different bytes — refusing to overwrite it (fail-closed)`);
79
+ }
80
+ function standingHolds(controlDir, kind, name, bytes) {
81
+ const standing = getFileControlObject(controlDir, kind, name);
82
+ return standing === undefined ? undefined : Buffer.from(standing).equals(bytes);
83
+ }
84
+ export function probeControlPlaneLinks(controlDir) {
85
+ const source = join(controlDir, `${LINK_PROBE_PREFIX}${randomUUID()}`);
86
+ const linked = `${source}.link`;
87
+ try {
88
+ closeSync(openSync(source, "wx", 0o600));
89
+ }
90
+ catch {
91
+ return;
92
+ }
93
+ let made = false;
94
+ try {
95
+ linkSync(source, linked);
96
+ made = true;
97
+ }
98
+ catch (err) {
99
+ const fault = errnoOf(err);
100
+ if (fault !== "EEXIST")
101
+ throw controlPlaneLinksRefusal(controlDir, fault);
102
+ }
103
+ finally {
104
+ for (const path of made ? [linked, source] : [source]) {
105
+ try {
106
+ rmSync(path, { force: true });
107
+ }
108
+ catch {
109
+ }
110
+ }
46
111
  }
47
112
  }
48
113
  export function putFileControlObject(controlDir, kind, name, bytes) {
49
114
  const path = objectPath(controlDir, kind, name);
50
- if (stands(path))
115
+ const held = standingHolds(controlDir, kind, name, bytes);
116
+ if (held === true)
51
117
  return "existed";
118
+ if (held === false)
119
+ throw otherBytesStand(kind, name);
52
120
  ensureDirExists(join(controlDir, fileControlObjectDirOf(kind)));
53
121
  const stageDir = join(controlDir, CONTROL_OBJECT_STAGE_DIR);
54
122
  ensureDirExists(stageDir);
@@ -72,8 +140,14 @@ export function putFileControlObject(controlDir, kind, name, bytes) {
72
140
  return "created";
73
141
  }
74
142
  catch (err) {
75
- if (errnoOf(err) === "EEXIST")
76
- return "existed";
143
+ if (errnoOf(err) === "EEXIST") {
144
+ const held = standingHolds(controlDir, kind, name, bytes);
145
+ if (held === true)
146
+ return "existed";
147
+ if (held === false)
148
+ throw otherBytesStand(kind, name);
149
+ throw new ControlPlaneCorruptError(`memory control object put ${kind}/${name}: the name stood when the object was published and was gone when its bytes were compared — nothing was written (fail-closed)`);
150
+ }
77
151
  throw err;
78
152
  }
79
153
  finally {
@@ -82,6 +156,11 @@ export function putFileControlObject(controlDir, kind, name, bytes) {
82
156
  }
83
157
  export function getFileControlObject(controlDir, kind, name) {
84
158
  const path = objectPath(controlDir, kind, name);
159
+ const state = entryAt(path);
160
+ if (state === "absent")
161
+ return undefined;
162
+ if (state === "other")
163
+ throw notAnObject(kind, name, "it is never read as missing");
85
164
  try {
86
165
  return new Uint8Array(readFileSync(path));
87
166
  }
@@ -91,7 +170,7 @@ export function getFileControlObject(controlDir, kind, name) {
91
170
  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
171
  }
93
172
  }
94
- export function listFileControlObjects(controlDir, kind) {
173
+ export function standingFileControlObjectNames(controlDir, kind) {
95
174
  const dir = join(controlDir, fileControlObjectDirOf(kind));
96
175
  try {
97
176
  return readdirSync(dir).sort();
@@ -102,6 +181,10 @@ export function listFileControlObjects(controlDir, kind) {
102
181
  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
182
  }
104
183
  }
184
+ export function listFileControlObjects(controlDir, kind) {
185
+ const dir = join(controlDir, fileControlObjectDirOf(kind));
186
+ return standingFileControlObjectNames(controlDir, kind).filter((name) => isControlObjectName(name) && entryAt(join(dir, name)) === "object");
187
+ }
105
188
  function sameBytes(a, b) {
106
189
  const sa = statSync(a);
107
190
  const sb = statSync(b);
@@ -131,14 +214,53 @@ export function moveFileControlObject(controlDir, from, to) {
131
214
  }
132
215
  if (code !== "EEXIST")
133
216
  throw err;
217
+ if (!lstatSync(dst).isFile())
218
+ throw new ControlPlaneCorruptError(`memory control object move ${from.kind}/${from.name} → ${to.kind}/${to.name}: the target already stands but is not a file of its own (a link, or no file) — refusing to drop the source onto it (fail-closed)`);
134
219
  if (!sameBytes(src, dst))
135
220
  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
221
  }
137
222
  unlinkSync(src);
138
223
  return "moved";
139
224
  }
225
+ export function putFileControlObjectOnce(controlDir, kind, name, bytes) {
226
+ try {
227
+ return putFileControlObject(controlDir, kind, name, bytes);
228
+ }
229
+ catch (err) {
230
+ let standing;
231
+ try {
232
+ standing = getFileControlObject(controlDir, kind, name);
233
+ }
234
+ catch {
235
+ throw err;
236
+ }
237
+ if (standing === undefined)
238
+ throw err;
239
+ return "existed";
240
+ }
241
+ }
242
+ export function captureIntoFileQuarantine(controlDir, path, content, now) {
243
+ const bytes = new TextEncoder().encode(content);
244
+ const base = quarantineCaptureBase(path, now);
245
+ try {
246
+ for (let attempt = 0; attempt <= 10; attempt++) {
247
+ const name = quarantineCaptureName(base, attempt);
248
+ if (putFileControlObjectOnce(controlDir, "quarantine", name, bytes) === "created")
249
+ return { name };
250
+ }
251
+ return { failed: "quarantine copy failed: every capture name already stands" };
252
+ }
253
+ catch (err) {
254
+ return { failed: `quarantine copy failed: ${thrownText(err)}` };
255
+ }
256
+ }
140
257
  export function deleteFileControlObject(controlDir, kind, name) {
141
258
  const path = objectPath(controlDir, kind, name);
259
+ const state = entryAt(path);
260
+ if (state === "absent")
261
+ return false;
262
+ if (state === "other")
263
+ throw notAnObject(kind, name, "refusing to delete it");
142
264
  try {
143
265
  unlinkSync(path);
144
266
  return true;
@@ -146,6 +268,6 @@ export function deleteFileControlObject(controlDir, kind, name) {
146
268
  catch (err) {
147
269
  if ((errnoOf(err) === "ENOENT" || errnoOf(err) === "ENOTDIR") && !stands(path))
148
270
  return false;
149
- throw err;
271
+ throw new ControlPlaneCorruptError(`memory control object ${kind}/${name} stands but could not be deleted (${errnoOf(err) ?? "io error"}) (fail-closed)`, { cause: err });
150
272
  }
151
273
  }
@@ -3,25 +3,27 @@ import { type MemoryControlObjectKind, type MemoryGovernanceDocName, type Memory
3
3
  export interface ReplicaControlPlaneStrays {
4
4
  /** The governance documents with a file (or a journal) in the replica. */
5
5
  readonly docs: readonly MemoryGovernanceDocName[];
6
- /** How many control objects of each kind the replica holds (kinds it holds none of are absent). */
6
+ /** How many entries stand in each kind's directory of the replica (kinds with none are absent): the control objects, and whatever
7
+ * else stands where an object's record belongs — adoption refuses each of those by name, never skips it. */
7
8
  readonly objects: Readonly<Partial<Record<MemoryControlObjectKind, number>>>;
8
9
  }
9
10
  /** One record adoption handled: a document (`doc:<name>`) or an object (`<kind>/<name>`). */
10
11
  export interface AdoptedControlRecord {
11
12
  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. */
13
+ /** What the carrier holds now, never what became of the replica's copy: `"written"` ⇔ the carrier lacked the record
14
+ * and now holds the same value; `"converged"` ⇔ it already held the same value. */
14
15
  readonly outcome: "written" | "converged";
15
16
  /** sha-256 of the record as the replica held it: an object's bytes, a document's committed JSON value. */
16
17
  readonly digest: string;
17
18
  }
18
19
  /** {@link adoptReplicaControlPlane}'s answer. */
19
20
  export interface ControlPlaneAdoptionReport {
20
- /** Records the carrier now holds with the replica's value (the replica keeps its copy). */
21
+ /** Records the carrier now holds with the replica's value. When `refused` is empty, the replica's copies of these are
22
+ * removed; otherwise the replica keeps every copy. */
21
23
  readonly adopted: readonly AdoptedControlRecord[];
22
24
  /** 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
+ * could not be read or verified, a receipt row that could not be written (then the carrier may already hold the
26
+ * value, and a re-run converges it), or a replica copy that could not be removed once the carrier held it. */
25
27
  readonly refused: readonly {
26
28
  readonly record: string;
27
29
  readonly reason: string;
@@ -33,9 +35,11 @@ export declare const CONTROL_PLANE_ADOPTION_FILE = "control-plane-adoption.json"
33
35
  * fails throws `ControlPlaneCorruptError` (never an empty answer). */
34
36
  export declare function replicaControlPlaneStrays(controlDir: string): ReplicaControlPlaneStrays;
35
37
  /**
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.
38
+ * Hand the replica control plane's carrier records to `carrier` (see the module note). Answers what the carrier now
39
+ * holds with the replica's value and what was refused; the replica's copies are removed only when nothing was refused.
40
+ * When `carrier` is the File store over `controlDir` itself there is nothing to hand over and the answer is empty. A
41
+ * `controlDir` that does not exist is refused (`ControlPlaneCorruptError`): the call is an operator's, over a path they
42
+ * named, and a wrong path must not read as "nothing to adopt".
39
43
  */
40
44
  export declare function adoptReplicaControlPlane(controlDir: string, carrier: MemoryGovernanceStore, opts?: {
41
45
  readonly now?: () => number;
@@ -1,12 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
- import { lstatSync, statSync } from "node:fs";
3
- import { join, resolve } from "node:path";
2
+ import { lstatSync } from "node:fs";
3
+ import { join } from "node:path";
4
4
  import { isDeepStrictEqual } from "node:util";
5
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";
6
+ import { ControlPlaneCorruptError, fileGovernanceDocOf, lockedStrictRemove, lockedStrictUpdate, readStrictSidecar } from "./layout.js";
7
+ import { deleteFileControlObject, getFileControlObject, standingFileControlObjectNames } from "./control-objects.js";
8
+ import { fileGovernanceStore, governanceStoreIsFileOver } from "./consolidation.js";
9
9
  import { moveOriginClearanceCustodyOut } from "./origin-clearance.js";
10
+ import { convertV1SessionAccountsAt } from "./delegation-settlement.js";
10
11
  import { thrownText } from "../thrown-value.js";
11
12
  export const CONTROL_PLANE_ADOPTION_FILE = "control-plane-adoption.json";
12
13
  function coerceReceipt(raw) {
@@ -38,33 +39,20 @@ export function replicaControlPlaneStrays(controlDir) {
38
39
  });
39
40
  const objects = {};
40
41
  for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
41
- const n = listFileControlObjects(controlDir, kind).length;
42
+ const n = standingFileControlObjectNames(controlDir, kind).length;
42
43
  if (n > 0)
43
44
  objects[kind] = n;
44
45
  }
45
46
  return { docs, objects };
46
47
  }
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
48
  export async function adoptReplicaControlPlane(controlDir, carrier, opts) {
63
49
  const now = opts?.now ?? Date.now;
64
- const adopted = [];
50
+ const handed = [];
65
51
  const refused = [];
66
- if (carriesThisDirectory(carrier, controlDir))
67
- return { adopted, refused };
52
+ if (governanceStoreIsFileOver(carrier, controlDir))
53
+ return { adopted: [], refused };
54
+ if (!standsAt(controlDir))
55
+ throw new ControlPlaneCorruptError(`memory control-plane adoption: ${controlDir} does not exist — a replica control plane to adopt from is a directory that stands (a wrong path hands over nothing and says so) (fail-closed)`);
68
56
  const receipt = (record, digest) => {
69
57
  lockedStrictUpdate(controlDir, CONTROL_PLANE_ADOPTION_FILE, "memory control-plane adoption receipt", coerceReceipt, (rec) => {
70
58
  if (rec.adopted.some((r) => r.record === record && r.digest === digest))
@@ -73,17 +61,28 @@ export async function adoptReplicaControlPlane(controlDir, carrier, opts) {
73
61
  return { next: rec, result: undefined };
74
62
  });
75
63
  };
76
- const clearances = join(controlDir, fileGovernanceDocOf("origin-clearances").file);
77
- if (standsAt(clearances) || standsAt(`${clearances}.journal`)) {
64
+ const docStands = (name) => {
65
+ const file = join(controlDir, fileGovernanceDocOf(name).file);
66
+ return standsAt(file) || standsAt(`${file}.journal`);
67
+ };
68
+ if (docStands("session-accounts")) {
78
69
  try {
79
- moveOriginClearanceCustodyOut(controlDir);
70
+ convertV1SessionAccountsAt(controlDir);
71
+ }
72
+ catch (err) {
73
+ refused.push({ record: "doc:session-accounts", reason: `its v1 key form could not be converted first: ${thrownText(err)}` });
74
+ }
75
+ }
76
+ if (docStands("origin-clearances")) {
77
+ try {
78
+ await moveOriginClearanceCustodyOut(fileGovernanceStore(controlDir));
80
79
  }
81
80
  catch (err) {
82
81
  refused.push({ record: "doc:origin-clearances", reason: `its inline custody could not be moved out first: ${thrownText(err)}` });
83
82
  }
84
83
  }
85
84
  for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
86
- for (const name of listFileControlObjects(controlDir, kind)) {
85
+ for (const name of standingFileControlObjectNames(controlDir, kind)) {
87
86
  const record = `${kind}/${name}`;
88
87
  try {
89
88
  const bytes = getFileControlObject(controlDir, kind, name);
@@ -102,7 +101,18 @@ export async function adoptReplicaControlPlane(controlDir, carrier, opts) {
102
101
  continue;
103
102
  }
104
103
  receipt(record, digest);
105
- adopted.push({ record, outcome, digest });
104
+ handed.push({
105
+ adopted: { record, outcome, digest },
106
+ removeSource: () => {
107
+ const current = getFileControlObject(controlDir, kind, name);
108
+ if (current === undefined)
109
+ return true;
110
+ if (sha256Hex(current) !== digest)
111
+ return false;
112
+ deleteFileControlObject(controlDir, kind, name);
113
+ return true;
114
+ },
115
+ });
106
116
  }
107
117
  catch (err) {
108
118
  refused.push({ record, reason: thrownText(err) });
@@ -115,7 +125,7 @@ export async function adoptReplicaControlPlane(controlDir, carrier, opts) {
115
125
  if (!before.includes(`doc:${name}`))
116
126
  refused.push({ record: `doc:${name}`, reason: `left in the replica until every record before it is adopted (refused: ${before.join(", ")})` });
117
127
  }
118
- return { adopted, refused };
128
+ return { adopted: handed.map((h) => h.adopted), refused };
119
129
  }
120
130
  for (const name of MEMORY_GOVERNANCE_DOC_NAMES) {
121
131
  const record = `doc:${name}`;
@@ -146,12 +156,29 @@ export async function adoptReplicaControlPlane(controlDir, carrier, opts) {
146
156
  continue;
147
157
  }
148
158
  receipt(record, digest);
149
- adopted.push({ record, outcome, digest });
159
+ handed.push({
160
+ adopted: { record, outcome, digest },
161
+ removeSource: () => lockedStrictRemove(controlDir, file, what, (committed) => sha256Hex(JSON.stringify(committed)) === digest) !== "kept",
162
+ });
150
163
  }
151
164
  catch (err) {
152
165
  refused.push({ record, reason: thrownText(err) });
153
166
  }
154
167
  }
168
+ if (refused.length > 0)
169
+ return { adopted: handed.map((h) => h.adopted), refused };
170
+ const adopted = [];
171
+ for (const h of handed) {
172
+ try {
173
+ if (h.removeSource())
174
+ adopted.push(h.adopted);
175
+ else
176
+ refused.push({ record: h.adopted.record, reason: "the carrier holds it; the replica's copy changed after it was adopted and is kept" });
177
+ }
178
+ catch (err) {
179
+ refused.push({ record: h.adopted.record, reason: `the carrier holds it; removing the replica's copy failed: ${thrownText(err)}` });
180
+ }
181
+ }
155
182
  return { adopted, refused };
156
183
  }
157
184
  export function readControlPlaneAdoptionReceipt(controlDir) {