@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
@@ -466,7 +466,9 @@ export async function prepareCardApproval(opts) {
466
466
  ...(opts.toolCallId !== undefined ? { toolCallId: opts.toolCallId } : {}),
467
467
  ...(opts.boundInputHash !== undefined ? { boundInputHash: opts.boundInputHash } : {}),
468
468
  };
469
- await opts.deps.approvals.create(record);
469
+ const created = await storeStep(() => opts.deps.approvals.create(record), RECORD_CREATE);
470
+ if ("refused" in created)
471
+ return created.refused;
470
472
  return {
471
473
  approvalId: record.id,
472
474
  offers: ruleOffersOfRecord(record),
@@ -491,7 +493,10 @@ export async function confirmRuleApproval(opts) {
491
493
  e.code = "config.invalid_argument";
492
494
  throw e;
493
495
  }
494
- const rec = await opts.deps.approvals.get(opts.approvalId);
496
+ const read = await storeStep(() => opts.deps.approvals.get(opts.approvalId), RECORD_READ);
497
+ if ("refused" in read)
498
+ return confirmStoreFailure(read.refused);
499
+ const rec = read.value;
495
500
  const recOwner = rec === undefined ? undefined : ownerOfRecord(rec);
496
501
  if (rec === undefined || recOwner === undefined || !sameRuleOwner(recOwner, caller))
497
502
  return no("record_not_found");
@@ -518,10 +523,15 @@ export async function confirmRuleApproval(opts) {
518
523
  return no("not_pending");
519
524
  if (rec.selectedOffer !== undefined)
520
525
  return no("record_malformed", { message: "a pending record must not already carry a chosen offer" });
521
- const won = await opts.deps.approvals.cas(rec.id, rec.rev, { ...rec, rev: rec.rev + 1, state: "approved", selectedOffer: chosen });
522
- if (won)
526
+ const casted = await storeStep(() => opts.deps.approvals.cas(rec.id, rec.rev, { ...rec, rev: rec.rev + 1, state: "approved", selectedOffer: chosen }), RECORD_CONFIRM_CAS);
527
+ if ("refused" in casted)
528
+ return confirmStoreFailure(casted.refused);
529
+ if (casted.value)
523
530
  return { ok: true };
524
- const again = await opts.deps.approvals.get(rec.id);
531
+ const reread = await storeStep(() => opts.deps.approvals.get(rec.id), RECORD_READ);
532
+ if ("refused" in reread)
533
+ return confirmStoreFailure(reread.refused);
534
+ const again = reread.value;
525
535
  if (again === undefined)
526
536
  return no("record_not_found");
527
537
  if (isStale(again))
@@ -646,9 +656,14 @@ async function confirmEditedCandidate(rec, edit, deps) {
646
656
  selectedOffer: rec.offers.length,
647
657
  edited: { index, text: edit.text, at: nowIso(deps), ...(checked.warnings !== undefined ? { warnings: checked.warnings.map((w) => w.code) } : {}) },
648
658
  };
649
- const won = await deps.approvals.cas(rec.id, rec.rev, next);
650
- if (!won) {
651
- const again = await deps.approvals.get(rec.id);
659
+ const casted = await storeStep(() => deps.approvals.cas(rec.id, rec.rev, next), RECORD_EDIT_CAS);
660
+ if ("refused" in casted)
661
+ return confirmStoreFailure(casted.refused);
662
+ if (!casted.value) {
663
+ const reread = await storeStep(() => deps.approvals.get(rec.id), RECORD_READ);
664
+ if ("refused" in reread)
665
+ return confirmStoreFailure(reread.refused);
666
+ const again = reread.value;
652
667
  if (again === undefined || isStale(again))
653
668
  return no("record_not_found");
654
669
  if (again.state === "pending")
@@ -657,20 +672,29 @@ async function confirmEditedCandidate(rec, edit, deps) {
657
672
  }
658
673
  return { ok: true, mintedCandidate: { index, rule: checked.canonicalRule, ticket: mintRuleTicket(rec.id, index) } };
659
674
  }
675
+ function refusalRetriable(code, committed) {
676
+ return (code === "store_read" || code === "store_write") && committed === "no";
677
+ }
660
678
  function refusal(code, reason, committed = "no") {
661
- return { status: "refused", code, committed, reason };
679
+ return { status: "refused", code, committed, retriable: refusalRetriable(code, committed), reason };
662
680
  }
663
681
  async function storeStep(step, failure) {
664
682
  try {
665
683
  return { value: await step() };
666
684
  }
667
685
  catch (err) {
668
- return { refused: refusal(failure.code, `${failure.what}: ${errText(err)}`, failure.code === "store_write" ? "unknown" : "no") };
686
+ return { refused: refusal(failure.code, `${failure.what}: ${errText(err)}`) };
669
687
  }
670
688
  }
671
689
  const RECORD_READ = { code: "store_read", what: "could not read the approval record" };
672
690
  const RECORD_CAS = { code: "store_write", what: "the approval record store failed the compare-and-set that records this redemption's dot" };
673
691
  const DOT_ALLOCATION = { code: "store_write", what: "the permission-rule store failed to allocate this redemption's dot" };
692
+ const RECORD_CREATE = { code: "store_write", what: "the approval record store failed to create the record" };
693
+ const RECORD_CONFIRM_CAS = { code: "store_write", what: "the approval record store failed the compare-and-set that records this confirmation" };
694
+ const RECORD_EDIT_CAS = { code: "store_write", what: "the approval record store failed the compare-and-set that records this card edit" };
695
+ function confirmStoreFailure(refused) {
696
+ return { ok: false, reason: refused.code, detail: { message: refused.reason } };
697
+ }
674
698
  export async function redeemRuleTicket(opts) {
675
699
  const caller = resolveCallerOwner(opts.principal, opts.owner, "redeemRuleTicket");
676
700
  const parsed = parseRuleTicket(opts.ticket);
@@ -764,12 +788,14 @@ async function tighteningSiblingsStand(rec, offer, index, store, durableSnapshot
764
788
  if (dot === undefined)
765
789
  return false;
766
790
  const view = sibling.scope.kind === "session" ? await effectiveOrThrow(store, { sessionId: sibling.scope.sessionId }) : durableSnapshot;
767
- const live = view.rules.some((r) => r.behavior === sibling.behavior && r.rule === sibling.rule && sameScope(r.scope, sibling.scope) && r.adds.some((a) => a.dot.actor === dot.actor && a.dot.counter === dot.counter));
768
- if (!live)
791
+ if (!redeemedDotLive(view, sibling, dot))
769
792
  return false;
770
793
  }
771
794
  return true;
772
795
  }
796
+ function redeemedDotLive(view, candidate, dot) {
797
+ return view.rules.some((r) => r.behavior === candidate.behavior && sameScope(r.scope, candidate.scope) && r.adds.some((a) => a.dot.actor === dot.actor && a.dot.counter === dot.counter));
798
+ }
773
799
  async function applyRedemption(args) {
774
800
  let store;
775
801
  try {
@@ -810,6 +836,17 @@ async function applyRedemption(args) {
810
836
  });
811
837
  if (!landing.landed)
812
838
  return refusal(landing.code, landing.reason, landing.committed);
839
+ let live = false;
840
+ try {
841
+ const snap = await effectiveOrThrow(store, args.candidate.scope.kind === "session" ? { sessionId: args.candidate.scope.sessionId } : undefined);
842
+ live = redeemedDotLive(snap, args.candidate, args.dot);
843
+ }
844
+ catch (err) {
845
+ return refusal("store_read", `could not read the permission-rule store to confirm this ${args.candidate.behavior} rule stands after its redemption: ${errText(err)}`, "unknown");
846
+ }
847
+ if (!live) {
848
+ return refusal("dot_removed", `this ${args.candidate.behavior} rule's redeemed dot ${args.dot.actor}#${args.dot.counter} is not live in the store (removed since it was redeemed) — a removed rule is not re-landed by replaying its record; a new consent is required`);
849
+ }
813
850
  return { status: "redeemed", behavior: args.parsedRule.behavior, rule: args.parsedRule.rule, scope: args.candidate.scope, dot: args.dot, rev: landing.rev, alreadyRedeemed: args.replay };
814
851
  }
815
852
  function originOfRecordKind(kind) {
@@ -931,7 +968,9 @@ export async function prepareCcImport(opts) {
931
968
  offers: [{ kind: "batch", candidates: candidates.map((_, i) => i) }],
932
969
  createdAt: nowIso(opts.deps),
933
970
  };
934
- await opts.deps.approvals.create(record);
971
+ const created = await storeStep(() => opts.deps.approvals.create(record), RECORD_CREATE);
972
+ if ("refused" in created)
973
+ return created.refused;
935
974
  return { preview, approvalId: record.id };
936
975
  }
937
976
  export const STARTER_RULES = [
@@ -965,7 +1004,9 @@ export async function prepareStarterBatch(opts) {
965
1004
  offers: [{ kind: "batch", candidates: candidates.map((_, i) => i) }],
966
1005
  createdAt: nowIso(opts.deps),
967
1006
  };
968
- await opts.deps.approvals.create(record);
1007
+ const created = await storeStep(() => opts.deps.approvals.create(record), RECORD_CREATE);
1008
+ if ("refused" in created)
1009
+ return created.refused;
969
1010
  return { preview: candidates, approvalId: record.id };
970
1011
  }
971
1012
  export async function redeemRuleBatch(opts) {
@@ -1009,7 +1050,8 @@ export async function redeemRuleBatch(opts) {
1009
1050
  for (const candidateIndex of ordered) {
1010
1051
  const candidate = rec.candidates[candidateIndex];
1011
1052
  const row = { candidateIndex, behavior: candidate.behavior, rule: candidate.rule, scope: candidate.scope };
1012
- if (candidate.behavior === "allow" && tighteningFailed !== undefined) {
1053
+ const tightening = candidate.behavior !== "allow";
1054
+ if (!tightening && tighteningFailed !== undefined) {
1013
1055
  members.push({ ...row, ...refusal("withheld", `withheld: candidate ${tighteningFailed} (a deny/ask member of this batch) did not land, and an allow must not stand wider than the list that was confirmed — redeem the batch again once the store accepts the tightening member`) });
1014
1056
  continue;
1015
1057
  }
@@ -1022,7 +1064,7 @@ export async function redeemRuleBatch(opts) {
1022
1064
  }
1023
1065
  catch (err) {
1024
1066
  members.push({ ...row, ...refusal("store_read", `could not read the permission-rule store: ${errText(err)}`) });
1025
- if (candidate.behavior !== "allow")
1067
+ if (tightening)
1026
1068
  tighteningFailed ??= candidateIndex;
1027
1069
  continue;
1028
1070
  }
@@ -1034,31 +1076,10 @@ export async function redeemRuleBatch(opts) {
1034
1076
  });
1035
1077
  if (res.status === "refused") {
1036
1078
  members.push({ ...row, ...res });
1037
- if (candidate.behavior !== "allow")
1079
+ if (tightening)
1038
1080
  tighteningFailed ??= candidateIndex;
1039
1081
  continue;
1040
1082
  }
1041
- if (candidate.behavior !== "allow") {
1042
- let live = false;
1043
- let unreadable;
1044
- try {
1045
- const snap = await effectiveOrThrow(store, candidate.scope.kind === "session" ? { sessionId: candidate.scope.sessionId } : undefined);
1046
- live = snap.rules.some((r) => r.behavior === candidate.behavior && r.rule === candidate.rule && sameScope(r.scope, candidate.scope) && r.adds.some((a) => a.dot.actor === res.dot.actor && a.dot.counter === res.dot.counter));
1047
- }
1048
- catch (err) {
1049
- unreadable = errText(err);
1050
- }
1051
- if (unreadable !== undefined) {
1052
- members.push({ ...row, ...refusal("store_read", `could not read the permission-rule store to confirm this ${candidate.behavior} member stands after its redemption: ${unreadable}`, "unknown") });
1053
- tighteningFailed ??= candidateIndex;
1054
- continue;
1055
- }
1056
- if (!live) {
1057
- members.push({ ...row, ...refusal("dot_removed", `this ${candidate.behavior} member's redeemed dot ${res.dot.actor}#${res.dot.counter} is not live in the store (removed since it was redeemed) — a removed rule is not re-landed by replaying its record; a new consent is required`) });
1058
- tighteningFailed ??= candidateIndex;
1059
- continue;
1060
- }
1061
- }
1062
1083
  rev = candidate.scope.kind === "session" ? Math.max(rev, res.rev) : res.rev;
1063
1084
  members.push({ ...row, status: alreadyThere ? "deduped" : "persisted", alreadyRedeemed: res.alreadyRedeemed, dot: res.dot });
1064
1085
  }
@@ -619,18 +619,26 @@ export type RemovalLiveness = (typeof REMOVAL_LIVENESS_WORDS)[number];
619
619
  * `"no"` = it has, and nothing does: a face that cannot write at all, a target the type face refuses,
620
620
  * a read that failed before any write, a refused preflight, an epoch seal, a compare-and-set that lost
621
621
  * every attempt. Each of those is the store saying nothing landed, so saying it is a fact. The same word
622
- * covers a write that DID land and that a read which SUCCEEDED then finds removed (a redemption walk's
623
- * `dot_removed`): the add's dot is in the raw state under its tombstone, the rule does not stand, and the
622
+ * covers a write that DID land and that a read which SUCCEEDED then finds removed (a redemption's
623
+ * `dot_removed`, at the single ticket and a batch member alike): the add's dot is in the raw state under its tombstone, the rule does not stand, and the
624
624
  * store has said so — the word is about whether the call's rule stands, never about the history of the
625
625
  * bytes, and a retry of the same ticket re-reads the same tombstone (a new consent is what lands it).
626
- * `"unknown"` = it has not: the apply THREW, which proves nothing either way (a backend can commit and
627
- * then lose its acknowledgement), or the read-back that would have settled it could not be taken. A
628
- * settled absence is never `unknown`: that word would send the caller to reconcile with `list()` for an
629
- * answer the store already gave.
630
- *
631
- * The word exists because the caller's two branches — retry, or reconcile with `list()` — are not
632
- * derivable from the failure PROSE. A consumer reading the strength out of the sentence is parsing a
633
- * message written for a person, and every such reader has to be updated by hand when the sentence is.
626
+ * The same word covers a failure at a step BEFORE the call's rule write is sent — the approval record's
627
+ * read, its creation, the compare-and-set that records the dot (or a confirmation, or a card edit), the
628
+ * dot's allocation: whatever that step's own bytes did (a compare-and-set can commit and lose its
629
+ * acknowledgement), the rule write was never issued, so the call's rule does not stand; a replay of the
630
+ * same ticket reuses the dot the record kept.
631
+ * `"unknown"` = it has not: the rule write WAS issued and the apply threw, which proves nothing either
632
+ * way (a backend can commit and then lose its acknowledgement), or the read-back after it that would have
633
+ * settled it could not be taken. A settled absence is never `unknown`: that word would send the caller to
634
+ * reconcile with `list()` for an answer the store already gave.
635
+ *
636
+ * The word exists because the caller's branch — reconcile with `list()`, or not — is not derivable from
637
+ * the failure PROSE. A consumer reading the strength out of the sentence is parsing a message written for
638
+ * a person, and every such reader has to be updated by hand when the sentence is. `no` does not say that
639
+ * repeating the call would land anything (a refused preflight, a tombstone and an epoch seal are all `no`,
640
+ * and none is cured by a retry): a redemption's refusal answers that second question beside this word, in
641
+ * its own member (`retriable`), derived once from the cause and this word, and never read off `no`.
634
642
  */
635
643
  export declare const RULE_WRITE_COMMITTED_WORDS: readonly ["no", "unknown"];
636
644
  export type RuleWriteCommitted = (typeof RULE_WRITE_COMMITTED_WORDS)[number];
@@ -643,7 +651,9 @@ export type RuleWriteCommitted = (typeof RULE_WRITE_COMMITTED_WORDS)[number];
643
651
  *
644
652
  * It rides beside {@link RuleWriteCommitted}, and the two answer different questions. The code says what stopped the
645
653
  * redemption; `committed` says what may be claimed about the bytes. The same code can carry both words (`store_read`:
646
- * a read before any write says `no`, a read-back after one that could not be taken says `unknown`).
654
+ * a read before the rule write says `no`, a read-back after it that could not be taken says `unknown`; `store_write`: a
655
+ * step before the rule write says `no`, the rule write itself `unknown`), and a consumer that needs to tell two `no`s
656
+ * apart reads the code.
647
657
  *
648
658
  * - `unsupported.layer_root` — an import record's global rule written from `/`, which no stored row can hold
649
659
  * - `ticket_invalid` — the ticket does not name a candidate (unparseable, or an index the record has none at)
@@ -657,11 +667,11 @@ export type RuleWriteCommitted = (typeof RULE_WRITE_COMMITTED_WORDS)[number];
657
667
  * - `store_unavailable` — the owner's store cannot be resolved, or has no write face
658
668
  * - `record_changed` — the record moved under this redemption and the dot it needed is not there
659
669
  * - `withheld` — held back because the batch's deny/ask members do not all stand, and an allow may not stand wider
660
- * - `store_read` — a store read failed: the permission-rule store's, or the approval record's (before the write: `no`; the read-back after it: `unknown`)
661
- * - `store_write` — the write threw, answered unreadably, or was reported landed with no trace of its dot; or the approval record's compare-and-set that records the dot, or the dot's allocation, threw (`unknown`)
670
+ * - `store_read` — a store read failed: the permission-rule store's, or the approval record's (before the rule write: `no`; the read-back after it: `unknown`); the confirmation and card-edit entries answer a failed record read with the same word
671
+ * - `store_write` — the rule write threw, answered unreadably, or was reported landed with no trace of its dot (`unknown`); or a step before it threw — the approval record's compare-and-set that records the dot (or the confirmation, or a card edit), the dot's allocation, or the record's creation at the prepare, import and starter entries (`no`: the rule write was never issued)
662
672
  * - `session_ended` — a session-scope rule whose session has ended; a late redemption cannot revive it
663
673
  * - `occ` — every optimistic-concurrency attempt lost its compare-and-set
664
- * - `dot_removed` — the member's redeemed dot is no longer live in the store (the rule was removed since); its
674
+ * - `dot_removed` — the redeemed dot (a single ticket's or a batch member's) is no longer live in the store (the rule was removed since); its
665
675
  * `committed` is `no`, the store having settled that the rule does not stand ({@link RuleWriteCommitted})
666
676
  */
667
677
  export declare const RULE_REFUSAL_CODES: readonly ["unsupported.layer_root", "ticket_invalid", "record_missing", "wrong_principal", "record_schema_stale", "not_confirmed", "record_malformed", "not_chosen", "parse_rejected", "store_unavailable", "record_changed", "withheld", "store_read", "store_write", "session_ended", "occ", "dot_removed"];
@@ -1,5 +1,4 @@
1
1
  import type { EngineStorageBackend } from "./engine-storage-backend.js";
2
- import type { MemoryStore } from "./memory.js";
3
2
  import type { WorkflowRunStore } from "./workflow-run-store.js";
4
3
  /** A store's retention declaration: `"managed"` = this store's rows are deleted on schedule by the
5
4
  * deployment; `"none"` = nothing deletes them on schedule. Absent ⇒ read fail-closed as `"none"`. */
@@ -89,10 +88,9 @@ export type RetentionCascadeDomain = (typeof RETENTION_CASCADE_DOMAINS)[number];
89
88
  * opt-out record dir and the lineage ledger are governance FACTS about content that exists, not
90
89
  * session data: deleting them makes a one-way privacy record revocable. */
91
90
  export declare const RETENTION_CASCADE_EXEMPT: readonly ["session-pollution", "session-capture-optout", "lineage.json"];
92
- /** The stores {@link RETENTION_CASCADE} covers, by seat name: every store member of {@link EngineStorageBackend}, the memory
93
- * store the bundled file backend carries beside them, and the workflow-run store a deployment constructs itself. */
91
+ /** The stores {@link RETENTION_CASCADE} covers, by seat name: every store member of {@link EngineStorageBackend} and the
92
+ * workflow-run store a deployment constructs itself. */
94
93
  export type RetentionCascadeStores = Omit<EngineStorageBackend, "retention" | "dispose"> & {
95
- readonly memoryStore: MemoryStore;
96
94
  readonly workflowRunStore: WorkflowRunStore;
97
95
  };
98
96
  /** One leg of a store's row: the store method a domain's operation calls on it. */
@@ -241,9 +239,6 @@ export declare const RETENTION_CASCADE: {
241
239
  usageWindowStore: {
242
240
  exempt: string;
243
241
  };
244
- memoryStore: {
245
- exempt: string;
246
- };
247
242
  };
248
243
  /** One session's erasure in order — {@link RETENTION_CASCADE}'s session-tree legs, ascending by step (the one reading of the order). */
249
244
  export declare const RETENTION_SESSION_TREE_STEPS: readonly (RetentionCascadeLeg & {
@@ -51,7 +51,6 @@ export const RETENTION_CASCADE = deepFreeze({
51
51
  ],
52
52
  },
53
53
  usageWindowStore: { exempt: "a usage-governance ledger keyed by principal: token and cost counts, no session content, bounded by the deployment's live window set" },
54
- memoryStore: { exempt: "memory is not session data: entries outlive the session that wrote them, and the governance records about them are RETENTION_CASCADE_EXEMPT" },
55
54
  });
56
55
  export const RETENTION_SESSION_TREE_STEPS = deepFreeze(Object.entries(RETENTION_CASCADE)
57
56
  .flatMap(([store, row]) => ("legs" in row ? row.legs.filter((leg) => leg.domain === "session-trees").map((leg) => ({ store, ...leg })) : []))
@@ -167,10 +167,12 @@ export declare function classifierUnavailableNotice(args: ClassifierUnavailableI
167
167
  runId?: string;
168
168
  }): EngineNotice;
169
169
  /** A classifier station's fork facts, wired once per leg: the route an ask the station hands on takes, and the
170
- * `classifier.unavailable` notice through the one throat. Both stations (the gate, the inherited fold) take it. */
170
+ * `classifier.unavailable` notice through the one throat, under the leg's notice admission when it has one (`admission`).
171
+ * Both stations (the gate, the inherited fold) take it. */
171
172
  export declare function classifierUnavailableSeat(args: ClassifierUnavailableStation & {
172
173
  route: ApprovalRoute;
173
174
  onNotice: RunnerDeps["onNotice"];
175
+ admission?: (notice: EngineNotice) => boolean;
174
176
  sessionId?: string;
175
177
  sourceSessionId?: string;
176
178
  agentId?: string;
@@ -136,8 +136,8 @@ export function classifierUnavailableNotice(args) {
136
136
  };
137
137
  }
138
138
  export function classifierUnavailableSeat(args) {
139
- const { route, onNotice, sessionId, sourceSessionId, agentId, runId, station, budgetMs } = args;
140
- return { route, onUnavailable: (info) => deliverEngineNotice(onNotice, classifierUnavailableNotice({ ...info, station, ...(budgetMs !== undefined ? { budgetMs } : {}), ...(sessionId !== undefined ? { sessionId } : {}), ...(sourceSessionId !== undefined ? { sourceSessionId } : {}), ...(agentId !== undefined ? { agentId } : {}), ...(runId !== undefined ? { runId } : {}) })) };
139
+ const { route, onNotice, admission, sessionId, sourceSessionId, agentId, runId, station, budgetMs } = args;
140
+ return { route, onUnavailable: (info) => deliverEngineNotice(onNotice, classifierUnavailableNotice({ ...info, station, ...(budgetMs !== undefined ? { budgetMs } : {}), ...(sessionId !== undefined ? { sessionId } : {}), ...(sourceSessionId !== undefined ? { sourceSessionId } : {}), ...(agentId !== undefined ? { agentId } : {}), ...(runId !== undefined ? { runId } : {}) }), admission) };
141
141
  }
142
142
  function classifierFallbackAnnouncer(args) {
143
143
  const announced = new Set();
@@ -749,11 +749,11 @@ export interface Prepared {
749
749
  * (they consult it at harvest time themselves — this accessor serves observers/tests).
750
750
  */
751
751
  pollution: {
752
- polluted: () => {
752
+ polluted: () => Promise<{
753
753
  at: number;
754
754
  reason: string;
755
755
  cause?: import("../memory-engine/types.js").MemoryOriginCause;
756
- } | undefined;
756
+ } | undefined>;
757
757
  /** `cause` is the structured mechanical fact the mark records (and the
758
758
  * origin marker minted off it carries): `"observed"` for a witnessed external event,
759
759
  * `"static"` for the capability over-approximation, `"derived"` for recall-taint. Absent
@@ -774,10 +774,9 @@ export interface Prepared {
774
774
  * default): an `"off"` deployment keeps the pre-336 accepted-cost posture byte-level.
775
775
  */
776
776
  settlement?: {
777
- /** The WRITE plane's governance store (the settlement / lineage / challenge documents). */
778
- governance: import("../memory-engine/types.js").MemoryGovernanceDocs;
779
- /** The WRITE plane's control-plane dir (the pollution marker and hold custody files). */
780
- controlDir: string;
777
+ /** The WRITE plane's governance store (the settlement / lineage / challenge documents and the pollution
778
+ * marker a settled delegation's effects reach). */
779
+ governance: import("../memory-engine/types.js").MemoryGovernanceStore;
781
780
  sessionId: string;
782
781
  provenance: "carry";
783
782
  };
@@ -2077,8 +2076,9 @@ export interface RunInternals {
2077
2076
  rootSessionId?: string;
2078
2077
  /** The occupant of {@link rootSessionId}'s row (`SessionMetadata.incarnation`) as the tree's root run acquired it — the
2079
2078
  * other half of the root anchor's ADDRESS, carried beside it by the same fixed point (the spawner passes its own
2080
- * `ctx.rootSessionIncarnation`). Absent = unknown: a revival, a resume or a wake (the row records no root occupant) and a
2081
- * row written before occupants were minted; a frame the notification lane escalates to the root anchor is then addressed
2079
+ * `ctx.rootSessionIncarnation`; a background spawn persists it on its row, `BackgroundAgentRecord.rootSessionIncarnation`, and a
2080
+ * revival reads it back with the anchor). Absent = unknown: a revival of a row that recorded none and a row written before
2081
+ * occupants were minted; a frame the notification lane escalates to the root anchor is then addressed
2082
2082
  * to an unknown occupant, which a root holding a token is not. TRUSTED run-scoped channel (never a TaskSpec field). */
2083
2083
  rootSessionIncarnation?: string;
2084
2084
  /** The delegation tree's owner seat ({@link import("./delegation-owner.js").DelegationOwnerSeat}): a fixed point like
@@ -3009,7 +3009,7 @@ export interface RunnerSelfSeat {
3009
3009
  */
3010
3010
  export type PrepareTaskFn = (spec: TaskSpec, deps: RunnerDeps, sessions: SessionStore, resume?: PrepareResume, internals?: RunInternals, runnerSelf?: RunnerSelfSeat, runIdSink?: {
3011
3011
  runId?: string;
3012
- }, holdSessionLock?: (sessionId: string) => Promise<void>, legWrites?: LegWrites) => Promise<Prepared>;
3012
+ }, holdSessionLock?: (sessionId: string) => Promise<void>, legWrites?: LegWrites, noticeDestinations?: import("../task-notification.js").NoticeDestinationJudge) => Promise<Prepared>;
3013
3013
  /** One leg's view of the Runner's session write ledger (`session-write-ledger.ts`): `issue` starts a write of the leg (`what` = the
3014
3014
  * entry type, for a report) or refuses it once `close` ran — the leg's hold ended; a write still in flight is reported when it settles. */
3015
3015
  export interface LegWrites {
@@ -22,14 +22,6 @@ export type DelegationOwnerReading = {
22
22
  export interface DelegationOwnerSeat {
23
23
  read(): Promise<DelegationOwnerReading>;
24
24
  }
25
- /**
26
- * Whether two readings of one session id's occupant cell (`SessionMetadata.incarnation`, `undefined` = no token) name the occupant a
27
- * run holds: the same token, or no token on either side (a row written before occupants were minted, taken as it reads — a row
28
- * created again under the id is minted a token, so it never reads as the one before it). A token on one side only is another
29
- * occupant. The one reading of this question for a run's own seats: the tree owner below and the session address a frame is
30
- * delivered to (`task-notification.ts`).
31
- */
32
- export declare function sameOccupant(held: string | undefined, current: string | undefined): boolean;
33
25
  /**
34
26
  * The seat of a run nobody spawned: the owner of the row it acquired, read by id through its own store's {@link SessionStore.headOf}
35
27
  * and taken only while the row's occupant is the one acquired ({@link sameOccupant} of the head's `incarnation` and the acquired
@@ -1,12 +1,10 @@
1
+ import { sameOccupant } from "../../engine/session/repo-utils.js";
1
2
  function ownerCellReading(sessionId, head) {
2
3
  const owner = head.owner;
3
4
  if (owner === null || typeof owner === "string")
4
5
  return { bound: true, owner };
5
6
  return { bound: false, reason: `the session ${sessionId}'s row answers an owner that is neither a name nor anonymous (${owner === undefined ? "none" : typeof owner})` };
6
7
  }
7
- export function sameOccupant(held, current) {
8
- return held === current;
9
- }
10
8
  export function ownRowDelegationOwner(sessions, sessionId, acquiredIncarnation) {
11
9
  let settled;
12
10
  let inFlight;
@@ -35,7 +35,8 @@ import { type HookEnvCapabilities, type HookInvocationIdentity } from "../hooks.
35
35
  import type { ToolPolicy } from "../tool-policy.js";
36
36
  import { type GateOutcome } from "../gate-outcome.js";
37
37
  import type { RunnerDeps, TaskSpec } from "../types.js";
38
- import type { NoticeAddress } from "../leg-identity.js";
38
+ import type { NoticeRoute } from "../leg-identity.js";
39
+ import type { NoticeDestinationJudge } from "../task-notification.js";
39
40
  import { type WiringManifest } from "../wiring-manifest.js";
40
41
  import type { WriteProtectionCheck } from "../write-protect.js";
41
42
  import type { ShellReadCheck } from "../../tools/fs/shell-read-check.js";
@@ -153,10 +154,12 @@ export interface PrepareGateStationsInput {
153
154
  hostTaskId: string;
154
155
  /** borrowed-readonly — the acquired session id (the settlement defects' error tag). */
155
156
  sessionId: string;
156
- /** borrowed-readonly — where this station's user-face notices are addressed (`noticeAddressOf`, minted once per leg beside the
157
- * ask source): the leg's own session on a top-level leg; the delegation tree's root, naming this leg, on a delegated one —
158
- * every notice below spreads it in place of the bare session id. */
159
- noticeAddress: NoticeAddress;
157
+ /** borrowed-readonly — where this station's user-face notices go (`noticeAddressOf`, minted once per leg beside the ask
158
+ * source): the leg's own session on a top-level leg; the delegation tree's root, naming this leg, on a delegated one — every
159
+ * notice below spreads its `address` in place of the bare session id, and is delivered under {@link legNoticeAdmission}. */
160
+ noticeRoute: NoticeRoute;
161
+ /** borrowed-readonly — the Runner's judge of a notice routed to the tree's root (absent outside a Runner). */
162
+ noticeDestinations: NoticeDestinationJudge | undefined;
160
163
  /** borrowed-readonly — the hand's live tracked cwd, or undefined; `current` is read per screening / per post seat. Not
161
164
  * written here. */
162
165
  handsCwdRef: CwdRef | undefined;
@@ -49,8 +49,16 @@ export function maybeHumanRejectionHalt(input) {
49
49
  },
50
50
  };
51
51
  }
52
+ function legNoticeAdmission(route, judge) {
53
+ const { address, destination } = route;
54
+ if (destination === undefined || judge === undefined)
55
+ return undefined;
56
+ return (notice) => judge(destination, { taskId: address.agentId ?? address.sourceSessionId ?? address.sessionId, taskType: notice.code }) !== true;
57
+ }
52
58
  export function prepareGateStations(input) {
53
- const { askLane, parkAsk, tools, toolRosterDeltas, deps, toolCallGateArmedRef, effectivePolicy, egressTools, irreversibleTools, spec, complianceDenies, harness, blockedToolCalls, inheritedAskGrants, inheritedUnavailableAsks, foldAskClasses, ancestorSandboxAdmissions, preToolContexts, toolOccurrences, batchHaltRef, blockedTracked, hookIdentity, reminderMark, hostTaskId, sessionId, noticeAddress, handsCwdRef, stampCallTarget, hookEnvFace, writeProtectionCheck, shellReadCheck, crossBoundaryCheck, readFace, irreversibilityTier, reversibilityProbes, abortController, shellGatedTools, autoModeDecider, autoModeDenialTracking, askRoute, permissionMode, toolMarkSources, a2aIsolatePeers, ancestorArbitrations, runId, stopForDenialLimit, permissionRuleLane, permissionRuleOrgLane, questionToolMounted, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, delegation, frameSettlement, seatInputsFor, modBus, inheritedInstallations } = input;
59
+ const { askLane, parkAsk, tools, toolRosterDeltas, deps, toolCallGateArmedRef, effectivePolicy, egressTools, irreversibleTools, spec, complianceDenies, harness, blockedToolCalls, inheritedAskGrants, inheritedUnavailableAsks, foldAskClasses, ancestorSandboxAdmissions, preToolContexts, toolOccurrences, batchHaltRef, blockedTracked, hookIdentity, reminderMark, hostTaskId, sessionId, noticeRoute, noticeDestinations, handsCwdRef, stampCallTarget, hookEnvFace, writeProtectionCheck, shellReadCheck, crossBoundaryCheck, readFace, irreversibilityTier, reversibilityProbes, abortController, shellGatedTools, autoModeDecider, autoModeDenialTracking, askRoute, permissionMode, toolMarkSources, a2aIsolatePeers, ancestorArbitrations, runId, stopForDenialLimit, permissionRuleLane, permissionRuleOrgLane, questionToolMounted, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, delegation, frameSettlement, seatInputsFor, modBus, inheritedInstallations } = input;
60
+ const noticeAddress = noticeRoute.address;
61
+ const admitsLegNotice = legNoticeAdmission(noticeRoute, noticeDestinations);
54
62
  const releasesAnnounced = new Map();
55
63
  const onModeReleased = (info) => {
56
64
  const table = info.readUnestablished === true ? input.readDenyInForce(info.toolCallId) : undefined;
@@ -60,7 +68,7 @@ export function prepareGateStations(input) {
60
68
  code: "permission.read_deny_unapplied",
61
69
  message: `the ${info.release.mode} permission mode released "${info.toolName}" although a read-deny table is in force (${named}): the read boundary could not establish what this command reads, so no row of the table was applied to it`,
62
70
  detail: { mode: info.release.mode, toolCallId: info.toolCallId, tiers: [...table.tiers], rows: table.rows.slice(0, 8), rowCount: table.rows.length, ...noticeAddress, runId },
63
- });
71
+ }, admitsLegNotice);
64
72
  }
65
73
  const key = `${info.release.mode}\u0000${info.release.askClass}`;
66
74
  const count = (releasesAnnounced.get(key) ?? 0) + 1;
@@ -71,7 +79,7 @@ export function prepareGateStations(input) {
71
79
  code: "permission.ask_released_by_mode",
72
80
  message: `the ${info.release.mode} permission mode released a ${info.release.askClass} ask on "${info.toolName}" without putting it to anyone (further releases of this pair in this run ride each call's tool_end.gate.disposition.released)`,
73
81
  detail: { mode: info.release.mode, askClass: info.release.askClass, ...(info.release.origin !== undefined ? { origin: info.release.origin } : {}), ...(info.release.mandate !== undefined ? { mandate: info.release.mandate } : {}), count, firstToolCallId: info.toolCallId, ...noticeAddress, runId },
74
- });
82
+ }, admitsLegNotice);
75
83
  };
76
84
  if (askLane !== undefined && parkAsk !== undefined) {
77
85
  const { adjudicate, resolveAskBound, notifyPermissionDenied, notifyHookError } = askLane;
@@ -140,7 +148,7 @@ export function prepareGateStations(input) {
140
148
  abortSignal: abortController.signal,
141
149
  onHookError: notifyHookError,
142
150
  shellGated: tierSeat?.shellGated(shellGatedTools, toolMarkSources) === true,
143
- ...(autoModeDecider.current !== undefined ? { autoMode: { decider: autoModeDecider.current, ...(autoModeDenialTracking.current !== undefined ? { denialTracking: autoModeDenialTracking.current } : {}), unavailable: classifierUnavailableSeat({ station: "leg", ...(autoModeDecider.current.timeoutMs !== undefined ? { budgetMs: autoModeDecider.current.timeoutMs } : {}), route: approvalRouteOf(askRoute), onNotice: deps.onNotice, ...noticeAddress, runId }) } } : {}),
151
+ ...(autoModeDecider.current !== undefined ? { autoMode: { decider: autoModeDecider.current, ...(autoModeDenialTracking.current !== undefined ? { denialTracking: autoModeDenialTracking.current } : {}), unavailable: classifierUnavailableSeat({ station: "leg", ...(autoModeDecider.current.timeoutMs !== undefined ? { budgetMs: autoModeDecider.current.timeoutMs } : {}), route: approvalRouteOf(askRoute), onNotice: deps.onNotice, admission: admitsLegNotice, ...noticeAddress, runId }) } } : {}),
144
152
  permissionMode: () => permissionMode.current, askSeatForm: askRoute.form,
145
153
  ...(markSources.size > 0 ? { toolMarkSources: markSources } : {}),
146
154
  ...seatInputsFor(e.toolName, wireOf("gate.skillActivationSeat", call)),
@@ -149,7 +157,7 @@ export function prepareGateStations(input) {
149
157
  onModeReleased,
150
158
  ancestorArbitrationOf: (toolCallId) => ancestorArbitrations.get(toolCallId),
151
159
  onHeadlessDenialLimit: stopForDenialLimit,
152
- onAskUnresolvable: (info) => deliverEngineNotice(deps.onNotice, askUnresolvableNotice({ ...noticeAddress, ...info })),
160
+ onAskUnresolvable: (info) => deliverEngineNotice(deps.onNotice, askUnresolvableNotice({ ...noticeAddress, ...info }), admitsLegNotice),
153
161
  ...(permissionRuleLane
154
162
  ? {
155
163
  persistedRules: {
@@ -30,7 +30,7 @@ export function prepareMemoryEngineSession(input) {
30
30
  onNotice: deps.onNotice,
31
31
  });
32
32
  if (memoryEngineSession?.settlement !== undefined) {
33
- delegationSettlementRef.current = { governance: memoryEngineSession.settlement.governance, controlDir: memoryEngineSession.settlement.controlDir, sessionId: memoryEngineSession.settlement.sessionId };
33
+ delegationSettlementRef.current = { governance: memoryEngineSession.settlement.governance, sessionId: memoryEngineSession.settlement.sessionId };
34
34
  }
35
35
  const recordExternal = () => {
36
36
  if (delegationProvenanceChannel !== undefined)
@@ -277,8 +277,8 @@ export async function prepareMemory(input) {
277
277
  ...planeScopes(planes.personal, planes.writePlane === "personal" ? memorySpec.writeScope : null),
278
278
  ]
279
279
  : planeScopes(memorySpec.scopes, memorySpec.writeScope)).map((scope) => ({ scope, origin: originOf(scope) }));
280
- const pollutedOpts = (engine) => {
281
- const rec = engine.sessionPollution(sessionId);
280
+ const pollutedOpts = async (engine) => {
281
+ const rec = await engine.sessionPollution(sessionId);
282
282
  return rec !== undefined ? { polluted: { reason: rec.reason, ...(rec.cause !== undefined ? { cause: rec.cause } : {}) } } : {};
283
283
  };
284
284
  let writeEngine;
@@ -421,7 +421,7 @@ export async function prepareMemory(input) {
421
421
  harvestBoth = async (phase) => {
422
422
  const writeFirst = writeIsPersonal ? [personalEngine, personalHandle] : [projectEngine, projectHandle];
423
423
  const readOther = writeIsPersonal ? [projectEngine, projectHandle] : [personalEngine, personalHandle];
424
- const writeReport = await writeFirst[0].harvest(writeFirst[1], { ...pollutedOpts(writeFirst[0]), sessionId, ...(await admitNothingOptsNow()), phase });
424
+ const writeReport = await writeFirst[0].harvest(writeFirst[1], { ...(await pollutedOpts(writeFirst[0])), sessionId, ...(await admitNothingOptsNow()), phase });
425
425
  let readReport;
426
426
  let readFailure;
427
427
  try {
@@ -447,7 +447,7 @@ export async function prepareMemory(input) {
447
447
  writeEngine = personalEngine;
448
448
  writeHandle = handle;
449
449
  injectFn = () => personalEngine.inject(handle, { writeToolMounted: writeChannelOpen, reminderMark: input.reminderMark });
450
- harvestBoth = async (phase) => personalEngine.harvest(handle, { ...pollutedOpts(personalEngine), sessionId, ...(await admitNothingOptsNow()), phase });
450
+ harvestBoth = async (phase) => personalEngine.harvest(handle, { ...(await pollutedOpts(personalEngine)), sessionId, ...(await admitNothingOptsNow()), phase });
451
451
  toolPlanes = [
452
452
  {
453
453
  backend: retrievalBackend(personal.backend, adoptionRestricted || captureOptedOut || captureIndeterminate || memorySpec.writeScope === null),
@@ -477,7 +477,7 @@ export async function prepareMemory(input) {
477
477
  writeEngine = engine;
478
478
  writeHandle = handle;
479
479
  injectFn = () => engine.inject(handle, { writeToolMounted: writeChannelOpen, reminderMark: input.reminderMark });
480
- harvestBoth = async (phase) => engine.harvest(handle, { ...pollutedOpts(engine), sessionId, ...(await admitNothingOptsNow()), phase });
480
+ harvestBoth = async (phase) => engine.harvest(handle, { ...(await pollutedOpts(engine)), sessionId, ...(await admitNothingOptsNow()), phase });
481
481
  toolPlanes = [
482
482
  {
483
483
  backend: retrievalBackend(backend, adoptionRestricted || captureOptedOut || captureIndeterminate || memorySpec.writeScope === null),
@@ -546,13 +546,13 @@ export async function prepareMemory(input) {
546
546
  return writeEngine.gateWrite(writeHandle, w.key, w.content);
547
547
  };
548
548
  let pollutionAnnounced = false;
549
- const announceHarvestContainment = (report) => {
549
+ const announceHarvestContainment = async (report) => {
550
550
  const { count, moved, escalated } = pollutionContainmentCounts(report);
551
551
  const indexOnly = input.memoryProvenance !== "off" && count === 0 && report.containment?.indexRolledBack === true;
552
552
  if (count > 0 || indexOnly) {
553
553
  let reason;
554
554
  try {
555
- reason = writeEngine.sessionPollution(sessionId)?.reason;
555
+ reason = (await writeEngine.sessionPollution(sessionId))?.reason;
556
556
  }
557
557
  catch {
558
558
  }
@@ -580,7 +580,7 @@ export async function prepareMemory(input) {
580
580
  const named = report.reportId !== undefined ? `${report.incident.kind}, report ${report.reportId}` : report.incident.kind;
581
581
  deps.onError?.(new Error(`memory harvest refused (${named}): ${report.incident.detail}`), { phase: "memory", sessionId });
582
582
  }
583
- announceHarvestContainment(report);
583
+ await announceHarvestContainment(report);
584
584
  try {
585
585
  deps.onMemoryHarvestReport?.(report, { sessionId, phase });
586
586
  }
@@ -698,7 +698,7 @@ export async function prepareMemory(input) {
698
698
  execIsExternalContent: memorySpec.execIsExternalContent === true,
699
699
  },
700
700
  ...(input.memoryProvenance !== "off"
701
- ? { settlement: { governance: writeEngine.governance, controlDir: writeEngine.controlPlaneRoot, sessionId, provenance: "carry" } }
701
+ ? { settlement: { governance: writeEngine.governance, sessionId, provenance: "carry" } }
702
702
  : {}),
703
703
  ...(input.memoryProvenance !== "off"
704
704
  ? {