@remnic/core 9.65.4 → 9.65.6

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 (214) hide show
  1. package/dist/access-admin-ops-surface.d.ts +1 -1
  2. package/dist/access-admin-ops-surface.js +24 -24
  3. package/dist/access-audit.js +2 -2
  4. package/dist/access-authorization-probe.d.ts +1 -1
  5. package/dist/access-authorization-probe.js +25 -25
  6. package/dist/access-boundary.d.ts +1 -1
  7. package/dist/access-boundary.js +24 -24
  8. package/dist/access-cli.js +69 -68
  9. package/dist/access-cli.js.map +1 -1
  10. package/dist/access-extraction-force-flush.d.ts +1 -1
  11. package/dist/access-extraction-force-flush.js +24 -24
  12. package/dist/access-http-lcm-compaction.d.ts +1 -1
  13. package/dist/access-http-lifecycle-flush.d.ts +1 -1
  14. package/dist/access-http-offline-stream.d.ts +1 -1
  15. package/dist/access-http-query.js +26 -26
  16. package/dist/access-http.d.ts +2 -2
  17. package/dist/access-http.js +37 -37
  18. package/dist/access-identity-continuity-surface.js +24 -24
  19. package/dist/access-lcm-surface.d.ts +1 -1
  20. package/dist/access-lcm-surface.js +24 -24
  21. package/dist/access-mcp.d.ts +1 -1
  22. package/dist/access-mcp.js +30 -30
  23. package/dist/access-namespace-preflight.js +24 -24
  24. package/dist/access-observe-write-surface.d.ts +1 -1
  25. package/dist/access-observe-write-surface.js +24 -24
  26. package/dist/access-operations-batch.js +26 -26
  27. package/dist/access-operations.d.ts +6 -6
  28. package/dist/access-operations.js +29 -29
  29. package/dist/access-recall-concurrency.d.ts +1 -1
  30. package/dist/access-recall-concurrency.js +24 -24
  31. package/dist/access-recall-response.d.ts +1 -1
  32. package/dist/access-recall-response.js +24 -24
  33. package/dist/access-recall-surface.d.ts +1 -1
  34. package/dist/access-recall-surface.js +24 -24
  35. package/dist/access-schema.d.ts +83 -83
  36. package/dist/access-schema.js +3 -3
  37. package/dist/access-service-helpers.d.ts +1 -1
  38. package/dist/access-service.d.ts +1 -1
  39. package/dist/access-service.js +24 -24
  40. package/dist/access-surface-catalog.d.ts +1 -1
  41. package/dist/access-surface-catalog.js +26 -26
  42. package/dist/briefing.js +10 -10
  43. package/dist/{capsule-crypto-YO5QJ6L3.js → capsule-crypto-GWVG7LGC.js} +2 -2
  44. package/dist/causal-consolidation.js +11 -11
  45. package/dist/{chunk-ZPOHEB5Z.js → chunk-2JHRCWHT.js} +37 -37
  46. package/dist/{chunk-BK5G2MHO.js → chunk-2RXUZVPU.js} +2 -2
  47. package/dist/{chunk-JPAKBNTM.js → chunk-3I22VWB3.js} +2 -2
  48. package/dist/{chunk-ECLJ4LA2.js → chunk-53MZQEBD.js} +2 -2
  49. package/dist/{chunk-HF5BUTI6.js → chunk-5GIZM4RX.js} +2 -2
  50. package/dist/{chunk-YHGCT462.js → chunk-5TG4MU2U.js} +4 -4
  51. package/dist/{chunk-VDX2J7OX.js → chunk-5W7CTZ2E.js} +4 -4
  52. package/dist/{chunk-IWKGOCL6.js → chunk-5W7MKXMU.js} +4 -4
  53. package/dist/{chunk-YHCBJULX.js → chunk-6FUMA6AA.js} +2 -2
  54. package/dist/{chunk-THVI4Y7X.js → chunk-6LS5OX3U.js} +5 -5
  55. package/dist/{chunk-TVVEYCNW.js → chunk-7K5Q6COX.js} +4 -4
  56. package/dist/{chunk-KPB2QHJZ.js → chunk-7OZSHBWK.js} +2 -2
  57. package/dist/{chunk-CQBIN77D.js → chunk-7SSRXEZJ.js} +2 -2
  58. package/dist/{chunk-NNBZS3DY.js → chunk-AG46P24C.js} +4 -4
  59. package/dist/{chunk-QJW4MZSW.js → chunk-AYAZWXJI.js} +2 -2
  60. package/dist/{chunk-WDXD6ITO.js → chunk-BXXOPKT5.js} +2 -2
  61. package/dist/{chunk-DJZWNKFO.js → chunk-D35XLYQ7.js} +10 -10
  62. package/dist/{chunk-KOO37E4Y.js → chunk-DYO24BNB.js} +2 -2
  63. package/dist/{chunk-DORFF5N5.js → chunk-FEO2CDXR.js} +2 -2
  64. package/dist/{chunk-IURMJBGP.js → chunk-HWVNYNIV.js} +2 -2
  65. package/dist/{chunk-OZDFB22S.js → chunk-IDQ6DKXC.js} +3 -3
  66. package/dist/{chunk-J3ATBB7M.js → chunk-IF4EY26E.js} +2 -2
  67. package/dist/{chunk-W675UJCZ.js → chunk-IRXMJLTW.js} +2 -2
  68. package/dist/{chunk-DUZARALI.js → chunk-JFWZRUKP.js} +3 -3
  69. package/dist/{chunk-DUEDOYZD.js → chunk-JGG5HVI2.js} +2 -2
  70. package/dist/{chunk-3NH3VP3U.js → chunk-KBOG7FJV.js} +2 -2
  71. package/dist/{chunk-UCKG36HO.js → chunk-LSYD7GHZ.js} +2 -2
  72. package/dist/{chunk-6433HV72.js → chunk-MVIYRRVJ.js} +5 -5
  73. package/dist/{chunk-GHD2LLG4.js → chunk-NLUCDKLT.js} +2 -2
  74. package/dist/{chunk-TJFI3K2O.js → chunk-O4BAGJDN.js} +2 -2
  75. package/dist/{chunk-LYBIHM4N.js → chunk-OMZLBT4B.js} +4 -4
  76. package/dist/{chunk-BXLOS5AJ.js → chunk-OWHERGF2.js} +2 -2
  77. package/dist/{chunk-I23ZHYSL.js → chunk-PGW64IFQ.js} +2 -2
  78. package/dist/{chunk-AZLLH6YA.js → chunk-PNAGNVGK.js} +43 -48
  79. package/dist/chunk-PNAGNVGK.js.map +1 -0
  80. package/dist/{chunk-YDKF4MSJ.js → chunk-QMZY3GG6.js} +3 -3
  81. package/dist/{chunk-N37X5RU7.js → chunk-RACZB5HT.js} +4 -4
  82. package/dist/{chunk-YZJM6CLF.js → chunk-ROEAEANL.js} +7 -7
  83. package/dist/{chunk-SR5LNI6Q.js → chunk-RQ2EQRRR.js} +4 -4
  84. package/dist/chunk-SDEPLF7V.js +325 -0
  85. package/dist/chunk-SDEPLF7V.js.map +1 -0
  86. package/dist/{chunk-2IXQSGCU.js → chunk-SR7JIRAR.js} +2 -2
  87. package/dist/{chunk-OCCHUEZB.js → chunk-TWBQQ3FT.js} +2 -2
  88. package/dist/{chunk-NLEH4RTB.js → chunk-US4IRASK.js} +2 -2
  89. package/dist/{chunk-DQEMWVMT.js → chunk-UVYI6VIX.js} +1 -1
  90. package/dist/{chunk-PTZQYCJ4.js → chunk-W6J4POB6.js} +2 -2
  91. package/dist/{chunk-OU34IQXV.js → chunk-X2DWBWOX.js} +2 -2
  92. package/dist/{chunk-2MVTAIL3.js → chunk-XAWIL7TC.js} +2 -2
  93. package/dist/{chunk-UFR6HX7A.js → chunk-XUZ5CIEE.js} +1 -1
  94. package/dist/{chunk-GIC6BASP.js → chunk-XZBXINXZ.js} +4 -4
  95. package/dist/{chunk-XGM3VQWG.js → chunk-YUTTMSC7.js} +13 -13
  96. package/dist/{chunk-3JZBPTLD.js → chunk-YWBOOBDP.js} +38 -38
  97. package/dist/{chunk-KFIOPZ25.js → chunk-ZXUZ54Z5.js} +2 -2
  98. package/dist/{cli-DO3i14pM.d.ts → cli-Bfgo0n1L.d.ts} +2 -2
  99. package/dist/cli.d.ts +3 -3
  100. package/dist/cli.js +53 -53
  101. package/dist/compounding/engine.js +10 -10
  102. package/dist/connectors/codex-materialize-runner.js +10 -10
  103. package/dist/connectors/index.js +10 -10
  104. package/dist/convergence-refresh.js +12 -12
  105. package/dist/corpus-watermark.js +12 -12
  106. package/dist/entity-retrieval.js +10 -10
  107. package/dist/external-wiki-access.d.ts +1 -1
  108. package/dist/external-wiki-access.js +25 -25
  109. package/dist/external-wiki-mcp-tools.d.ts +1 -1
  110. package/dist/extraction.js +10 -10
  111. package/dist/harmonic-retrieval.js +1 -1
  112. package/dist/index.d.ts +681 -680
  113. package/dist/index.js +92 -76
  114. package/dist/lcm/index.js +3 -3
  115. package/dist/maintenance/memory-governance.js +10 -10
  116. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
  117. package/dist/maintenance/rebuild-memory-projection.js +11 -11
  118. package/dist/mcp-memory-inspector-app.d.ts +1 -1
  119. package/dist/memory-controller.d.ts +203 -0
  120. package/dist/memory-controller.js +23 -0
  121. package/dist/memory-controller.js.map +1 -0
  122. package/dist/memory-subject-cli.d.ts +1 -1
  123. package/dist/memory-subject.d.ts +1 -1
  124. package/dist/namespaces/migrate.js +11 -11
  125. package/dist/namespaces/search.js +7 -7
  126. package/dist/namespaces/storage.js +10 -10
  127. package/dist/operator-doctor-corpus.js +13 -13
  128. package/dist/operator-toolkit.js +18 -18
  129. package/dist/orchestration/maintenance.js +16 -16
  130. package/dist/orchestrator.js +69 -68
  131. package/dist/{public-http-DhIXYBYI.d.ts → public-http-BP3VQDl5.d.ts} +1 -1
  132. package/dist/schemas.d.ts +124 -124
  133. package/dist/search/factory.js +6 -6
  134. package/dist/search/index.js +11 -11
  135. package/dist/search/lancedb-backend.js +2 -2
  136. package/dist/search/meilisearch-backend.js +2 -2
  137. package/dist/search/orama-backend.js +2 -2
  138. package/dist/semantic-consolidation.js +11 -11
  139. package/dist/semantic-rule-promotion.js +10 -10
  140. package/dist/semantic-rule-verifier.js +10 -10
  141. package/dist/shared-context/manager.d.ts +6 -6
  142. package/dist/source-agent-qualifier.js +10 -10
  143. package/dist/storage.js +9 -9
  144. package/dist/support-passport/index.d.ts +4 -4
  145. package/dist/support-passport/index.js +27 -27
  146. package/dist/transfer/backup.js +2 -2
  147. package/dist/transfer/capsule-export.js +2 -2
  148. package/dist/transfer/capsule-import.js +2 -2
  149. package/dist/transfer/types.d.ts +78 -78
  150. package/dist/verified-recall.js +10 -10
  151. package/dist/who-knows-cli.d.ts +1 -1
  152. package/dist/who-knows-cli.js +11 -11
  153. package/dist/who-knows.d.ts +1 -1
  154. package/dist/who-knows.js +10 -10
  155. package/package.json +2 -2
  156. package/src/index.ts +3 -0
  157. package/src/memory-controller.test.ts +347 -0
  158. package/src/memory-controller.ts +547 -0
  159. package/src/review/frontmatter.test.ts +15 -0
  160. package/src/review/frontmatter.ts +20 -0
  161. package/src/review/review-deck-snapshot.ts +4 -20
  162. package/src/review/review-deck.ts +1 -12
  163. package/dist/chunk-AZLLH6YA.js.map +0 -1
  164. package/dist/{access-service-DqPa3hy4.d.ts → access-service-sbiNS5UB.d.ts} +64 -64
  165. /package/dist/{capsule-crypto-YO5QJ6L3.js.map → capsule-crypto-GWVG7LGC.js.map} +0 -0
  166. /package/dist/{chunk-ZPOHEB5Z.js.map → chunk-2JHRCWHT.js.map} +0 -0
  167. /package/dist/{chunk-BK5G2MHO.js.map → chunk-2RXUZVPU.js.map} +0 -0
  168. /package/dist/{chunk-JPAKBNTM.js.map → chunk-3I22VWB3.js.map} +0 -0
  169. /package/dist/{chunk-ECLJ4LA2.js.map → chunk-53MZQEBD.js.map} +0 -0
  170. /package/dist/{chunk-HF5BUTI6.js.map → chunk-5GIZM4RX.js.map} +0 -0
  171. /package/dist/{chunk-YHGCT462.js.map → chunk-5TG4MU2U.js.map} +0 -0
  172. /package/dist/{chunk-VDX2J7OX.js.map → chunk-5W7CTZ2E.js.map} +0 -0
  173. /package/dist/{chunk-IWKGOCL6.js.map → chunk-5W7MKXMU.js.map} +0 -0
  174. /package/dist/{chunk-YHCBJULX.js.map → chunk-6FUMA6AA.js.map} +0 -0
  175. /package/dist/{chunk-THVI4Y7X.js.map → chunk-6LS5OX3U.js.map} +0 -0
  176. /package/dist/{chunk-TVVEYCNW.js.map → chunk-7K5Q6COX.js.map} +0 -0
  177. /package/dist/{chunk-KPB2QHJZ.js.map → chunk-7OZSHBWK.js.map} +0 -0
  178. /package/dist/{chunk-CQBIN77D.js.map → chunk-7SSRXEZJ.js.map} +0 -0
  179. /package/dist/{chunk-NNBZS3DY.js.map → chunk-AG46P24C.js.map} +0 -0
  180. /package/dist/{chunk-QJW4MZSW.js.map → chunk-AYAZWXJI.js.map} +0 -0
  181. /package/dist/{chunk-WDXD6ITO.js.map → chunk-BXXOPKT5.js.map} +0 -0
  182. /package/dist/{chunk-DJZWNKFO.js.map → chunk-D35XLYQ7.js.map} +0 -0
  183. /package/dist/{chunk-KOO37E4Y.js.map → chunk-DYO24BNB.js.map} +0 -0
  184. /package/dist/{chunk-DORFF5N5.js.map → chunk-FEO2CDXR.js.map} +0 -0
  185. /package/dist/{chunk-IURMJBGP.js.map → chunk-HWVNYNIV.js.map} +0 -0
  186. /package/dist/{chunk-OZDFB22S.js.map → chunk-IDQ6DKXC.js.map} +0 -0
  187. /package/dist/{chunk-J3ATBB7M.js.map → chunk-IF4EY26E.js.map} +0 -0
  188. /package/dist/{chunk-W675UJCZ.js.map → chunk-IRXMJLTW.js.map} +0 -0
  189. /package/dist/{chunk-DUZARALI.js.map → chunk-JFWZRUKP.js.map} +0 -0
  190. /package/dist/{chunk-DUEDOYZD.js.map → chunk-JGG5HVI2.js.map} +0 -0
  191. /package/dist/{chunk-3NH3VP3U.js.map → chunk-KBOG7FJV.js.map} +0 -0
  192. /package/dist/{chunk-UCKG36HO.js.map → chunk-LSYD7GHZ.js.map} +0 -0
  193. /package/dist/{chunk-6433HV72.js.map → chunk-MVIYRRVJ.js.map} +0 -0
  194. /package/dist/{chunk-GHD2LLG4.js.map → chunk-NLUCDKLT.js.map} +0 -0
  195. /package/dist/{chunk-TJFI3K2O.js.map → chunk-O4BAGJDN.js.map} +0 -0
  196. /package/dist/{chunk-LYBIHM4N.js.map → chunk-OMZLBT4B.js.map} +0 -0
  197. /package/dist/{chunk-BXLOS5AJ.js.map → chunk-OWHERGF2.js.map} +0 -0
  198. /package/dist/{chunk-I23ZHYSL.js.map → chunk-PGW64IFQ.js.map} +0 -0
  199. /package/dist/{chunk-YDKF4MSJ.js.map → chunk-QMZY3GG6.js.map} +0 -0
  200. /package/dist/{chunk-N37X5RU7.js.map → chunk-RACZB5HT.js.map} +0 -0
  201. /package/dist/{chunk-YZJM6CLF.js.map → chunk-ROEAEANL.js.map} +0 -0
  202. /package/dist/{chunk-SR5LNI6Q.js.map → chunk-RQ2EQRRR.js.map} +0 -0
  203. /package/dist/{chunk-2IXQSGCU.js.map → chunk-SR7JIRAR.js.map} +0 -0
  204. /package/dist/{chunk-OCCHUEZB.js.map → chunk-TWBQQ3FT.js.map} +0 -0
  205. /package/dist/{chunk-NLEH4RTB.js.map → chunk-US4IRASK.js.map} +0 -0
  206. /package/dist/{chunk-DQEMWVMT.js.map → chunk-UVYI6VIX.js.map} +0 -0
  207. /package/dist/{chunk-PTZQYCJ4.js.map → chunk-W6J4POB6.js.map} +0 -0
  208. /package/dist/{chunk-OU34IQXV.js.map → chunk-X2DWBWOX.js.map} +0 -0
  209. /package/dist/{chunk-2MVTAIL3.js.map → chunk-XAWIL7TC.js.map} +0 -0
  210. /package/dist/{chunk-UFR6HX7A.js.map → chunk-XUZ5CIEE.js.map} +0 -0
  211. /package/dist/{chunk-GIC6BASP.js.map → chunk-XZBXINXZ.js.map} +0 -0
  212. /package/dist/{chunk-XGM3VQWG.js.map → chunk-YUTTMSC7.js.map} +0 -0
  213. /package/dist/{chunk-3JZBPTLD.js.map → chunk-YWBOOBDP.js.map} +0 -0
  214. /package/dist/{chunk-KFIOPZ25.js.map → chunk-ZXUZ54Z5.js.map} +0 -0
