@sema-agent/core 7.63.0 → 7.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +408 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent.js +20 -3
  23. package/dist/core/allow-entry.d.ts +4 -0
  24. package/dist/core/ask-origin.d.ts +1 -1
  25. package/dist/core/ask-origin.js +2 -2
  26. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  27. package/dist/core/ask-unresolvable-notice.js +10 -3
  28. package/dist/core/auto-compaction.d.ts +7 -5
  29. package/dist/core/background-agent-store.d.ts +7 -0
  30. package/dist/core/background-agent-store.js +3 -0
  31. package/dist/core/checkpoint-queries.d.ts +9 -6
  32. package/dist/core/checkpoint-queries.js +8 -3
  33. package/dist/core/checkpoint-store.d.ts +5 -1
  34. package/dist/core/context-settings.d.ts +40 -9
  35. package/dist/core/context-settings.js +32 -10
  36. package/dist/core/engine-attestation.d.ts +26 -6
  37. package/dist/core/engine-attestation.js +5 -1
  38. package/dist/core/engine-notice.d.ts +24 -1
  39. package/dist/core/extension-requester.d.ts +9 -0
  40. package/dist/core/extension-requester.js +7 -0
  41. package/dist/core/file-history-store.d.ts +28 -0
  42. package/dist/core/file-history-store.js +48 -5
  43. package/dist/core/fs-write-gate-policy.js +1 -1
  44. package/dist/core/gate-fold.js +2 -0
  45. package/dist/core/gate-lanes.js +2 -0
  46. package/dist/core/gate-outcome.d.ts +39 -2
  47. package/dist/core/gate-outcome.js +20 -1
  48. package/dist/core/governance-codes.d.ts +3 -1
  49. package/dist/core/governance-codes.js +4 -0
  50. package/dist/core/leg-identity.d.ts +19 -1
  51. package/dist/core/leg-identity.js +12 -0
  52. package/dist/core/mailbox-store.d.ts +39 -4
  53. package/dist/core/mailbox-store.js +14 -2
  54. package/dist/core/memory-engine/consolidation.d.ts +3 -2
  55. package/dist/core/memory-engine/consolidation.js +16 -0
  56. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  57. package/dist/core/memory-engine/control-objects.js +151 -0
  58. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  59. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  60. package/dist/core/memory-engine/delegation-settlement.d.ts +21 -5
  61. package/dist/core/memory-engine/delegation-settlement.js +217 -26
  62. package/dist/core/memory-engine/dual-root.js +2 -2
  63. package/dist/core/memory-engine/engine.d.ts +38 -23
  64. package/dist/core/memory-engine/engine.js +14 -14
  65. package/dist/core/memory-engine/file-backend.d.ts +41 -65
  66. package/dist/core/memory-engine/file-backend.js +59 -166
  67. package/dist/core/memory-engine/index.d.ts +3 -2
  68. package/dist/core/memory-engine/index.js +2 -1
  69. package/dist/core/memory-engine/layout.d.ts +6 -1
  70. package/dist/core/memory-engine/layout.js +12 -7
  71. package/dist/core/memory-engine/memory-backend-contract.d.ts +10 -3
  72. package/dist/core/memory-engine/memory-backend-contract.js +158 -2
  73. package/dist/core/memory-engine/memory-deployment.d.ts +11 -3
  74. package/dist/core/memory-engine/memory-deployment.js +31 -6
  75. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  76. package/dist/core/memory-engine/origin-clearance.js +68 -9
  77. package/dist/core/memory-engine/session-write-home.d.ts +34 -1
  78. package/dist/core/memory-engine/session-write-home.js +37 -10
  79. package/dist/core/memory-engine/types.d.ts +44 -7
  80. package/dist/core/memory-engine/types.js +2 -1
  81. package/dist/core/mode-policy.js +3 -3
  82. package/dist/core/mods/agent-stations.d.ts +18 -0
  83. package/dist/core/mods/agent-stations.js +8 -6
  84. package/dist/core/mods/extension-call.d.ts +4 -0
  85. package/dist/core/mods/extension-call.js +8 -0
  86. package/dist/core/mods/tool-call.js +3 -4
  87. package/dist/core/parent-spec-seat.d.ts +2 -2
  88. package/dist/core/peer-channel.d.ts +5 -0
  89. package/dist/core/permission-rule-consent.d.ts +21 -10
  90. package/dist/core/permission-rule-consent.js +50 -23
  91. package/dist/core/permission-rule-store.d.ts +41 -16
  92. package/dist/core/permission-rule-store.js +2 -0
  93. package/dist/core/refusal-echo.d.ts +20 -0
  94. package/dist/core/refusal-echo.js +33 -0
  95. package/dist/core/retention.d.ts +180 -10
  96. package/dist/core/retention.js +45 -0
  97. package/dist/core/retired-keys.d.ts +5 -0
  98. package/dist/core/retired-keys.js +3 -0
  99. package/dist/core/rule-offer-read.d.ts +0 -4
  100. package/dist/core/rule-offer-read.js +2 -18
  101. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  102. package/dist/core/runner/classifier-ladder.js +4 -2
  103. package/dist/core/runner/compact-session.js +10 -7
  104. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  105. package/dist/core/runner/compaction-call-options.js +3 -2
  106. package/dist/core/runner/contracts.d.ts +21 -2
  107. package/dist/core/runner/delegation-owner.d.ts +10 -3
  108. package/dist/core/runner/delegation-owner.js +4 -1
  109. package/dist/core/runner/gate-exit.d.ts +6 -0
  110. package/dist/core/runner/gate-exit.js +11 -2
  111. package/dist/core/runner/memory-consolidation-driver.d.ts +4 -2
  112. package/dist/core/runner/memory-consolidation-driver.js +8 -5
  113. package/dist/core/runner/prepare-ask-lane.js +3 -3
  114. package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -1
  115. package/dist/core/runner/prepare-caps-and-workflow.js +2 -2
  116. package/dist/core/runner/prepare-config-doors.js +4 -0
  117. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  118. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  119. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  120. package/dist/core/runner/prepare-gate-stations.js +5 -5
  121. package/dist/core/runner/prepare-hands-readface.js +1 -1
  122. package/dist/core/runner/prepare-inherited-gate.d.ts +3 -1
  123. package/dist/core/runner/prepare-inherited-gate.js +4 -2
  124. package/dist/core/runner/prepare-memory.d.ts +4 -0
  125. package/dist/core/runner/prepare-memory.js +14 -20
  126. package/dist/core/runner/prepare-policy-chain.js +7 -7
  127. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  128. package/dist/core/runner/prepare-task.js +15 -10
  129. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  130. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  131. package/dist/core/runner/resume-admission.d.ts +2 -2
  132. package/dist/core/runner/resume-admission.js +2 -23
  133. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  134. package/dist/core/runner/role-resolution-table.js +62 -0
  135. package/dist/core/runner/run-compaction-machinery.js +2 -2
  136. package/dist/core/runner/run-identity-wiring.js +12 -9
  137. package/dist/core/runner/run-leg.js +8 -4
  138. package/dist/core/runner/run-notification-lane.js +22 -22
  139. package/dist/core/runner/run-recovery-lanes.js +3 -3
  140. package/dist/core/runner/run-terminal-adoption.js +1 -1
  141. package/dist/core/runner/run-turn-boundary.js +14 -15
  142. package/dist/core/runner/runtask.js +1 -1
  143. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  144. package/dist/core/runner/tool-occurrence.js +2 -2
  145. package/dist/core/runner-deps.d.ts +1 -1
  146. package/dist/core/session-checkout.d.ts +63 -3
  147. package/dist/core/session-checkout.js +152 -58
  148. package/dist/core/shell-read-silence.js +8 -0
  149. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  150. package/dist/core/task-event.d.ts +9 -5
  151. package/dist/core/task-notification.d.ts +110 -31
  152. package/dist/core/task-notification.js +180 -100
  153. package/dist/core/task-registry-agent.d.ts +11 -0
  154. package/dist/core/task-registry-agent.js +11 -3
  155. package/dist/core/task-registry-shared.d.ts +7 -0
  156. package/dist/core/task-registry.d.ts +18 -0
  157. package/dist/core/task-registry.js +27 -8
  158. package/dist/core/task-spec.d.ts +7 -2
  159. package/dist/core/tool-errors.d.ts +14 -6
  160. package/dist/core/tool-errors.js +1 -1
  161. package/dist/core/tool-policy.d.ts +18 -1
  162. package/dist/core/tool-policy.js +16 -7
  163. package/dist/core/tool-result-store.d.ts +20 -0
  164. package/dist/core/tool-spec.d.ts +4 -0
  165. package/dist/core/trace.d.ts +3 -2
  166. package/dist/core/workflow-journal-store.d.ts +11 -0
  167. package/dist/core/workflow-journal-store.js +7 -0
  168. package/dist/core/workflow-run-store.d.ts +9 -0
  169. package/dist/core/workflow-run-store.js +6 -0
  170. package/dist/engine/compaction/compaction.d.ts +2 -1
  171. package/dist/engine/harness/types.d.ts +1 -0
  172. package/dist/engine/session/session.d.ts +7 -1
  173. package/dist/engine/session/session.js +5 -2
  174. package/dist/index.d.ts +7 -5
  175. package/dist/index.js +7 -5
  176. package/dist/orchestration/run-workflow-tool.d.ts +4 -0
  177. package/dist/orchestration/run-workflow-tool.js +7 -0
  178. package/dist/orchestration/workflow-types.d.ts +2 -1
  179. package/dist/orchestration/workflow.d.ts +3 -0
  180. package/dist/orchestration/workflow.js +2 -1
  181. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  182. package/dist/stores/file/checkpoint-store.js +4 -1
  183. package/dist/stores/file/file-history-store.d.ts +13 -0
  184. package/dist/stores/file/file-history-store.js +75 -13
  185. package/dist/stores/file/index.d.ts +11 -1
  186. package/dist/stores/file/index.js +7 -11
  187. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  188. package/dist/stores/file/permission-rule-store.js +75 -7
  189. package/dist/stores/file/tool-result-store.d.ts +14 -0
  190. package/dist/stores/file/tool-result-store.js +39 -2
  191. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  192. package/dist/stores/file/workflow-journal-store.js +17 -0
  193. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  194. package/dist/stores/file/workflow-run-store.js +15 -0
  195. package/dist/tools/fs/read-deny.d.ts +15 -2
  196. package/dist/tools/fs/read-deny.js +10 -2
  197. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  198. package/dist/tools/fs/shell-read-check.js +7 -7
  199. package/package.json +2 -2
  200. package/test/export-surface.snapshot.json +63 -1
  201. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  202. package/wire-changes/core@7.64.0.json +2653 -0
  203. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  204. package/wire-changes/primitives@7.64.0.json +30 -0
