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.
Files changed (67) hide show
  1. package/README.md +62 -33
  2. package/dist/api/answer.js +22 -0
  3. package/dist/api-server.js +3 -2
  4. package/dist/cli/answer.js +39 -1
  5. package/dist/db.js +31 -20
  6. package/dist/doctor.js +5 -4
  7. package/dist/embed.js +53 -3
  8. package/dist/index.js +16 -10
  9. package/dist/lib/answer/index.js +3 -2
  10. package/dist/lib/answer/retrieval.js +6 -4
  11. package/dist/lib/answer/temporal.js +51 -0
  12. package/dist/lib/api-port.js +16 -0
  13. package/dist/lib/db-path.js +13 -1
  14. package/dist/lib/ingest-many.js +49 -0
  15. package/dist/mcp/tools/answer.js +23 -0
  16. package/dist/mcp-server.js +36 -5
  17. package/dist/reflect.js +2 -2
  18. package/dist/reindex-errors.js +19 -0
  19. package/dist/reindex.js +12 -2
  20. package/dist/search.js +27 -6
  21. package/package.json +4 -1
  22. package/prompts/consolidate.txt +13 -0
  23. package/prompts/digest.txt +5 -0
  24. package/dist/__tests__/brief-diversity.test.js +0 -266
  25. package/dist/__tests__/brief.test.js +0 -287
  26. package/dist/__tests__/churn.test.js +0 -66
  27. package/dist/__tests__/edge-typing.test.js +0 -99
  28. package/dist/__tests__/fts-or-fallback.test.js +0 -115
  29. package/dist/__tests__/ingest-event.test.js +0 -151
  30. package/dist/__tests__/op-audit-e2e.test.js +0 -130
  31. package/dist/__tests__/pragma-alignment.test.js +0 -123
  32. package/dist/__tests__/reindex-dedup.test.js +0 -80
  33. package/dist/__tests__/reindex-safety.test.js +0 -116
  34. package/dist/__tests__/reranker.test.js +0 -326
  35. package/dist/__tests__/retention.test.js +0 -99
  36. package/dist/__tests__/search-track-access.test.js +0 -49
  37. package/dist/__tests__/session-distill-sources.test.js +0 -98
  38. package/dist/__tests__/spo-injection.test.js +0 -172
  39. package/dist/__tests__/telemetry-per-chunk.test.js +0 -110
  40. package/dist/__tests__/temporal-detector.test.js +0 -103
  41. package/dist/__tests__/temporal-filter.test.js +0 -117
  42. package/dist/lib/answer/__tests__/e2e-gemini.test.js +0 -229
  43. package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
  44. package/dist/lib/answer/__tests__/integration.test.js +0 -347
  45. package/dist/lib/answer/__tests__/prompt.test.js +0 -117
  46. package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
  47. package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
  48. package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
  49. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
  50. package/dist/lib/events/__tests__/bus.test.js +0 -208
  51. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
  52. package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
  53. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
  54. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
  55. package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
  56. package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
  57. package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
  58. package/dist/privacy/__tests__/filter.test.js +0 -352
  59. package/dist/providers/__tests__/conformance-extended.test.js +0 -249
  60. package/dist/providers/__tests__/conformance.test.js +0 -98
  61. package/dist/providers/__tests__/cost-cap.test.js +0 -151
  62. package/dist/providers/__tests__/e2e-real.test.js +0 -79
  63. package/dist/providers/__tests__/factory.test.js +0 -80
  64. package/dist/providers/__tests__/fallback.test.js +0 -223
  65. package/dist/providers/__tests__/gemini.test.js +0 -191
  66. package/dist/providers/__tests__/health.test.js +0 -128
  67. package/dist/providers/__tests__/telemetry.test.js +0 -219
package/README.md CHANGED
@@ -9,12 +9,13 @@ Pain-weighted hybrid memory engine for AI agents. Self-hosted, zero vendor lock-
9
9
  ```bash
10
10
  npm i -g nox-mem
11
11
  export GEMINI_API_KEY=AIza... # https://aistudio.google.com/apikey
12
- export NOX_DB_PATH="$HOME/.nox-mem/nox.db"
13
- export NOX_MEM_DIR="$HOME/.nox-mem/memory"
14
- mkdir -p "$HOME/.nox-mem/memory"
15
- nox-mem stats
12
+ nox-mem stats # first run creates ~/.nox-mem/nox.db
13
+ nox-mem ingest notes/*.md # one or many files
14
+ nox-mem search "what did we decide"
16
15
  ```
17
16
 
17
+ The database defaults to `~/.nox-mem/nox.db`; set `NOX_DB_PATH` to put it elsewhere (its folder is created if missing).
18
+
18
19
  ---
19
20
 
20
21
  ## Prerequisites
@@ -23,16 +24,16 @@ nox-mem stats
23
24
 
24
25
  ```bash
25
26
  apt-get update
26
- apt-get install -y build-essential python3 python3-pip inotify-tools
27
+ apt-get install -y build-essential python3
27
28
  ```
28
29
 
29
- `build-essential` and `python3` are required by `better-sqlite3` (compiles a native addon) and `@xenova/transformers` (optional local embeddings).
30
+ `build-essential` and `python3` matter only when `better-sqlite3` cannot download a prebuilt binary for your platform and has to compile its native addon (`node-gyp` uses `python3`). `inotify-tools` is not needed to install or to run `nox-mem watch`; only the optional systemd script `nox-mem-watch.sh` uses `inotifywait`.
30
31
 