@@ -0,0 +1,547 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { planRecallMode } from "./intent.js";
3
+ import { evaluateMemoryActionPolicy } from "./memory-action-policy.js";
4
+ import type { RuntimePolicyValues } from "./policy-runtime.js";
5
+ import type { UtilityRuntimeValues } from "./utility-runtime.js";
6
+ import type { MemoryActionEligibilityContext, MemoryActionType, RecallPlanMode } from "./types.js";
7
+
8
+ /**
9
+ * Gated unified memory controller (#2348).
10
+ *
11
+ * One state enters, one choice leaves. Host-free: every effectful collaborator
12
+ * (adapters, executors, report reader, recorder, telemetry, clock) is injected.
13
+ * The coordinator creates no store and claims no counterfactual lift.
14
+ */
15
+
16
+ export type MemoryControllerMode = "off" | "shadow" | "active";
17
+
18
+ export type MemoryControllerActionFamily = "persistent_memory" | "recall" | "active_context" | "no_op";
19
+
20
+ /** #2347 adapter seam: the host supplies plans, core only picks one. */
21
+ export interface ActiveContextMessage {
22
+ id: string;
23
+ text: string;
24
+ }
25
+
26
+ export interface ActiveContextPlan {
27
+ transform: "SUMMARY" | "FILTER";
28
+ messageIds: string[];
29
+ planId: string;
30
+ }
31
+
32
+ export interface ActiveContextAdapter {
33
+ plan(messages: ActiveContextMessage[]): ActiveContextPlan | null;
34
+ }
35
+
36
+ /** #2345 report + #2346 paired-seed evidence, read through one port. */
37
+ export interface MemoryControllerEvidenceReport {
38
+ status: "pass" | "fail";
39
+ version: string;
40
+ configHash: string;
41
+ generatedAt: string;
42
+ /** sha256 over the canonical report fields; recomputed on verification. */
43
+ reportHash: string;
44
+ }
45
+
46
+ export interface MemoryControllerPairedSeedEvidence {
47
+ status: "pass" | "fail";
48
+ seedCount: number;
49
+ generatedAt: string;
50
+ }
51
+
52
+ export interface MemoryControllerEvidence {
53
+ report: MemoryControllerEvidenceReport;
54
+ pairedSeed: MemoryControllerPairedSeedEvidence;
55
+ }
56
+
57
+ export interface MemoryControllerReportReader {
58
+ read(): Promise<MemoryControllerEvidence | null>;
59
+ }
60
+
61
+ export interface MemoryControllerReceipt {
62
+ decisionId: string;
63
+ ok: boolean;
64
+ detail?: string;
65
+ }
66
+
67
+ export interface MemoryControllerExecutors {
68
+ executePersistentMemory?(input: {
69
+ decisionId: string;
70
+ action: MemoryActionType;
71
+ eligibility: MemoryActionEligibilityContext;
72
+ stateHash: string;
73
+ }): Promise<MemoryControllerReceipt>;
74
+ executeRecall?(input: { decisionId: string; mode: RecallPlanMode }): Promise<MemoryControllerReceipt>;
75
+ executeActiveContext?(input: {
76
+ decisionId: string;
77
+ plan: ActiveContextPlan;
78
+ }): Promise<MemoryControllerReceipt>;
79
+ }
80
+
81
+ export interface MemoryControllerEvent {
82
+ schemaVersion: 1;
83
+ phase: "choice" | "outcome";
84
+ decisionId: string;
85
+ timestamp: string;
86
+ requestedMode: MemoryControllerMode;
87
+ effectiveMode: MemoryControllerMode;
88
+ stateHash: string;
89
+ choice: MemoryControllerChoice;
90
+ scores: Record<MemoryControllerActionFamily, number>;
91
+ executed: boolean;
92
+ reviewOnly?: boolean;
93
+ demotionReasons?: string[];
94
+ failureClass?: "record_failed" | "executor_error" | "bad_receipt" | "no_executor";
95
+ receipt?: MemoryControllerReceipt;
96
+ }
97
+
98
+ export interface MemoryControllerRecorder {
99
+ record(event: MemoryControllerEvent): Promise<void>;
100
+ /** Prior shadow choice records; active promotion requires shadow history. */
101
+ countShadowRecords(): Promise<number>;
102
+ }
103
+
104
+ export interface MemoryControllerConfig {
105
+ mode: MemoryControllerMode;
106
+ /** Expected #2345 report schema version. */
107
+ reportVersion: string;
108
+ /** Evidence older than this is stale and forces shadow. */
109
+ evidenceMaxAgeMs: number;
110
+ /** Paired-seed arms must cover at least this many seeds (#2346). */
111
+ minPairedSeeds: number;
112
+ /** Active promotion requires at least this many prior shadow records. */
113
+ shadowMinRecords: number;
114
+ }
115
+
116
+ export interface MemoryControllerState {
117
+ prompt: string;
118
+ persistentMemoryCandidate?: {
119
+ action: MemoryActionType;
120
+ eligibility: MemoryActionEligibilityContext;
121
+ };
122
+ contextMessages?: ActiveContextMessage[];
123
+ /** 0..1 host-measured context pressure. */
124
+ contextPressure?: number;
125
+ }
126
+
127
+ export type MemoryControllerChoice =
128
+ | { family: "persistent_memory"; action: MemoryActionType; eligibility: MemoryActionEligibilityContext }
129
+ | { family: "recall"; mode: RecallPlanMode }
130
+ | { family: "active_context"; plan: ActiveContextPlan }
131
+ | { family: "no_op" };
132
+
133
+ export interface MemoryControllerRunResult {
134
+ decisionId: string;
135
+ requestedMode: MemoryControllerMode;
136
+ effectiveMode: MemoryControllerMode;
137
+ stateHash: string;
138
+ choice: MemoryControllerChoice;
139
+ scores: Record<MemoryControllerActionFamily, number>;
140
+ executed: boolean;
141
+ reviewOnly: boolean;
142
+ recorded: boolean;
143
+ receipt?: MemoryControllerReceipt;
144
+ demotionReasons: string[];
145
+ }
146
+
147
+ export interface MemoryControllerDeps {
148
+ config: MemoryControllerConfig;
149
+ reportReader?: MemoryControllerReportReader;
150
+ recorder?: MemoryControllerRecorder;
151
+ executors?: MemoryControllerExecutors;
152
+ activeContextAdapter?: ActiveContextAdapter;
153
+ policyRuntime?: { loadRuntimeValues(): Promise<RuntimePolicyValues | null> };
154
+ readUtilityRuntime?: () => Promise<UtilityRuntimeValues | null>;
155
+ telemetry?: (event: MemoryControllerEvent) => void;
156
+ clock?: () => Date;
157
+ }
158
+
159
+ const NO_OP_FLOOR = 0.35;
160
+ /** `discard` (and any destructive change) stays review-only in active mode. */
161
+ const REVIEW_ONLY_ACTIONS: Partial<Record<MemoryActionType, true>> = { discard: true };
162
+
163
+ export function controllerConfigHash(config: MemoryControllerConfig): string {
164
+ return sha256(
165
+ JSON.stringify({
166
+ mode: config.mode,
167
+ reportVersion: config.reportVersion,
168
+ evidenceMaxAgeMs: config.evidenceMaxAgeMs,
169
+ minPairedSeeds: config.minPairedSeeds,
170
+ shadowMinRecords: config.shadowMinRecords,
171
+ })
172
+ );
173
+ }
174
+
175
+ export function hashControllerState(state: MemoryControllerState): string {
176
+ return sha256(
177
+ JSON.stringify({
178
+ prompt: state.prompt,
179
+ persistentMemoryCandidate: state.persistentMemoryCandidate ?? null,
180
+ contextMessages: state.contextMessages ?? null,
181
+ contextPressure: state.contextPressure ?? null,
182
+ })
183
+ );
184
+ }
185
+
186
+ /** Canonical #2345 report hash; producers sign with this, the controller verifies. */
187
+ export function computeEvidenceReportHash(fields: {
188
+ status: MemoryControllerEvidenceReport["status"];
189
+ version: string;
190
+ configHash: string;
191
+ generatedAt: string;
192
+ }): string {
193
+ return sha256(JSON.stringify(fields));
194
+ }
195
+
196
+ /** Verifies the #2345 report hash over its canonical fields. */
197
+ export function verifyEvidenceReport(report: MemoryControllerEvidenceReport): boolean {
198
+ return (
199
+ computeEvidenceReportHash({
200
+ status: report.status,
201
+ version: report.version,
202
+ configHash: report.configHash,
203
+ generatedAt: report.generatedAt,
204
+ }) === report.reportHash
205
+ );
206
+ }
207
+
208
+ function sha256(input: string): string {
209
+ return createHash("sha256").update(input).digest("hex");
210
+ }
211
+
212
+ function clampScore(value: number): number {
213
+ if (!Number.isFinite(value)) return Number.NaN;
214
+ return Math.max(0, Math.min(1, value));
215
+ }
216
+
217
+ /**
218
+ * Bad scores fail closed to `no_op`.
219
+ */
220
+ export function chooseAction(input: {
221
+ state: MemoryControllerState;
222
+ activeContextAdapter?: ActiveContextAdapter;
223
+ runtimeValues?: RuntimePolicyValues | null;
224
+ utilityValues?: UtilityRuntimeValues | null;
225
+ }): { choice: MemoryControllerChoice; scores: Record<MemoryControllerActionFamily, number> } {
226
+ const { state, activeContextAdapter, runtimeValues, utilityValues } = input;
227
+
228
+ // recall: current recall path.
229
+ const recallMode = planRecallMode(state.prompt ?? "");
230
+ const recallScore =
231
+ recallMode === "no_recall" ? 0 : recallMode === "minimal" ? 0.4 : 0.6 + 0.2 * (runtimeValues?.recencyWeight ?? 0);
232
+
233
+ // persistent_memory: current action path + policy.
234
+ let persistentScore = 0;
235
+ const candidate = state.persistentMemoryCandidate;
236
+ if (candidate) {
237
+ const policy = evaluateMemoryActionPolicy({
238
+ action: candidate.action,
239
+ eligibility: candidate.eligibility,
240
+ options: { actionsEnabled: true, maxCompressionTokensPerHour: Number.POSITIVE_INFINITY },
241
+ });
242
+ if (policy.decision === "allow") {
243
+ persistentScore = 0.4 + 0.4 * (candidate.eligibility.confidence ?? 0);
244
+ } else if (policy.decision === "defer") {
245
+ persistentScore = 0.2;
246
+ }
247
+ // Utility runtime may suppress the persistent family.
248
+ if (utilityValues && utilityValues.rankingSuppressMultiplier > 1) {
249
+ persistentScore *= 1 / utilityValues.rankingSuppressMultiplier;
250
+ }
251
+ }
252
+
253
+ // active_context: current context path through the #2347 adapter.
254
+ let contextScore = 0;
255
+ let contextPlan: ActiveContextPlan | null = null;
256
+ const pressure = state.contextPressure;
257
+ if (activeContextAdapter && typeof pressure === "number" && Number.isFinite(pressure) && pressure > 0.5) {
258
+ contextPlan = activeContextAdapter.plan(state.contextMessages ?? []);
259
+ if (contextPlan && contextPlan.messageIds.length > 0) {
260
+ contextScore = 0.3 + 0.5 * Math.max(0, Math.min(1, pressure));
261
+ }
262
+ }
263
+
264
+ const scores: Record<MemoryControllerActionFamily, number> = {
265
+ recall: clampScore(recallScore),
266
+ persistent_memory: clampScore(persistentScore),
267
+ active_context: clampScore(contextScore),
268
+ no_op: NO_OP_FLOOR,
269
+ };
270
+
271
+ // Bad scores fail closed.
272
+ if (Object.values(scores).some((score) => !Number.isFinite(score) || score < 0 || score > 1)) {
273
+ return { choice: { family: "no_op" }, scores };
274
+ }
275
+
276
+ let choice: MemoryControllerChoice = { family: "no_op" };
277
+ let best = scores.no_op;
278
+ if (scores.recall > best) {
279
+ best = scores.recall;
280
+ choice = { family: "recall", mode: recallMode };
281
+ }
282
+ if (scores.persistent_memory > best) {
283
+ best = scores.persistent_memory;
284
+ choice = {
285
+ family: "persistent_memory",
286
+ action: candidate!.action,
287
+ eligibility: candidate!.eligibility,
288
+ };
289
+ }
290
+ if (scores.active_context > best) {
291
+ choice = { family: "active_context", plan: contextPlan! };
292
+ }
293
+ return { choice, scores };
294
+ }
295
+
296
+ /** Returns the demotion reasons when active-mode gates fail; empty means go. */
297
+ export async function evaluateActiveGates(input: {
298
+ config: MemoryControllerConfig;
299
+ reportReader?: MemoryControllerReportReader;
300
+ recorder?: MemoryControllerRecorder;
301
+ consecutiveReceiptFailures: number;
302
+ now: Date;
303
+ }): Promise<string[]> {
304
+ const { config, reportReader, recorder, consecutiveReceiptFailures, now } = input;
305
+ const reasons: string[] = [];
306
+
307
+ if (!reportReader) return ["no_report_reader"];
308
+
309
+ const evidence = await reportReader.read();
310
+ if (!evidence) return ["no_evidence"];
311
+
312
+ const { report, pairedSeed } = evidence;
313
+ if (report.status !== "pass") reasons.push("report_not_passing");
314
+ if (report.version !== config.reportVersion) reasons.push("report_version_mismatch");
315
+ if (report.configHash !== controllerConfigHash(config)) reasons.push("report_config_unbound");
316
+ if (!verifyEvidenceReport(report)) reasons.push("report_hash_invalid");
317
+ const reportGeneratedAt = Date.parse(report.generatedAt);
318
+ if (!Number.isFinite(reportGeneratedAt) || now.getTime() - reportGeneratedAt > config.evidenceMaxAgeMs) {
319
+ reasons.push("report_stale");
320
+ }
321
+
322
+ if (pairedSeed.status !== "pass") reasons.push("paired_seed_not_passing");
323
+ if (pairedSeed.seedCount < config.minPairedSeeds) reasons.push("paired_seed_count_low");
324
+ const seedGeneratedAt = Date.parse(pairedSeed.generatedAt);
325
+ if (!Number.isFinite(seedGeneratedAt) || now.getTime() - seedGeneratedAt > config.evidenceMaxAgeMs) {
326
+ reasons.push("paired_seed_stale");
327
+ }
328
+
329
+ const shadowRecords = recorder ? await recorder.countShadowRecords() : 0;
330
+ if (shadowRecords < config.shadowMinRecords) reasons.push("shadow_history_insufficient");
331
+
332
+ if (consecutiveReceiptFailures > 0) reasons.push("recent_receipt_failures");
333
+
334
+ return reasons;
335
+ }
336
+
337
+ export class MemoryControllerCoordinator {
338
+ private readonly deps: MemoryControllerDeps;
339
+ private readonly clock: () => Date;
340
+ private consecutiveReceiptFailures = 0;
341
+
342
+ constructor(deps: MemoryControllerDeps) {
343
+ this.deps = deps;
344
+ this.clock = deps.clock ?? (() => new Date());
345
+ }
346
+
347
+ async run(state: MemoryControllerState): Promise<MemoryControllerRunResult> {
348
+ const decisionId = randomUUID();
349
+ const stateHash = hashControllerState(state);
350
+ const requestedMode = this.deps.config.mode;
351
+
352
+ // off: no choice, no read, no write, no call.
353
+ if (requestedMode === "off") {
354
+ return {
355
+ decisionId,
356
+ requestedMode,
357
+ effectiveMode: "off",
358
+ stateHash,
359
+ choice: { family: "no_op" },
360
+ scores: { persistent_memory: 0, recall: 0, active_context: 0, no_op: 0 },
361
+ executed: false,
362
+ reviewOnly: false,
363
+ recorded: false,
364
+ demotionReasons: ["mode_off"],
365
+ };
366
+ }
367
+
368
+ const [runtimeValues, utilityValues] = await Promise.all([
369
+ this.deps.policyRuntime?.loadRuntimeValues() ?? null,
370
+ this.deps.readUtilityRuntime?.() ?? null,
371
+ ]);
372
+ const { choice, scores } = chooseAction({
373
+ state,
374
+ activeContextAdapter: this.deps.activeContextAdapter,
375
+ runtimeValues,
376
+ utilityValues,
377
+ });
378
+
379
+ let demotionReasons: string[] = [];
380
+ let effectiveMode = requestedMode;
381
+ if (requestedMode === "active") {
382
+ demotionReasons = await evaluateActiveGates({
383
+ config: this.deps.config,
384
+ reportReader: this.deps.reportReader,
385
+ recorder: this.deps.recorder,
386
+ consecutiveReceiptFailures: this.consecutiveReceiptFailures,
387
+ now: this.clock(),
388
+ });
389
+ if (demotionReasons.length > 0) effectiveMode = "shadow";
390
+ }
391
+
392
+ const baseEvent: MemoryControllerEvent = {
393
+ schemaVersion: 1,
394
+ phase: "choice",
395
+ decisionId,
396
+ timestamp: this.clock().toISOString(),
397
+ requestedMode,
398
+ effectiveMode,
399
+ stateHash,
400
+ choice,
401
+ scores,
402
+ executed: false,
403
+ ...(demotionReasons.length > 0 ? { demotionReasons } : {}),
404
+ };
405
+
406
+ // Shadow records before any active dispatch.
407
+ let recorded = false;
408
+ if (this.deps.recorder) {
409
+ try {
410
+ await this.deps.recorder.record(baseEvent);
411
+ this.deps.telemetry?.(baseEvent);
412
+ recorded = true;
413
+ } catch {
414
+ // Bad recorder stops work: no dispatch, no outcome event.
415
+ return {
416
+ decisionId,
417
+ requestedMode,
418
+ effectiveMode,
419
+ stateHash,
420
+ choice,
421
+ scores,
422
+ executed: false,
423
+ reviewOnly: false,
424
+ recorded: false,
425
+ demotionReasons: [...demotionReasons, "record_failed"],
426
+ };
427
+ }
428
+ }
429
+
430
+ if (effectiveMode !== "active") {
431
+ return {
432
+ decisionId,
433
+ requestedMode,
434
+ effectiveMode,
435
+ stateHash,
436
+ choice,
437
+ scores,
438
+ executed: false,
439
+ reviewOnly: false,
440
+ recorded,
441
+ demotionReasons,
442
+ };
443
+ }
444
+
445
+ // First active scope: reversible actions only.
446
+ if (choice.family === "persistent_memory" && REVIEW_ONLY_ACTIONS[choice.action]) {
447
+ const event: MemoryControllerEvent = {
448
+ ...baseEvent,
449
+ phase: "outcome",
450
+ reviewOnly: true,
451
+ demotionReasons: ["review_only_action"],
452
+ };
453
+ await this.recordOutcome(event);
454
+ return {
455
+ decisionId,
456
+ requestedMode,
457
+ effectiveMode,
458
+ stateHash,
459
+ choice,
460
+ scores,
461
+ executed: false,
462
+ reviewOnly: true,
463
+ recorded,
464
+ demotionReasons,
465
+ };
466
+ }
467
+
468
+ const receipt = await this.dispatch(choice, stateHash, decisionId, baseEvent);
469
+ return {
470
+ decisionId,
471
+ requestedMode,
472
+ effectiveMode,
473
+ stateHash,
474
+ choice,
475
+ scores,
476
+ executed: receipt?.ok === true,
477
+ reviewOnly: false,
478
+ recorded,
479
+ ...(receipt ? { receipt } : {}),
480
+ demotionReasons,
481
+ };
482
+ }
483
+
484
+ private async dispatch(
485
+ choice: MemoryControllerChoice,
486
+ stateHash: string,
487
+ decisionId: string,
488
+ baseEvent: MemoryControllerEvent
489
+ ): Promise<MemoryControllerReceipt | undefined> {
490
+ const executors = this.deps.executors ?? {};
491
+ try {
492
+ let receipt: MemoryControllerReceipt | undefined;
493
+ if (choice.family === "persistent_memory") {
494
+ if (!executors.executePersistentMemory) throw new Error("no_executor:persistent_memory");
495
+ receipt = await executors.executePersistentMemory({
496
+ decisionId,
497
+ action: choice.action,
498
+ eligibility: choice.eligibility,
499
+ stateHash,
500
+ });
501
+ } else if (choice.family === "recall") {
502
+ if (!executors.executeRecall) throw new Error("no_executor:recall");
503
+ receipt = await executors.executeRecall({ decisionId, mode: choice.mode });
504
+ } else if (choice.family === "active_context") {
505
+ if (!executors.executeActiveContext) throw new Error("no_executor:active_context");
506
+ receipt = await executors.executeActiveContext({ decisionId, plan: choice.plan });
507
+ } else {
508
+ // no_op executed trivially; no executor call.
509
+ receipt = { decisionId, ok: true };
510
+ }
511
+ if (!isValidReceipt(receipt, decisionId)) {
512
+ this.consecutiveReceiptFailures += 1;
513
+ await this.recordOutcome({ ...baseEvent, phase: "outcome", failureClass: "bad_receipt" });
514
+ return undefined;
515
+ }
516
+ this.consecutiveReceiptFailures = 0;
517
+ await this.recordOutcome({ ...baseEvent, phase: "outcome", executed: receipt.ok, receipt });
518
+ return receipt;
519
+ } catch (error) {
520
+ this.consecutiveReceiptFailures += 1;
521
+ await this.recordOutcome({
522
+ ...baseEvent,
523
+ phase: "outcome",
524
+ failureClass: (error as Error)?.message?.startsWith("no_executor:") ? "no_executor" : "executor_error",
525
+ });
526
+ return undefined;
527
+ }
528
+ }
529
+
530
+ private async recordOutcome(event: MemoryControllerEvent): Promise<void> {
531
+ if (!this.deps.recorder) return;
532
+ await this.deps.recorder.record(event);
533
+ this.deps.telemetry?.(event);
534
+ }
535
+ }
536
+
537
+ function isValidReceipt(receipt: unknown, decisionId: string): boolean {
538
+ return (
539
+ typeof receipt === "object" &&
540
+ receipt !== null &&
541
+ (receipt as MemoryControllerReceipt).decisionId === decisionId &&
542
+ typeof (receipt as MemoryControllerReceipt).ok === "boolean"
543
+ );
544
+ }
545
+
546
+ // ponytail: consecutiveReceiptFailures is per-instance, not persisted; persist
547
+ // with the recorder if coordinator restarts must carry receipt health forward.
@@ -0,0 +1,15 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import { parseFrontmatterFields, splitMarkdownFrontmatter } from "./frontmatter.js";
5
+
6
+ test("splitMarkdownFrontmatter uses indexOf, not a ReDoS regex", () => {
7
+ const split = splitMarkdownFrontmatter("---\nid: a\n---\nbody");
8
+ assert.deepEqual(split, { fields: "id: a", body: "body" });
9
+ assert.equal(splitMarkdownFrontmatter("no fence"), null);
10
+ });
11
+
12
+ test("parseFrontmatterFields reads key: value lines", () => {
13
+ assert.equal(parseFrontmatterFields("---\nid: mem-1\n---\n").id, "mem-1");
14
+ assert.deepEqual(parseFrontmatterFields("plain"), {});
15
+ });
@@ -0,0 +1,20 @@
1
+ export function splitMarkdownFrontmatter(content: string): { fields: string; body: string } | null {
2
+ if (!content.startsWith("---\n")) return null;
3
+ const end = content.indexOf("\n---", 4);
4
+ if (end === -1) return null;
5
+ const after = end + "\n---".length;
6
+ const body = content.startsWith("\n", after) ? content.slice(after + 1) : content.slice(after);
7
+ return { fields: content.slice(4, end), body };
8
+ }
9
+
10
+ export function parseFrontmatterFields(content: string): Record<string, string> {
11
+ const split = splitMarkdownFrontmatter(content);
12
+ if (!split) return {};
13
+ const fields: Record<string, string> = {};
14
+ for (const line of split.fields.split("\n")) {
15
+ const colonIdx = line.indexOf(":");
16
+ if (colonIdx === -1) continue;
17
+ fields[line.slice(0, colonIdx).trim()] = line.slice(colonIdx + 1).trim();
18
+ }
19
+ return fields;
20
+ }
@@ -6,6 +6,7 @@ import {
6
6
  type ReviewDeckSnapshot,
7
7
  type ReviewDeckSourceRow,
8
8
  } from "./review-deck.js";
