@remnic/core 9.3.601 → 9.3.603

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 (49) hide show
  1. package/dist/access-cli.js +6 -6
  2. package/dist/access-http.js +6 -6
  3. package/dist/access-mcp.js +5 -5
  4. package/dist/access-schema.d.ts +34 -34
  5. package/dist/access-service.js +4 -4
  6. package/dist/causal-behavior.js +2 -2
  7. package/dist/causal-chain.js +2 -2
  8. package/dist/causal-consolidation.js +2 -2
  9. package/dist/causal-retrieval.js +2 -2
  10. package/dist/causal-trajectory-graph.js +1 -1
  11. package/dist/causal-trajectory.js +1 -1
  12. package/dist/{chunk-ELKI4BB6.js → chunk-2ESBDLT5.js} +3 -3
  13. package/dist/{chunk-WZA5Y6AC.js → chunk-2QANQKSQ.js} +3 -3
  14. package/dist/{chunk-BDCCWRHR.js → chunk-5RPTH6AU.js} +3 -3
  15. package/dist/{chunk-JKV57BTN.js → chunk-7V2SGZ3H.js} +2 -2
  16. package/dist/{chunk-D4KJ74JJ.js → chunk-EWC6W6AB.js} +2 -2
  17. package/dist/{chunk-V67GWXM2.js → chunk-IP73YCZP.js} +1 -1
  18. package/dist/{chunk-KDUVQU6Y.js → chunk-MTGOAU7A.js} +4 -4
  19. package/dist/{chunk-65JSA4MP.js → chunk-RUYYYLDT.js} +7 -7
  20. package/dist/{chunk-CL3MWNNQ.js → chunk-TH67Q46T.js} +3 -3
  21. package/dist/{chunk-ZZYF3BUL.js → chunk-TQOU3VAT.js} +1 -1
  22. package/dist/{chunk-4JRRISLU.js → chunk-XL7FK7PJ.js} +61 -43
  23. package/dist/chunk-XL7FK7PJ.js.map +1 -0
  24. package/dist/cli.js +8 -8
  25. package/dist/compounding/engine.js +1 -1
  26. package/dist/{graph-edge-decay-MUP5J7CC.js → graph-edge-decay-5ZOK7ZNO.js} +2 -2
  27. package/dist/graph-snapshot.js +2 -2
  28. package/dist/graph.js +1 -1
  29. package/dist/index.js +10 -10
  30. package/dist/operator-toolkit.js +2 -2
  31. package/dist/orchestrator.js +4 -4
  32. package/dist/schemas.d.ts +64 -64
  33. package/dist/shared-context/manager.d.ts +2 -2
  34. package/dist/transfer/types.d.ts +12 -12
  35. package/package.json +1 -1
  36. package/src/graph.test.ts +76 -11
  37. package/src/graph.ts +101 -88
  38. package/dist/chunk-4JRRISLU.js.map +0 -1
  39. /package/dist/{chunk-ELKI4BB6.js.map → chunk-2ESBDLT5.js.map} +0 -0
  40. /package/dist/{chunk-WZA5Y6AC.js.map → chunk-2QANQKSQ.js.map} +0 -0
  41. /package/dist/{chunk-BDCCWRHR.js.map → chunk-5RPTH6AU.js.map} +0 -0
  42. /package/dist/{chunk-JKV57BTN.js.map → chunk-7V2SGZ3H.js.map} +0 -0
  43. /package/dist/{chunk-D4KJ74JJ.js.map → chunk-EWC6W6AB.js.map} +0 -0
  44. /package/dist/{chunk-V67GWXM2.js.map → chunk-IP73YCZP.js.map} +0 -0
  45. /package/dist/{chunk-KDUVQU6Y.js.map → chunk-MTGOAU7A.js.map} +0 -0
  46. /package/dist/{chunk-65JSA4MP.js.map → chunk-RUYYYLDT.js.map} +0 -0
  47. /package/dist/{chunk-CL3MWNNQ.js.map → chunk-TH67Q46T.js.map} +0 -0
  48. /package/dist/{chunk-ZZYF3BUL.js.map → chunk-TQOU3VAT.js.map} +0 -0
  49. /package/dist/{graph-edge-decay-MUP5J7CC.js.map → graph-edge-decay-5ZOK7ZNO.js.map} +0 -0
package/src/graph.test.ts CHANGED
@@ -1,15 +1,10 @@
1
- import test from "node:test";
2
1
  import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
5
+ import test from "node:test";
6
6
 
7
- import {
8
- GraphIndex,
9
- graphFilePath,
10
- readEdges,
11
- type GraphConfig,
12
- } from "./graph.js";
7
+ import { type GraphConfig, type GraphEdge, GraphIndex, graphFilePath, readEdges } from "./graph.js";
13
8
 
14
9
  function makeGraphConfig(): GraphConfig {
15
10
  return {
@@ -53,17 +48,87 @@ test("graph reads skip malformed JSON edge objects before traversal", async () =
53
48
  }),
54
49
  "",
55
50
  ].join("\n"),
56
- "utf-8",
51
+ "utf-8"
57
52
  );
58
53
 
59
54
  const edges = await readEdges(memoryDir, "entity");
60
- assert.deepEqual(edges.map((edge) => edge.to), ["c"]);
55
+ assert.deepEqual(
56
+ edges.map((edge) => edge.to),
57
+ ["c"]
58
+ );
61
59
 
62
60
  const graph = new GraphIndex(memoryDir, makeGraphConfig());
63
61
  const activated = await graph.spreadingActivation(["a"]);
64
- assert.deepEqual(activated.map((candidate) => candidate.path), ["c"]);
62
+ assert.deepEqual(
63
+ activated.map((candidate) => candidate.path),
64
+ ["c"]
65
+ );
65
66
  assert.equal(Number.isFinite(activated[0]?.score), true);
66
67
  } finally {
67
68
  await rm(memoryDir, { recursive: true, force: true });
68
69
  }
69
70
  });
