@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
@@ -1,9 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
- import { closeSync, existsSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
- import { basename, dirname, join } from "node:path";
4
- import { QUARANTINE_DIR, appendChallengeEvents, claimStaging, ensureDirExists, fileGovernanceDocOf, isSameFile, lockedStrictUpdate, mintStagingName, readStrictSidecar, stagingNamePattern, v1MemoryPathKeyResolver, lineageContributionsOfSession, markSessionPolluted, readProjectionDebts, readSessionPollution, ControlPlaneCorruptError } from "./layout.js";
2
+ import { existsSync, linkSync, lstatSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { appendChallengeEvents, claimStaging, fileGovernanceDocOf, isSameFile, lockedStrictUpdate, mintStagingName, readStrictSidecar, stagingNamePattern, v1MemoryPathKeyResolver, lineageContributionsOfSession, markSessionPolluted, readProjectionDebts, readSessionPollution, putControlObjectOnce, ControlPlaneCorruptError } from "./layout.js";
5
5
  import { thrownText } from "../thrown-value.js";
6
- import { fileControlObjectDirOf } from "./control-objects.js";
6
+ import { fileControlObjectDirOf, fileControlObjectFaultCode } from "./control-objects.js";
7
7
  function reqStr(v) {
8
8
  return typeof v === "string" && v.length > 0;
9
9
  }
@@ -190,7 +190,7 @@ export async function expireOverdueSettlements(docs, input) {
190
190
  await settleDelegation(docs, { settleId: s.row.settleId, status: "expired", now: input.now });
191
191
  return overdue.map((s) => s.row.settleId);
192
192
  }
193
- export async function replayExternalSettlementEffects(docs, controlDir, input) {
193
+ export async function replayExternalSettlementEffects(docs, input) {
194
194
  const applied = [];
195
195
  const folded = (await effectiveSettlements(docs)).filter((s) => s.effective === "external" && s.terminalEventId !== undefined);
196
196
  if (folded.length === 0)
@@ -200,7 +200,7 @@ export async function replayExternalSettlementEffects(docs, controlDir, input) {
200
200
  if (rec.effects[s.row.settleId] === s.terminalEventId)
201
201
  continue;
202
202
  const sessionId = s.row.sessionId;
203
- const outcome = markSessionPolluted(controlDir, sessionId, "a delegated child of this session settled external after launch (delegation settlement account)", input.now, "observed");
203
+ const outcome = await markSessionPolluted(docs, sessionId, "a delegated child of this session settled external after launch (delegation settlement account)", input.now, "observed");
204
204
  if (outcome === "unpersisted")
205
205
  continue;
206
206
  try {
@@ -299,7 +299,11 @@ function convertSessionAccounts(read, controlDir) {
299
299
  }
300
300
  export function convertV1SidecarKeys(controlDir) {
301
301
  readProjectionDebts(controlDir);
302
- readHolds(controlDir);
302
+ const holds = readStrictSidecar(controlDir, HOLDS_FILE, HOLDS_WHAT);
303
+ if (holdsOnDiskAreV1(holds))
304
+ lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (again) => ({ next: again, result: undefined }));
305
+ else
306
+ coerceHolds(holds);
303
307
  const accounts = fileGovernanceDocOf("session-accounts");
304
308
  if (coerceSessionAccounts(readStrictSidecar(controlDir, accounts.file, accounts.what)).version !== 2) {
305
309
  lockedStrictUpdate(controlDir, accounts.file, accounts.what, coerceSessionAccounts, (again) => {
@@ -308,31 +312,41 @@ export function convertV1SidecarKeys(controlDir) {
308
312
  });
309
313
  }
310
314
  }
311
- async function readSessionAccountsConverted(docs, controlDir) {
312
- const read = coerceSessionAccounts(await docs.readDoc("session-accounts"));
315
+ export function convertV1SessionAccountsAt(controlDir) {
316
+ const accounts = fileGovernanceDocOf("session-accounts");
317
+ lockedStrictUpdate(controlDir, accounts.file, accounts.what, (raw) => raw, (raw) => {
318
+ let read;
319
+ try {
320
+ read = coerceSessionAccounts(raw);
321
+ }
322
+ catch {
323
+ return { result: undefined };
324
+ }
325
+ const { rec, converted } = convertSessionAccounts(read, controlDir);
326
+ return converted ? { next: rec, result: undefined } : { result: undefined };
327
+ });
328
+ }
329
+ function sessionAccountsV2(read) {
313
330
  if (read.version === 2)
314
331
  return read;
315
- return docs.updateDoc("session-accounts", coerceSessionAccounts, (again) => {
316
- const { rec, converted } = convertSessionAccounts(again, controlDir);
317
- return converted ? { next: rec, result: rec } : { result: rec };
318
- });
332
+ throw new ControlPlaneCorruptError("memory session-account ledger is still in the v1 key form — the next mount of its control plane converts it (the File layout's upgrade step); refusing to read it until then (fail-closed)");
333
+ }
334
+ async function readSessionAccounts(docs) {
335
+ return sessionAccountsV2(coerceSessionAccounts(await docs.readDoc("session-accounts")));
319
336
  }
320
- export async function foreignDanglingSessionAccounts(docs, controlDir, selfSessionId) {
321
- const rec = await readSessionAccountsConverted(docs, controlDir);
337
+ export async function foreignDanglingSessionAccounts(docs, selfSessionId) {
338
+ const rec = await readSessionAccounts(docs);
322
339
  return rec.rows.filter((r) => r.sessionId !== selfSessionId && (r.closedAt === undefined || r.unadjudicated === true));
323
340
  }
324
- export async function openLayerWriters(docs, controlDir, selfLeg) {
325
- const open = (await readSessionAccountsConverted(docs, controlDir)).rows.filter((r) => (selfLeg === undefined || r.leg !== selfLeg) && (r.writeScope !== undefined ? r.terminatedAt === undefined : r.closedAt === undefined));
341
+ export async function openLayerWriters(docs, selfLeg) {
342
+ const open = (await readSessionAccounts(docs)).rows.filter((r) => (selfLeg === undefined || r.leg !== selfLeg) && (r.writeScope !== undefined ? r.terminatedAt === undefined : r.closedAt === undefined));
326
343
  return { scopes: new Set(open.flatMap((r) => (r.writeScope !== undefined ? [r.writeScope] : []))), unscoped: open.filter((r) => r.writeScope === undefined).length };
327
344
  }
328
- export async function sessionAccountLeg(docs, controlDir, sessionId) {
329
- return (await readSessionAccountsConverted(docs, controlDir)).rows.find((r) => r.sessionId === sessionId)?.leg;
345
+ export async function sessionAccountLeg(docs, sessionId) {
346
+ return (await readSessionAccounts(docs)).rows.find((r) => r.sessionId === sessionId)?.leg;
330
347
  }
331
348
  export async function sessionAccountWriteHome(docs, sessionId) {
332
- const read = coerceSessionAccounts(await docs.readDoc("session-accounts"));
333
- if (read.version !== 2)
334
- return undefined;
335
- const row = read.rows.find((r) => r.sessionId === sessionId);
349
+ const row = (await readSessionAccounts(docs)).rows.find((r) => r.sessionId === sessionId);
336
350
  return row?.writeScope === undefined ? undefined : { writeScope: row.writeScope, openedAt: row.openedAt };
337
351
  }
338
352
  export function emptyUnattributedSet() {
@@ -341,9 +355,9 @@ export function emptyUnattributedSet() {
341
355
  function memberKey(scope, rel) {
342
356
  return JSON.stringify([scope, rel]);
343
357
  }
344
- export async function openSessionAccount(docs, controlDir, input) {
358
+ export async function openSessionAccount(docs, input) {
345
359
  await docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
346
- const { rec } = convertSessionAccounts(read, controlDir);
360
+ const rec = sessionAccountsV2(read);
347
361
  const row = rec.rows.find((r) => r.sessionId === input.sessionId);
348
362
  if (row !== undefined && input.writeScope !== undefined)
349
363
  row.writeScope = input.writeScope;
@@ -374,17 +388,17 @@ export async function openSessionAccount(docs, controlDir, input) {
374
388
  return { next: rec, result: undefined };
375
389
  });
376
390
  }
377
- export async function sessionUnattributedSet(docs, controlDir, sessionId) {
378
- const row = (await readSessionAccountsConverted(docs, controlDir)).rows.find((r) => r.sessionId === sessionId);
391
+ export async function sessionUnattributedSet(docs, sessionId) {
392
+ const row = (await readSessionAccounts(docs)).rows.find((r) => r.sessionId === sessionId);
379
393
  if (row === undefined)
380
394
  return emptyUnattributedSet();
381
395
  const all = (row.unattributable?.length ?? 0) > 0;
382
396
  const keys = new Set(row.unattributed.map((m) => memberKey(m.scope, m.rel)));
383
397
  return { has: (scope, rel) => all || keys.has(memberKey(scope, rel.split("\\").join("/"))), empty: !all && keys.size === 0 };
384
398
  }
385
- export async function closeSessionAccount(docs, controlDir, input) {
399
+ export async function closeSessionAccount(docs, input) {
386
400
  return docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
387
- const { rec } = convertSessionAccounts(read, controlDir);
401
+ const rec = sessionAccountsV2(read);
388
402
  const row = rec.rows.find((r) => r.sessionId === input.sessionId);
389
403
  if (row === undefined)
390
404
  return { result: "absent" };
@@ -397,9 +411,9 @@ export async function closeSessionAccount(docs, controlDir, input) {
397
411
  return { next: rec, result: "written" };
398
412
  });
399
413
  }
400
- export async function terminateSessionAccount(docs, controlDir, input) {
414
+ export async function terminateSessionAccount(docs, input) {
401
415
  return docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
402
- const { rec } = convertSessionAccounts(read, controlDir);
416
+ const rec = sessionAccountsV2(read);
403
417
  const row = rec.rows.find((r) => r.sessionId === input.sessionId);
404
418
  if (row === undefined)
405
419
  return { result: "absent" };
@@ -409,14 +423,14 @@ export async function terminateSessionAccount(docs, controlDir, input) {
409
423
  return { next: rec, result: "written" };
410
424
  });
411
425
  }
412
- export async function resolveSessionAccountRecord(docs, controlDir, input) {
426
+ export async function resolveSessionAccountRecord(docs, input) {
413
427
  if (typeof input.requestId !== "string" || input.requestId.length === 0) {
414
428
  const e = new Error("resolveSessionAccount requires a non-empty requestId (the audit attribution of who closed) — refused, never defaulted.");
415
429
  e.code = "memory.session_account_resolve_unattributed";
416
430
  throw e;
417
431
  }
418
432
  await docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
419
- const { rec } = convertSessionAccounts(read, controlDir);
433
+ const rec = sessionAccountsV2(read);
420
434
  const row = rec.rows.find((r) => r.sessionId === input.sessionId);
421
435
  if (row === undefined) {
422
436
  const e = new Error(`resolveSessionAccount: unknown sessionId ${JSON.stringify(input.sessionId)}`);
@@ -484,11 +498,11 @@ function coerceHolds(raw) {
484
498
  function holdsOnDiskAreV1(raw) {
485
499
  return typeof raw === "object" && raw !== null && raw.version === 1;
486
500
  }
487
- export function readHolds(controlDir) {
488
- const raw = readStrictSidecar(controlDir, HOLDS_FILE, HOLDS_WHAT);
501
+ export async function readHolds(docs) {
502
+ const raw = await docs.readDoc("holds");
489
503
  if (!holdsOnDiskAreV1(raw))
490
504
  return coerceHolds(raw).rows;
491
- return lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (again) => ({ next: again, result: again.rows }));
505
+ return docs.updateDoc("holds", coerceHolds, (again) => ({ next: again, result: again.rows }));
492
506
  }
493
507
  function sha256(buf) {
494
508
  return createHash("sha256").update(buf).digest("hex");
@@ -503,41 +517,56 @@ function dropStaging(claimedPath) {
503
517
  export function stagingPathBeside(absPath, stagingName) {
504
518
  return join(dirname(absPath), stagingName);
505
519
  }
506
- function writeCustodyVerified(dest, bytes) {
520
+ async function heldBytesAt(objects, kind, name, digest) {
521
+ let bytes;
507
522
  try {
508
- const fd = openSync(dest, "wx", 0o600);
509
- try {
510
- writeFileSync(fd, bytes);
511
- fsyncSync(fd);
512
- }
513
- finally {
514
- closeSync(fd);
515
- }
516
- return sha256(readFileSync(dest)) === sha256(bytes);
523
+ bytes = await objects.getObject(kind, name);
524
+ }
525
+ catch {
526
+ return "other";
527
+ }
528
+ if (bytes === undefined)
529
+ return "absent";
530
+ return sha256(Buffer.from(bytes)) === digest ? "holds" : "other";
531
+ }
532
+ async function holdCustodyVerified(objects, captureName, bytes) {
533
+ try {
534
+ await putControlObjectOnce(objects, "hold", captureName, bytes);
517
535
  }
518
536
  catch {
519
537
  return false;
520
538
  }
539
+ return (await heldBytesAt(objects, "hold", captureName, sha256(bytes))) === "holds";
521
540
  }
522
- export function retireStagingToCustody(claimedPath, custodyDir, stagingName) {
541
+ export async function retireStagingToObject(objects, claimedPath, kind, name, refusedAt) {
523
542
  const unsettled = (why) => ({ settled: false, at: `${claimedPath} (${why})` });
524
543
  let bytes;
525
544
  try {
526
545
  bytes = readFileSync(claimedPath);
527
- ensureDirExists(custodyDir);
528
546
  }
529
547
  catch {
530
548
  return unsettled("the staged bytes could not be read into the control plane");
531
549
  }
532
- if (!writeCustodyVerified(join(custodyDir, stagingName), bytes))
550
+ try {
551
+ if ((await putControlObjectOnce(objects, kind, name, bytes)) !== "created")
552
+ return unsettled(`a control-plane ${kind} object named ${name} already stands`);
553
+ const back = await objects.getObject(kind, name);
554
+ if (back === undefined || sha256(Buffer.from(back)) !== sha256(bytes))
555
+ return unsettled("the control-plane custody copy could not be read back");
556
+ }
557
+ catch {
533
558
  return unsettled("the control-plane custody copy could not be written");
559
+ }
560
+ const refused = refusedAt();
561
+ if (refused !== undefined)
562
+ return unsettled(`a copy reached the control plane; this one was not removed: ${refused}`);
534
563
  try {
535
564
  unlinkSync(claimedPath);
536
565
  }
537
566
  catch {
538
567
  return unsettled("a copy reached the control plane; this one could not be removed");
539
568
  }
540
- return { settled: true, at: `${basename(custodyDir)}/${stagingName} in the memory control plane` };
569
+ return { settled: true, at: `${kind} object ${name} in the memory control plane` };
541
570
  }
542
571
  export function noReplaceRestore(stagingPath, destPath) {
543
572
  try {
@@ -567,24 +596,23 @@ export function noReplaceRestore(stagingPath, destPath) {
567
596
  }
568
597
  return "restored";
569
598
  }
570
- export function openInstructionHold(controlDir, input) {
599
+ export async function openInstructionHold(store, input) {
571
600
  const holdId = `hold-${input.now()}-${createHash("sha256").update(`${input.sessionId}\n${input.rel}\n${input.content}`).digest("hex").slice(0, 12)}`;
572
601
  const buf = Buffer.from(input.content, "utf8");
573
602
  const digest = sha256(buf);
574
603
  const captureName = `${holdId}.md`;
575
- const holdDir = join(controlDir, HOLD_DIR);
576
604
  let thirdWriterStrandedAt;
577
- const refuse = (rawReason, terminal) => {
605
+ const refuse = async (rawReason, terminal) => {
578
606
  const reason = thirdWriterStrandedAt === undefined ? rawReason : `${rawReason}; a concurrent writer's bytes are preserved at ${thirdWriterStrandedAt}`;
579
607
  try {
580
- disposeHold(controlDir, { holdId, terminal });
608
+ await disposeHold(store, { holdId, terminal });
581
609
  }
582
610
  catch {
583
611
  }
584
612
  return { ok: false, holdId, reason };
585
613
  };
586
614
  try {
587
- lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
615
+ await store.updateDoc("holds", coerceHolds, (rec) => {
588
616
  if (rec.rows.some((r) => r.holdId === holdId))
589
617
  return { result: undefined };
590
618
  rec.rows.push({
@@ -608,15 +636,12 @@ export function openInstructionHold(controlDir, input) {
608
636
  catch (err) {
609
637
  return { ok: false, reason: `hold ledger refused: ${thrownText(err)}` };
610
638
  }
611
- try {
612
- ensureDirExists(holdDir);
613
- }
614
- catch (err) {
615
- return refuse(`hold capture failed: ${thrownText(err)}`, "capture_lost");
616
- }
617
- if (!writeCustodyVerified(join(holdDir, captureName), buf)) {
639
+ if (!(await holdCustodyVerified(store, captureName, buf))) {
618
640
  return refuse("hold capture verification failed (the custody copy could not be written, made durable, or hashed back to the captured digest)", "capture_lost");
619
641
  }
642
+ const refused = input.actRefused(input.absPath, "holding an instruction-form file");
643
+ if (refused !== undefined)
644
+ return refuse(`hold removal refused: ${refused}`, "discarded");
620
645
  const stagingName = mintStagingName(holdId, input.now);
621
646
  const stagingPath = stagingPathBeside(input.absPath, stagingName);
622
647
  try {
@@ -639,14 +664,14 @@ export function openInstructionHold(controlDir, input) {
639
664
  else {
640
665
  const restore = noReplaceRestore(claimedPath, input.absPath);
641
666
  if (restore !== "restored") {
642
- const retired = retireStagingToCustody(claimedPath, holdDir, stagingName);
667
+ const retired = await retireStagingToObject(store, claimedPath, "hold", stagingName, () => input.actRefused(claimedPath, "removing a hold's staged copy"));
643
668
  if (restore === "stranded" || !retired.settled)
644
669
  thirdWriterStrandedAt = retired.at;
645
670
  }
646
671
  }
647
672
  }
648
673
  try {
649
- lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
674
+ await store.updateDoc("holds", coerceHolds, (rec) => {
650
675
  const row = rec.rows.find((r) => r.holdId === holdId);
651
676
  if (row === undefined || row.status !== "capturing")
652
677
  return { result: undefined };
@@ -659,12 +684,14 @@ export function openInstructionHold(controlDir, input) {
659
684
  }
660
685
  return { ok: true, holdId, ...(thirdWriterStrandedAt !== undefined ? { thirdWriterStrandedAt } : {}) };
661
686
  }
662
- export function reconcileHolds(controlDir, input) {
663
- const holdDir = join(controlDir, HOLD_DIR);
687
+ export async function reconcileHolds(store, input) {
664
688
  const discloseStranded = (holdId, scope, rel, at) => {
665
689
  input.onStranded(scope, `instruction hold ${holdId}: a concurrent writer's bytes for ${JSON.stringify(rel)} could not be restored onto the plane — they are preserved at ${at} for host recovery`);
666
690
  };
667
- const finishRemoval = (row, plane) => {
691
+ const finishRemoval = async (row, plane) => {
692
+ const refused = input.actRefused(plane, "removing a held file from the plane");
693
+ if (refused !== undefined)
694
+ throw new Error(refused);
668
695
  const stagingName = mintStagingName(row.holdId, input.now);
669
696
  renameSync(plane, stagingPathBeside(plane, stagingName));
670
697
  const staging = claimStaging(stagingPathBeside(plane, stagingName));
@@ -675,7 +702,7 @@ export function reconcileHolds(controlDir, input) {
675
702
  const restore = noReplaceRestore(staging, plane);
676
703
  if (restore === "restored")
677
704
  return;
678
- const retired = retireStagingToCustody(staging, holdDir, stagingName);
705
+ const retired = await retireStagingToObject(store, staging, "hold", stagingName, () => input.actRefused(staging, "removing a hold's staged copy"));
679
706
  if (restore === "stranded" || !retired.settled)
680
707
  discloseStranded(row.holdId, row.scope, row.rel, retired.at);
681
708
  };
@@ -694,7 +721,7 @@ export function reconcileHolds(controlDir, input) {
694
721
  seatListing.set(seatDir, names);
695
722
  return names;
696
723
  };
697
- const sweepStagingGenerations = (row, plane, custody) => {
724
+ const sweepStagingGenerations = async (row, plane, custody) => {
698
725
  const seatDir = dirname(plane);
699
726
  const pattern = stagingNamePattern(row.holdId);
700
727
  let seat;
@@ -707,6 +734,8 @@ export function reconcileHolds(controlDir, input) {
707
734
  for (const name of listSeat(seatDir)) {
708
735
  if (!pattern.test(name))
709
736
  continue;
737
+ if (input.actRefused(join(seatDir, name), "recovering a hold's staged copy") !== undefined)
738
+ continue;
710
739
  const staged = claimStaging(join(seatDir, name));
711
740
  let bytes;
712
741
  try {
@@ -718,48 +747,44 @@ export function reconcileHolds(controlDir, input) {
718
747
  continue;
719
748
  }
720
749
  if (sha256(bytes) === row.contentDigest) {
721
- if (custody === "holds" || (custody === "absent" && writeCustodyVerified(join(holdDir, row.captureName), bytes))) {
750
+ if (custody === "holds") {
722
751
  dropStaging(staged);
723
752
  continue;
724
753
  }
754
+ if (custody === "absent" && (await holdCustodyVerified(store, row.captureName, bytes))) {
755
+ if (input.actRefused(staged, "recovering a hold's staged copy") === undefined)
756
+ dropStaging(staged);
757
+ continue;
758
+ }
725
759
  }
726
760
  const onSeat = seat !== undefined && isSameFile(staged, seat);
727
- const retired = retireStagingToCustody(staged, holdDir, name);
761
+ const retired = await retireStagingToObject(store, staged, "hold", name, () => input.actRefused(staged, "removing a hold's staged copy"));
728
762
  if (!(onSeat && retired.settled && isSameFile(plane, seat)))
729
763
  discloseStranded(row.holdId, row.scope, row.rel, retired.at);
730
764
  }
731
765
  };
732
- const ledger = readHolds(controlDir);
766
+ const ledger = await readHolds(store);
733
767
  const rows = ledger.filter((r) => r.status === "capturing");
734
768
  for (const row of rows) {
735
- const custody = join(holdDir, row.captureName);
736
- let custodyBytes;
769
+ let custodyState = await heldBytesAt(store, "hold", row.captureName, row.contentDigest);
737
770
  try {
738
- custodyBytes = readFileSync(custody);
739
- }
740
- catch {
741
- custodyBytes = undefined;
742
- }
743
- const custodyState = custodyBytes === undefined ? "absent" : sha256(custodyBytes) === row.contentDigest ? "holds" : "mismatch";
744
- try {
745
- sweepStagingGenerations(row, join(input.homeOf(row.scope), row.rel), custodyState);
771
+ await sweepStagingGenerations(row, join(input.homeOf(row.scope), row.rel), custodyState);
746
772
  }
747
773
  catch {
748
774
  }
775
+ if (custodyState === "absent")
776
+ custodyState = await heldBytesAt(store, "hold", row.captureName, row.contentDigest);
749
777
  let terminalLost = false;
750
- if (existsSync(custody)) {
751
- const bytes = custodyBytes ?? readFileSync(custody);
752
- if (sha256(bytes) !== row.contentDigest) {
753
- terminalLost = true;
754
- }
755
- else {
756
- const plane = join(input.homeOf(row.scope), row.rel);
757
- if (existsSync(plane)) {
758
- try {
759
- finishRemoval(row, plane);
760
- }
761
- catch {
762
- }
778
+ if (custodyState === "other") {
779
+ terminalLost = true;
780
+ }
781
+ else if (custodyState === "holds") {
782
+ const plane = join(input.homeOf(row.scope), row.rel);
783
+ if (existsSync(plane)) {
784
+ try {
785
+ await finishRemoval(row, plane);
786
+ }
787
+ catch {
763
788
  }
764
789
  }
765
790
  }
@@ -769,10 +794,9 @@ export function reconcileHolds(controlDir, input) {
769
794
  const bytes = readFileSync(plane);
770
795
  if (sha256(bytes) === row.contentDigest) {
771
796
  try {
772
- ensureDirExists(holdDir);
773
- if (!writeCustodyVerified(custody, bytes))
774
- throw new Error("the custody copy could not be written or made durable");
775
- finishRemoval(row, plane);
797
+ if (!(await holdCustodyVerified(store, row.captureName, bytes)))
798
+ throw new Error("the custody copy could not be written or read back");
799
+ await finishRemoval(row, plane);
776
800
  }
777
801
  catch {
778
802
  terminalLost = true;
@@ -786,7 +810,7 @@ export function reconcileHolds(controlDir, input) {
786
810
  terminalLost = true;
787
811
  }
788
812
  }
789
- lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
813
+ await store.updateDoc("holds", coerceHolds, (rec) => {
790
814
  const r = rec.rows.find((x) => x.holdId === row.holdId);
791
815
  if (r === undefined || r.status !== "capturing")
792
816
  return { result: undefined };
@@ -802,7 +826,7 @@ export function reconcileHolds(controlDir, input) {
802
826
  }
803
827
  let custodyNames;
804
828
  try {
805
- custodyNames = new Set(readdirSync(holdDir));
829
+ custodyNames = new Set(await store.listObjects("hold"));
806
830
  }
807
831
  catch {
808
832
  custodyNames = new Set();
@@ -812,23 +836,21 @@ export function reconcileHolds(controlDir, input) {
812
836
  if (row.status !== "disposed" || quarantineName === undefined || !custodyNames.has(row.captureName))
813
837
  continue;
814
838
  try {
815
- const moved = moveCustodyToSeat(controlDir, row, quarantineName);
839
+ const moved = await moveCustodyToSeat(store, row, quarantineName);
816
840
  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`);
841
+ 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 the custody seat (hold object ${row.captureName} in the memory control plane) for host recovery, and the move is retried at every harvest`);
818
842
  }
819
843
  }
820
844
  catch (err) {
821
845
  input.onStranded(row.scope, `instruction hold ${row.holdId} (disposed, ${row.disposition.terminal}): ${thrownText(err)}`);
822
846
  }
823
847
  }
824
- adoptOrphanedQuarantineBytes(controlDir, ledger);
848
+ await adoptOrphanedQuarantineBytes(store, ledger);
825
849
  }
826
- function adoptOrphanedQuarantineBytes(controlDir, snapshot) {
827
- const holdDir = join(controlDir, HOLD_DIR);
828
- const qDir = join(controlDir, QUARANTINE_DIR);
850
+ async function adoptOrphanedQuarantineBytes(store, snapshot) {
829
851
  let listing;
830
852
  try {
831
- listing = readdirSync(qDir).filter((n) => n.includes("-hold-") && safeBasename(n)).sort();
853
+ listing = (await store.listObjects("quarantine")).filter((n) => n.includes("-hold-") && safeBasename(n));
832
854
  }
833
855
  catch {
834
856
  return;
@@ -839,35 +861,50 @@ function adoptOrphanedQuarantineBytes(controlDir, snapshot) {
839
861
  seats.add(r.disposition.quarantineName);
840
862
  if (listing.every((n) => seats.has(n)))
841
863
  return;
842
- lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
864
+ const standsAt = async (kind, name) => {
865
+ try {
866
+ return (await store.getObject(kind, name)) !== undefined;
867
+ }
868
+ catch {
869
+ return true;
870
+ }
871
+ };
872
+ const digests = new Map();
873
+ for (const n of listing) {
874
+ if (seats.has(n))
875
+ continue;
876
+ try {
877
+ const bytes = await store.getObject("quarantine", n);
878
+ digests.set(n, bytes === undefined ? undefined : sha256(Buffer.from(bytes)));
879
+ }
880
+ catch {
881
+ digests.set(n, undefined);
882
+ }
883
+ }
884
+ const custodyStands = new Map();
885
+ const seatStands = new Map();
886
+ for (const r of snapshot) {
887
+ custodyStands.set(r.holdId, await standsAt("hold", r.captureName));
888
+ const seat = r.disposition?.quarantineName;
889
+ if (seat !== undefined && !seatStands.has(seat))
890
+ seatStands.set(seat, await standsAt("quarantine", seat));
891
+ }
892
+ const moves = await store.updateDoc("holds", coerceHolds, (rec) => {
843
893
  const claimed = new Set();
844
894
  for (const r of rec.rows)
845
895
  if (r.disposition?.quarantineName !== undefined)
846
896
  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
- };
897
+ const digestOf = (name) => digests.get(name);
862
898
  const wants = (r) => {
863
- if (existsSync(join(holdDir, r.captureName)))
899
+ const custody = custodyStands.get(r.holdId);
900
+ if (custody !== false)
864
901
  return false;
865
902
  if (r.status === "held")
866
903
  return true;
867
904
  if (r.status !== "disposed")
868
905
  return false;
869
906
  const seat = r.disposition?.quarantineName;
870
- return seat === undefined || !existsSync(join(qDir, seat));
907
+ return seat === undefined || seatStands.get(seat) === false;
871
908
  };
872
909
  const endsWithCapture = (name, r) => name.endsWith(`-hold-${r.captureName}`);
873
910
  const reservedForOther = (name) => rec.rows.some((r) => endsWithCapture(name, r));
@@ -890,134 +927,80 @@ function adoptOrphanedQuarantineBytes(controlDir, snapshot) {
890
927
  }
891
928
  }
892
929
  let changed = false;
930
+ const back = [];
893
931
  for (const [r, f] of found) {
894
932
  if (r.status === "disposed") {
895
933
  r.disposition = { ...r.disposition, quarantineName: f };
896
934
  changed = true;
897
935
  continue;
898
936
  }
899
- try {
900
- ensureDirExists(holdDir);
901
- moveNoReplace(join(qDir, f), join(holdDir, r.captureName));
902
- }
903
- catch {
904
- }
937
+ back.push({ file: f, captureName: r.captureName });
905
938
  }
906
- return changed ? { next: rec, result: undefined } : { result: undefined };
939
+ return changed ? { next: rec, result: back } : { result: back };
907
940
  });
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) {
933
- const custody = join(controlDir, HOLD_DIR, row.captureName);
934
- const qDir = join(controlDir, QUARANTINE_DIR);
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;
941
+ for (const m of moves) {
942
942
  try {
943
- if (sha256(readFileSync(custody)) === row.contentDigest)
944
- unlinkSync(custody);
943
+ await store.moveObject({ kind: "quarantine", name: m.file }, { kind: "hold", name: m.captureName });
945
944
  }
946
945
  catch {
947
946
  }
948
- return { at: "seat" };
949
- };
950
- const there = atSeat();
951
- if (there !== undefined)
952
- return there;
953
- if (!existsSync(custody))
954
- return { at: "none" };
955
- try {
956
- ensureDirExists(qDir);
957
- }
958
- catch (err) {
959
- return { at: "custody", code: err.code ?? "mkdir error" };
960
947
  }
961
- if (moveNoReplace(custody, seat) === "moved")
962
- return { at: "seat" };
963
- return atSeat() ?? { at: "custody", code: "move refused" };
964
948
  }
965
- function moveNoReplace(from, to) {
949
+ export function holdQuarantineNameOf(row) {
950
+ return `${row.contentDigest.slice(0, 16)}-hold-${row.captureName}`;
951
+ }
952
+ function foreignSeatRefusal(holdId, seatName) {
953
+ return new ControlPlaneCorruptError(`memory instruction hold ${holdId}: the quarantine seat ${seatName} 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)`);
954
+ }
955
+ async function moveCustodyToSeat(objects, row, seatName) {
956
+ if ((await heldBytesAt(objects, "quarantine", seatName, row.contentDigest)) === "other")
957
+ throw foreignSeatRefusal(row.holdId, seatName);
966
958
  try {
967
- linkSync(from, to);
959
+ await objects.moveObject({ kind: "hold", name: row.captureName }, { kind: "quarantine", name: seatName });
960
+ return { at: "seat" };
968
961
  }
969
962
  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);
985
- }
986
- catch {
963
+ const seat = await heldBytesAt(objects, "quarantine", seatName, row.contentDigest);
964
+ if (seat === "other")
965
+ throw foreignSeatRefusal(row.holdId, seatName);
966
+ const custody = await heldBytesAt(objects, "hold", row.captureName, row.contentDigest);
967
+ if (custody === "absent")
968
+ return seat === "holds" ? { at: "seat" } : { at: "none" };
969
+ if (seat === "holds" && custody === "other")
970
+ return { at: "seat" };
971
+ return { at: "custody", code: fileControlObjectFaultCode(err) ?? "move refused" };
987
972
  }
988
- return "moved";
989
973
  }
990
- export function disposeHold(controlDir, input) {
991
- const row = readHolds(controlDir).find((r) => r.holdId === input.holdId);
974
+ export async function disposeHold(store, input) {
975
+ const row = (await readHolds(store)).find((r) => r.holdId === input.holdId);
992
976
  if (row === undefined || row.status === "disposed" || row.status === "released")
993
977
  return { ok: false };
994
978
  const quarantineName = holdQuarantineNameOf(row);
995
979
  if (!safeBasename(quarantineName)) {
996
980
  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
981
  }
998
- const seatPath = join(controlDir, QUARANTINE_DIR, quarantineName);
999
- const verdict = lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
982
+ const custodyHere = (await heldBytesAt(store, "hold", row.captureName, row.contentDigest)) !== "absent";
983
+ const seatState = await heldBytesAt(store, "quarantine", quarantineName, row.contentDigest);
984
+ const verdict = await store.updateDoc("holds", coerceHolds, (rec) => {
1000
985
  const r = rec.rows.find((x) => x.holdId === input.holdId);
1001
986
  if (r === undefined || r.status === "disposed" || r.status === "released")
1002
987
  return { result: undefined };
1003
- const custodyHere = existsSync(join(controlDir, HOLD_DIR, r.captureName));
1004
- const seatState = quarantineSeatState(seatPath, r.contentDigest);
1005
988
  const named = seatState === "holds" || (custodyHere && seatState === "absent");
1006
989
  r.status = "disposed";
1007
990
  r.disposition = { terminal: input.terminal, ...(named ? { quarantineName } : {}) };
1008
- return { next: rec, result: { named, refused: custodyHere && seatState === "foreign" } };
991
+ return { next: rec, result: { named, refused: custodyHere && seatState === "other" } };
1009
992
  });
1010
993
  if (verdict === undefined)
1011
994
  return { ok: false };
1012
995
  if (verdict.refused)
1013
- throw foreignSeatRefusal(row.holdId, seatPath);
996
+ throw foreignSeatRefusal(row.holdId, quarantineName);
1014
997
  if (!verdict.named)
1015
998
  return { ok: true };
1016
- const moved = moveCustodyToSeat(controlDir, row, quarantineName);
999
+ const moved = await moveCustodyToSeat(store, row, quarantineName);
1017
1000
  return { ok: true, ...(moved.at === "seat" ? { quarantineName } : {}) };
1018
1001
  }
1019
- export function markHoldReleased(controlDir, input) {
1020
- const captureName = lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
1002
+ export async function markHoldReleased(store, input) {
1003
+ const captureName = await store.updateDoc("holds", coerceHolds, (rec) => {
1021
1004
  const r = rec.rows.find((x) => x.holdId === input.holdId);
1022
1005
  if (r === undefined || (r.status !== "held" && !(r.status === "disposed" && r.disposition?.terminal === "expired")))
1023
1006
  return { result: undefined };
@@ -1029,12 +1012,12 @@ export function markHoldReleased(controlDir, input) {
1029
1012
  if (captureName === undefined)
1030
1013
  return;
1031
1014
  try {
1032
- unlinkSync(join(controlDir, HOLD_DIR, captureName));
1015
+ await store.deleteObject("hold", captureName);
1033
1016
  }
1034
1017
  catch {
1035
1018
  }
1036
1019
  }
1037
- export function resolveHoldRecord(controlDir, input) {
1020
+ export async function resolveHoldRecord(docs, input) {
1038
1021
  if (typeof input.requestId !== "string" || input.requestId.length === 0) {
1039
1022
  const e = new Error("resolveHold requires a non-empty requestId (the audit attribution of who resolved) — refused, never defaulted.");
1040
1023
  e.code = "memory.hold_resolve_unattributed";
@@ -1045,7 +1028,7 @@ export function resolveHoldRecord(controlDir, input) {
1045
1028
  e.code = "memory.hold_resolve_invalid";
1046
1029
  throw e;
1047
1030
  }
1048
- lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
1031
+ await docs.updateDoc("holds", coerceHolds, (rec) => {
1049
1032
  const r = rec.rows.find((x) => x.holdId === input.holdId);
1050
1033
  if (r === undefined) {
1051
1034
  const e = new Error(`resolveHold: unknown holdId ${JSON.stringify(input.holdId)}`);
@@ -1068,8 +1051,8 @@ export function resolveHoldRecord(controlDir, input) {
1068
1051
  return { next: rec, result: undefined };
1069
1052
  });
1070
1053
  }
1071
- export function clearHoldResolution(controlDir, input) {
1072
- lockedStrictUpdate(controlDir, HOLDS_FILE, HOLDS_WHAT, coerceHolds, (rec) => {
1054
+ export async function clearHoldResolution(docs, input) {
1055
+ await docs.updateDoc("holds", coerceHolds, (rec) => {
1073
1056
  const r = rec.rows.find((x) => x.holdId === input.holdId);
1074
1057
  if (r === undefined || r.resolved === undefined || r.resolvedAt !== input.ifResolvedAt)
1075
1058
  return { result: undefined };
@@ -1078,21 +1061,21 @@ export function clearHoldResolution(controlDir, input) {
1078
1061
  return { next: rec, result: undefined };
1079
1062
  });
1080
1063
  }
1081
- export function readHoldCustody(controlDir, row) {
1082
- const seats = [join(controlDir, HOLD_DIR, row.captureName), ...(row.disposition?.quarantineName !== undefined ? [join(controlDir, QUARANTINE_DIR, row.disposition.quarantineName)] : [])];
1083
- for (const seat of seats) {
1064
+ export async function readHoldCustody(objects, row) {
1065
+ const seats = [["hold", row.captureName], ...(row.disposition?.quarantineName !== undefined ? [["quarantine", row.disposition.quarantineName]] : [])];
1066
+ for (const [kind, name] of seats) {
1084
1067
  try {
1085
- const bytes = readFileSync(seat);
1086
- if (sha256(bytes) === row.contentDigest)
1087
- return bytes.toString("utf8");
1068
+ const bytes = await objects.getObject(kind, name);
1069
+ if (bytes !== undefined && sha256(Buffer.from(bytes)) === row.contentDigest)
1070
+ return Buffer.from(bytes).toString("utf8");
1088
1071
  }
1089
1072
  catch {
1090
1073
  }
1091
1074
  }
1092
1075
  return undefined;
1093
1076
  }
1094
- export async function sessionBlocksCleanRelease(docs, controlDir, sessionId) {
1095
- if (readSessionPollution(controlDir, sessionId) !== undefined)
1077
+ export async function sessionBlocksCleanRelease(docs, sessionId) {
1078
+ if ((await readSessionPollution(docs, sessionId)) !== undefined)
1096
1079
  return true;
1097
1080
  return (await sessionSettlements(docs, sessionId)).some((s) => s.effective !== "clean" && s.effective !== "void");
1098
1081
  }