9
+ import { parseFrontmatterFields, splitMarkdownFrontmatter } from "./frontmatter.js";
9
10
 
10
11
  const QUEUE_DIRS = ["suggestions", "review"] as const;
11
12
 
@@ -147,30 +148,13 @@ function readFileSafe(filePath: string): string | null {
147
148
  }
148
149
  }
149
150
 
150
- function splitFrontmatter(content: string): { fields: string; body: string } | null {
151
- if (!content.startsWith("---\n")) return null;
152
- const end = content.indexOf("\n---", 4);
153
- if (end === -1) return null;
154
- const after = end + "\n---".length;
155
- const body = content.startsWith("\n", after) ? content.slice(after + 1) : content.slice(after);
156
- return { fields: content.slice(4, end), body };
157
- }
158
-
159
151
  function parseFrontmatter(content: string): Record<string, unknown> | null {
160
- const split = splitFrontmatter(content);
161
- if (!split) return null;
162
- const fm: Record<string, unknown> = {};
163
- for (const line of split.fields.split("\n")) {
164
- const colonIdx = line.indexOf(":");
165
- if (colonIdx === -1) continue;
166
- fm[line.slice(0, colonIdx).trim()] = line.slice(colonIdx + 1).trim();
167
- }
168
- return fm;
152
+ if (!content.startsWith("---\n")) return null;
153
+ return parseFrontmatterFields(content);
169
154
  }