31
32
  ### Node.js 20+
32
33
 
33
34
  ```bash
34
- # Via NodeSource (Ubuntu/Debian)
35
- curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
35
+ # Via NodeSource (Ubuntu/Debian); 22 is the current LTS, 20 is the minimum
36
+ curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
36
37
  apt-get install -y nodejs
37
38
  node --version # expect v20.x or higher
38
39
  ```
@@ -51,8 +52,8 @@ nox-mem stats
51
52
  ### Build from source
52
53
 
53
54
  ```bash
54
- git clone https://github.com/totobusnello/nox-supermem.git
55
- cd nox-supermem/nox-mem
55
+ git clone https://github.com/totobusnello/nox-mem.git
56
+ cd nox-mem/nox-mem
56
57
  npm ci
57
58
  npm run build
58
59
  npm install -g .
@@ -64,10 +65,10 @@ After either method, the `nox-mem` command is available globally.
64
65
 
65
66
  ## Environment variables
66
67
 
67
- Copy `.env.example` to `.env` in your install directory and fill in the required values, then source it before running:
68
+ Put your settings in a `.env` and source it before running (the template is [`.env.example`](https://github.com/totobusnello/nox-mem/blob/main/nox-mem/.env.example) in the GitHub repo; it is **not** shipped in the npm package):
68
69
 
69
70
  ```bash
70
- set -a; source /path/to/.env; set +a
71
+ set -a; source ~/.nox-mem/.env; set +a
71
72
  nox-mem stats
72
73
  ```
73
74
 
@@ -75,9 +76,15 @@ nox-mem stats
75
76
 
76
77
  | Var | Default | Purpose |
77
78
  |---|---|---|
78
- | `GEMINI_API_KEY` | — | Google AI Studio key (default LLM + embedding provider). |
79
- | `NOX_DB_PATH` | `<cwd>/nox-mem.db` | SQLite database path. Its directory is auto-added to the op-audit allowlist. |
80
- | `NOX_MEM_DIR` | — | Directory of markdown memory files to ingest/watch. |
79
+ | `GEMINI_API_KEY` | — | Google AI Studio key (default LLM + embedding provider). Without it search still works as keyword search; `vectorize`, `answer` and `kg-build` need it. |
80
+
81
+ ### Common (all optional)
82
+
83
+ | Var | Default | Purpose |
84
+ |---|---|---|
85
+ | `NOX_DB_PATH` | `~/.nox-mem/nox.db` | SQLite database path. A missing parent directory is created (mode 0700). Its directory is auto-added to the op-audit allowlist. |
86
+ | `NOX_MEM_DIR` | — | **Not** the notes folder: nothing ingests or watches it. It only sets where pre-op snapshots go (`$NOX_MEM_DIR/.nox-snapshots`) and widens the op-audit allowlist. |
87
+ | `NOX_ALLOW_PROD_INGEST` | — | `1` skips the large-database ingest guard (same as `--allow-prod`). See [Large databases](#large-databases-the-ingest-guard). |
81
88
 
82
89
  ### API server
83
90
 
@@ -108,17 +115,17 @@ nox-mem stats
108
115
 
109
116
  | Var | Default | Purpose |
110
117
  |---|---|---|
111
- | `OPENCLAW_WORKSPACE` | `/root/.openclaw/workspace` | Origin platform workspace root (origin/legacy only). |
118
+ | `OPENCLAW_WORKSPACE` | unset | Origin platform workspace root (origin/legacy only). ⚠️ Leave it unset on a standalone install: without `NOX_DB_PATH` it moves the database to `$OPENCLAW_WORKSPACE/tools/nox-mem/nox-mem.db`, a different and empty one. |
112
119
  | `NOX_OP_AUDIT_ALLOWED_PREFIXES` | derived from `NOX_DB_PATH`/`NOX_MEM_DIR` + origin defaults | Comma-sep path prefixes the DB/snapshots may live under. |
113
- | `NOX_PRE_OP_SNAPSHOT_DIR` | `<NOX_MEM_DIR>/.nox-snapshots` (standalone) | Pre-op snapshot directory. |
120
+ | `NOX_PRE_OP_SNAPSHOT_DIR` | `<NOX_MEM_DIR or the DB's folder>/.nox-snapshots` (standalone) | Pre-op snapshot directory. |
114
121
  | `NOX_PROTECTED_NAMES` | empty | Comma-sep names never auto-merged in the KG. |
115
122
  | `NOX_NAME_ALIASES` | empty | `from:To` name-normalization pairs for the KG. |
116
123
  | `NOX_ENTITY_PATTERNS` / `NOX_PROJECT_PATTERNS` | empty | Terms for the legacy regex entity extractor. |
117
124
  | `NOX_KNOWN_PROJECTS` | empty | Project slugs for `project-context-gen`. |
118
125
  | `NOX_AGENTS` / `NOX_AGENTS_DIR` | empty / — | Multi-agent cross-search layout (no-op standalone). |