71
+
72
+ test("spreadingActivation propagates accumulated activation from multiple seeds", async () => {
73
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-graph-multi-seed-"));
74
+ try {
75
+ await writeGraphEdges(memoryDir, [
76
+ makeEdge("seed-a", "shared"),
77
+ makeEdge("seed-b", "shared"),
78
+ makeEdge("shared", "downstream"),
79
+ ]);
80
+
81
+ const graph = new GraphIndex(memoryDir, makeGraphConfig());
82
+ const activated = await graph.spreadingActivation(["seed-a", "seed-b"]);
83
+ const scores = new Map(activated.map((candidate) => [candidate.path, candidate.score]));
84
+
85
+ assert.equal(scores.get("shared"), 1);
86
+ assert.equal(scores.get("downstream"), 0.5);
87
+ } finally {
88
+ await rm(memoryDir, { recursive: true, force: true });
89
+ }
90
+ });
91
+
92
+ test("spreadingActivation propagates same-depth alternate path activation", async () => {
93
+ const memoryDir = await mkdtemp(path.join(os.tmpdir(), "remnic-graph-alt-path-"));
94
+ try {
95
+ await writeGraphEdges(memoryDir, [
96
+ makeEdge("seed", "left"),
97
+ makeEdge("seed", "right"),
98
+ makeEdge("left", "shared"),
99
+ makeEdge("right", "shared"),
100
+ makeEdge("shared", "downstream"),
101
+ ]);
102
+
103
+ const graph = new GraphIndex(memoryDir, {
104
+ ...makeGraphConfig(),
105
+ maxGraphTraversalSteps: 3,
106
+ });
107
+ const activated = await graph.spreadingActivation(["seed"]);
108
+ const scores = new Map(activated.map((candidate) => [candidate.path, candidate.score]));
109
+
110
+ assert.equal(scores.get("left"), 0.5);
111
+ assert.equal(scores.get("right"), 0.5);
112
+ assert.equal(scores.get("shared"), 0.5);
113
+ assert.equal(scores.get("downstream"), 0.25);
114
+ } finally {
115
+ await rm(memoryDir, { recursive: true, force: true });
116
+ }
117
+ });
118
+
119
+ function makeEdge(from: string, to: string): GraphEdge {
120
+ return {
121
+ from,
122
+ to,
123
+ type: "entity",
124
+ weight: 1,
125
+ label: "test",
126
+ ts: "2026-01-01T00:00:00.000Z",
127
+ };
128
+ }
129
+
130
+ async function writeGraphEdges(memoryDir: string, edges: GraphEdge[]): Promise<void> {
131
+ const filePath = graphFilePath(memoryDir, "entity");
132
+ await mkdir(path.dirname(filePath), { recursive: true });
133
+ await writeFile(filePath, `${edges.map((edge) => JSON.stringify(edge)).join("\n")}\n`, "utf-8");
134
+ }
package/src/graph.ts CHANGED
@@ -10,8 +10,8 @@
10
10
  * All writes are fail-open: errors are caught/logged, never thrown.
11
11
  */
12
12
 
13
- import { mkdir, appendFile, readFile } from "node:fs/promises";
14
- import * as path from "path";
13
+ import { appendFile, mkdir, readFile } from "node:fs/promises";
14
+ import * as path from "node:path";
15
15
 
16
16
  import { readEdgeConfidence } from "./graph-edge-reinforcement.js";
17
17
  import { emitGraphEvent } from "./graph-events.js";
@@ -66,14 +66,7 @@ export const DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR = 0.2;
66
66
  export const DEFAULT_GRAPH_TRAVERSAL_PAGERANK_ITERATIONS = 8;
67
67
 
68
68
  // Causal signal phrases — order matters (most specific first)
69
- export const CAUSAL_PHRASES = [
70
- "as a result",
71
- "led to",
72
- "because of",
73
- "therefore",
74
- "caused",
75
- "because",
76
- ];
69
+ export const CAUSAL_PHRASES = ["as a result", "led to", "because of", "therefore", "caused", "because"];
77
70
 
78
71
  export function graphsDir(memoryDir: string): string {
79
72
  return path.join(memoryDir, "state", "graphs");
@@ -114,8 +107,8 @@ export function withGraphWriteLock<T>(filePath: string, fn: () => Promise<T>): P
114
107
  filePath,
115
108
  next.then(
116
109
  () => undefined,
117
- () => undefined,
118
- ),
110
+ () => undefined
111
+ )
119
112
  );
120
113
  return next;
121
114
  }
