nox-mem 3.10.1 → 3.11.1

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
@@ -126,6 +126,7 @@ nox-mem stats
126
126
  | `NOX_KNOWN_PROJECTS` | empty | Project slugs for `project-context-gen`. |
127
127
  | `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`. |
128
128
  | `NOX_AGENTS` / `NOX_AGENTS_DIR` | empty / — | Multi-agent cross-search layout (no-op standalone). |
129
+ | `NOX_DISTILL_OUTCOMES_PATH` | unset | File where `session-distill` appends one JSON line of counts per real run (sessions pending/processed, memories extracted/deduped/ingested, blocks per outcome: `ok`, `empty`, `no_key`, `http_error`, `network_error`, `no_text`, `bad_json`). Unset, it writes nothing; the same counts go to stdout. Set it when a scheduler keeps no stdout. The directory must exist. |
129
130
  | `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`. |
130
131
  | `NOX_SPEAKER_FILTER` | empty | One-time V7 migration speaker classification. |
131
132
  | `NOX_NOTION_TOKEN_PATH` | `/root/.config/notion/api_key` | Path of an optional Notion token file (only `doctor` looks at it). |
@@ -136,7 +137,7 @@ nox-mem stats
136
137
 
137
138
  By default nox-mem uses **Gemini via Google AI Studio** for both LLM synthesis and embeddings (`GEMINI_API_KEY`, model `gemini-2.5-flash-lite`, embeddings `gemini-embedding-001` at 3072 dimensions).
138
139
 
139
- The RAG answer/reflect layer and embeddings are provider-pluggable at runtime — no rebuild required. Note: some internal LLM operations (knowledge-graph extraction, consolidation, digest, query expansion) still call Gemini directly and require `GEMINI_API_KEY` even when another provider is set — full provider routing is on the roadmap.
140
+ The RAG answer/reflect layer and embeddings are provider-pluggable at runtime — no rebuild required. Note: some internal LLM operations (knowledge-graph extraction, consolidation, digest, session distill, query expansion) still call Gemini directly and require `GEMINI_API_KEY` even when another provider is set — full provider routing is on the roadmap.
140
141
 
141
142
  ### LLM synthesis (reflect, answer)
142
143
 
package/dist/compact.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * compact.ts — Compress old chunks (>30 days) into summaries
3
- * Uses Gemini 2.5 Flash (primary), Groq (secondary), first-sentence (fallback)
3
+ * Uses Gemini 2.5 Flash-Lite, with a first-sentence fallback
4
4
  * Reduces DB size while preserving knowledge
5
5
  */
6
6
  import { getDb } from "./db.js";
@@ -34,34 +34,6 @@ async function geminiSummary(chunks, dateRange) {
34
34
  return null;
35
35
  }
36
36
  }
