nox-mem 3.5.2 → 3.7.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,168 @@
1
+ // tombstone.ts — what happens to chunks when their file leaves the disk
2
+ // (ROADMAP v6 item 3b, 2026-10-14).
3
+ //
4
+ // Before: the watcher ignored deletions (chunks stayed forever, unmarked) and
5
+ // reindex DELETEd every chunk whose file it did not find — including files kept
6
+ // on purpose after their source left the disk (D-2026-09-30: mac-docs PESSOAL /
7
+ // BANCOS). A rename left the old path's chunks behind as duplicates.
8
+ //
9
+ // Now a file that leaves the disk gets a TOMBSTONE row. Its chunks stay where
10
+ // they are, searchable as before — nothing here deletes on its own:
11
+ // - a later ingest of the same path removes the tombstone (the file came back);
12
+ // - an ingest of a NEW path with identical chunk text adopts the rows
13
+ // (chunk-sync.ts), so a rename keeps ids and vectors; the tombstone then
14
+ // records `renamed_to`;
15
+ // - `kept_at` marks a tombstone reviewed as "keep this content" (excluded from
16
+ // adoption and from the default listing);
17
+ // - only purgeTombstone(), called by an explicit operator command under
18
+ // withOpAudit, deletes chunks.
19
+ //
20
+ // Ranking is NOT touched: demoting tombstoned chunks is a scoring change and
21
+ // goes through its own feat(search) + shadow (CLAUDE.md rule 5).
22
+ //
23
+ // The table is created lazily (like ensureVecTable) instead of by a schema
24
+ // bump: the npm and production lineages number their schema versions
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";
28
+ /**
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.
33
+ *
34
+ * On a standalone install nothing lives under the default workspace, so keys
35
+ * start with `../`; that is the key, not an error.
36
+ */
37
+ export function sourceKey(path) {
38
+ return relative(workspaceRoot(), resolve(path));
39
+ }
40
+ /**
41
+ * What a CLI argument names: either a key exactly as `nox-mem tombstones` lists
42
+ * it (the review workflow pastes it back), or a path on disk relative to the cwd
43
+ * (`sourceKey`). The two coincide when the cwd is the workspace. When they differ
44
+ * and both are stored, they are two different files, so refuse rather than guess.
45
+ */
46
+ export function resolveSourceArg(db, arg) {
47
+ ensureTombstoneTable(db);
48
+ const fromPath = sourceKey(arg);
49
+ const stored = (k) => db.prepare("SELECT 1 FROM chunks WHERE source_file = ? UNION ALL SELECT 1 FROM chunk_tombstones WHERE source_file = ? LIMIT 1").get(k, k) !== undefined;
50
+ const hits = [...new Set([arg, fromPath])].filter(stored);
51
+ if (hits.length > 1) {
52
+ throw new Error(`ambiguous: "${arg}" is a stored key, and as a path from the cwd it is "${fromPath}", also stored. Pass an absolute path, or run from the workspace.`);
53
+ }
54
+ return hits[0] ?? fromPath;
55
+ }
56
+ export function ensureTombstoneTable(db) {
57
+ db.exec(`CREATE TABLE IF NOT EXISTS chunk_tombstones (
58
+ source_file TEXT PRIMARY KEY,
59
+ tombstoned_at TEXT NOT NULL DEFAULT (datetime('now')),
60
+ reason TEXT NOT NULL,
61
+ chunks_at_tombstone INTEGER NOT NULL,
62
+ renamed_to TEXT,
63
+ kept_at TEXT
64
+ )`);
65
+ }
66
+ /**
67
+ * Mark `relPath` as gone from disk. `existsOnDisk` is passed in (not probed
68
+ * here) so the caller decides how a path resolves against its workspace.
69
+ */
70
+ export function tombstoneFile(db, relPath, existsOnDisk, reason) {
71
+ ensureTombstoneTable(db);
72
+ if (existsOnDisk)
73
+ return { status: "exists-on-disk", chunks: 0 };
74
+ const chunks = db.prepare("SELECT COUNT(*) AS c FROM chunks WHERE source_file = ?").get(relPath).c;
75
+ if (chunks === 0)
76
+ return { status: "no-chunks", chunks: 0 };
77
+ const r = db
78
+ .prepare("INSERT OR IGNORE INTO chunk_tombstones (source_file, reason, chunks_at_tombstone) VALUES (?, ?, ?)")
79
+ .run(relPath, reason, chunks);
80
+ return { status: r.changes > 0 ? "tombstoned" : "already", chunks };
81
+ }
82
+ /**
83
+ * A directory left the disk (rm -r, or the old side of `mv dir/ other/`):
84
+ * tombstone every stored file under it that is no longer on disk. inotify
85
+ * reports a moved directory as ONE event, not one per file inside it.
86
+ */
87
+ export function tombstonePrefix(db, relDir, existsOnDisk, reason) {
88
+ ensureTombstoneTable(db);
89
+ const prefix = relDir.replace(/\/+$/, "") + "/";
90
+ const files = db
91
+ .prepare("SELECT DISTINCT source_file FROM chunks WHERE substr(source_file, 1, ?) = ?")
92
+ .all(prefix.length, prefix);
93
+ let n = 0, chunks = 0;
94
+ db.transaction(() => {
95
+ for (const { source_file } of files) {
96
+ const r = tombstoneFile(db, source_file, existsOnDisk(source_file), reason);
97
+ if (r.status === "tombstoned") {
98
+ n++;
99
+ chunks += r.chunks;
100
+ }
101
+ }
102
+ })();
103
+ return { files: n, chunks };
104
+ }
105
+ /** Called inside chunk-sync's transaction after a file is (re)ingested. */
106
+ export function resolveTombstoneOnIngest(db, relPath, adoptedFrom) {
107
+ db.prepare("DELETE FROM chunk_tombstones WHERE source_file = ?").run(relPath);
108
+ const mark = db.prepare("UPDATE chunk_tombstones SET renamed_to = ? WHERE source_file = ?");
109
+ for (const from of adoptedFrom)
110
+ mark.run(relPath, from);
111
+ }
112
+ /** Default: tombstones that still hold chunks and were not reviewed as kept. */
113
+ /**
114
+ * One pass, no correlated subquery (2026-10-15). The previous form ran a correlated EXISTS on chunk_text
115
+ * per tombstoned chunk; SQLite answered it with an automatic index over every chunk, and it took 8.5 min
116
+ * on 52.9k chunks with 20 tombstones. A tombstoned chunk is "duplicated elsewhere" when its text is
117
+ * stored under more than one path (its own is one of them), the same predicate as before.
118
+ */
119
+ export const LIST_TOMBSTONES_SQL = `WITH tc AS (
120
+ SELECT c.source_file, c.chunk_text FROM chunks c JOIN chunk_tombstones t ON t.source_file = c.source_file
121
+ ),
122
+ shared AS (
123
+ SELECT o.chunk_text FROM chunks o
124
+ WHERE o.chunk_text IN (SELECT chunk_text FROM tc)
125
+ GROUP BY o.chunk_text HAVING COUNT(DISTINCT o.source_file) > 1
126
+ ),
127
+ agg AS (
128
+ SELECT source_file, COUNT(*) AS live_chunks,
129
+ SUM(chunk_text IN (SELECT chunk_text FROM shared)) AS duplicated_elsewhere
130
+ FROM tc GROUP BY source_file
131
+ )
132
+ SELECT t.*, COALESCE(a.live_chunks, 0) AS live_chunks, COALESCE(a.duplicated_elsewhere, 0) AS duplicated_elsewhere
133
+ FROM chunk_tombstones t LEFT JOIN agg a ON a.source_file = t.source_file
134
+ ORDER BY t.tombstoned_at, t.source_file`;
135
+ export function listTombstones(db, opts = {}) {
136
+ ensureTombstoneTable(db);
137
+ const rows = db.prepare(LIST_TOMBSTONES_SQL).all();
138
+ return opts.all ? rows : rows.filter((r) => r.live_chunks > 0 && r.kept_at === null);
139
+ }
140
+ /** Review outcome "keep": content stays, tombstone leaves the default listing. */
141
+ export function keepTombstone(db, relPath) {
142
+ ensureTombstoneTable(db);
143
+ return db.prepare("UPDATE chunk_tombstones SET kept_at = datetime('now') WHERE source_file = ? AND kept_at IS NULL")
144
+ .run(relPath).changes > 0;
145
+ }
146
+ /**
147
+ * The ONLY place that deletes a tombstoned file's chunks. Callers wrap it in
148
+ * withOpAudit (snapshot first). Refuses when the file is back on disk, when it
149
+ * was never tombstoned, or when it was reviewed as kept.
150
+ */
151
+ export function purgeTombstone(db, relPath, existsOnDisk, opts = {}) {
152
+ ensureTombstoneTable(db);
153
+ if (existsOnDisk)
154
+ return { refused: "exists-on-disk", chunks: 0 };
155
+ const t = db.prepare("SELECT kept_at FROM chunk_tombstones WHERE source_file = ?").get(relPath);
156
+ if (!t)
157
+ return { refused: "no-tombstone", chunks: 0 };
158
+ if (t.kept_at !== null)
159
+ return { refused: "kept", chunks: 0 };
160
+ const chunks = db.prepare("SELECT COUNT(*) AS c FROM chunks WHERE source_file = ?").get(relPath).c;
161
+ if (opts.dryRun)
162
+ return { chunks };
163
+ db.transaction(() => {
164
+ db.prepare("DELETE FROM chunks WHERE source_file = ?").run(relPath);
165
+ db.prepare("DELETE FROM chunk_tombstones WHERE source_file = ?").run(relPath);
166
+ })();
167
+ return { chunks };
168
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * src/lib/workspace.ts — the ONE place the workspace root is resolved.
3
+ *
4
+ * Every `source_file` key is `relative(workspaceRoot(), file)`, and the
5
+ * workspace layout (`memory/`, `memory/entities/`, `shared/`) is read relative
6
+ * to it: entity routing, chunk types, reindex roots, watch defaults.
7
+ *
8
+ * Priority:
9
+ * 1. $OPENCLAW_WORKSPACE explicit (origin deployments, agents)
10
+ * 2. /root/.openclaw/workspace origin layout, when that directory exists
11
+ * 3. ~/.nox-mem standalone: where the default DB lives and
12
+ * where install.sh puts notes (`memory/`)
13
+ *
14
+ * Until 3.6.0, step 3 did not exist: a standalone install keyed every file
15
+ * relative to /root/.openclaw/workspace (`../../../home/u/...`), so
16
+ * `memory/entities/` files were never routed to the entity ingest, `watch`
17
+ * watched nothing and `reindex` refused. Schema v20 rewrites those keys
18
+ * (`migrateStandaloneKeys` in db.ts).
19
+ */
20
+ import { existsSync } from "fs";
21
+ import { homedir } from "os";
22
+ import { join } from "path";
23
+ export const ORIGIN_WORKSPACE = "/root/.openclaw/workspace";
24
+ export function standaloneWorkspace() {
25
+ return join(homedir(), ".nox-mem");
26
+ }
27
+ export function workspaceRootWithSource(env = process.env, exists = existsSync) {
28
+ if (env.OPENCLAW_WORKSPACE)
29
+ return { root: env.OPENCLAW_WORKSPACE, source: "OPENCLAW_WORKSPACE" };
30
+ if (exists(ORIGIN_WORKSPACE))
31
+ return { root: ORIGIN_WORKSPACE, source: "origin-default" };
32
+ return { root: standaloneWorkspace(), source: "standalone" };
33
+ }
34
+ export function workspaceRoot() {
35
+ return workspaceRootWithSource().root;
36
+ }
@@ -260,7 +260,7 @@ async function handleRequest(req) {
260
260
  asOf: args.as_of,
261
261
  changedSince: args.changed_since,
262
262
  });