119
- | `NOX_WATCH_DIRS` | origin layout | Comma-sep dirs for the file watcher. |
126
+ | `NOX_WATCH_DIRS` | OpenClaw layout (`$OPENCLAW_WORKSPACE/memory`, `/shared`, …) | Comma-sep **absolute** dirs for `nox-mem watch`. Standalone: `NOX_WATCH_DIRS="$HOME/notes" nox-mem watch`. Unset on a machine without that layout, the watcher reports "Watching 0 directories". |
120
127
  | `NOX_SPEAKER_FILTER` | empty | One-time V7 migration speaker classification. |
121
- | `NOX_NOTION_TOKEN` / `NOX_NOTION_TOKEN_PATH` | — / `/root/.config/notion/api_key` | Optional Notion sync token (value or file path). |
128
+ | `NOX_NOTION_TOKEN_PATH` | `/root/.config/notion/api_key` | Path of an optional Notion token file (only `doctor` looks at it). |
122
129
 
123
130
  ---
124
131
 
@@ -154,7 +161,7 @@ NOX_LLM_API_KEY=ollama
154
161
 
155
162
  ### Embedding provider
156
163
 
157
- Supported values for `NOX_EMBEDDING_PROVIDER` (alias `NOX_EMBED_PROVIDER`): `gemini` (default) · `openai` (any OpenAI-compat endpoint, including local Ollama/vLLM) · `voyage`.
164
+ Supported values for `NOX_EMBEDDING_PROVIDER` (alias `NOX_EMBED_PROVIDER`): `gemini` (default) · `openai` (any OpenAI-compat endpoint, including local Ollama/vLLM). `voyage` is a stub that cannot embed yet. Any other name (for example `openai-compat`) is rejected.
158
165
 
159
166
  **Example — OpenAI native (3072-dim parity with default Gemini table):**
160
167
  ```bash
@@ -180,7 +187,25 @@ NOX_EMBEDDING_API_KEY=ollama
180
187
 
181
188
  ## Operation audit snapshots
182
189
 
183
- All destructive operations (reindex, consolidate, compact, crystallize, kg-prune) create an atomic SQLite snapshot before mutating data. Snapshots land in `$NOX_PRE_OP_SNAPSHOT_DIR` (default: `/var/backups/nox-mem/pre-op/`). Retention: 7 days. Do NOT restore with raw `cp` — use the `safeRestore()` path or the `--restore` flag which handles WAL/SHM cleanup correctly.
190
+ All destructive operations (reindex, consolidate, compact, crystallize, kg-prune) create an atomic SQLite snapshot before mutating data. On a standalone install snapshots land in `<NOX_MEM_DIR or the database's folder>/.nox-snapshots` (for example `~/.nox-mem/.nox-snapshots/`); `NOX_PRE_OP_SNAPSHOT_DIR` overrides it. Retention: 7 days.
191
+
192
+ There is no restore command in the CLI. To restore, stop `nox-mem-api`, the watcher and anything else using the database, copy the snapshot over the database file, and only then delete the `-wal` and `-shm` files next to it (copying without removing a stale WAL corrupts the database):
193
+
194
+ ```bash
195
+ cp ~/.nox-mem/.nox-snapshots/<snapshot>.db ~/.nox-mem/nox.db
196
+ rm -f ~/.nox-mem/nox.db-wal ~/.nox-mem/nox.db-shm
197
+ ```
198
+
199
+ ### Large databases: the ingest guard
200
+
201
+ Once the database holds more than 10,000 chunks, `ingest`, `ingest-entity` and `watch` refuse to write until you confirm it is the database you mean. The check stops a test or eval script from writing into your real database by accident. Confirm with either:
202
+
203
+ ```bash
204
+ nox-mem ingest --allow-prod notes/*.md # also: ingest-entity, watch
205
+ NOX_ALLOW_PROD_INGEST=1 nox-mem ingest notes/*.md
206
+ ```
207
+
208
+ If the database is not the one you meant, point `NOX_DB_PATH` at another file instead.
184
209
 
185
210
  ---
186
211
 
@@ -192,14 +217,14 @@ After install, verify the engine is healthy:
192
217
  nox-mem doctor # Core must be ✅/⚠️; ⚪ under "Optional integrations" is fine
193
218
  nox-mem doctor --quiet # scripts: prints only core problems, exits 1 if one failed
194
219
 
195
- # Start the API server
220
+ # Start the API server (default port 18802; NOX_API_PORT overrides)
196
221
  nox-mem-api &
197
222
 
