nox-mem 3.9.0 → 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.
package/README.md CHANGED
@@ -84,8 +84,8 @@ nox-mem stats
84
84
  |---|---|---|
85
85
  | `NOX_DB_PATH` | `~/.nox-mem/nox.db` | SQLite database path. A missing parent directory is created (mode 0700). Its directory is auto-added to the op-audit allowlist. |
86
86
  | `NOX_MEM_DIR` | — | **Not** the notes folder: nothing ingests or watches it. It only sets where pre-op snapshots go (`$NOX_MEM_DIR/.nox-snapshots`) and widens the op-audit allowlist. |
87
- | `NOX_MEM_SCOPE` | unset | One sentence naming what the memory covers; the MCP server puts it in its `instructions` so the agent knows when a search can help. Recommended, see [Key commands](#key-commands). Collapsed to one line, capped at 800 characters. |
88
- | `NOX_MEM_INSTRUCTIONS` | on | `off` makes the MCP server send no `instructions`. |
87
+ | `NOX_MEM_SCOPE` | unset | One sentence naming what the memory covers; the MCP server puts it in its `instructions` so the agent knows when a search can help. Without it the server sends no `instructions` (3.9.1+). Recommended, see [Key commands](#key-commands). Collapsed to one line, capped at 800 characters. |
88
+ | `NOX_MEM_INSTRUCTIONS` | unset | `off` sends no `instructions` even with a scope; `unscoped` sends the generic text when `NOX_MEM_SCOPE` is unset (it searches on unrelated changes too). Unset: instructions only when `NOX_MEM_SCOPE` is set. |
89
89
  | `NOX_ALLOW_PROD_INGEST` | — | `1` skips the large-database ingest guard (same as `--allow-prod`). See [Large databases](#large-databases-the-ingest-guard). |
90
90
 
91
91
  ### API server
@@ -270,9 +270,11 @@ answered 7% of them right. The server now sends MCP `instructions` (the one serv
270
270
  clients keep in context before the agent picks a tool) saying when to search. With a one-sentence
271
271
  scope in `NOX_MEM_SCOPE`, the same tasks were answered right 53% of the time, and the agent
272
272
  searched on 2% of control tasks that the memory could not help with. Without a scope the server
273
- sends a generic version: about as accurate (56%), but it also searched on a third of unrelated
274
- configuration changes. So set the scope: name the projects or systems your memory holds, in one
275
- sentence, as you would to a new colleague. `NOX_MEM_INSTRUCTIONS=off` sends no instructions.
273
+ sends no instructions (since 3.9.1): a generic version was about as accurate (56%), but it also
274
+ searched on a third of unrelated configuration changes, so it is only sent if you ask for it with
275
+ `NOX_MEM_INSTRUCTIONS=unscoped`. So set the scope: name the projects or systems your memory holds,
276
+ in one sentence, as you would to a new colleague. `NOX_MEM_INSTRUCTIONS=off` sends no instructions
277
+ even with a scope.
276
278
  These numbers are from one model, one client and one corpus; the instructions did not make the
277
279
  agent record decisions (`nox_mem_decision_set`) any more often.
278
280
 
@@ -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();
@@ -14,6 +14,10 @@
14
14
  * - unscoped (NOX_MEM_SCOPE unset): pass rate 0.07 -> 0.56, +0.49 [0.35, 0.63], but it searched
15
15
  * on about one in three unrelated configuration changes (+31.7 pp).
16
16
  *
17
+ * Only the scoped text passed the evaluation's decision rule, so it is the only one sent by default:
18
+ * with no NOX_MEM_SCOPE the field is omitted (3.9.1; 3.9.0 sent the unscoped text). The unscoped
19
+ * text stays available on explicit request, NOX_MEM_INSTRUCTIONS=unscoped, with the cost above.
20
+ *
17
21
  * Edits to the wording are edits to a measured intervention: the tests pin both texts, and a
18
22
  * change should come with a new run.
19
23
  */
@@ -55,15 +59,20 @@ export function normaliseScope(raw) {
55
59
  return s;
56
60
  }
57
61
  /**
58
- * Build the `instructions` text. Returns undefined when disabled with NOX_MEM_INSTRUCTIONS=off,
59
- * so the caller can omit the field.
62
+ * Build the `instructions` text, or undefined so the caller omits the field:
63
+ * NOX_MEM_INSTRUCTIONS=off|0|false -> undefined, even with a scope
64
+ * NOX_MEM_SCOPE set -> scoped text (the one that passed)
65
+ * NOX_MEM_INSTRUCTIONS=unscoped -> unscoped text (searched on ~1 in 3 unrelated config changes)
66
+ * otherwise -> undefined
60
67
  */
61
68
  export function serverInstructions(env = process.env) {
62
69
  const mode = (env.NOX_MEM_INSTRUCTIONS || "").trim().toLowerCase();
63
70
  if (mode === "off" || mode === "0" || mode === "false")
64
71
  return undefined;
65
72
  const scope = normaliseScope(env.NOX_MEM_SCOPE);
66
- const intro = scope ? SCOPED_INTRO(scope) : UNSCOPED_INTRO;
67
- const when = scope ? SCOPED_WHEN : UNSCOPED_WHEN;
68
- return [intro, when, HOW, WRITE].join("\n\n");
73
+ if (scope)
74
+ return [SCOPED_INTRO(scope), SCOPED_WHEN, HOW, WRITE].join("\n\n");
75
+ if (mode === "unscoped")
76
+ return [UNSCOPED_INTRO, UNSCOPED_WHEN, HOW, WRITE].join("\n\n");
77
+ return undefined;
69
78
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.9.0",
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
- }