@sema-agent/core 7.64.0 → 7.65.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 (103) hide show
  1. package/CHANGELOG.md +317 -0
  2. package/dist/agents/peer-held-queue.js +1 -1
  3. package/dist/agents/peer-idle.js +1 -1
  4. package/dist/agents/peer-session-drain.js +3 -3
  5. package/dist/agents/subagent.js +5 -2
  6. package/dist/core/auto-promote.d.ts +3 -2
  7. package/dist/core/background-agent-store.d.ts +7 -0
  8. package/dist/core/checkpoint-store.d.ts +2 -3
  9. package/dist/core/context-settings.d.ts +1 -2
  10. package/dist/core/context-settings.js +1 -1
  11. package/dist/core/engine-attestation.d.ts +2 -2
  12. package/dist/core/engine-notice.d.ts +13 -1
  13. package/dist/core/engine-notice.js +3 -1
  14. package/dist/core/file-history-store.d.ts +2 -2
  15. package/dist/core/file-history-store.js +0 -4
  16. package/dist/core/gate-fold.js +3 -1
  17. package/dist/core/governance-codes.d.ts +6 -4
  18. package/dist/core/governance-codes.js +4 -3
  19. package/dist/core/leg-identity.d.ts +18 -2
  20. package/dist/core/leg-identity.js +5 -7
  21. package/dist/core/mailbox-store.d.ts +1 -1
  22. package/dist/core/memory-engine/consolidation.d.ts +10 -4
  23. package/dist/core/memory-engine/consolidation.js +11 -1
  24. package/dist/core/memory-engine/control-objects.d.ts +36 -3
  25. package/dist/core/memory-engine/control-objects.js +134 -12
  26. package/dist/core/memory-engine/control-plane-adoption.d.ts +5 -2
  27. package/dist/core/memory-engine/control-plane-adoption.js +5 -3
  28. package/dist/core/memory-engine/delegation-settlement.d.ts +59 -42
  29. package/dist/core/memory-engine/delegation-settlement.js +175 -202
  30. package/dist/core/memory-engine/dual-root.d.ts +3 -2
  31. package/dist/core/memory-engine/dual-root.js +5 -1
  32. package/dist/core/memory-engine/engine.d.ts +16 -10
  33. package/dist/core/memory-engine/engine.js +138 -145
  34. package/dist/core/memory-engine/file-backend.d.ts +17 -11
  35. package/dist/core/memory-engine/file-backend.js +53 -103
  36. package/dist/core/memory-engine/layout.d.ts +129 -49
  37. package/dist/core/memory-engine/layout.js +202 -82
  38. package/dist/core/memory-engine/memory-age.d.ts +12 -0
  39. package/dist/core/memory-engine/memory-age.js +17 -0
  40. package/dist/core/memory-engine/memory-backend-contract.js +5 -4
  41. package/dist/core/memory-engine/memory-deployment.d.ts +1 -1
  42. package/dist/core/memory-engine/origin-clearance.js +1 -5
  43. package/dist/core/memory-engine/tools.d.ts +2 -2
  44. package/dist/core/memory-engine/tools.js +7 -7
  45. package/dist/core/memory-engine/types.d.ts +16 -10
  46. package/dist/core/memory-vector.d.ts +6 -14
  47. package/dist/core/memory.d.ts +0 -462
  48. package/dist/core/memory.js +0 -333
  49. package/dist/core/permission-rule-consent.d.ts +49 -18
  50. package/dist/core/permission-rule-consent.js +59 -38
  51. package/dist/core/permission-rule-store.d.ts +24 -14
  52. package/dist/core/retention.d.ts +2 -7
  53. package/dist/core/retention.js +0 -1
  54. package/dist/core/runner/classifier-ladder.d.ts +3 -1
  55. package/dist/core/runner/classifier-ladder.js +2 -2
  56. package/dist/core/runner/contracts.d.ts +9 -9
  57. package/dist/core/runner/delegation-owner.d.ts +0 -8
  58. package/dist/core/runner/delegation-owner.js +1 -3
  59. package/dist/core/runner/prepare-gate-stations.d.ts +8 -5
  60. package/dist/core/runner/prepare-gate-stations.js +13 -5
  61. package/dist/core/runner/prepare-memory-engine-session.js +1 -1
  62. package/dist/core/runner/prepare-memory.js +9 -9
  63. package/dist/core/runner/prepare-policy-chain.js +11 -3
  64. package/dist/core/runner/prepare-task.d.ts +5 -1
  65. package/dist/core/runner/prepare-task.js +3 -3
  66. package/dist/core/runner/run-notification-lane.js +1 -1
  67. package/dist/core/runner/sub-agent-deny-lists.d.ts +19 -0
  68. package/dist/core/runner/sub-agent-deny-lists.js +25 -0
  69. package/dist/core/secret-env.d.ts +2 -2
  70. package/dist/core/secret-env.js +6 -20
  71. package/dist/core/session-store.d.ts +6 -6
  72. package/dist/core/session-store.js +3 -3
  73. package/dist/core/store-contracts/background-agent-store-contract.js +13 -0
  74. package/dist/core/task-notification.d.ts +35 -8
  75. package/dist/core/task-notification.js +31 -13
  76. package/dist/core/task-registry-agent.js +1 -0
  77. package/dist/core/task-registry-shared.d.ts +4 -0
  78. package/dist/core/tool-errors.d.ts +3 -3
  79. package/dist/core/tool-spec.d.ts +7 -7
  80. package/dist/core/write-protect.d.ts +16 -0
  81. package/dist/core/write-protect.js +10 -0
  82. package/dist/engine/session/repo-utils.d.ts +14 -4
  83. package/dist/engine/session/repo-utils.js +5 -4
  84. package/dist/index.d.ts +6 -6
  85. package/dist/index.js +6 -6
  86. package/dist/prompts/default.d.ts +1 -2
  87. package/dist/scenarios/full-body.d.ts +1 -1
  88. package/dist/stores/file/adoption/adopt.d.ts +1 -1
  89. package/dist/stores/file/index.d.ts +1 -15
  90. package/dist/stores/file/index.js +1 -15
  91. package/dist/stores/file/permission-rule-store.d.ts +12 -1
  92. package/dist/stores/file/permission-rule-store.js +31 -4
  93. package/dist/stores/file/session-store.js +1 -1
  94. package/package.json +2 -2
  95. package/test/export-surface.snapshot.json +9 -73
  96. package/wire-changes/core-stores-sql@7.65.0.json +30 -0
  97. package/wire-changes/core@7.65.0.json +1650 -0
  98. package/wire-changes/mods-kernel@7.65.0.json +30 -0
  99. package/wire-changes/primitives@7.65.0.json +337 -0
  100. package/dist/core/memory-recall.d.ts +0 -208
  101. package/dist/core/memory-recall.js +0 -136
  102. package/dist/stores/file/memory-store.d.ts +0 -124
  103. package/dist/stores/file/memory-store.js +0 -353
