nox-mem 3.9.1 → 3.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -532,18 +532,4 @@ server.listen(PORT, HOST, () => {
532
532
  catch (err) {
533
533
  console.error(`[nox-mem-api] reapZombies failed:`, err);
534
534
  }
535
- // D01 (2026-05-07): pre-warm reranker model se mode != off pra evitar p95 cold-start (~12-90s).
536
- // Spec specs/2026-05-07-D01-cross-encoder-reranker.md §risks §1. Single-shot, fire-and-forget.
537
- const rerankerMode = process.env.NOX_RERANKER_MODE ?? "off";
538
- if (rerankerMode === "shadow" || rerankerMode === "active") {
539
- import("./lib/reranker.js")
540
- .then(async (mod) => {
541
- const t0 = Date.now();
542
- await mod.preloadModel();
543
- console.log(`[nox-mem-api] reranker pre-warmed in ${Date.now() - t0}ms (mode=${rerankerMode})`);
544
- })
545
- .catch((err) => {
546
- console.error(`[nox-mem-api] reranker pre-warm failed (fail-open, lazy load on first call):`, err?.message ?? err);
547
- });
548
- }
549
535
  });
package/dist/index.js CHANGED
@@ -329,10 +329,22 @@ program
329
329
  });
330
330
  program
331
331
  .command("compact")
332
- .description("Compress old chunks (>30 days) into summaries")
332
+ .description("Replace old chunks with one LLM summary per file and DELETE the originals (a snapshot is taken first). " +
333
+ "Refuses without --destructive; use --dry-run to preview.")
333
334
  .option("--age <days>", "Minimum age in days", "30")
334
335
  .option("--dry-run", "Preview without making changes", false)