37
- /** Secondary: Groq summary */
38
- async function llmSummary(chunks, dateRange) {
39
- const apiKey = process.env.GROQ_API_KEY;
40
- if (!apiKey)
41
- return null;
42
- const combined = chunks.map((c) => `[${c.source_date}] ${c.chunk_text}`).join("\n\n");
43
- const prompt = `Você é um compressor de memória de agentes de IA. Resuma os seguintes ${chunks.length} registros de memória (período: ${dateRange}) em 2-3 frases densas em PT-BR. Preserve: decisões, lições, nomes de pessoas/projetos, datas importantes. Descarte: detalhes operacionais repetidos, contexto expirado.\n\nRegistros:\n${combined.substring(0, 3000)}\n\nResumo (2-3 frases):`;
44
- try {
45
- const res = await fetch("https://api.groq.com/openai/v1/chat/completions", {
46
- method: "POST",
47
- headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}` },
48
- body: JSON.stringify({
49
- model: "llama-3.3-70b-versatile",
50
- messages: [{ role: "user", content: prompt }],
51
- temperature: 0.1,
52
- max_tokens: 256,
53
- }),
54
- signal: AbortSignal.timeout(20_000),
55
- });
56
- if (!res.ok)
57
- return null;
58
- const data = await res.json();
59
- return data.choices?.[0]?.message?.content?.trim() || null;
60
- }
61
- catch {
62
- return null;
63
- }
64
- }
65
37
  /** Fallback: extract first meaningful sentence from each chunk */
66
38
  function firstSentenceFallback(chunks) {
67
39
  return chunks.map(c => {
@@ -101,9 +73,9 @@ async function _compactImpl(ageDays = DEFAULT_AGE_DAYS, dryRun = false) {
101
73
  // Get all chunks in this group
102
74
  const placeholders = chunkIds.map(() => "?").join(",");
103
75
  const chunks = db.prepare(`SELECT id, chunk_text, source_date FROM chunks WHERE id IN (${placeholders}) ORDER BY source_date ASC`).all(...chunkIds);
104
- // Create summary: Gemini (primary) → Groq (secondary) → first-sentence (fallback)
76
+ // Create summary: Gemini → first-sentence (fallback)
105
77
  const dateRange = `${group.first_date}..${group.last_date}`;
106
- const llmResult = (await geminiSummary(chunks, dateRange)) ?? (await llmSummary(chunks, dateRange));
78
+ const llmResult = await geminiSummary(chunks, dateRange);
107
79
  const summaryBody = llmResult
108
80
  ? llmResult
109
81
  : firstSentenceFallback(chunks);
@@ -75,49 +75,6 @@ async function callGemini(prompt, retries = 2) {
75
75
  }
76
76
  return null;
77
77
  }
78
- // Ollama removed — offline and not planned to return. Groq is first fallback.
79
- async function callGroqFallback(prompt, retries = 2) {
80
- const apiKey = process.env.GROQ_API_KEY;
81
- if (!apiKey) {
82
- console.error("[ERROR] GROQ_API_KEY not set — trying Gemini retry");
83
- return await callGeminiSimple(prompt);
84
- }
85
- const systemMsg = 'Você é um extrator de memória. Responda APENAS com JSON válido no formato: {"decisions":[],"lessons":[],"people":[],"projects":[],"pending":[]}';
86
- for (let attempt = 1; attempt <= retries; attempt++) {
87
- try {
88
- const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
89
- method: "POST",
90
- headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}` },
91
- body: JSON.stringify({
92
- model: "llama-3.3-70b-versatile",
93
- messages: [{ role: "system", content: systemMsg }, { role: "user", content: prompt }],
94
- temperature: 0, max_tokens: 2048, response_format: { type: "json_object" }
95
- }),
96
- signal: AbortSignal.timeout(30_000),
97
- });
98
- if (!response.ok) {
99
- console.error(`[WARN] Groq HTTP ${response.status}`);
100
- continue;
101
- }
102
- const data = await response.json();
103
- const text = data.choices?.[0]?.message?.content;
104
- if (!text)
105
- continue;
106
- const parsed = JSON.parse(text);
107
- if (parsed.decisions && parsed.lessons) {
108
- console.log("[INFO] Groq fallback OK");
109
- return parsed;
110
- }
111
- }
112
- catch (err) {
113
- console.error(`[WARN] Groq error: ${err instanceof Error ? err.message : String(err)}`);
114
- }
115
- }
116
- console.error("[WARN] Groq failed — falling back to Gemini retry");
117
- return await callGeminiSimple(prompt);
118
- // Note: Claude Haiku is called from the main consolidate() loop after callGroqFallback returns null.
119
- // callGeminiSimple is kept here as a last-resort inside the Groq path only.
120
- }
121
78
  /**
122
79
  * Final fallback: Claude Haiku via Anthropic Messages API.
123
80
  * sk-ant-oat OAuth tokens work fine with the direct API endpoint.
@@ -367,14 +324,15 @@ export async function consolidate(options) {
367
324
  }
368
325
  const fullText = filteredChunks.map((c) => c.chunk_text).join("\n\n");
369
326
  const prompt = promptTemplate + fullText;
370
- // Fallback chain: Gemini → Groq → Claude Haiku → GeminiSimple
327
+ // Fallback chain: Gemini → GeminiSimple → Claude Haiku. GeminiSimple used to run inside the
328
+ // Groq step, with or without its key; Groq left the package and the order did not change.
371
329
  let result = await callGemini(prompt);
372
330
  if (!result) {
373
- console.error("[WARN] Gemini failed — trying Groq fallback...");
374
- result = await callGroqFallback(prompt);
331
+ console.error("[WARN] Gemini failed — trying Gemini simple retry...");
332
+ result = await callGeminiSimple(prompt);
375
333
  }
376
334
  if (!result) {
377
- console.error("[WARN] Groq failed — trying Claude Haiku fallback...");
335
+ console.error("[WARN] Gemini simple failed — trying Claude Haiku fallback...");
378
336
  result = await callClaudeHaiku(prompt);
379
337
  }
380
338
  if (!result) {
package/dist/digest.js CHANGED
@@ -8,9 +8,6 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
8
8
  const WORKSPACE = workspaceRoot();
9
9
  // Primary: Gemini 2.5 Flash (large context, free tier, handles 50k+ tokens)
10
10
  const GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent";
11
- // Secondary: Groq (fast, but 12k TPM limit — fails on large digests)
12
- const GROQ_URL = "https://api.groq.com/openai/v1/chat/completions";
13
- const GROQ_MODEL = "llama-3.3-70b-versatile";
14
11
  // Fallback: Ollama local (llama3.2:3b — limited ctx 4096 tokens, may fail with large prompts)
15
12
  const OLLAMA_URL = "http://127.0.0.1:11434/api/generate";
16
13
  const OLLAMA_MODEL = "llama3.2:3b";
@@ -66,54 +63,6 @@ async function callGemini(prompt, retries = 2) {
66
63
  }
67
64
  return null;
68
65
  }
69
- /**
70
- * Call Groq API (OpenAI-compatible). Returns null if unavailable.
71
- */
72
- async function callGroq(prompt, retries = 2) {
73
- const apiKey = process.env.GROQ_API_KEY;
74
- if (!apiKey) {
75
- console.error("[WARN] GROQ_API_KEY not set — skipping Groq");
76
- return null;
77
- }
78
- for (let attempt = 1; attempt <= retries; attempt++) {
79
- try {
80
- console.error(`[INFO] Calling Groq (attempt ${attempt}/${retries})...`);
81
- const response = await fetch(GROQ_URL, {
82
- method: "POST",
83
- headers: {
84
- "Content-Type": "application/json",
85
- "Authorization": `Bearer ${apiKey}`,
86
- },
87
- body: JSON.stringify({
88
- model: GROQ_MODEL,
89
- messages: [{ role: "user", content: prompt }],
90
- temperature: 0.3,
91
- max_tokens: 1024,
92
- }),
93
- signal: AbortSignal.timeout(60_000),
94
- });
95
- if (!response.ok) {
96
- const body = await response.text();
97
- console.error(`[WARN] Groq HTTP ${response.status} (attempt ${attempt}/${retries}): ${body.slice(0, 200)}`);
98
- if (response.status === 401 || response.status === 403)
99
- return null; // auth error, no retry
100
- continue;
101
- }
102
- const data = (await response.json());
103
- const text = data.choices?.[0]?.message?.content?.trim();
104
- if (text && text.length > 10) {
105
- console.error(`[INFO] Groq response: ${text.length} chars`);
106
- return text;
107
- }
108
- console.error(`[WARN] Empty Groq response (attempt ${attempt}/${retries})`);
109
- }
110
- catch (err) {
111
- const msg = err instanceof Error ? err.message : String(err);
112
- console.error(`[WARN] Groq error (attempt ${attempt}/${retries}): ${msg}`);
113
- }
114
- }
115
- return null;
116
- }
117
66
  /**
118
67
  * Fallback: Call Ollama local. Note: llama3.2:3b has n_ctx=4096 tokens.
119
68
  * With large prompts (>3k tokens) Ollama returns HTTP 500 — skip gracefully.
@@ -176,18 +125,14 @@ export async function digest() {
176
125
  const fullText = chunks.map((c) => `[${c.chunk_type}] ${c.chunk_text}`).join("\n\n");
177
126
  const prompt = promptTemplate + fullText;
178
127
  console.log(`[INFO] Total prompt: ${prompt.length} chars (~${Math.ceil(prompt.length / 4)} tokens)`);
179
- // Try Gemini first (primary — large context), then Groq, then Ollama
128
+ // Try Gemini first (primary — large context), then Ollama
180
129
  let result = await callGemini(prompt);
181
130
  if (!result) {
182
- console.error("[WARN] Gemini failed, trying Groq fallback...");
183
- result = await callGroq(prompt);
184
- }
185
- if (!result) {
186
- console.error("[WARN] Groq failed, trying Ollama fallback...");
131
+ console.error("[WARN] Gemini failed, trying Ollama fallback...");
187
132
  result = await callOllama(prompt);
188
133
  }
189
134
  if (!result) {
190
- console.error("[ERROR] Digest failed — Gemini, Groq and Ollama all unavailable");
135
+ console.error("[ERROR] Digest failed — Gemini and Ollama both unavailable");
191
136
  return;
192
137
  }
193
138
  const weekId = getISOWeek(new Date());
package/dist/doctor.js CHANGED
@@ -65,7 +65,7 @@ export async function doctor(opts = {}) {
65
65
  }
66
66
  // ── Optional integrations ──────────────────────────────────────────────────
67
67
  // Ollama — only the last-resort fallback of `digest` (consolidate and
68
- // kg-extract use Gemini/Groq/Claude and never call it)
68
+ // kg-extract use Gemini/Claude and never call it)
69
69
  try {
70
70
  const response = await fetch("http://127.0.0.1:11434/api/tags", { signal: AbortSignal.timeout(5000) });
71
71
  if (response.ok) {
@@ -78,7 +78,7 @@ export async function doctor(opts = {}) {
78
78
  }
79
79
  }
80
80
  catch {
81
- optional.push({ name: "Ollama", status: "⚪", detail: "not running (optional — only `digest` falls back to it; consolidate uses Gemini, then Groq, then Claude)" });
81
+ optional.push({ name: "Ollama", status: "⚪", detail: "not running (optional — only `digest` falls back to it; consolidate uses Gemini, then Claude)" });
82
82
  }
83
83
  // Notion token
84
84
  const notionTokenPath = process.env.NOX_NOTION_TOKEN_PATH ?? "/root/.config/notion/api_key";
package/dist/index.js CHANGED
@@ -264,7 +264,7 @@ program
264
264
  });
265
265
  program
266
266
  .command("consolidate")
267
- .description("Consolidate daily notes into topic files (LLM: Gemini, then Groq, then Claude — needs GEMINI_API_KEY, GROQ_API_KEY or ANTHROPIC_API_KEY)")
267
+ .description("Consolidate daily notes into topic files (LLM: Gemini, then Claude — needs GEMINI_API_KEY or ANTHROPIC_API_KEY)")
268
268
  .action(async () => {
269
269
  const { consolidate } = await import("./consolidate.js");
270
270
  const result = await consolidate();
@@ -688,6 +688,7 @@ program
688
688
  console.log(` Memories extracted: ${result.memoriesExtracted}`);
689
689
  console.log(` Memories deduped: ${result.memoriesDeduplicated}`);
690
690
  console.log(` Memories ingested: ${result.memoriesIngested}`);
691
+ console.log(` Blocks by outcome: ${JSON.stringify(result.blockOutcomes)}`);
691
692
  closeDb();
692
693
  });
693
694
  // ─── Noise filter ─────────────────────────────────────────────────────────────
@@ -7,16 +7,25 @@
7
7
  * Fluxo:
8
8
  * 1. scan: lista sessões JSONL por agente, filtra já processadas
9
9
  * 2. chunk: extrai blocos user+assistant, aplica noise filter
10
- * 3. distill: envia para Gemini Flash (ou Groq fallback) → memories
10
+ * 3. distill: envia para Gemini Flash-Lite → memories
11
11
  * 4. import: dedup semântico + ingest como chunk_type="distilled"
12
12
  */
