nox-mem 3.6.0 → 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/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)
@@ -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. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.6.0",
3
+ "version": "3.7.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",