@@ -123,7 +116,7 @@ export function withGraphWriteLock<T>(filePath: string, fn: () => Promise<T>): P
123
116
  export async function appendEdge(memoryDir: string, edge: GraphEdge): Promise<void> {
124
117
  await ensureGraphsDir(memoryDir);
125
118
  const filePath = graphFilePath(memoryDir, edge.type);
126
- const line = JSON.stringify(edge) + "\n";
119
+ const line = `${JSON.stringify(edge)}\n`;
127
120
  await withGraphWriteLock(filePath, async () => {
128
121
  await appendFile(filePath, line, "utf8");
129
122
  });
@@ -205,7 +198,7 @@ export async function readEdgesStrict(memoryDir: string, type: GraphType): Promi
205
198
  */
206
199
  export async function readAllEdges(
207
200
  memoryDir: string,
208
- config: Pick<GraphConfig, "entityGraphEnabled" | "timeGraphEnabled" | "causalGraphEnabled">,
201
+ config: Pick<GraphConfig, "entityGraphEnabled" | "timeGraphEnabled" | "causalGraphEnabled">
209
202
  ): Promise<GraphEdge[]> {
210
203
  const parts: GraphEdge[][] = await Promise.all([
211
204
  config.entityGraphEnabled ? readEdges(memoryDir, "entity") : Promise.resolve([]),
@@ -243,9 +236,12 @@ function isValidGraphEdge(raw: unknown, expectedType: GraphType): raw is GraphEd
243
236
  const edge = raw as Record<string, unknown>;
244
237
  return (
245
238
  edge.type === expectedType &&
246
- typeof edge.from === "string" && edge.from.length > 0 &&
247
- typeof edge.to === "string" && edge.to.length > 0 &&
248
- typeof edge.weight === "number" && Number.isFinite(edge.weight) &&
239
+ typeof edge.from === "string" &&
240
+ edge.from.length > 0 &&
241
+ typeof edge.to === "string" &&
242
+ edge.to.length > 0 &&
243
+ typeof edge.weight === "number" &&
244
+ Number.isFinite(edge.weight) &&
249
245
  typeof edge.label === "string" &&
250
246
  typeof edge.ts === "string"
251
247
  );
@@ -258,7 +254,7 @@ export async function analyzeGraphHealth(
258
254
  timeGraphEnabled?: boolean;
259
255
  causalGraphEnabled?: boolean;
260
256
  includeRepairGuidance?: boolean;
261
- },
257
+ }
262
258
  ): Promise<GraphHealthReport> {
263
259
  const enabledTypes: GraphType[] = [];
264
260
  if (options?.entityGraphEnabled !== false) enabledTypes.push("entity");
@@ -324,7 +320,7 @@ export async function analyzeGraphHealth(
324
320
  validEdges: 0,
325
321
  corruptLines: 0,
326
322
  uniqueNodes: globalNodes.size,
327
- },
323
+ }
328
324
  );
329
325
  totals.uniqueNodes = globalNodes.size;
330
326
 
@@ -338,10 +334,14 @@ export async function analyzeGraphHealth(
338
334
  if (options?.includeRepairGuidance === true) {
339
335
  const guidance: string[] = [];
340
336
  if (totals.corruptLines > 0) {
341
- guidance.push("Corrupt graph lines detected: back up memory/state/graphs, then rebuild graphs from clean memory replay/extraction runs.");
337
+ guidance.push(
338
+ "Corrupt graph lines detected: back up memory/state/graphs, then rebuild graphs from clean memory replay/extraction runs."
339
+ );
342
340
  }
343
341
  if (totals.validEdges === 0) {
344
- guidance.push("No valid edges detected yet: run normal extraction traffic (or replay ingestion) to seed graph files.");
342
+ guidance.push(
343
+ "No valid edges detected yet: run normal extraction traffic (or replay ingestion) to seed graph files."
344
+ );
345
345
  }
346
346
  if (guidance.length > 0) report.repairGuidance = guidance;
347
347
  }
@@ -392,10 +392,7 @@ export class GraphIndex {
392
392
  }
393
393
 
394
394
  private async loadEdgesCached(): Promise<GraphEdge[]> {
395
- if (
396
- this.edgeCache &&
397
- Date.now() - this.edgeCache.loadedAt < GraphIndex.EDGE_CACHE_TTL_MS
398
- ) {
395
+ if (this.edgeCache && Date.now() - this.edgeCache.loadedAt < GraphIndex.EDGE_CACHE_TTL_MS) {
399
396
  return this.edgeCache.allEdges;
400
397
  }
401
398
  const allEdges = await readAllEdges(this.memoryDir, {
@@ -520,21 +517,23 @@ export class GraphIndex {
520
517
  * Default `false` (floor from config is applied).
521
518
  */
522
519
  includeLowConfidence?: boolean;
523
- },
524
- ): Promise<Array<{
525
- path: string;
526
- score: number;
527
- seed: string;
528
- hopDepth: number;
529
- decayedWeight: number;
530
- graphType: "entity" | "time" | "causal";
531
- /**
532
- * Confidence of the edge that produced this candidate's recorded
533
- * provenance (the strongest edge along the chosen entry path).
534
- * In `[0, 1]`. Legacy edges without `confidence` surface as 1.0.
535
- */
536
- edgeConfidence: number;
537
- }>> {
520
+ }
521
+ ): Promise<
522
+ Array<{
523
+ path: string;
524
+ score: number;
525
+ seed: string;
526
+ hopDepth: number;
527
+ decayedWeight: number;
528
+ graphType: "entity" | "time" | "causal";
529
+ /**
530
+ * Confidence of the edge that produced this candidate's recorded
531
+ * provenance (the strongest edge along the chosen entry path).
532
+ * In `[0, 1]`. Legacy edges without `confidence` surface as 1.0.
533
+ */
534
+ edgeConfidence: number;
535
+ }>
536
+ > {
538
537
  if (!this.cfg.multiGraphMemoryEnabled) return [];
539
538
  const steps = maxSteps ?? this.cfg.maxGraphTraversalSteps;
540
539
  const decay = this.cfg.graphActivationDecay;
@@ -543,12 +542,9 @@ export class GraphIndex {
543
542
  // Otherwise clamp the configured floor into [0, 1] so misconfiguration
544
543
  // cannot (a) admit edges with negative confidence or (b) reject every
545
544
  // edge.
546
- const floor = opts?.includeLowConfidence === true
547
- ? 0
548
- : clampConfidenceFloor(this.cfg.graphTraversalConfidenceFloor);
549
- const iterations = clampPageRankIterations(
550
- this.cfg.graphTraversalPageRankIterations,
551
- );
545
+ const floor =
546
+ opts?.includeLowConfidence === true ? 0 : clampConfidenceFloor(this.cfg.graphTraversalConfidenceFloor);
547
+ const iterations = clampPageRankIterations(this.cfg.graphTraversalPageRankIterations);
552
548
 
553
549
  try {
554
550
  const allEdges = await this.loadEdgesCached();
@@ -581,50 +577,67 @@ export class GraphIndex {
581
577
  edgeConfidence: number;
582
578
  }
583
579
  >();
584
- const visited = new Set<string>(seeds);
585
-
586
- // BFS queue: [nodePath, hop, seedPath]
587
- const queue: Array<[string, number, string]> = seeds.map((s) => [s, 0, s]);
588
-
589
- while (queue.length > 0) {
590
- const [node, hop, sourceSeed] = queue.shift()!;
591
- if (hop >= steps) continue;
592
-
593
- const edges = adj.get(node) ?? [];
594
- for (const edge of edges) {
595
- const neighbor = edge.to === node ? edge.from : edge.to;
596
- const conf = readEdgeConfidence(edge);
597
- // Defense in depth: the adjacency build already drops sub-floor
598
- // edges, but if a synthesized reverse edge ever bypassed that
599
- // path, this guard keeps spreading activation honest.
600
- if (conf < floor) continue;
601
- const score = edge.weight * conf * Math.pow(decay, hop + 1);
602
-
603
- if (!seedSet.has(neighbor)) {
604
- const existing = scores.get(neighbor) ?? 0;
605
- scores.set(neighbor, existing + score);
606
-
607
- const prev = provenance.get(neighbor);
608
- if (
609
- !prev ||
610
- hop + 1 < prev.hopDepth ||
611
- (hop + 1 === prev.hopDepth && score > prev.decayedWeight)
612
- ) {
613
- provenance.set(neighbor, {
614
- seed: sourceSeed,
615
- hopDepth: hop + 1,
616
- decayedWeight: score,
617
- graphType: edge.type,
618
- edgeConfidence: conf,
619
- });
580
+ let frontier = new Map<string, { node: string; seed: string; activation: number }>();
581
+ const reachedBySeed = new Map<string, Set<string>>();
582
+ for (const seed of seeds) {
583
+ frontier.set(`${seed}\0${seed}`, { node: seed, seed, activation: 1 });
584
+ reachedBySeed.set(seed, new Set([seed]));
585
+ }
586
+
587
+ for (let hop = 0; hop < steps && frontier.size > 0; hop++) {
588
+ const nextFrontier = new Map<string, { node: string; seed: string; activation: number }>();
589
+
590
+ for (const { node, seed: sourceSeed, activation } of frontier.values()) {
591
+ const edges = adj.get(node) ?? [];
592
+ for (const edge of edges) {
593
+ const neighbor = edge.to === node ? edge.from : edge.to;
594
+ const conf = readEdgeConfidence(edge);
595
+ // Defense in depth: the adjacency build already drops sub-floor
596
+ // edges, but if a synthesized reverse edge ever bypassed that
597
+ // path, this guard keeps spreading activation honest.
598
+ if (conf < floor) continue;
599
+ const score = activation * edge.weight * conf * decay;
600
+ const reachedForSeed = reachedBySeed.get(sourceSeed);
601
+ if (reachedForSeed?.has(neighbor)) {
602
+ continue;
620
603
  }
621
- }
622
604
 
623
- if (!visited.has(neighbor)) {
624
- visited.add(neighbor);
625
- queue.push([neighbor, hop + 1, sourceSeed]);
605
+ if (!seedSet.has(neighbor)) {
606
+ const existing = scores.get(neighbor) ?? 0;
607
+ scores.set(neighbor, existing + score);
608
+
609
+ const prev = provenance.get(neighbor);
610
+ if (!prev || hop + 1 < prev.hopDepth || (hop + 1 === prev.hopDepth && score > prev.decayedWeight)) {
611
+ provenance.set(neighbor, {
612
+ seed: sourceSeed,
613
+ hopDepth: hop + 1,
614
+ decayedWeight: score,
615
+ graphType: edge.type,
616
+ edgeConfidence: conf,
617
+ });
618
+ }
619
+
620
+ if (hop + 1 < steps) {
621
+ const frontierKey = `${sourceSeed}\0${neighbor}`;
622
+ const existingFrontier = nextFrontier.get(frontierKey);
623
+ if (existingFrontier) {
624
+ existingFrontier.activation += score;
625
+ } else {
626
+ nextFrontier.set(frontierKey, {
627
+ node: neighbor,
628
+ seed: sourceSeed,
629
+ activation: score,
630
+ });
631
+ }
632
+ }
633
+ }
626
634
  }
627
635
  }
636
+
637
+ for (const { node, seed } of nextFrontier.values()) {
638
+ reachedBySeed.get(seed)?.add(node);
639
+ }
640
+ frontier = nextFrontier;
628
641
  }
629
642
 
630
643
  // Issue #681 PR 3/3 — optional PageRank-style refinement.
@@ -712,7 +725,7 @@ export function clampPageRankIterations(raw: unknown): number {
712
725
  export function applyPageRankRefinement(
713
726
  scores: Map<string, number>,
714
727
  adj: Map<string, GraphEdge[]>,
715
- opts: { iterations: number; floor: number; damping: number },
728
+ opts: { iterations: number; floor: number; damping: number }
716
729
  ): void {
717
730
  const { iterations, floor, damping } = opts;
718
731
  if (iterations <= 0 || scores.size === 0) return;
@@ -793,7 +806,7 @@ export function applyPageRankRefinement(
793
806
  */
794
807
  export function applyLateralInhibition(
795
808
  scores: Map<string, number>,
796
- opts: { beta: number; topM: number },
809
+ opts: { beta: number; topM: number }
797
810
  ): Map<string, number> {
798
811
  const { beta, topM } = opts;
799
812
  if (beta === 0 || topM === 0) return new Map(scores);
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/graph.ts"],"sourcesContent":["/**\n * Multi-Graph Memory (MAGMA/SYNAPSE-inspired, v8.2)\n *\n * Maintains three typed edge graphs:\n * entity.jsonl — memories sharing a named entity (entityRef)\n * time.jsonl — consecutive memories in the same thread/session\n * causal.jsonl — memories linked by causal language heuristics\n *\n * Stored under `<memoryDir>/state/graphs/`.\n * All writes are fail-open: errors are caught/logged, never thrown.\n */\n\nimport { mkdir, appendFile, readFile } from \"node:fs/promises\";\nimport * as path from \"path\";\n\nimport { readEdgeConfidence } from \"./graph-edge-reinforcement.js\";\nimport { emitGraphEvent } from \"./graph-events.js\";\n\nexport type GraphType = \"entity\" | \"time\" | \"causal\";\n\nexport interface GraphEdge {\n from: string; // relative memory path (e.g. \"facts/2026-02-22/abc.md\")\n to: string; // relative memory path\n type: GraphType;\n weight: number; // 1.0 default, decay applied during traversal\n label: string; // entity name, threadId, or matched causal phrase\n ts: string; // ISO timestamp of edge creation\n\n // Issue #681 — edge confidence + reinforcement (PR 1/3: schema + primitive only).\n // Both fields are optional so existing edges without confidence still validate.\n // Treat a missing `confidence` as 1.0 (legacy behavior) at read sites.\n // PR 2/3 wires the maintenance decay job; PR 3/3 weights PageRank traversal by confidence.\n confidence?: number; // [0, 1]; missing = 1.0\n lastReinforcedAt?: string; // ISO timestamp of most recent reinforcement\n}\n\nexport interface GraphConfig {\n multiGraphMemoryEnabled: boolean;\n entityGraphEnabled: boolean;\n timeGraphEnabled: boolean;\n causalGraphEnabled: boolean;\n maxGraphTraversalSteps: number;\n graphActivationDecay: number;\n maxEntityGraphEdgesPerMemory: number;\n graphLateralInhibitionEnabled: boolean;\n graphLateralInhibitionBeta: number;\n graphLateralInhibitionTopM: number;\n /**\n * Issue #681 PR 3/3 — minimum edge confidence required for traversal.\n * Edges with confidence below this floor are pruned. Legacy edges\n * (no `confidence` field) are treated as 1.0 and always pass.\n * Range `[0, 1]`. Default 0.2.\n */\n graphTraversalConfidenceFloor: number;\n /**\n * Issue #681 PR 3/3 — number of PageRank-style refinement iterations\n * applied on top of BFS activation. Set to 0 to disable refinement\n * and return raw BFS scores. Default 8.\n */\n graphTraversalPageRankIterations: number;\n}\n\n/** Default minimum edge confidence required for traversal (issue #681 PR 3/3). */\nexport const DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR = 0.2;\n/** Default PageRank-style refinement iteration count (issue #681 PR 3/3). */\nexport const DEFAULT_GRAPH_TRAVERSAL_PAGERANK_ITERATIONS = 8;\n\n// Causal signal phrases — order matters (most specific first)\nexport const CAUSAL_PHRASES = [\n \"as a result\",\n \"led to\",\n \"because of\",\n \"therefore\",\n \"caused\",\n \"because\",\n];\n\nexport function graphsDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"graphs\");\n}\n\nexport function graphFilePath(memoryDir: string, type: GraphType): string {\n return path.join(graphsDir(memoryDir), `${type}.jsonl`);\n}\n\nexport async function ensureGraphsDir(memoryDir: string): Promise<void> {\n await mkdir(graphsDir(memoryDir), { recursive: true });\n}\n\n// ---------------------------------------------------------------------------\n// Per-graph-file write lock (gotcha #40 promise-chain pattern).\n//\n// Both the append path (`appendEdge`) and the rewrite path used by the\n// decay maintenance job must serialize on the same lock keyed by the\n// JSONL file path. Without this, an extraction can append a new edge\n// between the decay job's read-snapshot and rewrite, silently dropping\n// the appended edge during active traffic (issue #729 / Codex P1).\n// ---------------------------------------------------------------------------\nconst graphWriteLocks = new Map<string, Promise<void>>();\n\n/**\n * Run `fn` while holding the write lock for the given graph JSONL file.\n *\n * The lock is keyed by absolute file path so concurrent writes to\n * different graph types proceed independently. The chain recovers from\n * rejection (gotcha #40) so a single I/O failure does not poison all\n * future writers, but the original error is still surfaced to the\n * caller of `withGraphWriteLock`.\n */\nexport function withGraphWriteLock<T>(filePath: string, fn: () => Promise<T>): Promise<T> {\n const prev = graphWriteLocks.get(filePath) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n graphWriteLocks.set(\n filePath,\n next.then(\n () => undefined,\n () => undefined,\n ),\n );\n return next;\n}\n\nexport async function appendEdge(memoryDir: string, edge: GraphEdge): Promise<void> {\n await ensureGraphsDir(memoryDir);\n const filePath = graphFilePath(memoryDir, edge.type);\n const line = JSON.stringify(edge) + \"\\n\";\n await withGraphWriteLock(filePath, async () => {\n await appendFile(filePath, line, \"utf8\");\n });\n // Emit edge-added event for SSE subscribers (issue #691 PR 5/5).\n // Fail-open: emitGraphEvent catches listener errors so a bad SSE client\n // can never surface into the extraction pipeline.\n emitGraphEvent(memoryDir, \"edge-added\", {\n source: edge.from,\n target: edge.to,\n kind: edge.type,\n weight: edge.weight,\n label: edge.label,\n confidence: typeof edge.confidence === \"number\" ? edge.confidence : 1.0,\n });\n}\n\nfunction isNodeError(err: unknown): err is NodeJS.ErrnoException {\n return typeof err === \"object\" && err !== null && \"code\" in err;\n}\n\nfunction parseEdgesJsonl(raw: string, expectedType: GraphType): GraphEdge[] {\n const edges: GraphEdge[] = [];\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (isValidGraphEdge(parsed, expectedType)) {\n edges.push(parsed);\n }\n } catch {\n // skip corrupt lines — fail-open for partial JSONL recovery\n }\n }\n return edges;\n}\n\n/**\n * Read all edges of a given type from the JSONL file.\n * Returns [] if the file doesn't exist or any read error occurs (fail-open).\n *\n * Production traversal callers (recall/PageRank) depend on this fail-open\n * posture so a temporarily missing or unreadable graph file never blocks\n * a recall. Maintenance jobs that need to distinguish ENOENT from real\n * I/O failures must use {@link readEdgesStrict} instead.\n */\nexport async function readEdges(memoryDir: string, type: GraphType): Promise<GraphEdge[]> {\n const filePath = graphFilePath(memoryDir, type);\n try {\n const raw = await readFile(filePath, \"utf8\");\n return parseEdgesJsonl(raw, type);\n } catch {\n return [];\n }\n}\n\n/**\n * Same as {@link readEdges} but only swallows `ENOENT`; all other read\n * errors (`EACCES`, `EIO`, …) are propagated. Used by the graph-edge\n * decay maintenance job so I/O outages surface as a failed run instead\n * of being silently reported as \"no edges to decay\" (issue #729 /\n * Codex P1, line 120).\n */\nexport async function readEdgesStrict(memoryDir: string, type: GraphType): Promise<GraphEdge[]> {\n const filePath = graphFilePath(memoryDir, type);\n try {\n const raw = await readFile(filePath, \"utf8\");\n return parseEdgesJsonl(raw, type);\n } catch (err) {\n if (isNodeError(err) && err.code === \"ENOENT\") {\n return [];\n }\n throw err;\n }\n}\n\n/**\n * Read edges from all enabled graph types.\n */\nexport async function readAllEdges(\n memoryDir: string,\n config: Pick<GraphConfig, \"entityGraphEnabled\" | \"timeGraphEnabled\" | \"causalGraphEnabled\">,\n): Promise<GraphEdge[]> {\n const parts: GraphEdge[][] = await Promise.all([\n config.entityGraphEnabled ? readEdges(memoryDir, \"entity\") : Promise.resolve([]),\n config.timeGraphEnabled ? readEdges(memoryDir, \"time\") : Promise.resolve([]),\n config.causalGraphEnabled ? readEdges(memoryDir, \"causal\") : Promise.resolve([]),\n ]);\n return parts.flat();\n}\n\nexport interface GraphHealthFileStats {\n type: GraphType;\n filePath: string;\n exists: boolean;\n totalLines: number;\n validEdges: number;\n corruptLines: number;\n uniqueNodes: number;\n}\n\nexport interface GraphHealthReport {\n generatedAt: string;\n enabledTypes: GraphType[];\n totals: {\n totalLines: number;\n validEdges: number;\n corruptLines: number;\n uniqueNodes: number;\n };\n files: GraphHealthFileStats[];\n repairGuidance?: string[];\n}\n\nfunction isValidGraphEdge(raw: unknown, expectedType: GraphType): raw is GraphEdge {\n if (!raw || typeof raw !== \"object\") return false;\n const edge = raw as Record<string, unknown>;\n return (\n edge.type === expectedType &&\n typeof edge.from === \"string\" && edge.from.length > 0 &&\n typeof edge.to === \"string\" && edge.to.length > 0 &&\n typeof edge.weight === \"number\" && Number.isFinite(edge.weight) &&\n typeof edge.label === \"string\" &&\n typeof edge.ts === \"string\"\n );\n}\n\nexport async function analyzeGraphHealth(\n memoryDir: string,\n options?: {\n entityGraphEnabled?: boolean;\n timeGraphEnabled?: boolean;\n causalGraphEnabled?: boolean;\n includeRepairGuidance?: boolean;\n },\n): Promise<GraphHealthReport> {\n const enabledTypes: GraphType[] = [];\n if (options?.entityGraphEnabled !== false) enabledTypes.push(\"entity\");\n if (options?.timeGraphEnabled !== false) enabledTypes.push(\"time\");\n if (options?.causalGraphEnabled !== false) enabledTypes.push(\"causal\");\n\n const files: GraphHealthFileStats[] = [];\n const globalNodes = new Set<string>();\n\n for (const type of enabledTypes) {\n const filePath = graphFilePath(memoryDir, type);\n let exists = true;\n let totalLines = 0;\n let validEdges = 0;\n let corruptLines = 0;\n const nodes = new Set<string>();\n\n try {\n const raw = await readFile(filePath, \"utf8\");\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n totalLines += 1;\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (!isValidGraphEdge(parsed, type)) {\n corruptLines += 1;\n continue;\n }\n validEdges += 1;\n nodes.add(parsed.from);\n nodes.add(parsed.to);\n globalNodes.add(parsed.from);\n globalNodes.add(parsed.to);\n } catch {\n corruptLines += 1;\n }\n }\n } catch {\n exists = false;\n }\n\n files.push({\n type,\n filePath,\n exists,\n totalLines,\n validEdges,\n corruptLines,\n uniqueNodes: nodes.size,\n });\n }\n\n const totals = files.reduce(\n (acc, item) => {\n acc.totalLines += item.totalLines;\n acc.validEdges += item.validEdges;\n acc.corruptLines += item.corruptLines;\n return acc;\n },\n {\n totalLines: 0,\n validEdges: 0,\n corruptLines: 0,\n uniqueNodes: globalNodes.size,\n },\n );\n totals.uniqueNodes = globalNodes.size;\n\n const report: GraphHealthReport = {\n generatedAt: new Date().toISOString(),\n enabledTypes,\n totals,\n files,\n };\n\n if (options?.includeRepairGuidance === true) {\n const guidance: string[] = [];\n if (totals.corruptLines > 0) {\n guidance.push(\"Corrupt graph lines detected: back up memory/state/graphs, then rebuild graphs from clean memory replay/extraction runs.\");\n }\n if (totals.validEdges === 0) {\n guidance.push(\"No valid edges detected yet: run normal extraction traffic (or replay ingestion) to seed graph files.\");\n }\n if (guidance.length > 0) report.repairGuidance = guidance;\n }\n\n return report;\n}\n\n/**\n * Detect causal signal phrases in text. Returns the first matched phrase, or null.\n */\nexport function detectCausalPhrase(text: string): string | null {\n const lower = text.toLowerCase();\n for (const phrase of CAUSAL_PHRASES) {\n if (lower.includes(phrase)) return phrase;\n }\n return null;\n}\n\n/**\n * GraphIndex — builds and updates the three memory graphs.\n *\n * Usage (orchestrator):\n * this.graphIndex = new GraphIndex(config.memoryDir, config);\n *\n * // After each memory write:\n * await this.graphIndex.onMemoryWritten(memoryPath, frontmatter, threadId, recentInThread);\n */\nexport class GraphIndex {\n private readonly memoryDir: string;\n private readonly cfg: GraphConfig;\n\n // Cache for readAllEdges() result. With 30k+ entity edges (6 MB JSONL) the\n // file read + JSON parse takes 2-4 s per call. This instance-level cache\n // eliminates that overhead on every spreadingActivation() call; it is\n // invalidated (set to null) in onMemoryWritten() so new edges appear promptly.\n private edgeCache: { allEdges: GraphEdge[]; loadedAt: number } | null = null;\n private static readonly EDGE_CACHE_TTL_MS = 300_000; // 5 minutes\n\n constructor(memoryDir: string, cfg: GraphConfig) {\n this.memoryDir = memoryDir;\n this.cfg = cfg;\n }\n\n /** Clear the edge cache so the next spreadingActivation() re-reads from disk.\n * Call after any code path that appends edges outside of onMemoryWritten(). */\n invalidateEdgeCache(): void {\n this.edgeCache = null;\n }\n\n private async loadEdgesCached(): Promise<GraphEdge[]> {\n if (\n this.edgeCache &&\n Date.now() - this.edgeCache.loadedAt < GraphIndex.EDGE_CACHE_TTL_MS\n ) {\n return this.edgeCache.allEdges;\n }\n const allEdges = await readAllEdges(this.memoryDir, {\n entityGraphEnabled: this.cfg.entityGraphEnabled,\n timeGraphEnabled: this.cfg.timeGraphEnabled,\n causalGraphEnabled: this.cfg.causalGraphEnabled,\n });\n this.edgeCache = { allEdges, loadedAt: Date.now() };\n return allEdges;\n }\n\n /**\n * Called after a memory is written to disk.\n *\n * @param memoryPath - relative path from memoryDir (e.g. \"facts/2026-02-22/abc.md\")\n * @param entityRef - entityRef frontmatter field (if any)\n * @param content - full memory text (for causal detection)\n * @param created - ISO timestamp of this memory\n * @param threadId - current thread ID (for time graph)\n * @param recentInThread - paths of the N most-recent memories in this thread (for time graph)\n * @param entitySiblings - paths of other memories that share the same entityRef (for entity graph)\n */\n async onMemoryWritten(opts: {\n memoryPath: string;\n entityRef?: string;\n content: string;\n created: string;\n threadId?: string;\n recentInThread?: string[];\n entitySiblings?: string[];\n causalPredecessor?: string;\n }): Promise<void> {\n if (!this.cfg.multiGraphMemoryEnabled) return;\n const ts = new Date().toISOString();\n\n try {\n // Entity graph\n if (this.cfg.entityGraphEnabled && opts.entityRef && opts.entitySiblings?.length) {\n const siblings = opts.entitySiblings.slice(0, this.cfg.maxEntityGraphEdgesPerMemory);\n for (const sibling of siblings) {\n await appendEdge(this.memoryDir, {\n from: opts.memoryPath,\n to: sibling,\n type: \"entity\",\n weight: 1.0,\n label: opts.entityRef,\n ts,\n });\n }\n }\n\n // Time graph — link to most recent memory in same thread\n if (this.cfg.timeGraphEnabled && opts.threadId && opts.recentInThread?.length) {\n const predecessor = opts.recentInThread[opts.recentInThread.length - 1];\n if (predecessor && predecessor !== opts.memoryPath) {\n await appendEdge(this.memoryDir, {\n from: predecessor,\n to: opts.memoryPath,\n type: \"time\",\n weight: 1.0,\n label: opts.threadId,\n ts,\n });\n }\n }\n\n // Causal graph\n if (this.cfg.causalGraphEnabled && opts.causalPredecessor) {\n const phrase = detectCausalPhrase(opts.content);\n if (phrase) {\n await appendEdge(this.memoryDir, {\n from: opts.causalPredecessor,\n to: opts.memoryPath,\n type: \"causal\",\n weight: 1.0,\n label: phrase,\n ts,\n });\n }\n }\n } catch (err) {\n // Fail-open: graph write errors must never surface to caller\n const { log } = await import(\"./logger.js\");\n log.warn(`[graph] onMemoryWritten error: ${err}`);\n } finally {\n // Invalidate edge cache so spreadingActivation() picks up new edges.\n // In `finally` so the cache is cleared even on partial write failure.\n this.edgeCache = null;\n }\n }\n\n /**\n * Spreading activation BFS (SYNAPSE-inspired).\n *\n * Starting from `seeds`, traverse the combined graph for up to `maxSteps` hops.\n * Each candidate gets an activation score = edge.weight × edgeConfidence × decay^hop.\n *\n * Issue #681 PR 3/3 — confidence-aware traversal:\n * - Each edge's `weight` is multiplied by its `confidence` (legacy edges\n * missing `confidence` are treated as 1.0, preserving prior behavior).\n * - Edges with `confidence < graphTraversalConfidenceFloor` are pruned and\n * contribute neither activation nor downstream neighbors.\n * - When `graphTraversalPageRankIterations > 0`, an additional PageRank-\n * style refinement pass redistributes activation along confidence-weighted\n * edges, sharpening the ranking among multi-hop candidates.\n * - Per-result provenance includes the highest-confidence edge that landed\n * on each candidate, so the X-ray surface can attribute pruning and\n * ranking decisions back to specific edges.\n *\n * @param seeds - initial memory paths to expand from (e.g. QMD top results)\n * @param maxSteps - max BFS hops (from config: maxGraphTraversalSteps)\n * @returns Array of {path, score, edgeConfidence, ...} sorted descending, not including seed paths\n */\n async spreadingActivation(\n seeds: string[],\n maxSteps?: number,\n opts?: {\n /**\n * Issue #681 — when `true`, bypasses the configured\n * `graphTraversalConfidenceFloor` and includes low-confidence\n * edges in traversal. Equivalent to forcing the floor to `0`.\n * Default `false` (floor from config is applied).\n */\n includeLowConfidence?: boolean;\n },\n ): Promise<Array<{\n path: string;\n score: number;\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n /**\n * Confidence of the edge that produced this candidate's recorded\n * provenance (the strongest edge along the chosen entry path).\n * In `[0, 1]`. Legacy edges without `confidence` surface as 1.0.\n */\n edgeConfidence: number;\n }>> {\n if (!this.cfg.multiGraphMemoryEnabled) return [];\n const steps = maxSteps ?? this.cfg.maxGraphTraversalSteps;\n const decay = this.cfg.graphActivationDecay;\n // When `includeLowConfidence` is set, use floor=0 so all edges\n // participate in traversal regardless of their decay state.\n // Otherwise clamp the configured floor into [0, 1] so misconfiguration\n // cannot (a) admit edges with negative confidence or (b) reject every\n // edge.\n const floor = opts?.includeLowConfidence === true\n ? 0\n : clampConfidenceFloor(this.cfg.graphTraversalConfidenceFloor);\n const iterations = clampPageRankIterations(\n this.cfg.graphTraversalPageRankIterations,\n );\n\n try {\n const allEdges = await this.loadEdgesCached();\n\n // Build adjacency index: from → edges, to → edges (bidirectional for entity/time, directional for causal).\n // Edges below the confidence floor are pruned at index time so neither\n // direct activation nor downstream BFS expansion can re-introduce them.\n const adj = new Map<string, GraphEdge[]>();\n for (const edge of allEdges) {\n const conf = readEdgeConfidence(edge);\n if (conf < floor) continue;\n if (!adj.has(edge.from)) adj.set(edge.from, []);\n adj.get(edge.from)!.push(edge);\n // Entity and time edges are bidirectional\n if (edge.type !== \"causal\") {\n if (!adj.has(edge.to)) adj.set(edge.to, []);\n adj.get(edge.to)!.push({ ...edge, from: edge.to, to: edge.from });\n }\n }\n\n const seedSet = new Set(seeds);\n const scores = new Map<string, number>(); // candidate path → accumulated activation score\n const provenance = new Map<\n string,\n {\n seed: string;\n hopDepth: number;\n decayedWeight: number;\n graphType: \"entity\" | \"time\" | \"causal\";\n edgeConfidence: number;\n }\n >();\n const visited = new Set<string>(seeds);\n\n // BFS queue: [nodePath, hop, seedPath]\n const queue: Array<[string, number, string]> = seeds.map((s) => [s, 0, s]);\n\n while (queue.length > 0) {\n const [node, hop, sourceSeed] = queue.shift()!;\n if (hop >= steps) continue;\n\n const edges = adj.get(node) ?? [];\n for (const edge of edges) {\n const neighbor = edge.to === node ? edge.from : edge.to;\n const conf = readEdgeConfidence(edge);\n // Defense in depth: the adjacency build already drops sub-floor\n // edges, but if a synthesized reverse edge ever bypassed that\n // path, this guard keeps spreading activation honest.\n if (conf < floor) continue;\n const score = edge.weight * conf * Math.pow(decay, hop + 1);\n\n if (!seedSet.has(neighbor)) {\n const existing = scores.get(neighbor) ?? 0;\n scores.set(neighbor, existing + score);\n\n const prev = provenance.get(neighbor);\n if (\n !prev ||\n hop + 1 < prev.hopDepth ||\n (hop + 1 === prev.hopDepth && score > prev.decayedWeight)\n ) {\n provenance.set(neighbor, {\n seed: sourceSeed,\n hopDepth: hop + 1,\n decayedWeight: score,\n graphType: edge.type,\n edgeConfidence: conf,\n });\n }\n }\n\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n queue.push([neighbor, hop + 1, sourceSeed]);\n }\n }\n }\n\n // Issue #681 PR 3/3 — optional PageRank-style refinement.\n // Redistributes a node's accumulated activation along its outgoing\n // edges, weighted by edge confidence. Damping is fixed at the\n // canonical 0.85 so the ranking stays comparable across queries;\n // the `iterations` knob bounds compute, not behavior shape.\n if (iterations > 0 && scores.size > 1) {\n applyPageRankRefinement(scores, adj, {\n iterations,\n floor,\n damping: 0.85,\n });\n }\n\n // Apply lateral inhibition if enabled (Synapse-inspired competitive suppression)\n if (this.cfg.graphLateralInhibitionEnabled && scores.size > 1) {\n const inhibited = applyLateralInhibition(scores, {\n beta: this.cfg.graphLateralInhibitionBeta,\n topM: this.cfg.graphLateralInhibitionTopM,\n });\n for (const [k, v] of inhibited) {\n scores.set(k, v);\n }\n }\n\n return Array.from(scores.entries())\n .map(([p, score]) => ({\n path: p,\n score,\n seed: provenance.get(p)?.seed ?? \"\",\n hopDepth: provenance.get(p)?.hopDepth ?? 0,\n decayedWeight: provenance.get(p)?.decayedWeight ?? 0,\n graphType: provenance.get(p)?.graphType ?? \"entity\",\n edgeConfidence: provenance.get(p)?.edgeConfidence ?? 1,\n }))\n .sort((a, b) => b.score - a.score);\n } catch (err) {\n const { log } = await import(\"./logger.js\");\n log.warn(`[graph] spreadingActivation error: ${err}`);\n return [];\n }\n }\n}\n\n/**\n * Clamp `graphTraversalConfidenceFloor` into the legal range `[0, 1]`.\n * Non-finite or non-numeric values fall back to the documented default\n * so misconfiguration cannot silently disable the floor or reject every edge.\n *\n * Exported for tests; call sites in `spreadingActivation` use it to make\n * the contract explicit at every boundary.\n */\nexport function clampConfidenceFloor(raw: unknown): number {\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) {\n return DEFAULT_GRAPH_TRAVERSAL_CONFIDENCE_FLOOR;\n }\n if (raw < 0) return 0;\n if (raw > 1) return 1;\n return raw;\n}\n\n/**\n * Clamp `graphTraversalPageRankIterations` into a non-negative integer.\n * Negative or non-finite values fall back to 0 (disable refinement) so\n * misconfiguration cannot stall recall in an unbounded loop.\n */\nexport function clampPageRankIterations(raw: unknown): number {\n if (typeof raw !== \"number\" || !Number.isFinite(raw)) return 0;\n if (raw <= 0) return 0;\n return Math.floor(raw);\n}\n\n/**\n * PageRank-style refinement on top of the BFS activation map.\n *\n * Each iteration redistributes a fraction of every node's score along\n * its outgoing edges, scaled by edge confidence. Confidence below\n * `floor` is filtered out before redistribution, mirroring the BFS\n * pruning rule. Mutates `scores` in place.\n *\n * Exported for tests; in production, call sites pass the same adjacency\n * map already used by BFS so behavior stays consistent.\n */\nexport function applyPageRankRefinement(\n scores: Map<string, number>,\n adj: Map<string, GraphEdge[]>,\n opts: { iterations: number; floor: number; damping: number },\n): void {\n const { iterations, floor, damping } = opts;\n if (iterations <= 0 || scores.size === 0) return;\n const safeDamping = Math.min(1, Math.max(0, damping));\n\n // Pre-compute confidence-weighted out-edge totals for normalization.\n // Done once per refinement, not per iteration, since adjacency is\n // immutable inside the loop.\n //\n // Codex P1 (#735): the denominator MUST be computed over the same\n // eligible-neighbor set the iteration redistributes into — i.e.\n // edges whose neighbor is in `scores`. Counting edges-to-seeds (or\n // edges-to-unseen-nodes) in the denominator while dropping their\n // flow during iteration leaks `safeDamping × score` every pass and\n // collapses leaf candidates' scores instead of just re-ranking them.\n const eligible = (edge: GraphEdge, fromNode: string): boolean => {\n if (readEdgeConfidence(edge) < floor) return false;\n const neighbor = edge.to === fromNode ? edge.from : edge.to;\n return scores.has(neighbor);\n };\n const outboundTotal = new Map<string, number>();\n for (const [node, edges] of adj.entries()) {\n if (!scores.has(node)) continue; // only candidate nodes redistribute\n let sum = 0;\n for (const edge of edges) {\n if (!eligible(edge, node)) continue;\n sum += readEdgeConfidence(edge) * edge.weight;\n }\n if (sum > 0) outboundTotal.set(node, sum);\n }\n\n for (let i = 0; i < iterations; i += 1) {\n const next = new Map<string, number>();\n // Teleport / damping floor: every node retains `(1 - damping) * score`\n // of its current activation so dangling nodes do not bleed to zero.\n for (const [node, score] of scores) {\n next.set(node, (1 - safeDamping) * score);\n }\n for (const [node, score] of scores) {\n const outEdges = adj.get(node);\n const total = outboundTotal.get(node);\n // Dangling-node fallback: when a candidate has zero eligible\n // outflow (no in-scores neighbors above the floor), the\n // `safeDamping × score` portion would otherwise evaporate. Keep\n // it on `node` so total mass is conserved and the score reflects\n // the candidate's standing rather than its in-degree topology.\n if (!outEdges || outEdges.length === 0 || !total || total <= 0) {\n next.set(node, (next.get(node) ?? 0) + safeDamping * score);\n continue;\n }\n for (const edge of outEdges) {\n if (!eligible(edge, node)) continue;\n const conf = readEdgeConfidence(edge);\n const neighbor = edge.to === node ? edge.from : edge.to;\n const flow = safeDamping * score * ((conf * edge.weight) / total);\n next.set(neighbor, (next.get(neighbor) ?? 0) + flow);\n }\n }\n for (const [node, score] of next) {\n scores.set(node, score);\n }\n }\n}\n\n/**\n * Lateral inhibition (Synapse-inspired).\n *\n * For each node, the top-M higher-activation competitors exert inhibition\n * proportional to their activation difference. Output is clamped to [0, ∞).\n *\n * No sigmoid is applied here — downstream `normalizeGraphActivationScore`\n * already applies x/(1+x) soft squash, so adding a sigmoid would double-\n * normalize and cap graph influence at ~50%.\n *\n * Formula: u_hat_i = max(0, u_i - beta * sum_{k in top-M where u_k > u_i}(u_k - u_i))\n *\n * When beta=0 or topM=0, returns original scores unchanged (no-op).\n */\nexport function applyLateralInhibition(\n scores: Map<string, number>,\n opts: { beta: number; topM: number },\n): Map<string, number> {\n const { beta, topM } = opts;\n if (beta === 0 || topM === 0) return new Map(scores);\n\n const sorted = Array.from(scores.entries()).sort((a, b) => b[1] - a[1]);\n const topCompetitors = sorted.slice(0, topM);\n\n const result = new Map<string, number>();\n for (const [node, u] of scores) {\n let inhibition = 0;\n for (const [, uK] of topCompetitors) {\n if (uK > u) {\n inhibition += uK - u;\n }\n }\n result.set(node, Math.max(0, u - beta * inhibition));\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;AAYA,SAAS,OAAO,YAAY,gBAAgB;AAC5C,YAAY,UAAU;AAkDf,IAAM,2CAA2C;AAEjD,IAAM,8CAA8C;AAGpD,IAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,UAAU,WAA2B;AACnD,SAAY,UAAK,WAAW,SAAS,QAAQ;AAC/C;AAEO,SAAS,cAAc,WAAmB,MAAyB;AACxE,SAAY,UAAK,UAAU,SAAS,GAAG,GAAG,IAAI,QAAQ;AACxD;AAEA,eAAsB,gBAAgB,WAAkC;AACtE,QAAM,MAAM,UAAU,SAAS,GAAG,EAAE,WAAW,KAAK,CAAC;AACvD;AAWA,IAAM,kBAAkB,oBAAI,IAA2B;AAWhD,SAAS,mBAAsB,UAAkB,IAAkC;AACxF,QAAM,OAAO,gBAAgB,IAAI,QAAQ,KAAK,QAAQ,QAAQ;AAC9D,QAAM,OAAO,KAAK,KAAK,IAAI,EAAE;AAC7B,kBAAgB;AAAA,IACd;AAAA,IACA,KAAK;AAAA,MACH,MAAM;AAAA,MACN,MAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,WAAW,WAAmB,MAAgC;AAClF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