@@ -839,6 +839,8 @@ export async function runGateLanes(pass) {
839
839
  pass.deniedBy = "read_boundary";
840
840
  if (reading.verdict.details !== undefined)
841
841
  pass.denyDetails = reading.verdict.details;
842
+ if (reading.verdict.echoed !== undefined)
843
+ pass.denyEchoed = reading.verdict.echoed;
842
844
  }
843
845
  }
844
846
  }
@@ -11,6 +11,7 @@ import { type AskClass, type AskOrigin, type AssertAllKeysHandled, type ModeRele
11
11
  import { type AutoModeClassifierRound, type AutoModeFallbackCause } from "./auto-mode.js";
12
12
  import { type AllowRuleClearance } from "./allow-rule-shadow.js";
13
13
  import type { ResolvedOutcome } from "./checkpoint-store.js";
14
+ import { type RefusalEcho } from "./refusal-echo.js";
14
15
  /**
15
16
  * How the wait an ask was in ENDED — the closed set. One word per way a wait can end; the `who` on the
16
17
  * record says which party ended it and is fixed BY the word (see {@link Settlement}).
@@ -402,6 +403,24 @@ export declare const DENIED_BY_MAY_NAME_EXTENSION: {
402
403
  };
403
404
  /** Compile-time fence: `never` while every deny layer has an extension-naming row. */
404
405
  export type ExtensionTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<DeniedBy, keyof typeof DENIED_BY_MAY_NAME_EXTENSION>>;
406
+ /** Which deny layers may carry the literals their refusal sentence quotes ({@link GateDisposition}'s `echoed`): the read station,
407
+ * whose deny sentence is minted with them from one finding; an ask's resolution, whose refusal sentence quotes the question the
408
+ * engine composed with its literals. The mint reads it as the producer and the screen (invariant I13) as the archive: one table,
409
+ * two readers. Module-level only; not part of the package root. */
410
+ export declare const DENIED_BY_MAY_ECHO: {
411
+ readonly policy: false;
412
+ readonly hook: false;
413
+ readonly org: false;
414
+ readonly persisted_rule: false;
415
+ readonly classifier: false;
416
+ readonly compliance: false;
417
+ readonly write_protection: false;
418
+ readonly ask_resolution: true;
419
+ readonly read_boundary: true;
420
+ readonly mode: false;
421
+ };
422
+ /** Compile-time fence: `never` while every deny layer has an echo row. */
423
+ export type EchoTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<DeniedBy, keyof typeof DENIED_BY_MAY_ECHO>>;
405
424
  /** The final disposition of a gate pass. `cause` is present exactly when the deny came out of an auto-mode
406
425
  * classifier round that did not RULE ({@link ClassifierDenyCause}); a ruling block and every non-classifier
407
426
  * deny carry none. Invariant I5 ({@link screenGateOutcome}): a cause stands only beside a layer word in
@@ -436,7 +455,21 @@ export type ExtensionTableCoversEveryDeniedBy = AssertAllKeysHandled<Exclude<Den
436
455
  * refusing handler's registration is known; ABSENT beside every other layer word (an ancestor leg's screening reaches a
437
456
  * descendant as a `policy` refusal, and a refusal an inherited installation's question settled is that question's), and beside
438
457
  * a `hook` refusal that names no registration (the engine's own failed raise, a cancel). A display and audit fact: the call is
439
- * refused whatever the name. Additive. Invariant I12 ({@link screenGateOutcome}) screens its shape. */
458
+ * refused whatever the name. Additive. Invariant I12 ({@link screenGateOutcome}) screens its shape.
459
+ *
460
+ * `echoed` — on the denied arm only: the literals the refusal's sentence quotes — the path (with its canonical target where the
461
+ * sentence names one), the view of it the deny row actually matched when that is another spelling, and the pattern — in the order
462
+ * the sentence quotes them, each whole (the sentence elides the middle of a long one, this list never does). Minted with the
463
+ * sentence from one finding, so a consumer reads WHICH path, command or pattern was refused from here and never by taking the
464
+ * sentence apart. Present when `deniedBy` is `read_boundary` and the refusal is a deny-row hit, and when `deniedBy` is
465
+ * `ask_resolution` and the refusal quotes a question the engine composed with its literals (a write gate's or the plan mode's
466
+ * generic question about a path: the list then holds that path as the call spells it — not a canonical one) while the refusal's
467
+ * sentence is still the one the resolver composed ({@link DENIED_BY_MAY_ECHO}). ABSENT beside every other layer word, on a
468
+ * read-boundary refusal that quotes no deny row (a containment or identity finding), and on a resolution refusal whose question
469
+ * was anyone else's words or was rewritten or appended to on the way (a hook's, a persisted rule's, a card's added sentence): the
470
+ * sentence is then the whole account, and a consumer that finds the member absent reads it as it always did — what was asked is
471
+ * the call's own arguments. The member's presence says nothing about the layer: read the layer off `deniedBy`. Additive.
472
+ * Invariant I13 ({@link screenGateOutcome}) screens its shape. */
440
473
  export type GateDisposition = {
441
474
  kind: "allowed";
442
475
  classifier?: AutoModeClassifierRound;
@@ -451,6 +484,7 @@ export type GateDisposition = {
451
484
  askClass?: AskClass;
452
485
  classes?: readonly AskClass[];
453
486
  extension?: string;
487
+ echoed?: readonly RefusalEcho[];
454
488
  };
455
489
  /**
456
490
  * A permission MODE released a surviving ask — the allowed disposition's account of the question it did not put
@@ -511,6 +545,9 @@ export interface ModeRefusal {
511
545
  * I10 `settlement.when` present ⇒ a finite number (epoch ms — the moment the wait ended is a value a reader can order);
512
546
  * I12 `disposition.extension` present ⇒ the denied arm, a layer word {@link DENIED_BY_MAY_NAME_EXTENSION} admits (the hook layer),
513
547
  * and a non-empty string (a registration's name);
548
+ * I13 `disposition.echoed` present ⇒ the denied arm, a layer word {@link DENIED_BY_MAY_ECHO} admits (the read station, an ask's resolution), and a
549
+ * non-empty list of echoes ({@link refusalEchoDefects}): a kind of the closed set, a non-empty `value`, and a `canonical`
550
+ * only on a path;
514
551
  * I11 a winner's `decision` stated beside the record (the caller reads a durable row: `winnerDecision`) ⇒ a word a winner holds,
515
552
  * and its direction (allow: `allow` / `approve` / `edit`; refusal: `deny` / `reject`) is the direction of the record's
516
553
  * settlement ({@link SETTLEMENT_IS_REFUSAL}) and of its disposition (`allowed` / `denied`) — one decision, one direction.
@@ -582,7 +619,7 @@ export declare function isRetiredMember<S extends MemberSet>(set: S, word: unkno
582
619
  */
583
620
  export declare function releasePolicyDefects(g: unknown): string[];
584
621
  /** The members only the denied arm of a {@link GateDisposition} carries. */
585
- declare const DENY_ONLY_MEMBERS: readonly ["deniedBy", "cause", "mode", "askClass", "classes", "extension"];
622
+ declare const DENY_ONLY_MEMBERS: readonly ["deniedBy", "cause", "mode", "askClass", "classes", "extension", "echoed"];
586
623
  type DenyOnlyMember = Exclude<keyof Extract<GateDisposition, {
587
624
  kind: "denied";
588
625
  }>, keyof Extract<GateDisposition, {
@@ -1,6 +1,7 @@
1
1
  import { isAskClass, isAskOrigin, isModeReleaseReason, isPermissionMode, isPersistedRuleMandate, ASK_FACES, releasableAskClassesFor } from "./ask-origin.js";
2
2
  import { isAutoModeFallbackCause } from "./auto-mode.js";
3
3
  import { ALLOW_RULE_MEMBERS } from "./allow-rule-shadow.js";
4
+ import { refusalEchoDefects } from "./refusal-echo.js";
4
5
  export const SETTLEMENT_KINDS = Object.freeze([
5
6
  "human_allowed",
6
7
  "human_refused",
@@ -141,6 +142,18 @@ export const DENIED_BY_MAY_NAME_EXTENSION = {
141
142
  read_boundary: false,
142
143
  mode: false,
143
144
  };
145
+ export const DENIED_BY_MAY_ECHO = {
146
+ policy: false,
147
+ hook: false,
148
+ org: false,
149
+ persisted_rule: false,
150
+ classifier: false,
151
+ compliance: false,
152
+ write_protection: false,
153
+ ask_resolution: true,
154
+ read_boundary: true,
155
+ mode: false,
156
+ };
144
157
  const retired = (word, retiredIn) => Object.freeze({ word, retiredIn });
145
158
  export const RETIRED_MEMBERS = Object.freeze({
146
159
  askClass: Object.freeze([retired("write_protection_unresolved", "7.49.0"), retired("governance_unavailable", "7.51.0")]),
@@ -211,7 +224,7 @@ function clearanceDefects(v, settled, released) {
211
224
  }
212
225
  return out;
213
226
  }
214
- const DENY_ONLY_MEMBERS = Object.freeze(["deniedBy", "cause", "mode", "askClass", "classes", "extension"]);
227
+ const DENY_ONLY_MEMBERS = Object.freeze(["deniedBy", "cause", "mode", "askClass", "classes", "extension", "echoed"]);
215
228
  function objectOf(v) {
216
229
  return typeof v === "object" && v !== null && !Array.isArray(v) ? v : undefined;
217
230
  }
@@ -331,6 +344,12 @@ export function screenGateOutcome(g, opts) {
331
344
  if (layer && !(isDeniedBy(denied.deniedBy) && DENIED_BY_MAY_NAME_EXTENSION[denied.deniedBy]))
332
345
  defects.push(`I12: an extension cannot be named beside deniedBy "${String(denied.deniedBy)}"`);
333
346
  }
347
+ if (denied.echoed !== undefined) {
348
+ for (const defect of refusalEchoDefects(denied.echoed))
349
+ defects.push(`I13: disposition.${defect}`);
350
+ if (layer && !(isDeniedBy(denied.deniedBy) && DENIED_BY_MAY_ECHO[denied.deniedBy]))
351
+ defects.push(`I13: quoted literals cannot be filed beside deniedBy "${String(denied.deniedBy)}"`);
352
+ }
334
353
  if (denied.askClass !== undefined && !member("askClass", denied.askClass))
335
354
  defects.push(outside("disposition.askClass", "askClass", denied.askClass));
336
355
  if (denied.classes !== undefined && !classList(denied.classes))
@@ -145,7 +145,7 @@ export type NoticeAudience = "user" | "operator";
145
145
  * the union's catalog ({@link EngineNotice.code}). The groups below say only which family a row joins,
146
146
  * so the catalog is not written a second time here and the two cannot drift.
147
147
  */
148
- export declare const ENGINE_NOTICE_CODES: readonly ["config.autocompact_window_clamped", "config.env_timeout_discarded", "config.materialize_env_discarded", "config.models_swapped", "config.context_settings_swapped", "config.read_face_swapped", "config.read_face_deployment_clamped", "config.write_face_swapped", "config.write_face_deployment_clamped", "config.read_deny_swapped", "config.tool_model_gate_removed", "config.tool_model_gate_unknown_class", "config.tool_model_gate_env_invalid", "config.artifact_host_invalid", "config.task_root_not_canonical", "config.write_protection_target_view_absent", "config.path_view_unresolved", "config.execution_env_capability_invalid", "config.read_deny_floor_unkept", "config.read_floor_confinement_unavailable", "config.tool_card_undeclared", "config.tool_face_undeclared", "config.tool_face_invalid", "config.forward_sink_failed", "config.durable_gate_unavailable", "config.peer_admission_out_of_range", "config.peer_lane_unmounted", "config.secret_env_scrubbed", "inherit_env.names_withheld", "config.credential_not_withheld", "config.cross_boundary_posture_undeclared", "config.cross_boundary_record_unwritten", "config.permission_mode_unavailable", "permission.ask_released_by_mode", "permission.read_deny_unapplied", "permission.rule_store_unavailable", "permission.rule_row_dropped", "config.session_rules_earlier_grammar", "permission.allowed_tool_not_granted", "mods.registration_refused", "peer.inbound_disposition", "peer.held_settled", "peer.idle_subscription", "classifier.denial_limit", "classifier.fallback", "classifier.seat_rate_limited", "classifier.role_defaulted", "classifier.contract_broken", "classifier.unavailable", "checkpoint.execution_outcome_unrecorded", "delegation.transcript_integrity", "delegation.ask_unresolvable", "delegation.resume_lane_missing", "mcp.injection_dropped", "mcp.revocation_probe_failed", "mcp.server_redialed", "mcp.authorization_required", "mcp.credential_echoed", "workflow.governance_key_stripped", "workflow.agent_option_ignored", "memory.session_polluted", "memory.harvest_quarantined", "memory.harvest_refused", "memory.harvest_conflict", "memory.delegation_static_mark_waived", "memory.content_class_declared", "memory.hold_opened", "memory.hold_released", "memory.hold_disposed", "memory.consolidation_recommended", "memory.consolidation_committed", "memory.consolidation_conflict", "memory.consolidation_incomplete", "memory.consolidation_refused", "memory.consolidation_withheld", "memory.restore_withheld", "memory.project_scope_absent", "route.fallback_to_primary", "route.classifier_unroutable", "route.seat_detached", "advisor.not_attached", "route.credential_origin_mismatch", "route.credential_rebound", "route.response_model_mismatch", "route.tool_call_id_folded", "route.finish_reason_unknown", "route.stream_end_ignored", "route.extra_body_reserved_dropped", "model.capability_downgraded", "model.role_defaulted", "context.tool_turn_repaired", "context.media_removed", "context.tool_schema_removed", "task.user_steer_undrained", "task.user_followup_undrained", "steering.parked_input_blocked", "task.turn_interrupted", "task.halt_unconsumed", "task.late_approval", "task.interrupt_unconsumed", "task.tool_turn_incomplete", "approval.read_root_granted", "approval.read_root_grant_rejected", "memory.capture_opted_out", "memory.capture_optout_unpersisted", "skills.listing_truncated", "agents.listing_truncated", "tool_result.offload_put_failed", "tool_result.media_refused", "config.image_processor_unavailable", "fs.staging_file_left", "fs.staging_file_swept", "session.lineage_rerooted", "instructions.source_changed", "memory.layer_locked_legacy", "server.model_unreachable", "permission.entry_mode_clamped"];
148
+ export declare const ENGINE_NOTICE_CODES: readonly ["config.autocompact_window_clamped", "config.env_timeout_discarded", "config.materialize_env_discarded", "config.models_swapped", "config.context_settings_swapped", "config.read_face_swapped", "config.read_face_deployment_clamped", "config.write_face_swapped", "config.write_face_deployment_clamped", "config.read_deny_swapped", "config.tool_model_gate_removed", "config.tool_model_gate_unknown_class", "config.tool_model_gate_env_invalid", "config.artifact_host_invalid", "config.task_root_not_canonical", "config.write_protection_target_view_absent", "config.path_view_unresolved", "config.execution_env_capability_invalid", "config.read_deny_floor_unkept", "config.read_floor_confinement_unavailable", "config.tool_card_undeclared", "config.tool_face_undeclared", "config.tool_face_invalid", "config.forward_sink_failed", "config.durable_gate_unavailable", "config.peer_admission_out_of_range", "config.peer_lane_unmounted", "config.secret_env_scrubbed", "inherit_env.names_withheld", "config.credential_not_withheld", "config.cross_boundary_posture_undeclared", "config.cross_boundary_record_unwritten", "config.permission_mode_unavailable", "permission.ask_released_by_mode", "permission.read_deny_unapplied", "permission.rule_store_unavailable", "permission.rule_row_dropped", "config.session_rules_earlier_grammar", "permission.allowed_tool_not_granted", "mods.registration_refused", "peer.inbound_disposition", "peer.held_settled", "peer.idle_subscription", "classifier.denial_limit", "classifier.fallback", "classifier.seat_rate_limited", "classifier.role_defaulted", "classifier.contract_broken", "classifier.unavailable", "checkpoint.execution_outcome_unrecorded", "delegation.transcript_integrity", "delegation.ask_unresolvable", "delegation.resume_lane_missing", "delegation.delivery_discarded", "mcp.injection_dropped", "mcp.revocation_probe_failed", "mcp.server_redialed", "mcp.authorization_required", "mcp.credential_echoed", "workflow.governance_key_stripped", "workflow.agent_option_ignored", "memory.session_polluted", "memory.harvest_quarantined", "memory.harvest_refused", "memory.harvest_conflict", "memory.delegation_static_mark_waived", "memory.content_class_declared", "memory.hold_opened", "memory.hold_released", "memory.hold_disposed", "memory.consolidation_recommended", "memory.consolidation_committed", "memory.consolidation_conflict", "memory.consolidation_incomplete", "memory.consolidation_refused", "memory.consolidation_withheld", "memory.restore_withheld", "memory.project_scope_absent", "route.fallback_to_primary", "route.classifier_unroutable", "route.seat_detached", "advisor.not_attached", "route.credential_origin_mismatch", "route.credential_rebound", "route.response_model_mismatch", "route.tool_call_id_folded", "route.finish_reason_unknown", "route.stream_end_ignored", "route.extra_body_reserved_dropped", "model.capability_downgraded", "model.role_defaulted", "context.tool_turn_repaired", "context.media_removed", "context.tool_schema_removed", "task.user_steer_undrained", "task.user_followup_undrained", "steering.parked_input_blocked", "task.turn_interrupted", "task.halt_unconsumed", "task.late_approval", "task.interrupt_unconsumed", "task.tool_turn_incomplete", "approval.read_root_granted", "approval.read_root_grant_rejected", "memory.capture_opted_out", "memory.capture_optout_unpersisted", "skills.listing_truncated", "agents.listing_truncated", "tool_result.offload_put_failed", "tool_result.media_refused", "config.image_processor_unavailable", "fs.staging_file_left", "fs.staging_file_swept", "session.lineage_rerooted", "instructions.source_changed", "memory.layer_locked_legacy", "server.model_unreachable", "permission.entry_mode_clamped"];
149
149
  /** A catalogued code (see {@link ENGINE_NOTICE_CODES}); {@link NOTICE_MINTER} says who mints it. NOT the type of
150
150
  * `EngineNotice.code`, which stays `string` — a host forwarding its own notices through the same
151
151
  * sink is a supported shape, and narrowing that field would break it. */
@@ -239,6 +239,7 @@ declare const NOTICE_AUDIENCE_TABLE: {
239
239
  readonly "peer.idle_subscription": "user";
240
240
  readonly "delegation.transcript_integrity": "operator";
241
241
  readonly "delegation.resume_lane_missing": "operator";
242
+ readonly "delegation.delivery_discarded": "operator";
242
243
  readonly "checkpoint.execution_outcome_unrecorded": "operator";
243
244
  readonly "mcp.injection_dropped": "user";
244
245
  readonly "mcp.revocation_probe_failed": "operator";
@@ -359,6 +360,7 @@ declare const NOTICE_MINTER_TABLE: {
359
360
  readonly "delegation.transcript_integrity": "engine";
360
361
  readonly "delegation.ask_unresolvable": "engine";
361
362
  readonly "delegation.resume_lane_missing": "engine";
363
+ readonly "delegation.delivery_discarded": "engine";
362
364
  readonly "mcp.injection_dropped": "engine";
363
365
  readonly "mcp.revocation_probe_failed": "engine";
364
366
  readonly "mcp.server_redialed": "engine";
@@ -62,6 +62,7 @@ export const NON_GOVERNANCE_MEMORY_CODES = new Set([
62
62
  "memory.control_plane_not_corrupt",
63
63
  "memory.control_plane_rebuild_unsupported",
64
64
  "memory.governance_doc_unknown",
65
+ "memory.control_object_unknown",
65
66
  "memory.erasure_evidence_unavailable",
66
67
  "memory.erasure_selector_mismatch",
67
68
  "memory.erasure_census_incomplete",
@@ -181,6 +182,7 @@ export const ENGINE_NOTICE_CODES = Object.freeze([
181
182
  "delegation.transcript_integrity",
182
183
  "delegation.ask_unresolvable",
183
184
  "delegation.resume_lane_missing",
185
+ "delegation.delivery_discarded",
184
186
  "mcp.injection_dropped",
185
187
  "mcp.revocation_probe_failed",
186
188
  "mcp.server_redialed",
@@ -322,6 +324,7 @@ const NOTICE_AUDIENCE_TABLE = {
322
324
  "peer.idle_subscription": "user",
323
325
  "delegation.transcript_integrity": "operator",
324
326
  "delegation.resume_lane_missing": "operator",
327
+ "delegation.delivery_discarded": "operator",
325
328
  "checkpoint.execution_outcome_unrecorded": "operator",
326
329
  "mcp.injection_dropped": "user",
327
330
  "mcp.revocation_probe_failed": "operator",
@@ -423,6 +426,7 @@ const NOTICE_MINTER_TABLE = {
423
426
  "delegation.transcript_integrity": "engine",
424
427
  "delegation.ask_unresolvable": "engine",
425
428
  "delegation.resume_lane_missing": "engine",
429
+ "delegation.delivery_discarded": "engine",
426
430
  "mcp.injection_dropped": "engine",
427
431
  "mcp.revocation_probe_failed": "engine",
428
432
  "mcp.server_redialed": "engine",
@@ -1,5 +1,5 @@
1
1
  /**
2
- * A leg's two identity readings, as pure functions with no runtime imports — so a store's projection reads them exactly as
2
+ * A leg's identity readings, as pure functions with no runtime imports — so a store's projection reads them exactly as
3
3
  * the prepare mint and the stations do (one predicate each, never a second spelling at a reader that cannot reach the
4
4
  * mods layer).
5
5
  */
@@ -60,3 +60,21 @@ export interface AskSourceFacts {
60
60
  * refusal texts speak the right posture (parent thread: stop and wait for the user; delegated child: adapt or report).
61
61
  */
62
62
  export declare function mintAskSourceIdentity(leg: AskSourceFacts): AskSourceIdentity;
63
+ /** Where a leg's user-face notice is addressed: {@link noticeAddressOf}. Spread into the notice's detail as-is. */
64
+ export interface NoticeAddress {
65
+ /** The session the notice routes to (lifted onto the typed key at the one throat): the leg's own on a top-level leg, the
66
+ * delegation tree's root on a delegated one. */
67
+ readonly sessionId: string;
68
+ /** Present exactly on a delegated leg: the leg whose call the notice is about (its ask source's session). */
69
+ readonly sourceSessionId?: string;
70
+ /** Present on a delegated leg that carries one ({@link agentIdOf}): the agent id the leg's events and its spawner's card name. */
71
+ readonly agentId?: string;
72
+ }
73
+ /**
74
+ * The address of a leg's user-face notice — one rule: a user-face notice goes to the end of the delegation tree a person
75
+ * watches, and says which leg it came from. A top-level leg's notice is addressed to its own session and carries no source
76
+ * keys. A delegated leg's notice is addressed to the tree's root session (`internals.rootSessionId`: an intermediate parent
77
+ * at depth ≥ 2 has no host leg of its own to read it on) and carries the delegated leg's session and agent id — the shape a
78
+ * subagent's permission denial takes upstream (the top-level session id plus the agent id).
79
+ */
80
+ export declare function noticeAddressOf(askSource: AskSourceIdentity, rootSessionId: string | undefined): NoticeAddress;
@@ -16,3 +16,15 @@ export function mintAskSourceIdentity(leg) {
16
16
  ...(leg.isDelegatedChild ? { isDelegatedChild: true } : {}),
17
17
  });
18
18
  }
19
+ export function noticeAddressOf(askSource, rootSessionId) {
20
+ const own = askSource.sourceSessionId;
21
+ if (own === undefined || own.length === 0)
22
+ throw new TypeError("noticeAddressOf: the leg's ask source carries no session");
23
+ if (askSource.isDelegatedChild !== true)
24
+ return { sessionId: own };
25
+ return {
26
+ sessionId: rootSessionId !== undefined && rootSessionId.length > 0 ? rootSessionId : own,
27
+ sourceSessionId: own,
28
+ ...(askSource.agentId !== undefined ? { agentId: askSource.agentId } : {}),
29
+ };
30
+ }
@@ -99,9 +99,22 @@ export interface MailboxPeerMeta {
99
99
  * ahead of the non-urgent ones of the same pass and counts it on the inbox notice; it never changes
100
100
  * WHEN the recipient reads (the recipient's setting decides that, never the sender). */
101
101
  urgent?: boolean;
102
+ /**
103
+ * WHO the record is for: the occupant (`SessionMetadata.incarnation`) of the session the writer addressed, as the writer
104
+ * resolved that address — a park seat from its leg's address, a sender from the recipient's directory row, a notice from the
105
+ * reply address it answers. A session box outlives its occupant (the id can be deleted and created again, the box stays), so a
106
+ * drain hands a record only to the occupant it names ({@link import("./runner/delegation-owner.js").sameOccupant}: absent on
107
+ * both sides is one occupant — a deployment whose store mints no tokens; absent on one side only is another occupant). A
108
+ * record for another occupant is discarded with an account, never delivered. An addressing fact, not a secret and not a
109
+ * credential: it proves nothing about who wrote the record.
110
+ */
111
+ occupant?: string;
112
+ /** The occupant of the SENDING session, beside `fromSession`: what a notice answering this record (a receipt, an idle notice)
113
+ * is addressed to ({@link occupant} of that notice). Absent = the sender stated none. */
114
+ fromOccupant?: string;
102
115
  }
103
116
  /** design/385 — the typed body of a notice-kind record. `state` is drawn from the receipt states on a
104
- * `delivery_notice` (`held|denied|expired|delivered|refused|dropped`) and from the idle kinds on an
117
+ * `delivery_notice` (`held|denied|expired|delivered|refused|dropped|held_by_policy`) and from the idle kinds on an
105
118
  * `idle_notice` (`idle|exited|unavailable|expired`); the validator admits the union, the drain checks
106
119
  * the pairing (a state that does not fit its kind is settled `notice_unrouted`, never rendered). */
107
120
  export interface MailboxPeerNoticeMeta {
@@ -142,8 +155,9 @@ export declare const MAILBOX_PEER_RECORD_KINDS: readonly ["peer_message", "idle_
142
155
  export type MailboxPeerRecordKind = (typeof MAILBOX_PEER_RECORD_KINDS)[number];
143
156
  /** The `notice.state` vocabulary the validator admits (the union of both notice families; the drain
144
157
  * checks the kind↔state pairing). Spelled here, beside the record kinds, so the store contract is
145
- * self-contained — the lane's own closed sets re-derive from these. */
146
- export declare const MAILBOX_PEER_NOTICE_STATES: readonly ["held", "denied", "expired", "delivered", "refused", "dropped", "idle", "exited", "unavailable"];
158
+ * self-contained — the lane's two closed sets (`PEER_DELIVERY_RECEIPT_STATES`, `PEER_IDLE_NOTICE_KINDS`)
159
+ * are spelled beside their renderers and together equal this one (a pin holds the two spellings together). */
160
+ export declare const MAILBOX_PEER_NOTICE_STATES: readonly ["held", "denied", "expired", "delivered", "refused", "dropped", "idle", "exited", "unavailable", "held_by_policy"];
147
161
  export type MailboxPeerNoticeState = (typeof MAILBOX_PEER_NOTICE_STATES)[number];
148
162
  /** The `append` refusal code for a malformed `peerMeta` (design/385): a garbage record is refused up
149
163
  * front with this code, never silently stripped or stored — a drain that reads a half-typed record
@@ -383,7 +397,15 @@ export interface MailboxStore {
383
397
  releaseLease(scope: string, handle: string, owner: string): Promise<void>;
384
398
  /** Observation face (the "N pending" receipt figure) — count of currently-visible messages. */
385
399
  peekCount(scope: string, handle: string): Promise<number>;
386
- /** Drop the WHOLE mailbox for (scope, handle) — the row-deletion companion (F-13). */
400
+ /**
401
+ * Drop the WHOLE mailbox for (scope, handle) — the row-deletion companion (F-13).
402
+ *
403
+ * @contract mailbox.session_box_outlives_its_occupant — deleting a session's row does not remove its box
404
+ * `(scope, session.<id>)`: a deployment's deletion cascade clears it with this verb (retention is the deployment's). What
405
+ * stays behind is never delivered to another occupant: every session-box record names the occupant it is for
406
+ * ({@link MailboxPeerMeta.occupant}), and a drain hands a record only to that occupant — a record for an earlier occupant
407
+ * of the id is discarded with an account (`delegation.delivery_discarded`) by the next occupant's drain.
408
+ */
387
409
  drop(scope: string, handle: string): Promise<void>;
388
410
  /** Age out mailboxes whose newest message BY `sentAt` (not by array/insertion order — RB-250②)
389
411
  * is older than maxAgeMs. Returns mailboxes dropped. */
@@ -444,6 +466,19 @@ export type MailboxCrossProcessVerdict = {
444
466
  * value of the wrong type (a malformed declaration is refused, not read as "probably fine").
445
467
  */
446
468
  export declare function mailboxCrossProcessMountVerdict(store: MailboxStore): MailboxCrossProcessVerdict;
469
+ /**
470
+ * THE mount verdict of the SESSION-BOX lane — a session's own `session.<id>` box, the drain that consumes it and every seat that
471
+ * appends to it: the mailbox's cross-process declaration ({@link mailboxCrossProcessMountVerdict}) AND a session store that reads a
472
+ * session's row by id (`SessionStore.headOf`). A box outlives its session's occupant (the id can be deleted and created again), and
473
+ * a drain discards a record addressed to another occupant only after it has read, by id, that its run's session still holds the
474
+ * occupant it acquired; over a store that cannot be read by id every such record is undecidable and the box would jam, so the lane
475
+ * does not mount, and the reason names the missing read. One judgment, read by the drain mount, the peer-lane mount and the send
476
+ * face, so where a record is parked and where it is drained cannot disagree. `sessions` absent = no session store at all: the same
477
+ * refusal.
478
+ */
479
+ export declare function sessionBoxMountVerdict(mailbox: MailboxStore, sessions: {
480
+ readonly headOf?: unknown;
481
+ } | undefined): MailboxCrossProcessVerdict;
447
482
  /** RB-250② (2026-07-28) class fix — the box age for `reap` is the MAX `sentAt`, not the
448
483
  * last array element: `sentAt` is caller-supplied, so append order need not be time order, and taking
449
484
  * the tail let a box whose freshest message was mid-array be swept — both bundled backends discarded
@@ -52,10 +52,10 @@ export function assertMailboxDecisionMove(seq, expect, next) {
52
52
  }
53
53
  export const MAILBOX_PEER_FROM_MODES = Object.freeze(["bypass", "prompting"]);
54
54
  export const MAILBOX_PEER_RECORD_KINDS = Object.freeze(["peer_message", "idle_notice", "delivery_notice", "idle_subscription", "engine_frame"]);
55
- export const MAILBOX_PEER_NOTICE_STATES = Object.freeze(["held", "denied", "expired", "delivered", "refused", "dropped", "idle", "exited", "unavailable"]);
55
+ export const MAILBOX_PEER_NOTICE_STATES = Object.freeze(["held", "denied", "expired", "delivered", "refused", "dropped", "idle", "exited", "unavailable", "held_by_policy"]);
56
56
  export const MAILBOX_INVALID_PEER_META_CODE = "mailbox.invalid_peer_meta";
57
57
  export const MAILBOX_CROSS_PROCESS_UNSAFE_CODE = "mailbox.cross_process_unsafe";
58
- const PEER_META_STRING_KEYS = ["fromSession", "fromRoot", "senderKey", "fromScope", "gateReceiptId"];
58
+ const PEER_META_STRING_KEYS = ["fromSession", "fromRoot", "senderKey", "fromScope", "gateReceiptId", "occupant", "fromOccupant"];
59
59
  export function readMailboxPeerMeta(raw) {
60
60
  if (raw === undefined)
61
61
  return undefined;
@@ -228,6 +228,18 @@ export function mailboxCrossProcessMountVerdict(store) {
228
228
  : `the mailbox backend's crossProcessSafe declaration is malformed (${typeof declared}, expected a boolean)`;
229
229
  return { ok: false, code: MAILBOX_CROSS_PROCESS_UNSAFE_CODE, reason };
230
230
  }
231
+ export function sessionBoxMountVerdict(mailbox, sessions) {
232
+ const store = mailboxCrossProcessMountVerdict(mailbox);
233
+ if (!store.ok)
234
+ return store;
235
+ if (typeof sessions?.headOf === "function")
236
+ return { ok: true };
237
+ return {
238
+ ok: false,
239
+ code: MAILBOX_CROSS_PROCESS_UNSAFE_CODE,
240
+ reason: "the session store has no by-id read (SessionStore.headOf): a session box outlives its session's occupant, and without that read a drain cannot confirm that its run's session still holds the occupant it acquired before it discards a record addressed to another, so a box shared across runs would hand one occupant's records to another on luck",
241
+ };
242
+ }
231
243
  export function newestSentAt(messages) {
232
244
  let newest;
233
245
  for (const m of messages) {
@@ -560,8 +560,9 @@ export declare function fileGovernanceStoreDir(store: MemoryGovernanceStore): st
560
560
  /**
561
561
  * The consolidation state's File store over one control plane — the gate file, the plan workbook, the intent
562
562
  * credentials, the run account and the mint archive exactly as they have always been laid out (same names, same
563
- * bytes, same locks). The File backend carries it over its own control plane; an engine whose backend carries no
564
- * store keeps its state with this over the replica's control plane.
563
+ * bytes, same locks), each governance document in its own file ({@link fileGovernanceDocOf}) and each control object
564
+ * in its kind's directory (`control-objects.ts`). The File backend carries it over its own control plane; an engine
565
+ * whose backend carries no store keeps its state with this over the replica's control plane.
565
566
  */
566
567
  export declare function fileGovernanceStore(controlDir: string): MemoryGovernanceStore;
567
568
  /** Derive a product's slug from its proposed name (memory filename charset; collisions are the
@@ -2,6 +2,7 @@ import { existsSync, readdirSync, readFileSync, renameSync, rmSync } from "node:
2
2
  import { join } from "node:path";
3
3
  import { uuidv7 } from "../../engine/session/uuid.js";
4
4
  import { atomicWriteFileSync, fileGovernanceDocOf, lockedStrictUpdate, readStrictSidecar, ControlPlaneCorruptError, ensureDirExists } from "./layout.js";
5
+ import { deleteFileControlObject, getFileControlObject, listFileControlObjects, moveFileControlObject, putFileControlObject } from "./control-objects.js";
5
6
  import { thrownText } from "../thrown-value.js";
6
7
  import { optionKeys, receiveMembers } from "../own-property-receipt.js";
7
8
  export function deriveSupersededSet(headers, opts = {}) {
@@ -514,6 +515,21 @@ export function fileGovernanceStore(controlDir) {
514
515
  rmSync(path, { force: true });
515
516
  return true;
516
517
  },
518
+ async putObject(kind, name, bytes) {
519
+ return putFileControlObject(controlDir, kind, name, bytes);
520
+ },
521
+ async getObject(kind, name) {
522
+ return getFileControlObject(controlDir, kind, name);
523
+ },
524
+ async listObjects(kind) {
525
+ return listFileControlObjects(controlDir, kind);
526
+ },
527
+ async moveObject(from, to) {
528
+ return moveFileControlObject(controlDir, from, to);
529
+ },
530
+ async deleteObject(kind, name) {
531
+ return deleteFileControlObject(controlDir, kind, name);
532
+ },
517
533
  });
518
534
  FILE_GOVERNANCE_DIRS.set(store, controlDir);
519
535
  return store;
@@ -0,0 +1,25 @@
1
+ import { type MemoryControlObjectKind } from "./types.js";
2
+ /** Where a File store stages an object's bytes before publishing them under the object's name. Never a kind's
3
+ * directory: a listing of a kind answers published names only. */
4
+ export declare const CONTROL_OBJECT_STAGE_DIR = ".control-object-stage";
5
+ /** A control-object kind's directory under a File store's control plane. A kind outside
6
+ * {@link MEMORY_CONTROL_OBJECT_KINDS} is refused (`memory.control_object_unknown`) — never given a directory of its own. */
7
+ export declare function fileControlObjectDirOf(kind: MemoryControlObjectKind): string;
8
+ /** A name a store keeps an object under: one opaque, non-empty segment — never `.` / `..`, never a separator or a NUL. */
9
+ export declare function isControlObjectName(name: unknown): name is string;
10
+ /** Write `(kind, name)` once ({@link import("./types.js").MemoryGovernanceStore.putObject}). */
11
+ export declare function putFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string, bytes: Uint8Array): "created" | "existed";
12
+ /** A control object's bytes ({@link import("./types.js").MemoryGovernanceStore.getObject}). */
13
+ export declare function getFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string): Uint8Array | undefined;
14
+ /** Every name of `kind`, sorted ({@link import("./types.js").MemoryGovernanceStore.listObjects}). */
15
+ export declare function listFileControlObjects(controlDir: string, kind: MemoryControlObjectKind): string[];
16
+ /** Move one object, never overwriting ({@link import("./types.js").MemoryGovernanceStore.moveObject}). */
17
+ export declare function moveFileControlObject(controlDir: string, from: {
18
+ readonly kind: MemoryControlObjectKind;
19
+ readonly name: string;
20
+ }, to: {
21
+ readonly kind: MemoryControlObjectKind;
22
+ readonly name: string;
23
+ }): "moved" | "already-moved";
24
+ /** Delete one object ({@link import("./types.js").MemoryGovernanceStore.deleteObject}). */
25
+ export declare function deleteFileControlObject(controlDir: string, kind: MemoryControlObjectKind, name: string): boolean;
@@ -0,0 +1,151 @@
1
+ import { closeSync, fsyncSync, linkSync, lstatSync, openSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import { MEMORY_CONTROL_OBJECT_KINDS } from "./types.js";
5
+ import { ControlPlaneCorruptError, IMPORT_RECEIPTS_DIR, QUARANTINE_DIR, SESSION_CAPTURE_OPTOUT_DIR, SESSION_POLLUTION_DIR, ensureDirExists } from "./layout.js";
6
+ const FILE_CONTROL_OBJECT_DIRS = Object.freeze({
7
+ pollution: SESSION_POLLUTION_DIR,
8
+ "import-receipt": IMPORT_RECEIPTS_DIR,
9
+ quarantine: QUARANTINE_DIR,
10
+ hold: "hold",
11
+ "clearance-custody": "origin-clearance-custody",
12
+ capture: SESSION_CAPTURE_OPTOUT_DIR,
13
+ });
14
+ export const CONTROL_OBJECT_STAGE_DIR = ".control-object-stage";
15
+ function unknownObject(what) {
16
+ const e = new Error(`memory governance store: ${what} (a control object is one of ${MEMORY_CONTROL_OBJECT_KINDS.join(", ")}, named by one opaque segment)`);
17
+ e.code = "memory.control_object_unknown";
18
+ return e;
19
+ }
20
+ export function fileControlObjectDirOf(kind) {
21
+ if (typeof kind !== "string" || !Object.prototype.hasOwnProperty.call(FILE_CONTROL_OBJECT_DIRS, kind))
22
+ throw unknownObject(`${JSON.stringify(String(kind))} is not a control-object kind`);
23
+ return FILE_CONTROL_OBJECT_DIRS[kind];
24
+ }
25
+ export function isControlObjectName(name) {
26
+ return typeof name === "string" && name !== "" && name !== "." && name !== ".." && !/[/\\\0]/.test(name);
27
+ }
28
+ function objectPath(controlDir, kind, name) {
29
+ const dir = fileControlObjectDirOf(kind);
30
+ if (!isControlObjectName(name))
31
+ throw unknownObject(`${JSON.stringify(String(name))} is not a control-object name`);
32
+ return join(controlDir, dir, name);
33
+ }
34
+ function errnoOf(err) {
35
+ return typeof err === "object" && err !== null ? Reflect.get(err, "code") : undefined;
36
+ }
37
+ function stands(path) {
38
+ try {
39
+ lstatSync(path);
40
+ return true;
41
+ }
42
+ catch (err) {
43
+ if (errnoOf(err) === "ENOENT")
44
+ return false;
45
+ throw new ControlPlaneCorruptError(`memory control object at ${path} could not be probed (${errnoOf(err) ?? "io error"}) — whether it stands is unknown (fail-closed)`, { cause: err });
46
+ }
47
+ }
48
+ export function putFileControlObject(controlDir, kind, name, bytes) {
49
+ const path = objectPath(controlDir, kind, name);
50
+ if (stands(path))
51
+ return "existed";
52
+ ensureDirExists(join(controlDir, fileControlObjectDirOf(kind)));
53
+ const stageDir = join(controlDir, CONTROL_OBJECT_STAGE_DIR);
54
+ ensureDirExists(stageDir);
55
+ const staged = join(stageDir, randomUUID());
56
+ const fd = openSync(staged, "wx", 0o600);
57
+ try {
58
+ let written = 0;
59
+ while (written < bytes.byteLength) {
60
+ const n = writeSync(fd, bytes, written, bytes.byteLength - written);
61
+ if (n <= 0)
62
+ throw new Error(`memory control object ${kind}/${name}: write made no progress (${written}/${bytes.byteLength} bytes)`);
63
+ written += n;
64
+ }
65
+ fsyncSync(fd);
66
+ }
67
+ finally {
68
+ closeSync(fd);
69
+ }
70
+ try {
71
+ linkSync(staged, path);
72
+ return "created";
73
+ }
74
+ catch (err) {
75
+ if (errnoOf(err) === "EEXIST")
76
+ return "existed";
77
+ throw err;
78
+ }
79
+ finally {
80
+ rmSync(staged, { force: true });
81
+ }
82
+ }
83
+ export function getFileControlObject(controlDir, kind, name) {
84
+ const path = objectPath(controlDir, kind, name);
85
+ try {
86
+ return new Uint8Array(readFileSync(path));
87
+ }
88
+ catch (err) {
89
+ if ((errnoOf(err) === "ENOENT" || errnoOf(err) === "ENOTDIR") && !stands(path))
90
+ return undefined;
91
+ throw new ControlPlaneCorruptError(`memory control object ${kind}/${name} stands but cannot be read (${errnoOf(err) ?? "io error"}) — it is never read as missing (fail-closed)`, { cause: err });
92
+ }
93
+ }
94
+ export function listFileControlObjects(controlDir, kind) {
95
+ const dir = join(controlDir, fileControlObjectDirOf(kind));
96
+ try {
97
+ return readdirSync(dir).sort();
98
+ }
99
+ catch (err) {
100
+ if (errnoOf(err) === "ENOENT" && !stands(dir))
101
+ return [];
102
+ throw new ControlPlaneCorruptError(`memory control objects of kind ${kind} could not be enumerated (${errnoOf(err) ?? "io error"}) at ${dir} — an enumeration failure is not an empty kind (fail-closed)`, { cause: err });
103
+ }
104
+ }
105
+ function sameBytes(a, b) {
106
+ const sa = statSync(a);
107
+ const sb = statSync(b);
108
+ if (sa.dev === sb.dev && sa.ino === sb.ino)
109
+ return true;
110
+ return readFileSync(a).equals(readFileSync(b));
111
+ }
112
+ export function moveFileControlObject(controlDir, from, to) {
113
+ const src = objectPath(controlDir, from.kind, from.name);
114
+ const dst = objectPath(controlDir, to.kind, to.name);
115
+ const neither = () => new ControlPlaneCorruptError(`memory control object move ${from.kind}/${from.name} → ${to.kind}/${to.name}: neither the source nor the target stands — nothing to move or to resume (fail-closed)`);
116
+ if (src === dst) {
117
+ if (stands(src))
118
+ return "already-moved";
119
+ throw neither();
120
+ }
121
+ ensureDirExists(join(controlDir, fileControlObjectDirOf(to.kind)));
122
+ try {
123
+ linkSync(src, dst);
124
+ }
125
+ catch (err) {
126
+ const code = errnoOf(err);
127
+ if (code === "ENOENT" && !stands(src)) {
128
+ if (stands(dst))
129
+ return "already-moved";
130
+ throw neither();
131
+ }
132
+ if (code !== "EEXIST")
133
+ throw err;
134
+ if (!sameBytes(src, dst))
135
+ throw new ControlPlaneCorruptError(`memory control object move ${from.kind}/${from.name} → ${to.kind}/${to.name}: the target already stands with different bytes — refusing to overwrite it (fail-closed)`);
136
+ }
137
+ unlinkSync(src);
138
+ return "moved";
139
+ }
140
+ export function deleteFileControlObject(controlDir, kind, name) {
141
+ const path = objectPath(controlDir, kind, name);
142
+ try {
143
+ unlinkSync(path);
144
+ return true;
145
+ }
146
+ catch (err) {
147
+ if ((errnoOf(err) === "ENOENT" || errnoOf(err) === "ENOTDIR") && !stands(path))
148
+ return false;
149
+ throw err;
150
+ }
151
+ }