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.
@@ -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();
@@ -22,14 +22,14 @@
22
22
  //
23
23
  // Each file produces N+2 chunks: 1 frontmatter + 1 compiled + N timeline entries.
24
24
  import { existsSync, readFileSync } from "fs";
25
- import { relative, resolve } from "path";
25
+ import { resolve } from "path";
26
26
  import { getDb } from "./db.js";
27
27
  import { syncFileChunks } from "./lib/chunk-sync.js";
28
28
  import { getInitialTier } from "./tier-manager.js";
29
29
  import { resolveRetention } from "./retention.js";
30
30
  import { inferPain, inferImportance } from "./salience.js";
31
31
  import { redact as _redactPrivacy } from "./privacy/filter.js";
32
- import { workspaceRoot } from "./lib/workspace.js";
32
+ import { workspaceRoot, sourceKeyFor } from "./lib/workspace.js";
33
33
  const WORKSPACE = workspaceRoot();
34
34
  /**
35
35
  * Section boost values by section type. Multiplicative in search ranking but
@@ -122,7 +122,7 @@ function parseSimpleYaml(raw) {
122
122
  * `compiled == frontmatter` invariant (CLAUDE.md rule 6) holds per file.
123
123
  */
124
124
  export function ingestEntitySync(db, filePath) {
125
- const relPath = relative(WORKSPACE, filePath);
125
+ const relPath = sourceKeyFor(filePath, WORKSPACE);
126
126
  const content = readFileSync(filePath, "utf-8");
127
127
  const entity = parseEntityFile(content);
128
128
  if (!entity) {
package/dist/ingest.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from "fs";
2
- import { relative, resolve } from "path";
2
+ import { resolve } from "path";
3
3
  import { getDb } from "./db.js";
4
4
  import { syncFileChunks } from "./lib/chunk-sync.js";
5
5
  import { ensureTombstoneTable, resolveTombstoneOnIngest } from "./lib/tombstone.js";
@@ -7,7 +7,7 @@ import { getInitialTier, getInitialImportance } from "./tier-manager.js";
7
7
  import { resolveRetention } from "./retention.js";
8
8
  import { inferPain, inferImportance } from "./salience.js";
9
9
  import { redact } from "./privacy/filter.js";
10
- import { workspaceRoot } from "./lib/workspace.js";
10
+ import { workspaceRoot, sourceKeyFor } from "./lib/workspace.js";
11
11
  const WORKSPACE = workspaceRoot();
12
12
  const TYPE_MAP = {
13
13
  "memory/decisions.md": "decision",
@@ -180,7 +180,7 @@ const EMPTY = { chunks: 0, inserted: [], kept: 0, deleted: 0, adopted: 0 };
180
180
  * disk again, so a tombstone left when it was deleted is resolved (2026-10-15).
181
181
  */
182
182
  export function ingestMarkdownSync(db, filePath) {
183
- const relPath = relative(WORKSPACE, filePath);
183
+ const relPath = sourceKeyFor(filePath, WORKSPACE);
184
184
  // A2 (2026-04-25): entity routing lives in lib/ingest-router.ts — single dispatch.
185
185
  let content = readFileSync(filePath, "utf-8");
186
186
  if (!content.trim()) {
@@ -8,10 +8,9 @@
8
8
  //
9
9
  // Defesa em camadas: ingestFile() ainda tem guard interno pra entity files (caso
10
10
  // algum legacy caller pule o router). Mas o router é o caminho canônico daqui em diante.
11
- import { relative } from "node:path";
12
11
  import { ingestFile, ingestMarkdownSync } from "../ingest.js";
13
12
  import { ingestEntityFile, ingestEntitySync } from "../ingest-entity.js";
14
- import { workspaceRoot } from "./workspace.js";
13
+ import { workspaceRoot, sourceKeyFor } from "./workspace.js";
15
14
  const WORKSPACE = workspaceRoot();
16
15
  const diffOf = (r) => ({
17
16
  inserted: r.inserted, kept: r.kept, deleted: r.deleted, adopted: r.adopted,
@@ -21,7 +20,7 @@ const diffOf = (r) => ({
21
20
  * arquivo quando adicionar novo tipo (ex: "pdf-text-layer", "fathom-transcript").
22
21
  */
23
22
  export function detectIngestKind(filePath) {
24
- const relPath = relative(WORKSPACE, filePath);
23
+ const relPath = sourceKeyFor(filePath, WORKSPACE);
25
24
  if (relPath.startsWith("memory/entities/") && filePath.endsWith(".md"))
26
25
  return "entity";
27
26
  if (relPath.startsWith("graphify-out/") || relPath.includes("/graphify-out/"))
@@ -23,19 +23,18 @@
23
23
  // The table is created lazily (like ensureVecTable) instead of by a schema
24
24
  // bump: the npm and production lineages number their schema versions
25
25
  // differently, and a CREATE TABLE IF NOT EXISTS lands the same on both.
26
- import { relative, resolve } from "path";
27
- import { workspaceRoot } from "./workspace.js";
26
+ import { sourceKeyFor } from "./workspace.js";
28
27
  /**
29
- * The `source_file` key ingest writes for `path`: `relative(WORKSPACE, filePath)`
30
- * in ingest.ts and ingest-router.ts, where `relative()` resolves a relative
31
- * argument against the cwd. Every command that names a file by path has to land
32
- * on this same key, or it silently misses the chunks.
28
+ * The `source_file` key ingest writes for `path` (`sourceKeyFor` in workspace.ts,
29
+ * the one definition ingest, the router, the entity ingest, watch and reindex
30
+ * use); a relative argument resolves against the cwd. Every command that names
31
+ * a file by path has to land on this same key, or it silently misses the chunks.
33
32
  *
34
33
  * On a standalone install nothing lives under the default workspace, so keys
35
34
  * start with `../`; that is the key, not an error.
36
35
  */
37
36
  export function sourceKey(path) {
38
- return relative(workspaceRoot(), resolve(path));
37
+ return sourceKeyFor(path);
39
38
  }
40
39
  /**
41
40
  * What a CLI argument names: either a key exactly as `nox-mem tombstones` lists
@@ -17,9 +17,9 @@
17
17
  * watched nothing and `reindex` refused. Schema v20 rewrites those keys
18
18
  * (`migrateStandaloneKeys` in db.ts).
19
19
  */
20
- import { existsSync } from "fs";
20
+ import { existsSync, realpathSync } from "fs";
21
21
  import { homedir } from "os";
22
- import { join } from "path";
22
+ import { basename, dirname, join, relative, resolve } from "path";
23
23
  export const ORIGIN_WORKSPACE = "/root/.openclaw/workspace";
24
24
  export function standaloneWorkspace() {
25
25
  return join(homedir(), ".nox-mem");
@@ -34,3 +34,37 @@ export function workspaceRootWithSource(env = process.env, exists = existsSync)
34
34
  export function workspaceRoot() {
35
35
  return workspaceRootWithSource().root;
36
36
  }
37
+ /**
38
+ * `path` with every symlink resolved, also when the file itself no longer exists
39
+ * (a deleted note still has to land on the key it was stored under): the deepest
40
+ * existing ancestor is resolved and the missing tail is appended as written.
41
+ */
42
+ export function canonicalPath(path) {
43
+ const abs = resolve(path);
44
+ const tail = [];
45
+ let head = abs;
46
+ for (;;) {
47
+ try {
48
+ const real = realpathSync(head);
49
+ return tail.length ? join(real, ...tail.reverse()) : real;
50
+ }
51
+ catch {
52
+ const parent = dirname(head);
53
+ if (parent === head)
54
+ return abs;
55
+ tail.push(basename(head));
56
+ head = parent;
57
+ }
58
+ }
59
+ }
60
+ /**
61
+ * The `source_file` key for `path`, relative to the workspace root. Both sides
62
+ * go through `canonicalPath`, so a file reached through a symlink gets the same
63
+ * key as the file reached directly. Until 3.10.1 the key was `relative()` of
64
+ * the path as given: on the origin VPS `/root/.openclaw/agents/<a>` is a symlink
65
+ * to `<workspace>/agents/<a>`, and a job that ingested through the link stored
66
+ * the same note a second time under `../agents/<a>/…` (83 sources, 2026-11-11).
67
+ */
68
+ export function sourceKeyFor(path, root = workspaceRoot()) {
69
+ return relative(canonicalPath(root), canonicalPath(path));
70
+ }
package/dist/reindex.js CHANGED
@@ -39,9 +39,9 @@ import { routeIngestSync } from "./lib/ingest-router.js";
39
39
  import { ensureTombstoneTable, tombstoneFile } from "./lib/tombstone.js";
40
40
  import { existsSync, readdirSync } from "fs";
41
41
  import { createHash } from "crypto";
42
- import { join, relative, resolve } from "path";
42
+ import { join, resolve } from "path";
43
43
  import { ReindexWipeDetectedError, ReindexSourceMissingError, ReindexWorkspaceMismatchError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
44
- import { workspaceRoot, workspaceRootWithSource } from "./lib/workspace.js";
44
+ import { workspaceRoot, workspaceRootWithSource, sourceKeyFor } from "./lib/workspace.js";
45
45
  import { DEFAULT_STANDALONE_DB_PATH } from "./lib/db-path.js";
46
46
  export { ReindexWipeDetectedError, ReindexSourceMissingError, ReindexWorkspaceMismatchError } from "./reindex-errors.js";
47
47
  const WORKSPACE = workspaceRoot();
@@ -164,7 +164,7 @@ async function _reindexImpl() {
164
164
  // Same scan as assertReindexSource — one definition of "the source".
165
165
  const { memoryFiles, sharedFiles } = collectReindexFiles();
166
166
  const allFiles = [...memoryFiles, ...sharedFiles];
167
- const roots = reindexRoots().map((r) => relative(WORKSPACE, r) + "/");
167
+ const roots = reindexRoots().map((r) => sourceKeyFor(r, WORKSPACE) + "/");
168
168
  const fileErrors = [];
169
169
  const t = { chunks: 0, kept: 0, inserted: 0, deleted: 0, adopted: 0, tombstoned: 0 };
170
170
  let retainedDistinct = preDistinct;
package/dist/retention.js CHANGED
@@ -24,6 +24,7 @@ export const RETENTION_BY_TYPE = {
24
24
  digest: 180, // digest consolida várias sessões
25
25
  pending: 30, // se 30d sem resolver, escala pra review
26
26
  graph_node: 60, // repos externos indexados via graphify — research-like, decay rápido
27
+ distilled: null, // never — escolha explícita (DECISIONS 27/10 #3); session-distill grava NULL
27
28
  other: 90, // default
28
29
  };
29
30
  export const DEFAULT_RETENTION_DAYS = 90;
@@ -348,9 +348,14 @@ export async function distillSessions(options = {}) {
348
348
  const chunkType = "distilled";
349
349
  const tier = memory.importance >= 0.8 ? "working" : "peripheral";
350
350
  const today = new Date().toISOString().split("T")[0];
351
+ // retention_days = NULL is a choice, not an omission: distilled memory never decays
352
+ // (salience reads NULL as never-decay, so recency stays 1.0). Measured 2026-10-27 before
353
+ // choosing: a 90-day window would move a distilled chunk's median salience by -0.082 and
354
+ // archive nothing, which does not justify moving the served ranking. Listed explicitly so
355
+ // that no backfill or default can turn it into 90 days by accident (DECISIONS 27/10 #3).
351
356
  db.prepare(`
352
- INSERT INTO chunks (source_file, chunk_text, chunk_type, source_date, metadata, tier, importance)
353
- VALUES (?, ?, ?, ?, ?, ?, ?)
357
+ INSERT INTO chunks (source_file, chunk_text, chunk_type, source_date, metadata, tier, importance, retention_days)
358
+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
354
359
  `).run(`sessions/${agentId}/${sessionKey}`, `[${memory.category}|${agentId}] ${memory.text}`, chunkType, today, JSON.stringify({ category: memory.category, source_agent: agentId, session: sessionKey }), tier, memory.importance);
355
360
  stats.memoriesIngested++;
356
361
  sessionExtracted++;
package/dist/watch.js CHANGED
@@ -8,11 +8,11 @@
8
8
  * Skips: binary files, .db, .json session files, tmp files.
9
9
  */
10
10
  import { watch, statSync, existsSync, readdirSync } from "fs";
11
- import { resolve, extname, relative } from "path";
11
+ import { resolve, extname } from "path";
12
12
  import { routeIngest } from "./lib/ingest-router.js";
13
13
  import { getDb } from "./db.js";
14
14
  import { tombstoneFile, tombstonePrefix } from "./lib/tombstone.js";
15
- import { workspaceRoot } from "./lib/workspace.js";
15
+ import { workspaceRoot, sourceKeyFor } from "./lib/workspace.js";
16
16
  const WORKSPACE = workspaceRoot();
17
17
  // NOX_WATCH_DIRS: comma-separated list of ABSOLUTE paths to watch.
18
18
  // If unset, falls back to the default OpenClaw workspace layout below.
@@ -66,7 +66,7 @@ function shouldProcess(filepath) {
66
66
  const debounceMap = new Map();
67
67
  const DEBOUNCE_MS = 2000;
68
68
  function tombstoneMissing(filepath) {
69
- const rel = relative(WORKSPACE, filepath);
69
+ const rel = sourceKeyFor(filepath, WORKSPACE);
70
70
  if (rel.startsWith(".."))
71
71
  return; // NOX_WATCH_DIRS outside the workspace: no source_file to match
72
72
  try {
@@ -137,7 +137,7 @@ function debounceTombstoneDir(dirpath) {
137
137
  debounceMap.delete(key);
138
138
  if (existsSync(dirpath))
139
139
  return;
140
- const rel = relative(WORKSPACE, dirpath);
140
+ const rel = sourceKeyFor(dirpath, WORKSPACE);
141
141
  if (rel.startsWith("..") || rel === "")
142
142
  return;
143
143
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.9.1",
3
+ "version": "3.10.1",
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";