@remnic/core 10.0.166 → 10.0.168

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 (66) hide show
  1. package/dist/access-admin-ops-surface.js +6 -6
  2. package/dist/access-cli.js +6 -6
  3. package/dist/access-extraction-force-flush-preempt.js +6 -6
  4. package/dist/access-extraction-force-flush.js +6 -6
  5. package/dist/access-http-briefing.js +6 -6
  6. package/dist/access-http-query.js +6 -6
  7. package/dist/access-http.js +6 -6
  8. package/dist/access-identity-continuity-surface.js +6 -6
  9. package/dist/access-lcm-surface.js +6 -6
  10. package/dist/access-mcp.js +6 -6
  11. package/dist/access-observe-write-surface.js +6 -6
  12. package/dist/access-operations-batch.js +6 -6
  13. package/dist/access-operations.js +6 -6
  14. package/dist/access-recall-concurrency.js +6 -6
  15. package/dist/access-recall-response.js +6 -6
  16. package/dist/access-recall-surface.d.ts.map +1 -1
  17. package/dist/access-recall-surface.js +6 -6
  18. package/dist/access-service.js +6 -6
  19. package/dist/bulk-import/index.d.ts +1 -1
  20. package/dist/bulk-import/index.d.ts.map +1 -1
  21. package/dist/bulk-import/index.js +3 -1
  22. package/dist/bulk-import/pipeline.d.ts +8 -0
  23. package/dist/bulk-import/pipeline.d.ts.map +1 -1
  24. package/dist/{chunk-HSSERO3E.js → chunk-4P4GF76E.js} +8 -1
  25. package/dist/chunk-4P4GF76E.js.map +1 -0
  26. package/dist/{chunk-47LDDGAL.js → chunk-5PUZV73Z.js} +2 -2
  27. package/dist/{chunk-7QF26EWO.js → chunk-BFPQJNFZ.js} +1 -1
  28. package/dist/{chunk-7QF26EWO.js.map → chunk-BFPQJNFZ.js.map} +1 -1
  29. package/dist/{chunk-2FCZIWRI.js → chunk-D6BOOYNJ.js} +7 -15
  30. package/dist/{chunk-2FCZIWRI.js.map → chunk-D6BOOYNJ.js.map} +1 -1
  31. package/dist/{chunk-XKZBZOKV.js → chunk-JIF22AXI.js} +18 -1
  32. package/dist/chunk-JIF22AXI.js.map +1 -0
  33. package/dist/{chunk-E6EESRJ6.js → chunk-MOUSHJAR.js} +3 -3
  34. package/dist/{chunk-JFZZDMEZ.js → chunk-U3BCW7GX.js} +2 -2
  35. package/dist/cli.d.ts +1 -6
  36. package/dist/cli.d.ts.map +1 -1
  37. package/dist/cli.js +6 -6
  38. package/dist/connectors/droid-mcp.d.ts +4 -3
  39. package/dist/connectors/droid-mcp.d.ts.map +1 -1
  40. package/dist/connectors/index.js +1 -1
  41. package/dist/explicit-capture.js +6 -6
  42. package/dist/extraction.js +3 -3
  43. package/dist/index.js +6 -6
  44. package/dist/memory-controller.d.ts +8 -0
  45. package/dist/memory-controller.d.ts.map +1 -1
  46. package/dist/memory-controller.js +1 -1
  47. package/dist/orchestration/backlog-scheduler.js +7 -7
  48. package/dist/orchestration/buffer-drain-runner.js +7 -7
  49. package/dist/orchestrator.js +6 -6
  50. package/dist/recall-navigation.js +6 -6
  51. package/dist/source-agent-qualifier.js +2 -2
  52. package/package.json +2 -2
  53. package/src/access-recall-surface.ts +3 -10
  54. package/src/bulk-import/index.ts +1 -0
  55. package/src/bulk-import/pipeline.test.ts +31 -0
  56. package/src/bulk-import/pipeline.ts +14 -0
  57. package/src/cli.ts +3 -23
  58. package/src/connectors/droid-mcp.test.ts +46 -0
  59. package/src/connectors/droid-mcp.ts +5 -5
  60. package/src/memory-controller.test.ts +38 -0
  61. package/src/memory-controller.ts +25 -2
  62. package/dist/chunk-HSSERO3E.js.map +0 -1
  63. package/dist/chunk-XKZBZOKV.js.map +0 -1
  64. /package/dist/{chunk-47LDDGAL.js.map → chunk-5PUZV73Z.js.map} +0 -0
  65. /package/dist/{chunk-E6EESRJ6.js.map → chunk-MOUSHJAR.js.map} +0 -0
  66. /package/dist/{chunk-JFZZDMEZ.js.map → chunk-U3BCW7GX.js.map} +0 -0
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  BufferDrainRunner,
3
3
  ClaimBufferStorage
4
- } from "../chunk-E6EESRJ6.js";
5
- import "../chunk-2FCZIWRI.js";
4
+ } from "../chunk-MOUSHJAR.js";
5
+ import "../chunk-D6BOOYNJ.js";
6
6
  import "../chunk-TH6OYP6I.js";
7
7
  import "../chunk-PQM3B54K.js";
8
8
  import "../chunk-2MWKUVHT.js";
@@ -67,7 +67,7 @@ import "../chunk-JVBAPAWZ.js";
67
67
  import "../chunk-6O3SGRJD.js";
68
68
  import "../chunk-WWQMZBDI.js";
69
69
  import "../chunk-SI36RWC3.js";
70
- import "../chunk-HSSERO3E.js";
70
+ import "../chunk-4P4GF76E.js";
71
71
  import "../chunk-NOUJNHWG.js";
72
72
  import "../chunk-3PNJZTDV.js";
73
73
  import "../chunk-SQXCUH4L.js";
@@ -167,7 +167,7 @@ import "../chunk-573TEZCD.js";
167
167
  import "../chunk-3GPTTA4J.js";
168
168
  import "../chunk-UD7UNYRD.js";
169
169
  import "../chunk-IISBCCWR.js";
170
- import "../chunk-XKZBZOKV.js";
170
+ import "../chunk-JIF22AXI.js";
171
171
  import "../chunk-E4RMZGRS.js";
172
172
  import "../chunk-MZUQVWVC.js";
173
173
  import "../chunk-M4DB6ZNN.js";
@@ -195,10 +195,10 @@ import "../chunk-64NJRYU2.js";
195
195
  import "../chunk-U2PSE7MB.js";
196
196
  import "../chunk-BPPUH5JM.js";
197
197
  import "../chunk-LEO4MQ3S.js";
198
- import "../chunk-47LDDGAL.js";
198
+ import "../chunk-5PUZV73Z.js";
199
199
  import "../chunk-EI6V5UXY.js";
200
- import "../chunk-JFZZDMEZ.js";
201
- import "../chunk-7QF26EWO.js";
200
+ import "../chunk-U3BCW7GX.js";
201
+ import "../chunk-BFPQJNFZ.js";
202
202
  import "../chunk-SMDZTJ2D.js";
203
203
  import "../chunk-54V4BZWP.js";
204
204
  import "../chunk-DOWACHYO.js";
@@ -6,7 +6,7 @@ import {
6
6
  mergeGraphExpandedResults,
7
7
  qmdStartupCollectionChecksWithTimeout,
8
8
  resolveEffectiveIdentityInjectionMode
9
- } from "./chunk-2FCZIWRI.js";
9
+ } from "./chunk-D6BOOYNJ.js";
10
10
  import "./chunk-TH6OYP6I.js";