13
- import { readdirSync, readFileSync, existsSync, statSync } from "fs";
13
+ import { readdirSync, readFileSync, existsSync, statSync, appendFileSync } from "fs";
14
14
  import { resolve } from "path";
15
15
  import { homedir } from "os";
16
16
  import { getDb } from "./db.js";
17
17
  import { isNoise } from "./noise-filter.js";
18
18
  import { isDuplicate } from "./dedup.js";
19
19
  import { incrementMetric } from "./metrics.js";
20
+ // One line of counts per real run, appended to the file named by NOX_DISTILL_OUTCOMES_PATH.
21
+ // Off when the variable is unset: the same counts already go to stdout, and a package should
22
+ // not write files nobody asked for. Set it when the distiller runs under a scheduler that keeps
23
+ // no stdout (the case that motivated it: a cron agent whose output nothing kept). Counts and
24
+ // agent ids only, no block text, no memory text. No mkdir: a recursive mkdirSync under /proc
25
+ // spun forever in a smoke test; a missing directory fails the append at once and only warns.
26
+ export function outcomesPath() {
27
+ return process.env.NOX_DISTILL_OUTCOMES_PATH || null;
28
+ }
20
29
  // tier-manager not imported here: distilled chunks use LLM-provided importance to determine tier
21
30
  // (importance >= 0.8 → working, else peripheral) — more nuanced than static getInitialTier("distilled")