@@ -1,26 +1,27 @@
1
1
  import { createHash } from "node:crypto";
2
- import { accessSync, closeSync, constants as fsConstants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { accessSync, closeSync, constants as fsConstants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, unlinkSync } from "node:fs";
3
3
  import { basename, dirname, join, relative, sep } from "node:path";
4
4
  import { uuidv7 } from "../../internal/harness.js";
5
5
  import { MAX_MEMORY_BYTES, composeMemoryBlock, firstSentence } from "../memory.js";
6
6
  import { inlineUntrusted } from "../untrusted-text.js";
7
7
  import { canonicalJsonStringify } from "../canonical-json.js";
8
8
  import { mintSystemReminder } from "../reminder-mint.js";
9
- import { formatMemoryAge } from "../memory-recall.js";
9
+ 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, 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, fileGovernanceStoreDir, 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
- import { noReplaceRestore, retireStagingToCustody, stagingPathBeside } from "./delegation-settlement.js";
16
+ import { noReplaceRestore, retireStagingToObject, stagingPathBeside } from "./delegation-settlement.js";
17
+ import { probeControlPlaneLinks } from "./control-objects.js";
17
18
  import { sessionWriteHomeOf } from "./session-write-home.js";
18
19
  import { landedUndecided, layerDigest, layerObservationLookup, readOnlyLayerCandidates, readOnlyLayerCensus, recordLayerObservations, settleUndecidedLayerObservations, observationBacked, sameObservation, undecidedLayerObservations } from "./layer-observations.js";
19
20
  import { markOriginClearanceTombstoned, openOriginClearance, readOriginClearances, settleOriginClearance } from "./origin-clearance.js";
20
21
  import { carriesEntry } from "./entry-scan.js";
21
22
  import { DEFAULT_MAX_ENTRY_DEPTH, MEMORY_INDEX_FILENAME, captureErasureInput, erasureRequestInvalid, erasureScopeRefusal, erasureSelectHash, erasureStatusOf, sweepUnderErasureRecord, scanEntryFiles, } from "./file-backend.js";
22
23
  import { assembleMemoryExportBundle, canonicalExpectedScopes, computeMemoryBundleHash, expectedScopesInvalid, firstOutsideExpectedScopes, memoryBundleInvalid, } from "./export-bundle.js";
23
- import { QUARANTINE_DIR, SCAN_FUSE_THRESHOLD, quarantineAndTombstone, 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";
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";
24
25
  import { createSessionIncarnationSeat, recalledForAnyIdentity, recalledForIdentity, rememberForIdentity } from "./session-incarnation.js";
25
26
  import { scanMemoryFileName, scanMemoryWrite, scanRemediation } from "./scan.js";
26
27
  import { writableRootOf } from "./types.js";
@@ -120,7 +121,6 @@ function homeRel(home, canonical) {
120
121
  export const DEFAULT_HOLD_SETTLE_TIMEOUT_MS = 72 * 60 * 60 * 1000;
121
122
  export const MASS_DELETION_FUSE_RATIO = 0.5;
122
123
  const MEMORY_ENGINE_OPTION_KEYS = optionKeys()({ backend: 0, memoryDir: 0, controlDir: 0, now: 0, perScopeBudgetBytes: 0, perFileBytes: 0, maxFiles: 0, maxDepth: 0, provenance: 0, captureRecordStore: 0, sessionIncarnation: 0, holdSettleTimeoutMs: 0, harvestDeadlineMs: 0, harvestFileBudget: 0, onIncident: 0, consolidation: 0 });
123
- let indexCaptureSeq = 0;
124
124
  export function memorySessionPollutedNotice(input) {
125
125
  const reason = inlineUntrusted(input.reason, 200);
126
126
  const message = input.provenance === "carry"
@@ -488,7 +488,7 @@ export class MemoryEngine {
488
488
  }
489
489
  catch {
490
490
  }
491
- return this.backend.readCommittedShadow?.(id) ?? readSafe(join(this.controlDir, "shadow", `${id}.md`));
491
+ return this.backend.readCommittedShadow?.(id);
492
492
  }
493
493
  async restoreReadOnlyLayers(candidates, report, selfLeg, handle) {
494
494
  let writers;
@@ -778,28 +778,22 @@ export class MemoryEngine {
778
778
  async markSessionPolluted(sessionId, reason, cause) {
779
779
  const incarnation = this.incarnation.incarnationOf(sessionId);
780
780
  rememberForIdentity(this.pollutedSessions, sessionId, { at: this.now(), reason, ...(cause !== undefined ? { cause } : {}), ...(incarnation !== undefined ? { incarnation } : {}) });
781
- let outcome;
782
- try {
783
- outcome = markSessionPolluted(this.controlDir, sessionId, reason, this.now, cause, incarnation);
784
- }
785
- catch {
786
- outcome = "unpersisted";
787
- }
788
- if (outcome === "unpersisted") {
789
- const sink = this.onIncident;
790
- if (sink !== undefined) {
791
- try {
792
- const err = new Error(`memory pollution marker for session could not be persisted — the mark holds in-process only until it succeeds`);
793
- err.code = "memory.pollution_mark_failed";
794
- sink(err);
795
- }
796
- catch {
781
+ const written = markSessionPolluted(this.governanceStore, sessionId, reason, this.now, cause, incarnation).catch(() => "unpersisted");
782
+ const sweep = (async () => {
783
+ if ((await written) === "unpersisted") {
784
+ const sink = this.onIncident;
785
+ if (sink !== undefined) {
786
+ try {
787
+ const err = new Error(`memory pollution marker for session could not be persisted — the mark holds in-process only until it succeeds`);
788
+ err.code = "memory.pollution_mark_failed";
789
+ sink(err);
790
+ }
791
+ catch {
792
+ }
797
793
  }
798
794
  }
799
- }
800
- const sweep = (async () => {
801
795
  try {
802
- const rec = this.sessionPollution(sessionId) ?? { at: this.now(), reason };
796
+ const rec = (await this.sessionPollution(sessionId)) ?? { at: this.now(), reason };
803
797
  const swept = await lineageContributionsOfSession(this.governanceStore, sessionId, incarnation);
804
798
  const contributions = this.provenance === "carry" ? swept.filter((c) => c.marked !== true) : swept;
805
799
  await this.challengeAndAnnounce(contributions.map((c) => ({
@@ -829,19 +823,14 @@ export class MemoryEngine {
829
823
  finally {
830
824
  this.pendingPollutionSweeps.delete(sweep);
831
825
  }
832
- return outcome;
826
+ return written;
833
827
  }
834
- sessionPollution(sessionId) {
828
+ async sessionPollution(sessionId) {
835
829
  const identity = this.incarnation.identityRead(sessionId);
836
830
  const inProcess = recalledForIdentity(this.pollutedSessions, sessionId, identity.incarnation);
837
831
  if (inProcess !== undefined)
838
832
  return inProcess;
839
- try {
840
- return readSessionPollution(this.controlDir, sessionId, identity);
841
- }
842
- catch {
843
- return undefined;
844
- }
833
+ return readSessionPollution(this.governanceStore, sessionId, identity);
845
834
  }
846
835
  captureRecords;
847
836
  captureOptOutSessions = new Map();
@@ -921,13 +910,15 @@ export class MemoryEngine {
921
910
  if (first !== undefined && first !== baseline) {
922
911
  const onDisk = readSafe(indexPath);
923
912
  if (onDisk !== undefined && onDisk !== baseline) {
924
- const q = quarantineAndTombstone(indexPath, onDisk, join(this.controlDir, QUARANTINE_DIR), this.now);
913
+ const q = await this.containSuspect(indexPath, onDisk, "sweeping the index", handle);
925
914
  let contained = q.removed;
926
915
  if (baseline !== undefined) {
927
916
  try {
928
- writeFileNoFollow(indexPath, baseline);
929
- out.restored.push(MEMORY_INDEX_FILENAME);
930
- contained = true;
917
+ this.refuseOutsideStore(indexPath, "restoring the index", handle);
918
+ if (restoreContainedBaseline(indexPath, baseline, q.leftOnPlane) === "written") {
919
+ out.restored.push(MEMORY_INDEX_FILENAME);
920
+ contained = true;
921
+ }
931
922
  }
932
923
  catch {
933
924
  }
@@ -1002,9 +993,10 @@ export class MemoryEngine {
1002
993
  out.failures.push({ path: rel, detail: `${refusedHere} — not swept` });
1003
994
  continue;
1004
995
  }
1005
- const q = quarantineAndTombstone(canonical, text2, join(this.controlDir, QUARANTINE_DIR), this.now);
996
+ const q = await this.containSuspect(canonical, text2, "sweeping a residue file", handle);
1006
997
  let contained = q.removed;
1007
- if (committed !== undefined) {
998
+ const refusedRestore = committed !== undefined ? this.storeActRefusedText(canonical, "restoring a residue file's baseline", handle) : undefined;
999
+ if (committed !== undefined && refusedRestore === undefined) {
1008
1000
  const put = restoreContainedBaseline(canonical, committed, q.leftOnPlane);
1009
1001
  if (put === "written") {
1010
1002
  out.restored.push(rel);
@@ -1014,10 +1006,10 @@ export class MemoryEngine {
1014
1006
  out.withheld.push({ path: rel, ...(parsedId !== undefined ? { entryId: parsedId, rev: revOfText(committed, parsedId) } : {}) });
1015
1007
  }
1016
1008
  }
1017
- if (q.dest !== undefined && contained)
1009
+ if (q.dest !== undefined && contained && refusedRestore === undefined)
1018
1010
  out.swept.push(rel);
1019
1011
  else
1020
- out.failures.push({ path: rel, detail: q.detail ?? (q.dest === undefined ? "quarantine capture failed" : "removal from the authoritative plane incomplete") });
1012
+ out.failures.push({ path: rel, detail: refusedRestore !== undefined ? `${refusedRestore} — the committed baseline was not restored` : q.detail ?? (q.dest === undefined ? "quarantine capture failed" : "removal from the authoritative plane incomplete") });
1021
1013
  }
1022
1014
  return out;
1023
1015
  }
@@ -1230,6 +1222,7 @@ export class MemoryEngine {
1230
1222
  const notFound = resolvedIds.filter((id) => !byId.has(id)).map((id) => ({ id, historyUnknown: true }));
1231
1223
  const conflicts = report.conflicts.map((c) => ({ id: c.id, reason: c.reason }));
1232
1224
  const unverified = { unverified: true };
1225
+ const quarantine = await eraseQuarantineCopies(standingControlObjectsOf(this.governanceStore), new Set(resolvedIds)).catch(() => undefined);
1233
1226
  const att = {
1234
1227
  v: 2,
1235
1228
  requestId,
@@ -1244,8 +1237,8 @@ export class MemoryEngine {
1244
1237
  notFound,
1245
1238
  conflicts,
1246
1239
  residuals: {
1247
- carriers: { projection: unverified, shadow: unverified, indexLine: { removed: 0, remaining: 0 }, quarantineCopy: unverified, planArchive: unverified, planWorkbook: unverified, evidenceBinding: unverified, backendDerived: unverified },
1248
- quarantineUnattributed: unverified,
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 },
1241
+ quarantineUnattributed: quarantine !== undefined ? { count: quarantine.unattributed } : unverified,
1249
1242
  derivedEntries: unverified,
1250
1243
  replay: "unsupported",
1251
1244
  propagation: "local-store-only",
@@ -1400,16 +1393,18 @@ export class MemoryEngine {
1400
1393
  const readEnginePlane = async () => {
1401
1394
  const challenged = (await challengedEntryIds(this.governanceStore)).get(entryId);
1402
1395
  const lineage = await lineageAccountOfEntry(this.governanceStore, entryId);
1396
+ const contributors = [];
1397
+ for (const c of lineage.contributors) {
1398
+ const polluted = await this.sessionPollution(c.sessionId);
1399
+ contributors.push({
1400
+ sessionId: c.sessionId,
1401
+ lastRev: c.lastRev,
1402
+ lastAt: c.lastAt,
1403
+ ...(polluted !== undefined ? { polluted: { at: polluted.at, reason: polluted.reason } } : {}),
1404
+ });
1405
+ }
1403
1406
  return {
1404
- contributors: lineage.contributors.map((c) => {
1405
- const polluted = this.sessionPollution(c.sessionId);
1406
- return {
1407
- sessionId: c.sessionId,
1408
- lastRev: c.lastRev,
1409
- lastAt: c.lastAt,
1410
- ...(polluted !== undefined ? { polluted: { at: polluted.at, reason: polluted.reason } } : {}),
1411
- };
1412
- }),
1407
+ contributors,
1413
1408
  exclusion: challenged !== undefined
1414
1409
  ? { code: "challenged", generation: challenged.generation, at: challenged.at }
1415
1410
  : lineage.pendingLatched
@@ -1629,13 +1624,7 @@ export class MemoryEngine {
1629
1624
  for (const p of promoted) {
1630
1625
  if (this.provenance === "carry" && p.marked === true)
1631
1626
  continue;
1632
- let rec;
1633
- try {
1634
- rec = readSessionPollution(this.controlDir, p.sessionId);
1635
- }
1636
- catch {
1637
- rec = undefined;
1638
- }
1627
+ let rec = await readSessionPollution(this.governanceStore, p.sessionId);
1639
1628
  if (rec === undefined)
1640
1629
  rec = recalledForAnyIdentity(this.pollutedSessions, p.sessionId);
1641
1630
  if (rec === undefined)
@@ -1679,6 +1668,8 @@ export class MemoryEngine {
1679
1668
  this.assertRootAnchored();
1680
1669
  ensureDirExists(this.memoryDir);
1681
1670
  ensureDirExists(this.controlDir);
1671
+ if (this.governanceStore !== this.backend.governance)
1672
+ probeControlPlaneLinks(this.controlDir);
1682
1673
  await this.adoptLayoutBeforeMount(writeScope);
1683
1674
  this.assertRootAnchored();
1684
1675
  const restricted = opts?.adoptionRestricted === true;
@@ -1756,11 +1747,11 @@ export class MemoryEngine {
1756
1747
  if (committed !== undefined && committed !== text) {
1757
1748
  let captured = false;
1758
1749
  const captureName = `${this.now()}-residue-${parsed.id}.md`;
1759
- const capturePath = join(this.controlDir, QUARANTINE_DIR, captureName);
1760
1750
  try {
1761
- ensureDirExists(join(this.controlDir, QUARANTINE_DIR));
1762
- writeFileSync(capturePath, text, { encoding: "utf8", flag: "wx" });
1763
- captured = readFileSync(capturePath, "utf8") === text;
1751
+ if ((await putControlObjectOnce(this.governanceStore, "quarantine", captureName, new TextEncoder().encode(text))) === "created") {
1752
+ const back = await this.governanceStore.getObject("quarantine", captureName);
1753
+ captured = back !== undefined && new TextDecoder().decode(back) === text;
1754
+ }
1764
1755
  }
1765
1756
  catch {
1766
1757
  captured = false;
@@ -1784,7 +1775,7 @@ export class MemoryEngine {
1784
1775
  else {
1785
1776
  const restore = noReplaceRestore(stagingPath, canonical);
1786
1777
  if (restore !== "restored") {
1787
- const retired = retireStagingToCustody(stagingPath, join(this.controlDir, QUARANTINE_DIR), stagingName);
1778
+ const retired = await retireStagingToObject(this.governanceStore, stagingPath, "quarantine", stagingName, () => this.storeActRefusedText(stagingPath, "removing a contained staging copy"));
1788
1779
  if (restore === "stranded" || !retired.settled)
1789
1780
  this.discloseSessionAccountIncident(`a concurrent write to ${rel} landed during residue containment and could not be restored — its bytes are preserved at ${retired.at}`, undefined);
1790
1781
  }
@@ -1916,7 +1907,7 @@ export class MemoryEngine {
1916
1907
  }
1917
1908
  }
1918
1909
  }
1919
- const indexGate = this.gateDerivedIndex(handle);
1910
+ const indexGate = await this.gateDerivedIndex(handle);
1920
1911
  if (indexGate !== undefined) {
1921
1912
  if (!indexGate.contained)
1922
1913
  handle.indexOnDiskUntrusted = true;
@@ -2121,7 +2112,7 @@ export class MemoryEngine {
2121
2112
  return report;
2122
2113
  }
2123
2114
  async harvestCore(handle, opts) {
2124
- const openingRecord = opts?.sessionId !== undefined ? this.sessionPollution(opts.sessionId) : undefined;
2115
+ const openingRecord = opts?.sessionId !== undefined ? await this.sessionPollution(opts.sessionId) : undefined;
2125
2116
  let pollutedReason = opts?.polluted?.reason ?? openingRecord?.reason;
2126
2117
  let pollutionCause = opts?.polluted?.cause ?? openingRecord?.cause;
2127
2118
  const carry = this.provenance === "carry";
@@ -2233,7 +2224,12 @@ export class MemoryEngine {
2233
2224
  this.assertRootAnchored(handle);
2234
2225
  const stranded = [];
2235
2226
  try {
2236
- reconcileHolds(this.controlDir, { homeOf: (scope) => scopeDirFor(this.memoryDir, this.controlDir, scope), now: this.now, onStranded: (scope, line) => stranded.push({ scope, line }) });
2227
+ await reconcileHolds(this.governanceStore, {
2228
+ homeOf: (scope) => scopeDirFor(this.memoryDir, this.controlDir, scope),
2229
+ now: this.now,
2230
+ onStranded: (scope, line) => stranded.push({ scope, line }),
2231
+ actRefused: (path, act) => this.storeActRefusedText(path, act, handle),
2232
+ });
2237
2233
  }
2238
2234
  finally {
2239
2235
  for (const s of stranded)
@@ -2243,7 +2239,7 @@ export class MemoryEngine {
2243
2239
  if (newlyExpired.length > 0) {
2244
2240
  this.warnScoped(report, undefined, `${newlyExpired.length} delegation settlement row(s) passed the ${this.holdSettleTimeoutMs}ms window without settling and are now EXPIRED — a timeout, not a conviction: the affected sessions' unprovable windows close exposed, their held instruction entries dispose to quarantine (resolveHold can still release one with a "static"-cause marker), and resolveSettlement can overturn the expiry with an audited ruling`);
2245
2241
  }
2246
- await replayExternalSettlementEffects(this.governanceStore, this.controlDir, { carry, now: this.now });
2242
+ await replayExternalSettlementEffects(this.governanceStore, { carry, now: this.now });
2247
2243
  const settled = await this.settleDueHolds(handle, report);
2248
2244
  for (const rel of settled.released)
2249
2245
  signalContainment((c) => pushDistinct(c.releasedHolds, rel));
@@ -2273,7 +2269,7 @@ export class MemoryEngine {
2273
2269
  : `memory lineage transaction ${u.txnId} is unsettled (a crash landed between commit and its durable credential) — ${u.entryIds.length} entr${u.entryIds.length === 1 ? "y is" : "ies are"} latched (memory reads refuse them) until the host adjudicates it (adjudicatePendingLineage)`);
2274
2270
  }
2275
2271
  if (pollutedReason !== undefined && lineageSessionId !== undefined) {
2276
- const rec2 = this.sessionPollution(lineageSessionId);
2272
+ const rec2 = await this.sessionPollution(lineageSessionId);
2277
2273
  if (rec2 !== undefined) {
2278
2274
  const replaySwept = await lineageContributionsOfSession(this.governanceStore, lineageSessionId, this.incarnation.incarnationOf(lineageSessionId));
2279
2275
  const contributions = carry ? replaySwept.filter((c) => c.marked !== true) : replaySwept;
@@ -2357,7 +2353,7 @@ export class MemoryEngine {
2357
2353
  const pollutedStub = pollutedStubs.get(f.canonical);
2358
2354
  if (pollutedStub) {
2359
2355
  if (revOfText(f.text, pollutedStub.id) !== pollutedStub.rev) {
2360
- const sq = quarantineAndTombstone(f.canonical, f.text, join(this.controlDir, QUARANTINE_DIR), this.now);
2356
+ const sq = await this.containSuspect(f.canonical, f.text, "containing a withheld file", handle);
2361
2357
  const stubCaptured = sq.dest !== undefined;
2362
2358
  if (stubCaptured && sq.removed)
2363
2359
  report.movedToQuarantine.push(rel);
@@ -2374,7 +2370,7 @@ export class MemoryEngine {
2374
2370
  }
2375
2371
  return;
2376
2372
  }
2377
- const q = quarantineAndTombstone(f.canonical, f.text, join(this.controlDir, QUARANTINE_DIR), this.now);
2373
+ const q = await this.containSuspect(f.canonical, f.text, "containing a withheld file", handle);
2378
2374
  let contained = q.removed;
2379
2375
  const priorId = handle.baseIds.get(f.canonical);
2380
2376
  if (priorId !== undefined) {
@@ -2408,7 +2404,7 @@ export class MemoryEngine {
2408
2404
  report.warnings.push(`quarantine escalation for ${rel}: ${detail}`);
2409
2405
  }
2410
2406
  };
2411
- const restorePollutedIndex = () => {
2407
+ const restorePollutedIndex = async () => {
2412
2408
  const pollutedIndexPath = join(writableRoot, MEMORY_INDEX_FILENAME);
2413
2409
  const canonicalIndex = canonicalize(pollutedIndexPath);
2414
2410
  if (canonicalIndex !== pollutedIndexPath && !canonicalIndex.startsWith(`${writableRoot}${sep}`)) {
@@ -2418,19 +2414,22 @@ export class MemoryEngine {
2418
2414
  const indexNow = readSafe(pollutedIndexPath);
2419
2415
  if (indexNow === undefined || indexNow === handle.indexText)
2420
2416
  return false;
2421
- let indexCaptureLanded = false;
2422
- try {
2423
- const dest = join(this.controlDir, QUARANTINE_DIR, `${this.now()}-polluted-${MEMORY_INDEX_FILENAME}`);
2424
- ensureDirExists(dirname(dest));
2425
- writeFileSync(dest, indexNow, { encoding: "utf8", flag: "wx" });
2426
- indexCaptureLanded = true;
2427
- }
2428
- catch {
2429
- }
2417
+ const kept = await keepCopiesBeforeOverwrite(indexNow, async (bytes) => {
2418
+ try {
2419
+ return (await putControlObjectOnce(this.governanceStore, "quarantine", `${this.now()}-polluted-${MEMORY_INDEX_FILENAME}`, new TextEncoder().encode(bytes))) === "created" ? true : "an earlier capture stands under this name";
2420
+ }
2421
+ catch (err) {
2422
+ return thrownText(err);
2423
+ }
2424
+ }, () => {
2425
+ this.refuseOutsideStore(pollutedIndexPath, "reading the index again after its copy", handle);
2426
+ return readNoFollowSafe(pollutedIndexPath);
2427
+ });
2428
+ const indexCaptureLanded = kept.landed;
2430
2429
  try {
2431
2430
  this.refuseOutsideStore(pollutedIndexPath, "restoring the index", handle);
2432
2431
  writeFileNoFollow(pollutedIndexPath, handle.indexText);
2433
- report.warnings.push(`memory index restored to its pre-session state — this session's index additions were not retained (session polluted; ${indexCaptureLanded ? "the removed text was captured to quarantine" : "the quarantine capture did NOT land — the removed text is gone"})`);
2432
+ report.warnings.push(`memory index restored to its pre-session state — this session's index additions were not retained (session polluted; ${indexCaptureLanded ? "the removed text was captured to quarantine" : `the quarantine capture did NOT land for all of it (${kept.failed.join("; ")}) — the text it did not capture is gone`})`);
2434
2433
  return true;
2435
2434
  }
2436
2435
  catch (err) {
@@ -2441,7 +2440,7 @@ export class MemoryEngine {
2441
2440
  const containPollutedDomain = async () => {
2442
2441
  for (const f of records)
2443
2442
  await containPollutedRecord(f);
2444
- if (restorePollutedIndex())
2443
+ if (await restorePollutedIndex())
2445
2444
  signalContainment((c) => (c.indexRolledBack = true));
2446
2445
  report.warnings.push(`memory harvest committed nothing this session: ${inlineUntrusted(pollutedReason, 200)}`);
2447
2446
  };
@@ -2460,7 +2459,7 @@ export class MemoryEngine {
2460
2459
  signalContainment((c) => pushDistinct(c.quarantinedInstruction, f.rel));
2461
2460
  }
2462
2461
  }
2463
- if (restorePollutedIndex())
2462
+ if (await restorePollutedIndex())
2464
2463
  signalContainment((c) => (c.indexRolledBack = true));
2465
2464
  report.warnings.push(`memory harvest refused by an incident while this session is marked externally exposed — no entries were committed; instruction-form files were withheld and the derived index rolled back: ${inlineUntrusted(pollutedReason, 200)}`);
2466
2465
  };
@@ -2637,7 +2636,7 @@ export class MemoryEngine {
2637
2636
  const finding = scanFindings[0];
2638
2637
  if (finding !== undefined) {
2639
2638
  const refusedHere = this.storeActRefusedText(f.canonical, "quarantining a rejected file", handle);
2640
- const q = refusedHere === undefined ? quarantineAndTombstone(f.canonical, f.text, join(this.controlDir, QUARANTINE_DIR), this.now) : { removed: false, leftOnPlane: f.text, detail: refusedHere };
2639
+ const q = refusedHere === undefined ? await this.containSuspect(f.canonical, f.text, "quarantining a rejected file", handle) : { removed: false, leftOnPlane: f.text, detail: refusedHere };
2641
2640
  let contained = q.removed;
2642
2641
  const priorId = idByBasePath.get(f.canonical);
2643
2642
  if (priorId !== undefined) {
@@ -2645,9 +2644,14 @@ export class MemoryEngine {
2645
2644
  if (committed !== undefined) {
2646
2645
  try {
2647
2646
  this.refuseOutsideStore(f.canonical, "restoring a rejected file's committed content", handle);
2648
- writeFileNoFollow(f.canonical, committed);
2649
- report.restored.push(rel);
2650
- contained = true;
2647
+ const put = restoreContainedBaseline(f.canonical, committed, q.leftOnPlane);
2648
+ if (put === "written") {
2649
+ report.restored.push(rel);
2650
+ contained = true;
2651
+ }
2652
+ else if (put === "kept") {
2653
+ (report.restoreWithheld ??= []).push({ path: rel, entryId: priorId, rev: revOfText(committed, priorId) });
2654
+ }
2651
2655
  }
2652
2656
  catch {
2653
2657
  }
@@ -2747,7 +2751,7 @@ export class MemoryEngine {
2747
2751
  }
2748
2752
  if (instructionForm && sessionPending && lineageSessionId !== undefined) {
2749
2753
  const holdRefused = this.storeActRefusedText(f.canonical, "holding an instruction-form file", handle);
2750
- const held = holdRefused !== undefined ? { ok: false, reason: holdRefused } : openInstructionHold(this.controlDir, {
2754
+ const held = holdRefused !== undefined ? { ok: false, reason: holdRefused } : await openInstructionHold(this.governanceStore, {
2751
2755
  sessionId: lineageSessionId,
2752
2756
  rel: homeRel(writableRoot, f.canonical),
2753
2757
  absPath: f.canonical,
@@ -2759,6 +2763,7 @@ export class MemoryEngine {
2759
2763
  scope: writeScope,
2760
2764
  settleIds: pendingSettleIds,
2761
2765
  now: this.now,
2766
+ actRefused: (path, act) => this.storeActRefusedText(path, act, handle),
2762
2767
  });
2763
2768
  if (held.ok) {
2764
2769
  report.warnings.push(`${rel}: instruction-form entry HELD — this session's delegation outcome is still pending (attested-only evidence standard); the file was captured off the model-visible plane and commits automatically when every delegation settles clean, disposes to quarantine on a dirty or expired settlement (resolveHold is the host valve)`);
@@ -2918,7 +2923,7 @@ export class MemoryEngine {
2918
2923
  report.inboundFindings = preFindings;
2919
2924
  return report;
2920
2925
  }
2921
- const preCommit = lineageSessionId !== undefined ? this.sessionPollution(lineageSessionId) : undefined;
2926
+ const preCommit = lineageSessionId !== undefined ? await this.sessionPollution(lineageSessionId) : undefined;
2922
2927
  if (preCommit !== undefined && !carry) {
2923
2928
  if (lineageArmed) {
2924
2929
  try {
@@ -3154,7 +3159,7 @@ export class MemoryEngine {
3154
3159
  }
3155
3160
  catch {
3156
3161
  }
3157
- const postCommit = lineageSessionId !== undefined && pollutedReason === undefined ? this.sessionPollution(lineageSessionId) : undefined;
3162
+ const postCommit = lineageSessionId !== undefined && pollutedReason === undefined ? await this.sessionPollution(lineageSessionId) : undefined;
3158
3163
  if (postCommit !== undefined) {
3159
3164
  const appliedNonDelete = patchReport.applied.filter((a) => a.op !== "delete").map((a) => a.id);
3160
3165
  try {
@@ -3233,19 +3238,19 @@ export class MemoryEngine {
3233
3238
  if (drained !== undefined && drained.length > 0)
3234
3239
  report.inboundFindings = drained;
3235
3240
  if (pollutedReason !== undefined) {
3236
- if (restorePollutedIndex())
3241
+ if (await restorePollutedIndex())
3237
3242
  signalContainment((c) => (c.indexRolledBack = true));
3238
3243
  report.warnings.push(carry
3239
3244
  ? `memory entries from this externally exposed session were committed with an external-origin marker; its index prose additions were not retained: ${inlineUntrusted(pollutedReason, 200)}`
3240
3245
  : `memory harvest committed nothing this session: ${inlineUntrusted(pollutedReason, 200)}`);
3241
3246
  }
3242
3247
  else if (carry && sessionPending) {
3243
- if (restorePollutedIndex()) {
3248
+ if (await restorePollutedIndex()) {
3244
3249
  signalContainment((c) => (c.indexRolledBack = true));
3245
3250
  report.warnings.push("this session's index prose additions were not retained: its delegation outcome is still pending (prose has no entry anchor for the settlement account to govern; committed entries and mechanical index lines are unaffected)");
3246
3251
  }
3247
3252
  }
3248
- const indexGate = this.gateDerivedIndex(handle);
3253
+ const indexGate = await this.gateDerivedIndex(handle);
3249
3254
  if (indexGate !== undefined) {
3250
3255
  report.rejections.push(indexGate.rejection);
3251
3256
  if (!indexGate.contained)
@@ -3299,12 +3304,12 @@ export class MemoryEngine {
3299
3304
  }
3300
3305
  async settleDueHolds(handle, report) {
3301
3306
  const out = { released: [], disposed: [] };
3302
- const dispose = (row, terminal, why) => {
3303
- const d = disposeHold(this.controlDir, { holdId: row.holdId, terminal });
3307
+ const dispose = async (row, terminal, why) => {
3308
+ const d = await disposeHold(this.governanceStore, { holdId: row.holdId, terminal });
3304
3309
  out.disposed.push({ relPath: this.holdPlaneRel(row), terminal });
3305
3310
  this.warnScoped(report, row.scope, `held instruction entry ${this.holdPlaneRel(row)} DISPOSED (${terminal}): ${why}${d.quarantineName !== undefined ? ` — captured bytes moved to control-plane quarantine (${d.quarantineName})` : ""}`);
3306
3311
  };
3307
- for (const row of readHolds(this.controlDir)) {
3312
+ for (const row of await readHolds(this.governanceStore)) {
3308
3313
  const valveRelease = row.resolved === "release" && (row.status === "held" || (row.status === "disposed" && row.disposition?.terminal === "expired"));
3309
3314
  if (valveRelease) {
3310
3315
  const released = await this.releaseHold(handle, report, row, { valve: true, disposed: out.disposed });
@@ -3315,17 +3320,17 @@ export class MemoryEngine {
3315
3320
  if (row.status !== "held")
3316
3321
  continue;
3317
3322
  if (row.resolved === "discard") {
3318
- dispose(row, "discarded", "the host valve resolved this hold as discard");
3323
+ await dispose(row, "discarded", "the host valve resolved this hold as discard");
3319
3324
  continue;
3320
3325
  }
3321
- const marker = this.sessionPollution(row.sessionId);
3326
+ const marker = await this.sessionPollution(row.sessionId);
3322
3327
  const rows = await sessionSettlements(this.governanceStore, row.sessionId);
3323
3328
  if (marker !== undefined || rows.some((r) => r.effective === "external")) {
3324
- dispose(row, "dirty", marker !== undefined ? "the writer session is marked externally exposed" : "a delegation of the writer session settled with an observed external attestation");
3329
+ await dispose(row, "dirty", marker !== undefined ? "the writer session is marked externally exposed" : "a delegation of the writer session settled with an observed external attestation");
3325
3330
  continue;
3326
3331
  }
3327
3332
  if (rows.some((r) => r.effective === "unattestable" || r.effective === "expired")) {
3328
- dispose(row, "expired", "the writer session's delegation window closed UNPROVABLE (a timeout or an unattestable delivery — not a conviction); resolveHold(holdId, \"release\") commits the entry with a \"static\"-cause marker after host review");
3333
+ await dispose(row, "expired", "the writer session's delegation window closed UNPROVABLE (a timeout or an unattestable delivery — not a conviction); resolveHold(holdId, \"release\") commits the entry with a \"static\"-cause marker after host review");
3329
3334
  continue;
3330
3335
  }
3331
3336
  if (rows.some((r) => r.effective === "pending"))
@@ -3337,11 +3342,11 @@ export class MemoryEngine {
3337
3342
  return out;
3338
3343
  }
3339
3344
  async releaseHold(handle, report, row, opts) {
3340
- const disposeOut = (terminal, why) => {
3341
- const d = disposeHold(this.controlDir, { holdId: row.holdId, terminal });
3345
+ const disposeOut = async (terminal, why) => {
3346
+ const d = await disposeHold(this.governanceStore, { holdId: row.holdId, terminal });
3342
3347
  if (!d.ok) {
3343
3348
  try {
3344
- clearHoldResolution(this.controlDir, { holdId: row.holdId, ifResolvedAt: row.resolvedAt });
3349
+ await clearHoldResolution(this.governanceStore, { holdId: row.holdId, ifResolvedAt: row.resolvedAt });
3345
3350
  }
3346
3351
  catch {
3347
3352
  }
@@ -3352,7 +3357,7 @@ export class MemoryEngine {
3352
3357
  opts.disposed.push({ relPath: this.holdPlaneRel(row), terminal });
3353
3358
  return undefined;
3354
3359
  };
3355
- const content = readHoldCustody(this.controlDir, row);
3360
+ const content = await readHoldCustody(this.governanceStore, row);
3356
3361
  if (content === undefined)
3357
3362
  return disposeOut("capture_lost", `the captured bytes are missing or fail their digest (sha256 ${row.contentDigest}; no custody file or quarantine file hashes to it) — nothing verifiable to commit`);
3358
3363
  const findings = [];
@@ -3364,7 +3369,7 @@ export class MemoryEngine {
3364
3369
  return disposeOut("discarded", `the release re-scan refused it (${findings[0].code}: ${findings[0].reason})`);
3365
3370
  if (Buffer.byteLength(content, "utf8") > this.perFileBytes)
3366
3371
  return disposeOut("discarded", `the captured file is over the ${this.perFileBytes}-byte cap`);
3367
- if (this.sessionPollution(row.sessionId) !== undefined)
3372
+ if ((await this.sessionPollution(row.sessionId)) !== undefined)
3368
3373
  return disposeOut("discarded", "the writer session's pollution marker landed before the release could commit");
3369
3374
  const parsed = parseEntryFile(content);
3370
3375
  if (parsed.unclosed === true)
@@ -3436,7 +3441,7 @@ export class MemoryEngine {
3436
3441
  }
3437
3442
  }
3438
3443
  if (alreadyApplied) {
3439
- markHoldReleased(this.controlDir, { holdId: row.holdId, now: this.now });
3444
+ await markHoldReleased(this.governanceStore, { holdId: row.holdId, now: this.now });
3440
3445
  this.warnScoped(report, row.scope, `held instruction entry ${this.holdPlaneRel(row)} was already committed by an earlier release attempt (crash-idempotent retry) — marked released`);
3441
3446
  return this.holdPlaneRel(row);
3442
3447
  }
@@ -3450,7 +3455,7 @@ export class MemoryEngine {
3450
3455
  catch (err) {
3451
3456
  this.warnScoped(report, row.scope, `released hold ${this.holdPlaneRel(row)}: lineage settlement failed after commit — the entry stays latched until a later harvest reconciles: ${thrownText(err)}`);
3452
3457
  }
3453
- markHoldReleased(this.controlDir, { holdId: row.holdId, now: this.now });
3458
+ await markHoldReleased(this.governanceStore, { holdId: row.holdId, now: this.now });
3454
3459
  const landedSlug = patchReport.applied.find((a) => a.id === patch.id)?.slug ?? row.slug;
3455
3460
  const landedRel = landedSlug === row.slug ? row.rel : `${landedSlug}.md`;
3456
3461
  const abs = join(scopeDirFor(this.memoryDir, this.controlDir, row.scope), landedRel);
@@ -3472,8 +3477,8 @@ export class MemoryEngine {
3472
3477
  async resolveSettlement(settleId, to, requestId) {
3473
3478
  await resolveSettlementRecord(this.governanceStore, { settleId, to, requestId, now: this.now });
3474
3479
  }
3475
- resolveHold(holdId, action, requestId) {
3476
- resolveHoldRecord(this.controlDir, { holdId, action, requestId, now: this.now });
3480
+ async resolveHold(holdId, action, requestId) {
3481
+ await resolveHoldRecord(this.governanceStore, { holdId, action, requestId, now: this.now });
3477
3482
  }
3478
3483
  async resolveSessionAccount(sessionId, requestId) {
3479
3484
  await resolveSessionAccountRecord(this.governanceStore, this.controlDir, { sessionId, requestId, now: this.now });
@@ -3481,8 +3486,8 @@ export class MemoryEngine {
3481
3486
  async readDelegationSettlements() {
3482
3487
  return await effectiveSettlements(this.governanceStore);
3483
3488
  }
3484
- readInstructionHolds() {
3485
- return readHolds(this.controlDir);
3489
+ async readInstructionHolds() {
3490
+ return await readHolds(this.governanceStore);
3486
3491
  }
3487
3492
  async readDanglingSessionAccounts(selfSessionId) {
3488
3493
  return await foreignDanglingSessionAccounts(this.governanceStore, this.controlDir, selfSessionId);
@@ -5261,10 +5266,7 @@ export class MemoryEngine {
5261
5266
  fault = true;
5262
5267
  }
5263
5268
  }
5264
- const viaBackend = this.backend.readCommittedShadow?.(id);
5265
- if (viaBackend !== undefined)
5266
- return { content: viaBackend, fault: false };
5267
- const viaShadow = readSafe(join(this.controlDir, "shadow", `${id}.md`));
5269
+ const viaShadow = this.backend.readCommittedShadow?.(id);
5268
5270
  if (viaShadow !== undefined)
5269
5271
  return { content: viaShadow, fault: false };
5270
5272
  return { fault };
@@ -5280,11 +5282,10 @@ export class MemoryEngine {
5280
5282
  catch {
5281
5283
  }
5282
5284
  }
5283
- const viaBackend = this.backend.readCommittedShadow?.(id);
5284
- const text = viaBackend ?? readSafe(join(this.controlDir, "shadow", `${id}.md`));
5285
+ const text = this.backend.readCommittedShadow?.(id);
5285
5286
  return text !== undefined ? parseEntryFile(text).frontmatter : undefined;
5286
5287
  }
5287
- gateDerivedIndex(handle) {
5288
+ async gateDerivedIndex(handle) {
5288
5289
  if (handle.writableRoot === null)
5289
5290
  return undefined;
5290
5291
  const indexPath = join(handle.writableRoot, MEMORY_INDEX_FILENAME);
@@ -5294,30 +5295,15 @@ export class MemoryEngine {
5294
5295
  const finding = scanMemoryWrite(text).find((f) => f.code === "secret");
5295
5296
  if (finding === undefined)
5296
5297
  return undefined;
5297
- let detail = "";
5298
- let captured = false;
5299
- try {
5300
- const dest = join(this.controlDir, QUARANTINE_DIR, `${this.now()}-${MEMORY_INDEX_FILENAME}`);
5301
- ensureDirExists(dirname(dest));
5302
- let landed = false;
5303
- for (let attempt = 0; !landed && attempt < 10; attempt++) {
5304
- const candidate = attempt === 0 ? dest : `${dest}.${attempt}`;
5305
- try {
5306
- writeFileSync(candidate, text, { encoding: "utf8", flag: "wx" });
5307
- landed = true;
5308
- }
5309
- catch (err) {
5310
- if (!(err instanceof Error && "code" in err && err.code === "EEXIST"))
5311
- throw err;
5312
- }
5313
- }
5314
- if (!landed)
5315
- writeFileSync(`${dest}.${process.pid}.${indexCaptureSeq++}`, text, { encoding: "utf8", flag: "wx" });
5316
- captured = true;
5317
- }
5318
- catch (err) {
5319
- detail = `; quarantine capture failed: ${thrownText(err)}`;
5320
- }
5298
+ const kept = await keepCopiesBeforeOverwrite(text, async (bytes) => {
5299
+ const capture = await captureIntoQuarantine(this.governanceStore, indexPath, bytes, this.now);
5300
+ return "name" in capture ? true : capture.failed;
5301
+ }, () => {
5302
+ this.refuseOutsideStore(indexPath, "reading the index again after its copy", handle);
5303
+ return readNoFollowSafe(indexPath);
5304
+ });
5305
+ const captured = kept.landed;
5306
+ let detail = kept.failed.map((f) => `; ${f}`).join("");
5321
5307
  let cleared = false;
5322
5308
  try {
5323
5309
  this.refuseOutsideStore(indexPath, "clearing the index", handle);
@@ -5328,7 +5314,7 @@ export class MemoryEngine {
5328
5314
  detail = `${detail}; the derived index could NOT be cleared: ${this.writeFailureText(err)}`;
5329
5315
  }
5330
5316
  const outcome = [
5331
- captured ? "the offending prose was captured to quarantine" : "the quarantine capture FAILED — the prose was not preserved",
5317
+ captured ? "the offending prose was captured to quarantine" : "the quarantine capture FAILED — prose it did not capture was not preserved",
5332
5318
  cleared ? "the index file was cleared" : "the index file could NOT be cleared, so it still carries the offending content — it is excluded from the injected index and from the rebuild",
5333
5319
  ].join("; ");
5334
5320
  return {
@@ -5353,6 +5339,13 @@ export class MemoryEngine {
5353
5339
  return this.writeFailureText(err);
5354
5340
  }
5355
5341
  }
5342
+ async containSuspect(path, content, act, handle) {
5343
+ const capture = await captureIntoQuarantine(this.governanceStore, path, content, this.now);
5344
+ const refused = this.storeActRefusedText(path, act, handle);
5345
+ if (refused !== undefined)
5346
+ return { ...("name" in capture ? { dest: capture.name } : {}), removed: false, leftOnPlane: content, detail: "failed" in capture ? `${capture.failed}; ${refused}` : refused };
5347
+ return clearContainedPath(path, content, capture);
5348
+ }
5356
5349
  assertRootAnchored(handle) {
5357
5350
  const root = anchorStoreRoot(this.memoryDir, this.controlDir, { onIncident: this.onIncident, now: this.now });
5358
5351
  if (handle !== undefined && handle.memoryDir !== root)