@sema-agent/core 7.63.0 → 7.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +408 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent.js +20 -3
  23. package/dist/core/allow-entry.d.ts +4 -0
  24. package/dist/core/ask-origin.d.ts +1 -1
  25. package/dist/core/ask-origin.js +2 -2
  26. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  27. package/dist/core/ask-unresolvable-notice.js +10 -3
  28. package/dist/core/auto-compaction.d.ts +7 -5
  29. package/dist/core/background-agent-store.d.ts +7 -0
  30. package/dist/core/background-agent-store.js +3 -0
  31. package/dist/core/checkpoint-queries.d.ts +9 -6
  32. package/dist/core/checkpoint-queries.js +8 -3
  33. package/dist/core/checkpoint-store.d.ts +5 -1
  34. package/dist/core/context-settings.d.ts +40 -9
  35. package/dist/core/context-settings.js +32 -10
  36. package/dist/core/engine-attestation.d.ts +26 -6
  37. package/dist/core/engine-attestation.js +5 -1
  38. package/dist/core/engine-notice.d.ts +24 -1
  39. package/dist/core/extension-requester.d.ts +9 -0
  40. package/dist/core/extension-requester.js +7 -0
  41. package/dist/core/file-history-store.d.ts +28 -0
  42. package/dist/core/file-history-store.js +48 -5
  43. package/dist/core/fs-write-gate-policy.js +1 -1
  44. package/dist/core/gate-fold.js +2 -0
  45. package/dist/core/gate-lanes.js +2 -0
  46. package/dist/core/gate-outcome.d.ts +39 -2
  47. package/dist/core/gate-outcome.js +20 -1
  48. package/dist/core/governance-codes.d.ts +3 -1
  49. package/dist/core/governance-codes.js +4 -0
  50. package/dist/core/leg-identity.d.ts +19 -1
  51. package/dist/core/leg-identity.js +12 -0
  52. package/dist/core/mailbox-store.d.ts +39 -4
  53. package/dist/core/mailbox-store.js +14 -2
  54. package/dist/core/memory-engine/consolidation.d.ts +3 -2
  55. package/dist/core/memory-engine/consolidation.js +16 -0
  56. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  57. package/dist/core/memory-engine/control-objects.js +151 -0
  58. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  59. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  60. package/dist/core/memory-engine/delegation-settlement.d.ts +21 -5
  61. package/dist/core/memory-engine/delegation-settlement.js +217 -26
  62. package/dist/core/memory-engine/dual-root.js +2 -2
  63. package/dist/core/memory-engine/engine.d.ts +38 -23
  64. package/dist/core/memory-engine/engine.js +14 -14
  65. package/dist/core/memory-engine/file-backend.d.ts +41 -65
  66. package/dist/core/memory-engine/file-backend.js +59 -166
  67. package/dist/core/memory-engine/index.d.ts +3 -2
  68. package/dist/core/memory-engine/index.js +2 -1
  69. package/dist/core/memory-engine/layout.d.ts +6 -1
  70. package/dist/core/memory-engine/layout.js +12 -7
  71. package/dist/core/memory-engine/memory-backend-contract.d.ts +10 -3
  72. package/dist/core/memory-engine/memory-backend-contract.js +158 -2
  73. package/dist/core/memory-engine/memory-deployment.d.ts +11 -3
  74. package/dist/core/memory-engine/memory-deployment.js +31 -6
  75. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  76. package/dist/core/memory-engine/origin-clearance.js +68 -9
  77. package/dist/core/memory-engine/session-write-home.d.ts +34 -1
  78. package/dist/core/memory-engine/session-write-home.js +37 -10
  79. package/dist/core/memory-engine/types.d.ts +44 -7
  80. package/dist/core/memory-engine/types.js +2 -1
  81. package/dist/core/mode-policy.js +3 -3
  82. package/dist/core/mods/agent-stations.d.ts +18 -0
  83. package/dist/core/mods/agent-stations.js +8 -6
  84. package/dist/core/mods/extension-call.d.ts +4 -0
  85. package/dist/core/mods/extension-call.js +8 -0
  86. package/dist/core/mods/tool-call.js +3 -4
  87. package/dist/core/parent-spec-seat.d.ts +2 -2
  88. package/dist/core/peer-channel.d.ts +5 -0
  89. package/dist/core/permission-rule-consent.d.ts +21 -10
  90. package/dist/core/permission-rule-consent.js +50 -23
  91. package/dist/core/permission-rule-store.d.ts +41 -16
  92. package/dist/core/permission-rule-store.js +2 -0
  93. package/dist/core/refusal-echo.d.ts +20 -0
  94. package/dist/core/refusal-echo.js +33 -0
  95. package/dist/core/retention.d.ts +180 -10
  96. package/dist/core/retention.js +45 -0
  97. package/dist/core/retired-keys.d.ts +5 -0
  98. package/dist/core/retired-keys.js +3 -0
  99. package/dist/core/rule-offer-read.d.ts +0 -4
  100. package/dist/core/rule-offer-read.js +2 -18
  101. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  102. package/dist/core/runner/classifier-ladder.js +4 -2
  103. package/dist/core/runner/compact-session.js +10 -7
  104. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  105. package/dist/core/runner/compaction-call-options.js +3 -2
  106. package/dist/core/runner/contracts.d.ts +21 -2
  107. package/dist/core/runner/delegation-owner.d.ts +10 -3
  108. package/dist/core/runner/delegation-owner.js +4 -1
  109. package/dist/core/runner/gate-exit.d.ts +6 -0
  110. package/dist/core/runner/gate-exit.js +11 -2
  111. package/dist/core/runner/memory-consolidation-driver.d.ts +4 -2
  112. package/dist/core/runner/memory-consolidation-driver.js +8 -5
  113. package/dist/core/runner/prepare-ask-lane.js +3 -3
  114. package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -1
  115. package/dist/core/runner/prepare-caps-and-workflow.js +2 -2
  116. package/dist/core/runner/prepare-config-doors.js +4 -0
  117. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  118. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  119. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  120. package/dist/core/runner/prepare-gate-stations.js +5 -5
  121. package/dist/core/runner/prepare-hands-readface.js +1 -1
  122. package/dist/core/runner/prepare-inherited-gate.d.ts +3 -1
  123. package/dist/core/runner/prepare-inherited-gate.js +4 -2
  124. package/dist/core/runner/prepare-memory.d.ts +4 -0
  125. package/dist/core/runner/prepare-memory.js +14 -20
  126. package/dist/core/runner/prepare-policy-chain.js +7 -7
  127. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  128. package/dist/core/runner/prepare-task.js +15 -10
  129. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  130. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  131. package/dist/core/runner/resume-admission.d.ts +2 -2
  132. package/dist/core/runner/resume-admission.js +2 -23
  133. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  134. package/dist/core/runner/role-resolution-table.js +62 -0
  135. package/dist/core/runner/run-compaction-machinery.js +2 -2
  136. package/dist/core/runner/run-identity-wiring.js +12 -9
  137. package/dist/core/runner/run-leg.js +8 -4
  138. package/dist/core/runner/run-notification-lane.js +22 -22
  139. package/dist/core/runner/run-recovery-lanes.js +3 -3
  140. package/dist/core/runner/run-terminal-adoption.js +1 -1
  141. package/dist/core/runner/run-turn-boundary.js +14 -15
  142. package/dist/core/runner/runtask.js +1 -1
  143. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  144. package/dist/core/runner/tool-occurrence.js +2 -2
  145. package/dist/core/runner-deps.d.ts +1 -1
  146. package/dist/core/session-checkout.d.ts +63 -3
  147. package/dist/core/session-checkout.js +152 -58
  148. package/dist/core/shell-read-silence.js +8 -0
  149. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  150. package/dist/core/task-event.d.ts +9 -5
  151. package/dist/core/task-notification.d.ts +110 -31
  152. package/dist/core/task-notification.js +180 -100
  153. package/dist/core/task-registry-agent.d.ts +11 -0
  154. package/dist/core/task-registry-agent.js +11 -3
  155. package/dist/core/task-registry-shared.d.ts +7 -0
  156. package/dist/core/task-registry.d.ts +18 -0
  157. package/dist/core/task-registry.js +27 -8
  158. package/dist/core/task-spec.d.ts +7 -2
  159. package/dist/core/tool-errors.d.ts +14 -6
  160. package/dist/core/tool-errors.js +1 -1
  161. package/dist/core/tool-policy.d.ts +18 -1
  162. package/dist/core/tool-policy.js +16 -7
  163. package/dist/core/tool-result-store.d.ts +20 -0
  164. package/dist/core/tool-spec.d.ts +4 -0
  165. package/dist/core/trace.d.ts +3 -2
  166. package/dist/core/workflow-journal-store.d.ts +11 -0
  167. package/dist/core/workflow-journal-store.js +7 -0
  168. package/dist/core/workflow-run-store.d.ts +9 -0
  169. package/dist/core/workflow-run-store.js +6 -0
  170. package/dist/engine/compaction/compaction.d.ts +2 -1
  171. package/dist/engine/harness/types.d.ts +1 -0
  172. package/dist/engine/session/session.d.ts +7 -1
  173. package/dist/engine/session/session.js +5 -2
  174. package/dist/index.d.ts +7 -5
  175. package/dist/index.js +7 -5
  176. package/dist/orchestration/run-workflow-tool.d.ts +4 -0
  177. package/dist/orchestration/run-workflow-tool.js +7 -0
  178. package/dist/orchestration/workflow-types.d.ts +2 -1
  179. package/dist/orchestration/workflow.d.ts +3 -0
  180. package/dist/orchestration/workflow.js +2 -1
  181. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  182. package/dist/stores/file/checkpoint-store.js +4 -1
  183. package/dist/stores/file/file-history-store.d.ts +13 -0
  184. package/dist/stores/file/file-history-store.js +75 -13
  185. package/dist/stores/file/index.d.ts +11 -1
  186. package/dist/stores/file/index.js +7 -11
  187. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  188. package/dist/stores/file/permission-rule-store.js +75 -7
  189. package/dist/stores/file/tool-result-store.d.ts +14 -0
  190. package/dist/stores/file/tool-result-store.js +39 -2
  191. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  192. package/dist/stores/file/workflow-journal-store.js +17 -0
  193. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  194. package/dist/stores/file/workflow-run-store.js +15 -0
  195. package/dist/tools/fs/read-deny.d.ts +15 -2
  196. package/dist/tools/fs/read-deny.js +10 -2
  197. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  198. package/dist/tools/fs/shell-read-check.js +7 -7
  199. package/package.json +2 -2
  200. package/test/export-surface.snapshot.json +63 -1
  201. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  202. package/wire-changes/core@7.64.0.json +2653 -0
  203. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  204. package/wire-changes/primitives@7.64.0.json +30 -0
