@sema-agent/core 7.65.0 → 7.66.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +269 -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-session-drain.d.ts +51 -12
  7. package/dist/agents/peer-session-drain.js +44 -31
  8. package/dist/agents/read-inbox-tool.d.ts +6 -2
  9. package/dist/agents/read-inbox-tool.js +18 -5
  10. package/dist/agents/subagent.d.ts +3 -1
  11. package/dist/agents/subagent.js +79 -75
  12. package/dist/brain/reasoning.d.ts +2 -0
  13. package/dist/brain/reasoning.js +1 -0
  14. package/dist/core/allow-entry.d.ts +9 -0
  15. package/dist/core/allow-entry.js +7 -1
  16. package/dist/core/ask-origin.d.ts +23 -3
  17. package/dist/core/ask-origin.js +11 -1
  18. package/dist/core/engine-notice.d.ts +3 -3
  19. package/dist/core/governance-codes.js +1 -0
  20. package/dist/core/human-input-projection.d.ts +9 -0
  21. package/dist/core/human-input-projection.js +13 -0
  22. package/dist/core/input-author.d.ts +66 -6
  23. package/dist/core/input-author.js +21 -3
  24. package/dist/core/memory-engine/consolidation.d.ts +23 -9
  25. package/dist/core/memory-engine/consolidation.js +30 -5
  26. package/dist/core/memory-engine/control-plane-adoption.d.ts +11 -10
  27. package/dist/core/memory-engine/control-plane-adoption.js +54 -29
  28. package/dist/core/memory-engine/delegation-settlement.d.ts +18 -12
  29. package/dist/core/memory-engine/delegation-settlement.js +36 -26
  30. package/dist/core/memory-engine/engine.d.ts +17 -6
  31. package/dist/core/memory-engine/engine.js +78 -35
  32. package/dist/core/memory-engine/file-backend.d.ts +4 -1
  33. package/dist/core/memory-engine/file-backend.js +5 -1
  34. package/dist/core/memory-engine/index.d.ts +2 -2
  35. package/dist/core/memory-engine/index.js +2 -2
  36. package/dist/core/memory-engine/layout.d.ts +57 -36
  37. package/dist/core/memory-engine/layout.js +109 -134
  38. package/dist/core/memory-engine/memory-backend-contract.js +7 -7
  39. package/dist/core/memory-engine/memory-deployment.d.ts +3 -2
  40. package/dist/core/memory-engine/memory-deployment.js +6 -3
  41. package/dist/core/memory-engine/origin-clearance.d.ts +43 -15
  42. package/dist/core/memory-engine/origin-clearance.js +143 -55
  43. package/dist/core/model-receipt.d.ts +2 -1
  44. package/dist/core/model-receipt.js +5 -0
  45. package/dist/core/mods/dollar.d.ts +12 -0
  46. package/dist/core/mods/kernel/dispatch.d.ts +3 -1
  47. package/dist/core/mods/kernel/dispatch.js +5 -2
  48. package/dist/core/mods/kernel/events.d.ts +3 -1
  49. package/dist/core/mods/kernel/events.js +2 -2
  50. package/dist/core/mods/prompt-submit.d.ts +4 -0
  51. package/dist/core/mods/prompt-submit.js +24 -0
  52. package/dist/core/mods/stations.d.ts +23 -4
  53. package/dist/core/mods/stations.js +14 -7
  54. package/dist/core/retired-host-table-account.d.ts +19 -0
  55. package/dist/core/retired-host-table-account.js +28 -0
  56. package/dist/core/retired-tool-name-account.d.ts +60 -0
  57. package/dist/core/retired-tool-name-account.js +32 -0
  58. package/dist/core/roles.d.ts +3 -1
  59. package/dist/core/roles.js +5 -2
  60. package/dist/core/runner/compact-session.js +2 -1
  61. package/dist/core/runner/contracts.d.ts +1 -1
  62. package/dist/core/runner/gate-exit.js +9 -2
  63. package/dist/core/runner/memory-consolidation-driver.js +2 -2
  64. package/dist/core/runner/prepare-config-doors.js +1 -1
  65. package/dist/core/runner/prepare-delegation-surface.d.ts +1 -1
  66. package/dist/core/runner/prepare-delegation-surface.js +5 -3
  67. package/dist/core/runner/prepare-inherited-gate.js +2 -0
  68. package/dist/core/runner/prepare-memory.js +26 -5
  69. package/dist/core/runner/prepare-park-ask.d.ts +2 -0
  70. package/dist/core/runner/prepare-park-ask.js +3 -1
  71. package/dist/core/runner/prepare-policy-chain.js +2 -1
  72. package/dist/core/runner/prepare-project-context.js +2 -2
  73. package/dist/core/runner/prepare-question-face.d.ts +2 -2
  74. package/dist/core/runner/prepare-task.d.ts +5 -1
  75. package/dist/core/runner/prepare-task.js +5 -4
  76. package/dist/core/runner/prepare-wiring-manifest.js +5 -4
  77. package/dist/core/runner/prompt-suggestions.js +1 -1
  78. package/dist/core/runner/run-identity-wiring.js +2 -2
  79. package/dist/core/runner/run-leg.js +3 -3
  80. package/dist/core/runner/run-notification-lane.d.ts +3 -0
  81. package/dist/core/runner/run-notification-lane.js +2 -2
  82. package/dist/core/runner/runtask.js +6 -3
  83. package/dist/core/runner/steer-admission.d.ts +11 -2
  84. package/dist/core/runner/stream-steer-verb.d.ts +5 -2
  85. package/dist/core/runner/stream-steer-verb.js +67 -14
  86. package/dist/core/runner/sub-agent-deny-lists.d.ts +8 -27
  87. package/dist/core/runner/sub-agent-deny-lists.js +22 -33
  88. package/dist/core/runner-deps.d.ts +4 -4
  89. package/dist/core/shell-run-candidates.js +3 -3
  90. package/dist/core/side-query.js +1 -1
  91. package/dist/core/skill-grant.d.ts +7 -0
  92. package/dist/core/skill-grant.js +14 -5
  93. package/dist/core/task-event.d.ts +14 -0
  94. package/dist/core/tool-policy.js +2 -3
  95. package/dist/core/tool-spec.d.ts +13 -3
  96. package/dist/core/user-attachment.d.ts +5 -1
  97. package/dist/core/user-attachment.js +11 -5
  98. package/dist/engine/harness/agent-harness.d.ts +19 -11
  99. package/dist/engine/harness/agent-harness.js +7 -4
  100. package/dist/engine/llm/types.d.ts +22 -10
  101. package/dist/index.d.ts +4 -2
  102. package/dist/index.js +3 -1
  103. package/dist/shell/lex.d.ts +50 -15
  104. package/dist/shell/lex.js +43 -9
  105. package/dist/tools/fs/fs-bash.js +3 -3
  106. package/dist/tools/fs/removal-targets.d.ts +8 -2
  107. package/dist/tools/fs/removal-targets.js +31 -4
  108. package/dist/tools/fs/shell-read-argv.js +7 -1
  109. package/dist/tools/fs/shell-read-bindings.d.ts +21 -5
  110. package/dist/tools/fs/shell-read-bindings.js +130 -44
  111. package/dist/tools/fs/shell-read-plan.js +95 -29
  112. package/dist/tools/fs/shell-read-sourced.d.ts +25 -0
  113. package/dist/tools/fs/shell-read-sourced.js +119 -0
  114. package/dist/tools/fs/shell-read-word.d.ts +2 -2
  115. package/dist/tools/fs/shell-read-word.js +4 -5
  116. package/dist/tools/fs/shell-read-workdir.d.ts +19 -3
  117. package/dist/tools/fs/shell-read-workdir.js +60 -15
  118. package/dist/tools/fs/shell-reentry-text.d.ts +10 -2
  119. package/dist/tools/fs/shell-reentry-text.js +11 -4
  120. package/package.json +2 -2
  121. package/test/export-surface.snapshot.json +13 -7
  122. package/wire-changes/core-stores-sql@7.66.0.json +30 -0
  123. package/wire-changes/core-stores-sql@7.66.1.json +30 -0
  124. package/wire-changes/core@7.66.0.json +1218 -0
  125. package/wire-changes/core@7.66.1.json +46 -0
  126. package/wire-changes/mods-kernel@7.66.0.json +65 -0
  127. package/wire-changes/mods-kernel@7.66.1.json +30 -0
  128. package/wire-changes/primitives@7.66.0.json +30 -0
  129. package/wire-changes/primitives@7.66.1.json +30 -0
