nox-mem 3.5.2 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -115,15 +115,16 @@ nox-mem stats
115
115
 
116
116
  | Var | Default | Purpose |
117
117
  |---|---|---|
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. |
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. See [the workspace root](#where-files-are-keyed-from). |
119
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. |
120
120
  | `NOX_PRE_OP_SNAPSHOT_DIR` | `<NOX_MEM_DIR or the DB's folder>/.nox-snapshots` (standalone) | Pre-op snapshot directory. |
121
121
  | `NOX_PROTECTED_NAMES` | empty | Comma-sep names never auto-merged in the KG. |
122
122
  | `NOX_NAME_ALIASES` | empty | `from:To` name-normalization pairs for the KG. |
123
123
  | `NOX_ENTITY_PATTERNS` / `NOX_PROJECT_PATTERNS` | empty | Terms for the legacy regex entity extractor. |
124
124
  | `NOX_KNOWN_PROJECTS` | empty | Project slugs for `project-context-gen`. |
125
+ | `NOX_AGENT_NAME` | unset | Who is searching, written to `search_telemetry.requesting_agent` as `<surface>:<agent>` (`mcp:atlas`, `cli:unknown`; searches with `track=false` become `probe:<agent>`). Over HTTP the `X-Agent-Name` header wins. Only `[a-z0-9_.-]{1,40}` is kept; anything else is recorded as `invalid`. |
125
126
  | `NOX_AGENTS` / `NOX_AGENTS_DIR` | empty / — | Multi-agent cross-search layout (no-op standalone). |
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". |
127
+ | `NOX_WATCH_DIRS` | `<workspace>/memory`, `/shared` (+ OpenClaw agent folders) | Comma-sep **absolute** dirs for `nox-mem watch`. Unset on a standalone install it watches `~/.nox-mem/memory` (and `~/.nox-mem/shared` if present). Other folders: `NOX_WATCH_DIRS="$HOME/notes" nox-mem watch`. |
127
128
  | `NOX_SPEAKER_FILTER` | empty | One-time V7 migration speaker classification. |
128
129
  | `NOX_NOTION_TOKEN_PATH` | `/root/.config/notion/api_key` | Path of an optional Notion token file (only `doctor` looks at it). |
129
130
 
@@ -239,7 +240,10 @@ NOX_QUERY_EMBED_TIMEOUT_MS=5000 — time budget for embedding a search/reflect q
239
240
  nox-mem answer "question" — grounded answer with citations (needs GEMINI_API_KEY); --as-of / --changed-since filter the evidence
240
241
  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
242
  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)
243
+ nox-mem reindex — rebuild the index from <workspace>/memory and /shared (see warning below)
244
+ nox-mem tombstones — files gone from disk whose chunks are still stored (review queue); --all, --json
245
+ nox-mem tombstone-keep <f> — review outcome: keep that content on purpose
246
+ nox-mem tombstone-purge <f> — delete a tombstoned file's chunks (snapshot first; --dry-run)
243
247
  nox-mem vectorize — embed any unembedded chunks
244
248
  nox-mem stats — chunk/entity/vector counts
245
249
  nox-mem kg-build — extract knowledge graph entities
