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.
Files changed (66) hide show
  1. package/README.md +82 -31
  2. package/dist/api/answer.js +22 -0
  3. package/dist/api-server.js +22 -3
  4. package/dist/cli/answer.js +39 -1
  5. package/dist/db.js +47 -24
  6. package/dist/doctor.js +108 -29
  7. package/dist/embed.js +53 -3
  8. package/dist/index.js +73 -17
  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/dates.js +98 -0
  14. package/dist/lib/db-path.js +57 -0
  15. package/dist/lib/ingest-many.js +49 -0
  16. package/dist/lib/op-audit.js +19 -12
  17. package/dist/lib/reranker.js +4 -1
  18. package/dist/mcp/tools/answer.js +23 -0
  19. package/dist/mcp-server.js +45 -6
  20. package/dist/reflect.js +2 -2
  21. package/dist/reindex-errors.js +45 -0
  22. package/dist/reindex.js +116 -23
  23. package/dist/search.js +111 -16
  24. package/package.json +7 -2
  25. package/prompts/consolidate.txt +13 -0
  26. package/prompts/digest.txt +5 -0
  27. package/dist/__tests__/brief-diversity.test.js +0 -266
  28. package/dist/__tests__/brief.test.js +0 -287
  29. package/dist/__tests__/churn.test.js +0 -66
  30. package/dist/__tests__/edge-typing.test.js +0 -99
  31. package/dist/__tests__/ingest-event.test.js +0 -151
  32. package/dist/__tests__/op-audit-e2e.test.js +0 -130
  33. package/dist/__tests__/pragma-alignment.test.js +0 -123
  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/lib/answer/__tests__/e2e-gemini.test.js +0 -229
  42. package/dist/lib/answer/__tests__/integration-sqlite.test.js +0 -388
  43. package/dist/lib/answer/__tests__/integration.test.js +0 -347
  44. package/dist/lib/answer/__tests__/prompt.test.js +0 -117
  45. package/dist/lib/answer/__tests__/t5-t10.test.js +0 -501
  46. package/dist/lib/api/__tests__/safe-error-message.test.js +0 -155
  47. package/dist/lib/auth/__tests__/localhost-guard.test.js +0 -144
  48. package/dist/lib/error-sanitizer/__tests__/sanitize.test.js +0 -354
  49. package/dist/lib/events/__tests__/bus.test.js +0 -208
  50. package/dist/lib/op-audit-extension/__tests__/ran-at-guard.test.js +0 -109
  51. package/dist/lib/regex-extract/__tests__/extractor.test.js +0 -197
  52. package/dist/lib/regex-extract/__tests__/frontmatter.test.js +0 -75
  53. package/dist/lib/regex-extract/__tests__/ingest-router-l4.test.js +0 -139
  54. package/dist/lib/regex-extract/__tests__/production-wire.test.js +0 -177
  55. package/dist/lib/regex-extract/__tests__/reconcile.test.js +0 -170
  56. package/dist/lib/regex-extract/__tests__/strip-code.test.js +0 -36
  57. package/dist/privacy/__tests__/filter.test.js +0 -352
  58. package/dist/providers/__tests__/conformance-extended.test.js +0 -249
  59. package/dist/providers/__tests__/conformance.test.js +0 -98
  60. package/dist/providers/__tests__/cost-cap.test.js +0 -151
  61. package/dist/providers/__tests__/e2e-real.test.js +0 -79
  62. package/dist/providers/__tests__/factory.test.js +0 -80
  63. package/dist/providers/__tests__/fallback.test.js +0 -223
  64. package/dist/providers/__tests__/gemini.test.js +0 -191
  65. package/dist/providers/__tests__/health.test.js +0 -128
  66. 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
 
