nox-mem 3.6.0 → 3.8.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
@@ -249,7 +249,7 @@ nox-mem stats — chunk/entity/vector counts
249
249
  nox-mem kg-build — extract knowledge graph entities
250
250
  nox-mem reflect "question" — synthesis over memory + KG, with cited sources
251
251
  nox-mem-api — start HTTP API on $NOX_API_PORT (default 18802)
252
- nox-mem-mcp — start MCP server over stdio (21 tools, incl. nox_mem_answer, for agents)
252
+ nox-mem-mcp — start MCP server over stdio (22 tools, incl. nox_mem_answer and nox_mem_get, for agents)
253
253
  nox-mem doctor — health check (core + optional integrations)
254
254
  nox-mem --help — full command reference
255
255
  ```
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,
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/ingest.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from "fs";
2
2
  import { relative, resolve } from "path";
3
3
  import { getDb } from "./db.js";
4
4
  import { syncFileChunks } from "./lib/chunk-sync.js";
5
+ import { ensureTombstoneTable, resolveTombstoneOnIngest } from "./lib/tombstone.js";
5
6
  import { getInitialTier, getInitialImportance } from "./tier-manager.js";
6
7
  import { resolveRetention } from "./retention.js";
7
8
  import { inferPain, inferImportance } from "./salience.js";
@@ -42,6 +43,52 @@ export function extractDate(relPath) {
42
43
  const match = relPath.match(/(\d{4}-\d{2}-\d{2})/);
43
44
  return match ? match[1] : null;
44
45
  }
46
+ /**
47
+ * Hard ceiling on a chunk, in characters (2026-10-15). The word-count split below never fires on text
48
+ * with few spaces or no blank lines (CSV rows, OCR output), which left chunks of up to 1 MB; the embedding
49
+ * model reads ~2,048 tokens. Production text measured 1.6-3.9 chars/token, so 4,000 chars stays near
50
+ * 2,048 tokens even for CSV, and sits above the ~3-3.5 KB of a 500-word prose chunk.
51
+ */
52
+ export const MAX_CHUNK_CHARS = 4000;
53
+ /**
54
+ * Splits a text over `max` characters: lines are packed up to the cap; a line longer than the cap is cut
55
+ * at the last space inside its window, or hard-cut when the window has none. Only whitespace at the cuts
56
+ * is dropped.
57
+ */
58
+ export function capChunk(text, max = MAX_CHUNK_CHARS) {
59
+ if (text.length <= max)
60
+ return [text];
61
+ const out = [];
62
+ let buf = "";
63
+ const flush = () => {
64
+ if (buf.trim())
65
+ out.push(buf.trim());
66
+ buf = "";
67
+ };
68
+ for (const line of text.split("\n")) {
69
+ let rest = line;
70
+ // A line that fits on its own is never split: it starts a new chunk when the current one is full.
71
+ if (buf && buf.length + 1 + rest.length > max && rest.length <= max)
72
+ flush();
73
+ // A line over the cap fills the current chunk first (so a heading stays with its text), then the next.
74
+ while ((buf ? buf.length + 1 : 0) + rest.length > max) {
75
+ const room = max - (buf ? buf.length + 1 : 0);
76
+ if (room < max / 4) {
77
+ flush();
78
+ continue;
79
+ }
80
+ let cut = rest.lastIndexOf(" ", room);
81
+ if (cut < room / 2)
82
+ cut = room;
83
+ buf = buf ? `${buf}\n${rest.slice(0, cut)}` : rest.slice(0, cut);
84
+ flush();
85
+ rest = rest.slice(cut);
86
+ }
87
+ buf = buf ? `${buf}\n${rest}` : rest;
88
+ }
89
+ flush();
90
+ return out;
91
+ }
45
92
  export function chunkMarkdown(content) {
46
93
  const lines = content.split("\n");
47
94
  const chunks = [];
@@ -85,13 +132,13 @@ export function chunkMarkdown(content) {
85
132
  result.push(chunk);
86
133
  }
87
134
  }
88
- return result.filter((c) => c.trim().length > 0);
135
+ return result.filter((c) => c.trim().length > 0).flatMap((c) => capChunk(c));
89
136
  }
90
137
  export function chunkJson(content) {
91
138
  try {
92
139
  const data = JSON.parse(content);
93
140
  if (Array.isArray(data))
94
- return data.map((item) => JSON.stringify(item, null, 2));
141
+ return data.map((item) => JSON.stringify(item, null, 2)).flatMap((c) => capChunk(c));
95
142
  const chunks = [];
96
143
  for (const [key, value] of Object.entries(data)) {
97
144
  if (Array.isArray(value)) {
@@ -102,10 +149,10 @@ export function chunkJson(content) {
102
149
  chunks.push(`${key}: ${JSON.stringify(value)}`);
103
150
  }
104
151
  }
105
- return chunks.length > 0 ? chunks : [content];
152
+ return (chunks.length > 0 ? chunks : [content]).flatMap((c) => capChunk(c));
106
153
  }
107
154
  catch {
108
- return [content];
155
+ return capChunk(content);
109
156
  }
110
157
  }
111
158
  /**
@@ -129,14 +176,18 @@ const EMPTY = { chunks: 0, inserted: [], kept: 0, deleted: 0, adopted: 0 };
129
176
  /**
130
177
  * Synchronous core: read, redact, chunk, and diff into the DB (chunk-sync.ts).
131
178
  * No await inside, so a caller can run many files in one transaction (reindex).
132
- * An empty file changes nothing — it is not read as "delete every chunk".
179
+ * An empty file changes no chunk — it is not read as "delete every chunk". It is, however, a file on
180
+ * disk again, so a tombstone left when it was deleted is resolved (2026-10-15).
133
181
  */
134
182
  export function ingestMarkdownSync(db, filePath) {
135
183
  const relPath = relative(WORKSPACE, filePath);
136
184
  // A2 (2026-04-25): entity routing lives in lib/ingest-router.ts — single dispatch.
137
185
  let content = readFileSync(filePath, "utf-8");
138
- if (!content.trim())
186
+ if (!content.trim()) {
187
+ ensureTombstoneTable(db);
188
+ resolveTombstoneOnIngest(db, relPath, []);
139
189
  return EMPTY;
190
+ }
140
191
  // Sanitize UTF-8
141
192
  content = sanitizeUtf8(content);
142
193
  // Privacy filter: redact secrets/PII before storage (staged-privacy)
@@ -0,0 +1,13 @@
1
+ /**
2
+ * On a stdio MCP server, stdout carries JSON-RPC and nothing else. Library code logs with
3
+ * console.log (the schema migrations print "[MIGRATE V5] ..." the first time a DB is opened), and
4
+ * one such line on stdout is a frame the client cannot parse. Measured 2026-11-07 on the 3.8.0
5
+ * tarball: a fresh install's first MCP session wrote that line before the first response.
6
+ *
7
+ * Imported FIRST by mcp-server.ts: ES modules evaluate their imports in order, so this runs before
8
+ * any module that could log. The protocol itself writes with process.stdout.write, untouched.
9
+ */
10
+ console.log = console.error;
11
+ console.info = console.error;
12
+ console.debug = console.error;
13
+ export {};
@@ -110,19 +110,31 @@ export function resolveTombstoneOnIngest(db, relPath, adoptedFrom) {
110
110
  mark.run(relPath, from);
111
111
  }
112
112
  /** Default: tombstones that still hold chunks and were not reviewed as kept. */
113
+ /**
114
+ * One pass, no correlated subquery (2026-10-15). The previous form ran a correlated EXISTS on chunk_text
115
+ * per tombstoned chunk; SQLite answered it with an automatic index over every chunk, and it took 8.5 min
116
+ * on 52.9k chunks with 20 tombstones. A tombstoned chunk is "duplicated elsewhere" when its text is
117
+ * stored under more than one path (its own is one of them), the same predicate as before.
118
+ */
119
+ export const LIST_TOMBSTONES_SQL = `WITH tc AS (
120
+ SELECT c.source_file, c.chunk_text FROM chunks c JOIN chunk_tombstones t ON t.source_file = c.source_file
121
+ ),
122
+ shared AS (
123
+ SELECT o.chunk_text FROM chunks o
124
+ WHERE o.chunk_text IN (SELECT chunk_text FROM tc)
125
+ GROUP BY o.chunk_text HAVING COUNT(DISTINCT o.source_file) > 1
126
+ ),
127
+ agg AS (
128
+ SELECT source_file, COUNT(*) AS live_chunks,
129
+ SUM(chunk_text IN (SELECT chunk_text FROM shared)) AS duplicated_elsewhere
130
+ FROM tc GROUP BY source_file
131
+ )
132
+ SELECT t.*, COALESCE(a.live_chunks, 0) AS live_chunks, COALESCE(a.duplicated_elsewhere, 0) AS duplicated_elsewhere
133
+ FROM chunk_tombstones t LEFT JOIN agg a ON a.source_file = t.source_file
134
+ ORDER BY t.tombstoned_at, t.source_file`;
113
135
  export function listTombstones(db, opts = {}) {
114
136
  ensureTombstoneTable(db);
115
- const rows = db
116
- .prepare(`SELECT t.*,
117
- (SELECT COUNT(*) FROM chunks c WHERE c.source_file = t.source_file) AS live_chunks,
118
- (SELECT COUNT(*) FROM chunks c
119
- WHERE c.source_file = t.source_file
120
- AND EXISTS (SELECT 1 FROM chunks o
121
- WHERE o.chunk_text = c.chunk_text AND o.source_file != c.source_file)
122
- ) AS duplicated_elsewhere
123
- FROM chunk_tombstones t
124
- ORDER BY t.tombstoned_at, t.source_file`)
125
- .all();
137
+ const rows = db.prepare(LIST_TOMBSTONES_SQL).all();
126
138
  return opts.all ? rows : rows.filter((r) => r.live_chunks > 0 && r.kept_at === null);
127
139
  }
128
140
  /** Review outcome "keep": content stays, tombstone leaves the default listing. */
@@ -3,8 +3,9 @@
3
3
  * nox-mem MCP Server — exposes memory tools via Model Context Protocol (stdio)
4
4
  * Tools: search, stats, primer, ingest, answer, ... (see TOOLS below)
5
5
  */
6
- import { closeDb } from "./db.js";
7
- import { searchHybrid, formatResults } from "./search.js";
6
+ import "./lib/stdout-guard.js"; // must stay the first import: stdout is JSON-RPC only
7
+ import { getDb, closeDb } from "./db.js";
8
+ import { searchHybrid, formatResultsForAgent } from "./search.js";
8
9
  import { crossSearch, formatCrossResults, getCrossStats } from "./cross-search.js";
9
10
  import { getMetrics } from "./metrics.js";
10
11
  import { buildGraph, getGraphStats, formatEntityQuery, upsertDecision, getCurrentDecision, getDecisionHistory, listDecisions } from "./knowledge-graph.js";
@@ -35,6 +36,17 @@ const TOOLS = [
35
36
  required: ["query"],
36
37
  },
37
38
  },
39
+ {
40
+ name: "nox_mem_get",
41
+ description: "Return the full text of memory chunks by id (the 'chunk N' shown in nox_mem_search results). Use when a search hit was cut or you need the exact text.",
42
+ inputSchema: {
43
+ type: "object",
44
+ properties: {
45
+ id: { type: "number", description: "One chunk id" },
46
+ ids: { type: "array", items: { type: "number" }, description: "Several chunk ids (max 10)" },
47
+ },
48
+ },
49
+ },
38
50
  {
39
51
  name: "nox_mem_stats",
40
52
  description: "Get nox-mem database statistics: chunk counts by type, consolidation status, DB size",
@@ -209,6 +221,24 @@ const TOOLS = [
209
221
  inputSchema: noxMemAnswerTool.inputSchema,
210
222
  },
211
223
  ];
224
+ const MAX_GET_IDS = 10;
225
+ /** Read-only by design: no access counter, no telemetry, nothing a ranking signal could learn from. */
226
+ function getChunks(ids) {
227
+ const rows = getDb()
228
+ .prepare(`SELECT id, source_file, chunk_type, chunk_text, source_date FROM chunks
229
+ WHERE id IN (${ids.map(() => "?").join(",")})`)
230
+ .all(...ids);
231
+ const byId = new Map(rows.map((r) => [r.id, r]));
232
+ return ids
233
+ .map((id) => {
234
+ const r = byId.get(id);
235
+ if (!r)
236
+ return `chunk ${id}: not found`;
237
+ const date = r.source_date ? ` · ${r.source_date}` : "";
238
+ return `chunk ${r.id} · ${r.source_file} · ${r.chunk_type}${date}\n${r.chunk_text}`;
239
+ })
240
+ .join("\n\n---\n\n");
241
+ }
212
242
  function sendResponse(id, result) {
213
243
  const msg = JSON.stringify({ jsonrpc: "2.0", id, result });
214
244
  process.stdout.write(msg + "\n");
@@ -261,7 +291,16 @@ async function handleRequest(req) {
261
291
  changedSince: args.changed_since,
262
292
  });
263
293
  const results = await searchHybrid(query, limit, true, filter, { surface: "mcp", agent: process.env.NOX_AGENT_NAME });
264
- text = formatResults(results);
294
+ text = formatResultsForAgent(results);
295
+ break;
296
+ }
297
+ case "nox_mem_get": {
298
+ const raw = args.ids ?? (args.id != null ? [args.id] : []);
299
+ const ids = (Array.isArray(raw) ? raw : [raw]).map(Number);
300
+ if (ids.length === 0 || ids.length > MAX_GET_IDS || ids.some((n) => !Number.isInteger(n) || n <= 0)) {
301
+ throw new Error(`nox_mem_get takes "id" or "ids" (1 to ${MAX_GET_IDS} positive integers)`);
302
+ }
303
+ text = getChunks(ids);
265
304
  break;
266
305
  }
267
306
  case "nox_mem_stats":
package/dist/search.js CHANGED
@@ -676,6 +676,40 @@ export function formatResults(results) {
676
676
  })
677
677
  .join("\n\n");
678
678
  }
679
+ /**
680
+ * Formatter for agents (MCP). `formatResults` shows 200 characters per hit, which is a preview
681
+ * for a person at a terminal who can open the file. An agent usually cannot open it (the files
682
+ * live on the memory host, or its permissions forbid it), so it saw the opening of the right
683
+ * chunk and never the fact further down: measured 2026-11-06, 10 of 36 tasks answered when the
684
+ * agent was told to search, and 25 of 40 runs tried to read the file the preview came from.
685
+ *
686
+ * Each hit carries its chunk id and its whole text (chunks are capped at MAX_CHUNK_CHARS at
687
+ * ingest). A total budget keeps a 20-hit search bounded: a hit past the budget keeps at least
688
+ * MIN_PER_HIT characters and says how to get the rest (`nox_mem_get`), so a cut is never silent.
689
+ */
690
+ export const AGENT_OUTPUT_BUDGET_CHARS = 24_000;
691
+ const MIN_PER_HIT = 400;
692
+ export function formatResultsForAgent(results, budget = AGENT_OUTPUT_BUDGET_CHARS) {
693
+ if (results.length === 0)
694
+ return "No results found.";
695
+ let used = 0;
696
+ return results
697
+ .map((r, i) => {
698
+ const tag = r.match_type ? ` [${r.match_type}]` : "";
699
+ const idPart = r.id != null ? ` · chunk ${r.id}` : "";
700
+ const datePart = r.source_date ? ` · ${r.source_date}` : "";
701
+ const head = `#${i + 1} [${r.score}${tag}] ${r.source_file}${idPart}${datePart}`;
702
+ const room = Math.max(MIN_PER_HIT, budget - used);
703
+ let body = r.chunk_text;
704
+ if (body.length > room) {
705
+ const how = r.id != null ? `nox_mem_get with id ${r.id}` : "open the source file";
706
+ body = `${body.slice(0, room)}\n[cut at ${room} of ${r.chunk_text.length} characters: ${how} returns the rest]`;
707
+ }
708
+ used += body.length;
709
+ return `${head}\n${body}`;
710
+ })
711
+ .join("\n\n---\n\n");
712
+ }
679
713
  // ─── Test-only exports (named with _ prefix to signal "do not use externally") ─
680
714
  export const _internals = {
681
715
  recordAccess,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.6.0",
3
+ "version": "3.8.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",