@@ -260,7 +264,11 @@ HTTP endpoints worth knowing: `GET /api/health`, `GET /api/search?q=`, `GET /api
260
264
 
261
265
  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
266
 
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`.
267
+ > ⚠️ **`reindex` rebuilds only from `<workspace>/memory` and `/shared`** (`~/.nox-mem` on a standalone install; see below). If that source is missing or empty while the DB holds chunks, it **refuses before touching the DB**. It runs in one transaction: if the rebuild would drop more than 10% of the distinct content, it rolls back before commit (`NOX_REINDEX_MIN_RETENTION_RATIO`, override `NOX_REINDEX_ALLOW_WIPE=1`). Files under those two folders that left the disk are tombstoned, not deleted, and chunks ingested from anywhere else are left alone. 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`.
268
+
269
+ > **Re-ingesting and deleting files.** Ingest compares a file's chunks with what is stored: unchanged chunks keep their id, embedding and access history, so re-saving a file costs nothing and references to its chunks (briefs, telemetry, knowledge-graph evidence) stay valid. Only new or edited text is written and embedded. When a file is deleted or moved away, its chunks are **not** removed: the watcher (or the next `reindex`) records a tombstone, the chunks stay searchable, and `nox-mem tombstones` lists them for review. If the same text shows up under a new path, the new file takes over the existing rows (a rename keeps ids). Chunks are only deleted by `nox-mem tombstone-purge <file>`, which takes a snapshot first.
270
+
271
+ > <a id="where-files-are-keyed-from"></a>**Where files are keyed from.** Every stored chunk records its file relative to a workspace root, and the layout under it means something: `memory/entities/<type>/` files get the entity format, `memory/` and `shared/` are what `reindex` and `watch` cover. The root is `$OPENCLAW_WORKSPACE` if set; else `/root/.openclaw/workspace` if that directory exists; else **`~/.nox-mem`**, so on a standalone install notes in `~/.nox-mem/memory` are keyed `memory/…` and files elsewhere `../…`. Up to 3.5.x a standalone install keyed everything relative to `/root/.openclaw/workspace` (`../../../home/you/…`), so entity files were ingested as plain notes; the first open under 3.6.0 (schema 20) rewrites those keys once and leaves a copy of the database at `<db>.pre-v20-keys.bak`. Re-ingest your `memory/entities/` files afterwards to get the entity format.
264
272
 
265
273
  > **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
274
 
package/dist/api/brief.js CHANGED
@@ -163,6 +163,20 @@ export function titleFromSourceFile(sourceFile) {
163
163
  const base = sourceFile.split("/").pop() || sourceFile;
164
164
  return base.replace(/\.(md|txt|json|jsonl)$/i, "");
165
165
  }
166
+ /**
167
+ * Título exibido (2026-10-15). Itens distilled têm source_file "sessions/<agente>/<agente>:<uuid>", e o
168
+ * basename era só o id da sessão. Exibe "sessão <agente> <data>". Só renderização: dedup e diversidade
169
+ * continuam com titleFromSourceFile, então a seleção não muda.
170
+ */
171
+ const SESSION_TITLE = /^([a-z0-9_-]+):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
172
+ export function displayTitle(title, chunkType, contentDate) {
173
+ if (chunkType !== "distilled")
174
+ return title;
175
+ const m = SESSION_TITLE.exec(title);
176
+ if (!m)
177
+ return title;
178
+ return contentDate ? `sessão ${m[1]} ${contentDate.slice(0, 10)}` : `sessão ${m[1]}`;
179
+ }
166
180
  // ─── brief_log (única escrita do endpoint — schema próprio, zero ALTER) ─────
167
181
  let briefLogReady = false;
168
182
  export function ensureBriefLog(db) {
@@ -316,7 +330,7 @@ function toItems(picked, nowMs) {
316
330
  : 0;
317
331
  return {
318
332
  id: row.id,
319
- title,
333
+ title: displayTitle(title, row.chunk_type, ref ?? null),
320
334
  one_liner: oneLiner,
321
335
  type: row.chunk_type,
322
336
  pain: row.pain ?? 0.2,
@@ -413,7 +413,7 @@ async function handleRequest(req, res) {
413
413
  // E12 (2026-05-04): propagate requesting agent from header
414
414
  const agentHeader = req.headers["x-agent-name"];
415
415
  const requestingAgent = (Array.isArray(agentHeader) ? agentHeader[0] : agentHeader) ?? process.env.NOX_AGENT_NAME;
416
- const results = await searchHybrid(qText, limit, trackAccess, temporalFilter);
416
+ const results = await searchHybrid(qText, limit, trackAccess, temporalFilter, { surface: "http", agent: requestingAgent });
417
417
  // E03a (2026-05-02): SPO injection envelope. Mode shadow → compute+log only.
418
418
  // Mode active → surface vaultFacts in response. Mode off → no compute.
419
419
  const vf = getVaultFacts(qText, getDb());
@@ -8,8 +8,9 @@ import { isDuplicate as semanticIsDuplicate } from "./dedup.js";
8
8
  import { updateSessionState } from "./session-update.js";
9
9
  import { incrementMetric } from "./metrics.js";
10
10
  import { isNoise, learnNoise } from "./noise-filter.js";
11
+ import { workspaceRoot } from "./lib/workspace.js";
11
12
  const __dirname = dirname(fileURLToPath(import.meta.url));
12
- const WORKSPACE = process.env.OPENCLAW_WORKSPACE ?? "/root/.openclaw/workspace";
13
+ const WORKSPACE = workspaceRoot();
13
14
  const GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent";
14
15
  const ANTHROPIC_URL = "https://api.anthropic.com/v1/messages";
15
16
  const ANTHROPIC_VERSION = "2023-06-01";
package/dist/db.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import Database from "better-sqlite3";
2
- import { resolve, dirname } from "path";
2
+ import { resolve, dirname, relative } from "path";
3
3
  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
7
  import { resolveDbPathWithSource, isInsideNodeModules, ensureDbParentDir } from "./lib/db-path.js";
8
+ import { ORIGIN_WORKSPACE, workspaceRootWithSource } from "./lib/workspace.js";
8
9
  let _warnedNodeModules = false;
9
10
  const __dirname = dirname(fileURLToPath(import.meta.url));
10
11
  const _ws = process.env.OPENCLAW_WORKSPACE;
@@ -25,7 +26,7 @@ export const DB_PATH = _resolvedDb.path;
25
26
  // Backups live next to the DB. For the legacy package path this is the same
26
27
  // directory as before (<package root>/backups); it only moves for new installs.
27
28
  export const BACKUP_DIR = _ws ? resolve(_ws, "tools", "nox-mem", "backups") : resolve(dirname(DB_PATH), "backups");
28
- const SCHEMA_VERSION = 19;
29
+ const SCHEMA_VERSION = 20;
29
30
  // ────────────────────────────────────────────────────────────────────────────
30
31
  // Large-DB ingest guard (postmortem 2026-05-19)
31
32
  // ────────────────────────────────────────────────────────────────────────────
@@ -203,10 +204,94 @@ function ensureSchema(db) {
203
204
  migrateToV8(db);
204
205
  if (currentVersion < 19)
205
206
  migrateToV9(db);
207
+ if (currentVersion < 20)
208
+ migrateToV20(db);
206
209
  db.prepare("INSERT OR REPLACE INTO meta (key, value, updated_at) VALUES ('schema_version', ?, datetime('now'))").run(String(SCHEMA_VERSION));
207
210
  // Keep PRAGMA user_version in sync so op-audit and tests can rely on it.
208
211
  db.pragma(`user_version = ${SCHEMA_VERSION}`);
209
212
  }
213
+ function migrateToV20(db) {
214
+ // v20 — who searched, and whether the query carried a temporal expression.
215
+ //
216
+ // `requesting_agent` is `<surface>:<agent>` (`http:nox`, `mcp:unknown`,
217
+ // `probe:semantic-canary`), never NULL from the writer, so NULL keeps meaning
218
+ // "row written before v20". Without it a probe and an agent look the same: in
219
+ // the canonical engine's telemetry 62.8% of searches were probes.
220
+ //
221
+ // `was_temporal_query` is 0 (none), 1 (temporal word, no date) or 2 (date in
222
+ // the query). It measures the reopening trigger of the implicit temporal
223
+ // rerank, which stays off. DEFAULT 0 matches the canonical engine's column;
224
+ // rows before v20 read 0 without having been measured, so analyses start at
225
+ // the upgrade, not at the first row.
226
+ //
227
+ // Per-column try/catch keeps this idempotent on DBs patched out of band.
228
+ try {
229
+ db.exec(`ALTER TABLE search_telemetry ADD COLUMN requesting_agent TEXT`);
230
+ }
231
+ catch { }
232
+ try {
233
+ db.exec(`ALTER TABLE search_telemetry ADD COLUMN was_temporal_query INTEGER DEFAULT 0`);
234
+ }
235
+ catch { }
236
+ migrateStandaloneKeys(db);
237
+ }
238
+ /**
239
+ * v20 — standalone `source_file` keys move to the standalone workspace root.
240
+ *
241
+ * Up to 3.5.x a standalone install keyed files relative to
242
+ * /root/.openclaw/workspace, a directory it does not have
243
+ * (`../../../home/u/.nox-mem/memory/a.md`). 3.6.0 keys them relative to
244
+ * ~/.nox-mem (`memory/a.md`; `../notes/a.md` for a file elsewhere in $HOME).
245
+ * Without rewriting, the next ingest of the same file would write a second copy
246
+ * under the new key.
247
+ *
248
+ * Runs only when the root resolves to "standalone" (no $OPENCLAW_WORKSPACE, no
249
+ * /root/.openclaw/workspace): that is exactly the case where 3.5.x used the
250
+ * origin default as the base, so `resolve(ORIGIN_WORKSPACE, key)` recovers the
251
+ * absolute path. Only `../` keys are touched; nothing else can have come from
252
+ * that base on such a machine.
253
+ *
254
+ * Exported so the test can run it on a crafted DB. A copy of the DB is written
255
+ * first (`<db>.pre-v20-keys.bak`). The rewrite and a `meta` marker commit in one
256
+ * transaction, so a crash cannot apply the conversion twice.
257
+ */
258
+ /** `meta` row that marks the v20 standalone rebase as done. */
259
+ export const STANDALONE_REBASE_MARKER = "standalone-rebase-v20";
260
+ export function migrateStandaloneKeys(db, ws = workspaceRootWithSource()) {
261
+ if (ws.source !== "standalone")
262
+ return 0;
263
+ const done = db.prepare("SELECT 1 FROM meta WHERE key = ?").get(STANDALONE_REBASE_MARKER);
264
+ if (done)
265
+ return 0;
266
+ const tables = ["chunks", "consolidated_files"].filter((t) => db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t));
267
+ const keys = new Set();
268
+ for (const t of tables) {
269
+ for (const r of db.prepare(`SELECT DISTINCT source_file FROM ${t} WHERE source_file LIKE '../%'`).all()) {
270
+ keys.add(r.source_file);
271
+ }
272
+ }
273
+ const markStmt = db.prepare("INSERT OR REPLACE INTO meta (key, value, updated_at) VALUES (?, ?, datetime('now'))");
274
+ const mark = (n) => markStmt.run(STANDALONE_REBASE_MARKER, n);
275
+ if (keys.size === 0) {
276
+ mark("0");
277
+ return 0;
278
+ }
279
+ if (db.name && db.name !== ":memory:") {
280
+ const bak = `${db.name}.pre-v20-keys.bak`;
281
+ if (!existsSync(bak))
282
+ db.exec(`VACUUM INTO '${bak.replace(/'/g, "''")}'`);
283
+ }
284
+ db.transaction(() => {
285
+ for (const old of keys) {
286
+ const next = relative(ws.root, resolve(ORIGIN_WORKSPACE, old));
287
+ for (const t of tables)
288
+ db.prepare(`UPDATE OR IGNORE ${t} SET source_file = ? WHERE source_file = ?`).run(next, old);
289
+ }
290
+ mark(String(keys.size));
291
+ })();
292
+ console.error(`[nox-mem] schema v20: ${keys.size} file keys rebased onto ${ws.root} (backup: ${db.name}.pre-v20-keys.bak)`);
293
+ return keys.size;
294
+ }
210
295
  function migrateToV9(db) {
211
296
  // v19 — per-chunk search telemetry.
212
297
  //
package/dist/digest.js CHANGED
@@ -3,8 +3,9 @@ import { resolve, dirname } from "path";
3
3
  import { fileURLToPath } from "url";
4
4
  import { execFileSync } from "child_process";
5
5
  import { getDb } from "./db.js";
6
+ import { workspaceRoot } from "./lib/workspace.js";
6
7
  const __dirname = dirname(fileURLToPath(import.meta.url));
7
- const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
8
+ const WORKSPACE = workspaceRoot();
8
9
  // Primary: Gemini 2.5 Flash (large context, free tier, handles 50k+ tokens)
9
10
  const GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent";
10
11
  // Secondary: Groq (fast, but 12k TPM limit — fails on large digests)
package/dist/embed.js CHANGED
@@ -47,6 +47,13 @@ const EMBEDDING_MODEL = "gemini-embedding-001";
47
47
  const EMBEDDING_DIM = 3072; // gemini-embedding-001 actual output dimension
48
48
  const BATCH_SIZE = 20; // Gemini free tier: up to 100 req/min
49
49
  const API_BASE = "https://generativelanguage.googleapis.com/v1beta";
50
+ /**
51
+ * Payload guard for an embedding request, in CHARACTERS (2026-10-15). gemini-embedding-001 reads up to
52
+ * 2,048 TOKENS and truncates longer input itself; the client used to cut at 2,048 characters, which kept
53
+ * 44% of the corpus text out of every vector. Measured on production chunks: 1.6 to 3.9 chars/token, so
54
+ * 10,000 chars always carries at least the 2,048 tokens the model reads.
55
+ */
56
+ export const EMBED_MAX_CHARS = 10_000;
50
57
  // ─── Gemini Embedding API ────────────────────────────────────────────────────
51
58
  // Forensic-logged fetch with exponential backoff on 429/5xx.
52
59
  // 4 attempts: 1s, 2s, 4s backoff. Logs status, retry-related headers,
@@ -88,7 +95,7 @@ async function geminiEmbed(text) {
88
95
  headers: { "Content-Type": "application/json" },
89
96
  body: JSON.stringify({
90
97
  model: `models/${EMBEDDING_MODEL}`,
91
- content: { parts: [{ text: text.substring(0, 2048) }] },
98
+ content: { parts: [{ text: text.substring(0, EMBED_MAX_CHARS) }] },
92
99
  taskType: "RETRIEVAL_DOCUMENT",
93
100
  }),
94
101
  }, "embedDoc");
