nox-mem 3.5.2 → 3.6.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 +12 -4
- package/dist/api-server.js +1 -1
- package/dist/consolidate.js +2 -1
- package/dist/db.js +87 -2
- package/dist/digest.js +2 -1
- package/dist/index.js +112 -2
- package/dist/ingest-entity.js +69 -59
- package/dist/ingest.js +78 -54
- package/dist/lib/answer/retrieval.js +1 -1
- package/dist/lib/chunk-sync.js +197 -0
- package/dist/lib/ingest-many.js +3 -1
- package/dist/lib/ingest-router.js +31 -8
- package/dist/lib/tombstone.js +156 -0
- package/dist/lib/workspace.js +36 -0
- package/dist/mcp-server.js +1 -1
- package/dist/primer.js +2 -1
- package/dist/reflect.js +1 -1
- package/dist/reindex-errors.js +3 -2
- package/dist/reindex.js +87 -186
- package/dist/search.js +20 -6
- package/dist/session-update.js +2 -1
- package/dist/shared-memory.js +2 -1
- package/dist/temporal-retrieval.js +18 -0
- package/dist/watch.js +81 -7
- package/package.json +1 -1
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
|
-
|
|
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
|
package/dist/reindex-errors.js
CHANGED
|
@@ -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
|
|
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
|
-
`
|
|
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 {
|
|
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 =
|
|
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
|
-
|
|
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
|
|
123
|
+
* Core reindex — a per-file diff, in ONE transaction (2026-10-14, ROADMAP v6 item 3).
|
|
117
124
|
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
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
|
-
//
|
|
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
|
|
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
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
-
|
|
167
|
+
const roots = reindexRoots().map((r) => relative(WORKSPACE, r) + "/");
|
|
214
168
|
const fileErrors = [];
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
if (
|
|
223
|
-
|
|
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
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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
|
-
|
|
233
|
-
.
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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)}%
|
|
314
|
-
`
|
|
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: "
|
|
241
|
+
mode: "per-file diff in one transaction (2026-10-14)",
|
|
345
242
|
wouldUpsert: {
|
|
346
243
|
currentChunks,
|
|
347
|
-
note: "
|
|
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
|
|
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
|
-
|
|
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
|
-
`
|
|
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.
|
|
280
|
+
upserted: r.kept,
|
|
382
281
|
inserted: r.inserted,
|
|
383
|
-
orphaned: r.
|
|
282
|
+
orphaned: r.deleted,
|
|
283
|
+
adopted: r.adopted,
|
|
284
|
+
tombstoned: r.tombstoned,
|
|
384
285
|
};
|
|
385
286
|
});
|
|
386
287
|
}
|
package/dist/search.js
CHANGED
|
@@ -4,7 +4,7 @@ import { TIER_BOOST } from "./tier-manager.js";
|
|
|
4
4
|
import { expandQuery } from "./search-expansion.js";
|
|
5
5
|
import { dedupe } from "./search-dedup.js";
|
|
6
6
|
import { calculateSalience, calculateSalienceLegacy, getSalienceMode } from "./salience.js";
|
|
7
|
-
import { rerankByTemporalProximity, logTemporalProbe } from "./temporal-retrieval.js";
|
|
7
|
+
import { rerankByTemporalProximity, logTemporalProbe, temporalQueryKind } from "./temporal-retrieval.js";
|
|
8
8
|
import { countQueryEntities } from "./query-entity-count.js";
|
|
9
9
|
import { buildTemporalClause } from "./lib/dates.js";
|
|
10
10
|
// ─── Boost configuration (Fase 1.7a + A-boost-stack-wiring 2026-05-19) ────────
|
|
@@ -556,7 +556,19 @@ export async function searchSemantic(query, limit = 5, trackAccess = true, filte
|
|
|
556
556
|
function rrfScore(rank, k = 60) {
|
|
557
557
|
return 1 / (k + rank + 1);
|
|
558
558
|
}
|
|
559
|
-
function
|
|
559
|
+
export function telemetryCaller(caller, trackAccess) {
|
|
560
|
+
const clean = (v, fallback) => {
|
|
561
|
+
const t = (v ?? "").trim().toLowerCase();
|
|
562
|
+
if (!t)
|
|
563
|
+
return fallback;
|
|
564
|
+
return /^[a-z0-9_.-]{1,40}$/.test(t) ? t : "invalid";
|
|
565
|
+
};
|
|
566
|
+
const agent = clean(caller.agent, "unknown");
|
|
567
|
+
return `${trackAccess ? clean(caller.surface, "unknown") : "probe"}:${agent}`;
|
|
568
|
+
}
|
|
569
|
+
function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs, skipReason, top,
|
|
570
|
+
/** Already normalised by `telemetryCaller`. */
|
|
571
|
+
requestingAgent) {
|
|
560
572
|
try {
|
|
561
573
|
const db = getDb();
|
|
562
574
|
const hash = createHash("sha1").update(query).digest("hex").substring(0, 16);
|
|
@@ -567,14 +579,16 @@ function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs
|
|
|
567
579
|
const comId = (top ?? []).filter((r) => typeof r.id === "number");
|
|
568
580
|
const ids = comId.length ? JSON.stringify(comId.map((r) => r.id)) : null;
|
|
569
581
|
const scores = comId.length ? JSON.stringify(comId.map((r) => r.score)) : null;
|
|
570
|
-
|
|
571
|
-
|
|
582
|
+
const agent = requestingAgent ?? telemetryCaller({}, true);
|
|
583
|
+
const temporal = temporalQueryKind(query);
|
|
584
|
+
db.prepare(`INSERT INTO search_telemetry (query_hash, query_words, variants_count, results_count, has_semantic, latency_ms, expansion_skipped_reason, top_chunk_ids, top_scores, requesting_agent, was_temporal_query)
|
|
585
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(hash, words, variantsCount, resultsCount, hasSemantic ? 1 : 0, latencyMs, skipReason || null, ids, scores, agent, temporal);
|
|
572
586
|
}
|
|
573
587
|
catch {
|
|
574
588
|
// telemetria nunca derruba a search
|
|
575
589
|
}
|
|
576
590
|
}
|
|
577
|
-
export async function searchHybrid(query, limit = 5, trackAccess = true, filter) {
|
|
591
|
+
export async function searchHybrid(query, limit = 5, trackAccess = true, filter, caller = {}) {
|
|
578
592
|
const t0 = Date.now();
|
|
579
593
|
const perVariantLimit = limit * 2;
|
|
580
594
|
// Kick off original-query searches IMMEDIATELY and expansion in parallel.
|
|
@@ -629,7 +643,7 @@ export async function searchHybrid(query, limit = 5, trackAccess = true, filter)
|
|
|
629
643
|
.map(({ rrfScore: s, saw_semantic: _, ...r }) => ({ ...r, score: Math.round(s * 1000 * 100) / 100 }));
|
|
630
644
|
const final = dedupe(preDedup, limit);
|
|
631
645
|
const hasSemantic = final.some((r) => r.match_type === "semantic" || r.match_type === "hybrid");
|
|
632
|
-
logTelemetry(query, variants.length, final.length, hasSemantic, Date.now() - t0, expansion.reason, final);
|
|
646
|
+
logTelemetry(query, variants.length, final.length, hasSemantic, Date.now() - t0, expansion.reason, final, telemetryCaller(caller, trackAccess));
|
|
633
647
|
// D49 Phase 1 — temporal proximity rerank, shadow-mode opt-in.
|
|
634
648
|
// Only activates if NOX_TEMPORAL_PATH=shadow|active. In shadow mode the
|
|
635
649
|
// module computes the would-be rerank report but does NOT mutate `final`;
|
package/dist/session-update.js
CHANGED
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
import { readFileSync, writeFileSync, existsSync } from "fs";
|
|
6
6
|
import { resolve } from "path";
|
|
7
7
|
import { getDb } from "./db.js";
|
|
8
|
-
|
|
8
|
+
import { workspaceRoot } from "./lib/workspace.js";
|
|
9
|
+
const WORKSPACE = workspaceRoot();
|
|
9
10
|
export function updateSessionState() {
|
|
10
11
|
const sessionPath = resolve(WORKSPACE, "memory", "SESSION-STATE.md");
|
|
11
12
|
const db = getDb();
|
package/dist/shared-memory.js
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
import { getDb } from "./db.js";
|
|
8
8
|
import Database from "better-sqlite3";
|
|
9
9
|
import { resolve } from "path";
|
|
10
|
-
|
|
10
|
+
import { workspaceRoot } from "./lib/workspace.js";
|
|
11
|
+
const WORKSPACE = workspaceRoot();
|
|
11
12
|
const SHARED_DB = resolve(WORKSPACE, "tools/nox-mem/shared-memory.db");
|
|
12
13
|
// NOX_AGENTS_DIR: base directory where agent sub-dirs live.
|
|
13
14
|
// NOX_AGENTS: comma-separated list of agent names to include (no spaces).
|
|
@@ -168,6 +168,24 @@ export function detectTemporal(query, nowMs = Date.now()) {
|
|
|
168
168
|
}
|
|
169
169
|
return { isTemporal: false, anchor: null, anchorRange: null, signalSource: null };
|
|
170
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* Value of `search_telemetry.was_temporal_query` (schema v20).
|
|
173
|
+
*
|
|
174
|
+
* 0 — no temporal expression
|
|
175
|
+
* 1 — temporal word only, no date ("when", "last", "deploy") → no anchor
|
|
176
|
+
* 2 — a date in the query (ISO, month, year) → the only class a proximity
|
|
177
|
+
* rerank could use
|
|
178
|
+
*
|
|
179
|
+
* Measures how often real searches carry a temporal expression, which is what
|
|
180
|
+
* would justify reopening the implicit temporal rerank. Runs on every search
|
|
181
|
+
* regardless of NOX_TEMPORAL_PATH: regex over the query, results untouched.
|
|
182
|
+
*/
|
|
183
|
+
export function temporalQueryKind(query) {
|
|
184
|
+
const { isTemporal, signalSource } = detectTemporal(query);
|
|
185
|
+
if (!isTemporal)
|
|
186
|
+
return 0;
|
|
187
|
+
return signalSource === "adverbial" ? 1 : 2;
|
|
188
|
+
}
|
|
171
189
|
// ─── Proximity delta ──────────────────────────────────────────────────────────
|
|
172
190
|
//
|
|
173
191
|
// Gaussiana truncada: bump máximo de +0.5 em Δdays=0, decai exponencialmente.
|
package/dist/watch.js
CHANGED
|
@@ -3,12 +3,17 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Monitors memory files across all 6 agent workspaces.
|
|
5
5
|
* On change: debounce 2s → ingest file → log.
|
|
6
|
+
* On a path that no longer exists (delete, or the old side of a rename):
|
|
7
|
+
* tombstone its chunks — they stay, marked for review (lib/tombstone.ts).
|
|
6
8
|
* Skips: binary files, .db, .json session files, tmp files.
|
|
7
9
|
*/
|
|
8
|
-
import { watch, statSync, existsSync } from "fs";
|
|
9
|
-
import { resolve, extname } from "path";
|
|
10
|
+
import { watch, statSync, existsSync, readdirSync } from "fs";
|
|
11
|
+
import { resolve, extname, relative } from "path";
|
|
10
12
|
import { routeIngest } from "./lib/ingest-router.js";
|
|
11
|
-
|
|
13
|
+
import { getDb } from "./db.js";
|
|
14
|
+
import { tombstoneFile, tombstonePrefix } from "./lib/tombstone.js";
|
|
15
|
+
import { workspaceRoot } from "./lib/workspace.js";
|
|
16
|
+
const WORKSPACE = workspaceRoot();
|
|
12
17
|
// NOX_WATCH_DIRS: comma-separated list of ABSOLUTE paths to watch.
|
|
13
18
|
// If unset, falls back to the default OpenClaw workspace layout below.
|
|
14
19
|
// Example: NOX_WATCH_DIRS=/data/memory,/data/shared
|
|
@@ -60,9 +65,23 @@ function shouldProcess(filepath) {
|
|
|
60
65
|
// Debounce map: filepath → timer
|
|
61
66
|
const debounceMap = new Map();
|
|
62
67
|
const DEBOUNCE_MS = 2000;
|
|
68
|
+
function tombstoneMissing(filepath) {
|
|
69
|
+
const rel = relative(WORKSPACE, filepath);
|
|
70
|
+
if (rel.startsWith(".."))
|
|
71
|
+
return; // NOX_WATCH_DIRS outside the workspace: no source_file to match
|
|
72
|
+
try {
|
|
73
|
+
const r = tombstoneFile(getDb(), rel, existsSync(filepath), "deleted");
|
|
74
|
+
if (r.status === "tombstoned") {
|
|
75
|
+
console.log(`[WATCH] ${new Date().toISOString()} tombstoned ${r.chunks} chunks ← ${rel} (kept; review with: nox-mem tombstones)`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
console.error(`[WATCH] Error tombstoning ${filepath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
63
82
|
async function processFile(filepath) {
|
|
64
83
|
if (!existsSync(filepath))
|
|
65
|
-
return; // deleted
|
|
84
|
+
return tombstoneMissing(filepath); // deleted or renamed away
|
|
66
85
|
try {
|
|
67
86
|
const stat = statSync(filepath);
|
|
68
87
|
if (!stat.isFile())
|
|
@@ -72,8 +91,10 @@ async function processFile(filepath) {
|
|
|
72
91
|
if (stat.size > 5 * 1024 * 1024)
|
|
73
92
|
return; // skip > 5MB
|
|
74
93
|
const result = await routeIngest(filepath);
|
|
75
|
-
|
|
76
|
-
|
|
94
|
+
const changed = (result.inserted?.length ?? 0) + (result.deleted ?? 0) + (result.adopted ?? 0);
|
|
95
|
+
if (result && changed > 0) {
|
|
96
|
+
console.log(`[WATCH] ${new Date().toISOString()} +${result.inserted?.length ?? 0} new, -${result.deleted ?? 0} removed, ` +
|
|
97
|
+
`${result.kept ?? 0} kept, ${result.adopted ?? 0} adopted ← ${filepath.replace(WORKSPACE, "")}`);
|
|
77
98
|
}
|
|
78
99
|
}
|
|
79
100
|
catch (err) {
|
|
@@ -93,6 +114,42 @@ function debounceIngest(filepath) {
|
|
|
93
114
|
}, DEBOUNCE_MS);
|
|
94
115
|
debounceMap.set(filepath, timer);
|
|
95
116
|
}
|
|
117
|
+
function walkFiles(dir) {
|
|
118
|
+
const out = [];
|
|
119
|
+
try {
|
|
120
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
121
|
+
const p = resolve(dir, e.name);
|
|
122
|
+
if (e.isDirectory())
|
|
123
|
+
out.push(...walkFiles(p));
|
|
124
|
+
else if (e.isFile() && shouldProcess(p))
|
|
125
|
+
out.push(p);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch { }
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
function debounceTombstoneDir(dirpath) {
|
|
132
|
+
const key = `dir:${dirpath}`;
|
|
133
|
+
const existing = debounceMap.get(key);
|
|
134
|
+
if (existing)
|
|
135
|
+
clearTimeout(existing);
|
|
136
|
+
debounceMap.set(key, setTimeout(() => {
|
|
137
|
+
debounceMap.delete(key);
|
|
138
|
+
if (existsSync(dirpath))
|
|
139
|
+
return;
|
|
140
|
+
const rel = relative(WORKSPACE, dirpath);
|
|
141
|
+
if (rel.startsWith("..") || rel === "")
|
|
142
|
+
return;
|
|
143
|
+
try {
|
|
144
|
+
const r = tombstonePrefix(getDb(), rel, (p) => existsSync(resolve(WORKSPACE, p)), "deleted");
|
|
145
|
+
if (r.files > 0)
|
|
146
|
+
console.log(`[WATCH] ${new Date().toISOString()} tombstoned ${r.files} files (${r.chunks} chunks kept) ← ${rel}/`);
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
console.error(`[WATCH] Error tombstoning ${dirpath}/: ${err instanceof Error ? err.message : String(err)}`);
|
|
150
|
+
}
|
|
151
|
+
}, DEBOUNCE_MS));
|
|
152
|
+
}
|
|
96
153
|
export function startWatch(verbose = false) {
|
|
97
154
|
let watcherCount = 0;
|
|
98
155
|
const started = [];
|
|
@@ -107,8 +164,25 @@ export function startWatch(verbose = false) {
|
|
|
107
164
|
if (!filename)
|
|
108
165
|
return;
|
|
109
166
|
const filepath = resolve(dir, filename);
|
|
110
|
-
if (
|
|
167
|
+
if (SKIP_PATTERNS.some((p) => p.test(filepath)))
|
|
168
|
+
return;
|
|
169
|
+
if (!shouldProcess(filepath)) {
|
|
170
|
+
// A directory moved in arrives as ONE event: ingest what is inside it.
|
|
171
|
+
// A path without an allowed extension that is gone may have been a
|
|
172
|
+
// directory moved out or removed: tombstone what was stored under it.
|
|
173
|
+
let isDir = false;
|
|
174
|
+
try {
|
|
175
|
+
isDir = statSync(filepath).isDirectory();
|
|
176
|
+
}
|
|
177
|
+
catch { }
|
|
178
|
+
if (isDir)
|
|
179
|
+
walkFiles(filepath).forEach(debounceIngest);
|
|
180
|
+
// (no extname test: a directory may be named `projeto.v1`; a path that
|
|
181
|
+
// was never a directory simply matches nothing under its prefix)
|
|
182
|
+
else if (!existsSync(filepath))
|
|
183
|
+
debounceTombstoneDir(filepath);
|
|
111
184
|
return;
|
|
185
|
+
}
|
|
112
186
|
debounceIngest(filepath);
|
|
113
187
|
});
|
|
114
188
|
watcherCount++;
|