nox-mem 3.2.1 → 3.3.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/dist/__tests__/session-distill-sources.test.js +98 -0
- package/dist/__tests__/telemetry-per-chunk.test.js +110 -0
- package/dist/api-server.js +24 -1
- package/dist/db.js +35 -2
- package/dist/search.js +10 -4
- package/dist/session-distill.js +73 -24
- package/package.json +5 -5
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Guards for the two things a VPS migration moved at once: WHERE agent session
|
|
2
|
+
// transcripts live, and WHAT SHAPE they have. Both failures are silent — the
|
|
3
|
+
// old path simply reports "No unprocessed sessions found" with exit 0, and the
|
|
4
|
+
// old schema check drops every line of a Claude CLI transcript without an
|
|
5
|
+
// error. One deployment ran 28 days that way with its cron marked "ok".
|
|
6
|
+
//
|
|
7
|
+
// Run: npx tsc && node --test dist/__tests__/session-distill-sources.test.js
|
|
8
|
+
import { test } from "node:test";
|
|
9
|
+
import assert from "node:assert/strict";
|
|
10
|
+
import { mkdtempSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
import { resolve } from "node:path";
|
|
13
|
+
import { claudeProjectSlug, claudeProjectsDirs, sessionDirsFor, extractMessages, } from "../session-distill.js";
|
|
14
|
+
function writeTranscript(lines) {
|
|
15
|
+
const dir = mkdtempSync(resolve(tmpdir(), "nox-distill-"));
|
|
16
|
+
const file = resolve(dir, "session.jsonl");
|
|
17
|
+
writeFileSync(file, lines.map((l) => JSON.stringify(l)).join("\n"), "utf-8");
|
|
18
|
+
return file;
|
|
19
|
+
}
|
|
20
|
+
const CLI_LINES = [
|
|
21
|
+
{ type: "queue-operation", op: "enqueue" },
|
|
22
|
+
{ type: "attachment", path: "/tmp/x.png" },
|
|
23
|
+
{ type: "user", message: { role: "user", content: "por que o distill parou de rodar" } },
|
|
24
|
+
{
|
|
25
|
+
type: "assistant",
|
|
26
|
+
message: {
|
|
27
|
+
role: "assistant",
|
|
28
|
+
content: [
|
|
29
|
+
{ type: "text", text: "porque as sessoes mudaram de endereco" },
|
|
30
|
+
{ type: "tool_use", name: "Bash", input: {} },
|
|
31
|
+
],
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
];
|
|
35
|
+
test("Claude CLI transcripts (type user/assistant) are read", () => {
|
|
36
|
+
const msgs = extractMessages(writeTranscript(CLI_LINES));
|
|
37
|
+
assert.equal(msgs.length, 2, "both turns must survive");
|
|
38
|
+
assert.deepEqual(msgs.map((m) => m.role), ["user", "assistant"]);
|
|
39
|
+
// Only the text part is kept; tool_use carries no prose to distill.
|
|
40
|
+
assert.equal(msgs[1].text, "porque as sessoes mudaram de endereco");
|
|
41
|
+
});
|
|
42
|
+
test("legacy OpenClaw transcripts (type message) still are read", () => {
|
|
43
|
+
const msgs = extractMessages(writeTranscript([
|
|
44
|
+
{ type: "message", message: { role: "user", content: "pergunta legada" } },
|
|
45
|
+
{ type: "message", message: { role: "assistant", content: "resposta legada" } },
|
|
46
|
+
]));
|
|
47
|
+
assert.equal(msgs.length, 2);
|
|
48
|
+
});
|
|
49
|
+
test("unknown event types and heartbeat noise stay out", () => {
|
|
50
|
+
const msgs = extractMessages(writeTranscript([
|
|
51
|
+
{ type: "summary", message: { role: "user", content: "nao e um turno de conversa" } },
|
|
52
|
+
{ type: "user", message: { role: "user", content: "HEARTBEAT_OK" } },
|
|
53
|
+
{ type: "user", message: { role: "user", content: "[cron:eod] disparo" } },
|
|
54
|
+
{ type: "user", message: { role: "user", content: "ok" } },
|
|
55
|
+
{ type: "user", content: "sem o campo message" },
|
|
56
|
+
]));
|
|
57
|
+
assert.equal(msgs.length, 0);
|
|
58
|
+
});
|
|
59
|
+
test("slug derivation matches the Claude CLI layout", () => {
|
|
60
|
+
// The CLI replaces both "/" and "." with "-", so the leading slash and the
|
|
61
|
+
// dotted dir collapse into the doubled dash seen on disk.
|
|
62
|
+
assert.equal(claudeProjectSlug("/root/.openclaw/workspace"), "-root--openclaw-workspace");
|
|
63
|
+
assert.equal(claudeProjectSlug("/root/.openclaw/workspace/agents/forge"), "-root--openclaw-workspace-agents-forge");
|
|
64
|
+
});
|
|
65
|
+
test("an explicit NOX_CLAUDE_PROJECTS_DIR wins over discovery", () => {
|
|
66
|
+
const prev = process.env.NOX_CLAUDE_PROJECTS_DIR;
|
|
67
|
+
process.env.NOX_CLAUDE_PROJECTS_DIR = "/somewhere/projects";
|
|
68
|
+
try {
|
|
69
|
+
assert.deepEqual(claudeProjectsDirs(), ["/somewhere/projects"]);
|
|
70
|
+
const dirs = sessionDirsFor("forge");
|
|
71
|
+
// Legacy dir first, then the CLI one — the legacy dir still holds sessions
|
|
72
|
+
// predating the switch, so neither may be dropped.
|
|
73
|
+
assert.equal(dirs.length, 2);
|
|
74
|
+
assert.match(dirs[0], /agents\/forge\/sessions$/);
|
|
75
|
+
assert.equal(dirs[1], "/somewhere/projects/-root--openclaw-workspace-agents-forge");
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
if (prev === undefined)
|
|
79
|
+
delete process.env.NOX_CLAUDE_PROJECTS_DIR;
|
|
80
|
+
else
|
|
81
|
+
process.env.NOX_CLAUDE_PROJECTS_DIR = prev;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
test("the main agent maps to the workspace root, not to agents/main", () => {
|
|
85
|
+
const prev = process.env.NOX_CLAUDE_PROJECTS_DIR;
|
|
86
|
+
process.env.NOX_CLAUDE_PROJECTS_DIR = "/p";
|
|
87
|
+
try {
|
|
88
|
+
const cli = sessionDirsFor("main")[1];
|
|
89
|
+
assert.equal(cli, "/p/-root--openclaw-workspace");
|
|
90
|
+
assert.doesNotMatch(cli, /agents-main/);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
if (prev === undefined)
|
|
94
|
+
delete process.env.NOX_CLAUDE_PROJECTS_DIR;
|
|
95
|
+
else
|
|
96
|
+
process.env.NOX_CLAUDE_PROJECTS_DIR = prev;
|
|
97
|
+
}
|
|
98
|
+
});
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// v19 — telemetria por chunk (`top_chunk_ids` / `top_scores`).
|
|
2
|
+
//
|
|
3
|
+
// Dois grupos de asserção, com propósitos diferentes:
|
|
4
|
+
//
|
|
5
|
+
// (A) schema — a coluna existe tanto num install limpo quanto num DB legado
|
|
6
|
+
// que já estava em v18. Um `ALTER TABLE` só no caminho de migração deixa
|
|
7
|
+
// o install limpo sem a coluna; um `CREATE TABLE` só no caminho novo
|
|
8
|
+
// deixa o DB existente sem ela. Os dois caminhos são testados separados
|
|
9
|
+
// porque falham separado.
|
|
10
|
+
//
|
|
11
|
+
// (B) privacidade — o INSERT de `search.ts` NÃO pode conter `query_text`.
|
|
12
|
+
// Isso não é preferência de estilo: `db.ts` declara, no comentário do v6,
|
|
13
|
+
// que "não armazenamos texto cru da query por privacidade". A coluna
|
|
14
|
+
// `query_text` existe em alguns DBs por reconciliação de drift de schema,
|
|
15
|
+
// e existir não é autorização para escrever. Este teste lê o fonte e
|
|
16
|
+
// morde se alguém a reintroduzir — inclusive eu, que já fiz exatamente
|
|
17
|
+
// isso uma vez.
|
|
18
|
+
//
|
|
19
|
+
// Run: npm run build && node --test dist/__tests__/telemetry-per-chunk.test.js
|
|
20
|
+
import { test, before, after } from "node:test";
|
|
21
|
+
import assert from "node:assert/strict";
|
|
22
|
+
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
|
|
23
|
+
import { join, dirname, resolve } from "node:path";
|
|
24
|
+
import { fileURLToPath } from "node:url";
|
|
25
|
+
import { tmpdir } from "node:os";
|
|
26
|
+
import Database from "better-sqlite3";
|
|
27
|
+
const TMP_ROOT = mkdtempSync(join(process.env.NOX_TEST_TMP_ROOT || tmpdir(), "nox-mem-telemetry-test-"));
|
|
28
|
+
const TEST_DB = join(TMP_ROOT, "fresh.db");
|
|
29
|
+
process.env.NOX_DB_PATH = TEST_DB;
|
|
30
|
+
// dist/__tests__/ → ../../../src/search.ts
|
|
31
|
+
const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "src");
|
|
32
|
+
let getDb;
|
|
33
|
+
let closeDb;
|
|
34
|
+
before(async () => {
|
|
35
|
+
const m = await import("../db.js");
|
|
36
|
+
getDb = m.getDb;
|
|
37
|
+
closeDb = m.closeDb;
|
|
38
|
+
});
|
|
39
|
+
after(() => {
|
|
40
|
+
try {
|
|
41
|
+
closeDb();
|
|
42
|
+
}
|
|
43
|
+
catch { /* ignore */ }
|
|
44
|
+
rmSync(TMP_ROOT, { recursive: true, force: true });
|
|
45
|
+
});
|
|
46
|
+
const colunas = (db, tabela) => db.pragma(`table_info(${tabela})`).map((c) => c.name);
|
|
47
|
+
test("A1 — install limpo cria search_telemetry já com as duas colunas", () => {
|
|
48
|
+
const cols = colunas(getDb(), "search_telemetry");
|
|
49
|
+
assert.ok(cols.includes("top_chunk_ids"), `top_chunk_ids ausente: ${cols.join(", ")}`);
|
|
50
|
+
assert.ok(cols.includes("top_scores"), `top_scores ausente: ${cols.join(", ")}`);
|
|
51
|
+
closeDb();
|
|
52
|
+
});
|
|
53
|
+
test("A2 — DB legado parado em v18 ganha as colunas ao reabrir", async () => {
|
|
54
|
+
const legado = join(TMP_ROOT, "v18.db");
|
|
55
|
+
// Reconstrói o estado v6/v18: a tabela SEM as colunas novas, e o meta dizendo 18.
|
|
56
|
+
const raw = new Database(legado);
|
|
57
|
+
raw.exec(`
|
|
58
|
+
CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT, updated_at TEXT);
|
|
59
|
+
CREATE TABLE search_telemetry (
|
|
60
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
61
|
+
ts TEXT NOT NULL DEFAULT (datetime('now')),
|
|
62
|
+
query_hash TEXT NOT NULL,
|
|
63
|
+
query_words INTEGER NOT NULL,
|
|
64
|
+
variants_count INTEGER NOT NULL DEFAULT 1,
|
|
65
|
+
results_count INTEGER NOT NULL DEFAULT 0,
|
|
66
|
+
has_semantic INTEGER NOT NULL DEFAULT 0,
|
|
67
|
+
latency_ms INTEGER NOT NULL DEFAULT 0,
|
|
68
|
+
expansion_skipped_reason TEXT
|
|
69
|
+
);
|
|
70
|
+
INSERT INTO meta (key, value) VALUES ('schema_version', '18');
|
|
71
|
+
`);
|
|
72
|
+
const antes = raw.pragma("table_info(search_telemetry)").map((c) => c.name);
|
|
73
|
+
assert.ok(!antes.includes("top_chunk_ids"), "pré-condição do teste quebrou: legado já tinha a coluna");
|
|
74
|
+
raw.close();
|
|
75
|
+
process.env.NOX_DB_PATH = legado;
|
|
76
|
+
// Especificador em variável: precisa de uma instância NOVA do módulo (db.js
|
|
77
|
+
// memoiza a conexão em escopo de módulo), e o `?v18` faz o loader tratar como
|
|
78
|
+
// outra entrada de cache. Literal aqui faria o tsc tentar resolver o arquivo.
|
|
79
|
+
const espec = "../db.js?v18";
|
|
80
|
+
const m = (await import(espec));
|
|
81
|
+
const db = m.getDb();
|
|
82
|
+
const depois = colunas(db, "search_telemetry");
|
|
83
|
+
assert.ok(depois.includes("top_chunk_ids") && depois.includes("top_scores"), depois.join(", "));
|
|
84
|
+
// E a migração não perdeu as colunas antigas.
|
|
85
|
+
assert.ok(depois.includes("query_hash") && depois.includes("expansion_skipped_reason"));
|
|
86
|
+
m.closeDb();
|
|
87
|
+
process.env.NOX_DB_PATH = TEST_DB;
|
|
88
|
+
});
|
|
89
|
+
test("B1 — o INSERT de telemetria NÃO grava o texto cru da query", () => {
|
|
90
|
+
const fonte = readFileSync(join(SRC, "search.ts"), "utf8");
|
|
91
|
+
const m = fonte.match(/INSERT INTO search_telemetry \(([^)]*)\)/);
|
|
92
|
+
assert.ok(m, "não achei o INSERT INTO search_telemetry em search.ts");
|
|
93
|
+
const escritas = m[1].split(",").map((s) => s.trim());
|
|
94
|
+
assert.ok(!escritas.includes("query_text"), `regressão de privacidade: ${escritas.join(", ")}`);
|
|
95
|
+
assert.ok(escritas.includes("query_hash"), "o hash é a ÚNICA representação da query que pode ser gravada");
|
|
96
|
+
assert.ok(escritas.includes("top_chunk_ids") && escritas.includes("top_scores"), escritas.join(", "));
|
|
97
|
+
});
|
|
98
|
+
test("B2 — a lista de colunas do INSERT casa com o número de parâmetros", () => {
|
|
99
|
+
// Defeito mecânico clássico: adicionar coluna e esquecer o `?`, ou o argumento
|
|
100
|
+
// do `.run()`. O SQLite aceita a discrepância de argumento em silêncio em
|
|
101
|
+
// alguns casos, e a coluna nova fica NULL para sempre — que é indistinguível
|
|
102
|
+
// de "a feature não foi usada".
|
|
103
|
+
const fonte = readFileSync(join(SRC, "search.ts"), "utf8");
|
|
104
|
+
const bloco = fonte.slice(fonte.indexOf("INSERT INTO search_telemetry"));
|
|
105
|
+
const cols = bloco.match(/INSERT INTO search_telemetry \(([^)]*)\)/)[1].split(",").length;
|
|
106
|
+
const placeholders = bloco.match(/VALUES \(([^)]*)\)/)[1].split(",").length;
|
|
107
|
+
const args = bloco.slice(bloco.indexOf(".run(")).match(/\.run\(([^;]*)\)/)[1].split(",").length;
|
|
108
|
+
assert.equal(placeholders, cols, `${cols} colunas mas ${placeholders} placeholders`);
|
|
109
|
+
assert.equal(args, cols, `${cols} colunas mas ${args} argumentos no .run()`);
|
|
110
|
+
});
|
package/dist/api-server.js
CHANGED
|
@@ -137,12 +137,20 @@ async function handleRequest(req, res) {
|
|
|
137
137
|
// that never cleaned vec_chunk_map), silently claiming embeddings we don't have.
|
|
138
138
|
let embedded = 0;
|
|
139
139
|
let embeddingOrphans = 0;
|
|
140
|
+
let indexOnly = -1;
|
|
140
141
|
try {
|
|
141
142
|
const sqliteVec = await import("sqlite-vec");
|
|
142
143
|
sqliteVec.load(db);
|
|
143
144
|
embedded = db.prepare("SELECT COUNT(DISTINCT m.chunk_id) as c FROM vec_chunk_map m INNER JOIN chunks c ON c.id = m.chunk_id").get().c;
|
|
144
145
|
const totalMap = db.prepare("SELECT COUNT(*) as c FROM vec_chunk_map").get().c;
|
|
145
146
|
embeddingOrphans = Math.max(0, totalMap - embedded);
|
|
147
|
+
try {
|
|
148
|
+
const idx = db.prepare("SELECT COUNT(*) AS c FROM vec_chunks_rowids").get().c;
|
|
149
|
+
indexOnly = Math.max(0, idx - totalMap);
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
indexOnly = -1;
|
|
153
|
+
}
|
|
146
154
|
}
|
|
147
155
|
catch {
|
|
148
156
|
try {
|
|
@@ -259,7 +267,22 @@ async function handleRequest(req, res) {
|
|
|
259
267
|
json(res, {
|
|
260
268
|
chunks: { total, types },
|
|
261
269
|
consolidation: { done: consolidated.c, failed: failed.c, last: lastCon.d },
|
|
262
|
-
|
|
270
|
+
/**
|
|
271
|
+
* ⚠️ `orphans` é `totalMap − embedded`: derivado do MAP, logo cego para um
|
|
272
|
+
* vetor que perdeu a linha de map. `indexOnly` fecha esse ângulo lendo a
|
|
273
|
+
* shadow table `vec_chunks_rowids` direto — ela é tabela normal e não
|
|
274
|
+
* exige o módulo vec0 carregado, ao contrário de `vec_chunks`.
|
|
275
|
+
*
|
|
276
|
+
* Medido num deploy de produção em 2026-08-27: `orphans: 0` com
|
|
277
|
+
* `indexOnly: 2074` — 2.074 vetores válidos no índice, inalcançáveis pela
|
|
278
|
+
* busca e invisíveis a TODA ferramenta existente, porque as três (este
|
|
279
|
+
* campo, o `prune-orphan-vectors` e o alerta que os consome) partem do
|
|
280
|
+
* map. Um guarda cujo predicado exige o dado que falta não cobre a falta
|
|
281
|
+
* desse dado.
|
|
282
|
+
*
|
|
283
|
+
* −1 = shadow table ausente (vec0 nunca criado), que NÃO é zero.
|
|
284
|
+
*/
|
|
285
|
+
vectorCoverage: { embedded, total, orphans: embeddingOrphans, indexOnly },
|
|
263
286
|
knowledgeGraph: { entities: kgEntities, relations: kgRelations },
|
|
264
287
|
retentionDistribution,
|
|
265
288
|
archiveCandidates,
|
package/dist/db.js
CHANGED
|
@@ -21,7 +21,7 @@ export const DB_PATH = (process.env.NOX_DB_PATH
|
|
|
21
21
|
? resolve(_ws, "tools", "nox-mem", "nox-mem.db")
|
|
22
22
|
: resolve(__dirname, "..", "nox-mem.db"));
|
|
23
23
|
export const BACKUP_DIR = _ws ? resolve(_ws, "tools", "nox-mem", "backups") : resolve(__dirname, "..", "backups");
|
|
24
|
-
const SCHEMA_VERSION =
|
|
24
|
+
const SCHEMA_VERSION = 19;
|
|
25
25
|
// ────────────────────────────────────────────────────────────────────────────
|
|
26
26
|
// Large-DB ingest guard (postmortem 2026-05-19)
|
|
27
27
|
// ────────────────────────────────────────────────────────────────────────────
|
|
@@ -178,10 +178,39 @@ function ensureSchema(db) {
|
|
|
178
178
|
migrateToV7(db);
|
|
179
179
|
if (currentVersion < 18)
|
|
180
180
|
migrateToV8(db);
|
|
181
|
+
if (currentVersion < 19)
|
|
182
|
+
migrateToV9(db);
|
|
181
183
|
db.prepare("INSERT OR REPLACE INTO meta (key, value, updated_at) VALUES ('schema_version', ?, datetime('now'))").run(String(SCHEMA_VERSION));
|
|
182
184
|
// Keep PRAGMA user_version in sync so op-audit and tests can rely on it.
|
|
183
185
|
db.pragma(`user_version = ${SCHEMA_VERSION}`);
|
|
184
186
|
}
|
|
187
|
+
function migrateToV9(db) {
|
|
188
|
+
// v19 — per-chunk search telemetry.
|
|
189
|
+
//
|
|
190
|
+
// The v6 telemetry row records the SHAPE of a search (how many results, how
|
|
191
|
+
// fast, whether semantic fired) but not WHICH chunks came back. That is
|
|
192
|
+
// enough to answer "is search healthy?" and not enough to answer "what has
|
|
193
|
+
// this memory ever actually served?" — a question about the retrieval
|
|
194
|
+
// surface, which is what an agent's context is really made of.
|
|
195
|
+
//
|
|
196
|
+
// ⚠️ PRIVACY BOUNDARY, deliberate and load-bearing: this adds the chunk IDs
|
|
197
|
+
// and their scores. It does NOT add the raw query text. `query_hash` stays
|
|
198
|
+
// the only representation of the query (see the v6 comment below), and the
|
|
199
|
+
// test `telemetry-per-chunk.test.ts` reads the INSERT statement out of
|
|
200
|
+
// search.ts and fails if `query_text` ever appears in it. IDs are internal
|
|
201
|
+
// rowids of content the operator already owns; the query string is the one
|
|
202
|
+
// field that can carry a third party's words.
|
|
203
|
+
//
|
|
204
|
+
// Per-column try/catch keeps this idempotent on DBs patched out of band.
|
|
205
|
+
try {
|
|
206
|
+
db.exec(`ALTER TABLE search_telemetry ADD COLUMN top_chunk_ids TEXT`);
|
|
207
|
+
}
|
|
208
|
+
catch { }
|
|
209
|
+
try {
|
|
210
|
+
db.exec(`ALTER TABLE search_telemetry ADD COLUMN top_scores TEXT`);
|
|
211
|
+
}
|
|
212
|
+
catch { }
|
|
213
|
+
}
|
|
185
214
|
function migrateToV8(db) {
|
|
186
215
|
// Standalone consolidation of the column additions that the canonical engine
|
|
187
216
|
// introduced across schema v8–v18 (typed retention, pain-weighting, entity
|
|
@@ -318,7 +347,11 @@ function migrateToV6(db) {
|
|
|
318
347
|
results_count INTEGER NOT NULL DEFAULT 0,
|
|
319
348
|
has_semantic INTEGER NOT NULL DEFAULT 0,
|
|
320
349
|
latency_ms INTEGER NOT NULL DEFAULT 0,
|
|
321
|
-
expansion_skipped_reason TEXT
|
|
350
|
+
expansion_skipped_reason TEXT,
|
|
351
|
+
-- v19 (ver migrateToV9): quais chunks a busca devolveu, e com que score.
|
|
352
|
+
-- JSON array, ou NULL quando nenhum resultado trouxe id.
|
|
353
|
+
top_chunk_ids TEXT,
|
|
354
|
+
top_scores TEXT
|
|
322
355
|
);
|
|
323
356
|
CREATE INDEX IF NOT EXISTS idx_search_telemetry_ts ON search_telemetry(ts DESC);
|
|
324
357
|
`);
|
package/dist/search.js
CHANGED
|
@@ -461,13 +461,19 @@ export async function searchSemantic(query, limit = 5, trackAccess = true) {
|
|
|
461
461
|
function rrfScore(rank, k = 60) {
|
|
462
462
|
return 1 / (k + rank + 1);
|
|
463
463
|
}
|
|
464
|
-
function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs, skipReason) {
|
|
464
|
+
function logTelemetry(query, variantsCount, resultsCount, hasSemantic, latencyMs, skipReason, top) {
|
|
465
465
|
try {
|
|
466
466
|
const db = getDb();
|
|
467
467
|
const hash = createHash("sha1").update(query).digest("hex").substring(0, 16);
|
|
468
468
|
const words = query.trim().split(/\s+/).filter(Boolean).length;
|
|
469
|
-
|
|
470
|
-
|
|
469
|
+
// `id` é opcional em SearchResult: filtrar ANTES de serializar, senão as duas
|
|
470
|
+
// colunas ficam desalinhadas (um `undefined` vira `null` em `ids` mas o score
|
|
471
|
+
// correspondente permanece em `scores`, e o par deixa de ser um par).
|
|
472
|
+
const comId = (top ?? []).filter((r) => typeof r.id === "number");
|
|
473
|
+
const ids = comId.length ? JSON.stringify(comId.map((r) => r.id)) : null;
|
|
474
|
+
const scores = comId.length ? JSON.stringify(comId.map((r) => r.score)) : null;
|
|
475
|
+
db.prepare(`INSERT INTO search_telemetry (query_hash, query_words, variants_count, results_count, has_semantic, latency_ms, expansion_skipped_reason, top_chunk_ids, top_scores)
|
|
476
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(hash, words, variantsCount, resultsCount, hasSemantic ? 1 : 0, latencyMs, skipReason || null, ids, scores);
|
|
471
477
|
}
|
|
472
478
|
catch {
|
|
473
479
|
// telemetria nunca derruba a search
|
|
@@ -528,7 +534,7 @@ export async function searchHybrid(query, limit = 5, trackAccess = true) {
|
|
|
528
534
|
.map(({ rrfScore: s, saw_semantic: _, ...r }) => ({ ...r, score: Math.round(s * 1000 * 100) / 100 }));
|
|
529
535
|
const final = dedupe(preDedup, limit);
|
|
530
536
|
const hasSemantic = final.some((r) => r.match_type === "semantic" || r.match_type === "hybrid");
|
|
531
|
-
logTelemetry(query, variants.length, final.length, hasSemantic, Date.now() - t0, expansion.reason);
|
|
537
|
+
logTelemetry(query, variants.length, final.length, hasSemantic, Date.now() - t0, expansion.reason, final);
|
|
532
538
|
// D49 Phase 1 — temporal proximity rerank, shadow-mode opt-in.
|
|
533
539
|
// Only activates if NOX_TEMPORAL_PATH=shadow|active. In shadow mode the
|
|
534
540
|
// module computes the would-be rerank report but does NOT mutate `final`;
|
package/dist/session-distill.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { readdirSync, readFileSync, existsSync, statSync } from "fs";
|
|
14
14
|
import { resolve } from "path";
|
|
15
|
+
import { homedir } from "os";
|
|
15
16
|
import { getDb } from "./db.js";
|
|
16
17
|
import { isNoise } from "./noise-filter.js";
|
|
17
18
|
import { isDuplicate } from "./dedup.js";
|
|
@@ -27,7 +28,46 @@ const AGENTS_DIR = process.env.NOX_AGENTS_DIR ?? resolve(WORKSPACE, "agents");
|
|
|
27
28
|
// Standalone operators: set to "" or omit (no agent sessions to distill).
|
|
28
29
|
const DEFAULT_AGENTS = process.env.NOX_AGENTS
|
|
29
30
|
? process.env.NOX_AGENTS.split(",").map(s => s.trim()).filter(Boolean)
|
|
30
|
-
: ["nox", "forge", "atlas", "cipher", "boris", "lex"];
|
|
31
|
+
: ["main", "nox", "forge", "atlas", "cipher", "boris", "lex"];
|
|
32
|
+
// NOX_CLAUDE_PROJECTS_DIR: where the Claude CLI keeps session transcripts.
|
|
33
|
+
// Agents that run under the Claude CLI no longer write to <agents>/<id>/sessions/;
|
|
34
|
+
// the CLI stores each session under <projectsDir>/<slug>, where <slug> is the
|
|
35
|
+
// session cwd with "/" and "." replaced by "-" (/root/.openclaw/workspace ->
|
|
36
|
+
// -root--openclaw-workspace). Both locations are read: the legacy dir still
|
|
37
|
+
// holds sessions predating the switch.
|
|
38
|
+
//
|
|
39
|
+
// When unset, the CLI home is DISCOVERED rather than assumed: ~/.claude is the
|
|
40
|
+
// default, but a team account uses ~/.claude-<team>, and a host can have several
|
|
41
|
+
// at once (one deployment had three, and reading only one silently skipped the
|
|
42
|
+
// busiest). Discovery also avoids requiring an env var that a long-lived daemon
|
|
43
|
+
// would only pick up after a restart.
|
|
44
|
+
export function claudeProjectSlug(cwd) {
|
|
45
|
+
return cwd.replace(/[/.]/g, "-");
|
|
46
|
+
}
|
|
47
|
+
export function claudeProjectsDirs() {
|
|
48
|
+
const explicit = process.env.NOX_CLAUDE_PROJECTS_DIR;
|
|
49
|
+
if (explicit)
|
|
50
|
+
return [explicit];
|
|
51
|
+
const home = homedir();
|
|
52
|
+
try {
|
|
53
|
+
return readdirSync(home)
|
|
54
|
+
.filter((d) => d === ".claude" || d.startsWith(".claude-"))
|
|
55
|
+
.map((d) => resolve(home, d, "projects"))
|
|
56
|
+
.filter((d) => existsSync(d));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export function sessionDirsFor(agentId) {
|
|
63
|
+
// "main" runs in the workspace root; every other agent in agents/<id>.
|
|
64
|
+
const cwd = agentId === "main" ? WORKSPACE : resolve(AGENTS_DIR, agentId);
|
|
65
|
+
const slug = claudeProjectSlug(cwd);
|
|
66
|
+
return [
|
|
67
|
+
resolve(AGENTS_DIR, agentId, "sessions"),
|
|
68
|
+
...claudeProjectsDirs().map((d) => resolve(d, slug)),
|
|
69
|
+
];
|
|
70
|
+
}
|
|
31
71
|
// ─── Schema ──────────────────────────────────────────────────────────────────
|
|
32
72
|
export function ensureDistillTable(db) {
|
|
33
73
|
db.exec(`
|
|
@@ -46,39 +86,40 @@ function listUnprocessedSessions(db, agentIds, lookbackDays) {
|
|
|
46
86
|
const cutoff = new Date(Date.now() - lookbackDays * 24 * 60 * 60 * 1000).toISOString();
|
|
47
87
|
const sessions = [];
|
|
48
88
|
for (const agentId of agentIds) {
|
|
49
|
-
const sessionsDir
|
|
50
|
-
|
|
51
|
-
continue;
|
|
52
|
-
let files;
|
|
53
|
-
try {
|
|
54
|
-
files = readdirSync(sessionsDir).filter((f) => f.endsWith(".jsonl"));
|
|
55
|
-
}
|
|
56
|
-
catch {
|
|
57
|
-
continue;
|
|
58
|
-
}
|
|
59
|
-
for (const file of files) {
|
|
60
|
-
const sessionKey = `${agentId}:${file.replace(".jsonl", "")}`;
|
|
61
|
-
// Skip already processed
|
|
62
|
-
const already = db.prepare("SELECT id FROM session_distill_log WHERE session_key = ?").get(sessionKey);
|
|
63
|
-
if (already)
|
|
89
|
+
for (const sessionsDir of sessionDirsFor(agentId)) {
|
|
90
|
+
if (!existsSync(sessionsDir))
|
|
64
91
|
continue;
|
|
65
|
-
|
|
66
|
-
const filePath = resolve(sessionsDir, file);
|
|
92
|
+
let files;
|
|
67
93
|
try {
|
|
68
|
-
|
|
69
|
-
if (new Date(mtimeMs).toISOString() < cutoff)
|
|
70
|
-
continue;
|
|
94
|
+
files = readdirSync(sessionsDir).filter((f) => f.endsWith(".jsonl"));
|
|
71
95
|
}
|
|
72
96
|
catch {
|
|
73
97
|
continue;
|
|
74
98
|
}
|
|
75
|
-
|
|
99
|
+
for (const file of files) {
|
|
100
|
+
const sessionKey = `${agentId}:${file.replace(".jsonl", "")}`;
|
|
101
|
+
// Skip already processed
|
|
102
|
+
const already = db.prepare("SELECT id FROM session_distill_log WHERE session_key = ?").get(sessionKey);
|
|
103
|
+
if (already)
|
|
104
|
+
continue;
|
|
105
|
+
// Check file modification time against lookback
|
|
106
|
+
const filePath = resolve(sessionsDir, file);
|
|
107
|
+
try {
|
|
108
|
+
const { mtimeMs } = statSync(filePath);
|
|
109
|
+
if (new Date(mtimeMs).toISOString() < cutoff)
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
sessions.push({ agentId, sessionFile: filePath, sessionKey });
|
|
116
|
+
}
|
|
76
117
|
}
|
|
77
118
|
}
|
|
78
119
|
return sessions;
|
|
79
120
|
}
|
|
80
121
|
// ─── Message extraction ───────────────────────────────────────────────────────
|
|
81
|
-
function extractMessages(sessionFile) {
|
|
122
|
+
export function extractMessages(sessionFile) {
|
|
82
123
|
const messages = [];
|
|
83
124
|
let content;
|
|
84
125
|
try {
|
|
@@ -97,7 +138,15 @@ function extractMessages(sessionFile) {
|
|
|
97
138
|
catch {
|
|
98
139
|
continue;
|
|
99
140
|
}
|
|
100
|
-
|
|
141
|
+
// Two transcript schemas in the wild: the OpenClaw one tags events as
|
|
142
|
+
// type "message", while Claude CLI transcripts tag them "user"/"assistant".
|
|
143
|
+
// Accepting only the former dropped every line of the latter with no error
|
|
144
|
+
// and no log — measured 0 lines of type "message" in a current transcript.
|
|
145
|
+
if (!event.message)
|
|
146
|
+
continue;
|
|
147
|
+
if (event.type !== "message" &&
|
|
148
|
+
event.type !== "user" &&
|
|
149
|
+
event.type !== "assistant")
|
|
101
150
|
continue;
|
|
102
151
|
const { role, content: contentParts } = event.message;
|
|
103
152
|
if (role !== "user" && role !== "assistant")
|
package/package.json
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nox-mem",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"description": "Pain-weighted hybrid memory engine: FTS5 + semantic search + knowledge graph, self-hosted on any Linux VPS.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Luiz Antonio Busnello (Toto)",
|
|
8
|
-
"homepage": "https://github.com/totobusnello/nox-
|
|
8
|
+
"homepage": "https://github.com/totobusnello/nox-mem#readme",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|
|
11
|
-
"url": "git+https://github.com/totobusnello/nox-
|
|
11
|
+
"url": "git+https://github.com/totobusnello/nox-mem.git",
|
|
12
12
|
"directory": "nox-mem"
|
|
13
13
|
},
|
|
14
14
|
"bugs": {
|
|
15
|
-
"url": "https://github.com/totobusnello/nox-
|
|
15
|
+
"url": "https://github.com/totobusnello/nox-mem/issues"
|
|
16
16
|
},
|
|
17
17
|
"keywords": [
|
|
18
18
|
"agent-memory",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"test:op-audit": "node --test dist/__tests__/op-audit-e2e.test.js"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"better-sqlite3": "^11.
|
|
56
|
+
"better-sqlite3": "^12.11.1",
|
|
57
57
|
"commander": "^12.0.0",
|
|
58
58
|
"sqlite-vec": "^0.1.10-alpha.1"
|
|
59
59
|
},
|