11
11
  import "./chunk-PQM3B54K.js";
12
12
  import "./chunk-2MWKUVHT.js";
@@ -73,7 +73,7 @@ import "./chunk-JVBAPAWZ.js";
73
73
  import "./chunk-6O3SGRJD.js";
74
74
  import "./chunk-WWQMZBDI.js";
75
75
  import "./chunk-SI36RWC3.js";
76
- import "./chunk-HSSERO3E.js";
76
+ import "./chunk-4P4GF76E.js";
77
77
  import "./chunk-NOUJNHWG.js";
78
78
  import "./chunk-3PNJZTDV.js";
79
79
  import "./chunk-SQXCUH4L.js";
@@ -173,7 +173,7 @@ import "./chunk-573TEZCD.js";
173
173
  import "./chunk-3GPTTA4J.js";
174
174
  import "./chunk-UD7UNYRD.js";
175
175
  import "./chunk-IISBCCWR.js";
176
- import "./chunk-XKZBZOKV.js";
176
+ import "./chunk-JIF22AXI.js";
177
177
  import "./chunk-E4RMZGRS.js";
178
178
  import "./chunk-MZUQVWVC.js";
179
179
  import "./chunk-M4DB6ZNN.js";
@@ -203,10 +203,10 @@ import "./chunk-64NJRYU2.js";
203
203
  import "./chunk-U2PSE7MB.js";
204
204
  import "./chunk-BPPUH5JM.js";
205
205
  import "./chunk-LEO4MQ3S.js";
206
- import "./chunk-47LDDGAL.js";
206
+ import "./chunk-5PUZV73Z.js";
207
207
  import "./chunk-EI6V5UXY.js";
208
- import "./chunk-JFZZDMEZ.js";
209
- import "./chunk-7QF26EWO.js";
208
+ import "./chunk-U3BCW7GX.js";
209
+ import "./chunk-BFPQJNFZ.js";
210
210
  import "./chunk-SMDZTJ2D.js";
211
211
  import "./chunk-54V4BZWP.js";
212
212
  import "./chunk-DOWACHYO.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  runRecallNavigation
3
- } from "./chunk-2FCZIWRI.js";
3
+ } from "./chunk-D6BOOYNJ.js";
4
4
  import "./chunk-TH6OYP6I.js";
5
5
  import "./chunk-PQM3B54K.js";
6
6
  import "./chunk-2MWKUVHT.js";
@@ -65,7 +65,7 @@ import "./chunk-JVBAPAWZ.js";
65
65
  import "./chunk-6O3SGRJD.js";
66
66
  import "./chunk-WWQMZBDI.js";
67
67
  import "./chunk-SI36RWC3.js";
68
- import "./chunk-HSSERO3E.js";
68
+ import "./chunk-4P4GF76E.js";
69
69
  import "./chunk-NOUJNHWG.js";
70
70
  import "./chunk-3PNJZTDV.js";
71
71
  import "./chunk-SQXCUH4L.js";
@@ -165,7 +165,7 @@ import "./chunk-573TEZCD.js";
165
165
  import "./chunk-3GPTTA4J.js";
166
166
  import "./chunk-UD7UNYRD.js";
167
167
  import "./chunk-IISBCCWR.js";
168
- import "./chunk-XKZBZOKV.js";
168
+ import "./chunk-JIF22AXI.js";
169
169
  import "./chunk-E4RMZGRS.js";
170
170
  import "./chunk-MZUQVWVC.js";
171
171
  import "./chunk-M4DB6ZNN.js";
@@ -193,10 +193,10 @@ import "./chunk-64NJRYU2.js";
193
193
  import "./chunk-U2PSE7MB.js";
194
194
  import "./chunk-BPPUH5JM.js";
195
195
  import "./chunk-LEO4MQ3S.js";
196
- import "./chunk-47LDDGAL.js";
196
+ import "./chunk-5PUZV73Z.js";
197
197
  import "./chunk-EI6V5UXY.js";
198
- import "./chunk-JFZZDMEZ.js";
199
- import "./chunk-7QF26EWO.js";
198
+ import "./chunk-U3BCW7GX.js";
199
+ import "./chunk-BFPQJNFZ.js";
200
200
  import "./chunk-SMDZTJ2D.js";
201
201
  import "./chunk-54V4BZWP.js";
202
202
  import "./chunk-DOWACHYO.js";
@@ -3,8 +3,8 @@ import {
3
3
  headerConnector,
4
4
  renderExtractionConversation,
5
5
  resolveSourceConnector
6
- } from "./chunk-JFZZDMEZ.js";
7
- import "./chunk-7QF26EWO.js";
6
+ } from "./chunk-U3BCW7GX.js";
7
+ import "./chunk-BFPQJNFZ.js";
8
8
  import "./chunk-SMDZTJ2D.js";
9
9
  import "./chunk-ULLGI6XR.js";
10
10
  import "./chunk-PT4DZDJA.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remnic/core",
3
- "version": "10.0.166",
3
+ "version": "10.0.168",
4
4
  "description": "Framework-agnostic Remnic memory engine — orchestrator, storage, extraction, search, trust zones",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -3416,7 +3416,7 @@
3416
3416
  "core"
3417
3417
  ],
3418
3418
  "peerDependencies": {
3419
- "@remnic/coding-graph": "^10.0.166"
3419
+ "@remnic/coding-graph": "^10.0.168"
3420
3420
  },
