nox-mem 3.2.1 → 3.4.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.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * src/lib/dates.ts — flexible date parsing for the temporal search filter (P3).
3
+ *
4
+ * Accepted:
5
+ * ISO 8601 date: "2026-05-01" (start of day UTC; end of day for as-of)
6
+ * ISO 8601 full: "2026-05-01T12:00:00Z" (no offset ⇒ UTC)
7
+ * Relative: "15m" | "2h" | "7d" | "1w" (that long before `nowMs`)
8
+ *
9
+ * "1mo" is deliberately unsupported (months have no fixed length) — use "30d".
10
+ * Throws TemporalParseError on anything else, so surfaces can answer 400 / exit 2
11
+ * instead of silently searching without the filter.
12
+ */
13
+ export class TemporalParseError extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "TemporalParseError";
17
+ }
18
+ }
19
+ const RELATIVE_RE = /^(\d+)(m|h|d|w)$/i;
20
+ const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
21
+ // Requires at least YYYY-MM-DDTHH:MM so bare numbers or "May 1" are rejected
22
+ // (Date.parse accepts both, with locale-dependent results).
23
+ const ISO_FULL_RE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
24
+ const HAS_OFFSET_RE = /(Z|[+-]\d{2}:?\d{2})$/i;
25
+ const UNIT_MS = {
26
+ m: 60_000,
27
+ h: 3_600_000,
28
+ d: 86_400_000,
29
+ w: 604_800_000,
30
+ };
31
+ export function parseFlexibleDate(input, nowMs = Date.now(), opts = {}) {
32
+ const trimmed = String(input ?? "").trim();
33
+ if (!trimmed)
34
+ throw new TemporalParseError("temporal: empty date string");
35
+ const rel = RELATIVE_RE.exec(trimmed);
36
+ if (rel) {
37
+ const n = parseInt(rel[1], 10);
38
+ return new Date(nowMs - n * UNIT_MS[rel[2].toLowerCase()]);
39
+ }
40
+ let normalised = null;
41
+ if (DATE_ONLY_RE.test(trimmed)) {
42
+ // "as of 2026-01-10" reads as "by the end of that day"; "since 2026-01-10"
43
+ // as "from its start". Both in UTC.
44
+ normalised = opts.dateOnlyAs === "end" ? `${trimmed}T23:59:59.999Z` : `${trimmed}T00:00:00Z`;
45
+ }
46
+ else if (ISO_FULL_RE.test(trimmed)) {
47
+ // No offset ⇒ UTC, same as date-only (JS would otherwise read it as local time).
48
+ normalised = HAS_OFFSET_RE.test(trimmed) ? trimmed : `${trimmed}Z`;
49
+ }
50
+ const d = normalised ? new Date(normalised) : null;
51
+ if (!d || isNaN(d.getTime())) {
52
+ throw new TemporalParseError(`temporal: cannot parse date "${input}". ` +
53
+ `Accepted: ISO 8601 ("2026-05-01" or "2026-05-01T00:00:00Z") ` +
54
+ `or relative ("15m", "2h", "7d", "1w"). "1mo" is not supported — use "30d".`);
55
+ }
56
+ return d;
57
+ }
58
+ /** Parses the raw strings each surface receives; undefined/empty means "not set". */
59
+ export function parseTemporalFilter(raw, nowMs = Date.now()) {
60
+ const filter = {};
61
+ if (raw.asOf != null && String(raw.asOf).trim() !== "") {
62
+ filter.asOf = parseFlexibleDate(raw.asOf, nowMs, { dateOnlyAs: "end" });
63
+ }
64
+ if (raw.changedSince != null && String(raw.changedSince).trim() !== "") {
65
+ filter.changedSince = parseFlexibleDate(raw.changedSince, nowMs);
66
+ }
67
+ return filter.asOf || filter.changedSince ? filter : undefined;
68
+ }
69
+ /**
70
+ * SQL fragment over the `chunks` alias `c` (semantics: docs/PRIMITIVES.md §3).
71
+ *
72
+ * asOf: created_at IS NULL (legacy rows count as "always existed")
73
+ * OR created_at <= asOf
74
+ * changedSince: updated_at > since OR created_at > since
75
+ *
76
+ * Both sides go through datetime(): the columns hold `datetime('now')` text
77
+ * ("YYYY-MM-DD HH:MM:SS") while the bound value is ISO ("...T...Z"), and a
78
+ * plain string comparison between the two formats is wrong (' ' < 'T').
79
+ * There is no soft-delete column in the schema, so no deleted_at leg.
80
+ *
81
+ * Returns null when the filter is empty so callers keep their exact SQL.
82
+ */
83
+ export function buildTemporalClause(filter) {
84
+ if (!filter || (!filter.asOf && !filter.changedSince))
85
+ return null;
86
+ const parts = [];
87
+ const params = [];
88
+ if (filter.asOf) {
89
+ parts.push("(c.created_at IS NULL OR datetime(c.created_at) <= datetime(?))");
90
+ params.push(filter.asOf.toISOString());
91
+ }
92
+ if (filter.changedSince) {
93
+ const ts = filter.changedSince.toISOString();
94
+ parts.push("(datetime(c.updated_at) > datetime(?) OR datetime(c.created_at) > datetime(?))");
95
+ params.push(ts, ts);
96
+ }
97
+ return { sql: parts.join(" AND "), params };
98
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * src/lib/db-path.ts — the ONE place the database path is resolved.
3
+ *
4
+ * db.ts (which opens the DB) and op-audit.ts (which snapshots it before a
5
+ * destructive op) used to resolve the path separately. With no env set they
6
+ * disagreed: db.ts fell back to `<package>/nox-mem.db` while op-audit assumed
7
+ * `/root/.openclaw/workspace/tools/nox-mem/nox-mem.db` — the snapshot protected
8
+ * a different file than the op mutated (same class as incident 2026-05-25).
9
+ *
10
+ * Priority:
11
+ * 1. NOX_DB_PATH explicit override
12
+ * 2. $OPENCLAW_WORKSPACE/tools/nox-mem/nox-mem.db origin deployments
13
+ * 3. <package root>/nox-mem.db, ONLY IF IT EXISTS legacy: keeps every existing
14
+ * install (the VPS tree, 3.3.0 users) on the file it already uses
15
+ * 4. ~/.nox-mem/nox.db new standalone default
16
+ *
17
+ * Step 4 replaces the old unconditional step 3: for `npm install -g`, the package
18
+ * root is inside node_modules, and `npm update -g` replaces that directory —
19
+ * taking the database with it.
20
+ */
21
+ import { existsSync } from "fs";
22
+ import { homedir } from "os";
23
+ import { dirname, join, resolve, sep } from "path";
24
+ import { fileURLToPath } from "url";
25
+ /** `<package root>` = parent of dist/ (compiled) or src/ (ts). */
26
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
27
+ export const LEGACY_DB_PATH = resolve(PACKAGE_ROOT, "nox-mem.db");
28
+ export const DEFAULT_STANDALONE_DB_PATH = join(homedir(), ".nox-mem", "nox.db");
29
+ export function resolveDbPathWithSource(env = process.env, exists = existsSync) {
30
+ if (env.NOX_DB_PATH)
31
+ return { path: resolve(env.NOX_DB_PATH), source: "NOX_DB_PATH" };
32
+ if (env.OPENCLAW_WORKSPACE) {
33
+ return { path: resolve(env.OPENCLAW_WORKSPACE, "tools", "nox-mem", "nox-mem.db"), source: "OPENCLAW_WORKSPACE" };
34
+ }
35
+ if (exists(LEGACY_DB_PATH))
36
+ return { path: LEGACY_DB_PATH, source: "legacy-package" };
37
+ return { path: DEFAULT_STANDALONE_DB_PATH, source: "standalone-default" };
38
+ }
39
+ export function resolveDbPath() {
40
+ return resolveDbPathWithSource().path;
41
+ }
42
+ /** True when the path sits inside a node_modules tree (wiped by npm update/uninstall). */
43
+ export function isInsideNodeModules(p) {
44
+ return resolve(p).split(sep).includes("node_modules");
45
+ }
@@ -47,7 +47,7 @@ import { existsSync, mkdirSync, renameSync, statSync, unlinkSync, chmodSync, rea
47
47
  import { join, resolve, dirname } from 'node:path';
48
48
  import { randomUUID } from 'node:crypto';
49
49
  import Database from 'better-sqlite3';
50
- import { getDb } from '../db.js';
50
+ import { getDb, DB_PATH as DB_OPENED_PATH } from '../db.js';
51
51
  // Standalone decoupling (2026-06-15): ALLOWED_PREFIXES + snapshot dir are now CONFIGURABLE
52
52
  // so a non-origin operator can run nox-mem outside /root/.openclaw without weakening the
53
53
  // path-validation guard. Origin VPS behavior is preserved exactly: when none of the new
@@ -97,6 +97,12 @@ function computeAllowedPrefixes() {
97
97
  if (ws && !resolve(ws).startsWith('/root/.openclaw')) {
98
98
  prefixes.add(normalizePrefix(join(resolve(ws), 'tools', 'nox-mem')));
99
99
  }
100
+ // No env at all: the DB is either the legacy <package>/nox-mem.db or the
101
+ // standalone default ~/.nox-mem/nox.db — neither is attacker-chosen, so allow
102
+ // its directory (same trust as dirname(NOX_DB_PATH) above).
103
+ if (!process.env.NOX_DB_PATH && !ws) {
104
+ prefixes.add(normalizePrefix(dirname(DB_OPENED_PATH)));
105
+ }
100
106
  return Array.from(prefixes);
101
107
  }
102
108
  const ALLOWED_PREFIXES = computeAllowedPrefixes();
@@ -112,11 +118,9 @@ function computeDefaultSnapshotDir() {
112
118
  }
113
119
  // Standalone: prefer NOX_MEM_DIR, else the active DB's own directory (always allowlisted —
114
120
  // it's dirname(NOX_DB_PATH) or the OPENCLAW_WORKSPACE-derived nox-mem dir), else cwd.
115
- const base = process.env.NOX_MEM_DIR
116
- ? resolve(process.env.NOX_MEM_DIR)
117
- : (process.env.NOX_DB_PATH || process.env.OPENCLAW_WORKSPACE)
118
- ? dirname(dbPath)
119
- : resolve(process.cwd());
121
+ // (cwd is no longer a fallback: the DB dir is always known and allowlisted, and
122
+ // a snapshot scattered into whatever directory the command ran from is lost.)
123
+ const base = process.env.NOX_MEM_DIR ? resolve(process.env.NOX_MEM_DIR) : dirname(dbPath);
120
124
  return join(base, '.nox-snapshots');
121
125
  }
122
126
  // P2 fix (2026-05-27, task #21) — DB_PATH agora respeita OPENCLAW_WORKSPACE como db.ts faz.
@@ -131,13 +135,16 @@ function computeDefaultSnapshotDir() {
131
135
  // 1. NOX_DB_PATH (explicit override — eval/test isolation)
132
136
  // 2. OPENCLAW_WORKSPACE-derived path (production agent workspaces)
133
137
  // 3. Hardcoded main DB (default last resort)
138
+ //
139
+ // 2026-09-28: resolution now lives in lib/db-path.ts and is shared with db.ts.
140
+ // The old step 3 here was the hardcoded main DB while db.ts fell back to
141
+ // <package>/nox-mem.db — with no env set the snapshot covered a different file
142
+ // than the op mutated. On the origin tree both paths are the same file, so the
143
+ // VPS resolves exactly as before.
134
144
  function resolveDbPath() {
135
- if (process.env.NOX_DB_PATH)
136
- return resolve(process.env.NOX_DB_PATH);
137
- const ws = process.env.OPENCLAW_WORKSPACE;
138
- if (ws)
139
- return resolve(ws, 'tools', 'nox-mem', 'nox-mem.db');
140
- return '/root/.openclaw/workspace/tools/nox-mem/nox-mem.db';
145
+ // The very value db.ts resolved and opens — not a second resolution, so a
146
+ // legacy file created/removed in between cannot split them (TOCTOU).
147
+ return DB_OPENED_PATH;
141
148
  }
142
149
  const DB_PATH = resolveDbPath();
143
150
  // W2-2 (audit cleanup 04-26): validate DB_PATH at module load — symetric trust w/ snapshot dir.
@@ -92,7 +92,10 @@ async function getRerankerFn() {
92
92
  throw cachedFactoryError;
93
93
  try {
94
94
  // Dynamic import: Node ESM, evita carga em paths off-mode.
95
- const t = await import("@xenova/transformers");
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);
96
99
  // BGE-reranker-base é cross-encoder. xenova text-classification pipeline NÃO
97
100
  // suporta text_pair (passa pares como string única → tokenizer ignora pair).
98
101
  // Usar API low-level: AutoTokenizer + AutoModelForSequenceClassification com
@@ -14,6 +14,7 @@ import { getStats } from "./stats.js";
14
14
  import { primer } from "./primer.js";
15
15
  import { createInterface } from "readline";
16
16
  import { VERSION } from "./version.js";
17
+ import { parseTemporalFilter } from "./lib/dates.js";
17
18
  const SERVER_INFO = {
18
19
  name: "nox-mem",
19
20
  version: VERSION,
@@ -27,6 +28,8 @@ const TOOLS = [
27
28
  properties: {
28
29
  query: { type: "string", description: "Search query (natural language or keywords)" },
29
30
  limit: { type: "number", description: "Max results (default 5, max 20)", default: 5 },
31
+ as_of: { type: "string", description: "Time-travel: only chunks that existed at this date (ISO 8601 like 2026-05-01, or relative like 7d, 2h, 1w)" },
32
+ changed_since: { type: "string", description: "Recency window: only chunks created or updated after this date (ISO 8601 or relative)" },
30
33
  },
31
34
  required: ["query"],
32
35
  },
@@ -230,7 +233,12 @@ async function handleRequest(req) {
230
233
  case "nox_mem_search": {
231
234
  const query = args.query;
232
235
  const limit = Math.min(Number(args.limit) || 5, 20);
233
- const results = await searchHybrid(query, limit);
236
+ // Parse errors throw and reach the client as isError — never an unfiltered search.
237
+ const filter = parseTemporalFilter({
238
+ asOf: args.as_of,
239
+ changedSince: args.changed_since,
240
+ });
241
+ const results = await searchHybrid(query, limit, true, filter);
234
242
  text = formatResults(results);
235
243
  break;
236
244
  }
@@ -19,3 +19,29 @@ export class ReindexWipeDetectedError extends Error {
19
19
  this.ratio = ratio;
20
20
  }
21
21
  }
22
+ /**
23
+ * Thrown BEFORE any mutation when the rebuild source cannot be what the caller
24
+ * thinks it is: no source directory exists, or the scan found no file while
25
+ * the DB holds chunks. Without this, a reindex on a machine without
26
+ * $OPENCLAW_WORKSPACE scanned nothing and then deleted every chunk as "orphan";
27
+ * the ratio guard only fired after the DELETE (2026-09-28).
28
+ */
29
+ export class ReindexSourceMissingError extends Error {
30
+ roots;
31
+ preCount;
32
+ reason;
33
+ constructor(roots, preCount, reason) {
34
+ super(`[reindex] REFUSED before touching the DB: ` +
35
+ (reason === "no-files"
36
+ ? `found 0 files under ${roots.join(", ")} while the DB holds ${preCount} chunks. `
37
+ : `no source directory exists (looked for ${roots.join(", ")}) while the DB holds ${preCount} chunks. `) +
38
+ `reindex rebuilds ONLY from $OPENCLAW_WORKSPACE/memory and $OPENCLAW_WORKSPACE/shared ` +
39
+ `(OPENCLAW_WORKSPACE=${process.env.OPENCLAW_WORKSPACE ?? "<unset>"}); running it now would delete every chunk. ` +
40
+ `Standalone installs that add notes with \`nox-mem ingest <file>\` do not need reindex. ` +
41
+ `Set NOX_REINDEX_ALLOW_WIPE=1 ONLY if emptying the DB is intended.`);
42
+ this.name = "ReindexSourceMissingError";
43
+ this.roots = roots;
44
+ this.preCount = preCount;
45
+ this.reason = reason;
46
+ }
47
+ }
package/dist/reindex.js CHANGED
@@ -36,11 +36,11 @@
36
36
  import { getDb } from "./db.js";
37
37
  import { withOpAudit } from "./lib/op-audit.js";
38
38
  import { routeIngest } from "./lib/ingest-router.js";
39
- import { readdirSync } from "fs";
39
+ import { existsSync, readdirSync } from "fs";
40
40
  import { createHash } from "crypto";
41
41
  import { join, resolve } from "path";
42
- import { ReindexWipeDetectedError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
43
- export { ReindexWipeDetectedError } from "./reindex-errors.js";
42
+ import { ReindexWipeDetectedError, ReindexSourceMissingError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
43
+ export { ReindexWipeDetectedError, ReindexSourceMissingError } from "./reindex-errors.js";
44
44
  const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
45
45
  // Layer 4: tunable safety thresholds (env-overridable for emergency operations).
46
46
  // MIN_RETENTION_RATIO imported from reindex-errors.ts (single source of truth).
@@ -64,6 +64,37 @@ function findFiles(dir, extensions) {
64
64
  }
65
65
  return results;
66
66
  }
67
+ /** The directories reindex rebuilds from, in scan order. */
68
+ export function reindexRoots() {
69
+ return [resolve(WORKSPACE, "memory"), resolve(WORKSPACE, "shared")];
70
+ }
71
+ function collectReindexFiles() {
72
+ const [memoryRoot, sharedRoot] = reindexRoots();
73
+ return {
74
+ memoryFiles: findFiles(memoryRoot, [".md", ".json"]),
75
+ sharedFiles: findFiles(sharedRoot, [".md"]),
76
+ };
77
+ }
78
+ /**
79
+ * Refuses (throws) when reindex has nothing trustworthy to rebuild from.
80
+ * Only fires in wipe conditions — a deployment whose workspace holds files
81
+ * passes untouched. Overridable with NOX_REINDEX_ALLOW_WIPE=1.
82
+ */
83
+ export function assertReindexSource(preCount) {
84
+ if (ALLOW_WIPE)
85
+ return;
86
+ const roots = reindexRoots();
87
+ const existing = roots.filter((r) => existsSync(r));
88
+ if (existing.length === 0) {
89
+ if (preCount > 0)
90
+ throw new ReindexSourceMissingError(roots, preCount, "no-source-dir");
91
+ return;
92
+ }
93
+ const { memoryFiles, sharedFiles } = collectReindexFiles();
94
+ const found = memoryFiles.length + sharedFiles.length;
95
+ if (found === 0 && preCount > 0)
96
+ throw new ReindexSourceMissingError(existing, preCount, "no-files");
97
+ }
67
98
  // Content-addressed fingerprint for UPSERT identity.
68
99
  // (source_file, sha256(chunk_text)) is stable across reindex runs as long as the
69
100
  // chunker output is deterministic for the same input file. The schema's autoincrement
@@ -103,6 +134,11 @@ async function _reindexImpl() {
103
134
  }
104
135
  // ── Phase 1: snapshot pre-state ────────────────────────────────────────────
105
136
  const preCount = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
137
+ // ── Phase 0 guard (read-only so far): the rebuild source must exist ────────
138
+ // Measured 2026-09-28 on a clean npm install: no $OPENCLAW_WORKSPACE ⇒ the scan
139
+ // found 0 files ⇒ every chunk became an "orphan" and was deleted; the ratio
140
+ // guard below then threw — after the DELETE. Refuse here, before any write.
141
+ assertReindexSource(preCount);
106
142
  // Tolerant select: schema may lack some columns on older DBs (pre-v10).
107
143
  // `SELECT *` would force coupling; instead probe column existence.
108
144
  const cols = new Set(db.prepare("PRAGMA table_info(chunks)").all().map((r) => r.name));
@@ -124,10 +160,35 @@ async function _reindexImpl() {
124
160
  ].join(", ");
125
161
  const oldChunks = db.prepare(`SELECT ${selectCols} FROM chunks`).all();
126
162
  // Build content fingerprint -> oldChunk index.
163
+ // One representative per content fingerprint. When the DB already holds
164
+ // duplicates (every reindex before 2026-09-28 doubled unchanged content), the
165
+ // kept representative is the one WITH an embedding, then the lowest id — the
166
+ // other copies become orphans and are removed, and dropping one without a
167
+ // vector must never cost the one that has it.
168
+ let embeddedIds = new Set();
169
+ try {
170
+ embeddedIds = new Set(db.prepare("SELECT chunk_id FROM vec_chunk_map").all().map((r) => r.chunk_id));
171
+ }
172
+ catch {
173
+ /* no vector map yet (fresh / keyless install) — every row is equal */
174
+ }
175
+ const better = (a, b) => {
176
+ const ae = embeddedIds.has(a.id), be = embeddedIds.has(b.id);
177
+ if (ae !== be)
178
+ return ae ? a : b;
179
+ return a.id <= b.id ? a : b;
180
+ };
127
181
  const oldByFingerprint = new Map();
128
182
  for (const row of oldChunks) {
129
- oldByFingerprint.set(chunkFingerprint(row.source_file, row.chunk_text), row);
183
+ const fp = chunkFingerprint(row.source_file, row.chunk_text);
184
+ const cur = oldByFingerprint.get(fp);
185
+ oldByFingerprint.set(fp, cur ? better(cur, row) : row);
130
186
  }
187
+ // Retention is measured on DISTINCT content, not rows: removing a redundant
188
+ // copy of content that is still present is not a loss. Measured on rows, a DB
189
+ // doubled by the old bug (2N → N) read as a 50% wipe and the cleanup reindex
190
+ // was refused forever.
191
+ const preDistinct = oldByFingerprint.size;
131
192
  console.log(`[reindex] Phase 1: snapshotted ${oldChunks.length} existing chunks`);
132
193
  // ── Phase 2: ingest new chunks into a staging set ──────────────────────────
133
194
  // Strategy: do NOT delete first. Let routeIngest INSERT new chunks alongside old ones.
@@ -136,8 +197,8 @@ async function _reindexImpl() {
136
197
  //
137
198
  // To distinguish "old" vs "new" rows we capture max(id) before any ingest.
138
199
  const maxIdBefore = db.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM chunks").get().m;
139
- const memoryFiles = findFiles(resolve(WORKSPACE, "memory"), [".md", ".json"]);
140
- const sharedFiles = findFiles(resolve(WORKSPACE, "shared"), [".md"]);
200
+ // Same scan as assertReindexSource — one definition of "the source".
201
+ const { memoryFiles, sharedFiles } = collectReindexFiles();
141
202
  const allFiles = [...memoryFiles, ...sharedFiles];
142
203
  let totalChunksIngested = 0;
143
204
  const fileErrors = [];
@@ -161,24 +222,28 @@ async function _reindexImpl() {
161
222
  const newChunks = db
162
223
  .prepare("SELECT id, source_file, chunk_text FROM chunks WHERE id > ?")
163
224
  .all(maxIdBefore);
164
- // For each new chunk, look up by fingerprint to inherit access metadata.
165
- const updateNewMetadata = db.prepare(`
166
- UPDATE chunks
167
- SET tier = COALESCE(?, tier),
168
- access_count = COALESCE(?, access_count),
169
- importance = COALESCE(?, importance),
170
- last_accessed_at = COALESCE(?, last_accessed_at)
171
- WHERE id = ?
172
- `);
225
+ // For each new chunk, look up by fingerprint: unchanged content keeps the old row.
173
226
  const seenOldIds = new Set();
174
227
  let inheritedCount = 0;
228
+ // A new row whose fingerprint matches an old row is the SAME content: keep the
229
+ // old row (it already holds the embedding, a stable id and its metadata) and
230
+ // drop the fresh copy. Before 2026-09-28 both were kept, so every reindex left
231
+ // each unchanged chunk twice (measured: 10 chunks -> 20 after one reindex).
232
+ // Only the fresh copy (id > maxIdBefore) is ever deleted here — never old data.
233
+ const dropNewDuplicate = db.prepare("DELETE FROM chunks WHERE id = ? AND id > ?");
234
+ let newDuplicatesDropped = 0;
175
235
  const mergeTxn = db.transaction(() => {
176
236
  for (const nc of newChunks) {
177
237
  const fp = chunkFingerprint(nc.source_file, nc.chunk_text);
178
238
  const oldRow = oldByFingerprint.get(fp);
179
239
  if (oldRow) {
240
+ if (seenOldIds.has(oldRow.id)) {
241
+ // Second new copy of the same content in this run: keep the first.
242
+ newDuplicatesDropped += dropNewDuplicate.run(nc.id, maxIdBefore).changes;
243
+ continue;
244
+ }
180
245
  seenOldIds.add(oldRow.id);
181
- updateNewMetadata.run(oldRow.tier, oldRow.access_count, oldRow.importance, oldRow.last_accessed_at, nc.id);
246
+ newDuplicatesDropped += dropNewDuplicate.run(nc.id, maxIdBefore).changes;
182
247
  inheritedCount++;
183
248
  }
184
249
  }
@@ -189,6 +254,22 @@ async function _reindexImpl() {
189
254
  // If fileErrors is non-empty AND would cause a wipe, the Layer 4 invariant
190
255
  // check below will throw and roll back.
191
256
  const orphanIds = oldChunks.map((r) => r.id).filter((id) => !seenOldIds.has(id));
257
+ // Layer 4, moved IN FRONT of the delete: project the post-count and refuse if
258
+ // it would breach the retention ratio. The post-delete check below stays as a
259
+ // second leg, but by then the rows are already gone (no auto-restore).
260
+ // Distinct content that will remain after the delete (kept old rows + new
261
+ // rows). An edited file replaces content — it is not a loss — so this counts
262
+ // what will be present, not which old fingerprints survived.
263
+ const orphanSet = new Set(orphanIds);
264
+ const projectedFps = new Set();
265
+ for (const r of db.prepare("SELECT id, source_file, chunk_text FROM chunks").all()) {
266
+ if (!orphanSet.has(r.id))
267
+ projectedFps.add(chunkFingerprint(r.source_file, r.chunk_text));
268
+ }
269
+ const projectedDistinct = projectedFps.size;
270
+ if (preDistinct > 0 && projectedDistinct / preDistinct < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
271
+ throw new ReindexWipeDetectedError(preDistinct, projectedDistinct, MIN_RETENTION_RATIO);
272
+ }
192
273
  let orphanedDeleted = 0;
193
274
  if (orphanIds.length > 0) {
194
275
  const deleteOrphan = db.prepare("DELETE FROM chunks WHERE id = ?");
@@ -211,13 +292,16 @@ async function _reindexImpl() {
211
292
  // ── Layer 4: invariant check ────────────────────────────────────────────────
212
293
  // Compute retention ratio. If we lost more than (1 - MIN_RETENTION_RATIO) of chunks,
213
294
  // assume wipe-class failure and throw — withOpAudit failure path will preserve snapshot.
214
- const ratio = preCount === 0 ? 1 : postCount / preCount;
215
- if (preCount > 0 && ratio < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
216
- throw new ReindexWipeDetectedError(preCount, postCount, MIN_RETENTION_RATIO);
295
+ // Second leg, measured on the DB itself after the delete: distinct content present.
296
+ const retainedDistinct = new Set(db.prepare("SELECT source_file, chunk_text FROM chunks").all()
297
+ .map((r) => chunkFingerprint(r.source_file, r.chunk_text))).size;
298
+ const ratio = preDistinct === 0 ? 1 : retainedDistinct / preDistinct;
299
+ if (preDistinct > 0 && ratio < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
300
+ throw new ReindexWipeDetectedError(preDistinct, retainedDistinct, MIN_RETENTION_RATIO);
217
301
  }
218
302
  console.log(`[reindex] DONE files=${allFiles.length} pre=${preCount} post=${postCount} ` +
219
303
  `ratio=${(ratio * 100).toFixed(1)}% inherited=${inheritedCount} ` +
220
- `orphans-deleted=${orphanedDeleted} ingest-errors=${fileErrors.length}`);
304
+ `orphans-deleted=${orphanedDeleted} new-duplicates-dropped=${newDuplicatesDropped} ingest-errors=${fileErrors.length}`);
221
305
  if (fileErrors.length > 0) {
222
306
  console.error(`[reindex] ${fileErrors.length} files failed; first 5:`);
223
307
  for (const fe of fileErrors.slice(0, 5))
@@ -229,7 +313,7 @@ async function _reindexImpl() {
229
313
  preCount,
230
314
  postCount,
231
315
  upserted: inheritedCount,
232
- inserted: newChunks.length - inheritedCount,
316
+ inserted: newChunks.length - newDuplicatesDropped,
233
317
  preserved: inheritedCount,
234
318
  orphaned: orphanedDeleted,
235
319
  };
@@ -237,8 +321,7 @@ async function _reindexImpl() {
237
321
  export async function reindex(opts) {
238
322
  if (opts?.dryRun) {
239
323
  const db = getDb();
240
- const memoryFiles = findFiles(resolve(WORKSPACE, "memory"), [".md", ".json"]);
241
- const sharedFiles = findFiles(resolve(WORKSPACE, "shared"), [".md"]);
324
+ const { memoryFiles, sharedFiles } = collectReindexFiles();
242
325
  const allFiles = [...memoryFiles, ...sharedFiles];
243
326
  const currentChunks = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
244
327
  const entityFiles = allFiles.filter((f) => f.includes("/memory/entities/")).length;