nox-mem 3.5.1 → 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/crystallize.js +2 -2
- package/dist/db.js +87 -2
- package/dist/digest.js +2 -1
- package/dist/embed.js +23 -2
- 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/ingest.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { readFileSync } from "fs";
|
|
2
|
-
import { relative } from "path";
|
|
1
|
+
import { existsSync, readFileSync } from "fs";
|
|
2
|
+
import { relative, resolve } from "path";
|
|
3
3
|
import { getDb } from "./db.js";
|
|
4
|
+
import { syncFileChunks } from "./lib/chunk-sync.js";
|
|
4
5
|
import { getInitialTier, getInitialImportance } from "./tier-manager.js";
|
|
5
6
|
import { resolveRetention } from "./retention.js";
|
|
6
7
|
import { inferPain, inferImportance } from "./salience.js";
|
|
7
8
|
import { redact } from "./privacy/filter.js";
|
|
8
|
-
|
|
9
|
+
import { workspaceRoot } from "./lib/workspace.js";
|
|
10
|
+
const WORKSPACE = workspaceRoot();
|
|
9
11
|
const TYPE_MAP = {
|
|
10
12
|
"memory/decisions.md": "decision",
|
|
11
13
|
"memory/lessons.md": "lesson",
|
|
@@ -123,23 +125,18 @@ function sanitizeUtf8(text) {
|
|
|
123
125
|
.replace(/\u00c3\u00aa/g, "ê")
|
|
124
126
|
.replace(/\u00c3\u00a2/g, "â");
|
|
125
127
|
}
|
|
128
|
+
const EMPTY = { chunks: 0, inserted: [], kept: 0, deleted: 0, adopted: 0 };
|
|
126
129
|
/**
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
130
|
+
* Synchronous core: read, redact, chunk, and diff into the DB (chunk-sync.ts).
|
|
131
|
+
* No await inside, so a caller can run many files in one transaction (reindex).
|
|
132
|
+
* An empty file changes nothing — it is not read as "delete every chunk".
|
|
130
133
|
*/
|
|
131
|
-
export
|
|
132
|
-
const db = externalDb || getDb();
|
|
134
|
+
export function ingestMarkdownSync(db, filePath) {
|
|
133
135
|
const relPath = relative(WORKSPACE, filePath);
|
|
134
|
-
// A2 (2026-04-25): entity routing
|
|
135
|
-
// ingestFile() é agora handler de markdown puro; callers devem usar routeIngest()
|
|
136
|
-
// pra ter routing automático. Fallback path (forceMarkdown) chama ingestFile direto.
|
|
136
|
+
// A2 (2026-04-25): entity routing lives in lib/ingest-router.ts — single dispatch.
|
|
137
137
|
let content = readFileSync(filePath, "utf-8");
|
|
138
|
-
if (!content.trim())
|
|
139
|
-
|
|
140
|
-
db.close();
|
|
141
|
-
return { chunks: 0 };
|
|
142
|
-
}
|
|
138
|
+
if (!content.trim())
|
|
139
|
+
return EMPTY;
|
|
143
140
|
// Sanitize UTF-8
|
|
144
141
|
content = sanitizeUtf8(content);
|
|
145
142
|
// Privacy filter: redact secrets/PII before storage (staged-privacy)
|
|
@@ -157,10 +154,6 @@ export async function ingestFile(filePath, externalDb, skipDelete) {
|
|
|
157
154
|
: null);
|
|
158
155
|
const isJson = filePath.endsWith(".json");
|
|
159
156
|
const textChunks = isJson ? chunkJson(content) : chunkMarkdown(content);
|
|
160
|
-
// Skip delete if called from reindex (table already cleared)
|
|
161
|
-
if (!skipDelete) {
|
|
162
|
-
db.prepare("DELETE FROM chunks WHERE source_file = ?").run(relPath);
|
|
163
|
-
}
|
|
164
157
|
const tier = getInitialTier(chunkType);
|
|
165
158
|
// Fase 1.7b-b — use smarter importance heuristic (falls back to initial if type unknown).
|
|
166
159
|
// source_type is not known at ingest time for markdown (set post-ingest via migration);
|
|
@@ -169,42 +162,73 @@ export async function ingestFile(filePath, externalDb, skipDelete) {
|
|
|
169
162
|
// Fase 1.7b-a — retention resolved once per file; per-chunk override via HTML
|
|
170
163
|
// comment applies to the whole file (not per-chunk, to keep semantics simple).
|
|
171
164
|
const retentionDays = resolveRetention(chunkType, content);
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
165
|
+
const desired = textChunks.map((text) => ({
|
|
166
|
+
chunk_text: text,
|
|
167
|
+
section: null,
|
|
168
|
+
chunk_type: chunkType,
|
|
169
|
+
source_date: sourceDate,
|
|
170
|
+
metadata: null,
|
|
171
|
+
tier,
|
|
172
|
+
importance: baseImportance,
|
|
173
|
+
retention_days: retentionDays,
|
|
174
|
+
// Fase 1.7b-b — pain is per-chunk (text-driven); importance is per-file (type-driven).
|
|
175
|
+
pain: inferPain(chunkType, text),
|
|
176
|
+
section_boost: null,
|
|
177
|
+
}));
|
|
178
|
+
const r = syncFileChunks(db, relPath, desired, { existsOnDisk: (p) => existsSync(resolve(WORKSPACE, p)) });
|
|
179
|
+
return { chunks: textChunks.length, inserted: r.inserted, kept: r.kept, deleted: r.deleted, adopted: r.adopted };
|
|
180
|
+
}
|
|
181
|
+
/** Max chunks embedded inline per ingest; the 4-hourly `vectorize` catches up the rest. */
|
|
182
|
+
const INLINE_EMBED_CAP = 20;
|
|
183
|
+
/**
|
|
184
|
+
* Embed the rows an ingest just created. Kept rows already have their vector —
|
|
185
|
+
* re-embedding unchanged text is what the NOOP exists to avoid.
|
|
186
|
+
*/
|
|
187
|
+
export async function embedInserted(db, ids) {
|
|
188
|
+
if (ids.length === 0 || !process.env.GEMINI_API_KEY)
|
|
189
|
+
return 0;
|
|
190
|
+
let embedded = 0;
|
|
191
|
+
try {
|
|
192
|
+
const { embedDocument, ensureVecTable, upsertEmbedding } = await import("./embed.js");
|
|
193
|
+
ensureVecTable(db);
|
|
194
|
+
const get = db.prepare("SELECT chunk_text FROM chunks WHERE id = ?");
|
|
195
|
+
for (const id of ids.slice(0, INLINE_EMBED_CAP)) {
|
|
196
|
+
const row = get.get(id);
|
|
197
|
+
if (!row)
|
|
198
|
+
continue;
|
|
199
|
+
try {
|
|
200
|
+
const emb = await embedDocument(row.chunk_text);
|
|
201
|
+
if (emb && emb.length > 0) {
|
|
202
|
+
upsertEmbedding(db, id, emb);
|
|
203
|
+
embedded++;
|
|
199
204
|
}
|
|
200
|
-
catch {
|
|
201
|
-
break;
|
|
202
|
-
} // Stop on first API error (rate limit)
|
|
203
205
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
+
catch {
|
|
207
|
+
break;
|
|
208
|
+
} // Stop on first API error (rate limit)
|
|
206
209
|
}
|
|
207
|
-
catch { }
|
|
208
210
|
}
|
|
209
|
-
|
|
211
|
+
catch { }
|
|
212
|
+
return embedded;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* @param filePath — absolute path to .md or .json file
|
|
216
|
+
* @param externalDb — optional db connection; reindex passes one and vectorizes in batch afterwards
|
|
217
|
+
*
|
|
218
|
+
* Never closes the connection. It used to `db.close()` the getDb() singleton,
|
|
219
|
+
* which pulled the handle out from under any caller holding it (withOpAudit,
|
|
220
|
+
* the API and MCP servers): an op wrapping ingest ended `failed` with its work
|
|
221
|
+
* done (HANDOFF 2026-10-14). Closing is the CLI entry point's job (closeDb()).
|
|
222
|
+
*/
|
|
223
|
+
export async function ingestFile(filePath, externalDb) {
|
|
224
|
+
const db = externalDb || getDb();
|
|
225
|
+
const result = ingestMarkdownSync(db, filePath);
|
|
226
|
+
// Auto-vectorize direct ingests only. Reindex passes externalDb and is followed
|
|
227
|
+
// by a batch vectorize phase; embedding per file there is too expensive.
|
|
228
|
+
if (!externalDb) {
|
|
229
|
+
const embedded = await embedInserted(db, result.inserted);
|
|
230
|
+
if (embedded > 0)
|
|
231
|
+
console.log("[INGEST] Auto-vectorized " + embedded + " chunks");
|
|
232
|
+
}
|
|
233
|
+
return result;
|
|
210
234
|
}
|
|
@@ -33,7 +33,7 @@ export function __setRawSearchForTests(fn) {
|
|
|
33
33
|
*/
|
|
34
34
|
async function defaultRawSearch(question, topK, filter) {
|
|
35
35
|
// trackAccess stays at its default (true), exactly as before the filter existed.
|
|
36
|
-
const hits = await searchHybrid(question, topK, true, filter);
|
|
36
|
+
const hits = await searchHybrid(question, topK, true, filter, { surface: "answer", agent: process.env.NOX_AGENT_NAME });
|
|
37
37
|
return hits.map((h) => ({
|
|
38
38
|
chunk_id: h.id ?? 0,
|
|
39
39
|
file_path: h.source_file,
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// chunk-sync.ts — write path without loss (ROADMAP v6 item 3, 2026-10-14).
|
|
2
|
+
//
|
|
3
|
+
// Before this module every ingest did `DELETE FROM chunks WHERE source_file = ?`
|
|
4
|
+
// and re-inserted the whole file. Re-saving a file with one word changed gave
|
|
5
|
+
// EVERY chunk of it a new id, which broke whatever pointed at the old ids
|
|
6
|
+
// (brief_log, search_telemetry.top_chunk_ids, kg_relations.evidence_chunk_id)
|
|
7
|
+
// and threw away embeddings that had already been paid for.
|
|
8
|
+
//
|
|
9
|
+
// syncFileChunks() diffs instead. The key is (section, chunk_text):
|
|
10
|
+
// - a chunk whose key is already stored for the file KEEPS its row: same id,
|
|
11
|
+
// same vector, same access history (tier, access_count, importance);
|
|
12
|
+
// - a new key is INSERTed;
|
|
13
|
+
// - a stored key the file no longer produces is DELETEd (the text was edited
|
|
14
|
+
// away; that is the file's own content changing, not a loss);
|
|
15
|
+
// - when the file has no rows yet, a WHOLE tombstoned file is ADOPTED
|
|
16
|
+
// (re-pointed to the new path) when every one of its rows has a key in the
|
|
17
|
+
// new file — that is how a rename keeps ids. Never paragraph by paragraph:
|
|
18
|
+
// a shared paragraph is not a rename, and an adopted row would later be
|
|
19
|
+
// "edited away" from a file it never belonged to (Codex, nox-workspace#56).
|
|
20
|
+
//
|
|
21
|
+
// Matching is a multiset: a file that legitimately repeats a paragraph keeps
|
|
22
|
+
// one row per occurrence. When the DB holds MORE copies than the file (the
|
|
23
|
+
// pre-2026-09-28 reindex doubled content), the copy holding an embedding is the
|
|
24
|
+
// one kept, then the lowest id.
|
|
25
|
+
//
|
|
26
|
+
// No ranking/scoring change lives here (CLAUDE.md rule 5).
|
|
27
|
+
import { ensureTombstoneTable, resolveTombstoneOnIngest } from "./tombstone.js";
|
|
28
|
+
const keyOf = (section, text) => `${section ?? ""}\u0000${text}`;
|
|
29
|
+
function embeddedAmong(db, ids) {
|
|
30
|
+
if (ids.length === 0)
|
|
31
|
+
return new Set();
|
|
32
|
+
try {
|
|
33
|
+
const out = new Set();
|
|
34
|
+
// chunk the IN list: SQLite's default variable limit is 32766, files are far smaller
|
|
35
|
+
for (let i = 0; i < ids.length; i += 500) {
|
|
36
|
+
const part = ids.slice(i, i + 500);
|
|
37
|
+
const rows = db
|
|
38
|
+
.prepare(`SELECT chunk_id FROM vec_chunk_map WHERE chunk_id IN (${part.map(() => "?").join(",")})`)
|
|
39
|
+
.all(...part);
|
|
40
|
+
for (const r of rows)
|
|
41
|
+
out.add(r.chunk_id);
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return new Set(); // no vector map yet (fresh / keyless install)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** key → rows, best candidate first (embedded, then lowest id). */
|
|
50
|
+
function bucket(rows, embedded) {
|
|
51
|
+
const m = new Map();
|
|
52
|
+
for (const r of rows) {
|
|
53
|
+
const k = keyOf(r.section, r.chunk_text);
|
|
54
|
+
const list = m.get(k);
|
|
55
|
+
if (list)
|
|
56
|
+
list.push(r);
|
|
57
|
+
else
|
|
58
|
+
m.set(k, [r]);
|
|
59
|
+
}
|
|
60
|
+
for (const list of m.values()) {
|
|
61
|
+
list.sort((a, b) => {
|
|
62
|
+
const ae = embedded.has(a.id), be = embedded.has(b.id);
|
|
63
|
+
if (ae !== be)
|
|
64
|
+
return ae ? -1 : 1;
|
|
65
|
+
return a.id - b.id;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return m;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Make the stored chunks of `relPath` equal to `desired`, touching only what
|
|
72
|
+
* changed. Runs in one transaction (a savepoint when the caller already holds one).
|
|
73
|
+
*/
|
|
74
|
+
export function syncFileChunks(db, relPath, desired, opts = {}) {
|
|
75
|
+
ensureTombstoneTable(db);
|
|
76
|
+
const run = db.transaction(() => {
|
|
77
|
+
const stored = db
|
|
78
|
+
.prepare("SELECT id, chunk_text, section, retention_days, source_file, tier FROM chunks WHERE source_file = ?")
|
|
79
|
+
.all(relPath);
|
|
80
|
+
const own = bucket(stored, embeddedAmong(db, stored.map((r) => r.id)));
|
|
81
|
+
// Rename: only a path with no rows can adopt, only WHOLE files, and only from
|
|
82
|
+
// tombstones the watcher OBSERVED being deleted/moved (reason 'deleted').
|
|
83
|
+
// Never from 'missing-at-reindex': reindex tombstones every file absent from
|
|
84
|
+
// disk, including those D-2026-09-30 keeps on purpose (Codex, #56).
|
|
85
|
+
const foreign = new Map();
|
|
86
|
+
if (stored.length === 0 && desired.length > 0) {
|
|
87
|
+
const candidates = db
|
|
88
|
+
.prepare(`SELECT c.id, c.chunk_text, c.section, c.retention_days, c.source_file, c.tier
|
|
89
|
+
FROM chunks c JOIN chunk_tombstones t ON t.source_file = c.source_file
|
|
90
|
+
WHERE t.kept_at IS NULL AND t.reason = 'deleted' AND c.source_file != ?`)
|
|
91
|
+
.all(relPath);
|
|
92
|
+
if (candidates.length > 0) {
|
|
93
|
+
const want = new Map();
|
|
94
|
+
for (const d of desired) {
|
|
95
|
+
const k = keyOf(d.section, d.chunk_text);
|
|
96
|
+
want.set(k, (want.get(k) ?? 0) + 1);
|
|
97
|
+
}
|
|
98
|
+
const byFile = new Map();
|
|
99
|
+
for (const c of candidates) {
|
|
100
|
+
const list = byFile.get(c.source_file);
|
|
101
|
+
if (list)
|
|
102
|
+
list.push(c);
|
|
103
|
+
else
|
|
104
|
+
byFile.set(c.source_file, [c]);
|
|
105
|
+
}
|
|
106
|
+
// Largest file first; a file is adopted only if ALL its rows fit in what
|
|
107
|
+
// the new file still has unclaimed.
|
|
108
|
+
for (const rowsOfFile of [...byFile.values()].sort((a, b) => b.length - a.length)) {
|
|
109
|
+
if (opts.existsOnDisk?.(rowsOfFile[0].source_file))
|
|
110
|
+
continue;
|
|
111
|
+
const need = new Map();
|
|
112
|
+
for (const r of rowsOfFile) {
|
|
113
|
+
const k = keyOf(r.section, r.chunk_text);
|
|
114
|
+
need.set(k, (need.get(k) ?? 0) + 1);
|
|
115
|
+
}
|
|
116
|
+
if (![...need].every(([k, n]) => (want.get(k) ?? 0) >= n))
|
|
117
|
+
continue;
|
|
118
|
+
for (const [k, n] of need)
|
|
119
|
+
want.set(k, want.get(k) - n);
|
|
120
|
+
const embedded = embeddedAmong(db, rowsOfFile.map((r) => r.id));
|
|
121
|
+
for (const [k, list] of bucket(rowsOfFile, embedded)) {
|
|
122
|
+
const cur = foreign.get(k);
|
|
123
|
+
if (cur)
|
|
124
|
+
cur.push(...list);
|
|
125
|
+
else
|
|
126
|
+
foreign.set(k, list);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const insert = db.prepare(`INSERT INTO chunks (source_file, chunk_text, chunk_type, source_date, metadata, tier, importance, retention_days, pain, section, section_boost)
|
|
132
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
133
|
+
// `core` rows keep retention_days = NULL (never decay) — the same contract
|
|
134
|
+
// reindex enforces; re-deriving it from the file type would move salience.
|
|
135
|
+
const setRetention = db.prepare("UPDATE chunks SET retention_days = ? WHERE id = ? AND COALESCE(tier, '') != 'core'");
|
|
136
|
+
const adopt = db.prepare("UPDATE chunks SET source_file = ?, retention_days = CASE WHEN tier = 'core' THEN NULL ELSE ? END WHERE id = ?");
|
|
137
|
+
const refresh = opts.refreshKept;
|
|
138
|
+
const refreshSql = [
|
|
139
|
+
refresh?.pain ? "pain = @pain" : "",
|
|
140
|
+
refresh?.metadata ? "metadata = @metadata" : "",
|
|
141
|
+
refresh?.importance ? "importance = @importance" : "",
|
|
142
|
+
].filter(Boolean);
|
|
143
|
+
const setRefreshed = refreshSql.length > 0
|
|
144
|
+
? db.prepare(`UPDATE chunks SET ${refreshSql.join(", ")} WHERE id = @id`)
|
|
145
|
+
: null;
|
|
146
|
+
const del = db.prepare("DELETE FROM chunks WHERE id = ?");
|
|
147
|
+
const ids = [];
|
|
148
|
+
const inserted = [];
|
|
149
|
+
let kept = 0;
|
|
150
|
+
let adopted = 0;
|
|
151
|
+
const adoptedFrom = new Set();
|
|
152
|
+
for (const d of desired) {
|
|
153
|
+
const k = keyOf(d.section, d.chunk_text);
|
|
154
|
+
const mine = own.get(k);
|
|
155
|
+
if (mine && mine.length > 0) {
|
|
156
|
+
const row = mine.shift();
|
|
157
|
+
// retention is resolved per file from its content (an HTML-comment
|
|
158
|
+
// override can change without the chunk changing); everything else on a
|
|
159
|
+
// kept row is history worth keeping.
|
|
160
|
+
if (row.retention_days !== d.retention_days && row.tier !== "core")
|
|
161
|
+
setRetention.run(d.retention_days, row.id);
|
|
162
|
+
// Values the caller set EXPLICITLY (e.g. Paper 2's adjudicated pain and
|
|
163
|
+
// metadata) must land even when the text is unchanged (Codex, #56).
|
|
164
|
+
setRefreshed?.run({ id: row.id, pain: d.pain, metadata: d.metadata, importance: d.importance });
|
|
165
|
+
ids.push(row.id);
|
|
166
|
+
kept++;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
const theirs = foreign.get(k);
|
|
170
|
+
if (theirs && theirs.length > 0) {
|
|
171
|
+
const row = theirs.shift();
|
|
172
|
+
adopt.run(relPath, d.retention_days, row.id);
|
|
173
|
+
// explicit values land on adopted rows too, not only on kept ones (Codex, #56 r2)
|
|
174
|
+
setRefreshed?.run({ id: row.id, pain: d.pain, metadata: d.metadata, importance: d.importance });
|
|
175
|
+
adoptedFrom.add(row.source_file);
|
|
176
|
+
ids.push(row.id);
|
|
177
|
+
adopted++;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
const info = insert.run(relPath, d.chunk_text, d.chunk_type, d.source_date, d.metadata, d.tier, d.importance, d.retention_days, d.pain, d.section, d.section_boost);
|
|
181
|
+
const id = Number(info.lastInsertRowid);
|
|
182
|
+
ids.push(id);
|
|
183
|
+
inserted.push(id);
|
|
184
|
+
}
|
|
185
|
+
let deleted = 0;
|
|
186
|
+
for (const rest of own.values())
|
|
187
|
+
for (const r of rest)
|
|
188
|
+
deleted += del.run(r.id).changes;
|
|
189
|
+
resolveTombstoneOnIngest(db, relPath, [...adoptedFrom]);
|
|
190
|
+
return { ids, kept, inserted, deleted, adopted };
|
|
191
|
+
});
|
|
192
|
+
// IMMEDIATE takes the write lock before the read: two ingests of the same new
|
|
193
|
+
// file (watcher + a manual CLI run) would otherwise both see "no rows" in
|
|
194
|
+
// their WAL snapshot and insert it twice (Kimi, #56). Nested inside a
|
|
195
|
+
// caller's transaction (reindex, Paper 2) this is a savepoint as before.
|
|
196
|
+
return db.inTransaction ? run() : run.immediate();
|
|
197
|
+
}
|
package/dist/lib/ingest-many.js
CHANGED
|
@@ -34,7 +34,9 @@ export async function ingestMany(paths, deps) {
|
|
|
34
34
|
}
|
|
35
35
|
try {
|
|
36
36
|
const r = await deps.ingestOne(path);
|
|
37
|
-
|
|
37
|
+
const diff = r.kept === undefined ? "" :
|
|
38
|
+
` — ${r.inserted?.length ?? 0} new, ${r.kept} unchanged, ${r.deleted ?? 0} removed${r.adopted ? `, ${r.adopted} adopted` : ""}`;
|
|
39
|
+
deps.log(`[INFO] Ingested ${path}: ${r.chunks} chunks${diff} (kind=${r.kind}, via=${r.routedTo})`);
|
|
38
40
|
ok++;
|
|
39
41
|
}
|
|
40
42
|
catch (err) {
|
|
@@ -9,9 +9,13 @@
|
|
|
9
9
|
// Defesa em camadas: ingestFile() ainda tem guard interno pra entity files (caso
|
|
10
10
|
// algum legacy caller pule o router). Mas o router é o caminho canônico daqui em diante.
|
|
11
11
|
import { relative } from "node:path";
|
|
12
|
-
import { ingestFile } from "../ingest.js";
|
|
13
|
-
import { ingestEntityFile } from "../ingest-entity.js";
|
|
14
|
-
|
|
12
|
+
import { ingestFile, ingestMarkdownSync } from "../ingest.js";
|
|
13
|
+
import { ingestEntityFile, ingestEntitySync } from "../ingest-entity.js";
|
|
14
|
+
import { workspaceRoot } from "./workspace.js";
|
|
15
|
+
const WORKSPACE = workspaceRoot();
|
|
16
|
+
const diffOf = (r) => ({
|
|
17
|
+
inserted: r.inserted, kept: r.kept, deleted: r.deleted, adopted: r.adopted,
|
|
18
|
+
});
|
|
15
19
|
/**
|
|
16
20
|
* Detect ingest kind from path conventions. Centralizada aqui — mexer só nesse
|
|
17
21
|
* arquivo quando adicionar novo tipo (ex: "pdf-text-layer", "fathom-transcript").
|
|
@@ -35,26 +39,45 @@ export async function routeIngest(filePath, opts = {}) {
|
|
|
35
39
|
case "entity": {
|
|
36
40
|
const r = await ingestEntityFile(filePath, opts.externalDb);
|
|
37
41
|
if (r.parsed)
|
|
38
|
-
return { chunks: r.chunks, kind: "entity", routedTo: "ingestEntityFile" };
|
|
42
|
+
return { chunks: r.chunks, kind: "entity", routedTo: "ingestEntityFile", ...diffOf(r) };
|
|
39
43
|
// Entity file failed parse — fall through to markdown ingest pra não perder dado
|
|
40
|
-
const fallback = await ingestFile(filePath, opts.externalDb
|
|
41
|
-
return { chunks: fallback.chunks, kind: "markdown", routedTo: "ingestFile (fallback after entity parse fail)" };
|
|
44
|
+
const fallback = await ingestFile(filePath, opts.externalDb);
|
|
45
|
+
return { chunks: fallback.chunks, kind: "markdown", routedTo: "ingestFile (fallback after entity parse fail)", ...diffOf(fallback) };
|
|
42
46
|
}
|
|
43
47
|
case "graphify":
|
|
44
48
|
// Hoje não existe graphify-ingest separado pra arquivos individuais (graphify
|
|
45
49
|
// produz JSON em batch via skill própria). Cair no markdown como tratamento neutro.
|
|
46
50
|
// Reservado pra Wave 2+ se virar handler dedicado.
|
|
47
|
-
return await ingestFile(filePath, opts.externalDb
|
|
51
|
+
return await ingestFile(filePath, opts.externalDb).then((r) => ({
|
|
48
52
|
chunks: r.chunks,
|
|
49
53
|
kind: "graphify",
|
|
50
54
|
routedTo: "ingestFile (graphify path neutralized)",
|
|
55
|
+
...diffOf(r),
|
|
51
56
|
}));
|
|
52
57
|
case "markdown":
|
|
53
58
|
default:
|
|
54
|
-
return await ingestFile(filePath, opts.externalDb
|
|
59
|
+
return await ingestFile(filePath, opts.externalDb).then((r) => ({
|
|
55
60
|
chunks: r.chunks,
|
|
56
61
|
kind: "markdown",
|
|
57
62
|
routedTo: "ingestFile",
|
|
63
|
+
...diffOf(r),
|
|
58
64
|
}));
|
|
59
65
|
}
|
|
60
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* Synchronous dispatch for reindex, which runs every file inside ONE
|
|
69
|
+
* transaction so its wipe guard can roll back before commit. Same routing as
|
|
70
|
+
* routeIngest; no inline embedding (reindex vectorizes in batch afterwards).
|
|
71
|
+
*/
|
|
72
|
+
export function routeIngestSync(db, filePath) {
|
|
73
|
+
const kind = detectIngestKind(filePath);
|
|
74
|
+
if (kind === "entity") {
|
|
75
|
+
const r = ingestEntitySync(db, filePath);
|
|
76
|
+
if (r.parsed)
|
|
77
|
+
return { chunks: r.chunks, kind: "entity", routedTo: "ingestEntitySync", ...diffOf(r) };
|
|
78
|
+
const fallback = ingestMarkdownSync(db, filePath);
|
|
79
|
+
return { chunks: fallback.chunks, kind: "markdown", routedTo: "ingestMarkdownSync (fallback after entity parse fail)", ...diffOf(fallback) };
|
|
80
|
+
}
|
|
81
|
+
const r = ingestMarkdownSync(db, filePath);
|
|
82
|
+
return { chunks: r.chunks, kind, routedTo: "ingestMarkdownSync", ...diffOf(r) };
|
|
83
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
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
|
+
export function listTombstones(db, opts = {}) {
|
|
114
|
+
ensureTombstoneTable(db);
|
|
115
|
+
const rows = db
|
|
116
|
+
.prepare(`SELECT t.*,
|
|
117
|
+
(SELECT COUNT(*) FROM chunks c WHERE c.source_file = t.source_file) AS live_chunks,
|
|
118
|
+
(SELECT COUNT(*) FROM chunks c
|
|
119
|
+
WHERE c.source_file = t.source_file
|
|
120
|
+
AND EXISTS (SELECT 1 FROM chunks o
|
|
121
|
+
WHERE o.chunk_text = c.chunk_text AND o.source_file != c.source_file)
|
|
122
|
+
) AS duplicated_elsewhere
|
|
123
|
+
FROM chunk_tombstones t
|
|
124
|
+
ORDER BY t.tombstoned_at, t.source_file`)
|
|
125
|
+
.all();
|
|
126
|
+
return opts.all ? rows : rows.filter((r) => r.live_chunks > 0 && r.kept_at === null);
|
|
127
|
+
}
|
|
128
|
+
/** Review outcome "keep": content stays, tombstone leaves the default listing. */
|
|
129
|
+
export function keepTombstone(db, relPath) {
|
|
130
|
+
ensureTombstoneTable(db);
|
|
131
|
+
return db.prepare("UPDATE chunk_tombstones SET kept_at = datetime('now') WHERE source_file = ? AND kept_at IS NULL")
|
|
132
|
+
.run(relPath).changes > 0;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The ONLY place that deletes a tombstoned file's chunks. Callers wrap it in
|
|
136
|
+
* withOpAudit (snapshot first). Refuses when the file is back on disk, when it
|
|
137
|
+
* was never tombstoned, or when it was reviewed as kept.
|
|
138
|
+
*/
|
|
139
|
+
export function purgeTombstone(db, relPath, existsOnDisk, opts = {}) {
|
|
140
|
+
ensureTombstoneTable(db);
|
|
141
|
+
if (existsOnDisk)
|
|
142
|
+
return { refused: "exists-on-disk", chunks: 0 };
|
|
143
|
+
const t = db.prepare("SELECT kept_at FROM chunk_tombstones WHERE source_file = ?").get(relPath);
|
|
144
|
+
if (!t)
|
|
145
|
+
return { refused: "no-tombstone", chunks: 0 };
|
|
146
|
+
if (t.kept_at !== null)
|
|
147
|
+
return { refused: "kept", chunks: 0 };
|
|
148
|
+
const chunks = db.prepare("SELECT COUNT(*) AS c FROM chunks WHERE source_file = ?").get(relPath).c;
|
|
149
|
+
if (opts.dryRun)
|
|
150
|
+
return { chunks };
|
|
151
|
+
db.transaction(() => {
|
|
152
|
+
db.prepare("DELETE FROM chunks WHERE source_file = ?").run(relPath);
|
|
153
|
+
db.prepare("DELETE FROM chunk_tombstones WHERE source_file = ?").run(relPath);
|
|
154
|
+
})();
|
|
155
|
+
return { chunks };
|
|
156
|
+
}
|
|
@@ -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
|
+
}
|
package/dist/mcp-server.js
CHANGED
|
@@ -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
|
}
|