3421
3421
  "peerDependenciesMeta": {
3422
3422
  "@remnic/coding-graph": {
@@ -380,9 +380,7 @@ export class AccessRecallSurface {
380
380
  const parts = qmdCollectionPathParts(memoryPath);
381
381
  const coldCollection =
382
382
  this.deps.orchestrator.config.qmdColdCollection ?? "openclaw-engram-cold";
383
- const collectionNamespace = parts
384
- ? collectionNamespaceFromPrefix(parts.collection)
385
- : null;
383
+ const collectionNamespace = parts ? collectionNamespaceFromPrefix(parts.collection) : null;
386
384
  const preferredAttempted = Boolean(
387
385
  preferredNamespace &&
388
386
  (!parts ||
@@ -614,10 +612,7 @@ export class AccessRecallSurface {
614
612
  context.namespace !== this.deps.orchestrator.config.defaultNamespace
615
613
  ? `${context.namespace}:${context.sessionKey}`
616
614
  : context.sessionKey;
617
- const lcmSessionIds =
618
- context.lcmSessionIds !== undefined
619
- ? context.lcmSessionIds
620
- : [legacyKey];
615
+ const lcmSessionIds = context.lcmSessionIds !== undefined ? context.lcmSessionIds : [legacyKey];
621
616
  // Cap the excerpt fanout so recall responses stay bounded. Five matches
622
617
  // is enough to anchor the model in the raw transcript without ballooning
623
618
  // token spend; raw is meant as the escape hatch, not the default. The cap
@@ -1005,9 +1000,7 @@ export class AccessRecallSurface {
1005
1000
  }
1006
1001
 
1007
1002
  const namespacesEnabled = resolveNamespaceCapabilities(this.deps.orchestrator.config).namespaces;
1008
- const requestedNamespace = request.namespace?.trim()
1009
- ? this.deps.resolveNamespace(request.namespace)
1010
- : undefined;
1003
+ const requestedNamespace = request.namespace?.trim() ? this.deps.resolveNamespace(request.namespace) : undefined;
1011
1004
  const authenticatedPrincipal = request.authenticatedPrincipal?.trim();
1012
1005
  const principal =
1013
1006
  authenticatedPrincipal
@@ -26,6 +26,7 @@ export {
26
26
  export {
27
27
  runBulkImportPipeline,
28
28
  formatBatchTranscript,
29
+ processBatchFromIngest,
29
30
  validateBatchSize,
30
31
  resolveBulkImportContext,
31
32
  type ProcessBatchFn,
@@ -4,6 +4,7 @@ import { describe, it } from "node:test";
4
4
  import {
5
5
  runBulkImportPipeline,
6
6
  formatBatchTranscript,
7
+ processBatchFromIngest,
7
8
  resolveBulkImportContext,
8
9
  validateBatchSize,
9
10
  type ProcessBatchContext,
@@ -443,3 +444,33 @@ describe("validateBatchSize", () => {
443
444
  );
444
445
  });
445
446
  });
447
+
448
+ describe("processBatchFromIngest (issue #3554)", () => {
449
+ const context: ProcessBatchContext = { dedup: true, trustLevel: "import" };
450
+
451
+ it("counts only the memories this batch persisted, not concurrent writes", async () => {
452
+ // Another extraction writing to the same root during this batch must not
453
+ // change the count: the result comes from the batch's own persistedCount.
454
+ const concurrentWrites: string[] = [];
455
+ const fn = processBatchFromIngest(async (turns) => {
456
+ concurrentWrites.push("facts/organic-a.md", "facts/organic-b.md");
457
+ assert.equal(turns.length, 2);
458
+ return { persistedCount: 1 };
459
+ });
460
+ const result = await fn([makeTurn(0), makeTurn(1)], context);
461
+ assert.equal(concurrentWrites.length, 2);
462
+ assert.deepEqual(result, { memoriesCreated: 1, duplicatesSkipped: 0 });
463
+ });
464
+
465
+ it("reports zero when the batch persisted nothing", async () => {
466
+ const fn = processBatchFromIngest(async () => ({ persistedCount: 0 }));
467
+ assert.deepEqual(await fn([makeTurn(0)], context), { memoriesCreated: 0, duplicatesSkipped: 0 });
468
+ });
469
+
470
+ it("propagates an ingest failure instead of reporting a count", async () => {
471
+ const fn = processBatchFromIngest(async () => {
472
+ throw new Error("extraction failed");
473
+ });
474
+ await assert.rejects(() => fn([makeTurn(0)], context), /extraction failed/);
475
+ });
476
+ });
@@ -36,6 +36,20 @@ export type ProcessBatchFn = (
36
36
  context: ProcessBatchContext,
37
37
  ) => Promise<ProcessBatchResult>;
38
38
 
39
+ /**
40
+ * Batch processor backed by an ingest call that reports what it persisted.
41
+ * `memoriesCreated` is the batch's own `persistedCount`, so concurrent
42
+ * extractions writing to the same memory root cannot inflate it (issue #3554).
43
+ */
44
+ export function processBatchFromIngest(
45
+ ingest: (turns: ImportTurn[]) => Promise<{ persistedCount: number }>,
46
+ ): ProcessBatchFn {
47
+ return async (turns) => {
48
+ const { persistedCount } = await ingest(turns);
49
+ return { memoriesCreated: persistedCount, duplicatesSkipped: 0 };
50
+ };
51
+ }
52
+
39
53
  export function validateBatchSize(value: number | undefined): number {
40
54
  if (value === undefined) return DEFAULT_BATCH_SIZE;
41
55
  if (typeof value !== "number" || !Number.isFinite(value)) {
package/src/cli.ts CHANGED
@@ -52,6 +52,7 @@ import { isReplaySource, normalizeReplaySessionKey, type ReplaySource, type Repl
52
52
  import {
53
53
  getBulkImportSource,
54
54
  listBulkImportSources,
55
+ processBatchFromIngest,
55
56
  registerBulkImportSource,
56
57
  runBulkImportPipeline,
57
58
  type BulkImportResult,
@@ -3416,12 +3417,7 @@ async function walkMemoryMarkdownFiles(
3416
3417
  /**
3417
3418
  * List absolute paths of every `*.md` file under each recall category directory
3418
3419
  * of `memoryDir` (facts/, corrections/, decisions/, ...; see
3419
- * `walkMemoryMarkdownFiles`). Used by the bulk-import CLI to derive a per-batch
3420
- * `memoriesCreated` count via set-subtraction of "paths after extraction"
3421
- * against "paths before extraction". Caveat: the extraction queue is shared
3422
- * across sessions, so concurrent organic extractions between the two snapshots
3423
- * can still inflate the count; the set diff at least ignores pre-existing and
3424
- * deleted files. Exported for category-dir coverage tests (#1546).
3420
+ * `walkMemoryMarkdownFiles`). Exported for category-dir coverage tests (#1546).
3425
3421
  */
3426
3422
  export async function listMemoryMarkdownFilePaths(memoryDir: string): Promise<string[]> {
3427
3423
  const paths: string[] = [];
@@ -5142,23 +5138,7 @@ export function registerCli(
5142
5138
  writeNamespace,
5143
5139
  );
5144
5140
  const writeRoot = writeStorage.dir;
5145
- const ingestBatch: ProcessBatchFn = async (turns) => {
5146
- // Filename-set diff correctly excludes files that already existed
5147
- // (vs. a naïve `after - before` integer subtraction, which would
5148
- // inflate when unrelated files are deleted mid-batch). Concurrent
5149
- // organic extractions against the same writeRoot can still inflate
5150
- // this count; the extraction engine does not expose a per-session
5151
- // hook for "files created by this run", so full isolation against
5152
- // concurrent writes is tracked as a follow-up.
5153
- const before = new Set(await listMemoryMarkdownFilePaths(writeRoot));
5154
- await orchestrator.ingestBulkImportBatch(turns, {});
5155
- const after = await listMemoryMarkdownFilePaths(writeRoot);
5156
- let memoriesCreated = 0;
5157
- for (const p of after) {
5158
- if (!before.has(p)) memoriesCreated += 1;
5159
- }
5160
- return { memoriesCreated, duplicatesSkipped: 0 };
5161
- };
5141
+ const ingestBatch = processBatchFromIngest((turns) => orchestrator.ingestBulkImportBatch(turns, {}));
5162
5142
  try {
5163
5143
  const result = await runBulkImportCliCommand({
5164
5144
  memoryDir: writeRoot,
@@ -0,0 +1,46 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ import { droidInstallStep } from "./droid-mcp.js";
8
+ import type { TokenStore } from "../tokens.js";
9
+
10
+ test("droidInstallStep hands the prior token store to the saver when the mcp.json write fails", () => {
11
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "remnic-droid-step-"));
12
+ // A file where ~/.factory must be a directory makes the write fail.
13
+ fs.writeFileSync(path.join(home, ".factory"), "not a directory");
14
+ const priorHome = process.env.HOME;
15
+ process.env.HOME = home;
16
+ const prior: TokenStore = { tokens: [] };
17
+ const saved: TokenStore[] = [];
18
+ try {
19
+ const result = droidInstallStep("tok", {}, true, { token: "tok" }, prior, (store) => {
20
+ saved.push(store);
21
+ });
22
+ if (result.ok) assert.fail("the write into a non-directory must fail");
23
+ assert.deepEqual(saved, [prior]);
24
+ assert.match(result.errorMessage, /Token has been rolled back/);
25
+ } finally {
26
+ if (priorHome === undefined) delete process.env.HOME;
27
+ else process.env.HOME = priorHome;
28
+ fs.rmSync(home, { recursive: true, force: true });
29
+ }
30
+ });
31
+
32
+ test("droidInstallStep types its saver as a TokenStore saver (#3538)", () => {
33
+ // Compile-time contract only: tsc fails on an unused @ts-expect-error, so
34
+ // the call below only has to type-check; it never runs.
35
+ const call = () =>
36
+ droidInstallStep(
37
+ undefined,
38
+ {},
39
+ false,
40
+ null,
41
+ null,
42
+ // @ts-expect-error a saver for another shape is not a token-store saver
43
+ (store: { other: number }) => void store,
44
+ );
45
+ void call;
46
+ });
@@ -17,6 +17,7 @@ import os from "node:os";
17
17
 
18
18
  import { readEnvVar } from "../runtime/env.js";
19
19
  import type { ConnectorManifest } from "./index.js";
20
+ import type { TokenStore } from "../tokens.js";
20
21
 
21
22
  // ── Manifest ────────────────────────────────────────────────────────────────
22
23
 
@@ -76,17 +77,16 @@ export type DroidInstallStepResult =
76
77
  /**
77
78
  * Write the remnic MCP entry to ~/.factory/mcp.json, with token rollback on failure.
78
79
  *
79
- * `saveTokenStore` is passed as a callback to avoid a circular dependency
80
- * back into the main connectors module.
80
+ * `saveTokenStoreFn` is the token-store saver (`saveTokenStore` in
81
+ * production), injected so a test can observe or fail the rollback.
81
82
  */
82
83
  export function droidInstallStep(
83
84
  authToken: string | undefined,
84
85
  resolvedConfig: Record<string, unknown>,
85
86
  requiresToken: boolean,
86
87
  tokenEntry: { token: string } | null,
87
- priorTokenStore: unknown,
88
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
89
- saveTokenStoreFn: (store: any) => void,
88
+ priorTokenStore: TokenStore | null,
89
+ saveTokenStoreFn: (store: TokenStore) => void,
90
90
  ): DroidInstallStepResult {
91
91
  try {
92
92
  const result = writeDroidMcpEntry(authToken, resolvedConfig);
@@ -91,6 +91,16 @@ function harness(options?: {
91
91
  events.push(event);
92
92
  },
93
93
  countShadowRecords: async () => options?.shadowRecords ?? 10,
94
+ trailingReceiptFailures: async () => {
95
+ let count = 0;
96
+ for (let i = events.length - 1; i >= 0; i -= 1) {
97
+ const event = events[i];
98
+ if (event.phase !== "outcome") continue;
99
+ if (!event.failureClass || event.failureClass === "record_failed") break;
100
+ count += 1;
101
+ }
102
+ return count;
103
+ },
94
104
  },
95
105
  executors:
96
106
  options?.executors ??
@@ -245,6 +255,34 @@ test("failed receipt forces shadow on the next run", async () => {
245
255
  assert.equal(second.executed, false);
246
256
  });
247
257
 
258
+ test("a restarted coordinator keeps the receipt-failure demotion from recorded outcomes", async () => {
259
+ const h = harness({
260
+ executors: {
261
+ executeRecall: async () => ({ decisionId: "wrong-id", ok: true }),
262
+ },
263
+ });
264
+ const first = await new MemoryControllerCoordinator(h.deps).run({ prompt: RECALL_PROMPT });
265
+ assert.equal(first.executed, false);
266
+
267
+ const restarted = await new MemoryControllerCoordinator(h.deps).run({ prompt: RECALL_PROMPT });
268
+ assert.equal(restarted.effectiveMode, "shadow");
269
+ assert.ok(restarted.demotionReasons.includes("recent_receipt_failures"));
270
+ assert.equal(restarted.executed, false);
271
+ });
272
+
273
+ test("an unreadable receipt-failure history keeps the gate closed", async () => {
274
+ const h = harness();
275
+ h.deps.recorder = {
276
+ ...h.deps.recorder!,
277
+ trailingReceiptFailures: async () => {
278
+ throw new Error("history unavailable");
279
+ },
280
+ };
281
+ const result = await new MemoryControllerCoordinator(h.deps).run({ prompt: RECALL_PROMPT });
282
+ assert.equal(result.effectiveMode, "shadow");
283
+ assert.ok(result.demotionReasons.includes("recent_receipt_failures"));
284
+ });
285
+
248
286
  test("executor error or missing executor records a failure class and demotes next run", async () => {
249
287
  const h = harness({
250
288
  executors: {
@@ -99,6 +99,12 @@ export interface MemoryControllerRecorder {
99
99
  record(event: MemoryControllerEvent): Promise<void>;
100
100
  /** Prior shadow choice records; active promotion requires shadow history. */
101
101
  countShadowRecords(): Promise<number>;
102
+ /**
103
+ * Failed outcomes (executor_error, bad_receipt, no_executor) at the end of
104
+ * the recorded stream, newest first, stopping at the first success. A new
105
+ * coordinator seeds its receipt-failure gate from this count.
106
+ */
107
+ trailingReceiptFailures?(): Promise<number>;
102
108
  }
103
109
 
104
110
  export interface MemoryControllerConfig {
@@ -338,6 +344,7 @@ export class MemoryControllerCoordinator {
338
344
  private readonly deps: MemoryControllerDeps;
339
345
  private readonly clock: () => Date;
340
346
  private consecutiveReceiptFailures = 0;
347
+ private receiptFailuresSeeded = false;
341
348
 
342
349
  constructor(deps: MemoryControllerDeps) {
343
350
  this.deps = deps;
@@ -379,6 +386,7 @@ export class MemoryControllerCoordinator {
379
386
  let demotionReasons: string[] = [];
380
387
  let effectiveMode = requestedMode;
381
388
  if (requestedMode === "active") {
389
+ await this.seedReceiptFailures();
382
390
  demotionReasons = await evaluateActiveGates({
383
391
  config: this.deps.config,
384
392
  reportReader: this.deps.reportReader,
@@ -527,6 +535,23 @@ export class MemoryControllerCoordinator {
527
535
  }
528
536
  }
529
537
 
538
+ private async seedReceiptFailures(): Promise<void> {
539
+ if (this.receiptFailuresSeeded) return;
540
+ this.receiptFailuresSeeded = true;
541
+ const reader = this.deps.recorder?.trailingReceiptFailures;
542
+ if (!reader) return;
543
+ let recorded: number;
544
+ try {
545
+ recorded = await reader.call(this.deps.recorder);
546
+ } catch {
547
+ // Unknown receipt health keeps the gate closed.
548
+ recorded = 1;
549
+ }
550
+ if (Number.isFinite(recorded) && recorded > this.consecutiveReceiptFailures) {
551
+ this.consecutiveReceiptFailures = recorded;
552
+ }
553
+ }
554
+
530
555
  private async recordOutcome(event: MemoryControllerEvent): Promise<void> {
531
556
  if (!this.deps.recorder) return;
532
557
  await this.deps.recorder.record(event);
@@ -543,5 +568,3 @@ function isValidReceipt(receipt: unknown, decisionId: string): boolean {
543
568
  );
544
569
  }
545
570
 
546
- // ponytail: consecutiveReceiptFailures is per-instance, not persisted; persist
547
- // with the recorder if coordinator restarts must carry receipt health forward.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/bulk-import/registry.ts","../src/bulk-import/pipeline.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// Bulk-import source adapter registry\n// ---------------------------------------------------------------------------\n\nimport type { BulkImportSourceAdapter } from \"./types.js\";\n\nconst adapters = new Map<string, BulkImportSourceAdapter>();\n\n/**\n * Register a source adapter. Rejects duplicate names and empty names.\n */\nexport function registerBulkImportSource(\n adapter: BulkImportSourceAdapter,\n): void {\n if (!adapter || typeof adapter !== \"object\") {\n throw new Error(\"bulk-import adapter must be an object\");\n }\n if (\n !adapter.name ||\n typeof adapter.name !== \"string\" ||\n adapter.name.trim().length === 0\n ) {\n throw new Error(\"bulk-import adapter name must be a non-empty string\");\n }\n if (typeof adapter.parse !== \"function\") {\n throw new Error(\n `bulk-import adapter '${adapter.name}' must have a parse function`,\n );\n }\n const key = adapter.name.trim();\n if (adapters.has(key)) {\n throw new Error(\n `bulk-import source adapter '${key}' is already registered`,\n );\n }\n // Store adapter with trimmed name so `adapter.name` stays consistent with\n // the registry key returned by `listBulkImportSources()`.\n const normalized: BulkImportSourceAdapter =\n adapter.name === key ? adapter : { ...adapter, name: key };\n adapters.set(key, normalized);\n}\n\n/**\n * Retrieve a registered adapter by name.\n *\n * Names are trimmed on write (see `registerBulkImportSource`), so we\n * also trim on read to avoid the asymmetric-lookup footgun where a\n * whitespace-padded lookup would never find a registered adapter.\n * Non-string or empty-after-trim inputs return undefined.\n */\nexport function getBulkImportSource(\n name: string,\n): BulkImportSourceAdapter | undefined {\n if (typeof name !== \"string\") return undefined;\n const key = name.trim();\n if (key.length === 0) return undefined;\n return adapters.get(key);\n}\n\n/**\n * List all registered adapter names.\n */\nexport function listBulkImportSources(): string[] {\n return [...adapters.keys()];\n}\n\n/**\n * Clear all registered adapters (for testing).\n */\nexport function clearBulkImportSources(): void {\n adapters.clear();\n}\n","// ---------------------------------------------------------------------------\n// Bulk-import batch processing pipeline\n// ---------------------------------------------------------------------------\n\nimport {\n validateImportTurn,\n type BulkImportError,\n type BulkImportOptions,\n type BulkImportResult,\n type BulkImportSource,\n type ImportTurn,\n} from \"./types.js\";\n\nconst DEFAULT_BATCH_SIZE = 20;\nconst MIN_BATCH_SIZE = 1;\nconst MAX_BATCH_SIZE = 1000;\n\nexport interface ProcessBatchResult {\n memoriesCreated: number;\n duplicatesSkipped: number;\n /**\n * Number of entities created by the batch. Optional so Phase-1 stubs that\n * only count memories can omit it; when absent it is treated as 0.\n */\n entitiesCreated?: number;\n}\n\nexport interface ProcessBatchContext {\n dedup: boolean;\n trustLevel: \"import\";\n namespace?: string;\n}\n\nexport type ProcessBatchFn = (\n turns: ImportTurn[],\n context: ProcessBatchContext,\n) => Promise<ProcessBatchResult>;\n\nexport function validateBatchSize(value: number | undefined): number {\n if (value === undefined) return DEFAULT_BATCH_SIZE;\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new Error(\n `batchSize must be a finite number, received ${String(value)}`,\n );\n }\n if (!Number.isInteger(value)) {\n throw new Error(\n `batchSize must be an integer, received ${value}`,\n );\n }\n if (value < MIN_BATCH_SIZE || value > MAX_BATCH_SIZE) {\n throw new Error(\n `batchSize must be between ${MIN_BATCH_SIZE} and ${MAX_BATCH_SIZE}, received ${value}`,\n );\n }\n return value;\n}\n\nexport function resolveBulkImportContext(\n options: BulkImportOptions,\n): ProcessBatchContext {\n if (options.dedup !== undefined && typeof options.dedup !== \"boolean\") {\n throw new Error(\n `dedup must be a boolean when provided, received ${String(options.dedup)}`,\n );\n }\n if (options.trustLevel !== undefined && options.trustLevel !== \"import\") {\n throw new Error(\n `trustLevel must be 'import' when provided, received ${String(options.trustLevel)}`,\n );\n }\n if (options.namespace !== undefined) {\n if (typeof options.namespace !== \"string\" || options.namespace.trim().length === 0) {\n throw new Error(\n `namespace must be a non-empty string when provided, received ${String(options.namespace)}`,\n );\n }\n }\n\n return {\n dedup: options.dedup !== false,\n trustLevel: options.trustLevel ?? \"import\",\n ...(options.namespace !== undefined\n ? { namespace: options.namespace }\n : {}),\n };\n}\n\n/**\n * Format a batch of turns into a conversation transcript string.\n */\nexport function formatBatchTranscript(turns: ImportTurn[]): string {\n return turns\n .map((t) => {\n const prefix =\n t.participantName ?? t.participantId ?? t.role;\n return `[${t.timestamp}] ${prefix}: ${t.content}`;\n })\n .join(\"\\n\");\n}\n\n/**\n * Run the bulk-import pipeline over a parsed source.\n *\n * Splits turns into batches and delegates each to `processBatch`.\n * In dryRun mode, validates and counts without calling `processBatch`.\n */\nexport async function runBulkImportPipeline(\n source: BulkImportSource,\n options: BulkImportOptions = {},\n processBatch: ProcessBatchFn,\n): Promise<BulkImportResult> {\n const batchSize = validateBatchSize(options.batchSize);\n const dryRun = options.dryRun === true;\n const batchContext = resolveBulkImportContext(options);\n\n const result: BulkImportResult = {\n memoriesCreated: 0,\n duplicatesSkipped: 0,\n entitiesCreated: 0,\n turnsProcessed: 0,\n batchesProcessed: 0,\n errors: [],\n };\n\n const turns = source.turns;\n\n if (!turns || turns.length === 0) {\n return result;\n }\n\n // Validate all turns upfront; collect validation errors\n const validTurns: ImportTurn[] = [];\n for (let i = 0; i < turns.length; i += 1) {\n const issues = validateImportTurn(turns[i], i);\n if (issues.length > 0) {\n const error: BulkImportError = {\n batchIndex: -1,\n message: issues.map((iss) => iss.message).join(\"; \"),\n };\n result.errors.push(error);\n } else {\n validTurns.push(turns[i]);\n }\n }\n\n if (dryRun) {\n result.turnsProcessed = validTurns.length;\n result.batchesProcessed =\n validTurns.length > 0\n ? Math.ceil(validTurns.length / batchSize)\n : 0;\n return result;\n }\n\n // Process in batches\n let batchIndex = 0;\n for (let i = 0; i < validTurns.length; i += batchSize) {\n const batch = validTurns.slice(i, i + batchSize);\n try {\n const batchResult = await processBatch(batch, batchContext);\n result.memoriesCreated += batchResult.memoriesCreated;\n result.duplicatesSkipped += batchResult.duplicatesSkipped;\n if (typeof batchResult.entitiesCreated === \"number\") {\n result.entitiesCreated += batchResult.entitiesCreated;\n }\n } catch (err: unknown) {\n const message =\n err instanceof Error ? err.message : String(err);\n result.errors.push({ batchIndex, message });\n }\n result.turnsProcessed += batch.length;\n result.batchesProcessed += 1;\n batchIndex += 1;\n }\n\n return result;\n}\n"],"mappings":";;;;;AAMA,IAAM,WAAW,oBAAI,IAAqC;AAKnD,SAAS,yBACd,SACM;AACN,MAAI,CAAC,WAAW,OAAO,YAAY,UAAU;AAC3C,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AACA,MACE,CAAC,QAAQ,QACT,OAAO,QAAQ,SAAS,YACxB,QAAQ,KAAK,KAAK,EAAE,WAAW,GAC/B;AACA,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AACA,MAAI,OAAO,QAAQ,UAAU,YAAY;AACvC,UAAM,IAAI;AAAA,MACR,wBAAwB,QAAQ,IAAI;AAAA,IACtC;AAAA,EACF;AACA,QAAM,MAAM,QAAQ,KAAK,KAAK;AAC9B,MAAI,SAAS,IAAI,GAAG,GAAG;AACrB,UAAM,IAAI;AAAA,MACR,+BAA+B,GAAG;AAAA,IACpC;AAAA,EACF;AAGA,QAAM,aACJ,QAAQ,SAAS,MAAM,UAAU,EAAE,GAAG,SAAS,MAAM,IAAI;AAC3D,WAAS,IAAI,KAAK,UAAU;AAC9B;AAUO,SAAS,oBACd,MACqC;AACrC,MAAI,OAAO,SAAS,SAAU,QAAO;AACrC,QAAM,MAAM,KAAK,KAAK;AACtB,MAAI,IAAI,WAAW,EAAG,QAAO;AAC7B,SAAO,SAAS,IAAI,GAAG;AACzB;AAKO,SAAS,wBAAkC;AAChD,SAAO,CAAC,GAAG,SAAS,KAAK,CAAC;AAC5B;AAKO,SAAS,yBAA+B;AAC7C,WAAS,MAAM;AACjB;;;AC1DA,IAAM,qBAAqB;AAC3B,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AAuBhB,SAAS,kBAAkB,OAAmC;AACnE,MAAI,UAAU,OAAW,QAAO;A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OAAO,YAAY,oBAAoB,UAAU;AACnD,eAAO,mBAAmB,YAAY;AAAA,MACxC;AAAA,IACF,SAAS,KAAc;AACrB,YAAM,UACJ,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACjD,aAAO,OAAO,KAAK,EAAE,YAAY,QAAQ,CAAC;AAAA,IAC5C;AACA,WAAO,kBAAkB,MAAM;AAC/B,WAAO,oBAAoB;AAC3B,kBAAc;AAAA,EAChB;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/memory-controller.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { planRecallMode } from \"./intent.js\";\nimport { evaluateMemoryActionPolicy } from \"./memory-action-policy.js\";\nimport type { RuntimePolicyValues } from \"./policy-runtime.js\";\nimport type { UtilityRuntimeValues } from \"./utility-runtime.js\";\nimport type { MemoryActionEligibilityContext, MemoryActionType, RecallPlanMode } from \"./types.js\";\n\n/**\n * Gated unified memory controller (#2348).\n *\n * One state enters, one choice leaves. Host-free: every effectful collaborator\n * (adapters, executors, report reader, recorder, telemetry, clock) is injected.\n * The coordinator creates no store and claims no counterfactual lift.\n */\n\nexport type MemoryControllerMode = \"off\" | \"shadow\" | \"active\";\n\nexport type MemoryControllerActionFamily = \"persistent_memory\" | \"recall\" | \"active_context\" | \"no_op\";\n\n/** #2347 adapter seam: the host supplies plans, core only picks one. */\nexport interface ActiveContextMessage {\n id: string;\n text: string;\n}\n\nexport interface ActiveContextPlan {\n transform: \"SUMMARY\" | \"FILTER\";\n messageIds: string[];\n planId: string;\n}\n\nexport interface ActiveContextAdapter {\n plan(messages: ActiveContextMessage[]): ActiveContextPlan | null;\n}\n\n/** #2345 report + #2346 paired-seed evidence, read through one port. */\nexport interface MemoryControllerEvidenceReport {\n status: \"pass\" | \"fail\";\n version: string;\n configHash: string;\n generatedAt: string;\n /** sha256 over the canonical report fields; recomputed on verification. */\n reportHash: string;\n}\n\nexport interface MemoryControllerPairedSeedEvidence {\n status: \"pass\" | \"fail\";\n seedCount: number;\n generatedAt: string;\n}\n\nexport interface MemoryControllerEvidence {\n report: MemoryControllerEvidenceReport;\n pairedSeed: MemoryControllerPairedSeedEvidence;\n}\n\nexport interface MemoryControllerReportReader {\n read(): Promise<MemoryControllerEvidence | null>;\n}\n\nexport interface MemoryControllerReceipt {\n decisionId: string;\n ok: boolean;\n detail?: string;\n}\n\nexport interface MemoryControllerExecutors {\n executePersistentMemory?(input: {\n decisionId: string;\n action: MemoryActionType;\n eligibility: MemoryActionEligibilityContext;\n stateHash: string;\n }): Promise<MemoryControllerReceipt>;\n executeRecall?(input: { decisionId: string; mode: RecallPlanMode }): Promise<MemoryControllerReceipt>;\n executeActiveContext?(input: {\n decisionId: string;\n plan: ActiveContextPlan;\n }): Promise<MemoryControllerReceipt>;\n}\n\nexport interface MemoryControllerEvent {\n schemaVersion: 1;\n phase: \"choice\" | \"outcome\";\n decisionId: string;\n timestamp: string;\n requestedMode: MemoryControllerMode;\n effectiveMode: MemoryControllerMode;\n stateHash: string;\n choice: MemoryControllerChoice;\n scores: Record<MemoryControllerActionFamily, number>;\n executed: boolean;\n reviewOnly?: boolean;\n demotionReasons?: string[];\n failureClass?: \"record_failed\" | \"executor_error\" | \"bad_receipt\" | \"no_executor\";\n receipt?: MemoryControllerReceipt;\n}\n\nexport interface MemoryControllerRecorder {\n record(event: MemoryControllerEvent): Promise<void>;\n /** Prior shadow choice records; active promotion requires shadow history. */\n countShadowRecords(): Promise<number>;\n}\n\nexport interface MemoryControllerConfig {\n mode: MemoryControllerMode;\n /** Expected #2345 report schema version. */\n reportVersion: string;\n /** Evidence older than this is stale and forces shadow. */\n evidenceMaxAgeMs: number;\n /** Paired-seed arms must cover at least this many seeds (#2346). */\n minPairedSeeds: number;\n /** Active promotion requires at least this many prior shadow records. */\n shadowMinRecords: number;\n}\n\nexport interface MemoryControllerState {\n prompt: string;\n persistentMemoryCandidate?: {\n action: MemoryActionType;\n eligibility: MemoryActionEligibilityContext;\n };\n contextMessages?: ActiveContextMessage[];\n /** 0..1 host-measured context pressure. */\n contextPressure?: number;\n}\n\nexport type MemoryControllerChoice =\n | { family: \"persistent_memory\"; action: MemoryActionType; eligibility: MemoryActionEligibilityContext }\n | { family: \"recall\"; mode: RecallPlanMode }\n | { family: \"active_context\"; plan: ActiveContextPlan }\n | { family: \"no_op\" };\n\nexport interface MemoryControllerRunResult {\n decisionId: string;\n requestedMode: MemoryControllerMode;\n effectiveMode: MemoryControllerMode;\n stateHash: string;\n choice: MemoryControllerChoice;\n scores: Record<MemoryControllerActionFamily, number>;\n executed: boolean;\n reviewOnly: boolean;\n recorded: boolean;\n receipt?: MemoryControllerReceipt;\n demotionReasons: string[];\n}\n\nexport interface MemoryControllerDeps {\n config: MemoryControllerConfig;\n reportReader?: MemoryControllerReportReader;\n recorder?: MemoryControllerRecorder;\n executors?: MemoryControllerExecutors;\n activeContextAdapter?: ActiveContextAdapter;\n policyRuntime?: { loadRuntimeValues(): Promise<RuntimePolicyValues | null> };\n readUtilityRuntime?: () => Promise<UtilityRuntimeValues | null>;\n telemetry?: (event: MemoryControllerEvent) => void;\n clock?: () => Date;\n}\n\nconst NO_OP_FLOOR = 0.35;\n/** `discard` (and any destructive change) stays review-only in active mode. */\nconst REVIEW_ONLY_ACTIONS: Partial<Record<MemoryActionType, true>> = { discard: true };\n\nexport function controllerConfigHash(config: MemoryControllerConfig): string {\n return sha256(\n JSON.stringify({\n mode: config.mode,\n reportVersion: config.reportVersion,\n evidenceMaxAgeMs: config.evidenceMaxAgeMs,\n minPairedSeeds: config.minPairedSeeds,\n shadowMinRecords: config.shadowMinRecords,\n })\n );\n}\n\nexport function hashControllerState(state: MemoryControllerState): string {\n return sha256(\n JSON.stringify({\n prompt: state.prompt,\n persistentMemoryCandidate: state.persistentMemoryCandidate ?? null,\n contextMessages: state.contextMessages ?? null,\n contextPressure: state.contextPressure ?? null,\n })\n );\n}\n\n/** Canonical #2345 report hash; producers sign with this, the controller verifies. */\nexport function computeEvidenceReportHash(fields: {\n status: MemoryControllerEvidenceReport[\"status\"];\n version: string;\n configHash: string;\n generatedAt: string;\n}): string {\n return sha256(JSON.stringify(fields));\n}\n\n/** Verifies the #2345 report hash over its canonical fields. */\nexport function verifyEvidenceReport(report: MemoryControllerEvidenceReport): boolean {\n return (\n computeEvidenceReportHash({\n status: report.status,\n version: report.version,\n configHash: report.configHash,\n generatedAt: report.generatedAt,\n }) === report.reportHash\n );\n}\n\nfunction sha256(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction clampScore(value: number): number {\n if (!Number.isFinite(value)) return Number.NaN;\n return Math.max(0, Math.min(1, value));\n}\n\n/**\n * Bad scores fail closed to `no_op`.\n */\nexport function chooseAction(input: {\n state: MemoryControllerState;\n activeContextAdapter?: ActiveContextAdapter;\n runtimeValues?: RuntimePolicyValues | null;\n utilityValues?: UtilityRuntimeValues | null;\n}): { choice: MemoryControllerChoice; scores: Record<MemoryControllerActionFamily, number> } {\n const { state, activeContextAdapter, runtimeValues, utilityValues } = input;\n\n // recall: current recall path.\n const recallMode = planRecallMode(state.prompt ?? \"\");\n const recallScore =\n recallMode === \"no_recall\" ? 0 : recallMode === \"minimal\" ? 0.4 : 0.6 + 0.2 * (runtimeValues?.recencyWeight ?? 0);\n\n // persistent_memory: current action path + policy.\n let persistentScore = 0;\n const candidate = state.persistentMemoryCandidate;\n if (candidate) {\n const policy = evaluateMemoryActionPolicy({\n action: candidate.action,\n eligibility: candidate.eligibility,\n options: { actionsEnabled: true, maxCompressionTokensPerHour: Number.POSITIVE_INFINITY },\n });\n if (policy.decision === \"allow\") {\n persistentScore = 0.4 + 0.4 * (candidate.eligibility.confidence ?? 0);\n } else if (policy.decision === \"defer\") {\n persistentScore = 0.2;\n }\n // Utility runtime may suppress the persistent family.\n if (utilityValues && utilityValues.rankingSuppressMultiplier > 1) {\n persistentScore *= 1 / utilityValues.rankingSuppressMultiplier;\n }\n }\n\n // active_context: current context path through the #2347 adapter.\n let contextScore = 0;\n let contextPlan: ActiveContextPlan | null = null;\n const pressure = state.contextPressure;\n if (activeContextAdapter && typeof pressure === \"number\" && Number.isFinite(pressure) && pressure > 0.5) {\n contextPlan = activeContextAdapter.plan(state.contextMessages ?? []);\n if (contextPlan && contextPlan.messageIds.length > 0) {\n contextScore = 0.3 + 0.5 * Math.max(0, Math.min(1, pressure));\n }\n }\n\n const scores: Record<MemoryControllerActionFamily, number> = {\n recall: clampScore(recallScore),\n persistent_memory: clampScore(persistentScore),\n active_context: clampScore(contextScore),\n no_op: NO_OP_FLOOR,\n };\n\n // Bad scores fail closed.\n if (Object.values(scores).some((score) => !Number.isFinite(score) || score < 0 || score > 1)) {\n return { choice: { family: \"no_op\" }, scores };\n }\n\n let choice: MemoryControllerChoice = { family: \"no_op\" };\n let best = scores.no_op;\n if (scores.recall > best) {\n best = scores.recall;\n choice = { family: \"recall\", mode: recallMode };\n }\n if (scores.persistent_memory > best) {\n best = scores.persistent_memory;\n choice = {\n family: \"persistent_memory\",\n action: candidate!.action,\n eligibility: candidate!.eligibility,\n };\n }\n if (scores.active_context > best) {\n choice = { family: \"active_context\", plan: contextPlan! };\n }\n return { choice, scores };\n}\n\n/** Returns the demotion reasons when active-mode gates fail; empty means go. */\nexport async function evaluateActiveGates(input: {\n config: MemoryControllerConfig;\n reportReader?: MemoryControllerReportReader;\n recorder?: MemoryControllerRecorder;\n consecutiveReceiptFailures: number;\n now: Date;\n}): Promise<string[]> {\n const { config, reportReader, recorder, consecutiveReceiptFailures, now } = input;\n const reasons: string[] = [];\n\n if (!reportReader) return [\"no_report_reader\"];\n\n const evidence = await reportReader.read();\n if (!evidence) return [\"no_evidence\"];\n\n const { report, pairedSeed } = evidence;\n if (report.status !== \"pass\") reasons.push(\"report_not_passing\");\n if (report.version !== config.reportVersion) reasons.push(\"report_version_mismatch\");\n if (report.configHash !== controllerConfigHash(config)) reasons.push(\"report_config_unbound\");\n if (!verifyEvidenceReport(report)) reasons.push(\"report_hash_invalid\");\n const reportGeneratedAt = Date.parse(report.generatedAt);\n if (!Number.isFinite(reportGeneratedAt) || now.getTime() - reportGeneratedAt > config.evidenceMaxAgeMs) {\n reasons.push(\"report_stale\");\n }\n\n if (pairedSeed.status !== \"pass\") reasons.push(\"paired_seed_not_passing\");\n if (pairedSeed.seedCount < config.minPairedSeeds) reasons.push(\"paired_seed_count_low\");\n const seedGeneratedAt = Date.parse(pairedSeed.generatedAt);\n if (!Number.isFinite(seedGeneratedAt) || now.getTime() - seedGeneratedAt > config.evidenceMaxAgeMs) {\n reasons.push(\"paired_seed_stale\");\n }\n\n const shadowRecords = recorder ? await recorder.countShadowRecords() : 0;\n if (shadowRecords < config.shadowMinRecords) reasons.push(\"shadow_history_insufficient\");\n\n if (consecutiveReceiptFailures > 0) reasons.push(\"recent_receipt_failures\");\n\n return reasons;\n}\n\nexport class MemoryControllerCoordinator {\n private readonly deps: MemoryControllerDeps;\n private readonly clock: () => Date;\n private consecutiveReceiptFailures = 0;\n\n constructor(deps: MemoryControllerDeps) {\n this.deps = deps;\n this.clock = deps.clock ?? (() => new Date());\n }\n\n async run(state: MemoryControllerState): Promise<MemoryControllerRunResult> {\n const decisionId = randomUUID();\n const stateHash = hashControllerState(state);\n const requestedMode = this.deps.config.mode;\n\n // off: no choice, no read, no write, no call.\n if (requestedMode === \"off\") {\n return {\n decisionId,\n requestedMode,\n effectiveMode: \"off\",\n stateHash,\n choice: { family: \"no_op\" },\n scores: { persistent_memory: 0, recall: 0, active_context: 0, no_op: 0 },\n executed: false,\n reviewOnly: false,\n recorded: false,\n demotionReasons: [\"mode_off\"],\n };\n }\n\n const [runtimeValues, utilityValues] = await Promise.all([\n this.deps.policyRuntime?.loadRuntimeValues() ?? null,\n this.deps.readUtilityRuntime?.() ?? null,\n ]);\n const { choice, scores } = chooseAction({\n state,\n activeContextAdapter: this.deps.activeContextAdapter,\n runtimeValues,\n utilityValues,\n });\n\n let demotionReasons: string[] = [];\n let effectiveMode = requestedMode;\n if (requestedMode === \"active\") {\n demotionReasons = await evaluateActiveGates({\n config: this.deps.config,\n reportReader: this.deps.reportReader,\n recorder: this.deps.recorder,\n consecutiveReceiptFailures: this.consecutiveReceiptFailures,\n now: this.clock(),\n });\n if (demotionReasons.length > 0) effectiveMode = \"shadow\";\n }\n\n const baseEvent: MemoryControllerEvent = {\n schemaVersion: 1,\n phase: \"choice\",\n decisionId,\n timestamp: this.clock().toISOString(),\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n ...(demotionReasons.length > 0 ? { demotionReasons } : {}),\n };\n\n // Shadow records before any active dispatch.\n let recorded = false;\n if (this.deps.recorder) {\n try {\n await this.deps.recorder.record(baseEvent);\n this.deps.telemetry?.(baseEvent);\n recorded = true;\n } catch {\n // Bad recorder stops work: no dispatch, no outcome event.\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: false,\n recorded: false,\n demotionReasons: [...demotionReasons, \"record_failed\"],\n };\n }\n }\n\n if (effectiveMode !== \"active\") {\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: false,\n recorded,\n demotionReasons,\n };\n }\n\n // First active scope: reversible actions only.\n if (choice.family === \"persistent_memory\" && REVIEW_ONLY_ACTIONS[choice.action]) {\n const event: MemoryControllerEvent = {\n ...baseEvent,\n phase: \"outcome\",\n reviewOnly: true,\n demotionReasons: [\"review_only_action\"],\n };\n await this.recordOutcome(event);\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: true,\n recorded,\n demotionReasons,\n };\n }\n\n const receipt = await this.dispatch(choice, stateHash, decisionId, baseEvent);\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: receipt?.ok === true,\n reviewOnly: false,\n recorded,\n ...(receipt ? { receipt } : {}),\n demotionReasons,\n };\n }\n\n private async dispatch(\n choice: MemoryControllerChoice,\n stateHash: string,\n decisionId: string,\n baseEvent: MemoryControllerEvent\n ): Promise<MemoryControllerReceipt | undefined> {\n const executors = this.deps.executors ?? {};\n try {\n let receipt: MemoryControllerReceipt | undefined;\n if (choice.family === \"persistent_memory\") {\n if (!executors.executePersistentMemory) throw new Error(\"no_executor:persistent_memory\");\n receipt = await executors.executePersistentMemory({\n decisionId,\n action: choice.action,\n eligibility: choice.eligibility,\n stateHash,\n });\n } else if (choice.family === \"recall\") {\n if (!executors.executeRecall) throw new Error(\"no_executor:recall\");\n receipt = await executors.executeRecall({ decisionId, mode: choice.mode });\n } else if (choice.family === \"active_context\") {\n if (!executors.executeActiveContext) throw new Error(\"no_executor:active_context\");\n receipt = await executors.executeActiveContext({ decisionId, plan: choice.plan });\n } else {\n // no_op executed trivially; no executor call.\n receipt = { decisionId, ok: true };\n }\n if (!isValidReceipt(receipt, decisionId)) {\n this.consecutiveReceiptFailures += 1;\n await this.recordOutcome({ ...baseEvent, phase: \"outcome\", failureClass: \"bad_receipt\" });\n return undefined;\n }\n this.consecutiveReceiptFailures = 0;\n await this.recordOutcome({ ...baseEvent, phase: \"outcome\", executed: receipt.ok, receipt });\n return receipt;\n } catch (error) {\n this.consecutiveReceiptFailures += 1;\n await this.recordOutcome({\n ...baseEvent,\n phase: \"outcome\",\n failureClass: (error as Error)?.message?.startsWith(\"no_executor:\") ? \"no_executor\" : \"executor_error\",\n });\n return undefined;\n }\n }\n\n private async recordOutcome(event: MemoryControllerEvent): Promise<void> {\n if (!this.deps.recorder) return;\n await this.deps.recorder.record(event);\n this.deps.telemetry?.(event);\n }\n}\n\nfunction isValidReceipt(receipt: unknown, decisionId: string): boolean {\n return (\n typeof receipt === \"object\" &&\n receipt !== null &&\n (receipt as MemoryControllerReceipt).decisionId === decisionId &&\n typeof (receipt as MemoryControllerReceipt).ok === \"boolean\"\n );\n}\n\n// ponytail: consecutiveReceiptFailures is per-instance, not persisted; persist\n// with the recorder if coordinator restarts must carry receipt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