nox-mem 3.7.0 → 3.9.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
@@ -84,6 +84,8 @@ nox-mem stats
84
84
  |---|---|---|
85
85
  | `NOX_DB_PATH` | `~/.nox-mem/nox.db` | SQLite database path. A missing parent directory is created (mode 0700). Its directory is auto-added to the op-audit allowlist. |
86
86
  | `NOX_MEM_DIR` | — | **Not** the notes folder: nothing ingests or watches it. It only sets where pre-op snapshots go (`$NOX_MEM_DIR/.nox-snapshots`) and widens the op-audit allowlist. |
87
+ | `NOX_MEM_SCOPE` | unset | One sentence naming what the memory covers; the MCP server puts it in its `instructions` so the agent knows when a search can help. Recommended, see [Key commands](#key-commands). Collapsed to one line, capped at 800 characters. |
88
+ | `NOX_MEM_INSTRUCTIONS` | on | `off` makes the MCP server send no `instructions`. |
87
89
  | `NOX_ALLOW_PROD_INGEST` | — | `1` skips the large-database ingest guard (same as `--allow-prod`). See [Large databases](#large-databases-the-ingest-guard). |
88
90
 
89
91
  ### API server
@@ -249,7 +251,7 @@ nox-mem stats — chunk/entity/vector counts
249
251
  nox-mem kg-build — extract knowledge graph entities
250
252
  nox-mem reflect "question" — synthesis over memory + KG, with cited sources
251
253
  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)
254
+ nox-mem-mcp — start MCP server over stdio (22 tools, incl. nox_mem_answer and nox_mem_get, for agents)
253
255
  nox-mem doctor — health check (core + optional integrations)
254
256
  nox-mem --help — full command reference
255
257
  ```
@@ -257,9 +259,23 @@ nox-mem --help — full command reference
257
259
  Wire the MCP server into Claude Code:
258
260
 
259
261
  ```bash
260
- claude mcp add nox-mem -e NOX_DB_PATH="$HOME/.nox-mem/nox.db" -e GEMINI_API_KEY="$GEMINI_API_KEY" -- nox-mem-mcp
262
+ claude mcp add nox-mem -e NOX_DB_PATH="$HOME/.nox-mem/nox.db" -e GEMINI_API_KEY="$GEMINI_API_KEY" \
263
+ -e NOX_MEM_SCOPE="the billing API and its deploy pipeline, and the data warehouse" -- nox-mem-mcp
261
264
  ```
262
265
 
266
+ **Say what the memory covers (`NOX_MEM_SCOPE`).** An agent that is never told the memory holds
267
+ something relevant does not search it: in our evaluation (Claude Code, Sonnet 5.5) an agent with
268
+ the MCP server connected and no other guidance searched in 5% of tasks that needed the memory and
269
+ answered 7% of them right. The server now sends MCP `instructions` (the one server-side text that
270
+ clients keep in context before the agent picks a tool) saying when to search. With a one-sentence
271
+ scope in `NOX_MEM_SCOPE`, the same tasks were answered right 53% of the time, and the agent
272
+ searched on 2% of control tasks that the memory could not help with. Without a scope the server
273
+ sends a generic version: about as accurate (56%), but it also searched on a third of unrelated
274
+ configuration changes. So set the scope: name the projects or systems your memory holds, in one
275
+ sentence, as you would to a new colleague. `NOX_MEM_INSTRUCTIONS=off` sends no instructions.
276
+ These numbers are from one model, one client and one corpus; the instructions did not make the
277
+ agent record decisions (`nox_mem_decision_set`) any more often.
278
+
263
279
  HTTP endpoints worth knowing: `GET /api/health`, `GET /api/search?q=`, `GET /api/brief`, `POST /api/answer`, `GET /api/kg`, and `GET /api/reflect?q=…` (synthesis over memory + KG; `q` is required, a request without it is a 400).
264
280
 
265
281
  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.
@@ -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 {};
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Text the MCP server sends in the `instructions` field of its `initialize` result.
3
+ *
4
+ * Why it exists: MCP clients such as Claude Code defer tool schemas, so the model sees only tool
5
+ * names until it decides to search. A tool description is read after that decision, never before
6
+ * it. `instructions` is the one server-side channel that is always in context (Claude Code puts it
7
+ * in the system prompt), so it is where "when to search" has to live.
8
+ *
9
+ * Both texts below were measured, word for word, in the skill evaluation (Claude Code, Sonnet 5.5,
10
+ * 36 memory-dependent tasks and 20 control tasks, 3 replicas):
11
+ *
12
+ * - scoped (NOX_MEM_SCOPE set): pass rate 0.07 -> 0.53, +0.46 [0.32, 0.61]; searches on control
13
+ * tasks that do not need the memory +1.7 pp; median token overhead +2.1%.
14
+ * - unscoped (NOX_MEM_SCOPE unset): pass rate 0.07 -> 0.56, +0.49 [0.35, 0.63], but it searched
15
+ * on about one in three unrelated configuration changes (+31.7 pp).
16
+ *
17
+ * Edits to the wording are edits to a measured intervention: the tests pin both texts, and a
18
+ * change should come with a new run.
19
+ */
20
+ const MAX_SCOPE_CHARS = 800;
21
+ const SCOPED_INTRO = (scope) => `nox-mem holds this user's past work on one scope: ${scope}. It holds decisions, incidents, ` +
22
+ `measurements and notes about that scope. You cannot see it unless you search, and the usual ` +
23
+ `failure is not searching at all, because the task never names what the memory holds.`;
24
+ const SCOPED_WHEN = "Search nox-mem before acting when the task touches that scope and: you are about to change, or " +
25
+ "recommend changing, a setting, default, threshold, retention, schedule, schema, model or " +
26
+ "dependency (past decisions often forbid the obvious change); you are explaining why something is " +
27
+ "the way it is or what was decided; you are about to state a number about it; an error looks like " +
28
+ "it may have happened before. Also search when the task names a project or person you do not " +
29
+ "recognize. Do not search for software outside that scope (a setting of some other service, say), " +
30
+ "for general knowledge, or for a fully specified code change.";
31
+ const UNSCOPED_INTRO = "nox-mem holds this user's past work: decisions, incidents, measurements, notes. You cannot see " +
32
+ "it unless you search, and the usual failure is not searching at all, because the task never " +
33
+ "names what the memory holds.";
34
+ const UNSCOPED_WHEN = "Search nox-mem before acting when: you are about to change, or recommend changing, a setting, " +
35
+ "default, threshold, retention, schedule, schema, model or dependency (past decisions often forbid " +
36
+ "the obvious change); you are explaining why something is the way it is or what was decided; the " +
37
+ "task mentions a project, system or person you do not recognize; you are about to state a number " +
38
+ "about this project; an error looks like it may have happened before. Do not search for general " +
39
+ "knowledge or a fully specified code change.";
40
+ const HOW = "How: nox_mem_search with 3 to 8 distinctive nouns; nox_mem_get for the full text of a hit; " +
41
+ "nox_mem_decision_get or nox_mem_decision_list for recorded rules. Stop after three searches and " +
42
+ "say so if nothing relevant comes back. Treat results as dated evidence and name the source you " +
43
+ "relied on.";
44
+ // Measured with no effect on writing (0 of 30 runs wrote when the user stated a decision); kept
45
+ // because it is what was measured with the rest, not because it works.
46
+ const WRITE = "Write when the user states a decision (nox_mem_decision_set, stable slug key, with the reason) or " +
47
+ "a root cause is confirmed. Do not write what git already records.";
48
+ /** Normalise a user-supplied scope: one line, no trailing period, bounded length. */
49
+ export function normaliseScope(raw) {
50
+ if (!raw)
51
+ return "";
52
+ let s = raw.replace(/\s+/g, " ").trim().replace(/\.+$/, "").trim();
53
+ if (s.length > MAX_SCOPE_CHARS)
54
+ s = s.slice(0, MAX_SCOPE_CHARS).replace(/\s+\S*$/, "");
55
+ return s;
56
+ }
57
+ /**
58
+ * Build the `instructions` text. Returns undefined when disabled with NOX_MEM_INSTRUCTIONS=off,
59
+ * so the caller can omit the field.
60
+ */
61
+ export function serverInstructions(env = process.env) {
62
+ const mode = (env.NOX_MEM_INSTRUCTIONS || "").trim().toLowerCase();
63
+ if (mode === "off" || mode === "0" || mode === "false")
64
+ return undefined;
65
+ const scope = normaliseScope(env.NOX_MEM_SCOPE);
66
+ const intro = scope ? SCOPED_INTRO(scope) : UNSCOPED_INTRO;
67
+ const when = scope ? SCOPED_WHEN : UNSCOPED_WHEN;
68
+ return [intro, when, HOW, WRITE].join("\n\n");
69
+ }
@@ -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";
@@ -16,14 +17,18 @@ import { createInterface } from "readline";
16
17
  import { VERSION } from "./version.js";
17
18
  import { parseTemporalFilter } from "./lib/dates.js";
18
19
  import { noxMemAnswerTool } from "./mcp/tools/answer.js";
20
+ import { serverInstructions } from "./mcp-instructions.js";
19
21
  const SERVER_INFO = {
20
22
  name: "nox-mem",
21
23
  version: VERSION,
22
24
  };
25
+ // When to search lives here, not in tool descriptions: clients that defer tool schemas show the model
26
+ // only tool names until it has already decided to search. See mcp-instructions.ts.
27
+ const INSTRUCTIONS = serverInstructions();
23
28
  const TOOLS = [
24
29
  {
25
30
  name: "nox_mem_search",
26
- description: "Search nox-mem memory using FTS5 full-text search with BM25 ranking, type boosting, and recency scoring",
31
+ description: "Search this user's project memory (decisions, incidents, measurements, notes) with hybrid full-text and semantic ranking. Use before changing a setting, default, threshold, schedule, schema, model or dependency, or before explaining why something is the way it is: past decisions often forbid the obvious change. Returns each hit's chunk id, source, date and text.",
27
32
  inputSchema: {
28
33
  type: "object",
29
34
  properties: {
@@ -35,6 +40,17 @@ const TOOLS = [
35
40
  required: ["query"],
36
41
  },
37
42
  },
43
+ {
44
+ name: "nox_mem_get",
45
+ 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.",
46
+ inputSchema: {
47
+ type: "object",
48
+ properties: {
49
+ id: { type: "number", description: "One chunk id" },
50
+ ids: { type: "array", items: { type: "number" }, description: "Several chunk ids (max 10)" },
51
+ },
52
+ },
53
+ },
38
54
  {
39
55
  name: "nox_mem_stats",
40
56
  description: "Get nox-mem database statistics: chunk counts by type, consolidation status, DB size",
@@ -150,7 +166,7 @@ const TOOLS = [
150
166
  },
151
167
  {
152
168
  name: "nox_mem_decision_set",
153
- description: "Set/update a versioned decision. Stores full history — every call creates a new version. Use for technical decisions, policies, or operational rules that may evolve.",
169
+ description: "Record a decision the user states, with its reason, as a versioned entry (every call creates a new version). Use when the user decides something mid-task, or a root cause or operational rule is confirmed.",
154
170
  inputSchema: {
155
171
  type: "object",
156
172
  properties: {
@@ -209,6 +225,24 @@ const TOOLS = [
209
225
  inputSchema: noxMemAnswerTool.inputSchema,
210
226
  },
211
227
  ];
228
+ const MAX_GET_IDS = 10;
229
+ /** Read-only by design: no access counter, no telemetry, nothing a ranking signal could learn from. */
230
+ function getChunks(ids) {
231
+ const rows = getDb()
232
+ .prepare(`SELECT id, source_file, chunk_type, chunk_text, source_date FROM chunks
233
+ WHERE id IN (${ids.map(() => "?").join(",")})`)
234
+ .all(...ids);
235
+ const byId = new Map(rows.map((r) => [r.id, r]));
236
+ return ids
237
+ .map((id) => {
238
+ const r = byId.get(id);
239
+ if (!r)
240
+ return `chunk ${id}: not found`;
241
+ const date = r.source_date ? ` · ${r.source_date}` : "";
242
+ return `chunk ${r.id} · ${r.source_file} · ${r.chunk_type}${date}\n${r.chunk_text}`;
243
+ })
244
+ .join("\n\n---\n\n");
245
+ }
212
246
  function sendResponse(id, result) {
213
247
  const msg = JSON.stringify({ jsonrpc: "2.0", id, result });
214
248
  process.stdout.write(msg + "\n");
@@ -225,6 +259,7 @@ async function handleRequest(req) {
225
259
  protocolVersion: "2024-11-05",
226
260
  capabilities: { tools: {} },
227
261
  serverInfo: SERVER_INFO,
262
+ ...(INSTRUCTIONS ? { instructions: INSTRUCTIONS } : {}),
228
263
  });
229
264
  break;
230
265
  case "notifications/initialized":
@@ -261,7 +296,16 @@ async function handleRequest(req) {
261
296
  changedSince: args.changed_since,
262
297
  });
263
298
  const results = await searchHybrid(query, limit, true, filter, { surface: "mcp", agent: process.env.NOX_AGENT_NAME });
264
- text = formatResults(results);
299
+ text = formatResultsForAgent(results);
300
+ break;
301
+ }
302
+ case "nox_mem_get": {
303
+ const raw = args.ids ?? (args.id != null ? [args.id] : []);
304
+ const ids = (Array.isArray(raw) ? raw : [raw]).map(Number);
305
+ if (ids.length === 0 || ids.length > MAX_GET_IDS || ids.some((n) => !Number.isInteger(n) || n <= 0)) {
306
+ throw new Error(`nox_mem_get takes "id" or "ids" (1 to ${MAX_GET_IDS} positive integers)`);
307
+ }
308
+ text = getChunks(ids);
265
309
  break;
266
310
  }
267
311
  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.7.0",
3
+ "version": "3.9.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",