@@ -312,31 +312,41 @@ export function convertV1SidecarKeys(controlDir) {
312
312
  });
313
313
  }
314
314
  }
315
- async function readSessionAccountsConverted(docs, controlDir) {
316
- 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) {
317
330
  if (read.version === 2)
318
331
  return read;
319
- return docs.updateDoc("session-accounts", coerceSessionAccounts, (again) => {
320
- const { rec, converted } = convertSessionAccounts(again, controlDir);
321
- return converted ? { next: rec, result: rec } : { result: rec };
322
- });
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")));
323
336
  }
324
- export async function foreignDanglingSessionAccounts(docs, controlDir, selfSessionId) {
325
- const rec = await readSessionAccountsConverted(docs, controlDir);
337
+ export async function foreignDanglingSessionAccounts(docs, selfSessionId) {
338
+ const rec = await readSessionAccounts(docs);
326
339
  return rec.rows.filter((r) => r.sessionId !== selfSessionId && (r.closedAt === undefined || r.unadjudicated === true));
327
340
  }
328
- export async function openLayerWriters(docs, controlDir, selfLeg) {
329
- 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));
330
343
  return { scopes: new Set(open.flatMap((r) => (r.writeScope !== undefined ? [r.writeScope] : []))), unscoped: open.filter((r) => r.writeScope === undefined).length };
331
344
  }
332
- export async function sessionAccountLeg(docs, controlDir, sessionId) {
333
- 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;
334
347
  }
335
348
  export async function sessionAccountWriteHome(docs, sessionId) {
336
- const read = coerceSessionAccounts(await docs.readDoc("session-accounts"));
337
- if (read.version !== 2)
338
- return undefined;
339
- const row = read.rows.find((r) => r.sessionId === sessionId);
349
+ const row = (await readSessionAccounts(docs)).rows.find((r) => r.sessionId === sessionId);
340
350
  return row?.writeScope === undefined ? undefined : { writeScope: row.writeScope, openedAt: row.openedAt };
341
351
  }