263
- const results = await searchHybrid(query, limit, true, filter);
263
+ const results = await searchHybrid(query, limit, true, filter, { surface: "mcp", agent: process.env.NOX_AGENT_NAME });
264
264
  text = formatResults(results);
265
265
  break;
266
266
  }
package/dist/primer.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { readFileSync } from "fs";
2
2
  import { resolve } from "path";
3
3
  import { getDb } from "./db.js";
4
- const WORKSPACE = process.env.OPENCLAW_WORKSPACE ?? "/root/.openclaw/workspace";
4
+ import { workspaceRoot } from "./lib/workspace.js";
5
+ const WORKSPACE = workspaceRoot();
5
6
  /**
6
7
  * Extract a clean summary line from a decision chunk.
7
8
  * Handles both formats:
package/dist/reflect.js CHANGED
@@ -87,7 +87,7 @@ async function gatherEvidence(question) {
87
87
  // 1. Hybrid search top 10 (async because semantic is async)
88
88
  let searchResults;
89
89
  try {
90
- searchResults = await searchHybrid(question, 10);
90
+ searchResults = await searchHybrid(question, 10, true, undefined, { surface: "reflect", agent: process.env.NOX_AGENT_NAME });
91
91
  }
92
92
  catch {
93
93
  searchResults = search(question, 10); // fallback to FTS only
@@ -35,9 +35,10 @@ export class ReindexSourceMissingError extends Error {
35
35
  (reason === "no-files"
36
36
  ? `found 0 files under ${roots.join(", ")} while the DB holds ${preCount} chunks. `
37
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 ` +
38
+ `reindex rebuilds ONLY from <workspace>/memory and <workspace>/shared, where the workspace is ` +
39
+ `$OPENCLAW_WORKSPACE, else /root/.openclaw/workspace if it exists, else ~/.nox-mem ` +
39
40
  `(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
+ `Notes added with \`nox-mem ingest <file>\` from elsewhere do not need reindex. ` +
41
42
  `Set NOX_REINDEX_ALLOW_WIPE=1 ONLY if emptying the DB is intended.`);
42
43
  this.name = "ReindexSourceMissingError";
43
44
  this.roots = roots;
package/dist/reindex.js CHANGED
@@ -35,13 +35,16 @@
35
35
  // operator can restore via safeRestore().
36
36
  import { getDb } from "./db.js";
37
37
  import { withOpAudit } from "./lib/op-audit.js";
38
- import { routeIngest } from "./lib/ingest-router.js";
38
+ import { routeIngestSync } from "./lib/ingest-router.js";
39
+ import { ensureTombstoneTable, tombstoneFile } from "./lib/tombstone.js";
39
40
  import { existsSync, readdirSync } from "fs";
40
41
  import { createHash } from "crypto";
41
- import { join, resolve } from "path";
42
+ import { join, relative, resolve } from "path";
42
43
  import { ReindexWipeDetectedError, ReindexSourceMissingError, ReindexWorkspaceMismatchError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
44
+ import { workspaceRoot, workspaceRootWithSource } from "./lib/workspace.js";
45
+ import { DEFAULT_STANDALONE_DB_PATH } from "./lib/db-path.js";
43
46
  export { ReindexWipeDetectedError, ReindexSourceMissingError, ReindexWorkspaceMismatchError } from "./reindex-errors.js";
44
- const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
47
+ const WORKSPACE = workspaceRoot();
45
48
  // Layer 4: tunable safety thresholds (env-overridable for emergency operations).
46
49
  // MIN_RETENTION_RATIO imported from reindex-errors.ts (single source of truth).
47
50
  const ALLOW_WIPE = process.env.NOX_REINDEX_ALLOW_WIPE === "1";
@@ -87,7 +90,11 @@ export function assertReindexSource(preCount) {
87
90
  // workspace's own DB — how origin crons call it — passes.
88
91
  if (process.env.NOX_DB_PATH && !process.env.OPENCLAW_WORKSPACE) {
89
92
  const dbPath = resolve(process.env.NOX_DB_PATH);
90
- const workspaceDbPath = resolve(WORKSPACE, "tools", "nox-mem", "nox-mem.db");
93
+ // The workspace's own DB: origin layout keeps it under tools/nox-mem; the
94
+ // standalone root (~/.nox-mem) is where the default standalone DB lives.
95
+ const workspaceDbPath = workspaceRootWithSource().source === "standalone"
96
+ ? DEFAULT_STANDALONE_DB_PATH
97
+ : resolve(WORKSPACE, "tools", "nox-mem", "nox-mem.db");
91
98
  if (dbPath !== workspaceDbPath)
92
99
  throw new ReindexWorkspaceMismatchError(dbPath, workspaceDbPath);
93
100
  }
@@ -113,24 +120,24 @@ function chunkFingerprint(sourceFile, chunkText) {
113
120
  return createHash("sha256").update(sourceFile).update("\0").update(chunkText).digest("hex").substring(0, 32);
114
121
  }
115
122
  /**
116
- * Core reindex implementation — UPSERT-based, non-destructive.
123
+ * Core reindex — a per-file diff, in ONE transaction (2026-10-14, ROADMAP v6 item 3).
117
124
  *
118
- * Strategy:
119
- * 1. Snapshot existing (source_file, chunk_text) -> {id, tier, access_count, importance, last_accessed_at, section, retention_days, source_type, is_compiled, pain}
120
- * 2. Walk files, route via routeIngest into ISOLATED staging set (in-memory accumulator).
121
- * NOTE: routeIngest currently writes directly to DB. We pre-mark new ingests with
122
- * `__reindex_stage` chunk_type prefix and finalize via UPDATE.
123
- * Until routeIngest supports a staging mode (follow-up PR), we use the safer pattern:
124
- * preserve old chunks until ALL new ingests succeed, then UPSERT-merge.
125
- * 3. For each file processed by routeIngest, the NEW chunks have fresh ids. Match against
126
- * old chunks via content fingerprint and copy access metadata over.
127
- * 4. After ALL files succeed: DELETE old chunks that did NOT survive the fingerprint match
128
- * (i.e. content actually changed/removed). This is the SOLE destructive op, and only
129
- * runs AFTER all ingests completed without throwing.
125
+ * 1. Files under the reindex roots that left the disk are TOMBSTONED, first —
126
+ * so a file moved to a new path is adopted (ids kept) when step 2 reaches it.
127
+ * Their chunks stay. Before, reindex DELETEd every chunk whose file it did
128
+ * not walk, which included content kept on purpose (D-2026-09-30).
129
+ * 2. Every walked file goes through routeIngestSync → chunk-sync: unchanged
130
+ * chunks keep their row, new text is inserted, edited-away text removed.
131
+ * Duplicate rows of the same content (left by the pre-2026-09-28 reindex)
132
+ * collapse to one, keeping the embedded copy.
133
+ * 3. Distinct content retained is checked BEFORE commit; a breach throws and
134
+ * the whole transaction rolls back (withOpAudit keeps the snapshot anyway).
135
+ *
136
+ * Chunks of files outside the roots (agents/, sessions/, …) are not touched.
130
137
  */