198
- # Check vector coverage (should be close to 1.0). Code default port is 18800.
199
- curl -s "http://127.0.0.1:${NOX_API_PORT:-18800}/api/health" | jq .vectorCoverage
223
+ # Vector coverage: embedded / total (should be close to 1.0)
224
+ curl -s "http://127.0.0.1:${NOX_API_PORT:-18802}/api/health" | jq '.vectorCoverage | .embedded/.total'
200
225
  ```
201
226
 
202
- A `vectorCoverage` value below 0.99 means some chunks are not yet embedded — run `nox-mem vectorize` to catch up.
227
+ `vectorCoverage` is an object (`embedded`, `total`, `orphans`, `indexOnly`), not a single number. If `embedded/total` is below 0.99 some chunks are not yet embedded — run `nox-mem vectorize` to catch up.
203
228
 
204
229
  ---
205
230
 
@@ -209,16 +234,18 @@ A `vectorCoverage` value below 0.99 means some chunks are not yet embedded — r
209
234
  nox-mem search "query" — hybrid search (FTS5 + semantic + RRF)
210
235
  nox-mem search "q" --as-of 2026-05-01 — time-travel: chunks that existed then
211
236
  nox-mem search "q" --changed-since 7d — recency window (15m, 2h, 7d, 1w or ISO)
212
- NOX_FTS_OR_FALLBACK=auto|on|off — FTS5 OR retry (stopwords dropped) when the AND query finds nothing; auto (default) = only when no GEMINI_API_KEY/OPENAI_API_KEY is set, so natural-language questions work on keyless installs and keyed setups are unchanged
213
- nox-mem answer "question" — grounded answer with citations (needs GEMINI_API_KEY)
214
- nox-mem ingest <file> — ingest a markdown or entity file (one file per call)
237
+ NOX_FTS_OR_FALLBACK=auto|on|off — FTS5 OR retry (stopwords dropped) when the AND query finds nothing; auto (default) = only when the key of the resolved embedding provider (NOX_EMBEDDING_PROVIDER, default gemini) is missing, so natural-language questions work on keyless installs and keyed setups are unchanged. An unrelated key such as OPENAI_API_KEY under the default gemini provider does not turn it off
238
+ NOX_QUERY_EMBED_TIMEOUT_MS=5000 — time budget for embedding a search/reflect query (retries included). When the provider is slower than this, search falls back to FTS5 instead of waiting. 0 disables the budget. Ingest and vectorize are not affected
239
+ nox-mem answer "question" — grounded answer with citations (needs GEMINI_API_KEY); --as-of / --changed-since filter the evidence
240
+ nox-mem ingest <files...> — ingest one or more markdown/json files; a directory is an error naming it, the other files still run, exit 1 if any failed
241
+ nox-mem watch — auto-ingest changes; set NOX_WATCH_DIRS=/abs/dir[,/abs/dir2] (see Environment variables)
215
242
  nox-mem reindex — rebuild the index from $OPENCLAW_WORKSPACE (see warning below)
216
243
  nox-mem vectorize — embed any unembedded chunks
217
244
  nox-mem stats — chunk/entity/vector counts
218
245
  nox-mem kg-build — extract knowledge graph entities
219
- nox-mem reflect — surface high-salience insights
220
- nox-mem-api — start HTTP API on $NOX_API_PORT (code default 18800)
221
- nox-mem-mcp — start MCP server over stdio (20 tools, for agents)
246
+ nox-mem reflect "question" — synthesis over memory + KG, with cited sources
247
+ nox-mem-api — start HTTP API on $NOX_API_PORT (default 18802)
248
+ nox-mem-mcp — start MCP server over stdio (21 tools, incl. nox_mem_answer, for agents)
222
249
  nox-mem doctor — health check (core + optional integrations)
223
250
  nox-mem --help — full command reference
224
251
  ```
@@ -229,13 +256,15 @@ Wire the MCP server into Claude Code:
229
256
  claude mcp add nox-mem -e NOX_DB_PATH="$HOME/.nox-mem/nox.db" -e GEMINI_API_KEY="$GEMINI_API_KEY" -- nox-mem-mcp
