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.
- package/README.md +12 -4
- package/dist/api/brief.js +15 -1
- 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/embed.js +10 -3
- package/dist/index.js +112 -2
- package/dist/ingest-entity.js +69 -59
- package/dist/ingest.js +131 -56
- 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 +168 -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,14 @@
|
|
|
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";
|
|
5
|
+
import { ensureTombstoneTable, resolveTombstoneOnIngest } from "./lib/tombstone.js";
|
|
4
6
|
import { getInitialTier, getInitialImportance } from "./tier-manager.js";
|
|
5
7
|
import { resolveRetention } from "./retention.js";
|
|
6
8
|
import { inferPain, inferImportance } from "./salience.js";
|
|
7
9
|
import { redact } from "./privacy/filter.js";
|
|
8
|
-
|
|
10
|
+
import { workspaceRoot } from "./lib/workspace.js";
|
|
11
|
+
const WORKSPACE = workspaceRoot();
|
|
9
12
|
const TYPE_MAP = {
|
|
10
13
|
"memory/decisions.md": "decision",
|
|
11
14
|
"memory/lessons.md": "lesson",
|
|
@@ -40,6 +43,52 @@ export function extractDate(relPath) {
|
|
|
40
43
|
const match = relPath.match(/(\d{4}-\d{2}-\d{2})/);
|
|
41
44
|
return match ? match[1] : null;
|
|
42
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* Hard ceiling on a chunk, in characters (2026-10-15). The word-count split below never fires on text
|
|
48
|
+
* with few spaces or no blank lines (CSV rows, OCR output), which left chunks of up to 1 MB; the embedding
|
|
49
|
+
* model reads ~2,048 tokens. Production text measured 1.6-3.9 chars/token, so 4,000 chars stays near
|
|
50
|
+
* 2,048 tokens even for CSV, and sits above the ~3-3.5 KB of a 500-word prose chunk.
|
|
51
|
+
*/
|
|
52
|
+
export const MAX_CHUNK_CHARS = 4000;
|
|
53
|
+
/**
|
|
54
|
+
* Splits a text over `max` characters: lines are packed up to the cap; a line longer than the cap is cut
|
|
55
|
+
* at the last space inside its window, or hard-cut when the window has none. Only whitespace at the cuts
|
|
56
|
+
* is dropped.
|
|
57
|
+
*/
|
|
58
|
+
export function capChunk(text, max = MAX_CHUNK_CHARS) {
|
|
59
|
+
if (text.length <= max)
|
|
60
|
+
return [text];
|
|
61
|
+
const out = [];
|
|
62
|
+
let buf = "";
|
|
63
|
+
const flush = () => {
|
|
64
|
+
if (buf.trim())
|
|
65
|
+
out.push(buf.trim());
|
|
66
|
+
buf = "";
|
|
67
|
+
};
|
|
68
|
+
for (const line of text.split("\n")) {
|
|
69
|
+
let rest = line;
|
|
70
|
+
// A line that fits on its own is never split: it starts a new chunk when the current one is full.
|
|
71
|
+
if (buf && buf.length + 1 + rest.length > max && rest.length <= max)
|
|
72
|
+
flush();
|
|
73
|
+
// A line over the cap fills the current chunk first (so a heading stays with its text), then the next.
|
|
74
|
+
while ((buf ? buf.length + 1 : 0) + rest.length > max) {
|
|
75
|
+
const room = max - (buf ? buf.length + 1 : 0);
|
|
76
|
+
if (room < max / 4) {
|
|
77
|
+
flush();
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
let cut = rest.lastIndexOf(" ", room);
|
|
81
|
+
if (cut < room / 2)
|
|
82
|
+
cut = room;
|
|
83
|
+
buf = buf ? `${buf}\n${rest.slice(0, cut)}` : rest.slice(0, cut);
|
|
84
|
+
flush();
|
|
85
|
+
rest = rest.slice(cut);
|
|
86
|
+
}
|
|
87
|
+
buf = buf ? `${buf}\n${rest}` : rest;
|
|
88
|
+
}
|
|
89
|
+
flush();
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
43
92
|
export function chunkMarkdown(content) {
|
|
44
93
|
const lines = content.split("\n");
|
|
45
94
|
const chunks = [];
|
|
@@ -83,13 +132,13 @@ export function chunkMarkdown(content) {
|
|
|
83
132
|
result.push(chunk);
|
|
84
133
|
}
|
|
85
134
|
}
|
|
86
|
-
return result.filter((c) => c.trim().length > 0);
|
|
135
|
+
return result.filter((c) => c.trim().length > 0).flatMap((c) => capChunk(c));
|
|
87
136
|
}
|
|
88
137
|
export function chunkJson(content) {
|
|
89
138
|
try {
|
|
90
139
|
const data = JSON.parse(content);
|
|
91
140
|
if (Array.isArray(data))
|
|
92
|
-
return data.map((item) => JSON.stringify(item, null, 2));
|
|
141
|
+
return data.map((item) => JSON.stringify(item, null, 2)).flatMap((c) => capChunk(c));
|
|
93
142
|
const chunks = [];
|
|
94
143
|
for (const [key, value] of Object.entries(data)) {
|
|
95
144
|
if (Array.isArray(value)) {
|
|
@@ -100,10 +149,10 @@ export function chunkJson(content) {
|
|
|
100
149
|
chunks.push(`${key}: ${JSON.stringify(value)}`);
|
|
101
150
|
}
|
|
102
151
|
}
|
|
103
|
-
return chunks.length > 0 ? chunks : [content];
|
|
152
|
+
return (chunks.length > 0 ? chunks : [content]).flatMap((c) => capChunk(c));
|
|
104
153
|
}
|
|
105
154
|
catch {
|
|
106
|
-
return
|
|
155
|
+
return capChunk(content);
|
|
107
156
|
}
|
|
108
157
|
}
|
|
109
158
|
/**
|
|
@@ -123,22 +172,21 @@ function sanitizeUtf8(text) {
|
|
|
123
172
|
.replace(/\u00c3\u00aa/g, "ê")
|
|
124
173
|
.replace(/\u00c3\u00a2/g, "â");
|
|
125
174
|
}
|
|
175
|
+
const EMPTY = { chunks: 0, inserted: [], kept: 0, deleted: 0, adopted: 0 };
|
|
126
176
|
/**
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
177
|
+
* Synchronous core: read, redact, chunk, and diff into the DB (chunk-sync.ts).
|
|
178
|
+
* No await inside, so a caller can run many files in one transaction (reindex).
|
|
179
|
+
* An empty file changes no chunk — it is not read as "delete every chunk". It is, however, a file on
|
|
180
|
+
* disk again, so a tombstone left when it was deleted is resolved (2026-10-15).
|
|
130
181
|
*/
|
|
131
|
-
export
|
|
132
|
-
const db = externalDb || getDb();
|
|
182
|
+
export function ingestMarkdownSync(db, filePath) {
|
|
133
183
|
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.
|
|
184
|
+
// A2 (2026-04-25): entity routing lives in lib/ingest-router.ts — single dispatch.
|
|
137
185
|
let content = readFileSync(filePath, "utf-8");
|
|
138
186
|
if (!content.trim()) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
return
|
|
187
|
+
ensureTombstoneTable(db);
|
|
188
|
+
resolveTombstoneOnIngest(db, relPath, []);
|
|
189
|
+
return EMPTY;
|
|
142
190
|
}
|
|
143
191
|
// Sanitize UTF-8
|
|
144
192
|
content = sanitizeUtf8(content);
|
|
@@ -157,10 +205,6 @@ export async function ingestFile(filePath, externalDb, skipDelete) {
|
|
|
157
205
|
: null);
|
|
158
206
|
const isJson = filePath.endsWith(".json");
|
|
159
207
|
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
208
|
const tier = getInitialTier(chunkType);
|
|
165
209
|
// Fase 1.7b-b — use smarter importance heuristic (falls back to initial if type unknown).
|
|
166
210
|
// source_type is not known at ingest time for markdown (set post-ingest via migration);
|
|
@@ -169,42 +213,73 @@ export async function ingestFile(filePath, externalDb, skipDelete) {
|
|
|
169
213
|
// Fase 1.7b-a — retention resolved once per file; per-chunk override via HTML
|
|
170
214
|
// comment applies to the whole file (not per-chunk, to keep semantics simple).
|
|
171
215
|
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
|
-
|
|
216
|
+
const desired = textChunks.map((text) => ({
|
|
217
|
+
chunk_text: text,
|
|
218
|
+
section: null,
|
|
219
|
+
chunk_type: chunkType,
|
|
220
|
+
source_date: sourceDate,
|
|
221
|
+
metadata: null,
|
|
222
|
+
tier,
|
|
223
|
+
importance: baseImportance,
|
|
224
|
+
retention_days: retentionDays,
|
|
225
|
+
// Fase 1.7b-b — pain is per-chunk (text-driven); importance is per-file (type-driven).
|
|
226
|
+
pain: inferPain(chunkType, text),
|
|
227
|
+
section_boost: null,
|
|
228
|
+
}));
|
|
229
|
+
const r = syncFileChunks(db, relPath, desired, { existsOnDisk: (p) => existsSync(resolve(WORKSPACE, p)) });
|
|
230
|
+
return { chunks: textChunks.length, inserted: r.inserted, kept: r.kept, deleted: r.deleted, adopted: r.adopted };
|
|
231
|
+
}
|
|
232
|
+
/** Max chunks embedded inline per ingest; the 4-hourly `vectorize` catches up the rest. */
|
|
233
|
+
const INLINE_EMBED_CAP = 20;
|
|
234
|
+
/**
|
|
235
|
+
* Embed the rows an ingest just created. Kept rows already have their vector —
|
|
236
|
+
* re-embedding unchanged text is what the NOOP exists to avoid.
|
|
237
|
+
*/
|
|
238
|
+
export async function embedInserted(db, ids) {
|
|
239
|
+
if (ids.length === 0 || !process.env.GEMINI_API_KEY)
|
|
240
|
+
return 0;
|
|
241
|
+
let embedded = 0;
|
|
242
|
+
try {
|
|
243
|
+
const { embedDocument, ensureVecTable, upsertEmbedding } = await import("./embed.js");
|
|
244
|
+
ensureVecTable(db);
|
|
245
|
+
const get = db.prepare("SELECT chunk_text FROM chunks WHERE id = ?");
|
|
246
|
+
for (const id of ids.slice(0, INLINE_EMBED_CAP)) {
|
|
247
|
+
const row = get.get(id);
|
|
248
|
+
if (!row)
|
|
249
|
+
continue;
|
|
250
|
+
try {
|
|
251
|
+
const emb = await embedDocument(row.chunk_text);
|
|
252
|
+
if (emb && emb.length > 0) {
|
|
253
|
+
upsertEmbedding(db, id, emb);
|
|
254
|
+
embedded++;
|
|
199
255
|
}
|
|
200
|
-
catch {
|
|
201
|
-
break;
|
|
202
|
-
} // Stop on first API error (rate limit)
|
|
203
256
|
}
|
|
204
|
-
|
|
205
|
-
|
|
257
|
+
catch {
|
|
258
|
+
break;
|
|
259
|
+
} // Stop on first API error (rate limit)
|
|
206
260
|
}
|
|
207
|
-
catch { }
|
|
208
261
|
}
|
|
209
|
-
|
|
262
|
+
catch { }
|
|
263
|
+
return embedded;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* @param filePath — absolute path to .md or .json file
|
|
267
|
+
* @param externalDb — optional db connection; reindex passes one and vectorizes in batch afterwards
|
|
268
|
+
*
|
|
269
|
+
* Never closes the connection. It used to `db.close()` the getDb() singleton,
|
|
270
|
+
* which pulled the handle out from under any caller holding it (withOpAudit,
|
|
271
|
+
* the API and MCP servers): an op wrapping ingest ended `failed` with its work
|
|
272
|
+
* done (HANDOFF 2026-10-14). Closing is the CLI entry point's job (closeDb()).
|
|
273
|
+
*/
|
|
274
|
+
export async function ingestFile(filePath, externalDb) {
|
|
275
|
+
const db = externalDb || getDb();
|
|
276
|
+
const result = ingestMarkdownSync(db, filePath);
|
|
277
|
+
// Auto-vectorize direct ingests only. Reindex passes externalDb and is followed
|
|
278
|
+
// by a batch vectorize phase; embedding per file there is too expensive.
|
|
279
|
+
if (!externalDb) {
|
|
280
|
+
const embedded = await embedInserted(db, result.inserted);
|
|
281
|
+
if (embedded > 0)
|
|
282
|
+
console.log("[INGEST] Auto-vectorized " + embedded + " chunks");
|
|
283
|
+
}
|
|
284
|
+
return result;
|
|
210
285
|
}
|
|
@@ -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
|
+
}
|