@@ -0,0 +1,48 @@
1
+ import { type MemoryControlObjectKind, type MemoryGovernanceDocName, type MemoryGovernanceStore } from "./types.js";
2
+ /** The carrier records a replica control plane still holds. */
3
+ export interface ReplicaControlPlaneStrays {
4
+ /** The governance documents with a file (or a journal) in the replica. */
5
+ readonly docs: readonly MemoryGovernanceDocName[];
6
+ /** How many control objects of each kind the replica holds (kinds it holds none of are absent). */
7
+ readonly objects: Readonly<Partial<Record<MemoryControlObjectKind, number>>>;
8
+ }
9
+ /** One record adoption handled: a document (`doc:<name>`) or an object (`<kind>/<name>`). */
10
+ export interface AdoptedControlRecord {
11
+ readonly record: string;
12
+ /** What the carrier holds now, never what became of the replica's copy (which stays): `"written"` ⇔ the carrier
13
+ * lacked the record and now holds the same value; `"converged"` ⇔ it already held the same value. */
14
+ readonly outcome: "written" | "converged";
15
+ /** sha-256 of the record as the replica held it: an object's bytes, a document's committed JSON value. */
16
+ readonly digest: string;
17
+ }
18
+ /** {@link adoptReplicaControlPlane}'s answer. */
19
+ export interface ControlPlaneAdoptionReport {
20
+ /** Records the carrier now holds with the replica's value (the replica keeps its copy). */
21
+ readonly adopted: readonly AdoptedControlRecord[];
22
+ /** Records whose adoption did not complete, each with why — a different value already in the carrier, a record that
23
+ * could not be read or verified, or a receipt row that could not be written (then the carrier may already hold the
24
+ * value, and a re-run converges it). */
25
+ readonly refused: readonly {
26
+ readonly record: string;
27
+ readonly reason: string;
28
+ }[];
29
+ }
30
+ /** The replica's body-less record of which of its records the carrier holds with the same value (one row per record and digest). */
31
+ export declare const CONTROL_PLANE_ADOPTION_FILE = "control-plane-adoption.json";
32
+ /** The carrier records `controlDir` holds — documents with a file or journal, objects by kind. An enumeration that
33
+ * fails throws `ControlPlaneCorruptError` (never an empty answer). */
34
+ export declare function replicaControlPlaneStrays(controlDir: string): ReplicaControlPlaneStrays;
35
+ /**
36
+ * Copy the replica control plane's carrier records into `carrier` (see the module note). Answers what the carrier now
37
+ * holds with the replica's value and what was refused; the replica's records are not removed either way. When `carrier`
38
+ * is the File store over `controlDir` itself there is nothing to hand over and the answer is empty.
39
+ */
40
+ export declare function adoptReplicaControlPlane(controlDir: string, carrier: MemoryGovernanceStore, opts?: {
41
+ readonly now?: () => number;
42
+ }): Promise<ControlPlaneAdoptionReport>;
43
+ /** The replica's adoption receipt: one body-less row per adopted record (what, the digest of its bytes, when). */
44
+ export declare function readControlPlaneAdoptionReceipt(controlDir: string): ReadonlyArray<{
45
+ readonly record: string;
46
+ readonly digest: string;
47
+ readonly at: number;
48
+ }>;
@@ -0,0 +1,159 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync, statSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { MEMORY_CONTROL_OBJECT_KINDS, MEMORY_GOVERNANCE_DOC_NAMES } from "./types.js";
6
+ import { ControlPlaneCorruptError, fileGovernanceDocOf, lockedStrictUpdate, readStrictSidecar } from "./layout.js";
7
+ import { getFileControlObject, listFileControlObjects } from "./control-objects.js";
8
+ import { fileGovernanceStoreDir } from "./consolidation.js";
9
+ import { moveOriginClearanceCustodyOut } from "./origin-clearance.js";
10
+ import { thrownText } from "../thrown-value.js";
11
+ export const CONTROL_PLANE_ADOPTION_FILE = "control-plane-adoption.json";
12
+ function coerceReceipt(raw) {
13
+ if (raw === undefined)
14
+ return { version: 1, adopted: [] };
15
+ if (typeof raw !== "object" || raw === null || Reflect.get(raw, "version") !== 1 || !Array.isArray(Reflect.get(raw, "adopted"))) {
16
+ throw new ControlPlaneCorruptError("memory control-plane adoption receipt has the wrong shape (fail-closed)");
17
+ }
18
+ return raw;
19
+ }
20
+ function sha256Hex(bytes) {
21
+ return createHash("sha256").update(bytes).digest("hex");
22
+ }
23
+ function standsAt(path) {
24
+ try {
25
+ lstatSync(path);
26
+ return true;
27
+ }
28
+ catch (err) {
29
+ if (Reflect.get(err, "code") === "ENOENT")
30
+ return false;
31
+ throw new ControlPlaneCorruptError(`memory control plane: ${path} could not be probed (${String(Reflect.get(err, "code") ?? "io error")}) (fail-closed)`, { cause: err });
32
+ }
33
+ }
34
+ export function replicaControlPlaneStrays(controlDir) {
35
+ const docs = MEMORY_GOVERNANCE_DOC_NAMES.filter((name) => {
36
+ const file = join(controlDir, fileGovernanceDocOf(name).file);
37
+ return standsAt(file) || standsAt(`${file}.journal`);
38
+ });
39
+ const objects = {};
40
+ for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
41
+ const n = listFileControlObjects(controlDir, kind).length;
42
+ if (n > 0)
43
+ objects[kind] = n;
44
+ }
45
+ return { docs, objects };
46
+ }
47
+ function carriesThisDirectory(carrier, controlDir) {
48
+ const dir = fileGovernanceStoreDir(carrier);
49
+ if (dir === undefined)
50
+ return false;
51
+ if (resolve(dir) === resolve(controlDir))
52
+ return true;
53
+ try {
54
+ const a = statSync(dir);
55
+ const b = statSync(controlDir);
56
+ return a.dev === b.dev && a.ino === b.ino;
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
62
+ export async function adoptReplicaControlPlane(controlDir, carrier, opts) {
63
+ const now = opts?.now ?? Date.now;
64
+ const adopted = [];
65
+ const refused = [];
66
+ if (carriesThisDirectory(carrier, controlDir))
67
+ return { adopted, refused };
68
+ const receipt = (record, digest) => {
69
+ lockedStrictUpdate(controlDir, CONTROL_PLANE_ADOPTION_FILE, "memory control-plane adoption receipt", coerceReceipt, (rec) => {
70
+ if (rec.adopted.some((r) => r.record === record && r.digest === digest))
71
+ return { result: undefined };
72
+ rec.adopted.push({ record, digest, at: now() });
73
+ return { next: rec, result: undefined };
74
+ });
75
+ };
76
+ const clearances = join(controlDir, fileGovernanceDocOf("origin-clearances").file);
77
+ if (standsAt(clearances) || standsAt(`${clearances}.journal`)) {
78
+ try {
79
+ moveOriginClearanceCustodyOut(controlDir);
80
+ }
81
+ catch (err) {
82
+ refused.push({ record: "doc:origin-clearances", reason: `its inline custody could not be moved out first: ${thrownText(err)}` });
83
+ }
84
+ }
85
+ for (const kind of MEMORY_CONTROL_OBJECT_KINDS) {
86
+ for (const name of listFileControlObjects(controlDir, kind)) {
87
+ const record = `${kind}/${name}`;
88
+ try {
89
+ const bytes = getFileControlObject(controlDir, kind, name);
90
+ if (bytes === undefined)
91
+ continue;
92
+ const digest = sha256Hex(bytes);
93
+ const outcome = (await carrier.putObject(kind, name, bytes)) === "created" ? "written" : "converged";
94
+ const held = await carrier.getObject(kind, name);
95
+ if (held === undefined || sha256Hex(held) !== digest) {
96
+ refused.push({ record, reason: outcome === "converged" ? "the carrier already holds an object of this name with different bytes" : "the carrier's copy does not read back the same" });
97
+ continue;
98
+ }
99
+ const again = getFileControlObject(controlDir, kind, name);
100
+ if (again === undefined || sha256Hex(again) !== digest) {
101
+ refused.push({ record, reason: "the replica's bytes changed while they were adopted" });
102
+ continue;
103
+ }
104
+ receipt(record, digest);
105
+ adopted.push({ record, outcome, digest });
106
+ }
107
+ catch (err) {
108
+ refused.push({ record, reason: thrownText(err) });
109
+ }
110
+ }
111
+ }
112
+ const before = refused.map((r) => r.record);
113
+ if (before.length > 0) {
114
+ for (const name of replicaControlPlaneStrays(controlDir).docs) {
115
+ if (!before.includes(`doc:${name}`))
116
+ refused.push({ record: `doc:${name}`, reason: `left in the replica until every record before it is adopted (refused: ${before.join(", ")})` });
117
+ }
118
+ return { adopted, refused };
119
+ }
120
+ for (const name of MEMORY_GOVERNANCE_DOC_NAMES) {
121
+ const record = `doc:${name}`;
122
+ const { file, what } = fileGovernanceDocOf(name);
123
+ const path = join(controlDir, file);
124
+ try {
125
+ if (!standsAt(path) && !standsAt(`${path}.journal`))
126
+ continue;
127
+ const value = readStrictSidecar(controlDir, file, what);
128
+ if (value === undefined)
129
+ continue;
130
+ const digest = sha256Hex(JSON.stringify(value));
131
+ const outcome = await carrier.updateDoc(name, (raw) => raw, (cur) => {
132
+ if (cur === undefined)
133
+ return { next: value, result: "written" };
134
+ return { result: isDeepStrictEqual(cur, value) ? "converged" : "different" };
135
+ });
136
+ if (outcome === "different") {
137
+ refused.push({ record, reason: "the carrier already holds a different document of this name" });
138
+ continue;
139
+ }
140
+ if (!isDeepStrictEqual(await carrier.readDoc(name), value)) {
141
+ refused.push({ record, reason: "the carrier's copy does not read back the same" });
142
+ continue;
143
+ }
144
+ if (!isDeepStrictEqual(readStrictSidecar(controlDir, file, what), value)) {
145
+ refused.push({ record, reason: "the replica's document changed while it was adopted" });
146
+ continue;
147
+ }
148
+ receipt(record, digest);
149
+ adopted.push({ record, outcome, digest });
150
+ }
151
+ catch (err) {
152
+ refused.push({ record, reason: thrownText(err) });
153
+ }
154
+ }
155
+ return { adopted, refused };
156
+ }
157
+ export function readControlPlaneAdoptionReceipt(controlDir) {
158
+ return coerceReceipt(readStrictSidecar(controlDir, CONTROL_PLANE_ADOPTION_FILE, "memory control-plane adoption receipt")).adopted;
159
+ }
@@ -268,8 +268,10 @@ export declare function resolveSessionAccountRecord(docs: MemoryGovernanceDocs,
268
268
  requestId: string;
269
269
  now: () => number;
270
270
  }): Promise<void>;
271
- export declare const HOLDS_FILE = "holds.json";
272
- export declare const HOLD_DIR = "hold";
271
+ /** The hold ledger's file: the File store's coordinate of the governance document `holds`. */
272
+ export declare const HOLDS_FILE: string;
273
+ /** The hold custody directory: the File store's directory of the control-object kind `hold`. */
274
+ export declare const HOLD_DIR: string;
273
275
  export type HoldStatus = "capturing" | "held" | "released" | "disposed";
274
276
  export type HoldTerminal = "dirty" | "expired" | "conflict" | "discarded" | "capture_lost";
275
277
  export interface HoldRow {
@@ -385,18 +387,32 @@ export declare function openInstructionHold(controlDir: string, input: {
385
387
  * - `capturing` + custody absent + plane file gone ⇒ `capture_lost` (nothing to hold).
386
388
  * - `held` + plane file REAPPEARED at the seat ⇒ left alone (a fresh write is a fresh file —
387
389
  * the next harvest judges it on its own; the hold's custody bytes stay the hold's).
390
+ * - `disposed` + the row names its quarantine seat + the custody file is still at the custody seat
391
+ * ⇒ the disposal's move finishes (the row is written before the bytes move).
388
392
  */
389
393
  export declare function reconcileHolds(controlDir: string, input: {
390
394
  homeOf: (scope: string) => string;
391
395
  now: () => number;
392
396
  onStranded: (scope: string, line: string) => void;
393
397
  }): void;
394
- /** Dispose one held row: custody bytes move to the quarantine directory (host-auditable), the row
395
- * records its terminal + quarantineName (from-row-to-bytes addressing survives every terminal). */
398
+ /** The quarantine seat of a hold's custody bytes: a function of the ROW, never of a clock. The same
399
+ * row names the same seat on every call, in every process, after any crash — the old
400
+ * `<ms>-hold-<captureName>` shape with the row's own content digest where the wall clock was. */
401
+ export declare function holdQuarantineNameOf(row: Pick<HoldRow, "captureName" | "contentDigest">): string;
402
+ /** Dispose one held row: the row records its terminal and the quarantine seat NAMED BY THE ROW
403
+ * ({@link holdQuarantineNameOf}) first, then the custody bytes move there (host-auditable;
404
+ * from-row-to-bytes addressing survives every terminal). Row first, bytes second: a crash between
405
+ * the two leaves a row whose bytes are at the custody seat or the quarantine seat — both of which
406
+ * {@link readHoldCustody} tries — and {@link reconcileHolds} finishes the move; the reverse order
407
+ * would leave bytes in quarantine under a name no row recorded. Whether the row names a seat is read
408
+ * INSIDE the ledger lock, from what stands at the custody seat and the quarantine seat at that
409
+ * moment: a row with no custody bytes anywhere records the terminal with no name (nothing to move).
410
+ * The verdict always lands: a quarantine seat held by something that is not the hold's bytes records
411
+ * the terminal with no name, leaves the custody bytes where they are and replaces nothing — and then
412
+ * refuses loudly (the caller hears it; a refused intake is terminal all the same). */
396
413
  export declare function disposeHold(controlDir: string, input: {
397
414
  holdId: string;
398
415
  terminal: HoldTerminal;
399
- now: () => number;
400
416
  }): {
401
417
  ok: boolean;
402
418
  quarantineName?: string;
@@ -3,6 +3,7 @@ import { closeSync, existsSync, fsyncSync, linkSync, lstatSync, openSync, readFi
3
3
  import { basename, dirname, join } from "node:path";
4
4
  import { QUARANTINE_DIR, appendChallengeEvents, claimStaging, ensureDirExists, fileGovernanceDocOf, isSameFile, lockedStrictUpdate, mintStagingName, readStrictSidecar, stagingNamePattern, v1MemoryPathKeyResolver, lineageContributionsOfSession, markSessionPolluted, readProjectionDebts, readSessionPollution, ControlPlaneCorruptError } from "./layout.js";
5
5
  import { thrownText } from "../thrown-value.js";
6
+ import { fileControlObjectDirOf } from "./control-objects.js";
6
7
  function reqStr(v) {
7
8
  return typeof v === "string" && v.length > 0;
8
9
  }
@@ -428,8 +429,9 @@ export async function resolveSessionAccountRecord(docs, controlDir, input) {
428
429
  return { next: rec, result: undefined };
429
430
  });
430
431
  }
431
- export const HOLDS_FILE = "holds.json";
432
- export const HOLD_DIR = "hold";
432
+ export const HOLDS_FILE = fileGovernanceDocOf("holds").file;
433
+ const HOLDS_WHAT = fileGovernanceDocOf("holds").what;
434
+ export const HOLD_DIR = fileControlObjectDirOf("hold");
433
435
  const HOLD_STATUSES = new Set(["capturing", "held", "released", "disposed"]);
434
436
  const HOLD_TERMINALS = new Set(["dirty", "expired", "conflict", "discarded", "capture_lost"]);
435
437
  function coerceHolds(raw) {
@@ -483,10 +485,10 @@ function holdsOnDiskAreV1(raw) {
483
485
  return typeof raw === "object" && raw !== null && raw.version === 1;
484
486
  }
485
487
  export function readHolds(controlDir) {
486
- const raw = readStrictSidecar(controlDir, HOLDS_FILE, "memory instruction-hold ledger");
488
+ const raw = readStrictSidecar(controlDir, HOLDS_FILE, HOLDS_WHAT);
487
489
  if (!holdsOnDiskAreV1(raw))
488
490
  return coerceHolds(raw).rows;
489
- return lockedStrictUpdate(controlDir, HOLDS_FILE, "memory instruction-hold ledger", coerceHolds, (again) => ({ next: again, result: again.rows }));
491
+ return lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (again) => ({ next: again, result: again.rows }));
490
492
  }
491
493
  function sha256(buf) {
492
494
  return createHash("sha256").update(buf).digest("hex");
@@ -575,14 +577,14 @@ export function openInstructionHold(controlDir, input) {
575
577
  const refuse = (rawReason, terminal) => {
576
578
  const reason = thirdWriterStrandedAt === undefined ? rawReason : `${rawReason}; a concurrent writer's bytes are preserved at ${thirdWriterStrandedAt}`;
577
579
  try {
578
- disposeHold(controlDir, { holdId, terminal, now: input.now });
580
+ disposeHold(controlDir, { holdId, terminal });
579
581
  }
580
582
  catch {
581
583
  }
582
584
  return { ok: false, holdId, reason };
583
585
  };
584
586
  try {
585
- lockedStrictUpdate(controlDir, HOLDS_FILE, "memory instruction-hold ledger", coerceHolds, (rec) => {
587
+ lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
586
588
  if (rec.rows.some((r) => r.holdId === holdId))
587
589
  return { result: undefined };
588
590
  rec.rows.push({
@@ -644,7 +646,7 @@ export function openInstructionHold(controlDir, input) {
644
646
  }
645
647
  }
646
648
  try {
647
- lockedStrictUpdate(controlDir, HOLDS_FILE, "memory instruction-hold ledger", coerceHolds, (rec) => {
649
+ lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
648
650
  const row = rec.rows.find((r) => r.holdId === holdId);
649
651
  if (row === undefined || row.status !== "capturing")
650
652
  return { result: undefined };
@@ -727,7 +729,8 @@ export function reconcileHolds(controlDir, input) {
727
729
  discloseStranded(row.holdId, row.scope, row.rel, retired.at);
728
730
  }
729
731
  };
730
- const rows = readHolds(controlDir).filter((r) => r.status === "capturing");
732
+ const ledger = readHolds(controlDir);
733
+ const rows = ledger.filter((r) => r.status === "capturing");
731
734
  for (const row of rows) {
732
735
  const custody = join(holdDir, row.captureName);
733
736
  let custodyBytes;
@@ -783,7 +786,7 @@ export function reconcileHolds(controlDir, input) {
783
786
  terminalLost = true;
784
787
  }
785
788
  }
786
- lockedStrictUpdate(controlDir, HOLDS_FILE, "memory instruction-hold ledger", coerceHolds, (rec) => {
789
+ lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
787
790
  const r = rec.rows.find((x) => x.holdId === row.holdId);
788
791
  if (r === undefined || r.status !== "capturing")
789
792
  return { result: undefined };
@@ -797,36 +800,224 @@ export function reconcileHolds(controlDir, input) {
797
800
  return { next: rec, result: undefined };
798
801
  });
799
802
  }
803
+ let custodyNames;
804
+ try {
805
+ custodyNames = new Set(readdirSync(holdDir));
806
+ }
807
+ catch {
808
+ custodyNames = new Set();
809
+ }
810
+ for (const row of ledger) {
811
+ const quarantineName = row.disposition?.quarantineName;
812
+ if (row.status !== "disposed" || quarantineName === undefined || !custodyNames.has(row.captureName))
813
+ continue;
814
+ try {
815
+ const moved = moveCustodyToSeat(controlDir, row, quarantineName);
816
+ if (moved.at === "custody") {
817
+ input.onStranded(row.scope, `instruction hold ${row.holdId} (disposed, ${row.disposition.terminal}): its custody bytes could not be moved to the quarantine seat ${quarantineName} (${moved.code}) — they stay at ${join(holdDir, row.captureName)} for host recovery, and the move is retried at every harvest`);
818
+ }
819
+ }
820
+ catch (err) {
821
+ input.onStranded(row.scope, `instruction hold ${row.holdId} (disposed, ${row.disposition.terminal}): ${thrownText(err)}`);
822
+ }
823
+ }
824
+ adoptOrphanedQuarantineBytes(controlDir, ledger);
800
825
  }
801
- export function disposeHold(controlDir, input) {
802
- const rows = readHolds(controlDir);
803
- const row = rows.find((r) => r.holdId === input.holdId);
804
- if (row === undefined || row.status === "disposed" || row.status === "released")
805
- return { ok: false };
826
+ function adoptOrphanedQuarantineBytes(controlDir, snapshot) {
827
+ const holdDir = join(controlDir, HOLD_DIR);
828
+ const qDir = join(controlDir, QUARANTINE_DIR);
829
+ let listing;
830
+ try {
831
+ listing = readdirSync(qDir).filter((n) => n.includes("-hold-") && safeBasename(n)).sort();
832
+ }
833
+ catch {
834
+ return;
835
+ }
836
+ const seats = new Set();
837
+ for (const r of snapshot)
838
+ if (r.disposition?.quarantineName !== undefined)
839
+ seats.add(r.disposition.quarantineName);
840
+ if (listing.every((n) => seats.has(n)))
841
+ return;
842
+ lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
843
+ const claimed = new Set();
844
+ for (const r of rec.rows)
845
+ if (r.disposition?.quarantineName !== undefined)
846
+ claimed.add(r.disposition.quarantineName);
847
+ const digests = new Map();
848
+ const digestOf = (name) => {
849
+ if (!digests.has(name)) {
850
+ let digest;
851
+ try {
852
+ const path = join(qDir, name);
853
+ digest = lstatSync(path).isFile() ? sha256(readFileSync(path)) : undefined;
854
+ }
855
+ catch {
856
+ digest = undefined;
857
+ }
858
+ digests.set(name, digest);
859
+ }
860
+ return digests.get(name);
861
+ };
862
+ const wants = (r) => {
863
+ if (existsSync(join(holdDir, r.captureName)))
864
+ return false;
865
+ if (r.status === "held")
866
+ return true;
867
+ if (r.status !== "disposed")
868
+ return false;
869
+ const seat = r.disposition?.quarantineName;
870
+ return seat === undefined || !existsSync(join(qDir, seat));
871
+ };
872
+ const endsWithCapture = (name, r) => name.endsWith(`-hold-${r.captureName}`);
873
+ const reservedForOther = (name) => rec.rows.some((r) => endsWithCapture(name, r));
874
+ const wanting = rec.rows.filter(wants);
875
+ const found = new Map();
876
+ for (const r of wanting) {
877
+ const f = listing.find((n) => !claimed.has(n) && endsWithCapture(n, r) && digestOf(n) === r.contentDigest);
878
+ if (f !== undefined) {
879
+ found.set(r, f);
880
+ claimed.add(f);
881
+ }
882
+ }
883
+ for (const r of wanting) {
884
+ if (found.has(r))
885
+ continue;
886
+ const f = listing.find((n) => !claimed.has(n) && !reservedForOther(n) && digestOf(n) === r.contentDigest);
887
+ if (f !== undefined) {
888
+ found.set(r, f);
889
+ claimed.add(f);
890
+ }
891
+ }
892
+ let changed = false;
893
+ for (const [r, f] of found) {
894
+ if (r.status === "disposed") {
895
+ r.disposition = { ...r.disposition, quarantineName: f };
896
+ changed = true;
897
+ continue;
898
+ }
899
+ try {
900
+ ensureDirExists(holdDir);
901
+ moveNoReplace(join(qDir, f), join(holdDir, r.captureName));
902
+ }
903
+ catch {
904
+ }
905
+ }
906
+ return changed ? { next: rec, result: undefined } : { result: undefined };
907
+ });
908
+ }
909
+ export function holdQuarantineNameOf(row) {
910
+ return `${row.contentDigest.slice(0, 16)}-hold-${row.captureName}`;
911
+ }
912
+ function quarantineSeatState(seat, digest) {
913
+ let isFile;
914
+ try {
915
+ isFile = lstatSync(seat).isFile();
916
+ }
917
+ catch (err) {
918
+ return err.code === "ENOENT" ? "absent" : "foreign";
919
+ }
920
+ if (!isFile)
921
+ return "foreign";
922
+ try {
923
+ return sha256(readFileSync(seat)) === digest ? "holds" : "foreign";
924
+ }
925
+ catch {
926
+ return "foreign";
927
+ }
928
+ }
929
+ function foreignSeatRefusal(holdId, seat) {
930
+ return new ControlPlaneCorruptError(`memory instruction hold ${holdId}: the quarantine seat ${seat} is occupied by something that is not the hold's captured bytes — refusing to replace or adopt it (fail-closed; inspect or remove it, and the next harvest converges)`);
931
+ }
932
+ function moveCustodyToSeat(controlDir, row, seatName) {
806
933
  const custody = join(controlDir, HOLD_DIR, row.captureName);
807
- const quarantineName = `${input.now()}-hold-${row.captureName}`;
808
934
  const qDir = join(controlDir, QUARANTINE_DIR);
809
- let moved = false;
935
+ const seat = join(qDir, seatName);
936
+ const atSeat = () => {
937
+ const state = quarantineSeatState(seat, row.contentDigest);
938
+ if (state === "foreign")
939
+ throw foreignSeatRefusal(row.holdId, seat);
940
+ if (state === "absent")
941
+ return undefined;
942
+ try {
943
+ if (sha256(readFileSync(custody)) === row.contentDigest)
944
+ unlinkSync(custody);
945
+ }
946
+ catch {
947
+ }
948
+ return { at: "seat" };
949
+ };
950
+ const there = atSeat();
951
+ if (there !== undefined)
952
+ return there;
953
+ if (!existsSync(custody))
954
+ return { at: "none" };
810
955
  try {
811
956
  ensureDirExists(qDir);
812
- renameSync(custody, join(qDir, quarantineName));
813
- moved = true;
957
+ }
958
+ catch (err) {
959
+ return { at: "custody", code: err.code ?? "mkdir error" };
960
+ }
961
+ if (moveNoReplace(custody, seat) === "moved")
962
+ return { at: "seat" };
963
+ return atSeat() ?? { at: "custody", code: "move refused" };
964
+ }
965
+ function moveNoReplace(from, to) {
966
+ try {
967
+ linkSync(from, to);
968
+ }
969
+ catch (err) {
970
+ const code = err.code;
971
+ if (code === "EEXIST")
972
+ return "occupied";
973
+ if (code === "ENOENT")
974
+ return "refused";
975
+ try {
976
+ renameSync(from, to);
977
+ return "moved";
978
+ }
979
+ catch {
980
+ return "refused";
981
+ }
982
+ }
983
+ try {
984
+ unlinkSync(from);
814
985
  }
815
986
  catch {
816
- moved = existsSync(join(qDir, quarantineName));
817
987
  }
818
- lockedStrictUpdate(controlDir, HOLDS_FILE, "memory instruction-hold ledger", coerceHolds, (rec) => {
988
+ return "moved";
989
+ }
990
+ export function disposeHold(controlDir, input) {
991
+ const row = readHolds(controlDir).find((r) => r.holdId === input.holdId);
992
+ if (row === undefined || row.status === "disposed" || row.status === "released")
993
+ return { ok: false };
994
+ const quarantineName = holdQuarantineNameOf(row);
995
+ if (!safeBasename(quarantineName)) {
996
+ throw new ControlPlaneCorruptError(`memory instruction hold ${row.holdId}: its digest and capture name do not make a safe quarantine file name — refusing (fail-closed)`);
997
+ }
998
+ const seatPath = join(controlDir, QUARANTINE_DIR, quarantineName);
999
+ const verdict = lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
819
1000
  const r = rec.rows.find((x) => x.holdId === input.holdId);
820
1001
  if (r === undefined || r.status === "disposed" || r.status === "released")
821
1002
  return { result: undefined };
1003
+ const custodyHere = existsSync(join(controlDir, HOLD_DIR, r.captureName));
1004
+ const seatState = quarantineSeatState(seatPath, r.contentDigest);
1005
+ const named = seatState === "holds" || (custodyHere && seatState === "absent");
822
1006
  r.status = "disposed";
823
- r.disposition = { terminal: input.terminal, ...(moved ? { quarantineName } : {}) };
824
- return { next: rec, result: undefined };
1007
+ r.disposition = { terminal: input.terminal, ...(named ? { quarantineName } : {}) };
1008
+ return { next: rec, result: { named, refused: custodyHere && seatState === "foreign" } };
825
1009
  });
826
- return { ok: true, ...(moved ? { quarantineName } : {}) };
1010
+ if (verdict === undefined)
1011
+ return { ok: false };
1012
+ if (verdict.refused)
1013
+ throw foreignSeatRefusal(row.holdId, seatPath);
1014
+ if (!verdict.named)
1015
+ return { ok: true };
1016
+ const moved = moveCustodyToSeat(controlDir, row, quarantineName);
1017
+ return { ok: true, ...(moved.at === "seat" ? { quarantineName } : {}) };
827
1018
  }
828
1019
  export function markHoldReleased(controlDir, input) {
829
- const captureName = lockedStrictUpdate(controlDir, HOLDS_FILE, "memory instruction-hold ledger", coerceHolds, (rec) => {
1020
+ const captureName = lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
830
1021
  const r = rec.rows.find((x) => x.holdId === input.holdId);
831
1022
  if (r === undefined || (r.status !== "held" && !(r.status === "disposed" && r.disposition?.terminal === "expired")))
832
1023
  return { result: undefined };
@@ -854,7 +1045,7 @@ export function resolveHoldRecord(controlDir, input) {
854
1045
  e.code = "memory.hold_resolve_invalid";
855
1046
  throw e;
856
1047
  }
857
- lockedStrictUpdate(controlDir, HOLDS_FILE, "memory instruction-hold ledger", coerceHolds, (rec) => {
1048
+ lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
858
1049
  const r = rec.rows.find((x) => x.holdId === input.holdId);
859
1050
  if (r === undefined) {
860
1051
  const e = new Error(`resolveHold: unknown holdId ${JSON.stringify(input.holdId)}`);
@@ -878,7 +1069,7 @@ export function resolveHoldRecord(controlDir, input) {
878
1069
  });
879
1070
  }
880
1071
  export function clearHoldResolution(controlDir, input) {
881
- lockedStrictUpdate(controlDir, HOLDS_FILE, "memory instruction-hold ledger", coerceHolds, (rec) => {
1072
+ lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
882
1073
  const r = rec.rows.find((x) => x.holdId === input.holdId);
883
1074
  if (r === undefined || r.resolved === undefined || r.resolvedAt !== input.ifResolvedAt)
884
1075
  return { result: undefined };
@@ -89,14 +89,14 @@ export function mergeInjections(project, personal) {
89
89
  const indexParts = [project.index, personal.index].filter((s) => Boolean(s && s.trim()));
90
90
  const announcements = [...(project.announcements ?? []), ...(personal.announcements ?? [])];
91
91
  const announceParts = [project.announceBlock, personal.announceBlock].filter((s) => Boolean(s && s.trim()));
92
- const blockParts = [instruction || readOnlyNotice, ...indexParts, ...announceParts];
92
+ const blockParts = [instruction || readOnlyNotice, ...indexParts];
93
93
  const indexSeed = project.indexSeed ?? personal.indexSeed;
94
94
  return {
95
95
  instruction,
96
96
  ...(readOnlyNotice !== undefined ? { readOnlyNotice } : {}),
97
97
  ...(indexParts.length > 0 ? { index: indexParts.join("\n\n") } : {}),
98
98
  ...(announcements.length > 0 ? { announcements } : {}),
99
- ...(announceParts.length > 0 ? { announceBlock: announceParts.join("\n\n") } : {}),
99
+ ...(announceParts.length > 0 ? { announceBlock: announceParts.join("\n") } : {}),
100
100
  ...(indexSeed !== undefined ? { indexSeed } : {}),
101
101
  block: blockParts.filter((s) => s && s.trim()).join("\n\n"),
102
102
  };