nox-mem 3.4.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 +62 -33
- package/dist/api/answer.js +22 -0
- package/dist/api-server.js +3 -2
- package/dist/cli/answer.js +39 -1
- package/dist/db.js +31 -20
- package/dist/doctor.js +5 -4
- package/dist/embed.js +53 -3
- package/dist/index.js +16 -10
- 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/db-path.js +13 -1
- package/dist/lib/ingest-many.js +49 -0
- package/dist/mcp/tools/answer.js +23 -0
- package/dist/mcp-server.js +36 -5
- package/dist/reflect.js +2 -2
- package/dist/reindex-errors.js +19 -0
- package/dist/reindex.js +12 -2
- package/dist/search.js +27 -6
- package/package.json +4 -1
- 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__/fts-or-fallback.test.js +0 -115
- 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__/reindex-dedup.test.js +0 -80
- package/dist/__tests__/reindex-safety.test.js +0 -116
- 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/__tests__/temporal-filter.test.js +0 -117
- 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/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
|
+
}
|
package/dist/lib/db-path.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* root is inside node_modules, and `npm update -g` replaces that directory —
|
|
19
19
|
* taking the database with it.
|
|
20
20
|
*/
|
|
21
|
-
import { existsSync } from "fs";
|
|
21
|
+
import { existsSync, mkdirSync } from "fs";
|
|
22
22
|
import { homedir } from "os";
|
|
23
23
|
import { dirname, join, resolve, sep } from "path";
|
|
24
24
|
import { fileURLToPath } from "url";
|
|
@@ -43,3 +43,15 @@ export function resolveDbPath() {
|
|
|
43
43
|
export function isInsideNodeModules(p) {
|
|
44
44
|
return resolve(p).split(sep).includes("node_modules");
|
|
45
45
|
}
|
|
46
|
+
/**
|
|
47
|
+
* mkdir -p the directory that will hold the database, mode 0700 (the DB holds
|
|
48
|
+
* the user's notes). No-op when it already exists, so an existing directory's
|
|
49
|
+
* permissions are never changed. Returns true when it created anything.
|
|
50
|
+
*/
|
|
51
|
+
export function ensureDbParentDir(dbPath) {
|
|
52
|
+
const dir = dirname(resolve(dbPath));
|
|
53
|
+
if (existsSync(dir))
|
|
54
|
+
return false;
|
|
55
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ingest-many.ts — `nox-mem ingest <files...>`: ingest every path given.
|
|
3
|
+
*
|
|
4
|
+
* The command used to take a single `<file>`, so `nox-mem ingest notes/*.md`
|
|
5
|
+
* indexed the first match and silently dropped the rest. Now each path is
|
|
6
|
+
* ingested in order; a path that cannot be ingested (a directory, a missing
|
|
7
|
+
* file, a parse error) is reported by name and does NOT stop the others. The
|
|
8
|
+
* caller exits non-zero if any path failed.
|
|
9
|
+
*/
|
|
10
|
+
import { statSync } from "node:fs";
|
|
11
|
+
/** Why a path is not ingestable before we even try, or null when it looks fine. */
|
|
12
|
+
function preflight(path) {
|
|
13
|
+
let st;
|
|
14
|
+
try {
|
|
15
|
+
st = statSync(path);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return "no such file";
|
|
19
|
+
}
|
|
20
|
+
if (st.isDirectory()) {
|
|
21
|
+
return "is a directory, not a file (pass files, e.g. nox-mem ingest dir/*.md)";
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
export async function ingestMany(paths, deps) {
|
|
26
|
+
let ok = 0;
|
|
27
|
+
let failed = 0;
|
|
28
|
+
for (const path of paths) {
|
|
29
|
+
const problem = preflight(path);
|
|
30
|
+
if (problem) {
|
|
31
|
+
deps.error(`[ERROR] ${path}: ${problem}`);
|
|
32
|
+
failed++;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
const r = await deps.ingestOne(path);
|
|
37
|
+
deps.log(`[INFO] Ingested ${path}: ${r.chunks} chunks (kind=${r.kind}, via=${r.routedTo})`);
|
|
38
|
+
ok++;
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
deps.error(`[ERROR] ${path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
42
|
+
failed++;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (paths.length > 1 || failed > 0) {
|
|
46
|
+
deps.log(`[INFO] ingest: ${ok} ingested, ${failed} failed (of ${paths.length})`);
|
|
47
|
+
}
|
|
48
|
+
return { ok, failed };
|
|
49
|
+
}
|
package/dist/mcp/tools/answer.js
CHANGED
|
@@ -22,6 +22,8 @@
|
|
|
22
22
|
*/
|
|
23
23
|
import { answer as defaultAnswer, AnswerError } from "../../lib/answer/index.js";
|
|
24
24
|
import { recordAnswer, } from "../../lib/answer/telemetry.js";
|
|
25
|
+
import { resolveTemporalFilter } from "../../lib/answer/temporal.js";
|
|
26
|
+
import { TemporalParseError } from "../../lib/dates.js";
|
|
25
27
|
// ─── Input schema ─────────────────────────────────────────────────────────
|
|
26
28
|
export const INPUT_SCHEMA = {
|
|
27
29
|
type: "object",
|
|
@@ -33,6 +35,14 @@ export const INPUT_SCHEMA = {
|
|
|
33
35
|
model: { type: "string" },
|
|
34
36
|
temperature: { type: "number", minimum: 0, maximum: 1 },
|
|
35
37
|
no_citations: { type: "boolean", default: false },
|
|
38
|
+
as_of: {
|
|
39
|
+
type: "string",
|
|
40
|
+
description: "Time-travel: only chunks that existed at this date (ISO 8601 like 2026-05-01, or relative like 7d, 2h, 1w)",
|
|
41
|
+
},
|
|
42
|
+
changed_since: {
|
|
43
|
+
type: "string",
|
|
44
|
+
description: "Recency window: only chunks created or updated after this date (ISO 8601 or relative)",
|
|
45
|
+
},
|
|
36
46
|
},
|
|
37
47
|
required: ["question"],
|
|
38
48
|
additionalProperties: false,
|
|
@@ -90,6 +100,17 @@ export function parseInput(input) {
|
|
|
90
100
|
}
|
|
91
101
|
parsed.noCitations = o.no_citations;
|
|
92
102
|
}
|
|
103
|
+
// An unparseable date is invalid_input (isError), never a silently unfiltered answer.
|
|
104
|
+
try {
|
|
105
|
+
const temporal = resolveTemporalFilter({ asOf: o.as_of, changedSince: o.changed_since });
|
|
106
|
+
if (temporal !== undefined)
|
|
107
|
+
parsed.temporal = temporal;
|
|
108
|
+
}
|
|
109
|
+
catch (err) {
|
|
110
|
+
if (err instanceof TemporalParseError)
|
|
111
|
+
throw new McpInputError(err.message);
|
|
112
|
+
throw err;
|
|
113
|
+
}
|
|
93
114
|
return parsed;
|
|
94
115
|
}
|
|
95
116
|
// ─── Handler factory ──────────────────────────────────────────────────────
|
|
@@ -131,6 +152,8 @@ export const noxMemAnswerTool = {
|
|
|
131
152
|
opts.model = parsed.model;
|
|
132
153
|
if (parsed.temperature !== undefined)
|
|
133
154
|
opts.temperature = parsed.temperature;
|
|
155
|
+
if (parsed.temporal !== undefined)
|
|
156
|
+
opts.temporal = parsed.temporal;
|
|
134
157
|
const run = ctx?.answer ?? defaultAnswer;
|
|
135
158
|
try {
|
|
136
159
|
const res = await run(opts);
|
package/dist/mcp-server.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
3
|
* nox-mem MCP Server — exposes memory tools via Model Context Protocol (stdio)
|
|
4
|
-
* Tools: search, stats, primer, ingest
|
|
4
|
+
* Tools: search, stats, primer, ingest, answer, ... (see TOOLS below)
|
|
5
5
|
*/
|
|
6
6
|
import { closeDb } from "./db.js";
|
|
7
7
|
import { searchHybrid, formatResults } from "./search.js";
|
|
@@ -15,6 +15,7 @@ import { primer } from "./primer.js";
|
|
|
15
15
|
import { createInterface } from "readline";
|
|
16
16
|
import { VERSION } from "./version.js";
|
|
17
17
|
import { parseTemporalFilter } from "./lib/dates.js";
|
|
18
|
+
import { noxMemAnswerTool } from "./mcp/tools/answer.js";
|
|
18
19
|
const SERVER_INFO = {
|
|
19
20
|
name: "nox-mem",
|
|
20
21
|
version: VERSION,
|
|
@@ -199,7 +200,14 @@ const TOOLS = [
|
|
|
199
200
|
},
|
|
200
201
|
required: ["title", "steps"],
|
|
201
202
|
},
|
|
202
|
-
}
|
|
203
|
+
},
|
|
204
|
+
// `nox_mem_answer`: definition + handler live in src/mcp/tools/answer.ts (single code
|
|
205
|
+
// path shared with the CLI and POST /api/answer via lib/answer). Only registered here.
|
|
206
|
+
{
|
|
207
|
+
name: noxMemAnswerTool.name,
|
|
208
|
+
description: noxMemAnswerTool.description,
|
|
209
|
+
inputSchema: noxMemAnswerTool.inputSchema,
|
|
210
|
+
},
|
|
203
211
|
];
|
|
204
212
|
function sendResponse(id, result) {
|
|
205
213
|
const msg = JSON.stringify({ jsonrpc: "2.0", id, result });
|
|
@@ -227,6 +235,20 @@ async function handleRequest(req) {
|
|
|
227
235
|
case "tools/call": {
|
|
228
236
|
const toolName = params?.name;
|
|
229
237
|
const args = (params?.arguments ?? {});
|
|
238
|
+
// The answer tool returns a ready CallToolResult ({content, isError?}): invalid input,
|
|
239
|
+
// a missing GEMINI_API_KEY (llm_error) and every AnswerError come back as isError.
|
|
240
|
+
if (toolName === noxMemAnswerTool.name) {
|
|
241
|
+
try {
|
|
242
|
+
sendResponse(id, await noxMemAnswerTool.handler(args));
|
|
243
|
+
}
|
|
244
|
+
catch (err) {
|
|
245
|
+
sendResponse(id, {
|
|
246
|
+
content: [{ type: "text", text: "Error: " + err.message }],
|
|
247
|
+
isError: true,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
break;
|
|
251
|
+
}
|
|
230
252
|
try {
|
|
231
253
|
let text;
|
|
232
254
|
switch (toolName) {
|
|
@@ -385,16 +407,25 @@ async function handleRequest(req) {
|
|
|
385
407
|
}
|
|
386
408
|
}
|
|
387
409
|
const rl = createInterface({ input: process.stdin });
|
|
410
|
+
// In-flight requests. stdin closing (e.g. `printf '...' | nox-mem-mcp`) must not
|
|
411
|
+
// cut off async tools (answer, search, reflect) before they respond.
|
|
412
|
+
const pending = new Set();
|
|
388
413
|
rl.on("line", (line) => {
|
|
414
|
+
let req;
|
|
389
415
|
try {
|
|
390
|
-
|
|
391
|
-
handleRequest(req);
|
|
416
|
+
req = JSON.parse(line);
|
|
392
417
|
}
|
|
393
418
|
catch {
|
|
394
419
|
sendError(null, -32700, "Parse error");
|
|
420
|
+
return;
|
|
395
421
|
}
|
|
422
|
+
const p = handleRequest(req)
|
|
423
|
+
.catch((err) => sendError(req?.id ?? null, -32603, err.message))
|
|
424
|
+
.finally(() => pending.delete(p));
|
|
425
|
+
pending.add(p);
|
|
396
426
|
});
|
|
397
|
-
rl.on("close", () => {
|
|
427
|
+
rl.on("close", async () => {
|
|
428
|
+
await Promise.allSettled([...pending]);
|
|
398
429
|
closeDb();
|
|
399
430
|
process.exit(0);
|
|
400
431
|
});
|
package/dist/reflect.js
CHANGED
|
@@ -9,7 +9,7 @@ import { getDb } from "./db.js";
|
|
|
9
9
|
import { search, searchHybrid } from "./search.js";
|
|
10
10
|
import { queryEntity, listDecisions } from "./knowledge-graph.js";
|
|
11
11
|
import { findPath } from "./cross-agent-v2.js";
|
|
12
|
-
import { embedText } from "./embed.js";
|
|
12
|
+
import { embedText, queryEmbedTimeoutMs } from "./embed.js";
|
|
13
13
|
import { selectLLMProviderWithFallback, MissingKeyError } from "./providers/index.js";
|
|
14
14
|
const MAX_EVIDENCE_CHARS = 2000;
|
|
15
15
|
const CACHE_TTL_HOURS = 24;
|
|
@@ -219,7 +219,7 @@ export async function reflect(question, options = {}) {
|
|
|
219
219
|
const haveEmbeds = db.prepare("SELECT COUNT(*) AS c FROM reflect_cache WHERE query_embedding IS NOT NULL AND datetime(created_at, '+' || ttl_hours || ' hours') > datetime('now')").get().c;
|
|
220
220
|
if (haveEmbeds > 0)
|
|
221
221
|
try {
|
|
222
|
-
const queryEmbed = await embedText(question);
|
|
222
|
+
const queryEmbed = await embedText(question, { timeoutMs: queryEmbedTimeoutMs() });
|
|
223
223
|
// LIMIT 500 ORDER BY most recent — bounds scan; semantic_hit_count desc keeps hot entries
|
|
224
224
|
const candidates = db.prepare(`SELECT query_hash, query, response, evidence_sources, query_embedding
|
|
225
225
|
FROM reflect_cache
|
package/dist/reindex-errors.js
CHANGED
|
@@ -45,3 +45,22 @@ export class ReindexSourceMissingError extends Error {
|
|
|
45
45
|
this.reason = reason;
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Thrown BEFORE any mutation when the DB being rebuilt is not the DB of the
|
|
50
|
+
* workspace being scanned. With NOX_DB_PATH set and OPENCLAW_WORKSPACE unset,
|
|
51
|
+
* reindex scanned the default /root/.openclaw/workspace and treated every
|
|
52
|
+
* chunk of the NOX_DB_PATH database that did not come from there as an orphan.
|
|
53
|
+
* (With both set and disagreeing, op-audit already aborts — incident 2026-05-25.)
|
|
54
|
+
*/
|
|
55
|
+
export class ReindexWorkspaceMismatchError extends Error {
|
|
56
|
+
dbPath;
|
|
57
|
+
workspaceDbPath;
|
|
58
|
+
constructor(dbPath, workspaceDbPath) {
|
|
59
|
+
super(`[reindex] REFUSED before touching the DB: NOX_DB_PATH=${dbPath} is not the database of the workspace ` +
|
|
60
|
+
`reindex would scan (OPENCLAW_WORKSPACE unset ⇒ default workspace, whose DB is ${workspaceDbPath}). ` +
|
|
61
|
+
`Set OPENCLAW_WORKSPACE to the workspace that owns this DB, or unset NOX_DB_PATH.`);
|
|
62
|
+
this.name = "ReindexWorkspaceMismatchError";
|
|
63
|
+
this.dbPath = dbPath;
|
|
64
|
+
this.workspaceDbPath = workspaceDbPath;
|
|
65
|
+
}
|
|
66
|
+
}
|
package/dist/reindex.js
CHANGED
|
@@ -39,8 +39,8 @@ import { routeIngest } from "./lib/ingest-router.js";
|
|
|
39
39
|
import { existsSync, readdirSync } from "fs";
|
|
40
40
|
import { createHash } from "crypto";
|
|
41
41
|
import { join, resolve } from "path";
|
|
42
|
-
import { ReindexWipeDetectedError, ReindexSourceMissingError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
|
|
43
|
-
export { ReindexWipeDetectedError, ReindexSourceMissingError } from "./reindex-errors.js";
|
|
42
|
+
import { ReindexWipeDetectedError, ReindexSourceMissingError, ReindexWorkspaceMismatchError, MIN_RETENTION_RATIO } from "./reindex-errors.js";
|
|
43
|
+
export { ReindexWipeDetectedError, ReindexSourceMissingError, ReindexWorkspaceMismatchError } from "./reindex-errors.js";
|
|
44
44
|
const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
|
|
45
45
|
// Layer 4: tunable safety thresholds (env-overridable for emergency operations).
|
|
46
46
|
// MIN_RETENTION_RATIO imported from reindex-errors.ts (single source of truth).
|
|
@@ -81,6 +81,16 @@ function collectReindexFiles() {
|
|
|
81
81
|
* passes untouched. Overridable with NOX_REINDEX_ALLOW_WIPE=1.
|
|
82
82
|
*/
|
|
83
83
|
export function assertReindexSource(preCount) {
|
|
84
|
+
// The DB must belong to the workspace being scanned. Only reachable with
|
|
85
|
+
// NOX_DB_PATH set and OPENCLAW_WORKSPACE unset (both set and disagreeing is
|
|
86
|
+
// already refused by op-audit). NOX_DB_PATH pointing at the default
|
|
87
|
+
// workspace's own DB — how origin crons call it — passes.
|
|
88
|
+
if (process.env.NOX_DB_PATH && !process.env.OPENCLAW_WORKSPACE) {
|
|
89
|
+
const dbPath = resolve(process.env.NOX_DB_PATH);
|
|
90
|
+
const workspaceDbPath = resolve(WORKSPACE, "tools", "nox-mem", "nox-mem.db");
|
|
91
|
+
if (dbPath !== workspaceDbPath)
|
|
92
|
+
throw new ReindexWorkspaceMismatchError(dbPath, workspaceDbPath);
|
|
93
|
+
}
|
|
84
94
|
if (ALLOW_WIPE)
|
|
85
95
|
return;
|
|
86
96
|
const roots = reindexRoots();
|
package/dist/search.js
CHANGED
|
@@ -314,8 +314,8 @@ function recordAccess(db, ids, enabled) {
|
|
|
314
314
|
// that; without a key it does not. When — and only when — the AND query returns
|
|
315
315
|
// zero rows, search() retries with an OR of the content terms.
|
|
316
316
|
//
|
|
317
|
-
// Gate NOX_FTS_OR_FALLBACK: "on" always, "off" never, unset/"auto" only when
|
|
318
|
-
// embedding
|
|
317
|
+
// Gate NOX_FTS_OR_FALLBACK: "on" always, "off" never, unset/"auto" only when the
|
|
318
|
+
// RESOLVED embedding provider has no key (production has one ⇒ unchanged there).
|
|
319
319
|
// Read at call time, never frozen at import, so it stays testable in-process.
|
|
320
320
|
const FTS_STOPWORDS = new Set([
|
|
321
321
|
// EN
|
|
@@ -333,8 +333,28 @@ export function ftsOrFallbackEnabled(env = process.env) {
|
|
|
333
333
|
return true;
|
|
334
334
|
if (mode === "off")
|
|
335
335
|
return false;
|
|
336
|
-
|
|
337
|
-
|
|
336
|
+
return !hasResolvedEmbeddingKey(env);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* True when the embedding provider that selectEmbeddingProvider() would resolve
|
|
340
|
+
* (NOX_EMBEDDING_PROVIDER, alias NOX_EMBED_PROVIDER, default "gemini") has the
|
|
341
|
+
* key it needs. Only THAT provider's key counts: a stray OPENAI_API_KEY in the
|
|
342
|
+
* shell of someone on the default gemini provider must not switch the fallback
|
|
343
|
+
* off, because search would then have neither embeddings nor OR. "voyage" is a
|
|
344
|
+
* stub that cannot embed and unknown names throw, so neither has a usable key.
|
|
345
|
+
* Key names mirror src/providers/index.ts.
|
|
346
|
+
*/
|
|
347
|
+
function hasResolvedEmbeddingKey(env) {
|
|
348
|
+
const provider = (env.NOX_EMBEDDING_PROVIDER || env.NOX_EMBED_PROVIDER || "gemini").trim().toLowerCase();
|
|
349
|
+
const generic = env.NOX_EMBEDDING_API_KEY || env.NOX_EMBED_API_KEY;
|
|
350
|
+
switch (provider) {
|
|
351
|
+
case "gemini":
|
|
352
|
+
return Boolean(generic || env.GEMINI_API_KEY);
|
|
353
|
+
case "openai":
|
|
354
|
+
return Boolean(generic || env.OPENAI_API_KEY);
|
|
355
|
+
default:
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
338
358
|
}
|
|
339
359
|
/** OR expression of the non-stopword terms, each double-quoted; null if none is left. */
|
|
340
360
|
export function buildFtsOrQuery(sanitized) {
|
|
@@ -432,7 +452,7 @@ export function search(query, limit = 5, trackAccess = true, filter) {
|
|
|
432
452
|
export async function searchSemantic(query, limit = 5, trackAccess = true, filter) {
|
|
433
453
|
const temporal = buildTemporalClause(filter);
|
|
434
454
|
try {
|
|
435
|
-
const { embedText, semanticSearch, ensureVecTable, countEmbedded } = await import("./embed.js");
|
|
455
|
+
const { embedText, semanticSearch, ensureVecTable, countEmbedded, queryEmbedTimeoutMs } = await import("./embed.js");
|
|
436
456
|
const db = getDb();
|
|
437
457
|
ensureVecTable(db);
|
|
438
458
|
// Check if index has any embeddings
|
|
@@ -443,7 +463,8 @@ export async function searchSemantic(query, limit = 5, trackAccess = true, filte
|
|
|
443
463
|
}
|
|
444
464
|
// G10d: compute entity count once per query (shared cache with FTS path).
|
|
445
465
|
const { count: queryEntityCount } = countQueryEntities(query, db);
|
|
446
|
-
|
|
466
|
+
// Bounded: a slow provider falls back to FTS5 through the catch below.
|
|
467
|
+
const queryEmbedding = await embedText(query, { timeoutMs: queryEmbedTimeoutMs() });
|
|
447
468
|
// vec0 KNN cannot take a WHERE on chunk columns, so the temporal filter is
|
|
448
469
|
// applied to the KNN candidates. Over-fetch when filtering, otherwise a
|
|
449
470
|
// narrow window would leave the top-k almost empty.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nox-mem",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.5.0",
|
|
4
4
|
"description": "Pain-weighted hybrid memory engine: FTS5 + semantic search + knowledge graph, self-hosted on any Linux VPS.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -44,6 +44,9 @@
|
|
|
44
44
|
},
|
|
45
45
|
"files": [
|
|
46
46
|
"dist",
|
|
47
|
+
"!dist/**/__tests__/**",
|
|
48
|
+
"!dist/**/*.test.js",
|
|
49
|
+
"prompts",
|
|
47
50
|
"README.md",
|
|
48
51
|
"LICENSE"
|
|
49
52
|
],
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Extraia do texto abaixo todos os fatos relevantes.
|
|
2
|
+
Retorne APENAS um JSON com esta estrutura exata:
|
|
3
|
+
{
|
|
4
|
+
"decisions": [{"text": "descrição da decisão", "permanent": true}],
|
|
5
|
+
"lessons": [{"text": "descrição da lição", "type": "strategic"}],
|
|
6
|
+
"people": [{"name": "Nome Completo", "info": "informação relevante"}],
|
|
7
|
+
"projects": [{"name": "Nome Projeto", "update": "atualização"}],
|
|
8
|
+
"pending": [{"text": "descrição", "owner": "quem", "deadline": "quando"}]
|
|
9
|
+
}
|
|
10
|
+
Use arrays vazios se não houver itens daquela categoria.
|
|
11
|
+
Tipo de lessons: "strategic" para permanentes, "tactical" para temporárias.
|
|
12
|
+
Texto:
|
|
13
|
+
---
|