@@ -189,14 +214,17 @@ All destructive operations (reindex, consolidate, compact, crystallize, kg-prune
189
214
  After install, verify the engine is healthy:
190
215
 
191
216
  ```bash
192
- # Start the API server (no `serve` subcommand — run the server entry directly)
193
- node "$(npm root -g)/nox-mem/dist/api-server.js" &
217
+ nox-mem doctor # Core must be ✅/⚠️; ⚪ under "Optional integrations" is fine
218
+ nox-mem doctor --quiet # scripts: prints only core problems, exits 1 if one failed
219
+
220
+ # Start the API server (default port 18802; NOX_API_PORT overrides)
221
+ nox-mem-api &
194
222
 
195
- # Check vector coverage (should be close to 1.0). Code default port is 18800.
196
- 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'
197
225
  ```
198
226
 
199
- 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.
200
228
 
201
229
  ---
202
230
 
@@ -204,17 +232,40 @@ A `vectorCoverage` value below 0.99 means some chunks are not yet embedded — r
204
232
 
205
233
  ```
206
234
  nox-mem search "query" — hybrid search (FTS5 + semantic + RRF)
207
- nox-mem ingest <file> — ingest a markdown or entity file
208
- nox-mem reindex — rebuild FTS5 index
235
+ nox-mem search "q" --as-of 2026-05-01 — time-travel: chunks that existed then
236
+ nox-mem search "q" --changed-since 7d — recency window (15m, 2h, 7d, 1w or ISO)
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)
242
+ nox-mem reindex — rebuild the index from $OPENCLAW_WORKSPACE (see warning below)
209
243
  nox-mem vectorize — embed any unembedded chunks
210
244
  nox-mem stats — chunk/entity/vector counts
211
245
  nox-mem kg-build — extract knowledge graph entities
212
- nox-mem reflect — surface high-salience insights
213
- node dist/api-server.js — start HTTP API on $NOX_API_PORT (code default 18800)
214
- node dist/mcp-server.js — start MCP server (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)
249
+ nox-mem doctor — health check (core + optional integrations)
215
250
  nox-mem --help — full command reference
216
251
  ```
217
252
 
253
+ Wire the MCP server into Claude Code:
254
+
255
+ ```bash
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
257
+ ```
258
+
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.
262
+
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`.
264
+
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.
266
+
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.
268
+
218
269
  ---
219
270
 
220
271
  ## sqlite-vec and platform binaries
@@ -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";
@@ -18,9 +18,11 @@ import { applyCorsHeaders, handlePreflight } from "./api/cors.js";
18
18
  import { safeErrorMessage } from "./lib/api/safe-error-message.js";
19
19
  import { registerWireUpRoutes } from "./api/wire-up.js";
20
20
  import { handleBrief } from "./api/brief.js";
21
+ import { parseTemporalFilter, TemporalParseError } from "./lib/dates.js";
21
22
  import { handleIngestEvent } from "./api/ingest-event.js";
23
+ import { resolveApiPort } from "./lib/api-port.js";
22
24
  import { handleObsHealth, handleObsRecentOps, handleObsCanaryTail, } from "./observability.js";
23
- const PORT = parseInt(process.env.NOX_API_PORT || "18800");
25
+ const PORT = resolveApiPort();
24
26
  // Security 2026-04-23: bind to loopback by default (was 0.0.0.0).
25
27
  // retentionDistribution + chunks/types fields are info-leak if exposed publicly
26
28
  // in case UFW drops. Override via NOX_API_HOST=0.0.0.0 only if behind VPN/reverse proxy.
@@ -381,22 +383,39 @@ async function handleRequest(req, res) {
381
383
  let qText;
382
384
  let limitStr;
383
385
  let trackStr;
386
+ let asOfStr;
387
+ let changedSinceStr;
384
388
  if (req.method === "POST") {
385
389
  const body = await readJson(req);
386
390
  qText = body.q ?? body.query;
387
391
  limitStr = body.limit !== undefined ? String(body.limit) : undefined;
388
392
  trackStr = body.track !== undefined ? String(body.track) : undefined;
393
+ asOfStr = body.as_of;
394
+ changedSinceStr = body.changed_since;
389
395
  }
390
396
  else {
391
397
  const q = parseQuery(url);
392
398
  qText = q.q ?? q.query;
393
399
  limitStr = q.limit;
394
400
  trackStr = q.track;
401
+ asOfStr = q.as_of;
402
+ changedSinceStr = q.changed_since;
395
403
  }
396
404
  if (!qText) {
397
405
  json(res, { error: "q parameter required (POST body or GET query string, field name: q or query)" }, 400);
398
406
  break;
399
407
  }
408
+ // P3: an unparseable date is a 400, never a silently unfiltered search.
409
+ let temporalFilter;
410
+ try {
411
+ temporalFilter = parseTemporalFilter({ asOf: asOfStr, changedSince: changedSinceStr });
412
+ }
413
+ catch (err) {
414
+ if (!(err instanceof TemporalParseError))
415
+ throw err;
416
+ json(res, { error: err.message }, 400);
417
+ break;
418
+ }
400
419
  const limit = parseInt(limitStr || "10");
401
420
  // D1 (2026-06-07): healthchecks/canary pass ?track=false so automated
402
421
  // probes don't inflate access_count → salience feedback loop. Default
@@ -405,7 +424,7 @@ async function handleRequest(req, res) {
405
424
  // E12 (2026-05-04): propagate requesting agent from header
406
425
  const agentHeader = req.headers["x-agent-name"];
407
426
  const requestingAgent = (Array.isArray(agentHeader) ? agentHeader[0] : agentHeader) ?? process.env.NOX_AGENT_NAME;
408
- const results = await searchHybrid(qText, limit, trackAccess);
427
+ const results = await searchHybrid(qText, limit, trackAccess, temporalFilter);
409
428
  // E03a (2026-05-02): SPO injection envelope. Mode shadow → compute+log only.
410
429
  // Mode active → surface vaultFacts in response. Mode off → no compute.
411
430
  const vf = getVaultFacts(qText, getDb());
@@ -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,52 +4,62 @@ 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, ensureDbParentDir } from "./lib/db-path.js";
8
+ let _warnedNodeModules = false;
7
9
  const __dirname = dirname(fileURLToPath(import.meta.url));
8
10
  const _ws = process.env.OPENCLAW_WORKSPACE;
9
- // DB path resolution — priority order (postmortem 2026-05-19 fix):
11
+ // DB path resolution — priority order (postmortem 2026-05-19 fix), now shared
12
+ // with op-audit via src/lib/db-path.ts so the pre-op snapshot always covers the
13
+ // file this module opens:
10
14
  // 1. NOX_DB_PATH env var (explicit override for eval/test isolation)
11
15
  // 2. OPENCLAW_WORKSPACE-derived canonical path (production default)
12
- // 3. Relative fallback for local dev
16
+ // 3. <package root>/nox-mem.db, only if it already exists (legacy installs)
17
+ // 4. ~/.nox-mem/nox.db (standalone default — never inside node_modules)
13
18
  //
14
19
  // WARNING: Before this fix, only OPENCLAW_WORKSPACE was consulted. Any caller
15
20
  // that set NOX_DB_PATH (e.g. G3 eval orchestrator, run_locomo_ablations.sh)
16
21
  // was silently ignored — `nox-mem ingest` always wrote to the production DB.
17
22
  // Root cause of the 2026-05-19 wipe incident (500 eval chunks → prod).
18
- export const DB_PATH = (process.env.NOX_DB_PATH
19
- ? resolve(process.env.NOX_DB_PATH)
20
- : _ws
21
- ? resolve(_ws, "tools", "nox-mem", "nox-mem.db")
22
- : resolve(__dirname, "..", "nox-mem.db"));
23
- export const BACKUP_DIR = _ws ? resolve(_ws, "tools", "nox-mem", "backups") : resolve(__dirname, "..", "backups");
23
+ const _resolvedDb = resolveDbPathWithSource();
24
+ export const DB_PATH = _resolvedDb.path;
25
+ // Backups live next to the DB. For the legacy package path this is the same
26
+ // directory as before (<package root>/backups); it only moves for new installs.
27
+ export const BACKUP_DIR = _ws ? resolve(_ws, "tools", "nox-mem", "backups") : resolve(dirname(DB_PATH), "backups");
24
28
  const SCHEMA_VERSION = 19;
25
29
  // ────────────────────────────────────────────────────────────────────────────
26
30
  // Large-DB ingest guard (postmortem 2026-05-19)
27
31
  // ────────────────────────────────────────────────────────────────────────────
28
32
  // If the resolved DB has more than PROD_CHUNK_THRESHOLD chunks and the caller
29
- // has not set NOX_ALLOW_PROD_INGEST=1, abort before any write. This prevents
30
- // 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.
31
35
  //
32
- // Threshold: 10,000 chunks. Production is at 68k+; eval DBs start fresh.
33
- // 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)
34
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
+ }
35
56
  export function checkLargeDbIngestGuard(db, operation) {
36
57
  if (process.env.NOX_ALLOW_PROD_INGEST === "1")
37
58
  return;
38
59
  const row = db.prepare("SELECT COUNT(*) AS n FROM chunks").get();
39
60
  const chunkCount = row?.n ?? 0;
40
61
  if (chunkCount > PROD_CHUNK_THRESHOLD) {
41
- const msg = [
42
- `[db] ABORT: Large-DB ingest guard triggered on operation '${operation}'.`,
43
- ` DB path: ${DB_PATH}`,
44
- ` Chunk count: ${chunkCount} (threshold: ${PROD_CHUNK_THRESHOLD})`,
45
- ` This DB appears to be the production nox-mem.db.`,
46
- ` If you intend to ingest into production, set:`,
47
- ` NOX_ALLOW_PROD_INGEST=1 nox-mem ${operation} ...`,
48
- ` If you are running an eval/ablation, ensure NOX_DB_PATH points to an`,
49
- ` isolated eval DB (e.g. /tmp/entity-eval.db), NOT the production path.`,
50
- ` (Root cause of the 2026-05-19 wipe incident — see docs/INCIDENTS.md)`,
51
- ].join("\n");
52
- console.error(msg);
62
+ console.error(largeDbGuardMessage(operation, DB_PATH, chunkCount));
53
63
  process.exit(1);
54
64
  }
55
65
  }
@@ -57,6 +67,19 @@ let _db = null;
57
67
  export function getDb() {
58
68
  if (_db && _db.open)
59
69
  return _db;
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);
77
+ }
78
+ if (_resolvedDb.source === "legacy-package" && isInsideNodeModules(DB_PATH) && !_warnedNodeModules) {
79
+ _warnedNodeModules = true;
80
+ console.error(`[nox-mem] WARNING: database is inside node_modules (${DB_PATH}); \`npm update -g\` replaces that directory. ` +
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`);
82
+ }
60
83
  _db = new Database(DB_PATH);
61
84
  _db.pragma("journal_mode = WAL");
62
85
  _db.pragma("foreign_keys = ON");