230
257
  ```
231
258
 
232
- The temporal filter is also on HTTP (`?as_of=` / `?changed_since=` on `/api/search`, or the same keys in a POST body) and MCP (`as_of` / `changed_since` on `nox_mem_search`). It is a hard SQL pre-filter on `created_at` / `updated_at` (ingestion time), not a ranking boost. `as_of` answers *which chunks existed then*, not *what they said then*: there is no version history, so a chunk edited after the date comes back with its current text. A bare date means the whole day in UTC (`--as-of 2026-05-01` includes 23:59 that day; `--changed-since 2026-05-01` starts at 00:00); a time without an offset is read as UTC. An unparseable date is an error on every surface (exit 2 / HTTP 400 / MCP `isError`), never a silently unfiltered search.
259
+ HTTP endpoints worth knowing: `GET /api/health`, `GET /api/search?q=`, `GET /api/brief`, `POST /api/answer`, `GET /api/kg`, and `GET /api/reflect?q=…` (synthesis over memory + KG; `q` is required, a request without it is a 400).
260
+
261
+ The temporal filter is also on HTTP (`?as_of=` / `?changed_since=` on `/api/search`, or the same keys in a POST body) and MCP (`as_of` / `changed_since` on `nox_mem_search`). `answer` takes it too: `--as-of` / `--changed-since` on the CLI, and `as_of` / `changed_since` on `POST /api/answer` and on the `nox_mem_answer` MCP tool. A bad or blank date gives exit 2 / HTTP 400 / MCP `isError`. It is a hard SQL pre-filter on `created_at` / `updated_at` (ingestion time), not a ranking boost. `as_of` answers *which chunks existed then*, not *what they said then*: there is no version history, so a chunk edited after the date comes back with its current text. A bare date means the whole day in UTC (`--as-of 2026-05-01` includes 23:59 that day; `--changed-since 2026-05-01` starts at 00:00); a time without an offset is read as UTC. An unparseable date is an error on every surface (exit 2 / HTTP 400 / MCP `isError`), never a silently unfiltered search.
233
262
 
234
263
  > ⚠️ **`reindex` rebuilds only from `$OPENCLAW_WORKSPACE/memory` and `/shared`** (default workspace `/root/.openclaw/workspace`). If that source is missing or empty while the DB holds chunks, it **refuses before touching the DB**; if the rebuild would drop more than 10% of the chunks, it refuses before deleting anything (`NOX_REINDEX_MIN_RETENTION_RATIO`, override `NOX_REINDEX_ALLOW_WIPE=1`). Chunks ingested from outside the workspace are still treated as orphans by a reindex that does run. Preview with `nox-mem reindex --dry-run`. On a standalone install that adds notes with `nox-mem ingest <file>` you normally do not need `reindex`.
235
264
 
236
265
  > **Where the database lives.** `NOX_DB_PATH` if set; else `$OPENCLAW_WORKSPACE/tools/nox-mem/nox-mem.db`; else an existing `<package>/nox-mem.db` (installs from ≤3.4 keep working — with a warning if it sits inside `node_modules`, which `npm update -g` replaces); else `~/.nox-mem/nox.db`. `nox-mem doctor` prints the resolved path.
237
266
 
238
- > Without embeddings, search is FTS5 keyword search, which requires every term to match: prefer keywords (`"zebra migration"`) over full questions (`"when was the zebra migration?"`) until you run `vectorize`.
267
+ > Without embeddings, search is FTS5 keyword search. When every term must match and nothing does, the OR fallback (see `NOX_FTS_OR_FALLBACK` above) retries with the content words, so a full question (`"when was the zebra migration?"`) still finds `zebra migration`. Run `vectorize` for semantic search.
239
268
 
240
269
  ---
241
270
 
@@ -29,6 +29,8 @@
29
29
  import { randomUUID } from "node:crypto";
30
30
  import { answer as defaultAnswer, AnswerError } from "../lib/answer/index.js";
31
31
  import { recordAnswer, } from "../lib/answer/telemetry.js";
32
+ import { resolveTemporalFilter } from "../lib/answer/temporal.js";
33
+ import { TemporalParseError } from "../lib/dates.js";
32
34
  const MARKER_RE = /\s?\[chunk_\d+\]/g;
33
35
  // ─── Body validation ──────────────────────────────────────────────────────
34
36
  function getHeader(headers, name) {
@@ -108,6 +110,22 @@ export function validateBody(body) {
108
110
  }
109
111
  req.trace_id = b.trace_id;
110
112
  }
113
+ // An unparseable date is a 400, never a silently unfiltered answer.
114
+ try {
115
+ const temporal = resolveTemporalFilter({ asOf: b.as_of, changedSince: b.changed_since });
116
+ if (temporal !== undefined)
117
+ req.temporal = temporal;
118
+ }
119
+ catch (err) {
120
+ if (err instanceof TemporalParseError) {
121
+ throw new HttpError(400, "invalid_body", err.message);
122
+ }
123
+ throw err;
124
+ }
125
+ if (typeof b.as_of === "string")
126
+ req.as_of = b.as_of;
127
+ if (typeof b.changed_since === "string")
128
+ req.changed_since = b.changed_since;
111
129
  return req;
112
130
  }
113
131
  // ─── Status-code mapper ───────────────────────────────────────────────────
@@ -179,6 +197,8 @@ export async function handleAnswerRequest(args) {
179
197
  opts.provider = req.provider;
180
198
  if (req.model !== undefined)
181
199
  opts.model = req.model;
200
+ if (req.temporal !== undefined)
201
+ opts.temporal = req.temporal;
182
202
  const run = args.answer ?? defaultAnswer;
183
203
  try {
184
204
  const res = await run(opts);
@@ -270,5 +290,7 @@ export const REQUEST_SCHEMA = {
270
290
  temperature: { type: "number", minimum: 0, maximum: 1 },
271
291
  no_citations: { type: "boolean" },
272
292
  trace_id: { type: "string", maxLength: 64 },
293
+ as_of: { type: "string", minLength: 1 },
294
+ changed_since: { type: "string", minLength: 1 },
273
295
  },
274
296
  };
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * nox-mem API Server — lightweight HTTP API for dashboard consumption
4
- * Port 18800, CORS enabled, JSON responses
4
+ * Port 18802 (override: NOX_API_PORT), CORS enabled, JSON responses
5
5
  */
6
6
  import { createServer } from "http";
7
7
  import { getDb } from "./db.js";
@@ -20,8 +20,9 @@ import { registerWireUpRoutes } from "./api/wire-up.js";
20
20
  import { handleBrief } from "./api/brief.js";
21
21
  import { parseTemporalFilter, TemporalParseError } from "./lib/dates.js";
22
22
  import { handleIngestEvent } from "./api/ingest-event.js";
23
+ import { resolveApiPort } from "./lib/api-port.js";
23
24
  import { handleObsHealth, handleObsRecentOps, handleObsCanaryTail, } from "./observability.js";
24
- const PORT = parseInt(process.env.NOX_API_PORT || "18800");
25
+ const PORT = resolveApiPort();
25
26
  // Security 2026-04-23: bind to loopback by default (was 0.0.0.0).
26
27
  // retentionDistribution + chunks/types fields are info-leak if exposed publicly
27
28
  // in case UFW drops. Override via NOX_API_HOST=0.0.0.0 only if behind VPN/reverse proxy.
@@ -14,12 +14,14 @@
14
14
  * --no-cite suppress citation block (markers still kept inline)
15
15
  * --no-citations strip [chunk_N] markers from rendered answer too
16
16
  * --json machine-readable JSON; suppresses pretty output
17
+ * --as-of X only chunks that existed at X (ISO 8601 or 7d/2h/1w)
18
+ * --changed-since Y only chunks created/updated after Y (ISO 8601 or 7d/2h/1w)
17
19
  * --session-id X passthrough for telemetry correlation
18
20
  * --help, -h print usage and exit 0
19
21
  *
20
22
  * Exit codes (kickoff §6 status-code parity, mapped to shell-friendly ints):
21
23
  * 0 ok
22
- * 2 invalid argv (bad flag, missing question)
24
+ * 2 invalid argv (bad flag, missing question, unparseable --as-of/--changed-since)
23
25
  * 3 retrieval_empty
24
26
  * 4 hallucination_after_retry
25
27
  * 5 llm_error / llm_timeout
@@ -31,6 +33,8 @@
31
33
  */
32
34
  import { answer as defaultAnswer, AnswerError } from "../lib/answer/index.js";
33
35
  import { recordAnswer, } from "../lib/answer/telemetry.js";
36
+ import { resolveTemporalFilter } from "../lib/answer/temporal.js";
37
+ import { TemporalParseError } from "../lib/dates.js";
34
38
  export class CliArgError extends Error {
35
39
  constructor(message) {
36
40
  super(message);
@@ -118,6 +122,20 @@ export function parseArgs(argv) {
118
122
  out.temperature = n;
119
123
  break;
120
124
  }
125
+ case "--as-of": {
126
+ const v = argv[++i];
127
+ if (v === undefined)
128
+ throw new CliArgError(`${tok} requires a value`);
129
+ out.asOf = v;
130
+ break;
131
+ }
132
+ case "--changed-since": {
133
+ const v = argv[++i];
134
+ if (v === undefined)
135
+ throw new CliArgError(`${tok} requires a value`);
136
+ out.changedSince = v;
137
+ break;
138
+ }
121
139
  case "--session-id": {
122
140
  const v = argv[++i];
123
141
  if (v === undefined)
@@ -153,6 +171,10 @@ Flags:
153
171
  --provider X 'gemini' (default) | 'mock'
154
172
  --model Y model id (default gemini-2.5-flash-lite per D41 #1)
155
173
  --temperature N 0..1, default 0.2
174
+ --as-of X time-travel: only chunks that existed at X
175
+ (ISO 8601 like 2026-05-01, or relative like 7d, 2h, 1w)
176
+ --changed-since Y recency window: only chunks created or updated after Y
177
+ (ISO 8601 or relative); combine with --as-of for a range
156
178
  --cite include numbered citation block (default)
157
179
  --no-cite suppress citation block
158
180
  --no-citations also strip [chunk_N] markers from answer text
@@ -163,6 +185,8 @@ Flags:
163
185
  Examples:
164
186
  nox-mem answer "What is the salience formula?"
165
187
  nox-mem answer "Which retention default for lessons?" --top-k 12 --json
188
+ nox-mem answer "What was decided about X?" --as-of 2026-05-01
189
+ nox-mem answer "What changed on X?" --changed-since 7d
166
190
  NOX_ANSWER_MODEL=gemini-2.5-flash nox-mem answer "Provider swap test"
167
191
 
168
192
  Exit codes: 0 ok | 2 bad argv | 3 retrieval_empty | 4 hallucination_after_retry | 5 llm_error
@@ -210,7 +234,21 @@ export async function runCli(opts) {
210
234
  opts.stdout(HELP_TEXT);
211
235
  return 0;
212
236
  }
237
+ // An unparseable (or blank) date is an error, never a silently unfiltered answer.
238
+ let temporal;
239
+ try {
240
+ temporal = resolveTemporalFilter({ asOf: parsed.asOf, changedSince: parsed.changedSince });
241
+ }
242
+ catch (err) {
243
+ if (err instanceof TemporalParseError) {
244
+ opts.stderr(`error: ${err.message}`);
245
+ return 2;
246
+ }
247
+ throw err;
248
+ }
213
249
  const callOpts = { question: parsed.question };
250
+ if (temporal !== undefined)
251
+ callOpts.temporal = temporal;
214
252
  if (parsed.topK !== undefined)
215
253
  callOpts.topK = parsed.topK;
216
254
  if (parsed.maxTokens !== undefined)
package/dist/db.js CHANGED
@@ -4,7 +4,7 @@ import { fileURLToPath } from "url";
4
4
  import { copyFileSync, existsSync, mkdirSync, readdirSync, unlinkSync } from "fs";
5
5
  // @ts-ignore - sqlite-vec ships no type declarations for this helper
6
6
  import { getLoadablePath as vecLoadablePath } from "sqlite-vec";
7
- import { resolveDbPathWithSource, isInsideNodeModules } from "./lib/db-path.js";
7
+ import { resolveDbPathWithSource, isInsideNodeModules, ensureDbParentDir } from "./lib/db-path.js";
8
8
  let _warnedNodeModules = false;
9
9
  const __dirname = dirname(fileURLToPath(import.meta.url));
10
10
  const _ws = process.env.OPENCLAW_WORKSPACE;
@@ -30,30 +30,36 @@ const SCHEMA_VERSION = 19;
30
30
  // Large-DB ingest guard (postmortem 2026-05-19)
31
31
  // ────────────────────────────────────────────────────────────────────────────
32
32
  // If the resolved DB has more than PROD_CHUNK_THRESHOLD chunks and the caller
33
- // has not set NOX_ALLOW_PROD_INGEST=1, abort before any write. This prevents
34
- // eval/test ingests from silently polluting a large production DB.
33
+ // has not opted in, abort before any write. This stops an eval/test ingest from
34
+ // silently polluting a large, real database.
35
35
  //
36
- // Threshold: 10,000 chunks. Production is at 68k+; eval DBs start fresh.
37
- // Override: NOX_ALLOW_PROD_INGEST=1 (explicit, auditable, required for prod ops)
36
+ // Threshold: 10,000 chunks. A personal memory that grows past it will hit this
37
+ // on the next `ingest`/`watch`; that is expected, and the opt-in is one flag:
38
+ // nox-mem ingest --allow-prod <files...> (also: ingest-entity, watch)
39
+ // NOX_ALLOW_PROD_INGEST=1 nox-mem ingest ... (works for every command)
38
40
  const PROD_CHUNK_THRESHOLD = 10_000;
41
+ /** The text printed when the guard trips. Exported so the wording is testable. */
42
+ export function largeDbGuardMessage(operation, dbPath, chunkCount) {
43
+ return [
44
+ `[nox-mem] ABORT: '${operation}' refused because this database is large.`,
45
+ ` DB path: ${dbPath}`,
46
+ ` Chunk count: ${chunkCount} (guard limit: ${PROD_CHUNK_THRESHOLD})`,
47
+ ` Why: past ${PROD_CHUNK_THRESHOLD} chunks the database is assumed to be one you care about, and this`,
48
+ ` check stops a test or eval script from writing into it by accident.`,
49
+ ` If this IS the database you want to write to, confirm it with either:`,
50
+ ` nox-mem ${operation} --allow-prod ... (ingest, ingest-entity, watch)`,
51
+ ` NOX_ALLOW_PROD_INGEST=1 nox-mem ${operation} ...`,
52
+ ` If it is not, point NOX_DB_PATH at a separate database instead, e.g.:`,
53
+ ` NOX_DB_PATH=/tmp/scratch.db nox-mem ${operation} ...`,
54
+ ].join("\n");
55
+ }
39
56
  export function checkLargeDbIngestGuard(db, operation) {
40
57
  if (process.env.NOX_ALLOW_PROD_INGEST === "1")
41
58
  return;
42
59
  const row = db.prepare("SELECT COUNT(*) AS n FROM chunks").get();
43
60
  const chunkCount = row?.n ?? 0;
44
61
  if (chunkCount > PROD_CHUNK_THRESHOLD) {
45
- const msg = [
46
- `[db] ABORT: Large-DB ingest guard triggered on operation '${operation}'.`,
47
- ` DB path: ${DB_PATH}`,
48
- ` Chunk count: ${chunkCount} (threshold: ${PROD_CHUNK_THRESHOLD})`,
49
- ` This DB appears to be the production nox-mem.db.`,
50
- ` If you intend to ingest into production, set:`,
51
- ` NOX_ALLOW_PROD_INGEST=1 nox-mem ${operation} ...`,
52
- ` If you are running an eval/ablation, ensure NOX_DB_PATH points to an`,
53
- ` isolated eval DB (e.g. /tmp/entity-eval.db), NOT the production path.`,
54
- ` (Root cause of the 2026-05-19 wipe incident — see docs/INCIDENTS.md)`,
55
- ].join("\n");
56
- console.error(msg);
62
+ console.error(largeDbGuardMessage(operation, DB_PATH, chunkCount));
57
63
  process.exit(1);
58
64
  }
59
65
  }
@@ -61,10 +67,15 @@ let _db = null;
61
67
  export function getDb() {
62
68
  if (_db && _db.open)
63
69
  return _db;
64
- if (_resolvedDb.source === "standalone-default") {
65
- mkdirSync(dirname(DB_PATH), { recursive: true });
70
+ // Create the parent directory for every source that can point at a directory
71
+ // that does not exist yet (an explicit NOX_DB_PATH, the OPENCLAW_WORKSPACE
72
+ // layout, the ~/.nox-mem default) instead of crashing with "Cannot open
73
+ // database because the directory does not exist". Legacy package paths
74
+ // already exist by definition.
75
+ if (_resolvedDb.source !== "legacy-package") {
76
+ ensureDbParentDir(DB_PATH);
66
77
  }
67
- else if (_resolvedDb.source === "legacy-package" && isInsideNodeModules(DB_PATH) && !_warnedNodeModules) {
78
+ if (_resolvedDb.source === "legacy-package" && isInsideNodeModules(DB_PATH) && !_warnedNodeModules) {
68
79
  _warnedNodeModules = true;
69
80
  console.error(`[nox-mem] WARNING: database is inside node_modules (${DB_PATH}); \`npm update -g\` replaces that directory. ` +