170
155
 
171
156
  function extractBody(content: string): string {
172
- const split = splitFrontmatter(content);
173
- return split ? split.body.trim() : content.trim();
157
+ return splitMarkdownFrontmatter(content)?.body.trim() ?? content.trim();
174
158
  }
175
159
 
176
160
  function parseBoolean(value: unknown): boolean {
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { parseFrontmatterFields } from "./frontmatter.js";
2
3
 
3
4
  export type ReviewDeckChoice = "keep" | "prepare_fix" | "not_true";
4
5
  export type ReviewDeckRisk = "reversible";
@@ -255,18 +256,6 @@ function provenanceFromRow(row: ReviewDeckSourceRow): ReviewDeckEvidence[] {
255
256
  return provenance;
256
257
  }
257
258
 
258
- function parseFrontmatterFields(content: string): Record<string, string> {
259
- if (!content.startsWith("---\n")) return {};
260
- const end = content.indexOf("\n---", 4);
261
- if (end === -1) return {};
262
- const fields: Record<string, string> = {};
263
- for (const line of content.slice(4, end).split("\n")) {
264
- const colonIdx = line.indexOf(":");
265
- if (colonIdx === -1) continue;
266
- fields[line.slice(0, colonIdx).trim()] = line.slice(colonIdx + 1).trim();
267
- }
268
- return fields;
269
- }
270
259
 
271
260
  function idList(value: string | undefined): string[] {
272
261
  if (value === undefined || value.length === 0) return [];