@@ -109,7 +116,7 @@ async function geminiEmbedQuery(text, signal) {
109
116
  headers: { "Content-Type": "application/json" },
110
117
  body: JSON.stringify({
111
118
  model: `models/${EMBEDDING_MODEL}`,
112
- content: { parts: [{ text: text.substring(0, 2048) }] },
119
+ content: { parts: [{ text: text.substring(0, EMBED_MAX_CHARS) }] },
113
120
  taskType: "RETRIEVAL_QUERY",
114
121
  }),
115
122
  }, "embedQuery");
@@ -271,7 +278,7 @@ export async function embedBatchAPI(texts, options = {}) {
271
278
  const payload = {
272
279
  requests: slice.map((t) => ({
273
280
  model: `models/${EMBEDDING_MODEL}`,
274
- content: { parts: [{ text: t.substring(0, 2048) }] },
281
+ content: { parts: [{ text: t.substring(0, EMBED_MAX_CHARS) }] },
275
282
  taskType: "RETRIEVAL_DOCUMENT",
276
283
  })),
277
284
  };
package/dist/index.js CHANGED
@@ -41,7 +41,7 @@ program
41
41
  return;
42
42
  }
43
43
  if (opts.hybrid) {
44
- const results = await searchHybrid(query, parseInt(opts.limit, 10), true, filter);
44
+ const results = await searchHybrid(query, parseInt(opts.limit, 10), true, filter, { surface: "cli", agent: process.env.NOX_AGENT_NAME });
45
45
  console.log(formatResults(results));
46
46
  }
