nox-mem 3.9.1 → 3.10.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/api-server.js +0 -14
- package/dist/index.js +13 -1
- package/dist/ingest-entity.js +3 -3
- package/dist/ingest.js +3 -3
- package/dist/lib/ingest-router.js +2 -3
- package/dist/lib/tombstone.js +6 -7
- package/dist/lib/workspace.js +36 -2
- package/dist/reindex.js +3 -3
- package/dist/retention.js +1 -0
- package/dist/session-distill.js +7 -2
- package/dist/watch.js +4 -4
- package/package.json +2 -3
- package/dist/lib/regex-extract/extractor.js +0 -91
- package/dist/lib/regex-extract/frontmatter.js +0 -169
- package/dist/lib/regex-extract/index.js +0 -14
- package/dist/lib/regex-extract/ingest-router-l4.js +0 -102
- package/dist/lib/regex-extract/patterns.js +0 -91
- package/dist/lib/regex-extract/production-wire.js +0 -202
- package/dist/lib/regex-extract/reconcile.js +0 -210
- package/dist/lib/regex-extract/strip-code.js +0 -52
- package/dist/lib/regex-extract/types.js +0 -25
- package/dist/lib/reranker.js +0 -327
|
@@ -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
|
-
];
|