70
81
  `Move it and set NOX_DB_PATH, e.g.: mkdir -p ~/.nox-mem && mv "${DB_PATH}" ~/.nox-mem/nox.db && export NOX_DB_PATH=~/.nox-mem/nox.db`);
package/dist/doctor.js CHANGED
@@ -6,8 +6,8 @@ const WATCHER_UNITS = ["nox-mem-watcher.service", "nox-mem-watch.service"];
6
6
  /**
7
7
  * Two groups, deliberately:
8
8
  * core — the store, FTS5 and embeddings. A ❌ here means ingest/search is broken.
9
- * optional — integrations only some commands use (Ollama for consolidate /
10
- * kg-extract, Notion, the systemd watcher). Absent ⇒ ⚪, never ❌:
9
+ * optional — integrations only some commands use (Ollama as `digest`'s
10
+ * last-resort fallback, Notion, the systemd watcher). Absent ⇒ ⚪, never ❌:
11
11
  * a fresh install without them is healthy.
12
12
  *
13
13
  * `--quiet` prints only core problems and exits 1 iff a core check failed —
@@ -64,7 +64,8 @@ export async function doctor(opts = {}) {
64
64
  core.push({ name: "SQLite DB", status: "❌", detail: `${err}` });
65
65
  }
66
66
  // ── Optional integrations ──────────────────────────────────────────────────
67
- // Ollama — used by consolidate / kg-extract only
67
+ // Ollama — only the last-resort fallback of `digest` (consolidate and
68
+ // kg-extract use Gemini/Groq/Claude and never call it)
68
69
  try {
69
70
  const response = await fetch("http://127.0.0.1:11434/api/tags", { signal: AbortSignal.timeout(5000) });
70
71
  if (response.ok) {
@@ -77,7 +78,7 @@ export async function doctor(opts = {}) {
77
78
  }
78
79
  }
79
80
  catch {
80
- optional.push({ name: "Ollama", status: "⚪", detail: "not running (optional — used by consolidate and kg-extract)" });
81
+ optional.push({ name: "Ollama", status: "⚪", detail: "not running (optional — only `digest` falls back to it; consolidate uses Gemini, then Groq, then Claude)" });
81
82
  }
82
83
  // Notion token
83
84
  const notionTokenPath = process.env.NOX_NOTION_TOKEN_PATH ?? "/root/.config/notion/api_key";
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
@@ -79,10 +79,10 @@ program
79
79
  closeDb();
80
80
  });
81
81
  program
82
- .command("ingest <file>")
83
- .description("Index a specific .md or .json file")
84
- .option("--allow-prod", "Skip large-DB ingest guard (required for prod ops, see CLAUDE.md §6)")
85
- .action(async (file, opts) => {
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) => {
86
86
  // Large-DB guard (postmortem 2026-05-19): abort if DB looks like prod
87
87
  // and operator hasn't explicitly opted in. Override via --allow-prod flag
88
88
  // or NOX_ALLOW_PROD_INGEST=1 env var.
@@ -91,9 +91,15 @@ program
91
91
  }
92
92
  checkLargeDbIngestGuard(getDb(), "ingest");
93
93
  const { routeIngest } = await import("./lib/ingest-router.js");
94
- const result = await routeIngest(file);
95
- console.log(`[INFO] Ingested ${file}: ${result.chunks} chunks (kind=${result.kind}, via=${result.routedTo})`);
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
+ });
96
100
  closeDb();
101
+ if (failed > 0)
102
+ process.exitCode = 1;
97
103
  });
98
104
  program
99
105
  .command("ingest-entity <file>")
@@ -121,7 +127,7 @@ program
121
127
  }
122
128
  catch (err) {
123
129
  const name = err.name;
124
- if (name === "ReindexSourceMissingError" || name === "ReindexWipeDetectedError") {
130
+ if (name === "ReindexSourceMissingError" || name === "ReindexWipeDetectedError" || name === "ReindexWorkspaceMismatchError") {
125
131
  console.error(err.message);
126
132
  process.exitCode = 1;
127
133
  return;
@@ -148,7 +154,7 @@ program
148
154
  });
149
155
  program
150
156
  .command("consolidate")
151
- .description("Consolidate daily notes into topic files (requires Ollama)")
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)")
152
158
  .action(async () => {
153
159
  const { consolidate } = await import("./consolidate.js");
154
160
  const result = await consolidate();
@@ -175,7 +181,7 @@ program
175
181
  });
176
182
  program
177
183
  .command("doctor")
178
- .description("Diagnostic check — core (SQLite, FTS5, embeddings) + optional integrations (Ollama, Notion, watcher)")
184
+ .description("Diagnostic check — core (SQLite, FTS5, embeddings) + optional integrations (Ollama for digest, Notion, watcher)")
179
185
  .option("--quiet", "Print only core problems; exit 1 if a core check fails")
180
186
  .action(async (opts) => {
181
187
  const { doctor } = await import("./doctor.js");
@@ -400,7 +406,7 @@ program
400
406
  // ─── Knowledge Graph v2: LLM extraction ──────────────────────────────────────
401
407
  program
402
408
  .command("kg-extract")
403
- .description("Extract entities/relations from chunks using LLM (Ollama)")
409
+ .description("Extract entities/relations from chunks using Gemini (needs GEMINI_API_KEY)")
404
410
  .option("-n, --limit <n>", "Chunks to process", "50")
405
411
  .action(async (opts) => {
406
412
  const { extractWithLLM } = await import("./kg-llm.js");