342
352
  export function emptyUnattributedSet() {
@@ -345,9 +355,9 @@ export function emptyUnattributedSet() {
345
355
  function memberKey(scope, rel) {
346
356
  return JSON.stringify([scope, rel]);
347
357
  }
348
- export async function openSessionAccount(docs, controlDir, input) {
358
+ export async function openSessionAccount(docs, input) {
349
359
  await docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
350
- const { rec } = convertSessionAccounts(read, controlDir);
360
+ const rec = sessionAccountsV2(read);
351
361
  const row = rec.rows.find((r) => r.sessionId === input.sessionId);
352
362
  if (row !== undefined && input.writeScope !== undefined)
353
363
  row.writeScope = input.writeScope;
@@ -378,17 +388,17 @@ export async function openSessionAccount(docs, controlDir, input) {
378
388
  return { next: rec, result: undefined };
379
389
  });
380
390
  }
381
- export async function sessionUnattributedSet(docs, controlDir, sessionId) {
382
- 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);
383
393
  if (row === undefined)
384
394
  return emptyUnattributedSet();
385
395
  const all = (row.unattributable?.length ?? 0) > 0;
386
396
  const keys = new Set(row.unattributed.map((m) => memberKey(m.scope, m.rel)));
387
397
  return { has: (scope, rel) => all || keys.has(memberKey(scope, rel.split("\\").join("/"))), empty: !all && keys.size === 0 };
388
398
  }
389
- export async function closeSessionAccount(docs, controlDir, input) {
399
+ export async function closeSessionAccount(docs, input) {
390
400
  return docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
391
- const { rec } = convertSessionAccounts(read, controlDir);
401
+ const rec = sessionAccountsV2(read);
392
402
  const row = rec.rows.find((r) => r.sessionId === input.sessionId);
393
403
  if (row === undefined)
394
404
  return { result: "absent" };
@@ -401,9 +411,9 @@ export async function closeSessionAccount(docs, controlDir, input) {
401
411
  return { next: rec, result: "written" };
402
412
  });
403
413
  }
404
- export async function terminateSessionAccount(docs, controlDir, input) {
414
+ export async function terminateSessionAccount(docs, input) {
405
415
  return docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
406
- const { rec } = convertSessionAccounts(read, controlDir);
416
+ const rec = sessionAccountsV2(read);
407
417
  const row = rec.rows.find((r) => r.sessionId === input.sessionId);
408
418
  if (row === undefined)
409
419
  return { result: "absent" };
@@ -413,14 +423,14 @@ export async function terminateSessionAccount(docs, controlDir, input) {
413
423
  return { next: rec, result: "written" };
414
424
  });
415
425
  }
416
- export async function resolveSessionAccountRecord(docs, controlDir, input) {
426
+ export async function resolveSessionAccountRecord(docs, input) {
417
427
  if (typeof input.requestId !== "string" || input.requestId.length === 0) {
418
428
  const e = new Error("resolveSessionAccount requires a non-empty requestId (the audit attribution of who closed) — refused, never defaulted.");
419
429
  e.code = "memory.session_account_resolve_unattributed";
420
430
  throw e;
421
431
  }
422
432
  await docs.updateDoc("session-accounts", coerceSessionAccounts, (read) => {
423
- const { rec } = convertSessionAccounts(read, controlDir);
433
+ const rec = sessionAccountsV2(read);
424
434
  const row = rec.rows.find((r) => r.sessionId === input.sessionId);
425
435
  if (row === undefined) {
426
436
  const e = new Error(`resolveSessionAccount: unknown sessionId ${JSON.stringify(input.sessionId)}`);
@@ -280,9 +280,10 @@ export interface MemoryEngineOptions {
280
280
  */
281
281
  provenance?: "off" | "carry";
282
282
  /**
283
- * design/383 §2.1b — the capture opt-out record's control-plane carrier. Absent = the file trio
284
- * over this engine's control dir (single-process/single-host deployments: byte-identical to
285
- * having no seat). A deployment whose control plane is not durable across resume replicas
283
+ * design/383 §2.1b — the capture opt-out record's control-plane carrier. Absent = the `capture` objects
284
+ * of the governance store this engine keeps its documents in (#3484 — the File store over this
285
+ * engine's control dir: byte-identical names and bytes; the store the backend carries: one carrier
286
+ * for every replica). A deployment whose control plane is not durable across resume replicas
286
287
  * (server cloud form) supplies its own store here; see {@link import("./layout.js").SessionCaptureRecordStore}
287
288
  * for the fail-closed contract each leg must keep.
288
289
  */
@@ -873,6 +874,9 @@ export declare class MemoryEngine {
873
874
  private readonly memoryDir;
874
875
  private readonly controlDir;
875
876
  private readonly governanceStore;
877
+ /** `true` ⇔ the governance store is the File store at {@link controlDir} itself: that plane's records are this store's
878
+ * own, and its v1 documents are converted in place by the layout adoption (#3484). */
879
+ private readonly ownsControlPlaneRecords;
876
880
  private readonly now;
877
881
  private readonly perScopeBudgetBytes;
878
882
  private readonly perFileBytes;
@@ -1087,7 +1091,7 @@ export declare class MemoryEngine {
1087
1091
  /** The session's pollution record (in-process mark first, then the durable marker kept by the
1088
1092
  * governance store) — undefined = clean. Reads are side-effect-free. */
1089
1093
  sessionPollution(sessionId: string): Promise<SessionPollutionRecord | undefined>;
1090
- /** design/383 §2.1b — the record carrier (defaults to the file trio over this control dir). */
1094
+ /** design/383 §2.1b — the record carrier (defaults to the governance store's `capture` objects). */
1091
1095
  private readonly captureRecords;
1092
1096
  /** In-process half of the one-way record: a session opted out in THIS process reads opted-out here
1093
1097
  * even before/independent of the durable read (the harvest legs and read closures consult this
@@ -1286,6 +1290,11 @@ export declare class MemoryEngine {
1286
1290
  */
1287
1291
  eraseMemoryEntries(input: EraseMemoryEntriesInput): Promise<MemoryErasureAttestation>;
1288
1292
  private eraseMemoryEntriesCore;
1293
+ /** #3463 — the `clearanceCustody` class of an evidence face's attestation. A face that counted it (the File face, over
1294
+ * the same governance store) stands; one that did not — the class absent, or `unverified` (a face that never kept the
1295
+ * clearances) — is answered here, over the governance store the engine keeps the clearances in, for every resolved id
1296
+ * a conflict did not keep standing; an account that cannot be read or updated answers the class unverified. */
1297
+ private answerClearanceCustody;
1289
1298
  /**
1290
1299
  * design/178 v2-b (rescan hardening) — the erase-time DERIVED-INDEX sweep, both lanes. MEMORY.md
1291
1300
  * is the engine's model-visible distillation of entry frontmatter (name + description — routinely
@@ -1824,8 +1833,10 @@ export declare class MemoryEngine {
1824
1833
  provenance: EntryProvenanceAccount;
1825
1834
  }>>;
1826
1835
  /** §13-4② read half — the clearance audit trail (pending rows are crash-recovery seats: their
1827
- * custody carries the cleared bytes; a later {@link clearEntryOrigin} call resumes them). */
1828
- listOriginClearances(): OriginClearanceRow[];
1836
+ * custody carries the cleared bytes; a later {@link clearEntryOrigin} call resumes them). Read through the
1837
+ * governance store the engine keeps its documents in (#3484: a Promise — the store is awaited). A row whose custody
1838
+ * an erasure took answers `entryText: ""` and `custodyErased: true` (#3463). */
1839
+ listOriginClearances(): Promise<OriginClearanceRow[]>;
1829
1840
  /**
1830
1841
  * §13-4② — the audited UN-MARK valve. There is deliberately NO in-place strip spelling anywhere
1831
1842
  * (the backend immutability law stands untouched); the clear rides the law's own single legal
@@ -10,18 +10,19 @@ import { formatMemoryAge } from "./memory-age.js";
10
10
  import { committedDistilledOf, committedOriginOf, computeEntryRev, consolidationExposedFrontmatter, distilledEquals, hasDistilledFormExtra, hasOriginFormExtra, isValidEntryId, originEquals, parseEntryFile, serializeEntryFile, stripModelWrittenDistilled, stripModelWrittenOrigin, UNCLOSED_MEMORY_FILE_REASON } from "./frontmatter.js";
11
11
  import { MEMORY_PROVENANCE_RECALL_SENTENCE, memoryExposureIndexRow, parseMemoryExposureIndexRow } from "./provenance-wording.js";
12
12
  import { isInstructionEntry } from "./header-hints.js";
13
- import { ConsolidationRefusedError, CONSOLIDATION_WRITE_REFUSED_CODE, CONSOLIDATION_FORCE_THROTTLE_FLOOR_MS, CONSOLIDATION_SEAT_FREEZE_GRACE_MS, consolidationTypeEligible, deriveProductSlug, deriveSupersededSet, fileGovernanceStore, fileGovernanceStoreDir, standingControlObjectsOf, isValidConsolidationPlanId, productAddPatch, recordActiveSetBaseline, recordConsolidationSession, sessionsSinceExcludingCurrent, scanRefusalCeiling, screenConsolidationOptions, memoryGovernanceDurability, supersessionFuseCeiling, deletionFuseCeiling, MEMORY_CHALLENGED_ENTRY_GUIDANCE, } from "./consolidation.js";
13
+ import { ConsolidationRefusedError, CONSOLIDATION_WRITE_REFUSED_CODE, CONSOLIDATION_FORCE_THROTTLE_FLOOR_MS, CONSOLIDATION_SEAT_FREEZE_GRACE_MS, consolidationTypeEligible, deriveProductSlug, deriveSupersededSet, fileGovernanceStore, governanceCaptureRecordStore, fileGovernanceStoreDir, governanceStoreIsFileOver, standingControlObjectsOf, isValidConsolidationPlanId, productAddPatch, recordActiveSetBaseline, recordConsolidationSession, sessionsSinceExcludingCurrent, scanRefusalCeiling, screenConsolidationOptions, memoryGovernanceDurability, supersessionFuseCeiling, deletionFuseCeiling, MEMORY_CHALLENGED_ENTRY_GUIDANCE, } from "./consolidation.js";
14
14
  import { deriveShadowedSet } from "./shadowing.js";
15
15
  import { classifySessionSettlements, clearHoldResolution, closeSessionAccount, disposeHold, effectiveSettlements, expireOverdueSettlements, foreignDanglingSessionAccounts, openLayerWriters, terminateSessionAccount, sessionAccountLeg, markHoldReleased, openInstructionHold, openSessionAccount, readHoldCustody, readHolds, reconcileHolds, replayExternalSettlementEffects, resolveHoldRecord, resolveSessionAccountRecord, resolveSettlementRecord, sessionSettlements, sessionUnattributedSet, emptyUnattributedSet, convertV1SidecarKeys, } from "./delegation-settlement.js";
16
16
  import { noReplaceRestore, retireStagingToObject, stagingPathBeside } from "./delegation-settlement.js";
17
17
  import { probeControlPlaneLinks } from "./control-objects.js";
18
+ import { replicaControlPlaneStrays } from "./control-plane-adoption.js";
18
19
  import { sessionWriteHomeOf } from "./session-write-home.js";
19
20
  import { landedUndecided, layerDigest, layerObservationLookup, readOnlyLayerCandidates, readOnlyLayerCensus, recordLayerObservations, settleUndecidedLayerObservations, observationBacked, sameObservation, undecidedLayerObservations } from "./layer-observations.js";
20
- import { markOriginClearanceTombstoned, openOriginClearance, readOriginClearances, settleOriginClearance } from "./origin-clearance.js";
21
+ import { clearanceCustodyErased, eraseOriginClearanceCustody, markOriginClearanceTombstoned, openOriginClearance, readOriginClearances, settleOriginClearance } from "./origin-clearance.js";
21
22
  import { carriesEntry } from "./entry-scan.js";
22
23
  import { DEFAULT_MAX_ENTRY_DEPTH, MEMORY_INDEX_FILENAME, captureErasureInput, erasureRequestInvalid, erasureScopeRefusal, erasureSelectHash, erasureStatusOf, sweepUnderErasureRecord, scanEntryFiles, } from "./file-backend.js";
23
24
  import { assembleMemoryExportBundle, canonicalExpectedScopes, computeMemoryBundleHash, expectedScopesInvalid, firstOutsideExpectedScopes, memoryBundleInvalid, } from "./export-bundle.js";
24
- import { SCAN_FUSE_THRESHOLD, captureIntoQuarantine, clearContainedPath, eraseQuarantineCopies, keepCopiesBeforeOverwrite, putControlObjectOnce, restoreContainedBaseline, mintStagingName, indexLineIsStale, readIndexRevs, writeIndexRevs, bumpScanFuse, scanFuseKey, canonicalize, anchorStoreRoot, landingPathOf, landsOutsideStore, storeActRefusal, storeRootMovedRefusal, adoptRootScopeLayout, clearScanFuse, effectiveControlRootOf, sayAnnounceFailure, drainMemoryAnnouncements, enqueueMemoryAnnouncement, ensureDirExists, markSessionPolluted, readSessionPollution, fileSessionCaptureRecordStore, recordRetrievedAccount, writeFileNoFollow, writeFileNoReplace, withPermissionRemedy, permissionRemedyOf, readRetrievedAccount, registerScope, registeredScopes, scopeDirFor, appendChallengeEvents, appendLineageAudit, rebuildStrictControlPlaneLedger, isStrictControlPlaneLedgerCorrupt, CHALLENGE_LEDGER_MAX_EVENTS, adjudicateLineagePending, challengedEntryIds, clearLineageForEntries, discardLineagePending, lineageAccountOfEntry, lineageContributionsOfSession, lineageLatchedIds, promoteLineagePending, readChallengeEvents, readChallengedHistory, readLineageRecord, recordChallengedHistory, recordLineageCredential, reconcileLineage, readProjectionDebts, resolveChallengeEvent, settleProjectionDebts, stageLineagePending, stageProjectionDebts, } from "./layout.js";
25
+ import { SCAN_FUSE_THRESHOLD, captureIntoQuarantine, clearContainedPath, eraseQuarantineCopies, keepCopiesBeforeOverwrite, putControlObjectOnce, restoreContainedBaseline, mintStagingName, indexLineIsStale, readIndexRevs, writeIndexRevs, bumpScanFuse, scanFuseKey, canonicalize, anchorStoreRoot, landingPathOf, landsOutsideStore, storeActRefusal, storeRootMovedRefusal, adoptRootScopeLayout, clearScanFuse, effectiveControlRootOf, sayAnnounceFailure, drainMemoryAnnouncements, enqueueMemoryAnnouncement, ensureDirExists, markSessionPolluted, readSessionPollution, recordRetrievedAccount, writeFileNoFollow, writeFileNoReplace, withPermissionRemedy, permissionRemedyOf, readRetrievedAccount, registerScope, registeredScopes, scopeDirFor, appendChallengeEvents, appendLineageAudit, rebuildStrictControlPlaneLedger, isStrictControlPlaneLedgerCorrupt, CHALLENGE_LEDGER_MAX_EVENTS, adjudicateLineagePending, challengedEntryIds, clearLineageForEntries, discardLineagePending, lineageAccountOfEntry, lineageContributionsOfSession, lineageLatchedIds, promoteLineagePending, readChallengeEvents, readChallengedHistory, readLineageRecord, recordChallengedHistory, recordLineageCredential, reconcileLineage, readProjectionDebts, resolveChallengeEvent, settleProjectionDebts, stageLineagePending, stageProjectionDebts, controlPlaneStraysRefusal, } from "./layout.js";
25
26
  import { createSessionIncarnationSeat, recalledForAnyIdentity, recalledForIdentity, rememberForIdentity } from "./session-incarnation.js";
26
27
  import { scanMemoryFileName, scanMemoryWrite, scanRemediation } from "./scan.js";
27
28
  import { writableRootOf } from "./types.js";
@@ -373,6 +374,7 @@ export class MemoryEngine {
373
374
  memoryDir;
374
375
  controlDir;
375
376
  governanceStore;
377
+ ownsControlPlaneRecords;
376
378
  now;
377
379
  perScopeBudgetBytes;
378
380
  perFileBytes;
@@ -405,6 +407,12 @@ export class MemoryEngine {
405
407
  this.zeroCopy = typeof pinned === "string" && pinned !== "";
406
408
  this.controlDir = effectiveControlRootOf(o.memoryDir, { pinnedBy: o.backend, controlDir: o.controlDir, onIncident: o.onIncident });
407
409
  this.governanceStore = o.backend.governance ?? fileGovernanceStore(this.controlDir);
410
+ this.ownsControlPlaneRecords = governanceStoreIsFileOver(this.governanceStore, this.controlDir);
411
+ if (!this.ownsControlPlaneRecords) {
412
+ const strays = replicaControlPlaneStrays(this.controlDir);
413
+ if (strays.docs.length > 0 || Object.keys(strays.objects).length > 0)
414
+ throw controlPlaneStraysRefusal(this.controlDir, strays);
415
+ }
408
416
  this.now = o.now ?? Date.now;
409
417
  this.perScopeBudgetBytes = o.perScopeBudgetBytes ?? Number.MAX_SAFE_INTEGER;
410
418
  this.perFileBytes = o.perFileBytes ?? MAX_MEMORY_BYTES;
@@ -423,7 +431,7 @@ export class MemoryEngine {
423
431
  if (o.consolidation !== undefined) {
424
432
  this.consolidation = screenConsolidationOptions(o.consolidation, this.provenance, memoryGovernanceDurability(o.backend));
425
433
  }
426
- this.captureRecords = o.captureRecordStore ?? fileSessionCaptureRecordStore(this.controlDir);
434
+ this.captureRecords = o.captureRecordStore ?? governanceCaptureRecordStore(this.governanceStore);
427
435
  this.incarnation = createSessionIncarnationSeat({ resolve: o.sessionIncarnation, onIncident: o.onIncident });
428
436
  }
429
437
  incarnation;
@@ -436,7 +444,7 @@ export class MemoryEngine {
436
444
  }
437
445
  async endLeg(sessionId, leg) {
438
446
  try {
439
- return await terminateSessionAccount(this.governanceStore, this.controlDir, { sessionId, now: this.now, leg });
447
+ return await terminateSessionAccount(this.governanceStore, { sessionId, now: this.now, leg });
440
448
  }
441
449
  catch (err) {
442
450
  this.discloseSessionAccountIncident("the end of this session's leg could not be recorded — it keeps reading as a live writer of its layer (read-only restores there are withheld)", err);
@@ -502,7 +510,7 @@ export class MemoryEngine {
502
510
  if (committed === undefined)
503
511
  continue;
504
512
  try {
505
- writers ??= await openLayerWriters(this.governanceStore, this.controlDir, selfLeg);
513
+ writers ??= await openLayerWriters(this.governanceStore, selfLeg);
506
514
  }
507
515
  catch {
508
516
  writers = { scopes: new Set(), unscoped: 1 };
@@ -1172,7 +1180,7 @@ export class MemoryEngine {
1172
1180
  e.code = "config.memory_erasure_scope";
1173
1181
  throw e;
1174
1182
  }
1175
- const att = await face.call(this.backend, captured);
1183
+ const att = await this.answerClearanceCustody(await face.call(this.backend, captured));
1176
1184
  return this.sweepErasedIndexLines(att, requestId, (recorded) => ({ paths: recorded, homes: att.erased.flatMap((row) => (row.binding.state === "bound" ? [scopeDirFor(this.memoryDir, this.controlDir, row.binding.scope)] : [])) }));
1177
1185
  }
1178
1186
  if (captured.allowUnevidenced !== true) {
@@ -1223,6 +1231,8 @@ export class MemoryEngine {
1223
1231
  const conflicts = report.conflicts.map((c) => ({ id: c.id, reason: c.reason }));
1224
1232
  const unverified = { unverified: true };
1225
1233
  const quarantine = await eraseQuarantineCopies(standingControlObjectsOf(this.governanceStore), new Set(resolvedIds)).catch(() => undefined);
1234
+ const conflicted = new Set(conflicts.map((c) => c.id));
1235
+ const custody = await eraseOriginClearanceCustody(this.governanceStore, new Set(resolvedIds.filter((id) => !conflicted.has(id))), this.now()).catch(() => undefined);
1226
1236
  const att = {
1227
1237
  v: 2,
1228
1238
  requestId,
@@ -1237,7 +1247,7 @@ export class MemoryEngine {
1237
1247
  notFound,
1238
1248
  conflicts,
1239
1249
  residuals: {
1240
- carriers: { projection: unverified, shadow: unverified, indexLine: { removed: 0, remaining: 0 }, quarantineCopy: quarantine !== undefined ? { removed: quarantine.removed, remaining: quarantine.remaining, unreadable: quarantine.unreadable } : unverified, planArchive: unverified, planWorkbook: unverified, evidenceBinding: unverified, backendDerived: unverified },
1250
+ carriers: { projection: unverified, shadow: unverified, indexLine: { removed: 0, remaining: 0 }, quarantineCopy: quarantine !== undefined ? { removed: quarantine.removed, remaining: quarantine.remaining, unreadable: quarantine.unreadable } : unverified, clearanceCustody: custody !== undefined ? { removed: custody.removed, remaining: custody.remaining } : unverified, planArchive: unverified, planWorkbook: unverified, evidenceBinding: unverified, backendDerived: unverified },
1241
1251
  quarantineUnattributed: quarantine !== undefined ? { count: quarantine.unattributed } : unverified,
1242
1252
  derivedEntries: unverified,
1243
1253
  replay: "unsupported",
@@ -1254,6 +1264,28 @@ export class MemoryEngine {
1254
1264
  return { paths: deleted.map((e, i) => join(homes[i] ?? "", `${e.slug}.md`)), homes };
1255
1265
  });
1256
1266
  }
1267
+ async answerClearanceCustody(att) {
1268
+ let resolved;
1269
+ try {
1270
+ const counted = att.residuals.carriers.clearanceCustody;
1271
+ if (typeof counted === "object" && counted !== null && typeof counted.remaining === "number")
1272
+ return att;
1273
+ const conflicted = new Set(att.conflicts.map((c) => String(c.id)));
1274
+ resolved = att.resolvedIds.map(String).filter((id) => !conflicted.has(id));
1275
+ }
1276
+ catch {
1277
+ return att;
1278
+ }
1279
+ const custody = await eraseOriginClearanceCustody(this.governanceStore, new Set(resolved), this.now()).catch(() => undefined);
1280
+ try {
1281
+ const out = { ...att, residuals: { ...att.residuals, carriers: { ...att.residuals.carriers, clearanceCustody: custody !== undefined ? { removed: custody.removed, remaining: custody.remaining } : { unverified: true } } } };
1282
+ out.status = erasureStatusOf(out);
1283
+ return out;
1284
+ }
1285
+ catch {
1286
+ return att;
1287
+ }
1288
+ }
1257
1289
  async sweepErasedIndexLines(att, requestId, owedOf) {
1258
1290
  const uncleared = [];
1259
1291
  const indexScope = new Map();
@@ -1650,7 +1682,7 @@ export class MemoryEngine {
1650
1682
  this.assertRootAnchored();
1651
1683
  }
1652
1684
  if (adopt === undefined || !this.zeroCopy)
1653
- adoptRootScopeLayout(this.memoryDir, this.controlDir, { ownerCandidate: writeScope, onIncident: this.onIncident, convertSidecars: convertV1SidecarKeys });
1685
+ adoptRootScopeLayout(this.memoryDir, this.controlDir, { ownerCandidate: writeScope, onIncident: this.onIncident, ...(this.ownsControlPlaneRecords ? { convertSidecars: convertV1SidecarKeys } : {}) });
1654
1686
  }
1655
1687
  async materialize(scopes, writeScope, opts) {
1656
1688
  const legSeat = {};
@@ -1693,7 +1725,7 @@ export class MemoryEngine {
1693
1725
  if (this.provenance === "carry" && opts?.sessionId !== undefined && writeScope !== null && !restricted) {
1694
1726
  let accountFailed = false;
1695
1727
  try {
1696
- const foreign = await foreignDanglingSessionAccounts(this.governanceStore, this.controlDir, opts.sessionId);
1728
+ const foreign = await foreignDanglingSessionAccounts(this.governanceStore, opts.sessionId);
1697
1729
  const unattributed = [];
1698
1730
  if (foreign.length > 0) {
1699
1731
  const wroot = canonicalize(scopeDirFor(this.memoryDir, this.controlDir, writeScope));
@@ -1802,13 +1834,13 @@ export class MemoryEngine {
1802
1834
  }
1803
1835
  }
1804
1836
  accountLeg = legSeat.leg = uuidv7();
1805
- await openSessionAccount(this.governanceStore, this.controlDir, { sessionId: opts.sessionId, now: this.now, unattributed, writeScope, leg: accountLeg });
1837
+ await openSessionAccount(this.governanceStore, { sessionId: opts.sessionId, now: this.now, unattributed, writeScope, leg: accountLeg });
1806
1838
  }
1807
1839
  catch (err) {
1808
1840
  accountFailed = true;
1809
1841
  if (accountLeg !== undefined) {
1810
1842
  try {
1811
- if (await sessionAccountLeg(this.governanceStore, this.controlDir, opts.sessionId) !== accountLeg)
1843
+ if (await sessionAccountLeg(this.governanceStore, opts.sessionId) !== accountLeg)
1812
1844
  accountLeg = legSeat.leg = undefined;
1813
1845
  }
1814
1846
  catch {
@@ -2258,7 +2290,7 @@ export class MemoryEngine {
2258
2290
  sessionPending = true;
2259
2291
  pendingSettleIds = rows.filter((r) => r.effective === "pending").map((r) => r.row.settleId);
2260
2292
  }
2261
- unattributedSet = await sessionUnattributedSet(this.governanceStore, this.controlDir, lineageSessionId);
2293
+ unattributedSet = await sessionUnattributedSet(this.governanceStore, lineageSessionId);
2262
2294
  }
2263
2295
  }
2264
2296
  const rec = await reconcileLineage(this.governanceStore);
@@ -3265,7 +3297,7 @@ export class MemoryEngine {
3265
3297
  const rest = deferredSeats.length - shown.length;
3266
3298
  const seatList = `${shown.join(", ")}${rest > 0 ? ` (+${rest} more — see the rejections)` : ""}`;
3267
3299
  try {
3268
- const closed = handle.accountLeg !== undefined ? await closeSessionAccount(this.governanceStore, this.controlDir, { sessionId: lineageSessionId, now: this.now, leg: handle.accountLeg }) : "absent";
3300
+ const closed = handle.accountLeg !== undefined ? await closeSessionAccount(this.governanceStore, { sessionId: lineageSessionId, now: this.now, leg: handle.accountLeg }) : "absent";
3269
3301
  if (closed === "stale" && !report.warnings.includes(STALE_LEG_NOTE))
3270
3302
  report.warnings.push(STALE_LEG_NOTE);
3271
3303
  if (closed === "written" && deferredSeats.length > 0) {
@@ -3481,7 +3513,7 @@ export class MemoryEngine {
3481
3513
  await resolveHoldRecord(this.governanceStore, { holdId, action, requestId, now: this.now });
3482
3514
  }
3483
3515
  async resolveSessionAccount(sessionId, requestId) {
3484
- await resolveSessionAccountRecord(this.governanceStore, this.controlDir, { sessionId, requestId, now: this.now });
3516
+ await resolveSessionAccountRecord(this.governanceStore, { sessionId, requestId, now: this.now });
3485
3517
  }
3486
3518
  async readDelegationSettlements() {
3487
3519
  return await effectiveSettlements(this.governanceStore);
@@ -3490,7 +3522,7 @@ export class MemoryEngine {
3490
3522
  return await readHolds(this.governanceStore);
3491
3523
  }
3492
3524
  async readDanglingSessionAccounts(selfSessionId) {
3493
- return await foreignDanglingSessionAccounts(this.governanceStore, this.controlDir, selfSessionId);
3525
+ return await foreignDanglingSessionAccounts(this.governanceStore, selfSessionId);
3494
3526
  }
3495
3527
  requireConsolidation() {
3496
3528
  if (this.consolidation === undefined) {
@@ -4836,8 +4868,8 @@ export class MemoryEngine {
4836
4868
  }
4837
4869
  return out;
4838
4870
  }
4839
- listOriginClearances() {
4840
- return readOriginClearances(this.controlDir);
4871
+ async listOriginClearances() {
4872
+ return readOriginClearances(this.governanceStore);
4841
4873
  }
4842
4874
  async clearEntryOrigin(entryId, input) {
4843
4875
  if (typeof input.requestId !== "string" || input.requestId.length === 0) {
@@ -4846,7 +4878,7 @@ export class MemoryEngine {
4846
4878
  if (typeof input.reason !== "string" || input.reason.length === 0) {
4847
4879
  MemoryEngine.originClearRefusal("memory.origin_clear_invalid", "clearEntryOrigin requires a non-empty reason (the host's stated ground rides the audit row) — refused, never defaulted.");
4848
4880
  }
4849
- const clearances = readOriginClearances(this.controlDir);
4881
+ const clearances = await readOriginClearances(this.governanceStore);
4850
4882
  const pending = clearances.find((r) => r.entryId === entryId && r.status === "pending");
4851
4883
  if (pending !== undefined)
4852
4884
  return await this.completeOriginClearance(pending, input.requestId);
@@ -4880,13 +4912,16 @@ export class MemoryEngine {
4880
4912
  at: this.now(),
4881
4913
  entryText: serializeEntryFile(cleared),
4882
4914
  };
4883
- openOriginClearance(this.controlDir, row);
4915
+ await openOriginClearance(this.governanceStore, row);
4884
4916
  return await this.completeOriginClearance({ ...row, status: "pending", events: [] }, input.requestId);
4885
4917
  }
4886
4918
  async completeOriginClearance(row, requestId) {
4887
- const fail = (code, detail, keepPending) => {
4919
+ if (row.custodyErased === true) {
4920
+ MemoryEngine.originClearRefusal("memory.origin_clear_unknown", `clearEntryOrigin ${JSON.stringify(row.entryId.slice(0, 80))}: the entry was erased, and the custody of its pending clearance ${JSON.stringify(row.clearanceId)} was erased with it — nothing is resumed (the row keeps who cleared, why and when).`);
4921
+ }
4922
+ const fail = async (code, detail, keepPending) => {
4888
4923
  try {
4889
- settleOriginClearance(this.controlDir, { clearanceId: row.clearanceId, to: "failed", requestId, eventId: uuidv7(), now: this.now, detail, ...(keepPending ? { keepPending: true } : {}) });
4924
+ await settleOriginClearance(this.governanceStore, { clearanceId: row.clearanceId, to: "failed", requestId, eventId: uuidv7(), now: this.now, detail, ...(keepPending ? { keepPending: true } : {}) });
4890
4925
  }
4891
4926
  catch {
4892
4927
  }
@@ -4895,11 +4930,16 @@ export class MemoryEngine {
4895
4930
  const parsed = parseEntryFile(row.entryText);
4896
4931
  const cleared = { id: row.entryId, slug: row.slug, scope: row.scope, frontmatter: parsed.frontmatter, body: parsed.body, rev: "" };
4897
4932
  cleared.rev = computeEntryRev(cleared);
4933
+ const refuseIfErasedSince = async () => {
4934
+ if (await clearanceCustodyErased(this.governanceStore, row.clearanceId)) {
4935
+ MemoryEngine.originClearRefusal("memory.origin_clear_unknown", `clearEntryOrigin ${JSON.stringify(row.entryId.slice(0, 80))}: the entry was erased while its clearance ${JSON.stringify(row.clearanceId)} ran, and the custody went with it — the entry is not re-recorded.`);
4936
+ }
4937
+ };
4898
4938
  const [current] = await this.committedAuditFace().getByIds([row.entryId]);
4899
4939
  if (current === undefined || committedOriginOf(current.frontmatter) !== undefined) {
4900
4940
  if (parsed.id !== row.entryId || committedOriginOf(parsed.frontmatter) !== undefined) {
4901
4941
  const what = parsed.id !== row.entryId ? "the custody bytes carry a different entry id" : "an origin form survived in the custody bytes";
4902
- fail("memory.origin_clear_failed", `the clearance row's custody text failed its identity/cleared-state validation (${what}) — refusing to act on it. ` +
4942
+ return await fail("memory.origin_clear_failed", `the clearance row's custody text failed its identity/cleared-state validation (${what}) — refusing to act on it. ` +
4903
4943
  (current === undefined
4904
4944
  ? "The row stays PENDING (the tombstone has committed and the row's entryText is the recovery seat — repair it, or recover the bytes by hand)."
4905
4945
  : "Re-judge with a fresh clearEntryOrigin call (this row is terminal; the marked entry stands untouched)."), current === undefined);
@@ -4909,13 +4949,13 @@ export class MemoryEngine {
4909
4949
  let detail;
4910
4950
  if (current !== undefined && committedOriginOf(current.frontmatter) !== undefined) {
4911
4951
  if ((await this.readChallengeExclusions()).has(row.entryId)) {
4912
- fail("memory.origin_clear_challenged", "the entry is challenged/latched — adjudicate the challenge first (the clear valve is not a challenge exit); the marked entry stands untouched and this row is terminal.", false);
4952
+ return await fail("memory.origin_clear_challenged", "the entry is challenged/latched — adjudicate the challenge first (the clear valve is not a challenge exit); the marked entry stands untouched and this row is terminal.", false);
4913
4953
  }
4914
4954
  if (current.rev !== row.baseRev) {
4915
- fail("memory.origin_clear_conflict", `the entry moved since the clearance was judged (rev ${row.baseRev.slice(0, 12)}… → ${current.rev.slice(0, 12)}…) — call clearEntryOrigin again to re-judge (the marked entry stands untouched; this row is terminal).`, false);
4955
+ return await fail("memory.origin_clear_conflict", `the entry moved since the clearance was judged (rev ${row.baseRev.slice(0, 12)}… → ${current.rev.slice(0, 12)}…) — call clearEntryOrigin again to re-judge (the marked entry stands untouched; this row is terminal).`, false);
4916
4956
  }
4917
4957
  if (current.scope !== row.scope || current.slug !== row.slug) {
4918
- fail("memory.origin_clear_conflict", `the entry's projection moved since the clearance was judged (${JSON.stringify(row.scope)}/${JSON.stringify(row.slug.slice(0, 80))} → ${JSON.stringify(current.scope)}/${JSON.stringify(current.slug.slice(0, 80))}) — call clearEntryOrigin again to re-judge (the marked entry stands untouched; this row is terminal).`, false);
4958
+ return await fail("memory.origin_clear_conflict", `the entry's projection moved since the clearance was judged (${JSON.stringify(row.scope)}/${JSON.stringify(row.slug.slice(0, 80))} → ${JSON.stringify(current.scope)}/${JSON.stringify(current.slug.slice(0, 80))}) — call clearEntryOrigin again to re-judge (the marked entry stands untouched; this row is terminal).`, false);
4919
4959
  }
4920
4960
  const projText = readNoFollowSafe(join(scopeDirFor(this.memoryDir, this.controlDir, current.scope), `${current.slug}.md`));
4921
4961
  let projIsPristineStub = false;
@@ -4924,23 +4964,24 @@ export class MemoryEngine {
4924
4964
  projIsPristineStub = projText === serializeEntryFile({ id: current.id, frontmatter: currentStubFm, body: STUB_ARCHIVED_LINE });
4925
4965
  }
4926
4966
  if (projText !== undefined && revOfText(projText, current.id) !== current.rev && !projIsPristineStub) {
4927
- fail("memory.origin_clear_conflict", "the entry's on-disk projection diverges from its committed state (an unadopted out-of-session edit stands on the plane) — the clear will not overwrite it; adopt or reconcile the divergence first, then call clearEntryOrigin again (the marked entry and the on-disk bytes both stand untouched; this row is terminal).", false);
4967
+ return await fail("memory.origin_clear_conflict", "the entry's on-disk projection diverges from its committed state (an unadopted out-of-session edit stands on the plane) — the clear will not overwrite it; adopt or reconcile the divergence first, then call clearEntryOrigin again (the marked entry and the on-disk bytes both stand untouched; this row is terminal).", false);
4928
4968
  }
4929
4969
  const del = await this.backend.applyPatches([{ op: "delete", id: row.entryId, baseRev: row.baseRev }]);
4930
4970
  if (del.conflicts.length > 0) {
4931
4971
  const [reprobe] = await this.committedAuditFace().getByIds([row.entryId]);
4932
4972
  if (reprobe !== undefined && committedOriginOf(reprobe.frontmatter) !== undefined) {
4933
- fail("memory.origin_clear_conflict", `the tombstone leg was refused (${(del.conflicts[0]?.reason ?? "conflict").slice(0, 160)}) — call clearEntryOrigin again to re-judge (the marked entry stands untouched; this row is terminal).`, false);
4973
+ return await fail("memory.origin_clear_conflict", `the tombstone leg was refused (${(del.conflicts[0]?.reason ?? "conflict").slice(0, 160)}) — call clearEntryOrigin again to re-judge (the marked entry stands untouched; this row is terminal).`, false);
4934
4974
  }
4935
4975
  if (reprobe === undefined) {
4936
4976
  try {
4937
- markOriginClearanceTombstoned(this.controlDir, { clearanceId: row.clearanceId, now: this.now });
4977
+ await markOriginClearanceTombstoned(this.governanceStore, { clearanceId: row.clearanceId, now: this.now });
4938
4978
  }
4939
4979
  catch {
4940
4980
  }
4981
+ await refuseIfErasedSince();
4941
4982
  const add = await this.backend.applyPatches([{ op: "add", id: row.entryId, entry: cleared, guard: "absent" }]);
4942
4983
  if (add.conflicts.length > 0) {
4943
- fail("memory.origin_clear_failed", `the re-record leg was refused (${(add.conflicts[0]?.reason ?? "conflict").slice(0, 160)}) — the row stays PENDING with the cleared bytes in its custody (entryText); call clearEntryOrigin again to resume.`, true);
4984
+ return await fail("memory.origin_clear_failed", `the re-record leg was refused (${(add.conflicts[0]?.reason ?? "conflict").slice(0, 160)}) — the row stays PENDING with the cleared bytes in its custody (entryText); call clearEntryOrigin again to resume.`, true);
4944
4985
  }
4945
4986
  landedSlug = add.applied.find((a) => a.id === row.entryId)?.slug ?? row.slug;
4946
4987
  detail = `cleared and re-recorded at slug ${JSON.stringify(landedSlug)} (tombstone raced by a concurrent resumer)`;
@@ -4952,13 +4993,14 @@ export class MemoryEngine {
4952
4993
  }
4953
4994
  else {
4954
4995
  try {
4955
- markOriginClearanceTombstoned(this.controlDir, { clearanceId: row.clearanceId, now: this.now });
4996
+ await markOriginClearanceTombstoned(this.governanceStore, { clearanceId: row.clearanceId, now: this.now });
4956
4997
  }
4957
4998
  catch {
4958
4999
  }
5000
+ await refuseIfErasedSince();
4959
5001
  const add = await this.backend.applyPatches([{ op: "add", id: row.entryId, entry: cleared, guard: "absent" }]);
4960
5002
  if (add.conflicts.length > 0) {
4961
- fail("memory.origin_clear_failed", `the re-record leg was refused (${(add.conflicts[0]?.reason ?? "conflict").slice(0, 160)}) — the row stays PENDING with the cleared bytes in its custody (entryText); call clearEntryOrigin again to resume.`, true);
5003
+ return await fail("memory.origin_clear_failed", `the re-record leg was refused (${(add.conflicts[0]?.reason ?? "conflict").slice(0, 160)}) — the row stays PENDING with the cleared bytes in its custody (entryText); call clearEntryOrigin again to resume.`, true);
4962
5004
  }
4963
5005
  landedSlug = add.applied.find((a) => a.id === row.entryId)?.slug ?? row.slug;
4964
5006
  detail = `cleared and re-recorded at slug ${JSON.stringify(landedSlug)}`;
@@ -4966,11 +5008,12 @@ export class MemoryEngine {
4966
5008
  }
4967
5009
  else if (current === undefined) {
4968
5010
  if (row.tombstonedAt === undefined) {
4969
- fail("memory.origin_clear_unknown", "the entry is no longer committed and this clearance never recorded a committed tombstone — the deletion is not this clearance's and stands (nothing was resurrected). The cleared bytes remain in this row's custody (entryText) for host review; this row is terminal.", false);
5011
+ return await fail("memory.origin_clear_unknown", "the entry is no longer committed and this clearance never recorded a committed tombstone — the deletion is not this clearance's and stands (nothing was resurrected). The cleared bytes remain in this row's custody (entryText) for host review; this row is terminal.", false);
4970
5012
  }
5013
+ await refuseIfErasedSince();
4971
5014
  const add = await this.backend.applyPatches([{ op: "add", id: row.entryId, entry: cleared, guard: "absent" }]);
4972
5015
  if (add.conflicts.length > 0) {
4973
- fail("memory.origin_clear_failed", `the resumed re-record leg was refused (${(add.conflicts[0]?.reason ?? "conflict").slice(0, 160)}) — the row stays PENDING with the cleared bytes in its custody (entryText); call clearEntryOrigin again to resume.`, true);
5016
+ return await fail("memory.origin_clear_failed", `the resumed re-record leg was refused (${(add.conflicts[0]?.reason ?? "conflict").slice(0, 160)}) — the row stays PENDING with the cleared bytes in its custody (entryText); call clearEntryOrigin again to resume.`, true);
4974
5017
  }
4975
5018
  landedSlug = add.applied.find((a) => a.id === row.entryId)?.slug ?? row.slug;
4976
5019
  detail = `resumed after interruption: re-recorded at slug ${JSON.stringify(landedSlug)}`;
@@ -4979,7 +5022,7 @@ export class MemoryEngine {
4979
5022
  landedSlug = current.slug;
4980
5023
  detail = current.rev === cleared.rev ? "already complete (terminal event replay)" : "marker already absent (a later committed generation stands; custody retained on this row)";
4981
5024
  }
4982
- settleOriginClearance(this.controlDir, { clearanceId: row.clearanceId, to: "done", requestId, eventId: uuidv7(), now: this.now, detail });
5025
+ await settleOriginClearance(this.governanceStore, { clearanceId: row.clearanceId, to: "done", requestId, eventId: uuidv7(), now: this.now, detail });
4983
5026
  await this.announce(row.scope, { kind: "gate", at: this.now(), items: [`memory entry ${inlineUntrusted(row.entryId, 80)} external-origin marker CLEARED by host request ${JSON.stringify(inlineUntrusted(requestId, 80))} — re-recorded unmarked (${inlineUntrusted(detail, 160)})`] }, "origin-clearance enqueue");
4984
5027
  return { entryId: row.entryId, clearanceId: row.clearanceId, origin: row.origin, landedSlug };
4985
5028
  }
@@ -27,11 +27,14 @@ export type ErasedBinding = {
27
27
  * - `indexLine` — MEMORY.md pointer lines (name + description) naming a deleted projection path;
28
28
  * - `quarantineCopy` — the governance store's `quarantine` objects whose frontmatter id is the erased id (an object the
29
29
  * lane could not read to tell is counted as remaining and named by `unreadable`);
30
+ * - `clearanceCustody` — the governance store's `clearance-custody` objects (and inline texts) of the clearances of an
31
+ * erased entry (#3463): the cleared entry's text a clearance kept, taken with the entry (the clearance's row stays,
32
+ * `custodyErased`);
30
33
  * - `planArchive` / `planWorkbook` — the consolidation plane's mint archive and plan workbook;
31
34
  * - `evidenceBinding` — evidence-chain rows that still spell the entry's slug;
32
35
  * - `backendDerived` — anything a backend derives privately (vectors, summaries).
33
36
  */
34
- export declare const ERASURE_CARRIER_CLASSES: readonly ["projection", "shadow", "indexLine", "quarantineCopy", "planArchive", "planWorkbook", "evidenceBinding", "backendDerived"];
37
+ export declare const ERASURE_CARRIER_CLASSES: readonly ["projection", "shadow", "indexLine", "quarantineCopy", "clearanceCustody", "planArchive", "planWorkbook", "evidenceBinding", "backendDerived"];
35
38
  export type ErasureCarrierClass = (typeof ERASURE_CARRIER_CLASSES)[number];
36
39
  /** One carrier class's answer: what this call removed and what is known to remain, or `unverified`
37
40
  * when the answering lane cannot read that class (which never reads as clean). `unreadable`, when a
@@ -7,6 +7,7 @@ import { MAX_MEMORY_BYTES } from "../memory.js";
7
7
  import { inlineUntrusted } from "../untrusted-text.js";
8
8
  import { ambiguousOriginRepresentation, committedDistilledOf, committedOriginOf, computeEntryRev, distilledEquals, entryFromFile, isValidEntryId, originEquals, parseEntryFile, serializeEntryFile } from "./frontmatter.js";
9
9
  import { convertV1SidecarKeys } from "./delegation-settlement.js";
10
+ import { eraseOriginClearanceCustody } from "./origin-clearance.js";
10
11
  import { layerObservationLookup, observedDivergenceNotice } from "./layer-observations.js";
11
12
  import { DEFAULT_MAX_ENTRY_DEPTH, MEMORY_INDEX_FILENAME, carriesEntry, scanEntryFiles } from "./entry-scan.js";
12
13
  import { ControlPlaneCorruptError, CURSORS_FILE, STRICT_CONTROL_PLANE_LEDGERS, fileGovernanceDocOf, importReceiptName, appendChallengeEvents, atomicWriteFileSync, clearContainedPath, eraseQuarantineCopies, quarantineCaptureName, captureAndClearLineageForEntries, adoptRootScopeLayout, anchorStoreRoot, effectiveControlRootOf, ensureDirExists, LEDGER_FILE, sayAnnounceFailure, enqueueMemoryAnnouncement, importLatchTxnId, importLineageCommitted, importSessionPollution, isContainedIn, lockedStrictUpdate, readStrictSidecar, permissionRemedyOf, withPermissionRemedy, lineageContributionsOfSession, listSessionPollution, readChallengeEvents, readLineageRecord, registerScope, registeredScopes, releaseImportLatch, layoutNeedsAdoption, scopeDirFor, scopeDirName, scopeRegistryShape, stageImportLatch, landsOutsideStore, storeActRefusal, storeRootMovedRefusal, writeAllSync, STORE_JOURNAL_FILE, ERASURE_SWEEP_RECORD_FILE, ERASURE_SWEEP_RECORD_WHAT, coerceErasureSweepRecord, erasureSweepOwedAt, erasureSweepRecordPathOf, STORE_TXN_LOCK_DIR, TXN_LOCK_STALE_MS, acquireStoreTxnLock, assertStoreTxnLockOwnership, renewStoreTxnLock, tryStoreTxnLock, } from "./layout.js";
@@ -19,7 +20,7 @@ import { admittingLandings, cutPerLanding, LandingsNeedAdmission, requireLanding
19
20
  import { thrownText } from "../thrown-value.js";
20
21
  import { optionKeys, receiveOptions } from "../own-property-receipt.js";
21
22
  export { DEFAULT_MAX_ENTRY_DEPTH, MEMORY_INDEX_FILENAME, scanEntryFiles } from "./entry-scan.js";
22
- export const ERASURE_CARRIER_CLASSES = Object.freeze(["projection", "shadow", "indexLine", "quarantineCopy", "planArchive", "planWorkbook", "evidenceBinding", "backendDerived"]);
23
+ export const ERASURE_CARRIER_CLASSES = Object.freeze(["projection", "shadow", "indexLine", "quarantineCopy", "clearanceCustody", "planArchive", "planWorkbook", "evidenceBinding", "backendDerived"]);
23
24
  export function erasureStatusOf(att) {
24
25
  if (att.conflicts.length > 0)
25
26
  return "partial";
@@ -2807,6 +2808,8 @@ export class FileMemoryEngineBackend {
2807
2808
  }
2808
2809
  const resolvedSet = new Set(resolvedIds);
2809
2810
  const quarantine = await eraseQuarantineCopies(standingControlObjectsOf(this.governance), resolvedSet);
2811
+ const conflicted = new Set(conflicts.map((c) => c.id));
2812
+ const clearanceCustody = await eraseOriginClearanceCustody(this.governance, new Set(resolvedIds.filter((id) => !conflicted.has(id))), this.now());
2810
2813
  const att = {
2811
2814
  v: 2,
2812
2815
  requestId,
@@ -2827,6 +2830,7 @@ export class FileMemoryEngineBackend {
2827
2830
  shadow: { removed: ops.filter((op) => op.kind === "shadow-delete").length, remaining: 0 },
2828
2831
  indexLine: readErasureSweep(this.controlPlaneRoot, this.directoryRoot, requestId).length > 0 ? { unverified: true } : { removed: 0, remaining: 0 },
2829
2832
  quarantineCopy: { removed: quarantine.removed, remaining: quarantine.remaining, unreadable: quarantine.unreadable },
2833
+ clearanceCustody: { removed: clearanceCustody.removed, remaining: clearanceCustody.remaining },
2830
2834
  planArchive: this.controlDirHoldsAnything(CONSOLIDATION_DRIVER_PLANS_DIR) ? { unverified: true } : { removed: 0, remaining: 0 },
2831
2835
  planWorkbook: this.controlDirHoldsAnything(CONSOLIDATION_PLANS_DIR) ? { unverified: true } : { removed: 0, remaining: 0 },
2832
2836
  evidenceBinding: { removed: 0, remaining: chain.filter((r) => typeof r.parsed.id === "string" && resolvedSet.has(r.parsed.id) && (spellsSlug(r.parsed.from) || spellsSlug(r.parsed.to))).length },
@@ -4,13 +4,13 @@ export { MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, MEMORY_PROVENANCE_R
4
4
  export { scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE } from "./scan.js";
5
5
  export { FileMemoryEngineBackend, readMemoryLedgerForm, scanEntryFiles, MEMORY_INDEX_FILENAME, DEFAULT_MAX_ENTRY_DEPTH, type ScannedEntryFile, type TransferEvidence, type CommittedBinding, type CommittedEntrySnapshot, type CommittedScopeSnapshots, type EntryCustodyReport, erasureSelectHash, type EraseMemoryEntriesInput, type ErasureCarrierAnswer, type ErasureCarrierClass, type ErasureCountAnswer, type ErasureSelect, type ErasedBinding, type MemoryErasureAttestation, type MemoryExportSnapshot, } from "./file-backend.js";
6
6
  export { computeBundleSectionHashes, computeMemoryBundleHash, memoryBundleInvalid, type MemoryExportBundle, type MemoryImportReport, type MemoryBundleImportPlan, type BundleChallengeRow, type BundleLineageRow, type BundlePollutedSession, } from "./export-bundle.js";
7
- export { ControlPlaneCorruptError, deriveControlPlaneDir, deriveRepoControlPlaneDir, deriveRepoKey, deriveRepoMemoryDir, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, resolveMemoryEngineRoot, scopeDirFor, scopeDirName, scopeRegistryShape, layoutNeedsAdoption, adoptRootScopeLayout, v1MemoryPathKeyResolver, unresolvedProjectionDebts, scanFuseKey, type AdoptRootScopeLayoutOptions, type ScopeRegistryShape, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, type ControlPlaneRebuildReceipt, type StrictControlPlaneLedger, type ChallengeAppendResult, type ChallengeAssignment, type ChallengeEvent, type ChallengedHistoryRow, type LineagePendingTxn, type LineagePromotion, SESSION_CAPTURE_OPTOUT_DIR, markSessionCaptureOptOut, readSessionCaptureOptOut, listSessionCaptureOptOut, fileSessionCaptureRecordStore, type SessionCaptureOptOutRecord, type SessionCaptureOptOutMarkOutcome, type SessionCaptureRecordStore, } from "./layout.js";
7
+ export { ControlPlaneCorruptError, deriveControlPlaneDir, deriveRepoControlPlaneDir, deriveRepoKey, deriveRepoMemoryDir, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, resolveMemoryEngineRoot, scopeDirFor, scopeDirName, scopeRegistryShape, layoutNeedsAdoption, adoptRootScopeLayout, v1MemoryPathKeyResolver, unresolvedProjectionDebts, scanFuseKey, type AdoptRootScopeLayoutOptions, type ScopeRegistryShape, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, type ControlPlaneRebuildReceipt, type StrictControlPlaneLedger, type ChallengeAppendResult, type ChallengeAssignment, type ChallengeEvent, type ChallengedHistoryRow, type LineagePendingTxn, type LineagePromotion, SESSION_CAPTURE_OPTOUT_DIR, type SessionCaptureOptOutRecord, type SessionCaptureOptOutMarkOutcome, type SessionCaptureRecordStore, } from "./layout.js";
8
8
  export { readV2HeaderHints, isInstructionEntry, type V2HeaderHints } from "./header-hints.js";
9
9
  export { parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, committedOriginOf, originEquals, ambiguousOriginRepresentation, type ParsedEntryFile } from "./frontmatter.js";
10
10
  export { consolidationExposedFrontmatter } from "./frontmatter.js";
11
11
  export { committedDistilledOf, distilledEquals } from "./frontmatter.js";
12
12
  export { deriveShadowedSet } from "./shadowing.js";
13
- export { CONSOLIDATION_DEFAULTS, ConsolidationRefusedError, MEMORY_SEARCH_SUPERSEDED_TAG, consolidationTypeEligible, deriveSupersededSet, memorySupersededNote, supersessionFuseCeiling, DELETION_FUSE_FLOOR, fileGovernanceStore, memoryGovernanceDurability, type MemoryGovernanceDurability, type ConsolidationGateRead, type ConsolidationGateRow, type ConsolidationIntent, type ConsolidationIntentCredentialRow, type ConsolidationLeaseSeat, type ConsolidationProductProposal, type ConsolidationProposal, type ConsolidationWriteGate, type MemoryConsolidationOptions, CONSOLIDATION_RUN_STOP_REASONS, type ConsolidationRunStopReason, } from "./consolidation.js";
13
+ export { CONSOLIDATION_DEFAULTS, ConsolidationRefusedError, MEMORY_SEARCH_SUPERSEDED_TAG, consolidationTypeEligible, deriveSupersededSet, memorySupersededNote, supersessionFuseCeiling, DELETION_FUSE_FLOOR, fileGovernanceStore, fileSessionCaptureRecordStore, memoryGovernanceDurability, type MemoryGovernanceDurability, type ConsolidationGateRead, type ConsolidationGateRow, type ConsolidationIntent, type ConsolidationIntentCredentialRow, type ConsolidationLeaseSeat, type ConsolidationProductProposal, type ConsolidationProposal, type ConsolidationWriteGate, type MemoryConsolidationOptions, CONSOLIDATION_RUN_STOP_REASONS, type ConsolidationRunStopReason, } from "./consolidation.js";
14
14
  export { DISTILLER_DEFAULT_MAX_INPUTS_PER_PRODUCT, LLM_DISTILLER_CONTRACT, LLM_DISTILLER_CONTRACT_DL2, LLM_DISTILLER_CONTRACT_DL3, LLM_DISTILLER_CONTRACTS, MEMORY_DISTILLER_CONTRACT_V1, contractGroupingDiff, driveConsolidationToFixpoint, isAliasModelId, llmPlanDistiller, mintExposurePartitionedPlan, mintLlmConsolidationPlan, MEMORY_DISTILLER_PURITY_CONTRACT_V1, detectCleanArmVerbatimLeak, type CleanArmLeakFinding, type CleanArmLeakVerdict, type MemoryDistillerPurityContract, openAiCompatChatSeat, parseJsonAnswer, planParseRepairs, sanitizeLlmGroups, scheduleUnderFuse, type ConsolidationDistillFn, type ConsolidationDriveCycleRow, type ConsolidationDriveEngine, type ConsolidationDriveResult, type ConsolidationFoldState, type DistillerCandidate, type DistillerChatAnswer, type DistillerChatFn, type DistillerChatRequest, type FuseSchedule, type LlmConsolidationPlan, type LlmConsolidationPlanArm, type LlmConsolidationPlanProduct, type LlmDistillerContract, type MintLlmConsolidationPlanResult, type PlanParseRepairs, type SanitizedLlmGroups, } from "./distiller.js";
15
15
  export { CONSOLIDATION_WRITE_REFUSED_CODE, runMemoryConsolidationDriver, type ConsolidationDriverEngine, type ConsolidationDriverRunRow, type ConsolidationRunReceipt, type ConsolidationWriteJudge, type ConsolidationWriteTarget, type RunMemoryConsolidationOptions, } from "./consolidation-driver.js";
16
16
  export type { OriginClearanceRow, OriginClearanceEvent, OriginClearanceShadow } from "./origin-clearance.js";