47
47
  else {
@@ -115,9 +115,119 @@ program
115
115
  console.log(`[INFO] Ingested ${file}: ${result.chunks} chunks (kind=${result.kind}, via=${result.routedTo})`);
116
116
  closeDb();
117
117
  });
118
+ // ─── Tombstones (write path without loss, 2026-10-14) ──────────────────────
119
+ // A file that leaves the disk keeps its chunks; these commands mark, review and
120
+ // — only on explicit request, under withOpAudit — purge them.
121
+ // The argument is a key as `tombstones` lists it, or a path from the cwd
122
+ // (`resolveSourceArg`). It used to keep a relative argument as typed and refuse
123
+ // anything outside the workspace, which on a standalone install (keys start
124
+ // with `../`) missed or refused every path.
125
+ async function tombstonePath(arg) {
126
+ const { existsSync } = await import("fs");
127
+ const { resolve } = await import("path");
128
+ const { resolveSourceArg } = await import("./lib/tombstone.js");
129
+ const ws = (await import("./lib/workspace.js")).workspaceRoot();
130
+ const rel = resolveSourceArg(getDb(), arg);
131
+ return { rel, onDisk: existsSync(resolve(ws, rel)) };
132
+ }
133
+ program
134
+ .command("tombstone <files...>")
135
+ .description("Mark files that left the disk; their chunks stay (used by the watcher on delete/move)")
136
+ .option("--dir", "The paths are directories that left the disk: tombstone every stored file under them")
137
+ .action(async (files, opts) => {
138
+ const { tombstoneFile, tombstonePrefix } = await import("./lib/tombstone.js");
139
+ const { existsSync } = await import("fs");
140
+ const { resolve } = await import("path");
141
+ const ws = (await import("./lib/workspace.js")).workspaceRoot();
142
+ for (const f of files) {
143
+ try {
144
+ const { rel, onDisk } = await tombstonePath(f);
145
+ if (opts.dir) {
146
+ const r = tombstonePrefix(getDb(), rel, (p) => existsSync(resolve(ws, p)), "deleted");
147
+ console.log(`[TOMBSTONE] ${rel}/: ${r.files} files tombstoned (${r.chunks} chunks kept)`);
148
+ continue;
149
+ }
150
+ const r = tombstoneFile(getDb(), rel, onDisk, "deleted");
151
+ console.log(`[TOMBSTONE] ${rel}: ${r.status}${r.chunks ? ` (${r.chunks} chunks kept)` : ""}`);
152
+ }
153
+ catch (err) {
154
+ console.error(`[TOMBSTONE] ${f}: ${err.message}`);
155
+ process.exitCode = 1;
156
+ }
157
+ }
158
+ closeDb();
159
+ });
160
+ program
161
+ .command("tombstones")
162
+ .description("List files gone from disk whose chunks are still stored (review queue)")
163
+ .option("--all", "Include resolved (renamed / emptied) and kept tombstones")
164
+ .option("--json", "JSON output")
165
+ .action(async (opts) => {
166
+ const { listTombstones } = await import("./lib/tombstone.js");
167
+ const rows = listTombstones(getDb(), { all: opts.all });
168
+ if (opts.json) {
169
+ console.log(JSON.stringify(rows, null, 2));
170
+ }
171
+ else if (rows.length === 0) {
172
+ console.log("[TOMBSTONES] none");
173
+ }
174
+ else {
175
+ for (const r of rows) {
176
+ const extra = [
177
+ r.renamed_to ? `renamed_to=${r.renamed_to}` : "",
178
+ r.kept_at ? `kept ${r.kept_at}` : "",
179
+ r.duplicated_elsewhere ? `${r.duplicated_elsewhere} also stored under another path` : "",
180
+ ].filter(Boolean).join(", ");
181
+ console.log(`${r.tombstoned_at} ${r.reason.padEnd(18)} ${String(r.live_chunks).padStart(5)} chunks ${r.source_file}${extra ? ` (${extra})` : ""}`);
182
+ }
183
+ }
184
+ closeDb();
185
+ });
186
+ program
187
+ .command("tombstone-keep <file>")
188
+ .description("Review outcome: keep this content on purpose (leaves the review queue, never adopted)")
189
+ .action(async (file) => {
190
+ const { keepTombstone } = await import("./lib/tombstone.js");
191
+ const { rel } = await tombstonePath(file);
192
+ console.log(keepTombstone(getDb(), rel) ? `[TOMBSTONE] ${rel}: kept` : `[TOMBSTONE] ${rel}: no open tombstone`);
193
+ closeDb();
194
+ });
195
+ program
196
+ .command("tombstone-purge <file>")
197
+ .description("Delete the chunks of a tombstoned file (snapshot first via op-audit)")
198
+ .option("--dry-run", "Report how many chunks would be deleted; no write")
199
+ .option("--allow-prod", "Skip the large-DB guard (same as NOX_ALLOW_PROD_INGEST=1)")
200
+ .action(async (file, opts) => {
201
+ const { purgeTombstone } = await import("./lib/tombstone.js");
202
+ const { rel, onDisk } = await tombstonePath(file);
203
+ if (opts.dryRun) {
204
+ const r = purgeTombstone(getDb(), rel, onDisk, { dryRun: true });
205
+ console.log(JSON.stringify({ op: "tombstone-purge", dry_run: true, source_file: rel, ...r }));
206
+ closeDb();
207
+ return;
208
+ }
209
+ if (opts.allowProd)
210
+ process.env.NOX_ALLOW_PROD_INGEST = "1";
211
+ checkLargeDbIngestGuard(getDb(), "tombstone-purge");
212
+ const { withOpAudit } = await import("./lib/op-audit.js");
213
+ let refused;
214
+ const result = await withOpAudit("tombstone-purge", async () => {
215
+ const r = purgeTombstone(getDb(), rel, onDisk);
216
+ refused = r.refused;
217
+ return { affected_rows: r.chunks, notes: `source_file=${rel}${r.refused ? ` refused=${r.refused}` : ""}` };
218
+ });
219
+ if (refused) {
220
+ console.error(`[TOMBSTONE] ${rel}: purge refused (${refused})`);
221
+ process.exitCode = 1;
222
+ }
223
+ else {
224
+ console.log(`[TOMBSTONE] ${rel}: purged ${result.affected_rows ?? 0} chunks`);
225
+ }
226
+ closeDb();
227
+ });
118
228
  program
