nox-mem 3.3.0 → 3.5.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 +82 -31
- package/dist/api/answer.js +22 -0
- package/dist/api-server.js +22 -3
- package/dist/cli/answer.js +39 -1
- package/dist/db.js +47 -24
- package/dist/doctor.js +108 -29
- package/dist/embed.js +53 -3
- package/dist/index.js +73 -17
- package/dist/lib/answer/index.js +3 -2
- package/dist/lib/answer/retrieval.js +6 -4
- package/dist/lib/answer/temporal.js +51 -0
- package/dist/lib/api-port.js +16 -0
- package/dist/lib/dates.js +98 -0
- package/dist/lib/db-path.js +57 -0
- package/dist/lib/ingest-many.js +49 -0
- package/dist/lib/op-audit.js +19 -12
- package/dist/lib/reranker.js +4 -1
- package/dist/mcp/tools/answer.js +23 -0
- package/dist/mcp-server.js +45 -6
- package/dist/reflect.js +2 -2
- package/dist/reindex-errors.js +45 -0
- package/dist/reindex.js +116 -23
- package/dist/search.js +111 -16
- package/package.json +7 -2
- package/prompts/consolidate.txt +13 -0
- package/prompts/digest.txt +5 -0
- package/dist/__tests__/brief-diversity.test.js +0 -266
- package/dist/__tests__/brief.test.js +0 -287
- package/dist/__tests__/churn.test.js +0 -66
- package/dist/__tests__/edge-typing.test.js +0 -99
- package/dist/__tests__/ingest-event.test.js +0 -151
- package/dist/__tests__/op-audit-e2e.test.js +0 -130
- package/dist/__tests__/pragma-alignment.test.js +0 -123
- package/dist/__tests__/reranker.test.js +0 -326
- package/dist/__tests__/retention.test.js +0 -99
- package/dist/__tests__/search-track-access.test.js +0 -49
- package/dist/__tests__/session-distill-sources.test.js +0 -98
- package/dist/__tests__/spo-injection.test.js +0 -172
- package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
- package/dist/__tests__/temporal-detector.test.js +0 -103
- package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
- package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
- package/dist/lib/answer/__tests__/integration.test.js +0 -347
- package/dist/lib/answer/__tests__/prompt.test.js +0 -117
- package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
- package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
- package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
- package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
- package/dist/lib/events/__tests__/bus.test.js +0 -208
- package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
- package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
- package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
- package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
- package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
- package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
- package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
- package/dist/privacy/__tests__/filter.test.js +0 -352
- package/dist/providers/__tests__/conformance-extended.test.js +0 -249
- package/dist/providers/__tests__/conformance.test.js +0 -98
- package/dist/providers/__tests__/cost-cap.test.js +0 -151
- package/dist/providers/__tests__/e2e-real.test.js +0 -79
- package/dist/providers/__tests__/factory.test.js +0 -80
- package/dist/providers/__tests__/fallback.test.js +0 -223
- package/dist/providers/__tests__/gemini.test.js +0 -191
- package/dist/providers/__tests__/health.test.js +0 -128
- package/dist/providers/__tests__/telemetry.test.js +0 -219
package/dist/doctor.js
CHANGED
|
@@ -1,64 +1,143 @@
|
|
|
1
1
|
import { getDb, DB_PATH } from "./db.js";
|
|
2
2
|
import { statSync, existsSync } from "fs";
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
// Unit names the watcher has shipped under: the repo's unit file and the
|
|
4
|
+
// older name still used on the origin VPS.
|
|
5
|
+
const WATCHER_UNITS = ["nox-mem-watcher.service", "nox-mem-watch.service"];
|
|
6
|
+
/**
|
|
7
|
+
* Two groups, deliberately:
|
|
8
|
+
* core — the store, FTS5 and embeddings. A ❌ here means ingest/search is broken.
|
|
9
|
+
* optional — integrations only some commands use (Ollama as `digest`'s
|
|
10
|
+
* last-resort fallback, Notion, the systemd watcher). Absent ⇒ ⚪, never ❌:
|
|
11
|
+
* a fresh install without them is healthy.
|
|
12
|
+
*
|
|
13
|
+
* `--quiet` prints only core problems and exits 1 iff a core check failed —
|
|
14
|
+
* the contract scripts/test.sh relies on.
|
|
15
|
+
*/
|
|
16
|
+
export async function doctor(opts = {}) {
|
|
17
|
+
const core = [];
|
|
18
|
+
const optional = [];
|
|
5
19
|
// 1. SQLite database
|
|
6
20
|
try {
|
|
7
21
|
const db = getDb();
|
|
8
22
|
const version = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get();
|
|
9
|
-
|
|
23
|
+
core.push({ name: "SQLite DB", status: "✅", detail: `schema v${version?.value || "?"}, ${formatSize(DB_PATH)} at ${DB_PATH}` });
|
|
10
24
|
// 2. FTS5 index
|
|
11
|
-
|
|
25
|
+
// chunks_fts is an external-content table: COUNT(*) on it reads the CONTENT
|
|
26
|
+
// table (chunks), so "indexed == chunks" held by construction and this check
|
|
27
|
+
// could never fire. The docsize shadow table has one row per document the
|
|
28
|
+
// index actually holds — measured: after an FTS 'delete' it drops to 0 while
|
|
29
|
+
// COUNT(*) on chunks_fts still reports every chunk (2026-09-28).
|
|
30
|
+
const hasDocsize = db.prepare("SELECT 1 FROM sqlite_master WHERE name = 'chunks_fts_docsize'").get() !== undefined;
|
|
31
|
+
const ftsCount = db.prepare(`SELECT COUNT(*) as c FROM ${hasDocsize ? "chunks_fts_docsize" : "chunks_fts"}`).get().c;
|
|
12
32
|
const chunkCount = db.prepare("SELECT COUNT(*) as c FROM chunks").get().c;
|
|
13
33
|
const ftsOk = ftsCount === chunkCount;
|
|
14
|
-
|
|
15
|
-
// 3.
|
|
34
|
+
core.push({ name: "FTS5 Index", status: ftsOk ? "✅" : "⚠️", detail: `${ftsCount} indexed / ${chunkCount} chunks${ftsOk ? "" : ` — MISMATCH, rebuild the FTS index: sqlite3 "${DB_PATH}" "INSERT INTO chunks_fts(chunks_fts) VALUES('rebuild')"`}` });
|
|
35
|
+
// 3. Embeddings (semantic search). Missing key is a degraded mode, not a failure:
|
|
36
|
+
// search falls back to FTS5.
|
|
37
|
+
const hasKey = Boolean(process.env.NOX_EMBEDDING_API_KEY || process.env.NOX_EMBED_API_KEY || process.env.GEMINI_API_KEY || process.env.OPENAI_API_KEY);
|
|
38
|
+
let embedded = 0;
|
|
39
|
+
try {
|
|
40
|
+
const { ensureVecTable, countEmbedded } = await import("./embed.js");
|
|
41
|
+
ensureVecTable(db);
|
|
42
|
+
embedded = countEmbedded(db);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// sqlite-vec not loadable — reported through the detail below
|
|
46
|
+
}
|
|
47
|
+
if (!hasKey) {
|
|
48
|
+
core.push({ name: "Embeddings", status: "⚠️", detail: `no GEMINI_API_KEY — search is keyword-only (FTS5); ${embedded}/${chunkCount} embedded` });
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
const full = embedded >= chunkCount;
|
|
52
|
+
core.push({ name: "Embeddings", status: full ? "✅" : "⚠️", detail: `${embedded}/${chunkCount} embedded${full ? "" : " — run nox-mem vectorize"}` });
|
|
53
|
+
}
|
|
54
|
+
// 4. Consolidated files
|
|
16
55
|
const consolidated = db.prepare("SELECT COUNT(*) as c FROM consolidated_files WHERE status = 1").get().c;
|
|
17
56
|
const failed = db.prepare("SELECT COUNT(*) as c FROM consolidated_files WHERE status = -1").get().c;
|
|
18
57
|
const pending = db.prepare("SELECT COUNT(DISTINCT source_file) as c FROM chunks WHERE chunk_type = 'daily' AND source_file NOT IN (SELECT source_file FROM consolidated_files)").get().c;
|
|
19
|
-
|
|
20
|
-
//
|
|
58
|
+
core.push({ name: "Consolidation", status: failed > 0 ? "⚠️" : "✅", detail: `${consolidated} done, ${pending} pending, ${failed} failed` });
|
|
59
|
+
// 5. Last consolidation
|
|
21
60
|
const lastCon = db.prepare("SELECT value FROM meta WHERE key = 'last_consolidation'").get();
|
|
22
|
-
|
|
61
|
+
core.push({ name: "Last consolidation", status: "ℹ️", detail: lastCon?.value ?? "never" });
|
|
23
62
|
}
|
|
24
63
|
catch (err) {
|
|
25
|
-
|
|
64
|
+
core.push({ name: "SQLite DB", status: "❌", detail: `${err}` });
|
|
26
65
|
}
|
|
27
|
-
//
|
|
66
|
+
// ── Optional integrations ──────────────────────────────────────────────────
|
|
67
|
+
// Ollama — only the last-resort fallback of `digest` (consolidate and
|
|
68
|
+
// kg-extract use Gemini/Groq/Claude and never call it)
|
|
28
69
|
try {
|
|
29
70
|
const response = await fetch("http://127.0.0.1:11434/api/tags", { signal: AbortSignal.timeout(5000) });
|
|
30
71
|
if (response.ok) {
|
|
31
72
|
const data = (await response.json());
|
|
32
73
|
const models = data.models.map((m) => m.name).join(", ");
|
|
33
|
-
|
|
74
|
+
optional.push({ name: "Ollama", status: "✅", detail: `running, models: ${models}` });
|
|
34
75
|
}
|
|
35
76
|
else {
|
|
36
|
-
|
|
77
|
+
optional.push({ name: "Ollama", status: "⚠️", detail: `HTTP ${response.status}` });
|
|
37
78
|
}
|
|
38
79
|
}
|
|
39
80
|
catch {
|
|
40
|
-
|
|
81
|
+
optional.push({ name: "Ollama", status: "⚪", detail: "not running (optional — only `digest` falls back to it; consolidate uses Gemini, then Groq, then Claude)" });
|
|
41
82
|
}
|
|
42
|
-
//
|
|
83
|
+
// Notion token
|
|
43
84
|
const notionTokenPath = process.env.NOX_NOTION_TOKEN_PATH ?? "/root/.config/notion/api_key";
|
|
44
85
|
const notionTokenExists = existsSync(notionTokenPath);
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
86
|
+
optional.push({
|
|
87
|
+
name: "Notion token",
|
|
88
|
+
status: notionTokenExists ? "✅" : "⚪",
|
|
89
|
+
detail: notionTokenExists ? `found at ${notionTokenPath}` : "not configured (optional — set NOX_NOTION_TOKEN_PATH to enable)",
|
|
90
|
+
});
|
|
91
|
+
// File watcher (systemd). No systemd, or unit not installed ⇒ optional/absent.
|
|
92
|
+
// Installed but not active ⇒ ⚠️, because someone meant to run it.
|
|
93
|
+
optional.push(await watcherCheck());
|
|
94
|
+
// An FTS/chunks mismatch is ⚠️ on screen (fixable with reindex) but it breaks
|
|
95
|
+
// search, so scripts relying on --quiet must see it as a failure.
|
|
96
|
+
const coreFailed = core.some((c) => c.status === "❌" || (c.name === "FTS5 Index" && c.status !== "✅"));
|
|
97
|
+
if (opts.quiet) {
|
|
98
|
+
for (const check of core.filter((c) => c.status === "❌" || c.status === "⚠️")) {
|
|
99
|
+
console.error(` ${check.status} ${check.name}: ${check.detail}`);
|
|
100
|
+
}
|
|
52
101
|
}
|
|
53
|
-
|
|
54
|
-
|
|
102
|
+
else {
|
|
103
|
+
console.log("\n🩺 nox-mem doctor\n");
|
|
104
|
+
console.log(" Core");
|
|
105
|
+
for (const check of core)
|
|
106
|
+
console.log(` ${check.status} ${check.name}: ${check.detail}`);
|
|
107
|
+
console.log("\n Optional integrations (⚪ = not set up, fine to skip)");
|
|
108
|
+
for (const check of optional)
|
|
109
|
+
console.log(` ${check.status} ${check.name}: ${check.detail}`);
|
|
110
|
+
console.log("");
|
|
111
|
+
}
|
|
112
|
+
if (coreFailed)
|
|
113
|
+
process.exitCode = 1;
|
|
114
|
+
}
|
|
115
|
+
async function watcherCheck() {
|
|
116
|
+
const { execFileSync } = await import("child_process");
|
|
117
|
+
const run = (args) => {
|
|
118
|
+
try {
|
|
119
|
+
return execFileSync("systemctl", args, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
// `systemctl is-active` exits non-zero for inactive units but still prints the state
|
|
123
|
+
const out = err.stdout;
|
|
124
|
+
return typeof out === "string" ? out.trim() : null;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
if (run(["--version"]) === null) {
|
|
128
|
+
return { name: "File watcher", status: "⚪", detail: "no systemd (optional — run `nox-mem watch` in a terminal instead)" };
|
|
129
|
+
}
|
|
130
|
+
for (const unit of WATCHER_UNITS) {
|
|
131
|
+
const state = run(["is-active", unit]);
|
|
132
|
+
if (state === "active")
|
|
133
|
+
return { name: "File watcher", status: "✅", detail: `${unit} active` };
|
|
55
134
|
}
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
135
|
+
for (const unit of WATCHER_UNITS) {
|
|
136
|
+
const loaded = run(["show", "-p", "LoadState", "--value", unit]);
|
|
137
|
+
if (loaded === "loaded")
|
|
138
|
+
return { name: "File watcher", status: "⚠️", detail: `${unit} installed but not active` };
|
|
60
139
|
}
|
|
61
|
-
|
|
140
|
+
return { name: "File watcher", status: "⚪", detail: "not installed (optional — see nox-mem-watcher.service)" };
|
|
62
141
|
}
|
|
63
142
|
function formatSize(path) {
|
|
64
143
|
try {
|
package/dist/embed.js
CHANGED
|
@@ -99,11 +99,12 @@ async function geminiEmbed(text) {
|
|
|
99
99
|
const data = (await resp.json());
|
|
100
100
|
return data.embedding.values;
|
|
101
101
|
}
|
|
102
|
-
async function geminiEmbedQuery(text) {
|
|
102
|
+
async function geminiEmbedQuery(text, signal) {
|
|
103
103
|
if (!GEMINI_API_KEY)
|
|
104
104
|
throw new Error("GEMINI_API_KEY not set");
|
|
105
105
|
const url = `${API_BASE}/models/${EMBEDDING_MODEL}:embedContent?key=${GEMINI_API_KEY}`;
|
|
106
106
|
const resp = await fetchWithRetry(url, {
|
|
107
|
+
signal,
|
|
107
108
|
method: "POST",
|
|
108
109
|
headers: { "Content-Type": "application/json" },
|
|
109
110
|
body: JSON.stringify({
|
|
@@ -157,14 +158,63 @@ export function activeEmbeddingDim() {
|
|
|
157
158
|
return EMBEDDING_DIM;
|
|
158
159
|
}
|
|
159
160
|
// ─── Public API ──────────────────────────────────────────────────────────────
|
|
160
|
-
export async function embedText(text) {
|
|
161
|
+
export async function embedText(text, opts = {}) {
|
|
162
|
+
const timeoutMs = opts.timeoutMs ?? 0;
|
|
163
|
+
if (!(timeoutMs > 0))
|
|
164
|
+
return embedTextUnbounded(text);
|
|
165
|
+
// A slow provider is not an error: without a budget the caller just waits
|
|
166
|
+
// (retries + backoff included). The budget covers the whole call; on expiry the
|
|
167
|
+
// in-flight native request is aborted and the caller gets EmbedTimeoutError.
|
|
168
|
+
const ctrl = new AbortController();
|
|
169
|
+
let timer;
|
|
170
|
+
const expired = new Promise((_, reject) => {
|
|
171
|
+
timer = setTimeout(() => {
|
|
172
|
+
ctrl.abort();
|
|
173
|
+
reject(new EmbedTimeoutError(timeoutMs));
|
|
174
|
+
}, timeoutMs);
|
|
175
|
+
});
|
|
176
|
+
try {
|
|
177
|
+
return await Promise.race([embedTextUnbounded(text, ctrl.signal), expired]);
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
export class EmbedTimeoutError extends Error {
|
|
184
|
+
timeoutMs;
|
|
185
|
+
constructor(timeoutMs) {
|
|
186
|
+
super(`query embedding exceeded ${timeoutMs} ms`);
|
|
187
|
+
this.timeoutMs = timeoutMs;
|
|
188
|
+
this.name = "EmbedTimeoutError";
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Time budget for embedding a search query, in ms. NOX_QUERY_EMBED_TIMEOUT_MS
|
|
193
|
+
* overrides; 0 disables the budget. Default 5000: hybrid p50 is ~1 s, so a
|
|
194
|
+
* query still waiting after 5 s is better served by FTS5 than by waiting.
|
|
195
|
+
*/
|
|
196
|
+
export function queryEmbedTimeoutMs(env = process.env) {
|
|
197
|
+
const raw = env.NOX_QUERY_EMBED_TIMEOUT_MS;
|
|
198
|
+
if (raw === undefined || raw.trim() === "")
|
|
199
|
+
return 5000;
|
|
200
|
+
const n = Number(raw);
|
|
201
|
+
return Number.isFinite(n) && n >= 0 ? n : 5000;
|
|
202
|
+
}
|
|
203
|
+
/** Test seam: replaces the provider call behind embedText (null restores it). */
|
|
204
|
+
let embedOverride = null;
|
|
205
|
+
export function __setEmbedForTests(fn) {
|
|
206
|
+
embedOverride = fn;
|
|
207
|
+
}
|
|
208
|
+
async function embedTextUnbounded(text, signal) {
|
|
209
|
+
if (embedOverride)
|
|
210
|
+
return embedOverride(text, signal);
|
|
161
211
|
// Route to abstract provider when configured; keep native Gemini path as default.
|
|
162
212
|
const provider = activeEmbeddingProvider();
|
|
163
213
|
if (provider !== null) {
|
|
164
214
|
const vecs = await provider.embed([text]);
|
|
165
215
|
return vecs[0];
|
|
166
216
|
}
|
|
167
|
-
const values = await geminiEmbedQuery(text);
|
|
217
|
+
const values = await geminiEmbedQuery(text, signal);
|
|
168
218
|
return new Float32Array(values);
|
|
169
219
|
}
|
|
170
220
|
/**
|
package/dist/index.js
CHANGED
|
@@ -18,6 +18,7 @@ import { getNoiseStats, isNoise } from "./noise-filter.js";
|
|
|
18
18
|
import { distillSessions } from "./session-distill.js";
|
|
19
19
|
import { startWatch } from "./watch.js";
|
|
20
20
|
import { VERSION } from "./version.js";
|
|
21
|
+
import { parseTemporalFilter, TemporalParseError } from "./lib/dates.js";
|
|
21
22
|
const program = new Command();
|
|
22
23
|
program.name("nox-mem").description("Nox Supermem — search, consolidate, recover").version(VERSION);
|
|
23
24
|
program
|
|
@@ -25,16 +26,48 @@ program
|
|
|
25
26
|
.description("Search memory (FTS5 + boost + recency)")
|
|
26
27
|
.option("-n, --limit <n>", "Number of results", "5")
|
|
27
28
|
.option("--no-hybrid", "Disable semantic search (FTS5 only)")
|
|
29
|
+
.option("--as-of <date>", "Only chunks that existed at <date> (ISO 8601 or relative: 15m, 2h, 7d, 1w)")
|
|
30
|
+
.option("--changed-since <date>", "Only chunks created/updated after <date> (ISO 8601 or relative)")
|
|
28
31
|
.action(async (query, opts) => {
|
|
32
|
+
let filter;
|
|
33
|
+
try {
|
|
34
|
+
filter = parseTemporalFilter({ asOf: opts.asOf, changedSince: opts.changedSince });
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
if (!(err instanceof TemporalParseError))
|
|
38
|
+
throw err;
|
|
39
|
+
console.error(`error: ${err.message}`);
|
|
40
|
+
process.exitCode = 2;
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
29
43
|
if (opts.hybrid) {
|
|
30
|
-
const results = await searchHybrid(query, parseInt(opts.limit, 10));
|
|
44
|
+
const results = await searchHybrid(query, parseInt(opts.limit, 10), true, filter);
|
|
31
45
|
console.log(formatResults(results));
|
|
32
46
|
}
|
|
33
47
|
else {
|
|
34
|
-
console.log(formatResults(search(query, parseInt(opts.limit, 10))));
|
|
48
|
+
console.log(formatResults(search(query, parseInt(opts.limit, 10), true, filter)));
|
|
35
49
|
}
|
|
36
50
|
closeDb();
|
|
37
51
|
});
|
|
52
|
+
// `answer` keeps its own argv parser (src/cli/answer.ts, P1 T8), so commander
|
|
53
|
+
// only routes to it and hands over the raw argv after the subcommand name.
|
|
54
|
+
program
|
|
55
|
+
.command("answer")
|
|
56
|
+
.description("Grounded answer with citations over memory (needs GEMINI_API_KEY; see `nox-mem answer --help`)")
|
|
57
|
+
.argument("[question...]")
|
|
58
|
+
.allowUnknownOption(true)
|
|
59
|
+
.helpOption(false)
|
|
60
|
+
.action(async () => {
|
|
61
|
+
const { runCli } = await import("./cli/answer.js");
|
|
62
|
+
const argv = process.argv.slice(process.argv.indexOf("answer") + 1);
|
|
63
|
+
const code = await runCli({
|
|
64
|
+
argv,
|
|
65
|
+
stdout: (line) => console.log(line),
|
|
66
|
+
stderr: (line) => console.error(line),
|
|
67
|
+
});
|
|
68
|
+
closeDb();
|
|
69
|
+
process.exitCode = code;
|
|
70
|
+
});
|
|
38
71
|
program
|
|
39
72
|
.command("vectorize")
|
|
40
73
|
.description("Build/update vector index for all chunks (semantic search)")
|
|
@@ -46,10 +79,10 @@ program
|
|
|
46
79
|
closeDb();
|
|
47
80
|
});
|
|
48
81
|
program
|
|
49
|
-
.command("ingest <
|
|
50
|
-
.description("Index
|
|
51
|
-
.option("--allow-prod", "Skip large-DB ingest guard (
|
|
52
|
-
.action(async (
|
|
82
|
+
.command("ingest <files...>")
|
|
83
|
+
.description("Index one or more .md or .json files (a directory is an error: pass files, e.g. dir/*.md)")
|
|
84
|
+
.option("--allow-prod", "Skip the large-DB ingest guard (needed once the DB has more than 10,000 chunks; same as NOX_ALLOW_PROD_INGEST=1)")
|
|
85
|
+
.action(async (files, opts) => {
|
|
53
86
|
// Large-DB guard (postmortem 2026-05-19): abort if DB looks like prod
|
|
54
87
|
// and operator hasn't explicitly opted in. Override via --allow-prod flag
|
|
55
88
|
// or NOX_ALLOW_PROD_INGEST=1 env var.
|
|
@@ -58,9 +91,15 @@ program
|
|
|
58
91
|
}
|
|
59
92
|
checkLargeDbIngestGuard(getDb(), "ingest");
|
|
60
93
|
const { routeIngest } = await import("./lib/ingest-router.js");
|
|
61
|
-
const
|
|
62
|
-
|
|
94
|
+
const { ingestMany } = await import("./lib/ingest-many.js");
|
|
95
|
+
const { failed } = await ingestMany(files, {
|
|
96
|
+
ingestOne: (f) => routeIngest(f),
|
|
97
|
+
log: (l) => console.log(l),
|
|
98
|
+
error: (l) => console.error(l),
|
|
99
|
+
});
|
|
63
100
|
closeDb();
|
|
101
|
+
if (failed > 0)
|
|
102
|
+
process.exitCode = 1;
|
|
64
103
|
});
|
|
65
104
|
program
|
|
66
105
|
.command("ingest-entity <file>")
|
|
@@ -78,10 +117,26 @@ program
|
|
|
78
117
|
});
|
|
79
118
|
program
|
|
80
119
|
.command("reindex")
|
|
81
|
-
.description("Rebuild
|
|
82
|
-
.
|
|
83
|
-
|
|
84
|
-
|
|
120
|
+
.description("Rebuild the index from $OPENCLAW_WORKSPACE/memory and /shared (refuses if that source is missing)")
|
|
121
|
+
.option("--dry-run", "Print what would be reindexed as JSON; does not touch the DB")
|
|
122
|
+
.action(async (opts) => {
|
|
123
|
+
try {
|
|
124
|
+
const result = await reindex({ dryRun: opts.dryRun });
|
|
125
|
+
if (!opts.dryRun)
|
|
126
|
+
console.log(`[INFO] Reindexed ${result.files} files, ${result.chunks} chunks`);
|
|
127
|
+
}
|
|
128
|
+
catch (err) {
|
|
129
|
+
const name = err.name;
|
|
130
|
+
if (name === "ReindexSourceMissingError" || name === "ReindexWipeDetectedError" || name === "ReindexWorkspaceMismatchError") {
|
|
131
|
+
console.error(err.message);
|
|
132
|
+
process.exitCode = 1;
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
throw err;
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
closeDb();
|
|
139
|
+
}
|
|
85
140
|
});
|
|
86
141
|
program
|
|
87
142
|
.command("primer")
|
|
@@ -99,7 +154,7 @@ program
|
|
|
99
154
|
});
|
|
100
155
|
program
|
|
101
156
|
.command("consolidate")
|
|
102
|
-
.description("Consolidate daily notes into topic files (
|
|
157
|
+
.description("Consolidate daily notes into topic files (LLM: Gemini, then Groq, then Claude — needs GEMINI_API_KEY, GROQ_API_KEY or ANTHROPIC_API_KEY)")
|
|
103
158
|
.action(async () => {
|
|
104
159
|
const { consolidate } = await import("./consolidate.js");
|
|
105
160
|
const result = await consolidate();
|
|
@@ -126,10 +181,11 @@ program
|
|
|
126
181
|
});
|
|
127
182
|
program
|
|
128
183
|
.command("doctor")
|
|
129
|
-
.description("Diagnostic check —
|
|
130
|
-
.
|
|
184
|
+
.description("Diagnostic check — core (SQLite, FTS5, embeddings) + optional integrations (Ollama for digest, Notion, watcher)")
|
|
185
|
+
.option("--quiet", "Print only core problems; exit 1 if a core check fails")
|
|
186
|
+
.action(async (opts) => {
|
|
131
187
|
const { doctor } = await import("./doctor.js");
|
|
132
|
-
await doctor();
|
|
188
|
+
await doctor({ quiet: opts.quiet });
|
|
133
189
|
closeDb();
|
|
134
190
|
});
|
|
135
191
|
program
|
|
@@ -350,7 +406,7 @@ program
|
|
|
350
406
|
// ─── Knowledge Graph v2: LLM extraction ──────────────────────────────────────
|
|
351
407
|
program
|
|
352
408
|
.command("kg-extract")
|
|
353
|
-
.description("Extract entities/relations from chunks using
|
|
409
|
+
.description("Extract entities/relations from chunks using Gemini (needs GEMINI_API_KEY)")
|
|
354
410
|
.option("-n, --limit <n>", "Chunks to process", "50")
|
|
355
411
|
.action(async (opts) => {
|
|
356
412
|
const { extractWithLLM } = await import("./kg-llm.js");
|
package/dist/lib/answer/index.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Pipeline (T1-T4 scope + minimal T5/T6 anti-hallucination retry-once):
|
|
10
10
|
* 1. resolveConfig(opts) → ResolvedConfig
|
|
11
|
-
* 2. retrieveContext(question, topK)
|
|
11
|
+
* 2. retrieveContext(question, topK, temporal?) → RetrievedChunk[]
|
|
12
12
|
* 3. buildPrompt(question, chunks) → {system, user}
|
|
13
13
|
* 4. provider.complete(prompt + cfg) → LLMCallResult
|
|
14
14
|
* 5. parseCitations(text, chunks) → { citations, hallucinated[] }
|
|
@@ -26,6 +26,7 @@ export { selectProvider, MockProvider } from "./provider.js";
|
|
|
26
26
|
export { buildPrompt, buildRetryPrompt } from "./prompt.js";
|
|
27
27
|
export { retrieveContext, __setRawSearchForTests } from "./retrieval.js";
|
|
28
28
|
export { resolveConfig } from "./config.js";
|
|
29
|
+
export { resolveTemporalFilter } from "./temporal.js";
|
|
29
30
|
/** Thrown when the pipeline produces an unrecoverable failure. */
|
|
30
31
|
export class AnswerError extends Error {
|
|
31
32
|
reason;
|
|
@@ -54,7 +55,7 @@ export async function answer(opts) {
|
|
|
54
55
|
const provider = opts.providerOverride ?? selectProvider(cfg.provider);
|
|
55
56
|
const retrieve = opts.retrieveOverride ?? retrieveContext;
|
|
56
57
|
// ── Step 2: retrieval ──────────────────────────────────────────────────
|
|
57
|
-
const chunks = await retrieve(opts.question, cfg.topK);
|
|
58
|
+
const chunks = await retrieve(opts.question, cfg.topK, opts.temporal);
|
|
58
59
|
if (chunks.length === 0) {
|
|
59
60
|
// Honour kickoff §6 retrieval_empty: short-circuit, no LLM spend.
|
|
60
61
|
return {
|
|
@@ -31,8 +31,9 @@ export function __setRawSearchForTests(fn) {
|
|
|
31
31
|
* throw a clear error if called without injection — keeps tests honest
|
|
32
32
|
* (must always inject) and prevents accidental network calls.
|
|
33
33
|
*/
|
|
34
|
-
async function defaultRawSearch(question, topK) {
|
|
35
|
-
|
|
34
|
+
async function defaultRawSearch(question, topK, filter) {
|
|
35
|
+
// trackAccess stays at its default (true), exactly as before the filter existed.
|
|
36
|
+
const hits = await searchHybrid(question, topK, true, filter);
|
|
36
37
|
return hits.map((h) => ({
|
|
37
38
|
chunk_id: h.id ?? 0,
|
|
38
39
|
file_path: h.source_file,
|
|
@@ -45,16 +46,17 @@ async function defaultRawSearch(question, topK) {
|
|
|
45
46
|
*
|
|
46
47
|
* @param question Natural-language input.
|
|
47
48
|
* @param topK Max chunks to return. Caller should pre-clamp via config.
|
|
49
|
+
* @param filter Optional temporal pre-filter, handed to searchHybrid untouched.
|
|
48
50
|
* @returns Deduplicated, marker-assigned chunks ordered by score desc.
|
|
49
51
|
*/
|
|
50
|
-
export async function retrieveContext(question, topK) {
|
|
52
|
+
export async function retrieveContext(question, topK, filter) {
|
|
51
53
|
if (!question || question.trim().length === 0) {
|
|
52
54
|
return [];
|
|
53
55
|
}
|
|
54
56
|
if (topK <= 0)
|
|
55
57
|
return [];
|
|
56
58
|
const search = injectedSearch ?? defaultRawSearch;
|
|
57
|
-
const raw = await search(question, topK * 2); // overfetch to survive dedupe
|
|
59
|
+
const raw = await search(question, topK * 2, filter); // overfetch to survive dedupe
|
|
58
60
|
// Sort by score desc (defensive — most hybrid impls already do this, but
|
|
59
61
|
// we cannot trust ordering of an injected/mocked search).
|
|
60
62
|
const sorted = [...raw].sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/lib/answer/temporal.ts — turns the raw `as_of` / `changed_since` values each
|
|
3
|
+
* answer surface receives (CLI flag, HTTP body field, MCP argument) into the same
|
|
4
|
+
* TemporalFilter that `search` uses, with one rule added on top of parseTemporalFilter:
|
|
5
|
+
*
|
|
6
|
+
* a value that was PROVIDED must be usable. parseTemporalFilter reads "" (and
|
|
7
|
+
* whitespace) as "not set", which is right for an absent query-string key but would
|
|
8
|
+
* turn `--as-of ""` / `{"as_of": ""}` into a silently unfiltered answer — so here a
|
|
9
|
+
* blank string, or anything that is not a string, throws TemporalParseError.
|
|
10
|
+
*
|
|
11
|
+
* `undefined` / `null` still mean "not set". Each surface maps the thrown
|
|
12
|
+
* TemporalParseError to its own error channel (CLI exit 2 / HTTP 400 / MCP isError).
|
|
13
|
+
*/
|
|
14
|
+
import { parseTemporalFilter, TemporalParseError } from "../dates.js";
|
|
15
|
+
function checked(name, value) {
|
|
16
|
+
if (value === undefined || value === null)
|
|
17
|
+
return undefined;
|
|
18
|
+
if (typeof value !== "string") {
|
|
19
|
+
throw new TemporalParseError(`temporal: ${name} must be a string (ISO 8601 date or relative like "7d")`);
|
|
20
|
+
}
|
|
21
|
+
if (value.trim() === "") {
|
|
22
|
+
throw new TemporalParseError(`temporal: ${name} is empty — omit it to answer without a temporal filter`);
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
export function resolveTemporalFilter(raw, nowMs = Date.now()) {
|
|
27
|
+
const asOfStr = checked("as_of", raw.asOf);
|
|
28
|
+
const sinceStr = checked("changed_since", raw.changedSince);
|
|
29
|
+
const filter = {};
|
|
30
|
+
if (asOfStr !== undefined) {
|
|
31
|
+
try {
|
|
32
|
+
filter.asOf = parseTemporalFilter({ asOf: asOfStr }, nowMs)?.asOf;
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
if (err instanceof TemporalParseError)
|
|
36
|
+
throw new TemporalParseError(`as_of: ${err.message}`);
|
|
37
|
+
throw err;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (sinceStr !== undefined) {
|
|
41
|
+
try {
|
|
42
|
+
filter.changedSince = parseTemporalFilter({ changedSince: sinceStr }, nowMs)?.changedSince;
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
if (err instanceof TemporalParseError)
|
|
46
|
+
throw new TemporalParseError(`changed_since: ${err.message}`);
|
|
47
|
+
throw err;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return filter.asOf || filter.changedSince ? filter : undefined;
|
|
51
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* api-port.ts — the HTTP API port, in one place.
|
|
3
|
+
*
|
|
4
|
+
* Default 18802. The code used to default to the port just below it while every
|
|
5
|
+
* document said 18802, and that lower port is squatted by Chrome on many desktops.
|
|
6
|
+
* NOX_API_PORT overrides; an empty or non-numeric value falls back to the default
|
|
7
|
+
* rather than handing `listen()` a NaN.
|
|
8
|
+
*/
|
|
9
|
+
export const DEFAULT_API_PORT = 18802;
|
|
10
|
+
export function resolveApiPort(env = process.env) {
|
|
11
|
+
const raw = env.NOX_API_PORT?.trim();
|
|
12
|
+
if (!raw)
|
|
13
|
+
return DEFAULT_API_PORT;
|
|
14
|
+
const n = Number.parseInt(raw, 10);
|
|
15
|
+
return Number.isInteger(n) && n >= 0 && n <= 65535 ? n : DEFAULT_API_PORT;
|
|
16
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/lib/dates.ts — flexible date parsing for the temporal search filter (P3).
|
|
3
|
+
*
|
|
4
|
+
* Accepted:
|
|
5
|
+
* ISO 8601 date: "2026-05-01" (start of day UTC; end of day for as-of)
|
|
6
|
+
* ISO 8601 full: "2026-05-01T12:00:00Z" (no offset ⇒ UTC)
|
|
7
|
+
* Relative: "15m" | "2h" | "7d" | "1w" (that long before `nowMs`)
|
|
8
|
+
*
|
|
9
|
+
* "1mo" is deliberately unsupported (months have no fixed length) — use "30d".
|
|
10
|
+
* Throws TemporalParseError on anything else, so surfaces can answer 400 / exit 2
|
|
11
|
+
* instead of silently searching without the filter.
|
|
12
|
+
*/
|
|
13
|
+
export class TemporalParseError extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "TemporalParseError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const RELATIVE_RE = /^(\d+)(m|h|d|w)$/i;
|
|
20
|
+
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
21
|
+
// Requires at least YYYY-MM-DDTHH:MM so bare numbers or "May 1" are rejected
|
|
22
|
+
// (Date.parse accepts both, with locale-dependent results).
|
|
23
|
+
const ISO_FULL_RE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/;
|
|
24
|
+
const HAS_OFFSET_RE = /(Z|[+-]\d{2}:?\d{2})$/i;
|
|
25
|
+
const UNIT_MS = {
|
|
26
|
+
m: 60_000,
|
|
27
|
+
h: 3_600_000,
|
|
28
|
+
d: 86_400_000,
|
|
29
|
+
w: 604_800_000,
|
|
30
|
+
};
|
|
31
|
+
export function parseFlexibleDate(input, nowMs = Date.now(), opts = {}) {
|
|
32
|
+
const trimmed = String(input ?? "").trim();
|
|
33
|
+
if (!trimmed)
|
|
34
|
+
throw new TemporalParseError("temporal: empty date string");
|
|
35
|
+
const rel = RELATIVE_RE.exec(trimmed);
|
|
36
|
+
if (rel) {
|
|
37
|
+
const n = parseInt(rel[1], 10);
|
|
38
|
+
return new Date(nowMs - n * UNIT_MS[rel[2].toLowerCase()]);
|
|
39
|
+
}
|
|
40
|
+
let normalised = null;
|
|
41
|
+
if (DATE_ONLY_RE.test(trimmed)) {
|
|
42
|
+
// "as of 2026-01-10" reads as "by the end of that day"; "since 2026-01-10"
|
|
43
|
+
// as "from its start". Both in UTC.
|
|
44
|
+
normalised = opts.dateOnlyAs === "end" ? `${trimmed}T23:59:59.999Z` : `${trimmed}T00:00:00Z`;
|
|
45
|
+
}
|
|
46
|
+
else if (ISO_FULL_RE.test(trimmed)) {
|
|
47
|
+
// No offset ⇒ UTC, same as date-only (JS would otherwise read it as local time).
|
|
48
|
+
normalised = HAS_OFFSET_RE.test(trimmed) ? trimmed : `${trimmed}Z`;
|
|
49
|
+
}
|
|
50
|
+
const d = normalised ? new Date(normalised) : null;
|
|
51
|
+
if (!d || isNaN(d.getTime())) {
|
|
52
|
+
throw new TemporalParseError(`temporal: cannot parse date "${input}". ` +
|
|
53
|
+
`Accepted: ISO 8601 ("2026-05-01" or "2026-05-01T00:00:00Z") ` +
|
|
54
|
+
`or relative ("15m", "2h", "7d", "1w"). "1mo" is not supported — use "30d".`);
|
|
55
|
+
}
|
|
56
|
+
return d;
|
|
57
|
+
}
|
|
58
|
+
/** Parses the raw strings each surface receives; undefined/empty means "not set". */
|
|
59
|
+
export function parseTemporalFilter(raw, nowMs = Date.now()) {
|
|
60
|
+
const filter = {};
|
|
61
|
+
if (raw.asOf != null && String(raw.asOf).trim() !== "") {
|
|
62
|
+
filter.asOf = parseFlexibleDate(raw.asOf, nowMs, { dateOnlyAs: "end" });
|
|
63
|
+
}
|
|
64
|
+
if (raw.changedSince != null && String(raw.changedSince).trim() !== "") {
|
|
65
|
+
filter.changedSince = parseFlexibleDate(raw.changedSince, nowMs);
|
|
66
|
+
}
|
|
67
|
+
return filter.asOf || filter.changedSince ? filter : undefined;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* SQL fragment over the `chunks` alias `c` (semantics: docs/PRIMITIVES.md §3).
|
|
71
|
+
*
|
|
72
|
+
* asOf: created_at IS NULL (legacy rows count as "always existed")
|
|
73
|
+
* OR created_at <= asOf
|
|
74
|
+
* changedSince: updated_at > since OR created_at > since
|
|
75
|
+
*
|
|
76
|
+
* Both sides go through datetime(): the columns hold `datetime('now')` text
|
|
77
|
+
* ("YYYY-MM-DD HH:MM:SS") while the bound value is ISO ("...T...Z"), and a
|
|
78
|
+
* plain string comparison between the two formats is wrong (' ' < 'T').
|
|
79
|
+
* There is no soft-delete column in the schema, so no deleted_at leg.
|
|
80
|
+
*
|
|
81
|
+
* Returns null when the filter is empty so callers keep their exact SQL.
|
|
82
|
+
*/
|
|
83
|
+
export function buildTemporalClause(filter) {
|
|
84
|
+
if (!filter || (!filter.asOf && !filter.changedSince))
|
|
85
|
+
return null;
|
|
86
|
+
const parts = [];
|
|
87
|
+
const params = [];
|
|
88
|
+
if (filter.asOf) {
|
|
89
|
+
parts.push("(c.created_at IS NULL OR datetime(c.created_at) <= datetime(?))");
|
|
90
|
+
params.push(filter.asOf.toISOString());
|
|
91
|
+
}
|
|
92
|
+
if (filter.changedSince) {
|
|
93
|
+
const ts = filter.changedSince.toISOString();
|
|
94
|
+
parts.push("(datetime(c.updated_at) > datetime(?) OR datetime(c.created_at) > datetime(?))");
|
|
95
|
+
params.push(ts, ts);
|
|
96
|
+
}
|
|
97
|
+
return { sql: parts.join(" AND "), params };
|
|
98
|
+
}
|