131
138
  async function _reindexImpl() {
132
139
  const db = getDb();
133
- // Defensive: load sqlite-vec BEFORE any chunk mutation (2026-05-21 fix preserved).
140
+ // Load sqlite-vec extension so the vec cascade trigger on chunks can run.
134
141
  // Dynamic import via Function() avoids TS2307 in the staged-dir build (no sqlite-vec
135
142
  // dep here — real module installed on VPS via package.json at deploy target).
136
143
  try {
@@ -142,191 +149,81 @@ async function _reindexImpl() {
142
149
  console.error(`[reindex] WARN: failed to load sqlite-vec extension: ${err}`);
143
150
  throw new Error("sqlite-vec module not available; cannot safely reindex (vec_chunks trigger would fail)");
144
151
  }
145
- // ── Phase 1: snapshot pre-state ────────────────────────────────────────────
146
152
  const preCount = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
147
153
  // ── Phase 0 guard (read-only so far): the rebuild source must exist ────────
148
154
  // Measured 2026-09-28 on a clean npm install: no $OPENCLAW_WORKSPACE ⇒ the scan
149
- // found 0 files ⇒ every chunk became an "orphan" and was deleted; the ratio
150
- // guard below then threw — after the DELETE. Refuse here, before any write.
155
+ // found 0 files ⇒ every chunk became an "orphan" and was deleted. Refuse here.
151
156
  assertReindexSource(preCount);
152
- // Tolerant select: schema may lack some columns on older DBs (pre-v10).
153
- // `SELECT *` would force coupling; instead probe column existence.
154
- const cols = new Set(db.prepare("PRAGMA table_info(chunks)").all().map((r) => r.name));
155
- const has = (c) => cols.has(c);
156
- const selectCols = [
157
- "id",
158
- "source_file",
159
- "chunk_text",
160
- has("tier") ? "tier" : "NULL AS tier",
161
- has("access_count") ? "access_count" : "NULL AS access_count",
162
- has("importance") ? "importance" : "NULL AS importance",
163
- has("last_accessed_at") ? "last_accessed_at" : "NULL AS last_accessed_at",
164
- has("section") ? "section" : "NULL AS section",
165
- has("section_boost") ? "section_boost" : "NULL AS section_boost",
166
- has("retention_days") ? "retention_days" : "NULL AS retention_days",
167
- has("pain") ? "pain" : "NULL AS pain",
168
- has("source_type") ? "source_type" : "NULL AS source_type",
169
- has("is_compiled") ? "is_compiled" : "NULL AS is_compiled",
170
- ].join(", ");
171
- const oldChunks = db.prepare(`SELECT ${selectCols} FROM chunks`).all();
172
- // Build content fingerprint -> oldChunk index.
173
- // One representative per content fingerprint. When the DB already holds
174
- // duplicates (every reindex before 2026-09-28 doubled unchanged content), the
175
- // kept representative is the one WITH an embedding, then the lowest id — the
176
- // other copies become orphans and are removed, and dropping one without a
177
- // vector must never cost the one that has it.
178
- let embeddedIds = new Set();
179
- try {
180
- embeddedIds = new Set(db.prepare("SELECT chunk_id FROM vec_chunk_map").all().map((r) => r.chunk_id));
181
- }
182
- catch {
183
- /* no vector map yet (fresh / keyless install) — every row is equal */
184
- }
185
- const better = (a, b) => {
186
- const ae = embeddedIds.has(a.id), be = embeddedIds.has(b.id);
187
- if (ae !== be)
188
- return ae ? a : b;
189
- return a.id <= b.id ? a : b;
190
- };
191
- const oldByFingerprint = new Map();
192
- for (const row of oldChunks) {
193
- const fp = chunkFingerprint(row.source_file, row.chunk_text);
194
- const cur = oldByFingerprint.get(fp);
195
- oldByFingerprint.set(fp, cur ? better(cur, row) : row);
196
- }
197
157
  // Retention is measured on DISTINCT content, not rows: removing a redundant
198
158
  // copy of content that is still present is not a loss. Measured on rows, a DB
199
- // doubled by the old bug (2N → N) read as a 50% wipe and the cleanup reindex
200
- // was refused forever.
201
- const preDistinct = oldByFingerprint.size;
202
- console.log(`[reindex] Phase 1: snapshotted ${oldChunks.length} existing chunks`);
203
- // ── Phase 2: ingest new chunks into a staging set ──────────────────────────
204
- // Strategy: do NOT delete first. Let routeIngest INSERT new chunks alongside old ones.
205
- // After all files succeed, we merge: keep new chunks (overlap by fingerprint inherits old metadata),
206
- // delete pure-old chunks (no matching fingerprint = content removed).
207
- //
208
- // To distinguish "old" vs "new" rows we capture max(id) before any ingest.
209
- const maxIdBefore = db.prepare("SELECT COALESCE(MAX(id), 0) AS m FROM chunks").get().m;
159
+ // doubled by the old bug (2N → N) read as a 50% wipe.
160
+ const distinctContent = () => new Set(db.prepare("SELECT source_file, chunk_text FROM chunks").all()
161
+ .map((r) => chunkFingerprint(r.source_file, r.chunk_text))).size;
162
+ const preDistinct = distinctContent();
163
+ console.log(`[reindex] Phase 1: ${preCount} chunks, ${preDistinct} distinct`);
210
164
  // Same scan as assertReindexSource — one definition of "the source".
211
165
  const { memoryFiles, sharedFiles } = collectReindexFiles();
212
166
  const allFiles = [...memoryFiles, ...sharedFiles];
213
- let totalChunksIngested = 0;
167
+ const roots = reindexRoots().map((r) => relative(WORKSPACE, r) + "/");
214
168
  const fileErrors = [];
215
- for (const file of allFiles) {
216
- try {
217
- // skipDelete=true: do NOT let routeIngest call its own DELETE FROM chunks WHERE source_file=?
218
- // We handle merge globally after the loop.
219
- const result = await routeIngest(file, { externalDb: db, skipDelete: true });
220
- totalChunksIngested += result.chunks;
221
- // Verbose log gated behind env to avoid blasting nightly cron output.
222
- if (process.env.NOX_REINDEX_VERBOSE === "1") {
223
- console.log(`[reindex] ${file}: ${result.chunks} chunks`);
169
+ const t = { chunks: 0, kept: 0, inserted: 0, deleted: 0, adopted: 0, tombstoned: 0 };
170
+ let retainedDistinct = preDistinct;
171
+ ensureTombstoneTable(db);
172
+ db.transaction(() => {
173
+ // ── Phase 2: tombstone what left the disk (before ingest, so renames adopt) ──
174
+ const sources = db.prepare("SELECT DISTINCT source_file FROM chunks").all();
175
+ for (const { source_file } of sources) {
176
+ if (!roots.some((r) => source_file.startsWith(r)))
177
+ continue;
178
+ if (existsSync(resolve(WORKSPACE, source_file)))
179
+ continue;
180
+ if (tombstoneFile(db, source_file, false, "missing-at-reindex").status === "tombstoned")
181
+ t.tombstoned++;
182
+ }
183
+ // ── Phase 3: per-file diff ──────────────────────────────────────────────
184
+ for (const file of allFiles) {
185
+ try {
186
+ const r = routeIngestSync(db, file);
187
+ t.chunks += r.chunks;
188
+ t.kept += r.kept ?? 0;
189
+ t.inserted += r.inserted?.length ?? 0;
190
+ t.deleted += r.deleted ?? 0;
191
+ t.adopted += r.adopted ?? 0;
192
+ if (process.env.NOX_REINDEX_VERBOSE === "1")
193
+ console.log(`[reindex] ${file}: ${r.chunks} chunks`);
194
+ }
195
+ catch (err) {
196
+ const msg = err instanceof Error ? err.message : String(err);
197
+ fileErrors.push({ file, error: msg });
198
+ console.error(`[reindex] ERROR ingesting ${file}: ${msg}`);
224
199
  }
225
200
  }
226
- catch (err) {
227
- const msg = err instanceof Error ? err.message : String(err);
228
- fileErrors.push({ file, error: msg });
229
- console.error(`[reindex] ERROR ingesting ${file}: ${msg}`);
201
+ // ── Phase 4: core tier retention_days = NULL contract (preserved) ─────────
202
+ const cols = new Set(db.prepare("PRAGMA table_info(chunks)").all().map((r) => r.name));
203
+ if (cols.has("retention_days") && cols.has("tier")) {
204
+ db.exec("UPDATE chunks SET retention_days = NULL WHERE tier = 'core'");
230
205
  }
231
- }
232
- const newChunks = db
233
- .prepare("SELECT id, source_file, chunk_text FROM chunks WHERE id > ?")
234
- .all(maxIdBefore);
235
- // For each new chunk, look up by fingerprint: unchanged content keeps the old row.
236
- const seenOldIds = new Set();
237
- let inheritedCount = 0;
238
- // A new row whose fingerprint matches an old row is the SAME content: keep the
239
- // old row (it already holds the embedding, a stable id and its metadata) and
240
- // drop the fresh copy. Before 2026-09-28 both were kept, so every reindex left
241
- // each unchanged chunk twice (measured: 10 chunks -> 20 after one reindex).
242
- // Only the fresh copy (id > maxIdBefore) is ever deleted here — never old data.
243
- const dropNewDuplicate = db.prepare("DELETE FROM chunks WHERE id = ? AND id > ?");
244
- let newDuplicatesDropped = 0;
245
- const mergeTxn = db.transaction(() => {
246
- for (const nc of newChunks) {
247
- const fp = chunkFingerprint(nc.source_file, nc.chunk_text);
248
- const oldRow = oldByFingerprint.get(fp);
249
- if (oldRow) {
250
- if (seenOldIds.has(oldRow.id)) {
251
- // Second new copy of the same content in this run: keep the first.
252
- newDuplicatesDropped += dropNewDuplicate.run(nc.id, maxIdBefore).changes;
253
- continue;
254
- }
255
- seenOldIds.add(oldRow.id);
256
- newDuplicatesDropped += dropNewDuplicate.run(nc.id, maxIdBefore).changes;
257
- inheritedCount++;
258
- }
206
+ // ── Layer 4: invariant check, BEFORE commit ─────────────────────────────
207
+ // An edited file replaces content — it is not a loss — so this counts what
208
+ // is present now. A breach throws and rolls the whole reindex back.
209
+ retainedDistinct = distinctContent();
210
+ if (preDistinct > 0 && retainedDistinct / preDistinct < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
211
+ throw new ReindexWipeDetectedError(preDistinct, retainedDistinct, MIN_RETENTION_RATIO);
259
212
  }
260
- });
261
- mergeTxn();
262
- // ── Phase 4: delete pure-old chunks (no fingerprint match in new set) ──────
263
- // This is the SOLE destructive op. Runs AFTER all ingests succeeded.
264
- // If fileErrors is non-empty AND would cause a wipe, the Layer 4 invariant
265
- // check below will throw and roll back.
266
- const orphanIds = oldChunks.map((r) => r.id).filter((id) => !seenOldIds.has(id));
267
- // Layer 4, moved IN FRONT of the delete: project the post-count and refuse if
268
- // it would breach the retention ratio. The post-delete check below stays as a
269
- // second leg, but by then the rows are already gone (no auto-restore).
270
- // Distinct content that will remain after the delete (kept old rows + new
271
- // rows). An edited file replaces content — it is not a loss — so this counts
272
- // what will be present, not which old fingerprints survived.
273
- const orphanSet = new Set(orphanIds);
274
- const projectedFps = new Set();
275
- for (const r of db.prepare("SELECT id, source_file, chunk_text FROM chunks").all()) {
276
- if (!orphanSet.has(r.id))
277
- projectedFps.add(chunkFingerprint(r.source_file, r.chunk_text));
278
- }
279
- const projectedDistinct = projectedFps.size;
280
- if (preDistinct > 0 && projectedDistinct / preDistinct < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
281
- throw new ReindexWipeDetectedError(preDistinct, projectedDistinct, MIN_RETENTION_RATIO);
282
- }
283
- let orphanedDeleted = 0;
284
- if (orphanIds.length > 0) {
285
- const deleteOrphan = db.prepare("DELETE FROM chunks WHERE id = ?");
286
- const deleteOrphansTxn = db.transaction(() => {
287
- for (const id of orphanIds) {
288
- const r = deleteOrphan.run(id);
289
- if (r.changes > 0)
290
- orphanedDeleted++;
291
- }
292
- });
293
- deleteOrphansTxn();
294
- }
213
+ })();
295
214
  // Re-rebuild FTS index (cheap, idempotent — content= table optimization).
296
215
  db.exec("INSERT INTO chunks_fts(chunks_fts) VALUES('rebuild')");
297
- // ── Phase 5: core tier retention_days = NULL contract (preserved) ───────────
298
- if (cols.has("retention_days") && cols.has("tier")) {
299
- db.exec("UPDATE chunks SET retention_days = NULL WHERE tier = 'core'");
300
- }
301
216
  const postCount = db.prepare("SELECT COUNT(*) AS c FROM chunks").get().c;
302
- // ── Layer 4: invariant check ────────────────────────────────────────────────
303
- // Compute retention ratio. If we lost more than (1 - MIN_RETENTION_RATIO) of chunks,
304
- // assume wipe-class failure and throw — withOpAudit failure path will preserve snapshot.
305
- // Second leg, measured on the DB itself after the delete: distinct content present.
306
- const retainedDistinct = new Set(db.prepare("SELECT source_file, chunk_text FROM chunks").all()
307
- .map((r) => chunkFingerprint(r.source_file, r.chunk_text))).size;
308
217
  const ratio = preDistinct === 0 ? 1 : retainedDistinct / preDistinct;
309
- if (preDistinct > 0 && ratio < MIN_RETENTION_RATIO && !ALLOW_WIPE) {
310
- throw new ReindexWipeDetectedError(preDistinct, retainedDistinct, MIN_RETENTION_RATIO);
311
- }
312
218
  console.log(`[reindex] DONE files=${allFiles.length} pre=${preCount} post=${postCount} ` +
313
- `ratio=${(ratio * 100).toFixed(1)}% inherited=${inheritedCount} ` +
314
- `orphans-deleted=${orphanedDeleted} new-duplicates-dropped=${newDuplicatesDropped} ingest-errors=${fileErrors.length}`);
219
+ `ratio=${(ratio * 100).toFixed(1)}% kept=${t.kept} inserted=${t.inserted} deleted=${t.deleted} ` +
220
+ `adopted=${t.adopted} tombstoned=${t.tombstoned} ingest-errors=${fileErrors.length}`);
315
221
  if (fileErrors.length > 0) {
316
222
  console.error(`[reindex] ${fileErrors.length} files failed; first 5:`);
317
223
  for (const fe of fileErrors.slice(0, 5))
318
224
  console.error(` - ${fe.file}: ${fe.error}`);
319
225
  }
320
- return {
321
- files: allFiles.length,
322
- chunks: totalChunksIngested,
323
- preCount,
324
- postCount,
325
- upserted: inheritedCount,
326
- inserted: newChunks.length - newDuplicatesDropped,
327
- preserved: inheritedCount,
328
- orphaned: orphanedDeleted,
329
- };
226
+ return { files: allFiles.length, preCount, postCount, ...t };
330
227
  }
331
228
  export async function reindex(opts) {
332
229
  if (opts?.dryRun) {
@@ -341,10 +238,10 @@ export async function reindex(opts) {
341
238
  console.log(JSON.stringify({
342
239
  dryRun: true,
343
240
  operation: "reindex",
344
- mode: "UPSERT (emergency fix 2026-05-23)",
241
+ mode: "per-file diff in one transaction (2026-10-14)",
345
242
  wouldUpsert: {
346
243
  currentChunks,
347
- note: "existing chunks preserved by content-fingerprint; metadata inherited",
244
+ note: "unchanged chunks keep their row (id, vector, history); files gone from disk are tombstoned, not deleted",
348
245
  },
349
246
  wouldProcess: {
350
247
  totalFiles: allFiles.length,
@@ -360,7 +257,8 @@ export async function reindex(opts) {
360
257
  coreTierRetention: "YES",
361
258
  entityRouting: "YES via routeIngest",
362
259
  wipeGuard: `YES via Layer-4 invariant (min ratio ${MIN_RETENTION_RATIO})`,
363
- upsert: "YES via content-fingerprint match (no DELETE FROM chunks)",
260
+ upsert: "YES via chunk-sync (DELETE only for text edited away from a file still on disk)",
261
+ missingFiles: "tombstoned (nox-mem tombstones), never deleted",
364
262
  },
365
263
  estimatedDuration: "2-5 min depending on Gemini API latency",
366
264
  }, null, 2));
@@ -373,14 +271,17 @@ export async function reindex(opts) {
373
271
  return {
374
272
  files: r.files,
375
273
  chunks: r.chunks,
376
- affected_rows: r.upserted + r.inserted,
274
+ // rows written; kept rows are untouched by design
275
+ affected_rows: r.inserted + r.deleted + r.adopted,
377
276
  notes: `db_source=main | ${r.files} files reindexed | pre=${r.preCount} post=${r.postCount} ` +
378
- `inherited=${r.upserted} new=${r.inserted} orphans=${r.orphaned}`,
277
+ `kept=${r.kept} new=${r.inserted} deleted=${r.deleted} adopted=${r.adopted} tombstoned=${r.tombstoned}`,
379
278
  preCount: r.preCount,
380
279
  postCount: r.postCount,
381
- upserted: r.upserted,
280
+ upserted: r.kept,
382
281
  inserted: r.inserted,
383
- orphaned: r.orphaned,
282
+ orphaned: r.deleted,
283
+ adopted: r.adopted,
284
+ tombstoned: r.tombstoned,
384
285
  };
385
286
  });
386
287
  }