336
+ .option("--destructive", "Confirm that the original chunks will be deleted", false)
335
337
  .action(async (opts) => {
338
+ // Guard (2026-11-08): in the reference deployment `compact` reduced 10,204 chunks to 210
339
+ // summaries over six months with no decision on record (DECISIONS "NÃO FAZEMOS" #32), and the
340
+ // deleted originals carried the evidence the KG pointed to. Deleting must be an explicit choice.
341
+ if (!opts.dryRun && !opts.destructive) {
342
+ console.error("[COMPACT] Refused: compact deletes the original chunks and keeps only a summary per file. " +
343
+ "Run with --dry-run to see what would change, or --destructive to proceed (a snapshot is taken first).");
344
+ closeDb();
345
+ process.exitCode = 2;
346
+ return;
347
+ }
336
348
  const result = await compact(parseInt(opts.age, 10), opts.dryRun);
337
349
  console.log("[COMPACT] Done: " + result.compacted + " compacted, " + result.summaries + " summaries, " + result.deleted + " removed");
338
350
  closeDb();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.9.1",
3
+ "version": "3.10.0",
4
4
  "description": "Pain-weighted hybrid memory engine: FTS5 + semantic search + knowledge graph, self-hosted on any Linux VPS.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -52,7 +52,7 @@
52
52
  ],
53
53
  "scripts": {
54
54
  "build": "tsc",
55
- "prepublishOnly": "npm run build",
55
+ "prepublishOnly": "rm -rf dist && npm run build",
56
56
  "test": "rm -rf dist && npm run build && tsc -p tsconfig.test.json && node --test \"dist/**/*.test.js\"",
57
57
  "test:retention": "node --test dist/__tests__/retention.test.js",
58
58
  "test:op-audit": "node --test dist/__tests__/op-audit-e2e.test.js"
@@ -63,7 +63,6 @@
63
63
  "sqlite-vec": "^0.1.10-alpha.1"
64
64
  },
65
65
  "optionalDependencies": {
66
- "@xenova/transformers": "^2.17.2",
67
66
  "sqlite-vec-darwin-arm64": "^0.1.10-alpha.1",
68
67
  "sqlite-vec-darwin-x64": "^0.1.10-alpha.1",
69
68
  "sqlite-vec-linux-arm64": "^0.1.10-alpha.1",
@@ -1,91 +0,0 @@
1
- /**
2
- * T3 + T5 — Entity ref + code-path extractors.
3
- *
4
- * Pure functions: no IO, no DB, no async. Caller composes with stripCodeBlocks
5
- * (default) and frontmatter parsing in the router (T6).
6
- *
7
- * Adapted from gbrain/src/core/link-extraction.ts (MIT) — adjusted to nox-mem
8
- * domain (DIR_PATTERN whitelist, FK-id resolution deferred to router).
9
- *
10
- * Spec: specs/2026-05-18-L4-regex-first-extraction.md §6.2-§6.4.
11
- */
12
- import { stripCodeBlocks } from "./strip-code.js";
13
- import { buildBareRefRe, buildCodeRefRe, buildMarkdownLinkRe, buildWikilinkRe, } from "./patterns.js";
14
- import { NOX_ENTITY_TYPES, } from "./types.js";
15
- const ENTITY_TYPE_SET = new Set(NOX_ENTITY_TYPES);
16
- function asEntityType(value) {
17
- return ENTITY_TYPE_SET.has(value) ? value : null;
18
- }
19
- function pushRef(bucket, rawEntityType, rawSlug, source, display) {
20
- const entityType = asEntityType(rawEntityType);
21
- if (!entityType)
22
- return;
23
- const slug = rawSlug.toLowerCase();
24
- if (!slug)
25
- return;
26
- const key = `${entityType}/${slug}`;
27
- const existing = bucket.get(key);
28
- if (existing) {
29
- // Prefer explicit display from markdown_link/wikilink over bare_ref.
30
- if (!existing.display && display)
31
- existing.display = display;
32
- return;
33
- }
34
- bucket.set(key, { entityType, slug, key, source, display });
35
- }
36
- /**
37
- * Pure regex-based entity-ref extractor.
38
- *
39
- * Pipeline:
40
- * 1. stripCodeBlocks (suppress matches inside ```code```)
41
- * 2. Markdown links `[Name](type/slug)`
42
- * 3. Obsidian wikilinks `[[type/slug|Display]]`
43
- * 4. Bare refs `type/slug` (boundary-anchored)
44
- * 5. Dedupe by canonical key
45
- */
46
- export function extractEntityRefsRegex(content) {
47
- if (!content)
48
- return [];
49
- const { stripped } = stripCodeBlocks(content);
50
- const refs = new Map();
51
- const mdRe = buildMarkdownLinkRe();
52
- for (const m of stripped.matchAll(mdRe)) {
53
- pushRef(refs, m[2] ?? "", m[3] ?? "", "markdown_link", m[1]?.trim());
54
- }
55
- const wikiRe = buildWikilinkRe();
56
- for (const m of stripped.matchAll(wikiRe)) {
57
- pushRef(refs, m[1] ?? "", m[2] ?? "", "wikilink", m[3]?.trim());
58
- }
59
- const bareRe = buildBareRefRe();
60
- for (const m of stripped.matchAll(bareRe)) {
61
- pushRef(refs, m[1] ?? "", m[2] ?? "", "bare_ref");
62
- }
63
- return Array.from(refs.values());
64
- }
65
- /**
66
- * T5 — extract code-path references (`src/foo.ts:42`, `specs/X.md`).
67
- *
68
- * Stripped of code fences first (gbrain pattern — avoid recursive matches
69
- * inside example fences).
70
- */
71
- export function extractCodeRefs(content) {
72
- if (!content)
73
- return [];
74
- const { stripped } = stripCodeBlocks(content);
75
- const seen = new Map();
76
- const re = buildCodeRefRe();
77
- for (const m of stripped.matchAll(re)) {
78
- const root = (m[1] ?? "").toLowerCase();
79
- const path = m[2] ?? "";
80
- if (!root || !path)
81
- continue;
82
- const lineRaw = m[4];
83
- const line = lineRaw ? Number.parseInt(lineRaw, 10) : undefined;
84
- const normalized = `${root}/${path}`.toLowerCase();
85
- const key = `codepath/${normalized}${line ? `:${line}` : ""}`;
86
- if (seen.has(key))
87
- continue;
88
- seen.set(key, { root, path, line, key });
89
- }
90
- return Array.from(seen.values());
91
- }
@@ -1,169 +0,0 @@
1
- /**
2
- * T4 — extractFrontmatterRelations.
3
- *
4
- * Parses a small, well-known subset of YAML frontmatter (scalars + flow/block
5
- * arrays of scalars) — enough to support the 6 rules in spec §5 without an
6
- * external dep. If consumers need full YAML they can preprocess and pass the
7
- * already-parsed object via {@link extractFrontmatterRelationsFromObject}.
8
- *
9
- * Spec: specs/2026-05-18-L4-regex-first-extraction.md §5.
10
- */
11
- /** Match a leading `---\n...\n---` block. */
12
- const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
13
- const FIELD_TO_RELATION = {
14
- agent: "is_agent_of",
15
- references: "references",
16
- supersedes: "supersedes",
17
- caused_by: "caused_by",
18
- resolves: "resolves",
19
- decided_by: "decided_by",
20
- };
21
- /** Strip surrounding quotes (single or double). */
22
- function unquote(s) {
23
- const t = s.trim();
24
- if (t.length >= 2) {
25
- const first = t[0];
26
- const last = t[t.length - 1];
27
- if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
28
- return t.slice(1, -1);
29
- }
30
- }
31
- return t;
32
- }
33
- /** Pull the `---`-delimited block from the head of a markdown doc. */
34
- export function extractFrontmatterBlock(content) {
35
- const m = content.match(FRONTMATTER_RE);
36
- return m ? (m[1] ?? null) : null;
37
- }
38
- /**
39
- * Minimal YAML scalar/array parser for top-level fields. NOT a full YAML
40
- * implementation — handles:
41
- * - `key: value`
42
- * - `key: "quoted value"`
43
- * - `key: [a, b, c]` (flow array)
44
- * - block array:
45
- * key:
46
- * - a
47
- * - b
48
- */
49
- export function parseFrontmatterFields(block) {
50
- const lines = block.split(/\r?\n/);
51
- const out = [];
52
- let i = 0;
53
- while (i < lines.length) {
54
- const line = lines[i] ?? "";
55
- const trimmed = line.trim();
56
- if (!trimmed || trimmed.startsWith("#")) {
57
- i++;
58
- continue;
59
- }
60
- const colonIdx = trimmed.indexOf(":");
61
- if (colonIdx <= 0) {
62
- i++;
63
- continue;
64
- }
65
- const key = trimmed.slice(0, colonIdx).trim();
66
- const rest = trimmed.slice(colonIdx + 1).trim();
67
- if (!rest) {
68
- // Possible block array — peek subsequent indented `- ` lines.
69
- const items = [];
70
- let j = i + 1;
71
- while (j < lines.length) {
72
- const peek = lines[j] ?? "";
73
- const peekTrim = peek.trim();
74
- if (peekTrim.startsWith("- ")) {
75
- items.push(unquote(peekTrim.slice(2)));
76
- j++;
77
- continue;
78
- }
79
- if (peekTrim === "") {
80
- j++;
81
- continue;
82
- }
83
- break;
84
- }
85
- if (items.length > 0) {
86
- out.push({ key, array: items });
87
- i = j;
88
- continue;
89
- }
90
- out.push({ key, scalar: "" });
91
- i++;
92
- continue;
93
- }
94
- if (rest.startsWith("[") && rest.endsWith("]")) {
95
- const inner = rest.slice(1, -1).trim();
96
- const items = inner ? inner.split(",").map((p) => unquote(p)) : [];
97
- out.push({ key, array: items.filter(Boolean) });
98
- i++;
99
- continue;
100
- }
101
- out.push({ key, scalar: unquote(rest) });
102
- i++;
103
- }
104
- return out;
105
- }
106
- function relationFrom(field, raw) {
107
- const rel = FIELD_TO_RELATION[field];
108
- if (!rel)
109
- return null;
110
- const target = raw.trim();
111
- if (!target)
112
- return null;
113
- return { relationType: rel, target, raw };
114
- }
115
- /**
116
- * Parse frontmatter block + emit typed relations per spec §5 table.
117
- *
118
- * Returns [] when the doc has no frontmatter.
119
- */
120
- export function extractFrontmatterRelations(content) {
121
- const block = extractFrontmatterBlock(content);
122
- if (!block)
123
- return [];
124
- const fields = parseFrontmatterFields(block);
125
- const out = [];
126
- for (const f of fields) {
127
- if (!(f.key in FIELD_TO_RELATION))
128
- continue;
129
- if (f.array) {
130
- for (const v of f.array) {
131
- const rel = relationFrom(f.key, v);
132
- if (rel)
133
- out.push(rel);
134
- }
135
- }
136
- else if (f.scalar !== undefined && f.scalar !== "") {
137
- const rel = relationFrom(f.key, f.scalar);
138
- if (rel)
139
- out.push(rel);
140
- }
141
- }
142
- return out;
143
- }
144
- /**
145
- * Variant for callers that already parsed YAML (e.g. via gray-matter elsewhere
146
- * in the pipeline). Object values may be string | string[].
147
- */
148
- export function extractFrontmatterRelationsFromObject(data) {
149
- const out = [];
150
- for (const [k, v] of Object.entries(data)) {
151
- if (!(k in FIELD_TO_RELATION))
152
- continue;
153
- if (Array.isArray(v)) {
154
- for (const item of v) {
155
- if (typeof item !== "string")
156
- continue;
157
- const rel = relationFrom(k, item);
158
- if (rel)
159
- out.push(rel);
160
- }
161
- }
162
- else if (typeof v === "string") {
163
- const rel = relationFrom(k, v);
164
- if (rel)
165
- out.push(rel);
166
- }
167
- }
168
- return out;
169
- }
@@ -1,14 +0,0 @@
1
- /**
2
- * L4 regex-extract — public surface (T1-T6).
3
- *
4
- * gbrain-inspired (MIT, Garry Tan) regex-first KG extraction with Gemini
5
- * fallback. See specs/2026-05-18-L4-regex-first-extraction.md.
6
- */
7
- export * from "./types.js";
8
- export { stripCodeBlocks } from "./strip-code.js";
9
- export { DIR_PATTERN, OPTIONAL_TOP, SLUG_CHARS, buildMarkdownLinkRe, buildWikilinkRe, buildBareRefRe, buildCodeRefRe, } from "./patterns.js";
10
- export { extractEntityRefsRegex, extractCodeRefs } from "./extractor.js";
11
- export { extractFrontmatterBlock, parseFrontmatterFields, extractFrontmatterRelations, extractFrontmatterRelationsFromObject, } from "./frontmatter.js";
12
- export { decideExtraction, mergeRelations, } from "./ingest-router-l4.js";
13
- export { reconcileEntityLinks, extractTargetSlugsFromContent, detectSlugChange, rewriteChunksForRename, detectCircularRename, STALE_CONFIDENCE, STALE_REASON, } from "./reconcile.js";
14
- export { runProductionFastPath, filterHighConfidence, mergeWithLlmRelations, relationDedupKey, isRegexEnabled, isSkipGeminiEnabled, scoreEntityRef, scoreFrontmatterRelation, CONFIDENCE_THRESHOLD, CONFIDENCE_FRONTMATTER, CONFIDENCE_EXPLICIT_LINK, CONFIDENCE_BARE_REF, } from "./production-wire.js";
@@ -1,102 +0,0 @@
1
- /**
2
- * T6 — Ingest router integration: regex-first KG extraction with Gemini fallback.
3
- *
4
- * Pure orchestration layer — no DB writes, no Gemini API calls. Returns a
5
- * structured decision payload that the actual ingest router (production
6
- * `src/lib/ingest-router.ts`) consumes to:
7
- * 1) write `kg_relations` rows tagged `extraction_method`
8
- * 2) decide whether to invoke `geminiKgExtract`
9
- * 3) merge + dedup results
10
- * 4) emit telemetry per spec §7
11
- *
12
- * Keeping this layer pure means it's covered by unit tests without DB or
13
- * network fixtures — the integration test layer (T7+ deferred) wires the
14
- * production ingestor.
15
- *
16
- * Spec: specs/2026-05-18-L4-regex-first-extraction.md §3 + §7.
17
- */
18
- import { extractEntityRefsRegex, extractCodeRefs } from "./extractor.js";
19
- import { extractFrontmatterRelations } from "./frontmatter.js";
20
- /** Sections eligible for the skip-Gemini fast path. */
21
- const SKIP_ELIGIBLE_SECTIONS = new Set([
22
- "compiled",
23
- "frontmatter",
24
- "timeline",
25
- ]);
26
- /** Chunk types that ALWAYS run Gemini (prose-heavy, weak structure). */
27
- const FORCE_GEMINI_TYPES = new Set([
28
- "conversation",
29
- "daily_log",
30
- "freeform",
31
- ]);
32
- /**
33
- * Run regex extraction + decide whether Gemini should be skipped.
34
- *
35
- * Skip-gate (spec §7):
36
- * section ∈ {compiled, frontmatter, timeline}
37
- * AND regex_relations_count ≥ 1
38
- * AND chunk.type ∉ {conversation, daily_log, freeform}
39
- */
40
- export function decideExtraction(chunk) {
41
- const t0 = performanceNowSafe();
42
- const entityRefs = extractEntityRefsRegex(chunk.content);
43
- const frontmatterRelations = extractFrontmatterRelations(chunk.content);
44
- const codeRefs = extractCodeRefs(chunk.content);
45
- const regexElapsed = performanceNowSafe() - t0;
46
- const regexRelationsCount = entityRefs.length + frontmatterRelations.length + codeRefs.length;
47
- const sectionEligible = chunk.section
48
- ? SKIP_ELIGIBLE_SECTIONS.has(chunk.section)
49
- : false;
50
- const typeAllowsSkip = !FORCE_GEMINI_TYPES.has(chunk.type);
51
- const skipGemini = sectionEligible && typeAllowsSkip && regexRelationsCount >= 1;
52
- let method;
53
- if (skipGemini) {
54
- method = "regex_only";
55
- }
56
- else if (regexRelationsCount === 0) {
57
- method = "gemini_only_after_regex_zero";
58
- }
59
- else if (sectionEligible) {
60
- method = "regex_primary_gemini_secondary";
61
- }
62
- else {
63
- method = "gemini_only";
64
- }
65
- const regex = {
66
- entityRefs,
67
- frontmatterRelations,
68
- codeRefs,
69
- hadCodeFences: chunk.content.includes("`"),
70
- };
71
- const telemetry = {
72
- section: chunk.section,
73
- extraction_method: method,
74
- regex_relations_count: regexRelationsCount,
75
- gemini_relations_count: null,
76
- gemini_call_skipped: skipGemini,
77
- latency_ms: { regex: regexElapsed, gemini: null, total: null },
78
- };
79
- return {
80
- regex,
81
- regexRelationsCount,
82
- skipGemini,
83
- telemetry,
84
- };
85
- }
86
- export function mergeRelations(regex, gemini) {
87
- const seen = new Set();
88
- const out = [];
89
- for (const r of [...regex, ...gemini]) {
90
- const k = `${r.source}|${r.target}|${r.relationType}`.toLowerCase();
91
- if (seen.has(k))
92
- continue;
93
- seen.add(k);
94
- out.push(r);
95
- }
96
- return out;
97
- }
98
- /** Cross-platform high-resolution timer; falls back to Date.now() on Edge runtimes. */
99
- function performanceNowSafe() {
100
- const g = globalThis;
101
- return g.performance?.now?.() ?? Date.now();
102
- }
@@ -1,91 +0,0 @@
1
- /**
2
- * T2 — DIR_PATTERN + entity-ref regexes.
3
- *
4
- * Adapted from gbrain/src/core/link-extraction.ts (MIT). Adjusted for nox-mem
5
- * entity-type whitelist (specs/2026-05-18-L4-regex-first-extraction.md §4).
6
- *
7
- * IMPORTANT: All consumer regexes carry the global flag (`g`). Always reset
8
- * `.lastIndex = 0` before reuse or instantiate a fresh RegExp; callers in
9
- * extractor.ts do so by constructing per call via {@link buildEntityRefRe}.
10
- */
11
- import { NOX_ENTITY_TYPES } from "./types.js";
12
- /** `(?:feedback|person|...)` literal alternation snippet — non-capturing. */
13
- export const DIR_PATTERN = `(?:${NOX_ENTITY_TYPES.filter((t) => t !== "entities").join("|")})`;
14
- /** Top-level dir prefix `entities/` is optional in wikilinks. */
15
- export const OPTIONAL_TOP = `(?:entities\\/)?`;
16
- /** Slug character class: letters, digits, underscore, dash. NO dots (drops `.md`). */
17
- export const SLUG_CHARS = `[a-z0-9_\\-]+`;
18
- /**
19
- * Markdown-link form: `[Name](path/to/entityType/slug)`, optional `.md`, optional
20
- * tooltip `"..."`. Path may have `../` prefix.
21
- *
22
- * Groups:
23
- * 1 — display text
24
- * 2 — entity type
25
- * 3 — slug (no .md, no anchor)
26
- */
27
- export function buildMarkdownLinkRe() {
28
- return new RegExp(String.raw `\[([^\]\n]+?)\]\(` +
29
- String.raw `(?:\.{1,2}\/)*` +
30
- `(?:entities\\/)?` +
31
- `(${DIR_PATTERN})\\/` +
32
- `(${SLUG_CHARS})` +
33
- String.raw `(?:\.md)?` +
34
- String.raw `(?:#[^)\s]*)?` +
35
- String.raw `(?:\s+"[^"]*")?` +
36
- String.raw `\)`, "g");
37
- }
38
- /**
39
- * Obsidian wikilink form: `[[entityType/slug]]`, optional `entities/` prefix,
40
- * optional `#anchor`, optional `|display`. Accept ASCII-aware slugs only —
41
- * Unicode boundary issues handled in extractor via stripping non-slug chars.
42
- *
43
- * Groups:
44
- * 1 — entity type
45
- * 2 — slug
46
- * 3 — display (after `|`, optional)
47
- */
48
- export function buildWikilinkRe() {
49
- return new RegExp(String.raw `\[\[` +
50
- `(?:entities\\/)?` +
51
- `(${DIR_PATTERN})\\/` +
52
- `(${SLUG_CHARS})` +
53
- String.raw `(?:#[^|\]\n]*)?` +
54
- String.raw `(?:\|([^\]\n]+?))?` +
55
- String.raw `\]\]`, "g");
56
- }
57
- /**
58
- * Bare slug form: standalone `entityType/slug` token, only when surrounded by
59
- * whitespace/start/punctuation boundary. Uses lookbehind/lookahead WITHOUT
60
- * `\b` (MEMORY.md `JS regex \b falha em Unicode`).
61
- *
62
- * Tightly anchored to avoid URL false-positives — disallow `/` directly before
63
- * the token (so `example.com/feedback/foo` does NOT match).
64
- *
65
- * Groups:
66
- * 1 — entity type
67
- * 2 — slug
68
- */
69
- export function buildBareRefRe() {
70
- return new RegExp(`(?<=^|[\\s(,;:'"\`])` +
71
- `(${DIR_PATTERN})\\/` +
72
- `(${SLUG_CHARS})` +
73
- `(?=$|[\\s).,?!;:'"\`])`, "gm");
74
- }
75
- /**
76
- * Code-path references (`src/lib/op-audit.ts:42`, `specs/foo.md`). Domain dirs
77
- * are whitelisted to suppress matches against unrelated path-like text.
78
- *
79
- * Groups:
80
- * 1 — top-level dir
81
- * 2 — path under root (extension included)
82
- * 3 — extension
83
- * 4 — line number (optional)
84
- */
85
- export function buildCodeRefRe() {
86
- return new RegExp(`(?<=^|[\\s(,;:'"\`])` +
87
- `(src|specs|audits|eval|validation|memory|paper|docs|runbooks|scripts|lessons|benchmark)` +
88
- `\\/` +
89
- `([a-z0-9_\\-\\/\\.]+\\.(ts|js|md|sh|json|yaml|yml|sql|py))` +
90
- `(?::(\\d+))?`, "gmi");
91
- }
@@ -1,202 +0,0 @@
1
- /**
2
- * T9 — Production wire-up: regex extractor as FAST-PATH before LLM extraction.
3
- *
4
- * Hooks the regex extractor into the existing `ingestFile()` pipeline as a
5
- * fast-path check BEFORE calling Gemini for KG extraction.
6
- *
7
- * Decision rule (spec §7 + T9):
8
- * If regex extraction confidence ≥ CONFIDENCE_THRESHOLD (0.8):
9
- * - Typed link from frontmatter (is_agent_of, supersedes, etc.) → confidence=0.95
10
- * - Explicit [[wikilink]] or [md-link](slug) → confidence=0.90
11
- * - Bare ref `entityType/slug` → confidence=0.75 (below threshold → falls through)
12
- * → SKIP Gemini for this chunk
13
- * Else:
14
- * → Fall through to LLM (existing path)
15
- *
16
- * Telemetry: `extraction_method` logged per kg_relations row.
17
- *
18
- * This module is a pure adapter — it wraps `decideExtraction` with the
19
- * confidence-gate logic and returns a wire-compatible result. The production
20
- * `ingestFile()` router imports this and acts on the decision.
21
- *
22
- * Spec: specs/2026-05-18-L4-regex-first-extraction.md §3, §7, T9.
23
- */
24
- import { decideExtraction } from "./ingest-router-l4.js";
25
- // ---------------------------------------------------------------------------
26
- // Confidence thresholds
27
- // ---------------------------------------------------------------------------
28
- /**
29
- * Minimum confidence required to skip LLM extraction.
30
- * Below this, fall through to Gemini (existing path).
31
- */
32
- export const CONFIDENCE_THRESHOLD = 0.8;
33
- /** Confidence for frontmatter typed-link relations (highest precision). */
34
- export const CONFIDENCE_FRONTMATTER = 0.95;
35
- /** Confidence for explicit [[wikilink]] or [md-link](slug) matches. */
36
- export const CONFIDENCE_EXPLICIT_LINK = 0.90;
37
- /** Confidence for bare `entityType/slug` references. */
38
- export const CONFIDENCE_BARE_REF = 0.75;
39
- // ---------------------------------------------------------------------------
40
- // Confidence scoring
41
- // ---------------------------------------------------------------------------
42
- /**
43
- * Compute confidence for a single entity ref based on its source pattern.
44
- * Spec §7: frontmatter > explicit link > bare ref.
45
- */
46
- export function scoreEntityRef(ref) {
47
- switch (ref.source) {
48
- case "markdown_link":
49
- case "wikilink":
50
- return CONFIDENCE_EXPLICIT_LINK;
51
- case "bare_ref":
52
- return CONFIDENCE_BARE_REF;
53
- default:
54
- return CONFIDENCE_BARE_REF;
55
- }
56
- }
57
- /**
58
- * Compute confidence for a frontmatter-derived typed relation.
59
- * Frontmatter fields are explicitly authored → highest precision.
60
- */
61
- export function scoreFrontmatterRelation(_rel) {
62
- return CONFIDENCE_FRONTMATTER;
63
- }
64
- // ---------------------------------------------------------------------------
65
- // Core fast-path check
66
- // ---------------------------------------------------------------------------
67
- /**
68
- * Run the regex fast-path check for a chunk.
69
- *
70
- * 1. Calls `decideExtraction` to get regex hits and LLM skip decision.
71
- * 2. Scores each relation by confidence.
72
- * 3. If max confidence ≥ CONFIDENCE_THRESHOLD → skipLlm=true.
73
- * 4. Returns scored relations ready for kg_relations insert.
74
- *
75
- * @param chunk Chunk metadata + content.
76
- * @param sourceSlug The entity slug this chunk belongs to (for FK resolution).
77
- */
78
- export function runProductionFastPath(chunk, sourceSlug) {
79
- const decision = decideExtraction(chunk);
80
- const { regex } = decision;
81
- const regexRelations = [];
82
- let maxConfidence = 0;
83
- // Score frontmatter relations (highest confidence).
84
- for (const rel of regex.frontmatterRelations) {
85
- const confidence = scoreFrontmatterRelation(rel);
86
- maxConfidence = Math.max(maxConfidence, confidence);
87
- regexRelations.push({
88
- sourceSlug,
89
- targetSlug: rel.target,
90
- relationType: rel.relationType,
91
- confidence,
92
- extraction_method: "regex",
93
- relation_reason: "regex_extracted",
94
- });
95
- }
96
- // Score entity refs (wikilink/markdown_link/bare_ref).
97
- for (const ref of regex.entityRefs) {
98
- const confidence = scoreEntityRef(ref);
99
- maxConfidence = Math.max(maxConfidence, confidence);
100
- regexRelations.push({
101
- sourceSlug,
102
- targetSlug: ref.key,
103
- relationType: "references",
104
- confidence,
105
- extraction_method: "regex",
106
- relation_reason: "regex_extracted",
107
- });
108
- }
109
- // Code refs: treated as bare-ref confidence level.
110
- for (const cref of regex.codeRefs) {
111
- const confidence = CONFIDENCE_BARE_REF;
112
- maxConfidence = Math.max(maxConfidence, confidence);
113
- regexRelations.push({
114
- sourceSlug,
115
- targetSlug: cref.key,
116
- relationType: "code_ref",
117
- confidence,
118
- extraction_method: "regex",
119
- relation_reason: "regex_extracted",
120
- });
121
- }
122
- // Override skip decision: also check our confidence gate.
123
- // decideExtraction may say skipGemini=true via section/type gate;
124
- // we additionally require maxConfidence ≥ CONFIDENCE_THRESHOLD.
125
- const skipLlm = decision.skipGemini && maxConfidence >= CONFIDENCE_THRESHOLD;
126
- const telemetry = {
127
- extraction_method: skipLlm
128
- ? "regex_only"
129
- : decision.telemetry.extraction_method,
130
- regex_relations_count: regexRelations.length,
131
- gemini_call_skipped: skipLlm,
132
- latency_ms_regex: decision.telemetry.latency_ms.regex,
133
- };
134
- return {
135
- regexRelations,
136
- maxConfidence,
137
- skipLlm,
138
- decision,
139
- telemetry,
140
- };
141
- }
142
- // ---------------------------------------------------------------------------
143
- // Filter helpers (for production ingestFile() integration)
144
- // ---------------------------------------------------------------------------
145
- /**
146
- * Filter a list of scored relations to only those above the confidence gate.
147
- * Used when merging regex + LLM output — only high-confidence regex relations
148
- * suppress their LLM counterparts.
149
- */
150
- export function filterHighConfidence(relations, threshold = CONFIDENCE_THRESHOLD) {
151
- return relations.filter((r) => r.confidence >= threshold);
152
- }
153
- /**
154
- * Build a dedup key for a relation — used to merge regex + LLM output.
155
- * Key = `<sourceSlug>|<targetSlug>|<relationType>` (case-insensitive).
156
- */
157
- export function relationDedupKey(r) {
158
- return `${r.sourceSlug}|${r.targetSlug}|${r.relationType}`.toLowerCase();
159
- }
160
- /**
161
- * Merge regex scored relations with LLM relations. Deduplicates by key,
162
- * preferring high-confidence regex entries over LLM for the same triple.
163
- */
164
- export function mergeWithLlmRelations(regexRelations, llmRelations) {
165
- const seen = new Map();
166
- // Regex first (higher priority for dedup).
167
- for (const r of regexRelations) {
168
- const k = relationDedupKey(r);
169
- if (!seen.has(k))
170
- seen.set(k, r);
171
- }
172
- // LLM fills gaps not covered by regex.
173
- for (const r of llmRelations) {
174
- const k = relationDedupKey(r);
175
- if (!seen.has(k)) {
176
- seen.set(k, {
177
- ...r,
178
- confidence: 0.7, // default LLM confidence
179
- extraction_method: "llm",
180
- relation_reason: "gemini_extracted",
181
- });
182
- }
183
- }
184
- return Array.from(seen.values());
185
- }
186
- // ---------------------------------------------------------------------------
187
- // Env-flag helpers
188
- // ---------------------------------------------------------------------------
189
- /**
190
- * Returns true when the L4 regex feature is enabled via env flag.
191
- * Feature is opt-in via `NOX_L4_REGEX_ENABLED=1`.
192
- */
193
- export function isRegexEnabled() {
194
- return process.env["NOX_L4_REGEX_ENABLED"] === "1";
195
- }
196
- /**
197
- * Returns true when the skip-Gemini gate is enabled.
198
- * Requires both `NOX_L4_REGEX_ENABLED=1` AND `NOX_L4_SKIP_GEMINI=1`.
199
- */
200
- export function isSkipGeminiEnabled() {
201
- return isRegexEnabled() && process.env["NOX_L4_SKIP_GEMINI"] === "1";
202
- }
@@ -1,210 +0,0 @@
1
- /**
2
- * T7 — Stale-link reconciliation on entity file update.
3
- *
4
- * When an entity file is renamed or edited, links pointing to the old slug may
5
- * become stale. This module handles two modes:
6
- *
7
- * - stale-mark (default): sets `confidence` to STALE_CONFIDENCE + adds a
8
- * `superseded_by` pointer to the new slug in each affected relation.
9
- * - auto-rename (env `NOX_L4_AUTO_RENAME=1`): rewrites old slug → new slug
10
- * across all affected kg_relations records.
11
- *
12
- * CRITICAL: auto-rename is DESTRUCTIVE — must require explicit env opt-in.
13
- * Default is stale-mark (append-only philosophy per CLAUDE.md regra 6).
14
- *
15
- * Spec: specs/2026-05-18-L4-regex-first-extraction.md §8.
16
- */
17
- import { extractEntityRefsRegex } from "./extractor.js";
18
- import { extractFrontmatterRelations } from "./frontmatter.js";
19
- // ---------------------------------------------------------------------------
20
- // Constants
21
- // ---------------------------------------------------------------------------
22
- /** Confidence assigned to stale relations (low — known stale). */
23
- export const STALE_CONFIDENCE = 0.3;
24
- /**
25
- * Reason string written to superseded_reason when stale-marking a relation.
26
- * Matches the reason used in the stale-link reconciliation flow (spec §8).
27
- */
28
- export const STALE_REASON = "stale_link_reconciliation";
29
- // ---------------------------------------------------------------------------
30
- // Content → slug set extraction
31
- // ---------------------------------------------------------------------------
32
- /**
33
- * Derive the full set of target slugs found in `content` via regex extraction
34
- * (entity refs + frontmatter relations combined). Code refs are excluded from
35
- * reconciliation — they're not direct KG entity slugs.
36
- */
37
- export function extractTargetSlugsFromContent(content) {
38
- const slugs = new Set();
39
- for (const ref of extractEntityRefsRegex(content)) {
40
- slugs.add(ref.key); // already `<entityType>/<slug>`
41
- }
42
- for (const rel of extractFrontmatterRelations(content)) {
43
- const tgt = rel.target.trim();
44
- if (tgt)
45
- slugs.add(tgt);
46
- }
47
- return slugs;
48
- }
49
- /**
50
- * Reconcile kg_relations for a given entity when its content changes.
51
- *
52
- * Algorithm (spec §8):
53
- * 1. Extract new target slugs from `newContent` via regex.
54
- * 2. Diff `existingRelations` vs new slug set:
55
- * - Added: in new set, not in existing → emit `add` action.
56
- * - Removed: in existing (regex_extracted only), not in new set → emit
57
- * `mark_stale` or `auto_rename` action.
58
- * - Unchanged: present in both → emit `noop`.
59
- * 3. Gemini relations (extraction_method='gemini') are NEVER touched —
60
- * deferred to next Gemini run.
61
- * 4. Already-superseded relations are skipped.
62
- *
63
- * @param sourceSlug The entity being reconciled (e.g. `feedback/no_secrets`).
64
- * @param newContent New markdown content of the entity file.
65
- * @param existingRelations Current `kg_relations` rows for this entity.
66
- * @param opts Reconcile options.
67
- */
68
- export function reconcileEntityLinks(sourceSlug, newContent, existingRelations, opts = {}) {
69
- const autoRename = opts.autoRename === true;
70
- const newSlug = opts.newSlug?.trim() ?? "";
71
- const mode = autoRename && newSlug
72
- ? "auto_rename"
73
- : "stale_mark";
74
- // Derive new target slug set from updated content.
75
- const newTargetSlugs = extractTargetSlugsFromContent(newContent);
76
- // Build lookup of existing REGEX-extracted (active) relations by target slug.
77
- const existingByTarget = new Map();
78
- for (const rel of existingRelations) {
79
- if (rel.extraction_method !== "regex")
80
- continue; // only manage regex rels
81
- if (rel.superseded)
82
- continue; // skip already-superseded
83
- existingByTarget.set(rel.targetSlug, rel);
84
- }
85
- const actions = [];
86
- const added = [];
87
- const removed = [];
88
- const unchanged = [];
89
- // Check new slugs: adds vs noops.
90
- for (const tgtSlug of newTargetSlugs) {
91
- if (existingByTarget.has(tgtSlug)) {
92
- actions.push({ type: "noop", targetSlug: tgtSlug });
93
- unchanged.push(tgtSlug);
94
- }
95
- else {
96
- actions.push({
97
- type: "add",
98
- targetSlug: tgtSlug,
99
- relationType: "regex_extracted",
100
- });
101
- added.push(tgtSlug);
102
- }
103
- }
104
- // Check removed: existing regex rels not in new set.
105
- for (const [tgtSlug, rel] of existingByTarget) {
106
- if (newTargetSlugs.has(tgtSlug))
107
- continue; // handled above
108
- if (mode === "auto_rename" && newSlug) {
109
- actions.push({
110
- type: "auto_rename",
111
- relation: rel,
112
- oldTargetSlug: tgtSlug,
113
- newTargetSlug: newSlug,
114
- });
115
- }
116
- else {
117
- actions.push({
118
- type: "mark_stale",
119
- relation: rel,
120
- newConfidence: STALE_CONFIDENCE,
121
- supersededReason: STALE_REASON,
122
- });
123
- }
124
- removed.push(tgtSlug);
125
- }
126
- return { actions, added, removed, unchanged, mode };
127
- }
128
- // ---------------------------------------------------------------------------
129
- // Rename detection helper
130
- // ---------------------------------------------------------------------------
131
- /**
132
- * Detect whether an entity slug has changed between two content snapshots by
133
- * comparing the `slug` frontmatter field (or the first heading). Returns the
134
- * detected new slug if different, null if no change detected.
135
- *
136
- * This is a lightweight heuristic — the definitive source is the filesystem
137
- * rename event from the watcher. Use this as a sanity check.
138
- */
139
- export function detectSlugChange(oldContent, newContent) {
140
- const extractSlugHint = (content) => {
141
- // Try frontmatter `slug:` field first.
142
- const fm = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
143
- if (fm) {
144
- const slugMatch = fm[1]?.match(/^slug:\s*([^\r\n]+)/m);
145
- if (slugMatch)
146
- return slugMatch[1]?.trim() ?? null;
147
- }
148
- // Fallback: first H1.
149
- const h1 = content.match(/^#\s+(.+)$/m);
150
- if (h1)
151
- return h1[1]?.trim() ?? null;
152
- return null;
153
- };
154
- const oldSlug = extractSlugHint(oldContent);
155
- const newSlug = extractSlugHint(newContent);
156
- const changed = oldSlug !== null && newSlug !== null && oldSlug !== newSlug;
157
- return { changed, oldSlug, newSlug };
158
- }
159
- export function rewriteChunksForRename(chunks, oldSlug, newSlug) {
160
- if (!oldSlug || !newSlug || oldSlug === newSlug) {
161
- return chunks.map((c) => ({
162
- chunkId: c.chunkId,
163
- original: c.content,
164
- rewritten: c.content,
165
- changed: false,
166
- }));
167
- }
168
- const escaped = oldSlug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
169
- // Rewrite markdown links: [label](path/to/oldSlug) → [label](path/to/newSlug)
170
- const mdLinkRe = new RegExp(`(\\[[^\\]]*\\]\\()([^)]*?)\\b${escaped}\\b([^)]*)\\)`, "g");
171
- // Rewrite wikilinks: [[oldSlug]] → [[newSlug]] (including anchors and pipes)
172
- const wikilinkRe = new RegExp(`(\\[\\[)${escaped}((?:#[^|\\]\\n]*)?(?:\\|[^\\]\\n]*)?)(\\]\\])`, "g");
173
- // Rewrite bare refs: anchored to word-like boundaries (avoid URLs)
174
- const bareRefRe = new RegExp(`(?<=^|[\\s(,;])${escaped}(?=$|[\\s).,?!;:])`, "gm");
175
- return chunks.map((c) => {
176
- let rewritten = c.content;
177
- rewritten = rewritten.replace(mdLinkRe, `$1$2${newSlug}$3)`);
178
- rewritten = rewritten.replace(wikilinkRe, `$1${newSlug}$2$3`);
179
- rewritten = rewritten.replace(bareRefRe, newSlug);
180
- const changed = rewritten !== c.content;
181
- return { chunkId: c.chunkId, original: c.content, rewritten, changed };
182
- });
183
- }
184
- // ---------------------------------------------------------------------------
185
- // Circular rename guard
186
- // ---------------------------------------------------------------------------
187
- /**
188
- * Validate a sequence of renames for circular dependencies.
189
- * Returns an error string if a cycle is detected, null otherwise.
190
- *
191
- * A cycle exists when following rename chain A→B→C→A.
192
- */
193
- export function detectCircularRename(renames) {
194
- const edges = new Map();
195
- for (const r of renames) {
196
- edges.set(r.from, r.to);
197
- }
198
- for (const start of edges.keys()) {
199
- const visited = new Set();
200
- let cur = start;
201
- while (cur !== undefined) {
202
- if (visited.has(cur)) {
203
- return `Circular rename detected: ${Array.from(visited).join(" → ")} → ${cur}`;
204
- }
205
- visited.add(cur);
206
- cur = edges.get(cur);
207
- }
208
- }
209
- return null;
210
- }
@@ -1,52 +0,0 @@
1
- /**
2
- * T1 — stripCodeBlocks helper.
3
- *
4
- * Adapted from gbrain/src/core/link-extraction.ts (MIT, Garry Tan, https://github.com/garry-tan/gbrain).
5
- * Spec: specs/2026-05-18-L4-regex-first-extraction.md §6.1.
6
- *
7
- * Replaces fenced ``` blocks (with optional language tag) AND inline `code`
8
- * with whitespace of equivalent length. Preserving length keeps any downstream
9
- * offset/line maths stable across the strip — callers can run regexes over the
10
- * stripped buffer and report locations against the original text.
11
- */
12
- /** Match fenced code blocks (```...``` with optional info-string). DOTALL via [\s\S]. */
13
- const FENCE_RE = /```[^\n]*\n[\s\S]*?```/g;
14
- /** Match indented (4-space) code blocks at line start. Multi-line block. */
15
- const INDENTED_BLOCK_RE = /(^|\n)((?: [^\n]*(?:\n|$))+)/g;
16
- /** Match inline code: balanced single/double/triple backticks on one line. */
17
- const INLINE_CODE_RE = /(`{1,3})([^\n`]|`(?!`))+?\1/g;
18
- /**
19
- * Replace each match with same-length whitespace (newlines preserved verbatim
20
- * so line numbers don't shift).
21
- */
22
- function blankPreserveNewlines(input) {
23
- let out = "";
24
- for (let i = 0; i < input.length; i++) {
25
- const ch = input[i];
26
- out += ch === "\n" || ch === "\r" ? ch : " ";
27
- }
28
- return out;
29
- }
30
- /**
31
- * Strip fenced + inline + indented-4 code spans from markdown, returning a
32
- * length-preserved string safe for further regex matching.
33
- *
34
- * Order matters: fences first (so triple-backtick inline doesn't get clipped),
35
- * then inline backticks.
36
- */
37
- export function stripCodeBlocks(text) {
38
- let hadFences = false;
39
- let out = text.replace(FENCE_RE, (m) => {
40
- hadFences = true;
41
- return blankPreserveNewlines(m);
42
- });
43
- out = out.replace(INDENTED_BLOCK_RE, (full, prefix, body) => {
44
- hadFences = true;
45
- return prefix + blankPreserveNewlines(body);
46
- });
47
- out = out.replace(INLINE_CODE_RE, (m) => {
48
- hadFences = true;
49
- return blankPreserveNewlines(m);
50
- });
51
- return { stripped: out, hadFences };
52
- }
@@ -1,25 +0,0 @@
1
- /**
2
- * L4 regex-extract — shared types.
3
- *
4
- * Cross-ref: specs/2026-05-18-L4-regex-first-extraction.md §4-§7.
5
- */
6
- /** Whitelist of recognized entity types (DIR_PATTERN sources). */
7
- export const NOX_ENTITY_TYPES = [
8
- "feedback",
9
- "person",
10
- "lesson",
11
- "decision",
12
- "project",
13
- "team",
14
- "daily",
15
- "pending",
16
- "graph_node",
17
- "agent",
18
- "incident",
19
- "spec",
20
- "audit",
21
- "skill",
22
- "persona",
23
- "reference",
24
- "entities", // top-level dir prefix in vault paths
25
- ];
@@ -1,327 +0,0 @@
1
- // D01 — Cross-encoder Reranker (shadow)
2
- // 2026-05-07 impl. Spec: specs/2026-05-07-D01-cross-encoder-reranker.md (memoria-nox)
3
- //
4
- // Adiciona camada de cross-encoder pós-RRF ao hybrid pipeline. BGE-reranker-base
5
- // via @xenova/transformers (ONNX in Node, ~85MB on disk). Default off; shadow
6
- // computa lift sem mutar resultados; active substitui ranking pelo reranker.
7
- //
8
- // Modes (env NOX_RERANKER_MODE):
9
- // off — disabled (default), no compute, no apply
10
- // shadow — rerank executa, telemetria, ranking final = original (não muta)
11
- // active — rerank substitui ranking final
12
- //
13
- // Fail-open: model load falha, ONNX timeout, exception qualquer → log + retorna
14
- // candidates originais (off-mode efetivo). Zero crash exposto ao caller.
15
- //
16
- // Telemetria computada mesmo em shadow:
17
- // - position_changes: chunks que mudaram posição entre orig top-K e rerank top-K
18
- // - lift_score: |sum(orig_pos − new_pos)| / K_OUT, normalizado [0,1]
19
- //
20
- // Cache do modelo: default em node_modules/@xenova/transformers/.cache/
21
- // Override via env TRANSFORMERS_CACHE (recomendado prod: /var/cache/nox-mem-models/).
22
- // ─── Defaults ────────────────────────────────────────────────────────────────
23
- export const DEFAULT_TOP_K_IN = 50;
24
- export const DEFAULT_TOP_K_OUT = 10;
25
- export const DEFAULT_MODEL = "Xenova/bge-reranker-base";
26
- export const DEFAULT_TIMEOUT_MS = 2000;
27
- // ─── Env config ──────────────────────────────────────────────────────────────
28
- export function getMode() {
29
- const v = (process.env.NOX_RERANKER_MODE || "off").toLowerCase();
30
- if (v === "off" || v === "shadow" || v === "active")
31
- return v;
32
- return "off";
33
- }
34
- export function getTopKIn() {
35
- const raw = process.env.NOX_RERANKER_TOP_K_IN;
36
- if (!raw)
37
- return DEFAULT_TOP_K_IN;
38
- const n = parseInt(raw, 10);
39
- if (!Number.isFinite(n) || n <= 0)
40
- return DEFAULT_TOP_K_IN;
41
- return n;
42
- }
43
- export function getTopKOut() {
44
- const raw = process.env.NOX_RERANKER_TOP_K_OUT;
45
- if (!raw)
46
- return DEFAULT_TOP_K_OUT;
47
- const n = parseInt(raw, 10);
48
- if (!Number.isFinite(n) || n <= 0)
49
- return DEFAULT_TOP_K_OUT;
50
- return n;
51
- }
52
- export function getModelName() {
53
- return process.env.NOX_RERANKER_MODEL || DEFAULT_MODEL;
54
- }
55
- export function getTimeoutMs() {
56
- const raw = process.env.NOX_RERANKER_TIMEOUT_MS;
57
- if (!raw)
58
- return DEFAULT_TIMEOUT_MS;
59
- const n = parseInt(raw, 10);
60
- if (!Number.isFinite(n) || n < 100)
61
- return DEFAULT_TIMEOUT_MS;
62
- return n;
63
- }
64
- let cachedFn = null;
65
- let cachedModelName = null;
66
- let cachedFactoryError = null;
67
- /**
68
- * Test hook: injetar uma fn mock pra evitar download do modelo.
69
- * Em produção, NÃO chamar — `rerank()` carrega lazy via @xenova/transformers.
70
- *
71
- * Quando fn=null + reset=true (default), limpa singleton + cached error.
72
- * Use reset=false só pra cenários onde você quer preservar erro cacheado.
73
- */
74
- export function __setRerankerFnForTesting(fn, reset = true) {
75
- cachedFn = fn;
76
- if (reset || fn !== null) {
77
- cachedFactoryError = null;
78
- }
79
- cachedModelName = fn ? "__test__" : null;
80
- }
81
- /**
82
- * Lazy-load do modelo. First call paga ~2-4s de cold start (ONNX bind).
83
- * Subsequent calls reusam singleton. Fail-open: se carga falha, cacheia error
84
- * pra evitar retry-storm.
85
- */
86
- async function getRerankerFn() {
87
- const wantedModel = getModelName();
88
- // Test injection bypass: __test__ marker overrides model match check.
89
- if (cachedFn && (cachedModelName === "__test__" || cachedModelName === wantedModel))
90
- return cachedFn;
91
- if (cachedFactoryError)
92
- throw cachedFactoryError;
93
- try {
94
- // Dynamic import: Node ESM, evita carga em paths off-mode.
95
- // Specifier held in a variable so tsc does not require the optional
96
- // dependency at build time; a clone without it still type-checks.
97
- const xenovaSpecifier = "@xenova/transformers";
98
- const t = await import(xenovaSpecifier);
99
- // BGE-reranker-base é cross-encoder. xenova text-classification pipeline NÃO
100
- // suporta text_pair (passa pares como string única → tokenizer ignora pair).
101
- // Usar API low-level: AutoTokenizer + AutoModelForSequenceClassification com
102
- // tokenize batch de pares (queries + docs) → logits.
103
- // Quantized=true reduz disk de ~430MB → ~85MB sem perda significativa.
104
- const tokenizer = await t.AutoTokenizer.from_pretrained(wantedModel);
105
- const model = await t.AutoModelForSequenceClassification.from_pretrained(wantedModel, {
106
- quantized: true,
107
- });
108
- const fn = async (pairs) => {
109
- if (pairs.length === 0)
110
- return [];
111
- const queries = pairs.map((p) => p.text);
112
- const docs = pairs.map((p) => p.text_pair);
113
- const encoded = await tokenizer(queries, {
114
- text_pair: docs,
115
- padding: true,
116
- truncation: true,
117
- });
118
- const out = await model(encoded);
119
- // out.logits.dims = [batch, 1]; data = Float32Array
120
- const data = Array.from(out.logits.data);
121
- // Sigmoid-like normalize não obrigatório (sort desc por logit funciona).
122
- // Mantemos raw logits — sort desc preserva ordem correta.
123
- return data.map((s) => ({ score: s }));
124
- };
125
- cachedFn = fn;
126
- cachedModelName = wantedModel;
127
- return fn;
128
- }
129
- catch (e) {
130
- cachedFactoryError = e instanceof Error ? e : new Error(String(e));
131
- throw cachedFactoryError;
132
- }
133
- }
134
- /**
135
- * Pre-warm o singleton do modelo. Chamado pelo nox-mem-api boot quando
136
- * NOX_RERANKER_MODE != off, pra evitar cold-start de ~12-90s no primeiro
137
- * search request (D01 spec §risks §1). Idempotente: subsequent calls são no-op.
138
- */
139
- export async function preloadModel() {
140
- await getRerankerFn();
141
- }
142
- // ─── Helpers: telemetry math (pure, testable) ────────────────────────────────
143
- /**
144
- * Conta chunks que mudaram posição entre os top-K original e o pós-rerank.
145
- * Trabalha por id (campo opcional). Chunks sem id são ignorados (não rastreáveis).
146
- */
147
- export function computePositionChanges(origTopK, newTopK) {
148
- const origPos = new Map();
149
- const newPos = new Map();
150
- origTopK.forEach((c, i) => {
151
- if (typeof c.id === "number")
152
- origPos.set(c.id, i);
153
- });
154
- newTopK.forEach((c, i) => {
155
- if (typeof c.id === "number")
156
- newPos.set(c.id, i);
157
- });
158
- const allIds = new Set([...origPos.keys(), ...newPos.keys()]);
159
- let changes = 0;
160
- for (const id of allIds) {
161
- const a = origPos.get(id);
162
- const b = newPos.get(id);
163
- if (a === undefined || b === undefined) {
164
- // chunk entrou ou saiu do top-K → mudança
165
- changes++;
166
- }
167
- else if (a !== b) {
168
- changes++;
169
- }
170
- }
171
- return changes;
172
- }
173
- /**
174
- * Lift score: mean displacement normalizado em [0, 1].
175
- *
176
- * Combina dois sinais:
177
- * 1) displacement intra-intersection: |orig_pos − new_pos| pra ids em ambos
178
- * 2) turnover (set churn): id que entrou OU saiu conta como displacement = K
179
- *
180
- * Total = sum(deltas) / (count * K), onde K = max(|orig|, |new|).
181
- *
182
- * Edge cases:
183
- * - sets disjoint → todos turnover, score = 1
184
- * - identical → 0
185
- * - swap top-2 (K=5) → 2 ids movem 1 cada → 2/(5*4) = 0.1
186
- */
187
- export function computeLiftScore(origTopK, newTopK) {
188
- if (origTopK.length === 0 || newTopK.length === 0)
189
- return 0;
190
- const k = Math.max(origTopK.length, newTopK.length);
191
- if (k <= 1)
192
- return 0;
193
- const origPos = new Map();
194
- const newPos = new Map();
195
- origTopK.forEach((c, i) => {
196
- if (typeof c.id === "number")
197
- origPos.set(c.id, i);
198
- });
199
- newTopK.forEach((c, i) => {
200
- if (typeof c.id === "number")
201
- newPos.set(c.id, i);
202
- });
203
- const allIds = new Set([...origPos.keys(), ...newPos.keys()]);
204
- if (allIds.size === 0)
205
- return 0;
206
- let sumDelta = 0;
207
- for (const id of allIds) {
208
- const a = origPos.get(id);
209
- const b = newPos.get(id);
210
- if (a === undefined || b === undefined) {
211
- // turnover: id entrou ou saiu → trata como displacement máximo (k)
212
- sumDelta += k;
213
- }
214
- else {
215
- sumDelta += Math.abs(a - b);
216
- }
217
- }
218
- // Normalize: max possible = allIds.size * k (all turned over)
219
- const norm = sumDelta / (allIds.size * k);
220
- return Math.min(1, Math.max(0, norm));
221
- }
222
- // ─── Core rerank function ────────────────────────────────────────────────────
223
- /**
224
- * Rerank candidates via cross-encoder. Comportamento per mode:
225
- *
226
- * - off: no-op, retorna candidates.slice(0, topK), summary mode='off'
227
- * - shadow: roda reranker, calcula lift, retorna candidates ORIGINAIS top-K
228
- * (não muta ranking — caller recebe ordem pre-rerank)
229
- * - active: roda reranker, retorna pós-rerank top-K (muta ranking)
230
- *
231
- * Fail-open: qualquer erro (model load, timeout, ONNX crash) → retorna
232
- * candidates.slice(0, topK) original com summary.failed=true. Não joga.
233
- */
234
- export async function rerank(query, candidates, topKOut) {
235
- const mode = getMode();
236
- const kIn = getTopKIn();
237
- const kOut = topKOut ?? getTopKOut();
238
- const t0 = Date.now();
239
- const summaryBase = (overrides = {}) => ({
240
- mode,
241
- topKIn: 0,
242
- topKOut: 0,
243
- latencyMs: 0,
244
- positionChanges: 0,
245
- liftScore: 0,
246
- failed: false,
247
- ...overrides,
248
- });
249
- // off-mode: bypass total
250
- if (mode === "off") {
251
- return {
252
- results: candidates.slice(0, kOut),
253
- summary: summaryBase({ topKOut: Math.min(candidates.length, kOut) }),
254
- };
255
- }
256
- // empty / single candidate: nothing to rerank
257
- if (candidates.length <= 1 || !query || query.trim().length === 0) {
258
- return {
259
- results: candidates.slice(0, kOut),
260
- summary: summaryBase({ topKOut: Math.min(candidates.length, kOut), latencyMs: Date.now() - t0 }),
261
- };
262
- }
263
- const slice = candidates.slice(0, kIn);
264
- const origTopK = candidates.slice(0, kOut);
265
- let scored;
266
- try {
267
- const fn = await getRerankerFn();
268
- const pairs = slice.map((c) => ({
269
- text: query,
270
- text_pair: (c.chunk_text || "").slice(0, 4000), // safety truncate (model max 512 tokens)
271
- }));
272
- const timeoutMs = getTimeoutMs();
273
- // Race contra timeout
274
- const rerankPromise = fn(pairs);
275
- const timer = new Promise((_, reject) => setTimeout(() => reject(new Error(`reranker timeout after ${timeoutMs}ms`)), timeoutMs));
276
- const scores = await Promise.race([rerankPromise, timer]);
277
- if (!Array.isArray(scores) || scores.length !== slice.length) {
278
- throw new Error(`reranker returned ${Array.isArray(scores) ? scores.length : "non-array"} scores for ${slice.length} pairs`);
279
- }
280
- scored = slice.map((c, i) => ({ candidate: c, score: scores[i].score }));
281
- }
282
- catch (e) {
283
- const msg = e?.message || String(e);
284
- if (process.env.NOX_RERANKER_LOG === "1") {
285
- logRerank(query, mode, kIn, kOut, Date.now() - t0, 0, 0, true, msg);
286
- }
287
- return {
288
- results: origTopK,
289
- summary: summaryBase({
290
- topKIn: slice.length,
291
- topKOut: origTopK.length,
292
- latencyMs: Date.now() - t0,
293
- failed: true,
294
- failureReason: msg.slice(0, 200),
295
- }),
296
- };
297
- }
298
- // Sort by reranker score desc
299
- scored.sort((a, b) => b.score - a.score);
300
- const newTopK = scored.slice(0, kOut).map((s) => s.candidate);
301
- const positionChanges = computePositionChanges(origTopK, newTopK);
302
- const liftScore = computeLiftScore(origTopK, newTopK);
303
- const latencyMs = Date.now() - t0;
304
- if (process.env.NOX_RERANKER_LOG === "1") {
305
- logRerank(query, mode, kIn, kOut, latencyMs, positionChanges, liftScore, false);
306
- }
307
- const summary = summaryBase({
308
- topKIn: slice.length,
309
- topKOut: kOut,
310
- latencyMs,
311
- positionChanges,
312
- liftScore,
313
- failed: false,
314
- });
315
- // mode=shadow: NÃO muta resultado retornado (ranking original)
316
- // mode=active: substitui pelo rerank
317
- return {
318
- results: mode === "active" ? newTopK : origTopK,
319
- summary,
320
- };
321
- }
322
- function logRerank(query, mode, kIn, kOut, latencyMs, positionChanges, liftScore, failed, failureReason) {
323
- const safeQuery = (query || "").replace(/[\r\n"]/g, " ").slice(0, 80);
324
- const tag = mode === "active" ? "rerank-active" : mode === "shadow" ? "rerank-shadow" : "rerank-off";
325
- const status = failed ? `FAILED reason="${(failureReason || "").slice(0, 120)}"` : "ok";
326
- console.error(`[${tag}] query="${safeQuery}" kIn=${kIn} kOut=${kOut} lat=${latencyMs}ms changes=${positionChanges} lift=${liftScore.toFixed(3)} ${status}`);
327
- }