22
31
  const WORKSPACE = process.env.OPENCLAW_WORKSPACE ?? "/root/.openclaw/workspace";
@@ -81,8 +90,7 @@ export function ensureDistillTable(db) {
81
90
  );
82
91
  `);
83
92
  }
84
- // ─── Session scanning ────────────────────────────────────────────────────────
85
- function listUnprocessedSessions(db, agentIds, lookbackDays) {
93
+ export function listUnprocessedSessions(db, agentIds, lookbackDays) {
86
94
  const cutoff = new Date(Date.now() - lookbackDays * 24 * 60 * 60 * 1000).toISOString();
87
95
  const sessions = [];
88
96
  for (const agentId of agentIds) {
@@ -104,20 +112,52 @@ function listUnprocessedSessions(db, agentIds, lookbackDays) {
104
112
  continue;
105
113
  // Check file modification time against lookback
106
114
  const filePath = resolve(sessionsDir, file);
115
+ let mtimeMs;
107
116
  try {
108
- const { mtimeMs } = statSync(filePath);
117
+ mtimeMs = statSync(filePath).mtimeMs;
109
118
  if (new Date(mtimeMs).toISOString() < cutoff)
110
119
  continue;
111
120
  }
112
121
  catch {
113
122
  continue;
114
123
  }
115
- sessions.push({ agentId, sessionFile: filePath, sessionKey });
124
+ sessions.push({ agentId, sessionFile: filePath, sessionKey, mtimeMs });
116
125
  }
117
126
  }
118
127
  }
128
+ // Oldest first. The caller cuts this list at maxSessionsPerRun; in readdir order, agent by
129
+ // agent, which sessions ran under a backlog was arbitrary, and the ones closest to leaving the
130
+ // lookback could wait behind new ones until they aged out (measured on one deployment: a
131
+ // backlog of 118 sessions after a transcript address change). Oldest first, a backlog drains
132
+ // before any of it expires.
133
+ sessions.sort((a, b) => a.mtimeMs - b.mtimeMs || a.sessionKey.localeCompare(b.sessionKey));
119
134
  return sessions;
120
135
  }
136
+ /** A session with fewer messages than this holds only init events: nothing to distill. */
137
+ export const MIN_SESSION_MESSAGES = 3;
138
+ /**
139
+ * Walks `pending` in order and splits it into the sessions to distill now (at most `max`, each
140
+ * with its messages already read) and the short ones, which are logged as done without counting
141
+ * against `max`. Reading stops once `max` sessions are taken; `left` is how many were not read.
142
+ *
143
+ * The budget used to be cut before the short sessions were set aside, so they spent it. Measured
144
+ * on one deployment (nightly run, 1-day lookback, max 50): 43 to 48 of the 50 sessions taken each
145
+ * night since 2026-11-10 were short, 2 to 7 were distilled, and the ~35 left over aged out of the
146
+ * lookback before the next run.
147
+ */
148
+ export function partitionPending(pending, max, read) {
149
+ const take = [];
150
+ const short = [];
151
+ let i = 0;
152
+ for (; i < pending.length && take.length < max; i++) {
153
+ const messages = read(pending[i]);
154
+ if (messages.length < MIN_SESSION_MESSAGES)
155
+ short.push({ session: pending[i], count: messages.length });
156
+ else
157
+ take.push({ session: pending[i], messages });
158
+ }
159
+ return { take, short, left: pending.length - i };
160
+ }
121
161
  // ─── Message extraction ───────────────────────────────────────────────────────
122
162
  export function extractMessages(sessionFile) {
123
163
  const messages = [];
@@ -195,12 +235,13 @@ Responda APENAS com JSON válido:
195
235
 
196
236
  Importância: 0.9+ = crítico, 0.7-0.9 = importante, 0.5-0.7 = útil, <0.5 = ignorar.
197
237
  Retorne [] se não houver nada relevante. Máximo 10 itens.`;