119
229
  .command("reindex")
120
- .description("Rebuild the index from $OPENCLAW_WORKSPACE/memory and /shared (refuses if that source is missing)")
230
+ .description("Rebuild the index from <workspace>/memory and /shared (workspace: $OPENCLAW_WORKSPACE, the OpenClaw layout, or ~/.nox-mem; refuses if that source is missing)")
121
231
  .option("--dry-run", "Print what would be reindexed as JSON; does not touch the DB")
122
232
  .action(async (opts) => {
123
233
  try {
@@ -21,14 +21,16 @@
21
21
  // - **2026-04-20** — [implementation] Heartbeat migrated
22
22
  //
23
23
  // Each file produces N+2 chunks: 1 frontmatter + 1 compiled + N timeline entries.
24
- import { readFileSync } from "fs";
25
- import { relative } from "path";
24
+ import { existsSync, readFileSync } from "fs";
25
+ import { relative, resolve } from "path";
26
26
  import { getDb } from "./db.js";
27
+ import { syncFileChunks } from "./lib/chunk-sync.js";
27
28
  import { getInitialTier } from "./tier-manager.js";
28
29
  import { resolveRetention } from "./retention.js";
29
30
  import { inferPain, inferImportance } from "./salience.js";
30
31
  import { redact as _redactPrivacy } from "./privacy/filter.js";
31
- const WORKSPACE = process.env.OPENCLAW_WORKSPACE || "/root/.openclaw/workspace";
32
+ import { workspaceRoot } from "./lib/workspace.js";
33
+ const WORKSPACE = workspaceRoot();
32
34
  /**
33
35
  * Section boost values by section type. Multiplicative in search ranking but
34
36
  * applied additively when combined with tier/importance boosts to avoid
@@ -113,76 +115,84 @@ function parseSimpleYaml(raw) {
113
115
  return out;
114
116
  }
115
117
  /**
116
- * Ingest a single entity file as 1 frontmatter chunk + 1 compiled chunk
117
- * + N timeline chunks. All chunks share the same source_file relative path.
118
- *
119
- * chunk_type is inferred from directory:
120
- * memory/entities/agents/ → 'person' (never-decay)
121
- * memory/entities/projects/ → 'project' (365d retention)
122
- * memory/entities/systems/ → 'other' (90d — system state evolves)
123
- * memory/entities/people/ → 'person'
118
+ * Synchronous core (no await, so reindex can run it inside one transaction).
119
+ * Diffs the file's N+2 chunks against what is stored (chunk-sync.ts): an entity
120
+ * whose compiled truth changed gets ONE new row; frontmatter and the untouched
121
+ * timeline entries keep their ids. The key includes the section, so the
122
+ * `compiled == frontmatter` invariant (CLAUDE.md rule 6) holds per file.
124
123
  */
125
- export async function ingestEntityFile(filePath, externalDb) {
124
+ export function ingestEntitySync(db, filePath) {
126
125
  const relPath = relative(WORKSPACE, filePath);
127
126
  const content = readFileSync(filePath, "utf-8");
128
127
  const entity = parseEntityFile(content);
129
128
  if (!entity) {
130
- return { parsed: false, chunks: 0 };
129
+ return { parsed: false, chunks: 0, compiledChunkId: null, inserted: [], kept: 0, deleted: 0, adopted: 0 };
131
130
  }
132
- const db = externalDb ?? getDb();
133
131
  const chunkType = inferChunkTypeFromPath(relPath);
134
132
  const tier = getInitialTier(chunkType);
135
133
  const importance = inferImportance(chunkType);
136
134
  // Compiled truth represents user-declared current state → bump importance
137
135
  const compiledImportance = Math.max(importance, 0.9);
138
136
  const retentionDays = resolveRetention(chunkType, content);
139
- // Delete previous chunks from this file (idempotent re-ingest)
140
- db.prepare("DELETE FROM chunks WHERE source_file = ?").run(relPath);
141
- const insert = db.prepare(`
142
- INSERT INTO chunks (source_file, chunk_text, chunk_type, source_date, metadata, tier, importance, retention_days, pain, section, section_boost)
143
- VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?)
144
- `);
145
137
  const today = new Date().toISOString().slice(0, 10);
146
- let count = 0;
147
- db.transaction(() => {
148
- // 1. Frontmatter chunk
149
- let fmText = `---\n${entity.frontmatterRaw}\n---`;
150
- // Privacy filter: redact before INSERT (staged-privacy follow-up Wave Q)
151
- const _rFm = _redactPrivacy(fmText);
152
- fmText = _rFm.text;
153
- if (_rFm.redactionCount > 0) {
154
- console.warn(`[privacy-filter] redacted ${_rFm.redactionCount} secret(s) in entity frontmatter — kinds: ${_rFm.kinds.join(", ")}`);
155
- }
156
- insert.run(relPath, fmText, chunkType, JSON.stringify({ section: "frontmatter", entity: entity.frontmatter.name ?? null }), tier, importance, retentionDays, inferPain(chunkType, fmText), "frontmatter", SECTION_BOOST.frontmatter);
157
- count++;
158
- // 2. Compiled truth chunk — single chunk, the "current state"
159
- if (entity.compiled) {
160
- let compiledText = entity.compiled;
161
- // Privacy filter: redact before INSERT (staged-privacy follow-up Wave Q)
162
- const _rCo = _redactPrivacy(compiledText);
163
- compiledText = _rCo.text;
164
- if (_rCo.redactionCount > 0) {
165
- console.warn(`[privacy-filter] redacted ${_rCo.redactionCount} secret(s) in entity compiled — kinds: ${_rCo.kinds.join(", ")}`);
166
- }
167
- insert.run(relPath, compiledText, chunkType, JSON.stringify({ section: "compiled", entity: entity.frontmatter.name ?? null, recompiled_at: today }), tier, compiledImportance, retentionDays, inferPain(chunkType, compiledText), "compiled", SECTION_BOOST.compiled);
168
- count++;
138
+ const name = entity.frontmatter.name ?? null;
139
+ // Privacy filter: redact before storage (staged-privacy follow-up Wave Q)
140
+ const redacted = (text, where) => {
141
+ const r = _redactPrivacy(text);
142
+ if (r.redactionCount > 0) {
143
+ console.warn(`[privacy-filter] redacted ${r.redactionCount} secret(s) in entity ${where} — kinds: ${r.kinds.join(", ")}`);
169
144
  }
170
- // 3. Timeline entries — one chunk each, reverse-chronological preserved as-is
171
- for (const entry of entity.timeline) {
172
- let entryText = entry;
173
- // Privacy filter: redact before INSERT (staged-privacy follow-up Wave Q)
174
- const _rTl = _redactPrivacy(entryText);
175
- entryText = _rTl.text;
176
- if (_rTl.redactionCount > 0) {
177
- console.warn(`[privacy-filter] redacted ${_rTl.redactionCount} secret(s) in entity timeline — kinds: ${_rTl.kinds.join(", ")}`);
178
- }
179
- insert.run(relPath, entryText, chunkType, JSON.stringify({ section: "timeline", entity: entity.frontmatter.name ?? null }), tier, importance, retentionDays, inferPain(chunkType, entryText), "timeline", SECTION_BOOST.timeline);
180
- count++;
181
- }
182
- })();
183
- if (!externalDb)
184
- db.close();
185
- return { parsed: true, chunks: count };
145
+ return r.text;
146
+ };
147
+ const chunk = (text, section, metadata, imp) => ({
148
+ chunk_text: text,
149
+ section,
150
+ chunk_type: chunkType,
151
+ source_date: null,
152
+ metadata: JSON.stringify(metadata),
153
+ tier,
154
+ importance: imp,
155
+ retention_days: retentionDays,
156
+ pain: inferPain(chunkType, text),
157
+ section_boost: SECTION_BOOST[section] ?? null,
158
+ });
159
+ const desired = [];
160
+ // 1. Frontmatter chunk
161
+ desired.push(chunk(redacted(`---\n${entity.frontmatterRaw}\n---`, "frontmatter"), "frontmatter", { section: "frontmatter", entity: name }, importance));
162
+ // 2. Compiled truth chunk — single chunk, the "current state"
163
+ const compiledAt = entity.compiled ? desired.length : -1;
164
+ if (entity.compiled) {
165
+ desired.push(chunk(redacted(entity.compiled, "compiled"), "compiled", { section: "compiled", entity: name, recompiled_at: today }, compiledImportance));
166
+ }
167
+ // 3. Timeline entries — one chunk each, reverse-chronological preserved as-is
168
+ for (const entry of entity.timeline) {
169
+ desired.push(chunk(redacted(entry, "timeline"), "timeline", { section: "timeline", entity: name }, importance));
170
+ }
171
+ const r = syncFileChunks(db, relPath, desired, { existsOnDisk: (p) => existsSync(resolve(WORKSPACE, p)) });
172
+ return {
173
+ parsed: true,
174
+ chunks: desired.length,
175
+ compiledChunkId: compiledAt >= 0 ? r.ids[compiledAt] : null,
176
+ inserted: r.inserted,
177
+ kept: r.kept,
178
+ deleted: r.deleted,
179
+ adopted: r.adopted,
180
+ };
181
+ }
182
+ /**
183
+ * Ingest a single entity file as 1 frontmatter chunk + 1 compiled chunk
184
+ * + N timeline chunks. All chunks share the same source_file relative path.
185
+ *
186
+ * chunk_type is inferred from directory:
187
+ * memory/entities/agents/ → 'person' (never-decay)
188
+ * memory/entities/projects/ → 'project' (365d retention)
189
+ * memory/entities/systems/ → 'other' (90d — system state evolves)
190
+ * memory/entities/people/ → 'person'
191
+ *
192
+ * Never closes the connection (see ingestFile).
193
+ */
194
+ export async function ingestEntityFile(filePath, externalDb) {
195
+ return ingestEntitySync(externalDb ?? getDb(), filePath);
186
196
  }
187
197
  function inferChunkTypeFromPath(relPath) {
188
198
  if (/entities\/agents\//.test(relPath))