@remnic/core 1.1.0 → 1.1.1
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.
- package/dist/access-audit.d.ts +56 -0
- package/dist/access-audit.js +9 -0
- package/dist/access-cli.js +62 -45
- package/dist/access-cli.js.map +1 -1
- package/dist/access-http.d.ts +16 -9
- package/dist/access-http.js +25 -17
- package/dist/access-mcp.d.ts +16 -9
- package/dist/access-mcp.js +29 -7
- package/dist/access-schema.d.ts +124 -33
- package/dist/access-schema.js +5 -1
- package/dist/{access-service-HmO1Trrx.d.ts → access-service-Br8ZydTK.d.ts} +158 -63
- package/dist/access-service.d.ts +13 -6
- package/dist/access-service.js +22 -14
- package/dist/bootstrap.d.ts +6 -3
- package/dist/briefing.d.ts +1 -0
- package/dist/briefing.js +7 -6
- package/dist/buffer-surprise-report.d.ts +70 -0
- package/dist/buffer-surprise-report.js +7 -0
- package/dist/buffer-surprise-report.js.map +1 -0
- package/dist/buffer-surprise.d.ts +98 -0
- package/dist/buffer-surprise.js +11 -0
- package/dist/buffer-surprise.js.map +1 -0
- package/dist/buffer.d.ts +100 -2
- package/dist/buffer.js +1 -1
- package/dist/calibration.js +5 -5
- package/dist/causal-behavior.js +4 -4
- package/dist/causal-chain.js +2 -2
- package/dist/causal-consolidation.js +17 -16
- package/dist/causal-consolidation.js.map +1 -1
- package/dist/causal-retrieval.js +4 -4
- package/dist/causal-trajectory.js +1 -1
- package/dist/{chunk-QNJMBKFK.js → chunk-2LGMW3DJ.js} +3 -2
- package/dist/chunk-2LGMW3DJ.js.map +1 -0
- package/dist/{chunk-QDYXG4CS.js → chunk-3FPTCC3Z.js} +4 -3
- package/dist/chunk-3FPTCC3Z.js.map +1 -0
- package/dist/chunk-3GPTTA4J.js +57 -0
- package/dist/chunk-3GPTTA4J.js.map +1 -0
- package/dist/{chunk-44ICJRF3.js → chunk-3GXCSUXR.js} +4 -4
- package/dist/{chunk-ITRLGI2T.js → chunk-3OGMS3PE.js} +2 -2
- package/dist/chunk-54V4BZWP.js +139 -0
- package/dist/chunk-54V4BZWP.js.map +1 -0
- package/dist/chunk-5JRF2PZA.js +67 -0
- package/dist/chunk-5JRF2PZA.js.map +1 -0
- package/dist/chunk-64NJRYU2.js +332 -0
- package/dist/chunk-64NJRYU2.js.map +1 -0
- package/dist/{chunk-OIT5QGG4.js → chunk-6AUUAZEX.js} +72 -2
- package/dist/chunk-6AUUAZEX.js.map +1 -0
- package/dist/{chunk-ZVBB3T7V.js → chunk-7I7FKFZH.js} +24 -22
- package/dist/chunk-7I7FKFZH.js.map +1 -0
- package/dist/chunk-AJU4PJGY.js +126 -0
- package/dist/chunk-AJU4PJGY.js.map +1 -0
- package/dist/chunk-ASAITVLA.js +64 -0
- package/dist/chunk-ASAITVLA.js.map +1 -0
- package/dist/{chunk-3QHL5ABG.js → chunk-B5WXLVDY.js} +187 -6
- package/dist/chunk-B5WXLVDY.js.map +1 -0
- package/dist/{chunk-SYUK3VLY.js → chunk-BGJGXLZ7.js} +111 -2
- package/dist/{chunk-SYUK3VLY.js.map → chunk-BGJGXLZ7.js.map} +1 -1
- package/dist/{chunk-MBJHSA7F.js → chunk-BK2EFTE2.js} +258 -13
- package/dist/chunk-BK2EFTE2.js.map +1 -0
- package/dist/chunk-C4SQJZAF.js +486 -0
- package/dist/chunk-C4SQJZAF.js.map +1 -0
- package/dist/{chunk-6UJ47TVX.js → chunk-CUPFXL3J.js} +2 -2
- package/dist/chunk-DF3RVK3X.js +119 -0
- package/dist/chunk-DF3RVK3X.js.map +1 -0
- package/dist/{chunk-37UIFYWO.js → chunk-DFTTJYSO.js} +108 -9
- package/dist/chunk-DFTTJYSO.js.map +1 -0
- package/dist/chunk-DGVM5SFL.js +69 -0
- package/dist/chunk-DGVM5SFL.js.map +1 -0
- package/dist/chunk-EIR5VLIH.js +90 -0
- package/dist/chunk-EIR5VLIH.js.map +1 -0
- package/dist/{chunk-PAORGQRI.js → chunk-EPQJM2GC.js} +37 -23
- package/dist/chunk-EPQJM2GC.js.map +1 -0
- package/dist/{chunk-GV6NLQ4X.js → chunk-F5VP6YCB.js} +374 -16
- package/dist/chunk-F5VP6YCB.js.map +1 -0
- package/dist/{chunk-6ZH4TU6I.js → chunk-FAAFWE4G.js} +2 -1
- package/dist/chunk-FAAFWE4G.js.map +1 -0
- package/dist/{chunk-7WQ6SLIE.js → chunk-FVA6TGI3.js} +2 -2
- package/dist/chunk-GDFS42HT.js +206 -0
- package/dist/chunk-GDFS42HT.js.map +1 -0
- package/dist/{chunk-MVTHXUBX.js → chunk-GKFXUTJ2.js} +479 -20
- package/dist/chunk-GKFXUTJ2.js.map +1 -0
- package/dist/{chunk-NQEVYWX6.js → chunk-HK3FGIEW.js} +209 -5
- package/dist/chunk-HK3FGIEW.js.map +1 -0
- package/dist/chunk-IISBCCWR.js +52 -0
- package/dist/chunk-IISBCCWR.js.map +1 -0
- package/dist/{chunk-WBSAYXVI.js → chunk-INXV5JBT.js} +198 -42
- package/dist/chunk-INXV5JBT.js.map +1 -0
- package/dist/chunk-JBMSGZEQ.js +441 -0
- package/dist/chunk-JBMSGZEQ.js.map +1 -0
- package/dist/{chunk-J4IYOZZ5.js → chunk-JXS5PDQ7.js} +3 -1
- package/dist/chunk-JXS5PDQ7.js.map +1 -0
- package/dist/{chunk-6LX5ORAS.js → chunk-KUB6JU6H.js} +4 -4
- package/dist/chunk-KVBLZUKV.js +173 -0
- package/dist/chunk-KVBLZUKV.js.map +1 -0
- package/dist/chunk-LBLXEFWK.js +51 -0
- package/dist/chunk-LBLXEFWK.js.map +1 -0
- package/dist/{chunk-3WHVNEN7.js → chunk-LTCGGW2D.js} +1 -1
- package/dist/chunk-LTCGGW2D.js.map +1 -0
- package/dist/{chunk-UEYA6UC7.js → chunk-NZLQTHS5.js} +25 -2
- package/dist/chunk-NZLQTHS5.js.map +1 -0
- package/dist/chunk-PVPWZSSI.js +37 -0
- package/dist/chunk-PVPWZSSI.js.map +1 -0
- package/dist/{chunk-4NRAJUDS.js → chunk-RBBWYEFJ.js} +1 -1
- package/dist/chunk-RFYAYKTD.js +146 -0
- package/dist/chunk-RFYAYKTD.js.map +1 -0
- package/dist/{chunk-DHHP2Z4X.js → chunk-RGLL5SPU.js} +2 -2
- package/dist/{chunk-3SV6CQHO.js → chunk-S3EEFKNY.js} +101 -65
- package/dist/chunk-S3EEFKNY.js.map +1 -0
- package/dist/chunk-SOBJ6NEY.js +18 -0
- package/dist/chunk-SOBJ6NEY.js.map +1 -0
- package/dist/{chunk-JIU55F3X.js → chunk-SPI27QT6.js} +2 -2
- package/dist/chunk-TVVEYCNW.js +65 -0
- package/dist/chunk-TVVEYCNW.js.map +1 -0
- package/dist/chunk-ULYOGL6R.js +322 -0
- package/dist/chunk-ULYOGL6R.js.map +1 -0
- package/dist/{chunk-47UU5PU2.js → chunk-VBVG2M5G.js} +18 -3
- package/dist/chunk-VBVG2M5G.js.map +1 -0
- package/dist/{chunk-7ECD5ATE.js → chunk-VDX363PS.js} +2 -2
- package/dist/{chunk-DEPL3635.js → chunk-VYM3VWOF.js} +1432 -188
- package/dist/chunk-VYM3VWOF.js.map +1 -0
- package/dist/{chunk-MTLYEMJB.js → chunk-WCLICCGB.js} +18 -3
- package/dist/chunk-WCLICCGB.js.map +1 -0
- package/dist/{chunk-4LACOVZX.js → chunk-WVVA7F5A.js} +2 -2
- package/dist/chunk-X6GF3FX2.js +26 -0
- package/dist/chunk-X6GF3FX2.js.map +1 -0
- package/dist/{chunk-3QFQGRHO.js → chunk-XMHBH5H6.js} +4 -4
- package/dist/{chunk-BLKTA7MM.js → chunk-YNQKWQT4.js} +50 -17
- package/dist/chunk-YNQKWQT4.js.map +1 -0
- package/dist/chunk-ZAIM4TUE.js +488 -0
- package/dist/chunk-ZAIM4TUE.js.map +1 -0
- package/dist/{chunk-N42IWANG.js → chunk-ZEM3OK2K.js} +2 -2
- package/dist/chunk-ZZTOURJI.js +91 -0
- package/dist/chunk-ZZTOURJI.js.map +1 -0
- package/dist/{cli-BneVIEvh.d.ts → cli-BkeRaYfk.d.ts} +2 -2
- package/dist/cli.d.ts +13 -6
- package/dist/cli.js +40 -29
- package/dist/config.js +1 -1
- package/dist/consolidation-operator.d.ts +41 -0
- package/dist/consolidation-operator.js +11 -0
- package/dist/consolidation-operator.js.map +1 -0
- package/dist/consolidation-provenance-check.d.ts +68 -0
- package/dist/consolidation-provenance-check.js +9 -0
- package/dist/consolidation-provenance-check.js.map +1 -0
- package/dist/consolidation-undo.d.ts +123 -0
- package/dist/consolidation-undo.js +426 -0
- package/dist/consolidation-undo.js.map +1 -0
- package/dist/{contradiction-scan-GR33PONM.js → contradiction-scan-E3GJTI4F.js} +43 -7
- package/dist/contradiction-scan-E3GJTI4F.js.map +1 -0
- package/dist/cross-namespace-budget.d.ts +133 -0
- package/dist/cross-namespace-budget.js +9 -0
- package/dist/cross-namespace-budget.js.map +1 -0
- package/dist/direct-answer-wiring.js +5 -70
- package/dist/direct-answer-wiring.js.map +1 -1
- package/dist/{engine-5TIQBYZR.js → engine-F3GOXGE5.js} +8 -7
- package/dist/engine-F3GOXGE5.js.map +1 -0
- package/dist/entity-retrieval.d.ts +1 -0
- package/dist/entity-retrieval.js +7 -6
- package/dist/explicit-capture.d.ts +6 -3
- package/dist/explicit-capture.js +2 -2
- package/dist/extraction-judge-telemetry.d.ts +113 -0
- package/dist/extraction-judge-telemetry.js +14 -0
- package/dist/extraction-judge-telemetry.js.map +1 -0
- package/dist/extraction-judge-training.d.ts +85 -0
- package/dist/extraction-judge-training.js +16 -0
- package/dist/extraction-judge-training.js.map +1 -0
- package/dist/extraction-judge.d.ts +124 -2
- package/dist/extraction-judge.js +11 -1
- package/dist/extraction.js +6 -5
- package/dist/fallback-llm.js +2 -2
- package/dist/graph-recall.d.ts +100 -0
- package/dist/graph-recall.js +8 -0
- package/dist/graph-recall.js.map +1 -0
- package/dist/graph-retrieval.d.ts +271 -0
- package/dist/graph-retrieval.js +21 -0
- package/dist/graph-retrieval.js.map +1 -0
- package/dist/importance.js +1 -1
- package/dist/index.d.ts +585 -20
- package/dist/index.js +503 -312
- package/dist/index.js.map +1 -1
- package/dist/memory-worth-bench.d.ts +51 -0
- package/dist/memory-worth-bench.js +131 -0
- package/dist/memory-worth-bench.js.map +1 -0
- package/dist/memory-worth-filter.d.ts +128 -0
- package/dist/memory-worth-filter.js +10 -0
- package/dist/memory-worth-filter.js.map +1 -0
- package/dist/memory-worth-outcomes.d.ts +118 -0
- package/dist/memory-worth-outcomes.js +9 -0
- package/dist/memory-worth-outcomes.js.map +1 -0
- package/dist/memory-worth.d.ts +102 -0
- package/dist/memory-worth.js +7 -0
- package/dist/memory-worth.js.map +1 -0
- package/dist/operator-toolkit.d.ts +40 -1
- package/dist/operator-toolkit.js +23 -14
- package/dist/{orchestrator-DRYA6_lW.d.ts → orchestrator-CmJ-NTdJ.d.ts} +233 -8
- package/dist/orchestrator.d.ts +6 -3
- package/dist/orchestrator.js +49 -39
- package/dist/page-versioning.d.ts +12 -1
- package/dist/page-versioning.js +5 -3
- package/dist/{port-C1GZFv8h.d.ts → port-BADbLZU5.d.ts} +2 -2
- package/dist/qmd-recall-cache.d.ts +1 -1
- package/dist/qmd.d.ts +5 -3
- package/dist/qmd.js +1 -1
- package/dist/reasoning-trace-recall.d.ts +90 -0
- package/dist/reasoning-trace-recall.js +13 -0
- package/dist/reasoning-trace-recall.js.map +1 -0
- package/dist/reasoning-trace-types.d.ts +54 -0
- package/dist/reasoning-trace-types.js +17 -0
- package/dist/reasoning-trace-types.js.map +1 -0
- package/dist/recall-audit-anomaly.d.ts +112 -0
- package/dist/recall-audit-anomaly.js +11 -0
- package/dist/recall-audit-anomaly.js.map +1 -0
- package/dist/recall-audit.js +5 -44
- package/dist/recall-audit.js.map +1 -1
- package/dist/recall-explain-renderer.d.ts +49 -0
- package/dist/recall-explain-renderer.js +18 -0
- package/dist/recall-explain-renderer.js.map +1 -0
- package/dist/recall-state.d.ts +12 -1
- package/dist/recall-state.js +1 -1
- package/dist/recall-xray-cli.d.ts +40 -0
- package/dist/recall-xray-cli.js +11 -0
- package/dist/recall-xray-cli.js.map +1 -0
- package/dist/recall-xray-renderer.d.ts +44 -0
- package/dist/recall-xray-renderer.js +18 -0
- package/dist/recall-xray-renderer.js.map +1 -0
- package/dist/recall-xray.d.ts +179 -0
- package/dist/recall-xray.js +13 -0
- package/dist/recall-xray.js.map +1 -0
- package/dist/resume-bundles.js +5 -5
- package/dist/retrieval-agents.d.ts +1 -1
- package/dist/retrieval-tiers.d.ts +17 -0
- package/dist/retrieval-tiers.js +9 -0
- package/dist/retrieval-tiers.js.map +1 -0
- package/dist/schemas.d.ts +287 -31
- package/dist/schemas.js +1 -1
- package/dist/{semantic-consolidation-DrvSYRdB.d.ts → semantic-consolidation-CxJU6MJk.d.ts} +62 -1
- package/dist/semantic-consolidation.d.ts +2 -1
- package/dist/semantic-consolidation.js +21 -7
- package/dist/semantic-rule-promotion.js +7 -6
- package/dist/semantic-rule-verifier.js +7 -6
- package/dist/storage.d.ts +82 -1
- package/dist/storage.js +6 -5
- package/dist/summarizer.js +3 -3
- package/dist/temporal-supersession.d.ts +1 -0
- package/dist/tier-migration.d.ts +2 -1
- package/dist/types.d.ts +276 -2
- package/dist/types.js +1 -1
- package/dist/verified-recall.js +7 -6
- package/package.json +1 -1
- package/dist/chunk-37UIFYWO.js.map +0 -1
- package/dist/chunk-3QHL5ABG.js.map +0 -1
- package/dist/chunk-3SV6CQHO.js.map +0 -1
- package/dist/chunk-3WHVNEN7.js.map +0 -1
- package/dist/chunk-47UU5PU2.js.map +0 -1
- package/dist/chunk-6ZH4TU6I.js.map +0 -1
- package/dist/chunk-BLKTA7MM.js.map +0 -1
- package/dist/chunk-DEPL3635.js.map +0 -1
- package/dist/chunk-GV6NLQ4X.js.map +0 -1
- package/dist/chunk-J4IYOZZ5.js.map +0 -1
- package/dist/chunk-LAYN4LDC.js +0 -267
- package/dist/chunk-LAYN4LDC.js.map +0 -1
- package/dist/chunk-MBJHSA7F.js.map +0 -1
- package/dist/chunk-MTLYEMJB.js.map +0 -1
- package/dist/chunk-MVTHXUBX.js.map +0 -1
- package/dist/chunk-NQEVYWX6.js.map +0 -1
- package/dist/chunk-OIT5QGG4.js.map +0 -1
- package/dist/chunk-PAORGQRI.js.map +0 -1
- package/dist/chunk-QDYXG4CS.js.map +0 -1
- package/dist/chunk-QNJMBKFK.js.map +0 -1
- package/dist/chunk-UEYA6UC7.js.map +0 -1
- package/dist/chunk-UVJFDP7P.js +0 -202
- package/dist/chunk-UVJFDP7P.js.map +0 -1
- package/dist/chunk-WBSAYXVI.js.map +0 -1
- package/dist/chunk-ZVBB3T7V.js.map +0 -1
- package/dist/contradiction-scan-GR33PONM.js.map +0 -1
- /package/dist/{engine-5TIQBYZR.js.map → access-audit.js.map} +0 -0
- /package/dist/{chunk-44ICJRF3.js.map → chunk-3GXCSUXR.js.map} +0 -0
- /package/dist/{chunk-ITRLGI2T.js.map → chunk-3OGMS3PE.js.map} +0 -0
- /package/dist/{chunk-6UJ47TVX.js.map → chunk-CUPFXL3J.js.map} +0 -0
- /package/dist/{chunk-7WQ6SLIE.js.map → chunk-FVA6TGI3.js.map} +0 -0
- /package/dist/{chunk-6LX5ORAS.js.map → chunk-KUB6JU6H.js.map} +0 -0
- /package/dist/{chunk-4NRAJUDS.js.map → chunk-RBBWYEFJ.js.map} +0 -0
- /package/dist/{chunk-DHHP2Z4X.js.map → chunk-RGLL5SPU.js.map} +0 -0
- /package/dist/{chunk-JIU55F3X.js.map → chunk-SPI27QT6.js.map} +0 -0
- /package/dist/{chunk-7ECD5ATE.js.map → chunk-VDX363PS.js.map} +0 -0
- /package/dist/{chunk-4LACOVZX.js.map → chunk-WVVA7F5A.js.map} +0 -0
- /package/dist/{chunk-3QFQGRHO.js.map → chunk-XMHBH5H6.js.map} +0 -0
- /package/dist/{chunk-N42IWANG.js.map → chunk-ZEM3OK2K.js.map} +0 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import {
|
|
2
|
+
log
|
|
3
|
+
} from "./chunk-2ODBA7MQ.js";
|
|
4
|
+
|
|
5
|
+
// src/extraction-judge-training.ts
|
|
6
|
+
import path from "path";
|
|
7
|
+
import { homedir } from "os";
|
|
8
|
+
import { appendFile, mkdir, readFile, readdir } from "fs/promises";
|
|
9
|
+
function expandTilde(p) {
|
|
10
|
+
const home = homedir();
|
|
11
|
+
if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) {
|
|
12
|
+
return home + p.slice(1);
|
|
13
|
+
}
|
|
14
|
+
if (p === "$HOME" || p.startsWith("$HOME/") || p.startsWith("$HOME\\")) {
|
|
15
|
+
return home + p.slice(5);
|
|
16
|
+
}
|
|
17
|
+
if (p === "${HOME}" || p.startsWith("${HOME}/") || p.startsWith("${HOME}\\")) {
|
|
18
|
+
return home + p.slice(7);
|
|
19
|
+
}
|
|
20
|
+
return p;
|
|
21
|
+
}
|
|
22
|
+
function resolveTrainingDir(options) {
|
|
23
|
+
if (options.directory && options.directory.length > 0) {
|
|
24
|
+
return expandTilde(options.directory);
|
|
25
|
+
}
|
|
26
|
+
return path.join(homedir(), ".remnic", "judge-training");
|
|
27
|
+
}
|
|
28
|
+
function dateStamp(iso) {
|
|
29
|
+
const ms = Date.parse(iso);
|
|
30
|
+
const d = Number.isFinite(ms) ? new Date(ms) : /* @__PURE__ */ new Date();
|
|
31
|
+
const yyyy = d.getUTCFullYear().toString().padStart(4, "0");
|
|
32
|
+
const mm = (d.getUTCMonth() + 1).toString().padStart(2, "0");
|
|
33
|
+
const dd = d.getUTCDate().toString().padStart(2, "0");
|
|
34
|
+
return `${yyyy}-${mm}-${dd}`;
|
|
35
|
+
}
|
|
36
|
+
function trainingFilePathFor(directory, iso) {
|
|
37
|
+
return path.join(directory, `${dateStamp(iso)}.jsonl`);
|
|
38
|
+
}
|
|
39
|
+
async function recordJudgeTrainingPair(row, options) {
|
|
40
|
+
if (!options.enabled) return;
|
|
41
|
+
const dir = resolveTrainingDir(options);
|
|
42
|
+
const filePath = trainingFilePathFor(dir, row.ts);
|
|
43
|
+
try {
|
|
44
|
+
await mkdir(dir, { recursive: true });
|
|
45
|
+
await appendFile(filePath, `${JSON.stringify(row)}
|
|
46
|
+
`, "utf-8");
|
|
47
|
+
} catch (err) {
|
|
48
|
+
log.debug(
|
|
49
|
+
`extraction-judge-training: append failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async function readJudgeTrainingPairs(options) {
|
|
54
|
+
const dir = resolveTrainingDir({ enabled: true, ...options });
|
|
55
|
+
let entries;
|
|
56
|
+
try {
|
|
57
|
+
entries = await readdir(dir);
|
|
58
|
+
} catch (err) {
|
|
59
|
+
const code = err.code;
|
|
60
|
+
if (code === "ENOENT") return { rows: [], malformed: 0 };
|
|
61
|
+
throw err;
|
|
62
|
+
}
|
|
63
|
+
const rows = [];
|
|
64
|
+
let malformed = 0;
|
|
65
|
+
entries.sort();
|
|
66
|
+
for (const name of entries) {
|
|
67
|
+
if (!name.endsWith(".jsonl")) continue;
|
|
68
|
+
const raw = await readFile(path.join(dir, name), "utf-8");
|
|
69
|
+
for (const line of raw.split("\n")) {
|
|
70
|
+
if (!line.trim()) continue;
|
|
71
|
+
let parsed;
|
|
72
|
+
try {
|
|
73
|
+
parsed = JSON.parse(line);
|
|
74
|
+
} catch {
|
|
75
|
+
malformed += 1;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (!isValidTrainingPair(parsed)) {
|
|
79
|
+
malformed += 1;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
rows.push(parsed);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { rows, malformed };
|
|
86
|
+
}
|
|
87
|
+
function isValidTrainingPair(value) {
|
|
88
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
const p = value;
|
|
92
|
+
if (p.version !== 1) return false;
|
|
93
|
+
if (typeof p.ts !== "string") return false;
|
|
94
|
+
if (typeof p.candidateText !== "string") return false;
|
|
95
|
+
if (typeof p.candidateCategory !== "string") return false;
|
|
96
|
+
if (p.verdictKind !== "accept" && p.verdictKind !== "reject" && p.verdictKind !== "defer") {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
if (typeof p.reason !== "string") return false;
|
|
100
|
+
if (p.candidateConfidence !== void 0 && typeof p.candidateConfidence !== "number") {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
if (p.priorDeferrals !== void 0 && typeof p.priorDeferrals !== "number") {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
if (p.groundTruthLabel !== void 0 && p.groundTruthLabel !== "accept" && p.groundTruthLabel !== "reject" && p.groundTruthLabel !== "defer") {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export {
|
|
113
|
+
resolveTrainingDir,
|
|
114
|
+
trainingFilePathFor,
|
|
115
|
+
recordJudgeTrainingPair,
|
|
116
|
+
readJudgeTrainingPairs,
|
|
117
|
+
isValidTrainingPair
|
|
118
|
+
};
|
|
119
|
+
//# sourceMappingURL=chunk-DF3RVK3X.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/extraction-judge-training.ts"],"sourcesContent":["/**\n * Extraction Judge Training Data Shim (issue #562, PR 4).\n *\n * Opt-in collector for `(candidate_text, verdict_kind, reason,\n * ground_truth_label?)` tuples. Rows are appended to JSONL files under\n * `~/.remnic/judge-training/<YYYY-MM-DD>.jsonl` so operators can ship the\n * data into a future GRPO training pipeline without exfiltrating live\n * memory content through the regular observation ledger.\n *\n * Gating:\n * - Off by default. Must be explicitly enabled via\n * `collectJudgeTrainingPairs: true` in plugin config.\n * - The ground-truth label is always optional — labels are added out-of-\n * band once reviewers disambiguate the candidate's fate.\n *\n * Privacy: the row carries only what the judge already sees — the\n * candidate text and its metadata. It does NOT carry session keys,\n * principal IDs, or any user identifiers. The file lives in the user's\n * home directory rather than the shared memory directory so it is never\n * committed, sync'd, or bundled into exports.\n */\n\nimport path from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { appendFile, mkdir, readFile, readdir } from \"node:fs/promises\";\nimport { log } from \"./logger.js\";\nimport type { JudgeVerdictKind } from \"./extraction-judge.js\";\n\n/**\n * Persisted training row. Intentionally minimal: just the signal needed\n * to train a judge replacement policy. Schema version is tagged so future\n * readers can migrate older rows.\n */\nexport interface JudgeTrainingPair {\n version: 1;\n ts: string; // ISO-8601\n candidateText: string;\n candidateCategory: string;\n candidateConfidence?: number;\n verdictKind: JudgeVerdictKind;\n reason: string;\n /**\n * Number of prior deferrals when the verdict was resolved. `0` for the\n * first resolution; only set when known (defer pathway).\n */\n priorDeferrals?: number;\n /**\n * Optional human-applied ground-truth label. Added after the fact by a\n * reviewer / labelling script; not present on fresh rows.\n */\n groundTruthLabel?: JudgeVerdictKind;\n}\n\nexport interface JudgeTrainingOptions {\n enabled: boolean;\n /**\n * Override for the output directory. Defaults to\n * `~/.remnic/judge-training`. Tests pass a temp path here.\n */\n directory?: string;\n}\n\n/**\n * Expand a leading `~` / `~/` / `$HOME/` / `${HOME}/` to the process home\n * directory. Node's `fs` APIs do not expand `~` themselves (CLAUDE.md\n * gotcha 17), so every user-facing path input must be funnelled through\n * this helper before it reaches the filesystem.\n */\nfunction expandTilde(p: string): string {\n const home = homedir();\n if (p === \"~\" || p.startsWith(\"~/\") || p.startsWith(\"~\\\\\")) {\n return home + p.slice(1);\n }\n if (p === \"$HOME\" || p.startsWith(\"$HOME/\") || p.startsWith(\"$HOME\\\\\")) {\n return home + p.slice(5);\n }\n if (p === \"${HOME}\" || p.startsWith(\"${HOME}/\") || p.startsWith(\"${HOME}\\\\\")) {\n return home + p.slice(7);\n }\n return p;\n}\n\nexport function resolveTrainingDir(options: JudgeTrainingOptions): string {\n if (options.directory && options.directory.length > 0) {\n // Expand `~` / `$HOME` in the override so operators can write the\n // config as the user sees it (CLAUDE.md gotcha 17).\n return expandTilde(options.directory);\n }\n return path.join(homedir(), \".remnic\", \"judge-training\");\n}\n\nfunction dateStamp(iso: string): string {\n // `YYYY-MM-DD` from an ISO-8601 string. Falls back to today on a parse\n // failure rather than throwing — the caller already wrote a row and the\n // timestamp is best-effort.\n const ms = Date.parse(iso);\n const d = Number.isFinite(ms) ? new Date(ms) : new Date();\n const yyyy = d.getUTCFullYear().toString().padStart(4, \"0\");\n const mm = (d.getUTCMonth() + 1).toString().padStart(2, \"0\");\n const dd = d.getUTCDate().toString().padStart(2, \"0\");\n return `${yyyy}-${mm}-${dd}`;\n}\n\nexport function trainingFilePathFor(\n directory: string,\n iso: string,\n): string {\n return path.join(directory, `${dateStamp(iso)}.jsonl`);\n}\n\n/**\n * Append a single training row. Fails open — write errors are logged at\n * debug level and swallowed, same policy as the telemetry emitter.\n * No-op when `options.enabled` is false.\n */\nexport async function recordJudgeTrainingPair(\n row: JudgeTrainingPair,\n options: JudgeTrainingOptions,\n): Promise<void> {\n if (!options.enabled) return;\n const dir = resolveTrainingDir(options);\n const filePath = trainingFilePathFor(dir, row.ts);\n try {\n await mkdir(dir, { recursive: true });\n await appendFile(filePath, `${JSON.stringify(row)}\\n`, \"utf-8\");\n } catch (err) {\n log.debug(\n `extraction-judge-training: append failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * Read all training rows from the configured directory. Returns an empty\n * array when the directory is missing. Malformed lines are skipped and\n * counted in the returned `malformed` tally.\n */\nexport async function readJudgeTrainingPairs(\n options: Pick<JudgeTrainingOptions, \"directory\">,\n): Promise<{ rows: JudgeTrainingPair[]; malformed: number }> {\n const dir = resolveTrainingDir({ enabled: true, ...options });\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return { rows: [], malformed: 0 };\n throw err;\n }\n\n const rows: JudgeTrainingPair[] = [];\n let malformed = 0;\n // Sort so reads are deterministic across platforms.\n entries.sort();\n for (const name of entries) {\n if (!name.endsWith(\".jsonl\")) continue;\n const raw = await readFile(path.join(dir, name), \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n malformed += 1;\n continue;\n }\n if (!isValidTrainingPair(parsed)) {\n malformed += 1;\n continue;\n }\n rows.push(parsed);\n }\n }\n return { rows, malformed };\n}\n\n/**\n * Structural validator matching the persisted schema. Forward-compat: an\n * unknown `verdictKind` string is treated as malformed (strict training\n * signal — we do not want to admit unlabelled gibberish into a trainer).\n */\nexport function isValidTrainingPair(value: unknown): value is JudgeTrainingPair {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const p = value as Record<string, unknown>;\n if (p.version !== 1) return false;\n if (typeof p.ts !== \"string\") return false;\n if (typeof p.candidateText !== \"string\") return false;\n if (typeof p.candidateCategory !== \"string\") return false;\n if (\n p.verdictKind !== \"accept\" &&\n p.verdictKind !== \"reject\" &&\n p.verdictKind !== \"defer\"\n ) {\n return false;\n }\n if (typeof p.reason !== \"string\") return false;\n if (\n p.candidateConfidence !== undefined &&\n typeof p.candidateConfidence !== \"number\"\n ) {\n return false;\n }\n if (p.priorDeferrals !== undefined && typeof p.priorDeferrals !== \"number\") {\n return false;\n }\n if (\n p.groundTruthLabel !== undefined &&\n p.groundTruthLabel !== \"accept\" &&\n p.groundTruthLabel !== \"reject\" &&\n p.groundTruthLabel !== \"defer\"\n ) {\n return false;\n }\n return true;\n}\n"],"mappings":";;;;;AAsBA,OAAO,UAAU;AACjB,SAAS,eAAe;AACxB,SAAS,YAAY,OAAO,UAAU,eAAe;AA4CrD,SAAS,YAAY,GAAmB;AACtC,QAAM,OAAO,QAAQ;AACrB,MAAI,MAAM,OAAO,EAAE,WAAW,IAAI,KAAK,EAAE,WAAW,KAAK,GAAG;AAC1D,W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AO,EAAE,sBAAsB,SAAU,QAAO;AACpD,MACE,EAAE,gBAAgB,YAClB,EAAE,gBAAgB,YAClB,EAAE,gBAAgB,SAClB;AACA,WAAO;AAAA,EACT;AACA,MAAI,OAAO,EAAE,WAAW,SAAU,QAAO;AACzC,MACE,EAAE,wBAAwB,UAC1B,OAAO,EAAE,wBAAwB,UACjC;AACA,WAAO;AAAA,EACT;AACA,MAAI,EAAE,mBAAmB,UAAa,OAAO,EAAE,mBAAmB,UAAU;AAC1E,WAAO;AAAA,EACT;AACA,MACE,EAAE,qBAAqB,UACvB,EAAE,qBAAqB,YACvB,EAAE,qBAAqB,YACvB,EAAE,qBAAqB,SACvB;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
2
|
EngramMcpServer
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import {
|
|
5
|
-
validateRequest
|
|
6
|
-
} from "./chunk-MTLYEMJB.js";
|
|
3
|
+
} from "./chunk-HK3FGIEW.js";
|
|
7
4
|
import {
|
|
8
5
|
EngramAccessInputError
|
|
9
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-GKFXUTJ2.js";
|
|
10
7
|
import {
|
|
11
8
|
isTrustZoneName
|
|
12
9
|
} from "./chunk-EQINRHYR.js";
|
|
13
10
|
import {
|
|
14
11
|
log
|
|
15
12
|
} from "./chunk-2ODBA7MQ.js";
|
|
13
|
+
import {
|
|
14
|
+
validateRequest
|
|
15
|
+
} from "./chunk-WCLICCGB.js";
|
|
16
16
|
|
|
17
17
|
// src/access-http.ts
|
|
18
18
|
import { createServer } from "http";
|
|
@@ -402,17 +402,28 @@ var EngramAccessHttpServer = class {
|
|
|
402
402
|
}
|
|
403
403
|
if (req.method === "POST" && pathname === "/engram/v1/recall") {
|
|
404
404
|
const body = await this.readValidatedBody(req, "recall");
|
|
405
|
+
const codingContext = "codingContext" in body ? body.codingContext : void 0;
|
|
405
406
|
const response = await this.service.recall({
|
|
406
407
|
query: body.query ?? "",
|
|
407
408
|
sessionKey: body.sessionKey,
|
|
408
409
|
namespace: this.resolveNamespace(req, body.namespace),
|
|
409
410
|
topK: body.topK,
|
|
410
411
|
mode: body.mode,
|
|
411
|
-
includeDebug: body.includeDebug === true
|
|
412
|
+
includeDebug: body.includeDebug === true,
|
|
413
|
+
codingContext
|
|
412
414
|
});
|
|
413
415
|
this.respondJson(res, 200, response);
|
|
414
416
|
return;
|
|
415
417
|
}
|
|
418
|
+
if (req.method === "POST" && pathname === "/engram/v1/coding-context") {
|
|
419
|
+
const body = await this.readValidatedBody(req, "setCodingContext");
|
|
420
|
+
this.service.setCodingContext({
|
|
421
|
+
sessionKey: body.sessionKey,
|
|
422
|
+
codingContext: body.codingContext
|
|
423
|
+
});
|
|
424
|
+
this.respondJson(res, 200, { ok: true });
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
416
427
|
if (req.method === "POST" && pathname === "/engram/v1/recall/explain") {
|
|
417
428
|
const body = await this.readValidatedBody(req, "recallExplain");
|
|
418
429
|
const response = await this.service.recallExplain({
|
|
@@ -422,6 +433,77 @@ var EngramAccessHttpServer = class {
|
|
|
422
433
|
this.respondJson(res, 200, response);
|
|
423
434
|
return;
|
|
424
435
|
}
|
|
436
|
+
if (req.method === "GET" && pathname === "/engram/v1/recall/tier-explain") {
|
|
437
|
+
const sessionParam = parsed.searchParams.get("session");
|
|
438
|
+
const sessionKey = sessionParam && sessionParam.length > 0 ? sessionParam : void 0;
|
|
439
|
+
const namespaceParam = parsed.searchParams.get("namespace");
|
|
440
|
+
const namespace = this.resolveNamespace(
|
|
441
|
+
req,
|
|
442
|
+
namespaceParam && namespaceParam.length > 0 ? namespaceParam : void 0
|
|
443
|
+
);
|
|
444
|
+
const payload = await this.service.recallTierExplain(
|
|
445
|
+
sessionKey,
|
|
446
|
+
namespace,
|
|
447
|
+
this.resolveRequestPrincipal(req)
|
|
448
|
+
);
|
|
449
|
+
this.respondJson(res, 200, payload);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
if (req.method === "GET" && pathname === "/engram/v1/recall/xray") {
|
|
453
|
+
const queryParam = parsed.searchParams.get("q");
|
|
454
|
+
if (!queryParam || queryParam.trim().length === 0) {
|
|
455
|
+
this.respondJson(res, 400, {
|
|
456
|
+
error: "missing_query",
|
|
457
|
+
code: "missing_query",
|
|
458
|
+
message: "q search parameter is required and must be non-empty"
|
|
459
|
+
});
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const sessionParam = parsed.searchParams.get("session");
|
|
463
|
+
const sessionKey = sessionParam && sessionParam.length > 0 ? sessionParam : void 0;
|
|
464
|
+
const namespaceParam = parsed.searchParams.get("namespace");
|
|
465
|
+
const namespace = this.resolveNamespace(
|
|
466
|
+
req,
|
|
467
|
+
namespaceParam && namespaceParam.length > 0 ? namespaceParam : void 0
|
|
468
|
+
);
|
|
469
|
+
const budgetParam = parsed.searchParams.get("budget");
|
|
470
|
+
let budget;
|
|
471
|
+
if (budgetParam !== null && budgetParam !== "") {
|
|
472
|
+
const parsedBudget = Number(budgetParam);
|
|
473
|
+
if (!Number.isFinite(parsedBudget) || parsedBudget <= 0 || !Number.isInteger(parsedBudget)) {
|
|
474
|
+
this.respondJson(res, 400, {
|
|
475
|
+
error: "invalid_budget",
|
|
476
|
+
code: "invalid_budget",
|
|
477
|
+
message: "budget expects a positive integer"
|
|
478
|
+
});
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
budget = parsedBudget;
|
|
482
|
+
}
|
|
483
|
+
let payload;
|
|
484
|
+
try {
|
|
485
|
+
payload = await this.service.recallXray({
|
|
486
|
+
query: queryParam,
|
|
487
|
+
sessionKey,
|
|
488
|
+
namespace,
|
|
489
|
+
budget,
|
|
490
|
+
authenticatedPrincipal: this.resolveRequestPrincipal(req)
|
|
491
|
+
});
|
|
492
|
+
} catch (err) {
|
|
493
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
494
|
+
if (message.startsWith("recallXray:")) {
|
|
495
|
+
this.respondJson(res, 400, {
|
|
496
|
+
error: "invalid_request",
|
|
497
|
+
code: "invalid_request",
|
|
498
|
+
message
|
|
499
|
+
});
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
throw err;
|
|
503
|
+
}
|
|
504
|
+
this.respondJson(res, 200, payload);
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
425
507
|
if (req.method === "POST" && pathname === "/engram/v1/observe") {
|
|
426
508
|
const body = await this.readValidatedBody(req, "observe");
|
|
427
509
|
this.ensureWriteRateLimitAvailable();
|
|
@@ -588,6 +670,23 @@ var EngramAccessHttpServer = class {
|
|
|
588
670
|
);
|
|
589
671
|
return;
|
|
590
672
|
}
|
|
673
|
+
if (req.method === "GET" && pathname === "/engram/v1/procedural/stats") {
|
|
674
|
+
const namespaceParam = parsed.searchParams.get("namespace");
|
|
675
|
+
this.respondJson(
|
|
676
|
+
res,
|
|
677
|
+
200,
|
|
678
|
+
await this.service.procedureStats(
|
|
679
|
+
{
|
|
680
|
+
namespace: this.resolveNamespace(
|
|
681
|
+
req,
|
|
682
|
+
namespaceParam && namespaceParam.length > 0 ? namespaceParam : void 0
|
|
683
|
+
)
|
|
684
|
+
},
|
|
685
|
+
this.resolveRequestPrincipal(req)
|
|
686
|
+
)
|
|
687
|
+
);
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
591
690
|
if (req.method === "GET" && pathname === "/engram/v1/trust-zones/records") {
|
|
592
691
|
const limitRaw = parseInt(parsed.searchParams.get("limit") ?? "25", 10);
|
|
593
692
|
const offsetRaw = parseInt(parsed.searchParams.get("offset") ?? "0", 10);
|
|
@@ -767,12 +866,12 @@ var EngramAccessHttpServer = class {
|
|
|
767
866
|
}
|
|
768
867
|
if (req.method === "POST" && pathname === "/engram/v1/contradiction-scan") {
|
|
769
868
|
const body = await this.readJsonBody(req);
|
|
770
|
-
const { runContradictionScan } = await import("./contradiction-scan-
|
|
869
|
+
const { runContradictionScan } = await import("./contradiction-scan-E3GJTI4F.js");
|
|
771
870
|
const result = await runContradictionScan({
|
|
772
871
|
storage: this.service.storageRef,
|
|
773
872
|
config: this.service.configRef,
|
|
774
873
|
memoryDir: this.service.memoryDir,
|
|
775
|
-
|
|
874
|
+
embeddingLookupFactory: this.service.embeddingLookupFactoryRef,
|
|
776
875
|
localLlm: this.service.localLlmRef,
|
|
777
876
|
fallbackLlm: this.service.fallbackLlmRef,
|
|
778
877
|
namespace: typeof body.namespace === "string" ? body.namespace : void 0
|
|
@@ -944,4 +1043,4 @@ var EngramAccessHttpServer = class {
|
|
|
944
1043
|
export {
|
|
945
1044
|
EngramAccessHttpServer
|
|
946
1045
|
};
|
|
947
|
-
//# sourceMappingURL=chunk-
|
|
1046
|
+
//# sourceMappingURL=chunk-DFTTJYSO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/access-http.ts","../src/adapters/types.ts","../src/adapters/claude-code.ts","../src/adapters/codex.ts","../src/adapters/replit.ts","../src/adapters/hermes.ts","../src/adapters/registry.ts"],"sourcesContent":["import { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\nimport { randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { fileURLToPath, URL } from \"node:url\";\nimport { log } from \"./logger.js\";\nimport { EngramAccessInputError, type EngramAccessService } from \"./access-service.js\";\nimport { EngramMcpServer } from \"./access-mcp.js\";\nimport { validateRequest, type SchemaName, type SchemaTypeFor } from \"./access-schema.js\";\nimport type { RecallPlanMode } from \"./types.js\";\nimport { isTrustZoneName, type TrustZoneName, type TrustZoneRecordKind, type TrustZoneSourceClass } from \"./trust-zones.js\";\nimport { AdapterRegistry, type ResolvedIdentity } from \"./adapters/index.js\";\nimport type { CitationEntry } from \"./citations.js\";\n\nexport interface EngramAccessHttpServerOptions {\n service: EngramAccessService;\n host?: string;\n port?: number;\n authToken?: string;\n /** Additional valid tokens (for multi-connector auth). Checked alongside authToken. */\n authTokens?: string[];\n /** Dynamic token loader — called on each auth check so new/revoked tokens take effect without restart. */\n authTokensGetter?: () => string[];\n principal?: string;\n maxBodyBytes?: number;\n adminConsoleEnabled?: boolean;\n adminConsolePublicDir?: string;\n trustPrincipalHeader?: boolean;\n /** Enable adapter-based identity resolution from request headers */\n enableAdapters?: boolean;\n /** Custom adapter registry (defaults to built-in adapters) */\n adapterRegistry?: AdapterRegistry;\n /** Enable oai-mem-citation blocks in recall responses (issue #379). */\n citationsEnabled?: boolean;\n /** Auto-enable citations for Codex adapter connections (issue #379). */\n citationsAutoDetect?: boolean;\n}\n\nexport interface EngramAccessHttpServerStatus {\n running: boolean;\n host: string;\n port: number;\n maxBodyBytes: number;\n}\n\nfunction resolveDefaultAdminConsolePublicDir(): string {\n const candidates = [\n fileURLToPath(new URL(\"../admin-console/public\", import.meta.url)),\n fileURLToPath(new URL(\"./admin-console/public\", import.meta.url)),\n ];\n return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];\n}\n\nconst defaultAdminConsolePublicDir = resolveDefaultAdminConsolePublicDir();\nconst correlationIdStore = new AsyncLocalStorage<string>();\n\nconst WRITE_RATE_LIMIT_WINDOW_MS = 60_000;\nconst WRITE_RATE_LIMIT_MAX_REQUESTS = 30;\nconst TRUST_ZONE_RECORD_KINDS = [\"memory\", \"artifact\", \"state\", \"trajectory\", \"external\"] as const;\nconst TRUST_ZONE_SOURCE_CLASSES = [\"tool_output\", \"web_content\", \"subagent_trace\", \"system_memory\", \"user_input\", \"manual\"] as const;\n\nclass HttpError extends Error {\n readonly code: string;\n readonly details?: unknown;\n constructor(readonly status: number, message: string, code?: string, details?: unknown) {\n super(message);\n this.code = code ?? `http_${status}`;\n this.details = details;\n }\n}\n\nfunction hostToUrlAuthority(host: string): string {\n if (host.includes(\":\") && !host.startsWith(\"[\") && !host.endsWith(\"]\")) {\n return `[${host}]`;\n }\n return host;\n}\n\nfunction parseTrustZoneKindFilter(raw: string | null): TrustZoneRecordKind | undefined {\n if (raw === null) return undefined;\n if ((TRUST_ZONE_RECORD_KINDS as readonly string[]).includes(raw)) {\n return raw as TrustZoneRecordKind;\n }\n throw new HttpError(400, `kind must be one of ${TRUST_ZONE_RECORD_KINDS.join(\"|\")}`, \"invalid_kind_filter\");\n}\n\nfunction parseTrustZoneSourceClassFilter(raw: string | null): TrustZoneSourceClass | undefined {\n if (raw === null) return undefined;\n if ((TRUST_ZONE_SOURCE_CLASSES as readonly string[]).includes(raw)) {\n return raw as TrustZoneSourceClass;\n }\n throw new HttpError(400, `sourceClass must be one of ${TRUST_ZONE_SOURCE_CLASSES.join(\"|\")}`, \"invalid_source_class_filter\");\n}\n\nfunction parseTrustZoneFilter(raw: string | null): TrustZoneName | undefined {\n if (raw === null) return undefined;\n if (isTrustZoneName(raw)) {\n return raw;\n }\n throw new HttpError(400, \"zone must be one of quarantine|working|trusted\", \"invalid_zone_filter\");\n}\n\nexport class EngramAccessHttpServer {\n private readonly service: EngramAccessService;\n private readonly host: string;\n private readonly requestedPort: number;\n private readonly authToken?: string;\n private readonly authTokens: string[];\n private readonly authTokensGetter?: () => string[];\n private readonly authenticatedPrincipal?: string;\n private readonly maxBodyBytes: number;\n private readonly adminConsoleEnabled: boolean;\n private readonly adminConsolePublicDir: string;\n private readonly trustPrincipalHeader: boolean;\n private readonly adapterRegistry: AdapterRegistry | null;\n private readonly writeRequestTimestamps: number[] = [];\n private readonly mcpServer: EngramMcpServer;\n private server: Server | null = null;\n private boundPort = 0;\n\n constructor(options: EngramAccessHttpServerOptions) {\n this.service = options.service;\n this.host = options.host?.trim() || \"127.0.0.1\";\n this.requestedPort = Number.isFinite(options.port) ? Math.max(0, Math.floor(options.port ?? 0)) : 0;\n this.authToken = options.authToken?.trim() || undefined;\n this.authTokens = (options.authTokens ?? []).map((t) => t.trim()).filter(Boolean);\n this.authTokensGetter = options.authTokensGetter;\n this.authenticatedPrincipal = options.principal?.trim() || undefined;\n this.maxBodyBytes = Number.isFinite(options.maxBodyBytes)\n ? Math.max(1, Math.floor(options.maxBodyBytes ?? 131072))\n : 131072;\n this.adminConsoleEnabled = options.adminConsoleEnabled !== false;\n this.adminConsolePublicDir = options.adminConsolePublicDir ?? defaultAdminConsolePublicDir;\n this.trustPrincipalHeader = options.trustPrincipalHeader === true;\n this.adapterRegistry = options.enableAdapters !== false\n ? (options.adapterRegistry ?? new AdapterRegistry())\n : null;\n this.mcpServer = new EngramMcpServer(this.service, {\n principal: options.principal,\n citationsEnabled: options.citationsEnabled,\n citationsAutoDetect: options.citationsAutoDetect,\n });\n }\n\n async start(): Promise<EngramAccessHttpServerStatus> {\n if (!this.authToken && this.authTokens.length === 0 && !this.authTokensGetter) {\n throw new Error(\"engram access HTTP requires authToken or authTokens\");\n }\n if (this.server) return this.status();\n\n const server = createServer((req, res) => {\n const correlationId = randomUUID();\n correlationIdStore.run(correlationId, () => {\n void this.handle(req, res, correlationId).catch((err) => {\n log.debug(`engram access HTTP request failed [${correlationId}]: ${err}`);\n if (err instanceof HttpError) {\n const payload: Record<string, unknown> = { error: err.message, code: err.code };\n if (err.details) payload.details = err.details;\n this.respondJson(res, err.status, payload);\n return;\n }\n if (err instanceof EngramAccessInputError) {\n this.respondJson(res, 400, { error: err.message, code: \"input_error\" });\n return;\n }\n if (res.headersSent) {\n res.destroy(err as Error);\n return;\n }\n this.respondJson(res, 500, { error: \"internal_error\", code: \"internal_error\" });\n });\n });\n });\n\n try {\n await new Promise<void>((resolve, reject) => {\n const onError = (err: Error) => {\n server.off(\"listening\", onListening);\n reject(err);\n };\n const onListening = () => {\n server.off(\"error\", onError);\n resolve();\n };\n server.once(\"error\", onError);\n server.once(\"listening\", onListening);\n server.listen(this.requestedPort, this.host);\n });\n } catch (err) {\n server.close();\n throw err;\n }\n\n this.server = server;\n const address = server.address();\n this.boundPort = typeof address === \"object\" && address ? address.port : this.requestedPort;\n return this.status();\n }\n\n async stop(): Promise<void> {\n if (!this.server) return;\n const server = this.server;\n this.server = null;\n this.boundPort = 0;\n await new Promise<void>((resolve, reject) => {\n server.close((err) => (err ? reject(err) : resolve()));\n });\n }\n\n status(): EngramAccessHttpServerStatus {\n return {\n running: this.server !== null,\n host: this.host,\n port: this.boundPort,\n maxBodyBytes: this.maxBodyBytes,\n };\n }\n\n /**\n * Resolve the adapter identity for the incoming request.\n * Includes MCP clientInfo from the last initialize handshake if available.\n * Returns null if no adapter matches or adapters are disabled.\n */\n resolveAdapterIdentity(req: IncomingMessage): ResolvedIdentity | null {\n if (!this.adapterRegistry) return null;\n // Look up clientInfo for this specific MCP session to avoid cross-session leaks.\n // Non-MCP requests (no mcp-session-id header) get undefined clientInfo and\n // rely on HTTP headers for adapter matching.\n const sessionId = (() => {\n const raw = req.headers[\"mcp-session-id\"];\n return typeof raw === \"string\" ? raw.trim() : undefined;\n })();\n return this.adapterRegistry.resolve({\n headers: req.headers as Record<string, string | string[] | undefined>,\n clientInfo: this.mcpServer.getClientInfo(sessionId),\n });\n }\n\n /** Cache for per-request identity resolution (avoids double adapter resolution) */\n private identityCache = new WeakMap<IncomingMessage, { principal?: string; namespace?: string }>();\n\n /** Resolve principal and namespace from request headers and adapter identity */\n private resolveRequestIdentity(req: IncomingMessage): { principal?: string; namespace?: string } {\n const cached = this.identityCache.get(req);\n if (cached) return cached;\n let principal: string | undefined;\n let namespace: string | undefined;\n\n // Explicit header override takes priority for principal\n if (this.trustPrincipalHeader) {\n const headerVal = req.headers[\"x-engram-principal\"];\n const raw = Array.isArray(headerVal) ? headerVal[0] : headerVal;\n if (typeof raw === \"string\") {\n const trimmed = raw.trim();\n if (trimmed.length > 0) {\n principal = trimmed;\n }\n }\n }\n\n // Try adapter-based identity resolution for both principal and namespace\n const adapterIdentity = this.resolveAdapterIdentity(req);\n if (adapterIdentity) {\n if (!principal) {\n principal = adapterIdentity.principal;\n }\n namespace = adapterIdentity.namespace;\n }\n\n if (!principal) {\n principal = this.authenticatedPrincipal;\n }\n\n const result = { principal, namespace };\n this.identityCache.set(req, result);\n return result;\n }\n\n private resolveRequestPrincipal(req: IncomingMessage): string | undefined {\n return this.resolveRequestIdentity(req).principal;\n }\n\n /** Resolve namespace: only use the explicit body value. Adapter-inferred namespace\n * is intentionally NOT used as a fallback for REST requests — omitting namespace\n * should default to the server's global namespace, not silently scope to an adapter. */\n private resolveNamespace(_req: IncomingMessage, bodyNamespace?: string): string | undefined {\n return bodyNamespace || undefined;\n }\n\n private async handle(req: IncomingMessage, res: ServerResponse, correlationId: string): Promise<void> {\n const parsed = new URL(req.url ?? \"/\", `http://${hostToUrlAuthority(this.host)}`);\n const pathname = parsed.pathname;\n\n if (this.adminConsoleEnabled && await this.handleAdminConsole(req, res, pathname)) {\n return;\n }\n\n if (!this.isAuthorized(req)) {\n const body = JSON.stringify({ error: \"unauthorized\", code: \"unauthorized\" });\n res.writeHead(401, {\n \"content-type\": \"application/json; charset=utf-8\",\n \"www-authenticate\": \"Bearer\",\n \"x-request-id\": correlationId,\n });\n res.end(body);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/mcp\") {\n await this.handleMcpRequest(req, res);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/health\") {\n this.respondJson(res, 200, await this.service.health());\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/adapters\") {\n const identity = this.resolveAdapterIdentity(req);\n this.respondJson(res, 200, {\n adaptersEnabled: this.adapterRegistry !== null,\n registered: this.adapterRegistry?.list() ?? [],\n resolved: identity,\n });\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/recall\") {\n const body = await this.readValidatedBody(req, \"recall\");\n // Preserve the distinction between `codingContext: null` (explicit\n // clear) and `codingContext` missing from the JSON payload\n // (untouched). The previous `?? undefined` collapsed both into\n // undefined, so callers lost the ability to clear the session's\n // attached context through the recall endpoint.\n const codingContext =\n \"codingContext\" in body ? body.codingContext : undefined;\n const response = await this.service.recall({\n query: body.query ?? \"\",\n sessionKey: body.sessionKey,\n namespace: this.resolveNamespace(req, body.namespace),\n topK: body.topK,\n mode: body.mode as RecallPlanMode | \"auto\" | undefined,\n includeDebug: body.includeDebug === true,\n codingContext,\n });\n this.respondJson(res, 200, response);\n return;\n }\n\n // Attach / clear coding-agent context for a session (issue #569 PR 5).\n // Mirrors `setCodingContext` on the access service. Connectors call this\n // at session start after resolving a git context for the cwd; `remnic\n // doctor` (PR 8) surfaces the attached context.\n if (req.method === \"POST\" && pathname === \"/engram/v1/coding-context\") {\n const body = await this.readValidatedBody(req, \"setCodingContext\");\n this.service.setCodingContext({\n sessionKey: body.sessionKey,\n codingContext: body.codingContext,\n });\n this.respondJson(res, 200, { ok: true });\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/recall/explain\") {\n const body = await this.readValidatedBody(req, \"recallExplain\");\n const response = await this.service.recallExplain({\n sessionKey: body.sessionKey,\n namespace: this.resolveNamespace(req, body.namespace),\n });\n this.respondJson(res, 200, response);\n return;\n }\n\n // Tier-explain (issue #518): structured per-result annotation from\n // the direct-answer retrieval tier. Orthogonal to /recall/explain\n // above, which returns a graph-path explanation document.\n if (req.method === \"GET\" && pathname === \"/engram/v1/recall/tier-explain\") {\n const sessionParam = parsed.searchParams.get(\"session\");\n const sessionKey = sessionParam && sessionParam.length > 0 ? sessionParam : undefined;\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const namespace = this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0 ? namespaceParam : undefined,\n );\n const payload = await this.service.recallTierExplain(\n sessionKey,\n namespace,\n this.resolveRequestPrincipal(req),\n );\n this.respondJson(res, 200, payload);\n return;\n }\n\n // Recall X-ray (issue #570 PR 4): unified per-result attribution\n // snapshot. Requires bearer auth (same as every other endpoint\n // here) and enforces namespace scope before the recall fires\n // (CLAUDE.md rule 42). Query comes from the `q` search param so\n // GET stays cacheable; `namespace` / `session` / `budget` are\n // optional.\n if (req.method === \"GET\" && pathname === \"/engram/v1/recall/xray\") {\n const queryParam = parsed.searchParams.get(\"q\");\n if (!queryParam || queryParam.trim().length === 0) {\n this.respondJson(res, 400, {\n error: \"missing_query\",\n code: \"missing_query\",\n message: \"q search parameter is required and must be non-empty\",\n });\n return;\n }\n const sessionParam = parsed.searchParams.get(\"session\");\n const sessionKey = sessionParam && sessionParam.length > 0\n ? sessionParam\n : undefined;\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n const namespace = this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0\n ? namespaceParam\n : undefined,\n );\n const budgetParam = parsed.searchParams.get(\"budget\");\n // Reject invalid `budget` with 400 rather than silently\n // defaulting (CLAUDE.md rules 14 + 51).\n let budget: number | undefined;\n if (budgetParam !== null && budgetParam !== \"\") {\n const parsedBudget = Number(budgetParam);\n if (\n !Number.isFinite(parsedBudget)\n || parsedBudget <= 0\n || !Number.isInteger(parsedBudget)\n ) {\n this.respondJson(res, 400, {\n error: \"invalid_budget\",\n code: \"invalid_budget\",\n message:\n \"budget expects a positive integer\",\n });\n return;\n }\n budget = parsedBudget;\n }\n // Only translate validation errors (empty query, bad budget)\n // into 400s. Backend faults (timeouts, storage errors,\n // unexpected orchestrator failures) must bubble to the global\n // `handle()` error handler so they return 500 and get logged\n // properly. `service.recallXray` prefixes its validation\n // errors with \"recallXray:\" so we key off that prefix rather\n // than catching everything.\n let payload: Awaited<ReturnType<typeof this.service.recallXray>>;\n try {\n payload = await this.service.recallXray({\n query: queryParam,\n sessionKey,\n namespace,\n budget,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (message.startsWith(\"recallXray:\")) {\n this.respondJson(res, 400, {\n error: \"invalid_request\",\n code: \"invalid_request\",\n message,\n });\n return;\n }\n // Anything else is a server-side fault; rethrow so the\n // outer `handle()` catch returns 500 + logs the error.\n throw err;\n }\n this.respondJson(res, 200, payload);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/observe\") {\n const body = await this.readValidatedBody(req, \"observe\");\n this.ensureWriteRateLimitAvailable();\n const response = await this.service.observe({\n sessionKey: body.sessionKey,\n messages: body.messages,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n skipExtraction: body.skipExtraction === true,\n });\n this.recordWriteRateLimitHit();\n this.respondJson(res, 202, response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/lcm/search\") {\n const body = await this.readValidatedBody(req, \"lcmSearch\");\n const response = await this.service.lcmSearch({\n query: body.query,\n sessionKey: body.sessionKey,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n limit: body.limit,\n });\n this.respondJson(res, 200, response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/lcm/status\") {\n this.respondJson(res, 200, await this.service.lcmStatus());\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/memories\") {\n const body = await this.readValidatedBody(req, \"memoryStore\");\n const request = {\n schemaVersion: body.schemaVersion,\n idempotencyKey: body.idempotencyKey,\n dryRun: body.dryRun === true,\n sessionKey: body.sessionKey,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n content: body.content,\n category: body.category,\n confidence: body.confidence,\n namespace: this.resolveNamespace(req, body.namespace),\n tags: body.tags,\n entityRef: body.entityRef,\n ttl: body.ttl,\n sourceReason: body.sourceReason,\n };\n const idempotencyStatus = await this.service.peekMemoryStoreIdempotency(request);\n if (idempotencyStatus === \"miss\" && request.dryRun !== true) {\n this.ensureWriteRateLimitAvailable();\n }\n const response = await this.service.memoryStore(request);\n if (this.shouldCountWriteRateLimit(response as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit();\n }\n this.respondJson(res, this.writeResponseStatus(response), response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/suggestions\") {\n const body = await this.readValidatedBody(req, \"suggestionSubmit\");\n const request = {\n schemaVersion: body.schemaVersion,\n idempotencyKey: body.idempotencyKey,\n dryRun: body.dryRun === true,\n sessionKey: body.sessionKey,\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n content: body.content,\n category: body.category,\n confidence: body.confidence,\n namespace: this.resolveNamespace(req, body.namespace),\n tags: body.tags,\n entityRef: body.entityRef,\n ttl: body.ttl,\n sourceReason: body.sourceReason,\n };\n const idempotencyStatus = await this.service.peekSuggestionSubmitIdempotency(request);\n if (idempotencyStatus === \"miss\" && request.dryRun !== true) {\n this.ensureWriteRateLimitAvailable();\n }\n const response = await this.service.suggestionSubmit(request);\n if (this.shouldCountWriteRateLimit(response as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit();\n }\n this.respondJson(res, this.writeResponseStatus(response), response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/memories\") {\n const limitRaw = parseInt(parsed.searchParams.get(\"limit\") ?? \"50\", 10);\n const offsetRaw = parseInt(parsed.searchParams.get(\"offset\") ?? \"0\", 10);\n const sortParam = parsed.searchParams.get(\"sort\") ?? undefined;\n const sort = sortParam === \"updated_desc\"\n || sortParam === \"updated_asc\"\n || sortParam === \"created_desc\"\n || sortParam === \"created_asc\"\n ? sortParam\n : undefined;\n const response = await this.service.memoryBrowse({\n query: parsed.searchParams.get(\"q\") ?? undefined,\n status: parsed.searchParams.get(\"status\") ?? undefined,\n category: parsed.searchParams.get(\"category\") ?? undefined,\n namespace: parsed.searchParams.get(\"namespace\") ?? undefined,\n sort,\n limit: Number.isFinite(limitRaw) ? limitRaw : 50,\n offset: Number.isFinite(offsetRaw) ? offsetRaw : 0,\n });\n this.respondJson(res, 200, response);\n return;\n }\n\n const memoryMatch = pathname.match(/^\\/engram\\/v1\\/memories\\/([^/]+)$/);\n if (req.method === \"GET\" && memoryMatch) {\n const memoryId = decodeURIComponent(memoryMatch[1] ?? \"\");\n const namespace = parsed.searchParams.get(\"namespace\") ?? undefined;\n const response = await this.service.memoryGet(memoryId, namespace, this.resolveRequestPrincipal(req));\n this.respondJson(res, response.found ? 200 : 404, response);\n return;\n }\n\n const timelineMatch = pathname.match(/^\\/engram\\/v1\\/memories\\/([^/]+)\\/timeline$/);\n if (req.method === \"GET\" && timelineMatch) {\n const memoryId = decodeURIComponent(timelineMatch[1] ?? \"\");\n const namespace = parsed.searchParams.get(\"namespace\") ?? undefined;\n const limitRaw = parseInt(parsed.searchParams.get(\"limit\") ?? \"200\", 10);\n const limit = Number.isFinite(limitRaw) ? limitRaw : 200;\n const response = await this.service.memoryTimeline(memoryId, namespace, limit, this.resolveRequestPrincipal(req));\n this.respondJson(res, response.found ? 200 : 404, response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/entities\") {\n const limitRaw = parseInt(parsed.searchParams.get(\"limit\") ?? \"50\", 10);\n const offsetRaw = parseInt(parsed.searchParams.get(\"offset\") ?? \"0\", 10);\n const response = await this.service.entityList({\n namespace: parsed.searchParams.get(\"namespace\") ?? undefined,\n query: parsed.searchParams.get(\"q\") ?? undefined,\n limit: Number.isFinite(limitRaw) ? limitRaw : 50,\n offset: Number.isFinite(offsetRaw) ? offsetRaw : 0,\n });\n this.respondJson(res, 200, response);\n return;\n }\n\n const entityMatch = pathname.match(/^\\/engram\\/v1\\/entities\\/([^/]+)$/);\n if (req.method === \"GET\" && entityMatch) {\n const entityName = decodeURIComponent(entityMatch[1] ?? \"\");\n const namespace = parsed.searchParams.get(\"namespace\") ?? undefined;\n const response = await this.service.entityGet(entityName, namespace);\n this.respondJson(res, response.found ? 200 : 404, response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/review-queue\") {\n const response = await this.service.reviewQueue(\n parsed.searchParams.get(\"runId\") ?? undefined,\n parsed.searchParams.get(\"namespace\") ?? undefined,\n this.resolveRequestPrincipal(req),\n );\n this.respondJson(res, 200, response);\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/maintenance\") {\n this.respondJson(res, 200, await this.service.maintenance(parsed.searchParams.get(\"namespace\") ?? undefined, this.resolveRequestPrincipal(req)));\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/quality\") {\n this.respondJson(res, 200, await this.service.quality(parsed.searchParams.get(\"namespace\") ?? undefined, this.resolveRequestPrincipal(req)));\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/trust-zones/status\") {\n this.respondJson(\n res,\n 200,\n await this.service.trustZoneStatus(parsed.searchParams.get(\"namespace\") ?? undefined, this.resolveRequestPrincipal(req)),\n );\n return;\n }\n\n // Procedural memory stats (issue #567 PR 5/5). Read-only; namespace is\n // scoped via the same resolver used by recall/trust-zones so cross-\n // tenant reads aren't possible (CLAUDE.md rule 42).\n if (req.method === \"GET\" && pathname === \"/engram/v1/procedural/stats\") {\n const namespaceParam = parsed.searchParams.get(\"namespace\");\n this.respondJson(\n res,\n 200,\n await this.service.procedureStats(\n {\n namespace: this.resolveNamespace(\n req,\n namespaceParam && namespaceParam.length > 0\n ? namespaceParam\n : undefined,\n ),\n },\n this.resolveRequestPrincipal(req),\n ),\n );\n return;\n }\n\n if (req.method === \"GET\" && pathname === \"/engram/v1/trust-zones/records\") {\n const limitRaw = parseInt(parsed.searchParams.get(\"limit\") ?? \"25\", 10);\n const offsetRaw = parseInt(parsed.searchParams.get(\"offset\") ?? \"0\", 10);\n const response = await this.service.trustZoneBrowse({\n query: parsed.searchParams.get(\"q\") ?? undefined,\n zone: parseTrustZoneFilter(parsed.searchParams.get(\"zone\")),\n kind: parseTrustZoneKindFilter(parsed.searchParams.get(\"kind\")),\n sourceClass: parseTrustZoneSourceClassFilter(parsed.searchParams.get(\"sourceClass\")),\n namespace: parsed.searchParams.get(\"namespace\") ?? undefined,\n limit: Number.isFinite(limitRaw) ? limitRaw : 25,\n offset: Number.isFinite(offsetRaw) ? offsetRaw : 0,\n }, this.resolveRequestPrincipal(req));\n this.respondJson(res, 200, response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/review-disposition\") {\n const body = await this.readValidatedBody(req, \"reviewDisposition\");\n this.ensureWriteRateLimitAvailable();\n const response = await this.service.reviewDisposition({\n memoryId: body.memoryId,\n status: body.status,\n reasonCode: body.reasonCode,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n if (this.shouldCountWriteRateLimit(response as unknown as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit();\n }\n this.respondJson(res, 200, response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/trust-zones/promote\") {\n const body = await this.readValidatedBody(req, \"trustZonePromote\");\n const dryRun = body.dryRun === true;\n if (!dryRun) {\n this.ensureWriteRateLimitAvailable();\n }\n const response = await this.service.trustZonePromote({\n recordId: body.recordId,\n targetZone: body.targetZone,\n promotionReason: body.promotionReason,\n recordedAt: body.recordedAt,\n summary: body.summary,\n dryRun,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n if (this.shouldCountWriteRateLimit(response as unknown as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit();\n }\n this.respondJson(res, response.dryRun ? 200 : 201, response);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/trust-zones/demo-seed\") {\n const body = await this.readValidatedBody(req, \"trustZoneDemoSeed\");\n const dryRun = body.dryRun === true;\n if (!dryRun) {\n this.ensureWriteRateLimitAvailable();\n }\n const response = await this.service.trustZoneDemoSeed({\n scenario: body.scenario,\n recordedAt: body.recordedAt,\n dryRun,\n namespace: this.resolveNamespace(req, body.namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n });\n if (this.shouldCountWriteRateLimit(response as unknown as { dryRun?: boolean; idempotencyReplay?: boolean })) {\n this.recordWriteRateLimitHit();\n }\n this.respondJson(res, response.dryRun ? 200 : 201, response);\n return;\n }\n\n // Citation usage tracking (issue #379)\n if (req.method === \"POST\" && pathname === \"/v1/citations/observed\") {\n const body = await this.readJsonBody(req);\n if (!body || typeof body !== \"object\" || Array.isArray(body)) {\n throw new HttpError(400, \"request body must be a JSON object\", \"invalid_body\");\n }\n const payload = body as Record<string, unknown>;\n const sessionId = typeof payload.sessionId === \"string\" ? payload.sessionId : undefined;\n const namespace = typeof payload.namespace === \"string\" ? payload.namespace : undefined;\n const citationsRaw = payload.citations;\n if (!citationsRaw || typeof citationsRaw !== \"object\" || Array.isArray(citationsRaw)) {\n throw new HttpError(400, \"citations must be a JSON object with entries and rolloutIds\", \"invalid_citations\");\n }\n const citObj = citationsRaw as Record<string, unknown>;\n const entries: CitationEntry[] = [];\n if (Array.isArray(citObj.entries)) {\n for (const raw of citObj.entries) {\n if (raw && typeof raw === \"object\" && !Array.isArray(raw)) {\n const e = raw as Record<string, unknown>;\n if (\n typeof e.path === \"string\" &&\n typeof e.lineStart === \"number\" &&\n typeof e.lineEnd === \"number\"\n ) {\n entries.push({\n path: e.path,\n lineStart: e.lineStart,\n lineEnd: e.lineEnd,\n note: typeof e.note === \"string\" ? e.note : \"\",\n });\n }\n }\n }\n }\n const rolloutIds: string[] = [];\n if (Array.isArray(citObj.rolloutIds)) {\n for (const id of citObj.rolloutIds) {\n if (typeof id === \"string\" && id.length > 0) {\n rolloutIds.push(id);\n }\n }\n }\n\n // Record usage: for each citation entry, try to increment usage on the\n // matching memory. The service exposes recordAccess for this purpose.\n // Pass authenticatedPrincipal so namespace ACL checks use the same\n // identity resolution as other write endpoints (Finding #1, issue #379).\n let matched = 0;\n let submitted = 0;\n if (typeof this.service.recordCitationUsage === \"function\") {\n const result = await this.service.recordCitationUsage({\n sessionId,\n namespace: this.resolveNamespace(req, namespace),\n authenticatedPrincipal: this.resolveRequestPrincipal(req),\n entries,\n rolloutIds,\n });\n submitted = result.submitted;\n matched = result.matched;\n }\n\n this.respondJson(res, 200, {\n ok: true,\n submitted,\n matched,\n entriesReceived: entries.length,\n rolloutIdsReceived: rolloutIds.length,\n });\n return;\n }\n\n // ── Contradiction Review (issue #520) ─────────────────────────────────────\n if (req.method === \"GET\" && pathname === \"/engram/v1/review/contradictions\") {\n const VALID_FILTERS = new Set([\"all\", \"unresolved\", \"contradicts\", \"independent\", \"duplicates\", \"needs-user\"]);\n const rawFilter = parsed.searchParams.get(\"filter\") ?? \"unresolved\";\n if (!VALID_FILTERS.has(rawFilter)) {\n this.respondJson(res, 400, { error: `Invalid filter '${rawFilter}'. Valid: ${[...VALID_FILTERS].join(\", \")}` });\n return;\n }\n const namespace = parsed.searchParams.get(\"namespace\") ?? undefined;\n const limitRaw = parseInt(parsed.searchParams.get(\"limit\") ?? \"50\", 10);\n const { listPairs } = await import(\"./contradiction/contradiction-review.js\");\n const result = listPairs(this.service.memoryDir, {\n filter: rawFilter as \"all\" | \"unresolved\" | \"contradicts\" | \"independent\" | \"duplicates\" | \"needs-user\",\n namespace,\n limit: Number.isFinite(limitRaw) ? limitRaw : 50,\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n if (req.method === \"GET\" && pathname.startsWith(\"/engram/v1/review/contradictions/\")) {\n const pairId = pathname.split(\"/\").pop() ?? \"\";\n const { readPair } = await import(\"./contradiction/contradiction-review.js\");\n const pair = readPair(this.service.memoryDir, pairId);\n if (!pair) {\n this.respondJson(res, 404, { error: \"pair_not_found\" });\n return;\n }\n this.respondJson(res, 200, pair);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/review/resolve\") {\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n const pairId = typeof body.pairId === \"string\" ? body.pairId : \"\";\n const verb = typeof body.verb === \"string\" ? body.verb : \"\";\n if (!pairId || !verb) {\n this.respondJson(res, 400, { error: \"pairId and verb are required\" });\n return;\n }\n const { isValidResolutionVerb, executeResolution } = await import(\"./contradiction/resolution.js\");\n if (!isValidResolutionVerb(verb)) {\n this.respondJson(res, 400, { error: `Invalid verb: ${verb}. Must be one of: keep-a, keep-b, merge, both-valid, needs-more-context` });\n return;\n }\n const result = await executeResolution(this.service.memoryDir, this.service.storageRef, pairId, verb);\n this.respondJson(res, 200, result);\n return;\n }\n\n if (req.method === \"POST\" && pathname === \"/engram/v1/contradiction-scan\") {\n const body = await this.readJsonBody(req) as Record<string, unknown>;\n const { runContradictionScan } = await import(\"./contradiction/contradiction-scan.js\");\n const result = await runContradictionScan({\n storage: this.service.storageRef,\n config: this.service.configRef,\n memoryDir: this.service.memoryDir,\n embeddingLookupFactory: this.service.embeddingLookupFactoryRef,\n localLlm: this.service.localLlmRef,\n fallbackLlm: this.service.fallbackLlmRef,\n namespace: typeof body.namespace === \"string\" ? body.namespace : undefined,\n });\n this.respondJson(res, 200, result);\n return;\n }\n\n this.respondJson(res, 404, { error: \"not_found\", code: \"not_found\" });\n }\n\n private async handleMcpRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const body = await this.readJsonBody(req);\n const request = body as {\n jsonrpc?: string;\n id?: string | number | null;\n method?: string;\n params?: Record<string, unknown>;\n };\n\n // Enforce write rate limiting for MCP tool calls that mutate state,\n // matching the same protection applied to the REST write endpoints.\n // Pre-check ensures capacity; post-check skips counting dry runs and\n // idempotency replays, consistent with the REST handlers.\n const isMcpWrite =\n request.method === \"tools/call\" &&\n typeof request.params?.name === \"string\" &&\n (request.params.name === \"engram.memory_store\" || request.params.name === \"engram.suggestion_submit\" || request.params.name === \"engram.observe\");\n if (isMcpWrite) {\n this.ensureWriteRateLimitAvailable();\n }\n\n const sessionId = (() => {\n const raw = req.headers[\"mcp-session-id\"];\n return typeof raw === \"string\" ? raw.trim() : undefined;\n })();\n const mcpCorrelationId = correlationIdStore.getStore() ?? randomUUID();\n const response = await this.mcpServer.handleRequest(request, {\n principalOverride: this.resolveRequestPrincipal(req),\n sessionId,\n correlationId: mcpCorrelationId,\n });\n\n if (isMcpWrite && response !== null) {\n const result = (response as Record<string, unknown>).result as Record<string, unknown> | undefined;\n const isError = result?.isError === true;\n const structured = result?.structuredContent as { dryRun?: boolean; idempotencyReplay?: boolean } | undefined;\n if (!isError && structured && this.shouldCountWriteRateLimit(structured)) {\n this.recordWriteRateLimitHit();\n }\n }\n if (response === null) {\n res.statusCode = 202;\n res.end();\n return;\n }\n // If this was an initialize response, pop the session ID keyed by\n // correlation ID (unique per HTTP request, not client-chosen JSON-RPC id).\n const assignedSessionId = this.mcpServer.popInitSessionId(mcpCorrelationId);\n if (assignedSessionId) {\n res.setHeader(\"mcp-session-id\", assignedSessionId);\n }\n this.respondJson(res, 200, response);\n }\n\n private respondJson(res: ServerResponse, status: number, payload: unknown): void {\n const body = JSON.stringify(payload, null, 2);\n res.statusCode = status;\n res.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n res.setHeader(\"content-length\", String(Buffer.byteLength(body)));\n const cid = correlationIdStore.getStore();\n if (cid) {\n res.setHeader(\"x-request-id\", cid);\n }\n res.end(body);\n }\n\n private async handleAdminConsole(\n req: IncomingMessage,\n res: ServerResponse,\n pathname: string,\n ): Promise<boolean> {\n if (req.method !== \"GET\") return false;\n if (pathname === \"/engram/ui\" || pathname === \"/engram/ui/\") {\n await this.respondStatic(res, path.join(this.adminConsolePublicDir, \"index.html\"), \"text/html; charset=utf-8\");\n return true;\n }\n if (pathname === \"/engram/ui/app.js\") {\n await this.respondStatic(res, path.join(this.adminConsolePublicDir, \"app.js\"), \"application/javascript; charset=utf-8\");\n return true;\n }\n return false;\n }\n\n private async respondStatic(res: ServerResponse, filePath: string, contentType: string): Promise<void> {\n try {\n const body = await readFile(filePath, \"utf-8\");\n res.statusCode = 200;\n res.setHeader(\"content-type\", contentType);\n res.setHeader(\"content-length\", String(Buffer.byteLength(body)));\n res.end(body);\n } catch {\n this.respondJson(res, 404, { error: \"not_found\" });\n }\n }\n\n private async readJsonBody(req: IncomingMessage): Promise<Record<string, unknown>> {\n const chunks: Buffer[] = [];\n let total = 0;\n for await (const chunk of req) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n total += buffer.length;\n if (total > this.maxBodyBytes) {\n throw new HttpError(413, \"request_body_too_large\", \"request_body_too_large\");\n }\n chunks.push(buffer);\n }\n if (chunks.length === 0) return {};\n const raw = Buffer.concat(chunks).toString(\"utf-8\").trim();\n if (raw.length === 0) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new HttpError(400, \"invalid_json\", \"invalid_json\");\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new HttpError(400, \"invalid_json_object\", \"invalid_json_object\");\n }\n return parsed as Record<string, unknown>;\n }\n\n private async readValidatedBody<S extends SchemaName>(req: IncomingMessage, schemaName: S): Promise<SchemaTypeFor<S>> {\n const raw = await this.readJsonBody(req);\n const result = validateRequest(schemaName, raw);\n if (!result.success) {\n throw new HttpError(400, result.error.error, \"validation_error\", result.error.details);\n }\n return result.data as SchemaTypeFor<S>;\n }\n\n private isAuthorized(req: IncomingMessage): boolean {\n if (!this.authToken && this.authTokens.length === 0 && !this.authTokensGetter) return false;\n const raw = req.headers.authorization;\n if (!raw) return false;\n const separator = raw.indexOf(\" \");\n if (separator <= 0) return false;\n const scheme = raw.slice(0, separator).toLowerCase();\n if (scheme !== \"bearer\") return false;\n const token = raw.slice(separator + 1).trim();\n // Check primary token\n if (this.authToken && this.timingSafeStringEqual(token, this.authToken)) return true;\n // Check static multi-connector tokens\n for (const valid of this.authTokens) {\n if (this.timingSafeStringEqual(token, valid)) return true;\n }\n // Check dynamic tokens (reloaded per request for generate/revoke without restart)\n if (this.authTokensGetter) {\n for (const valid of this.authTokensGetter()) {\n if (this.timingSafeStringEqual(token, valid)) return true;\n }\n }\n return false;\n }\n\n private timingSafeStringEqual(a: string, b: string): boolean {\n const left = this.encodeSecret(a);\n const right = this.encodeSecret(b);\n if (!left || !right) return false;\n return timingSafeEqual(left, right);\n }\n\n private encodeSecret(value: string): Buffer | null {\n const encoded = Buffer.from(value, \"utf-8\");\n if (encoded.length > 1024) return null;\n const out = Buffer.alloc(2 + 1024);\n out.writeUInt16BE(encoded.length, 0);\n encoded.copy(out, 2);\n return out;\n }\n\n private writeResponseStatus(response: { dryRun: boolean; status: string }): number {\n if (response.dryRun === true) return 200;\n if (response.status === \"stored\" || response.status === \"queued_for_review\") return 201;\n return 200;\n }\n\n private ensureWriteRateLimitAvailable(): void {\n const now = Date.now();\n while (\n this.writeRequestTimestamps.length > 0 &&\n now - (this.writeRequestTimestamps[0] ?? 0) > WRITE_RATE_LIMIT_WINDOW_MS\n ) {\n this.writeRequestTimestamps.shift();\n }\n if (this.writeRequestTimestamps.length >= WRITE_RATE_LIMIT_MAX_REQUESTS) {\n throw new HttpError(429, \"write_rate_limited\", \"write_rate_limited\");\n }\n }\n\n private recordWriteRateLimitHit(): void {\n this.writeRequestTimestamps.push(Date.now());\n }\n\n private shouldCountWriteRateLimit(response: { dryRun?: boolean; idempotencyReplay?: boolean }): boolean {\n return response.dryRun !== true && response.idempotencyReplay !== true;\n }\n}\n","/**\n * Adapter interface for external system identity resolution.\n *\n * Each adapter maps an external system's session/identity conventions\n * to Engram's namespace + principal model. Adapters are stateless and\n * lightweight — they don't manage lifecycles or load plugins.\n */\n\nexport interface AdapterContext {\n /** Raw HTTP headers from the incoming request */\n headers: Record<string, string | string[] | undefined>;\n /** MCP client info (from initialize handshake, if available) */\n clientInfo?: { name: string; version?: string };\n /** Explicit session key from request args */\n sessionKey?: string;\n}\n\nexport interface ResolvedIdentity {\n /** Engram namespace (scopes memory access) */\n namespace: string;\n /** Engram principal (authorization subject) */\n principal: string;\n /** Session key for continuity tracking */\n sessionKey?: string;\n /** Which adapter resolved this identity */\n adapterId: string;\n}\n\nexport interface EngramAdapter {\n /** Adapter identifier (e.g., \"claude-code\", \"codex\", \"hermes\", \"replit\") */\n readonly id: string;\n\n /** Whether this adapter recognizes the given request context */\n matches(context: AdapterContext): boolean;\n\n /** Map external session/identity to Engram namespace + principal */\n resolveIdentity(context: AdapterContext): ResolvedIdentity;\n}\n\n/**\n * Extract and trim a single header value from a headers record.\n * Returns undefined if the header is missing, empty, or all whitespace.\n */\nexport function headerValue(\n headers: Record<string, string | string[] | undefined>,\n key: string,\n): string | undefined {\n const raw = headers[key];\n const value = Array.isArray(raw) ? raw[0] : raw;\n return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n}\n","import { headerValue, type AdapterContext, type EngramAdapter, type ResolvedIdentity } from \"./types.js\";\n\n/**\n * Claude Code adapter.\n *\n * Detection: Claude Code sends clientInfo.name = \"claude-code\" in the\n * MCP initialize handshake, and User-Agent: claude-code/<version> in\n * HTTP requests. Project path is available via MCP ListRoots capability\n * (server receives the cwd as a file:// URI root), not via headers.\n *\n * For HTTP REST (non-MCP) requests, detection relies on User-Agent or\n * user-configured X-Engram-Client-Id header in .claude.json headers.\n *\n * Namespace/principal can be set by configuring custom headers in\n * .claude.json or .mcp.json:\n * \"headers\": { \"X-Engram-Namespace\": \"my-project\", \"X-Engram-Principal\": \"my-team\" }\n */\nexport class ClaudeCodeAdapter implements EngramAdapter {\n readonly id = \"claude-code\";\n\n matches(context: AdapterContext): boolean {\n // Primary: MCP clientInfo from initialize handshake (exact match)\n if (context.clientInfo?.name === \"claude-code\") return true;\n\n // Fallback: User-Agent header (Claude Code sends \"claude-code/<version>\")\n const ua = headerValue(context.headers, \"user-agent\");\n if (ua && ua.toLowerCase().startsWith(\"claude-code/\")) return true;\n\n // Fallback: user-configured client identifier header\n const clientId = headerValue(context.headers, \"x-engram-client-id\");\n if (clientId?.toLowerCase() === \"claude-code\") return true;\n\n return false;\n }\n\n resolveIdentity(context: AdapterContext): ResolvedIdentity {\n // MCP session ID (standard MCP header, server-assigned)\n const mcpSessionId = headerValue(context.headers, \"mcp-session-id\");\n\n // Principal: explicit header > default\n const principal = headerValue(context.headers, \"x-engram-principal\")\n || \"claude-code\";\n\n // Namespace: explicit header > default\n const namespace = headerValue(context.headers, \"x-engram-namespace\")\n || \"claude-code\";\n\n return {\n namespace,\n principal,\n sessionKey: mcpSessionId ?? context.sessionKey,\n adapterId: this.id,\n };\n }\n}\n\n","import { headerValue, type AdapterContext, type EngramAdapter, type ResolvedIdentity } from \"./types.js\";\n\n/**\n * Codex CLI adapter.\n *\n * Detection: Codex CLI sends clientInfo.name = \"codex-mcp-client\" and\n * clientInfo.title = \"Codex\" in the MCP initialize handshake. It does\n * NOT send agent names, session IDs, or project context automatically.\n *\n * For Streamable HTTP transport, Codex supports custom headers via\n * http_headers in ~/.codex/config.toml:\n * [mcp_servers.engram]\n * url = \"http://localhost:4318/mcp\"\n * http_headers = { \"X-Engram-Namespace\" = \"my-project\", \"X-Engram-Principal\" = \"codex-agent\" }\n *\n * Codex also sends a custom \"sandbox_state\" RPC notification after\n * init with sandbox policy info (read-only/writable paths).\n */\nexport class CodexAdapter implements EngramAdapter {\n readonly id = \"codex\";\n\n matches(context: AdapterContext): boolean {\n // Primary: MCP clientInfo from initialize handshake (exact match)\n if (context.clientInfo?.name === \"codex-mcp-client\") return true;\n\n // Also match on clientInfo name containing \"codex\" for forward compat\n const clientName = context.clientInfo?.name?.toLowerCase() ?? \"\";\n if (clientName.includes(\"codex\") && clientName !== \"codex-mcp-client\") return true;\n\n // Fallback: user-configured client identifier header\n const clientId = headerValue(context.headers, \"x-engram-client-id\");\n if (clientId?.toLowerCase() === \"codex\") return true;\n\n return false;\n }\n\n resolveIdentity(context: AdapterContext): ResolvedIdentity {\n // MCP session ID (standard MCP header, server-assigned)\n const mcpSessionId = headerValue(context.headers, \"mcp-session-id\");\n\n // Principal: explicit header > default\n const principal = headerValue(context.headers, \"x-engram-principal\")\n || \"codex\";\n\n // Namespace: explicit header > default\n const namespace = headerValue(context.headers, \"x-engram-namespace\")\n || \"codex\";\n\n return {\n namespace,\n principal,\n sessionKey: mcpSessionId ?? context.sessionKey,\n adapterId: this.id,\n };\n }\n}\n\n","import { headerValue, type AdapterContext, type EngramAdapter, type ResolvedIdentity } from \"./types.js\";\n\n/**\n * Replit Agent adapter.\n *\n * Detection: Replit Agent supports MCP natively (HTTP-only, configured\n * via the Integrations pane). It does NOT send identifying headers\n * automatically — detection relies on user-configured custom headers\n * in Replit's MCP Integrations UI.\n *\n * Replit provides env vars to running code (REPL_ID, REPL_OWNER,\n * REPL_SLUG) but these are NOT sent as HTTP headers to MCP servers.\n *\n * To identify Replit connections, users should configure a custom header\n * in the Replit Integrations pane when adding the Engram MCP server:\n * Header Name: X-Engram-Client-Id\n * Header Value: replit\n *\n * Optionally also set X-Engram-Namespace and X-Engram-Principal for\n * project/user scoping.\n */\nexport class ReplitAdapter implements EngramAdapter {\n readonly id = \"replit\";\n\n matches(context: AdapterContext): boolean {\n // Primary: user-configured client identifier header\n const clientId = headerValue(context.headers, \"x-engram-client-id\");\n if (clientId?.toLowerCase() === \"replit\") return true;\n\n // MCP clientInfo (Replit's MCP client name is not publicly documented,\n // but check for it in case it becomes available)\n const clientName = context.clientInfo?.name?.toLowerCase() ?? \"\";\n if (clientName.includes(\"replit\")) return true;\n\n return false;\n }\n\n resolveIdentity(context: AdapterContext): ResolvedIdentity {\n const mcpSessionId = headerValue(context.headers, \"mcp-session-id\");\n\n const principal = headerValue(context.headers, \"x-engram-principal\")\n || \"replit-agent\";\n\n const namespace = headerValue(context.headers, \"x-engram-namespace\")\n || \"replit\";\n\n return {\n namespace,\n principal,\n sessionKey: mcpSessionId ?? context.sessionKey,\n adapterId: this.id,\n };\n }\n}\n\n","import { headerValue, type AdapterContext, type EngramAdapter, type ResolvedIdentity } from \"./types.js\";\n\n/**\n * Hermes Agent adapter.\n *\n * Detection: Hermes supports both MCP (via config.yaml mcp_servers)\n * and a dedicated MemoryProvider plugin protocol (Python). The MCP\n * client name is not yet publicly documented, so detection uses:\n *\n * 1. X-Hermes-Session-Id header — confirmed in v0.7.0 API server\n * 2. User-configured headers in Hermes MCP config:\n * mcp_servers:\n * engram:\n * url: \"http://localhost:4318/mcp\"\n * headers:\n * X-Engram-Client-Id: \"hermes\"\n * X-Engram-Namespace: \"my-profile\"\n * 3. MCP clientInfo name containing \"hermes\" (for forward compat)\n *\n * Hermes profiles isolate agent state under ~/.hermes/profiles/<name>/.\n * Each profile can map to a separate Engram namespace via the\n * X-Engram-Namespace header.\n *\n * For deeper integration, Hermes v0.7.0+ supports MemoryProvider\n * plugins (Python protocol with initialize/enrich_turn/sync_turn/\n * shutdown). A Python Engram MemoryProvider plugin would be the\n * optimal integration path — see docs/integration/hermes-setup.md.\n */\nexport class HermesAdapter implements EngramAdapter {\n readonly id = \"hermes\";\n\n matches(context: AdapterContext): boolean {\n // Confirmed header from Hermes v0.7.0 API server\n if (headerValue(context.headers, \"x-hermes-session-id\")) return true;\n\n // User-configured client identifier header\n const clientId = headerValue(context.headers, \"x-engram-client-id\");\n if (clientId?.toLowerCase() === \"hermes\") return true;\n\n // MCP clientInfo (for forward compat when Hermes documents its name)\n const clientName = context.clientInfo?.name?.toLowerCase() ?? \"\";\n if (clientName.includes(\"hermes\")) return true;\n\n return false;\n }\n\n resolveIdentity(context: AdapterContext): ResolvedIdentity {\n const sessionId = headerValue(context.headers, \"x-hermes-session-id\");\n\n const principal = headerValue(context.headers, \"x-engram-principal\")\n || \"hermes-agent\";\n\n const namespace = headerValue(context.headers, \"x-engram-namespace\")\n || \"hermes\";\n\n return {\n namespace,\n principal,\n sessionKey: sessionId ?? context.sessionKey,\n adapterId: this.id,\n };\n }\n}\n\n","import type { AdapterContext, EngramAdapter, ResolvedIdentity } from \"./types.js\";\nimport { ClaudeCodeAdapter } from \"./claude-code.js\";\nimport { CodexAdapter } from \"./codex.js\";\nimport { ReplitAdapter } from \"./replit.js\";\nimport { HermesAdapter } from \"./hermes.js\";\n\n/**\n * Adapter registry. Attempts to identify which external system is\n * connecting by checking each registered adapter in order. Falls back\n * to explicit namespace/principal from the request args.\n */\nexport class AdapterRegistry {\n private readonly adapters: EngramAdapter[];\n\n constructor(adapters?: EngramAdapter[]) {\n this.adapters = adapters ?? [\n new HermesAdapter(),\n new ReplitAdapter(),\n new CodexAdapter(),\n new ClaudeCodeAdapter(),\n ];\n }\n\n /**\n * Try each adapter in order. Return the first match, or null if\n * no adapter recognizes the request context.\n */\n resolve(context: AdapterContext): ResolvedIdentity | null {\n for (const adapter of this.adapters) {\n if (adapter.matches(context)) {\n return adapter.resolveIdentity(context);\n }\n }\n return null;\n }\n\n /** List registered adapter IDs */\n list(): string[] {\n return this.adapters.map((a) => a.id);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAAS,oBAA4E;AACrF,SAAS,YAAY,uBAAuB;AAC5C,SAAS,yBAAyB;AAClC,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,OAAO,UAAU;AACjB,SAAS,eAAe,WAAW;;;ACqC5B,SAAS,YACd,SACA,KACoB;AACpB,QAAM,MAAM,QAAQ,GAAG;AACvB,QAAM,QAAQ,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,IAAI;AAC5C,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,MAAM,KAAK,IAAI;AAC/E;;;ACjCO,IAAM,oBAAN,MAAiD;AAAA,EAC7C,KAAK;AAAA,EAEd,QAAQ,SAAkC;AAExC,QAAI,QAAQ,YAAY,SAAS,cAAe,QAAO;AAGvD,UAAM,KAAK,YAAY,QAAQ,SAAS,YAAY;AACpD,QAAI,MAAM,GAAG,YAAY,EAAE,WAAW,cAAc,EAAG,QAAO;AAG9D,UAAM,WAAW,YAAY,QAAQ,SAAS,oBAAoB;AAClE,QAAI,UAAU,YAAY,MAAM,cAAe,QAAO;AAEtD,WAAO;AAAA,EACT;AAAA,EAEA,gBAAgB,SAA2C;AAEzD,UAAM,eAAe,YAAY,QAAQ,SAAS,gBAAgB;AAGlE,UAAM,YAAY,YAAY,QAAQ,SAAS,oBAAoB,KAC9D;AAGL,UAAM,YAAY,YAAY,QAAQ,SAAS,oBAAoB,KAC9D;AAEL,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,YAAY,gBAAgB,QAAQ;AAAA,MACpC,WAAW,KAAK;AAAA,I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,KAAK,KAAK,CAAC;AACnB,WAAO;AAAA,EACT;AAAA,EAEQ,oBAAoB,UAAuD;AACjF,QAAI,SAAS,WAAW,KAAM,QAAO;AACrC,QAAI,SAAS,WAAW,YAAY,SAAS,WAAW,oBAAqB,QAAO;AACpF,WAAO;AAAA,EACT;AAAA,EAEQ,gCAAsC;AAC5C,UAAM,MAAM,KAAK,IAAI;AACrB,WACE,KAAK,uBAAuB,SAAS,KACrC,OAAO,KAAK,uBAAuB,CAAC,KAAK,KAAK,4BAC9C;AACA,WAAK,uBAAuB,MAAM;AAAA,IACpC;AACA,QAAI,KAAK,uBAAuB,UAAU,+BAA+B;AACvE,YAAM,IAAI,UAAU,KAAK,sBAAsB,oBAAoB;AAAA,IACrE;AAAA,EACF;AAAA,EAEQ,0BAAgC;AACtC,SAAK,uBAAuB,KAAK,KAAK,IAAI,CAAC;AAAA,EAC7C;AAAA,EAEQ,0BAA0B,UAAsE;AACtG,WAAO,SAAS,WAAW,QAAQ,SAAS,sBAAsB;AAAA,EACpE;AACF;","names":[]}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_PPR_DAMPING,
|
|
3
|
+
DEFAULT_PPR_ITERATIONS,
|
|
4
|
+
buildGraphFromMemories,
|
|
5
|
+
queryGraph
|
|
6
|
+
} from "./chunk-64NJRYU2.js";
|
|
7
|
+
|
|
8
|
+
// src/graph-recall.ts
|
|
9
|
+
function runGraphRecall(config, options) {
|
|
10
|
+
if (!config.recallGraphEnabled) {
|
|
11
|
+
return {
|
|
12
|
+
ran: false,
|
|
13
|
+
results: [],
|
|
14
|
+
graph: null,
|
|
15
|
+
reason: "disabled",
|
|
16
|
+
iterations: 0,
|
|
17
|
+
converged: true
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
const topK = typeof config.recallGraphTopK === "number" && Number.isFinite(config.recallGraphTopK) ? config.recallGraphTopK : 50;
|
|
21
|
+
if (topK <= 0) {
|
|
22
|
+
return {
|
|
23
|
+
ran: false,
|
|
24
|
+
results: [],
|
|
25
|
+
graph: null,
|
|
26
|
+
reason: "topk-zero",
|
|
27
|
+
iterations: 0,
|
|
28
|
+
converged: true
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
if (options.memories.length === 0) {
|
|
32
|
+
return {
|
|
33
|
+
ran: false,
|
|
34
|
+
results: [],
|
|
35
|
+
graph: null,
|
|
36
|
+
reason: "empty-input",
|
|
37
|
+
iterations: 0,
|
|
38
|
+
converged: true
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
const graph = buildGraphFromMemories(options.memories);
|
|
42
|
+
const damping = typeof config.recallGraphDamping === "number" && Number.isFinite(config.recallGraphDamping) ? config.recallGraphDamping : DEFAULT_PPR_DAMPING;
|
|
43
|
+
const iterations = typeof config.recallGraphIterations === "number" && Number.isFinite(config.recallGraphIterations) ? config.recallGraphIterations : DEFAULT_PPR_ITERATIONS;
|
|
44
|
+
const ppr = queryGraph(graph, options.seedIds, {
|
|
45
|
+
damping,
|
|
46
|
+
iterations,
|
|
47
|
+
seedWeights: options.seedWeights
|
|
48
|
+
});
|
|
49
|
+
const memoryResults = [];
|
|
50
|
+
for (const node of ppr.rankedNodes) {
|
|
51
|
+
const graphNode = graph.nodes.get(node.id);
|
|
52
|
+
if (!graphNode || graphNode.type !== "memory") continue;
|
|
53
|
+
memoryResults.push({ id: node.id, score: node.score });
|
|
54
|
+
if (memoryResults.length >= topK) break;
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
ran: true,
|
|
58
|
+
results: memoryResults,
|
|
59
|
+
graph,
|
|
60
|
+
reason: "ran",
|
|
61
|
+
iterations: ppr.iterations,
|
|
62
|
+
converged: ppr.converged
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export {
|
|
67
|
+
runGraphRecall
|
|
68
|
+
};
|
|
69
|
+
//# sourceMappingURL=chunk-DGVM5SFL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/graph-recall.ts"],"sourcesContent":["/**\n * Graph-based retrieval integration (issue #559 PR 4 of 5).\n *\n * Pure helper that composes `extractGraphEdges` (PR 2) and `queryGraph`\n * (PR 3) into a single retrieval surface. Operators opt in via the\n * `recallGraphEnabled` config flag; until the `retrieval-graph` bench in\n * PR 5 justifies flipping the default, this tier ships disabled.\n *\n * Kept as a pure function so the orchestrator can call it with whatever\n * candidate pool it has (hot cache, recent window, QMD first-pass, etc.)\n * without forcing a specific storage contract on this module.\n */\n\nimport {\n DEFAULT_PPR_DAMPING,\n DEFAULT_PPR_ITERATIONS,\n type MemoryEdgeSource,\n type RemnicGraph,\n buildGraphFromMemories,\n queryGraph,\n} from \"./graph-retrieval.js\";\n\n/**\n * Subset of `PluginConfig` that governs the graph retrieval tier. Kept\n * as a local interface so this module does not pull in the full\n * `PluginConfig` import — `orchestrator.ts` can pass the fields directly.\n */\nexport interface GraphRecallConfig {\n /** Master enable flag. When false, `runGraphRecall` is a no-op. */\n recallGraphEnabled: boolean;\n /** PPR damping factor (default 0.85). */\n recallGraphDamping: number;\n /** PPR power-iteration cap (default 20). */\n recallGraphIterations: number;\n /**\n * Max memories the graph tier returns. `0` disables the tier's\n * contribution without touching `recallGraphEnabled`.\n */\n recallGraphTopK: number;\n}\n\n/** Per-invocation options for `runGraphRecall`. */\nexport interface GraphRecallOptions {\n /**\n * Candidate memories to build the graph from. Typically the caller's\n * recall candidate pool (hot cache + QMD first-pass). The extractor\n * reads only the fields declared on `MemoryEdgeSource` — callers can\n * safely pass richer memory objects.\n */\n memories: readonly MemoryEdgeSource[];\n /**\n * Seed memory / entity ids produced by the query-to-graph matcher.\n * Typically the ids of the top QMD hits plus any entity-exact matches.\n * If empty, PPR falls back to a uniform distribution over graph nodes.\n */\n seedIds: readonly string[];\n /**\n * Optional per-seed weights. When provided, PPR starts from the\n * weighted distribution instead of uniform-over-seeds.\n */\n seedWeights?: ReadonlyMap<string, number> | Readonly<Record<string, number>>;\n}\n\n/** A single result from the graph tier. */\nexport interface GraphRecallResult {\n /** Memory id (the `to` of the highest-scoring `memory`-typed node). */\n id: string;\n /** PPR score in [0, 1]. Higher is better. */\n score: number;\n}\n\n/** The full shape returned by `runGraphRecall`. */\nexport interface GraphRecallRun {\n /**\n * Whether the graph tier actually ran. `false` when `recallGraphEnabled`\n * is `false` or `recallGraphTopK <= 0` — in both cases `results` is `[]`\n * and `reason` indicates which gate short-circuited.\n */\n ran: boolean;\n /**\n * Memory-typed ranked results. Entity / agent nodes are filtered out\n * because the orchestrator merges this list with memory-typed QMD\n * results via MMR.\n */\n results: GraphRecallResult[];\n /** The graph that was built (or `null` if the tier did not run). */\n graph: RemnicGraph | null;\n /** Debugging tag for tier-explain surfaces. */\n reason: \"ran\" | \"disabled\" | \"topk-zero\" | \"empty-input\";\n /** Number of power-iteration rounds that executed. */\n iterations: number;\n /** Whether PPR's L1 delta fell below tolerance before the iter cap. */\n converged: boolean;\n}\n\n/**\n * Pure graph retrieval run.\n *\n * 1. Short-circuits to `{ ran: false }` when the feature flag is off,\n * `topK <= 0`, or the memory pool is empty. No graph is built, no\n * PPR runs — this preserves the zero-cost guarantee for\n * `recallGraphEnabled: false` (the default).\n * 2. Otherwise builds the retrieval graph from the candidate pool via\n * `buildGraphFromMemories` (PR 2 extractor).\n * 3. Runs Personalized PageRank via `queryGraph` (PR 3).\n * 4. Projects ranked nodes to memory-typed ids only — entity and agent\n * nodes never appear in the recall result set.\n */\nexport function runGraphRecall(\n config: GraphRecallConfig,\n options: GraphRecallOptions,\n): GraphRecallRun {\n if (!config.recallGraphEnabled) {\n return {\n ran: false,\n results: [],\n graph: null,\n reason: \"disabled\",\n iterations: 0,\n converged: true,\n };\n }\n\n // `isFinite` guard on `topK` mirrors the checks on `damping` and\n // `iterations` below. Without it a `NaN` topK would pass the typeof\n // check, then `NaN <= 0` is false (bypassing the short-circuit) and\n // the downstream `memoryResults.length >= topK` never triggers.\n const topK =\n typeof config.recallGraphTopK === \"number\" && Number.isFinite(config.recallGraphTopK)\n ? config.recallGraphTopK\n : 50;\n if (topK <= 0) {\n return {\n ran: false,\n results: [],\n graph: null,\n reason: \"topk-zero\",\n iterations: 0,\n converged: true,\n };\n }\n\n if (options.memories.length === 0) {\n return {\n ran: false,\n results: [],\n graph: null,\n reason: \"empty-input\",\n iterations: 0,\n converged: true,\n };\n }\n\n const graph = buildGraphFromMemories(options.memories);\n\n const damping =\n typeof config.recallGraphDamping === \"number\" && Number.isFinite(config.recallGraphDamping)\n ? config.recallGraphDamping\n : DEFAULT_PPR_DAMPING;\n const iterations =\n typeof config.recallGraphIterations === \"number\" && Number.isFinite(config.recallGraphIterations)\n ? config.recallGraphIterations\n : DEFAULT_PPR_ITERATIONS;\n\n // PPR runs without a topK so we can post-filter non-memory nodes without\n // the trim dropping memory-typed results. We apply topK after projection.\n const ppr = queryGraph(graph, options.seedIds, {\n damping,\n iterations,\n seedWeights: options.seedWeights,\n });\n\n const memoryResults: GraphRecallResult[] = [];\n for (const node of ppr.rankedNodes) {\n const graphNode = graph.nodes.get(node.id);\n if (!graphNode || graphNode.type !== \"memory\") continue;\n memoryResults.push({ id: node.id, score: node.score });\n if (memoryResults.length >= topK) break;\n }\n\n return {\n ran: true,\n results: memoryResults,\n graph,\n reason: \"ran\",\n iterations: ppr.iterations,\n converged: ppr.converged,\n };\n}\n"],"mappings":";;;;;;;;AA4GO,SAAS,eACd,QACA,SACgB;AAChB,MAAI,CAAC,OAAO,oBAAoB;AAC9B,WAAO;AAAA,MACL,KAAK;AAAA,MACL,SAAS,CAAC;AAAA,MACV,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ,WAAW;AAAA,IACb;AAAA,EACF;AAMA,QAAM,OACJ,OAAO,OAAO,oBAAoB,YAAY,OAAO,SAAS,OAAO,eAAe,IAChF,OAAO,kBACP;AACN,MAAI,QAAQ,GAAG;AACb,WAAO;AAAA,MACL,KAAK;AAAA,MACL,SAAS,CAAC;AAAA,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