198
- async function distillWithGemini(conversationBlock) {
238
+ export async function distillWithGemini(conversationBlock) {
199
239
  const apiKey = process.env.GEMINI_API_KEY;
200
240
  if (!apiKey)
201
- return [];
241
+ return { outcome: "no_key", memories: [] };
242
+ let response;
202
243
  try {
203
- const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent?key=${apiKey}`, {
244
+ response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-lite:generateContent?key=${apiKey}`, {
204
245
  method: "POST",
205
246
  headers: { "Content-Type": "application/json" },
206
247
  body: JSON.stringify({
@@ -211,59 +252,52 @@ async function distillWithGemini(conversationBlock) {
211
252
  }),
212
253
  signal: AbortSignal.timeout(30_000),
213
254
  });
214
- if (!response.ok)
215
- return [];
216
- const data = await response.json();
217
- const text = data.candidates?.[0]?.content?.parts?.[0]?.text;
218
- if (!text)
219
- return [];
220
- const parsed = JSON.parse(text);
221
- return (parsed.memories ?? []).filter((m) => m.importance >= 0.5);
222
255
  }
223
256
  catch {
224
- return [];
257
+ return { outcome: "network_error", memories: [] };
225
258
  }
226
- }
227
- async function distillWithGroq(conversationBlock) {
228
- const apiKey = process.env.GROQ_API_KEY;
229
- if (!apiKey)
230
- return [];
259
+ if (!response.ok)
260
+ return { outcome: "http_error", memories: [] };
261
+ let text;
231
262
  try {
232
- const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
233
- method: "POST",
234
- headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}` },
235
- body: JSON.stringify({
236
- model: "llama-3.3-70b-versatile",
237
- messages: [
238
- { role: "system", content: DISTILL_SYSTEM },
239
- { role: "user", content: "Conversa:\n" + conversationBlock }
240
- ],
241
- temperature: 0.1,
242
- max_tokens: 1024,
243
- response_format: { type: "json_object" },
244
- }),
245
- signal: AbortSignal.timeout(25_000),
246
- });
247
- if (!response.ok)
248
- return [];
249
263
  const data = await response.json();
250
- const text = data.choices?.[0]?.message?.content;
251
- if (!text)
252
- return [];
264
+ text = data.candidates?.[0]?.content?.parts?.[0]?.text;
265
+ }
266
+ catch {
267
+ return { outcome: "bad_json", memories: [] };
268
+ }
269
+ if (!text)
270
+ return { outcome: "no_text", memories: [] };
271
+ try {
253
272
  const parsed = JSON.parse(text);
254
- return (parsed.memories ?? []).filter((m) => m.importance >= 0.5);
273
+ const memories = (parsed.memories ?? []).filter((m) => m.importance >= 0.5);
274
+ return { outcome: memories.length > 0 ? "ok" : "empty", memories };
255
275
  }
256
276
  catch {
257
- return [];
277
+ return { outcome: "bad_json", memories: [] };
258
278
  }
259
279
  }
260
- async function distillBlock(conversationBlock) {
261
- // Try Gemini first (cheaper, faster)
262
- const geminiResult = await distillWithGemini(conversationBlock);
263
- if (geminiResult.length > 0)
264
- return geminiResult;
265
- // Fallback to Groq
266
- return await distillWithGroq(conversationBlock);
280
+ export function recordOutcomes(dryRun, agentIds, lookbackDays, pending, stats) {
281
+ const path = outcomesPath();
282
+ if (dryRun || !path)
283
+ return;
284
+ try {
285
+ appendFileSync(path, JSON.stringify({
286
+ ts: new Date().toISOString(),
287
+ agents: agentIds,
288
+ lookback_days: lookbackDays,
289
+ pending,
290
+ processed: stats.processedSessions,
291
+ skipped: stats.skippedSessions,
292
+ extracted: stats.memoriesExtracted,
293
+ deduped: stats.memoriesDeduplicated,
294
+ ingested: stats.memoriesIngested,
295
+ block_outcomes: stats.blockOutcomes,
296
+ }) + "\n");
297
+ }
298
+ catch (e) {
299
+ console.warn(`[DISTILL] could not record outcomes in ${path}: ${e.message}`);
300
+ }
267
301
  }
268
302
  export async function distillSessions(options = {}) {
269
303
  const { agentIds = DEFAULT_AGENTS, maxSessionsPerRun = 50, lookbackDays = 30, dryRun = false, } = options;
@@ -276,25 +310,31 @@ export async function distillSessions(options = {}) {
276
310
  memoriesExtracted: 0,
277
311
  memoriesDeduplicated: 0,
278
312
  memoriesIngested: 0,
313
+ blockOutcomes: {},
279
314
  };
280
- const sessions = listUnprocessedSessions(db, agentIds, lookbackDays).slice(0, maxSessionsPerRun);
315
+ const pending = listUnprocessedSessions(db, agentIds, lookbackDays);
316
+ const { take: sessions, short, left } = partitionPending(pending, maxSessionsPerRun, (s) => extractMessages(s.sessionFile));
317
+ // Short sessions (just init events) are logged as done and do not count against the budget.
318
+ for (const { session, count } of short) {
319
+ stats.skippedSessions++;
320
+ if (!dryRun) {
321
+ db.prepare("INSERT OR IGNORE INTO session_distill_log (session_key, agent, chunks_extracted, message_count) VALUES (?, ?, 0, ?)").run(session.sessionKey, session.agentId, count);
322
+ }
323
+ }
324
+ if (left > 0) {
325
+ // A full list on every run is the backlog signal: say how much is left, in the log a
326
+ // scheduled job keeps, instead of leaving it to be found by a census.
327
+ console.log(`[DISTILL] Backlog: ${pending.length} unprocessed in the lookback; ${short.length} short logged, taking the ${sessions.length} oldest; ${left} left for the next run`);
328
+ }
281
329
  if (sessions.length === 0) {
282
- console.log("[DISTILL] No unprocessed sessions found");
330
+ console.log(short.length ? `[DISTILL] ${short.length} short sessions logged, none to distill` : "[DISTILL] No unprocessed sessions found");
331
+ recordOutcomes(dryRun, agentIds, lookbackDays, pending.length, stats);
283
332
  return stats;
284
333
  }
285
- console.log(`[DISTILL] Processing ${sessions.length} sessions (lookback: ${lookbackDays}d)`);
334
+ console.log(`[DISTILL] Processing ${sessions.length} sessions (lookback: ${lookbackDays}d; ${short.length} short logged)`);
286
335
  // Group messages into blocks of ~2000 chars for the LLM
287
336
  const BLOCK_SIZE = 2000;
288
- for (const { agentId, sessionFile, sessionKey } of sessions) {
289
- const messages = extractMessages(sessionFile);
290
- if (messages.length < 3) {
291
- // Skip tiny sessions (just session init events)
292
- stats.skippedSessions++;
293
- if (!dryRun) {
294
- db.prepare("INSERT OR IGNORE INTO session_distill_log (session_key, agent, chunks_extracted, message_count) VALUES (?, ?, 0, ?)").run(sessionKey, agentId, messages.length);
295
- }
296
- continue;
297
- }
337
+ for (const { session: { agentId, sessionKey }, messages } of sessions) {
298
338
  stats.messagesRead += messages.length;
299
339
  // Build conversation text, apply noise filter
300
340
  const conversationLines = messages
@@ -324,7 +364,8 @@ export async function distillSessions(options = {}) {
324
364
  console.log(`[DRY RUN] Would distill block (${block.length} chars) from ${agentId}`);
325
365
  continue;
326
366
  }
327
- const memories = await distillBlock(block);
367
+ const { outcome, memories } = await distillWithGemini(block);
368
+ stats.blockOutcomes[outcome] = (stats.blockOutcomes[outcome] ?? 0) + 1;
328
369
  stats.memoriesExtracted += memories.length;
329
370
  for (const memory of memories) {
330
371
  // Skip low importance
@@ -374,6 +415,8 @@ export async function distillSessions(options = {}) {
374
415
  }
375
416
  console.log(`[DISTILL] ${agentId} ${sessionKey.split(":")[1]?.substring(0, 8)} → ${sessionExtracted} memories`);
376
417
  }
418
+ console.log(`[DISTILL] Blocks by outcome: ${JSON.stringify(stats.blockOutcomes)}`);
377
419
  console.log(`[DISTILL] Done: ${stats.processedSessions} sessions, ${stats.memoriesIngested} ingested, ${stats.memoriesDeduplicated} deduped`);
420
+ recordOutcomes(dryRun, agentIds, lookbackDays, pending.length, stats);
378
421
  return stats;
379
422
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nox-mem",
3
- "version": "3.10.1",
3
+ "version": "3.11.1",
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",