@jossuealcala/madre 1.1.0 → 1.1.2

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.
@@ -76,7 +76,7 @@ async function geminiEmbed(texts, { key, model, dims, query, fetchImpl, timeoutM
76
76
  export function createEmbedder({ key = null, env = process.env, fetchImpl = globalThis.fetch, timeoutMs = Number(env.PULSE_EMBED_TIMEOUT_MS ?? 8000), ollama = null, ollamaEmbedder: makeOllama = null } = {}) {
77
77
  if (env.PULSE_EMBED === '0') return null;
78
78
  if (env.PULSE_EMBED_FAKE === '1') {
79
- return { model: 'fake-64', dims: 64, embed: async (texts) => texts.map((text) => fakeEmbedding(text)) };
79
+ return { model: 'fake-64', dims: 64, provider: 'fake', embed: async (texts) => texts.map((text) => fakeEmbedding(text)) };
80
80
  }
81
81
  const provider = env.PULSE_EMBED_PROVIDER ?? 'auto';
82
82
  if (provider !== 'gemini' && ollama?.running && ollama.embedModel && makeOllama) return makeOllama({ host: ollama.host, model: ollama.embedModel, fetchImpl });
@@ -84,5 +84,5 @@ export function createEmbedder({ key = null, env = process.env, fetchImpl = glob
84
84
  if (!key) return null;
85
85
  const model = env.PULSE_EMBED_MODEL ?? DEFAULT_EMBED_MODEL;
86
86
  const dims = Number(env.PULSE_EMBED_DIMS ?? DEFAULT_EMBED_DIMS);
87
- return { model: `${model}@${dims}`, dims, embed: (texts, { query = false } = {}) => geminiEmbed(texts, { key, model, dims, query, fetchImpl, timeoutMs }) };
87
+ return { model: `${model}@${dims}`, dims, provider: 'gemini', embed: (texts, { query = false } = {}) => geminiEmbed(texts, { key, model, dims, query, fetchImpl, timeoutMs }) };
88
88
  }
package/src/file-ops.mjs CHANGED
@@ -32,7 +32,8 @@ export function needsDesignation(...paths) {
32
32
  // words of a path are not its place. `src/../.git/config`, a link named `gitlink` that points at
33
33
  // `.git`, `.ENV` on a disk that does not tell it from `.env` — each wrote into a guarded zone with
34
34
  // no designation, because only the words were read. A path that does not exist yet is judged by
35
- // the real folder it would land in.
35
+ // the real folder it would land in: the nearest one that exists, however many are still to be
36
+ // made (2026-11-01, external review #60) — `gitlink/hooks/new/x` lands in .git/hooks.
36
37
  export async function needsDesignationOnDisk(root, ...paths) {
37
38
  if (needsDesignation(...paths)) return true;
38
39
  const top = await realpath(root).catch(() => null);
@@ -40,8 +41,13 @@ export async function needsDesignationOnDisk(root, ...paths) {
40
41
  for (const path of paths.filter(Boolean)) {
41
42
  const wanted = resolve(top, String(path).replace(/^\/+/, ''));
42
43
  const real = await realpath(wanted).catch(async () => {
43
- const folder = await realpath(dirname(wanted)).catch(() => null);
44
- return folder ? join(folder, basename(wanted)) : null;
44
+ const missing = [basename(wanted)];
45
+ for (let folder = dirname(wanted); ; folder = dirname(folder)) {
46
+ const found = await realpath(folder).catch(() => null);
47
+ if (found) return join(found, ...missing.reverse());
48
+ if (dirname(folder) === folder) return null;
49
+ missing.push(basename(folder));
50
+ }
45
51
  });
46
52
  if (!real || (real !== top && !real.startsWith(top + sep))) continue; // outside: the fence refuses it elsewhere
47
53
  if (needsDesignation(relative(top, real).split(sep).join('/'))) return true;
package/src/github.mjs CHANGED
@@ -229,14 +229,16 @@ export function parseIncluded(text) {
229
229
  // already has installed — it notices that and does not count the request twice. Either way the
230
230
  // line holds the method, the address, whether it went and how long it took. Never a body, never
231
231
  // a header, never the credential.
232
- export async function githubRequest({ method = 'GET', path, body = null, auth, log = null, env = process.env, timeoutMs = 20000 }) {
232
+ // `accept` is for the few reads that come in another shape (the stargazers with the day each star
233
+ // was given, src/rumbo.mjs).
234
+ export async function githubRequest({ method = 'GET', path, body = null, auth, log = null, env = process.env, timeoutMs = 20000, accept = 'application/vnd.github+json' }) {
233
235
  if (!auth) throw new GithubError('NO_CREDENTIAL', ERRORS.NO_SESSION);
234
236
  if (!String(path ?? '').startsWith('/')) throw new GithubError('FAILED', ERRORS.FAILED);
235
237
  const verb = String(method).toUpperCase();
236
238
  const url = `${API}${path}`;
237
239
  const started = Date.now();
238
240
  if (auth.kind === 'gh') {
239
- const args = ['api', '--method', verb, '--include', '-H', 'Accept: application/vnd.github+json', '-H', 'X-GitHub-Api-Version: 2022-11-28', path.replace(/^\/+/, '')];
241
+ const args = ['api', '--method', verb, '--include', '-H', `Accept: ${accept}`, '-H', 'X-GitHub-Api-Version: 2022-11-28', path.replace(/^\/+/, '')];
240
242
  if (body != null) args.push('--input', '-');
241
243
  // GH_HOST pinned: a session for an enterprise host in the environment must not take this
242
244
  // request anywhere but the host the module declared.
@@ -259,7 +261,7 @@ export async function githubRequest({ method = 'GET', path, body = null, auth, l
259
261
  response = await send(url, {
260
262
  method: verb,
261
263
  headers: {
262
- accept: 'application/vnd.github+json',
264
+ accept,
263
265
  'x-github-api-version': '2022-11-28',
264
266
  'user-agent': 'MADRE',
265
267
  authorization: `Bearer ${auth.token}`,
@@ -262,12 +262,32 @@ export async function marketAnnounced(stateRoot, keys = []) {
262
262
  export const marketNews = async (stateRoot) => (await readJson(join(folder(stateRoot), 'updates.json'))) ?? [];
263
263
  export async function marketNewsSeen(stateRoot) { await writeAtomic(join(folder(stateRoot), 'updates.json'), '[]').catch(() => {}); }
264
264
 
265
+ // What a newer file declares that the one the person accepted did not (2026-11-01, external review
266
+ // #10): a place it reaches, a key it asks for, tools for the agents, reading the chats, writing in
267
+ // the project, a command. Empty when it asks for nothing more.
268
+ export function widens(before = {}, after = {}) {
269
+ const more = [];
270
+ const hosts = (said) => new Set((said?.reaches ?? []).map((one) => one.host ?? one.to).filter(Boolean));
271
+ const had = hosts(before);
272
+ for (const host of hosts(after)) if (!had.has(host)) more.push({ what: 'reaches', host });
273
+ const keys = new Set((before?.secrets ?? []).map((one) => one.name));
274
+ for (const secret of after?.secrets ?? []) if (!keys.has(secret.name)) more.push({ what: 'secret', name: secret.label ?? secret.name });
275
+ for (const flag of ['tools', 'reads', 'writes']) if (after?.[flag] && !before?.[flag]) more.push({ what: flag });
276
+ const commands = new Set(before?.commands ?? []);
277
+ for (const command of after?.commands ?? []) if (!commands.has(command)) more.push({ what: 'command', name: command });
278
+ return more;
279
+ }
280
+
265
281
  // Every module got from the Market whose signed file changed: the new one, installed, and a line
266
- // for the person. One that fails stays as it was and is tried again next time.
282
+ // for the person. One that fails stays as it was and is tried again next time. One that declares
283
+ // more than the file the person accepted is not installed on its own: it waits, and the person is
284
+ // told once what it asks for (`held`), because accepting a module once is not accepting whatever
285
+ // it becomes.
267
286
  export async function updateFromMarket({ stateRoot, projectRoot, catalog, madre, fetchImpl = globalThis.fetch, verifyText, installText, names = {}, remove = null }) {
268
287
  const installed = await installedFromMarket(stateRoot);
269
288
  const updated = [];
270
289
  const removed = [];
290
+ const held = [];
271
291
  // Taken back (2026-10-25): a module, or the version of it this computer has, that the catalog says
272
292
  // must not run any more is removed and forgotten here, so no next catalog brings it back.
273
293
  for (const [id, have] of Object.entries(installed)) {
@@ -283,12 +303,25 @@ export async function updateFromMarket({ stateRoot, projectRoot, catalog, madre,
283
303
  const entry = catalog?.modules.find((one) => one.id === id && one.file);
284
304
  if (!entry || entry.file.sha256 === have.sha256 || !fitsVersion(madre, entry.minMadre)) continue;
285
305
  try {
306
+ if (have.held === entry.file.sha256) continue;
307
+ const fresh = await installFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl, verifyText, installText, review: true });
308
+ const kept = await readFile(join(stateRoot, 'modules', `${id}.mjs`), 'utf8').catch(() => null);
309
+ const accepted = kept ? await verifyText({ text: kept, name: `${id}.mjs`, replace: true }).catch(() => null) : null;
310
+ const more = accepted ? widens(accepted.declares, fresh.declares) : [];
311
+ if (more.length) {
312
+ // Read again: an update installed a moment ago in this same pass is already in the file.
313
+ const now = await installedFromMarket(stateRoot);
314
+ now[id] = { ...(now[id] ?? have), held: entry.file.sha256 };
315
+ await writeAtomic(join(folder(stateRoot), 'installed.json'), JSON.stringify(now, null, 2));
316
+ held.push({ id, name: names[id] ?? (typeof entry.name === 'string' ? entry.name : entry.name?.en) ?? id, kind: 'held', from: have.version ?? null, to: entry.version, more, at: new Date().toISOString() });
317
+ continue;
318
+ }
286
319
  await installFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl, verifyText, installText, accepted: true });
287
320
  updated.push({ id, name: names[id] ?? (typeof entry.name === 'string' ? entry.name : entry.name?.en) ?? id, from: have.version ?? null, to: entry.version, changes: entry.changes ?? null, at: new Date().toISOString() });
288
321
  } catch { /* tried again the next time MADRE opens */ }
289
322
  }
290
323
  // Said once each: what updated itself, and what was taken out of this computer and why.
291
- const told = [...updated, ...removed];
324
+ const told = [...updated, ...removed, ...held];
292
325
  if (told.length) {
293
326
  const news = [...(await marketNews(stateRoot)).filter((one) => !told.some((fresh) => fresh.id === one.id)), ...told];
294
327
  await writeAtomic(join(folder(stateRoot), 'updates.json'), JSON.stringify(news, null, 2));
@@ -15,7 +15,7 @@
15
15
  import { readFile, readdir, stat, realpath } from 'node:fs/promises';
16
16
  import { homedir } from 'node:os';
17
17
  import { join } from 'node:path';
18
- import { RoomMemory, formatRecall, formatMemories, MEMORY_KINDS } from '../memory.mjs';
18
+ import { RoomMemory, formatRecall, formatMemories, travels, ABERRATION, MEMORY_KINDS } from '../memory.mjs';
19
19
  import { createEmbedder } from '../embeddings.mjs';
20
20
  import { loadConfig } from '../config.mjs';
21
21
  import { Privacy, privacySettings } from '../privacy.mjs';
@@ -117,7 +117,10 @@ export async function callTool(name, args = {}, { memory, projectRoot = process.
117
117
  const text = String(args.text ?? '').replace(/\s+/g, ' ').trim();
118
118
  if (!text) return 'Give me the memory as one sentence.';
119
119
  if (text.length > 240) return `Too long (${text.length} characters): one sentence of at most 240.`;
120
- const kind = MEMORY_KINDS.includes(args.kind) ? args.kind : 'fact';
120
+ // An unknown kind is said back, not filed as a fact (2026-11-01, external review #13): the
121
+ // store drops it for the same reason (src/memory.mjs, addMemories).
122
+ if (!MEMORY_KINDS.includes(args.kind)) return `Say what kind of memory it is: one of ${MEMORY_KINDS.join(', ')}.`;
123
+ const kind = args.kind;
121
124
  const sources = (Array.isArray(args.sources) ? args.sources : []).map(Number).filter((n) => Number.isInteger(n) && n > 0);
122
125
  const last = memory.lastSequence();
123
126
  const before = memory.maxMemoryId();
@@ -154,7 +157,13 @@ export async function callTool(name, args = {}, { memory, projectRoot = process.
154
157
  return `${lines.join('\n\n')}${truncated ? '\n\n[truncated; ask for a narrower range]' : ''}`;
155
158
  }
156
159
  case 'memory_notes': {
157
- const notes = memory.memories({ limit: clamp(args.limit, 1, 100, 20), kind: MEMORY_KINDS.includes(args.kind) ? args.kind : null });
160
+ // What still stands, as the recall hands it (2026-11-01, external review #14): a note the
161
+ // human quarantined or one a later note refuted is archive, not knowledge, and listing it
162
+ // here put it back in the turn the recall had kept it out of. Asked by name, aberrations are
163
+ // listed for what they are — claims the room established are false — with what is true.
164
+ const limit = clamp(args.limit, 1, 100, 20);
165
+ const kind = MEMORY_KINDS.includes(args.kind) ? args.kind : null;
166
+ const notes = kind === ABERRATION ? memory.memories({ limit, kind }) : memory.memories({ limit: 500, kind }).filter(travels).slice(0, limit);
158
167
  return notes.length ? formatMemories(notes) : 'No distilled notes yet.';
159
168
  }
160
169
  case 'memory_timeline': {
package/src/mcp/proxy.mjs CHANGED
@@ -37,20 +37,42 @@ const say = (text) => process.stderr.write(`MADRE MCP ${serverId ?? '?'}: ${text
37
37
  // The ids of tools/list requests in flight, so their answers can be filtered on the way back.
38
38
  const listing = new Set();
39
39
  function filterOutbound(message) {
40
+ if (Array.isArray(message)) return message.map(filterOutbound);
40
41
  if (!allowed || !message || message.id === undefined || !listing.has(message.id)) return message;
41
42
  listing.delete(message.id);
42
43
  const tools = message.result?.tools;
43
44
  if (!Array.isArray(tools)) return message;
44
45
  return { ...message, result: { ...message.result, tools: tools.filter((tool) => allowed.has(tool?.name)) } };
45
46
  }
46
- // A message from the CLI: answered here when it asks for a tool it may not use; passed on otherwise.
47
+ // What a CLI may ask a server for in a turn, besides tools/call (2026-11-01, external review #61):
48
+ // the handshake and the protocol's reads. Anything else — a method this list does not know, from
49
+ // a newer protocol or from nobody — is answered here and never reaches the server, so a tool kept
50
+ // out of the turn cannot come in through a door the filter did not name. Notifications and the
51
+ // CLI's answers to the server's own questions pass as they are.
52
+ const CLIENT_METHODS = new Set([
53
+ 'initialize', 'ping', 'tools/list', 'tools/call',
54
+ 'resources/list', 'resources/templates/list', 'resources/read', 'resources/subscribe', 'resources/unsubscribe',
55
+ 'prompts/list', 'prompts/get', 'completion/complete', 'logging/setLevel',
56
+ ]);
57
+ // A message from the CLI: answered here when it asks for something it may not use; passed on
58
+ // otherwise. Answers what to send on, or null. A batch (an array) is each of its messages.
47
59
  function admit(message) {
48
- if (message?.method === 'tools/list' && message.id !== undefined) listing.add(message.id);
49
- if (message?.method === 'tools/call' && allowed && !allowed.has(message.params?.name)) {
60
+ if (Array.isArray(message)) {
61
+ const kept = message.map(admit).filter(Boolean);
62
+ return kept.length ? kept : null;
63
+ }
64
+ if (!message || typeof message !== 'object') return null;
65
+ if (typeof message.method !== 'string') return message; // the CLI's answer to the server
66
+ if (allowed && !message.method.startsWith('notifications/') && !CLIENT_METHODS.has(message.method)) {
67
+ fail(message.id, `MADRE does not pass ${message.method} to this server.`, -32601);
68
+ return null;
69
+ }
70
+ if (message.method === 'tools/list' && message.id !== undefined) listing.add(message.id);
71
+ if (message.method === 'tools/call' && allowed && !allowed.has(message.params?.name)) {
50
72
  write({ jsonrpc: '2.0', id: message.id, result: { isError: true, content: [{ type: 'text', text: `MADRE does not allow ${message.params?.name ?? 'that tool'} in this turn.` }] } });
51
- return false;
73
+ return null;
52
74
  }
53
- return true;
75
+ return message;
54
76
  }
55
77
 
56
78
  function lines(stream, onMessage) {
@@ -79,7 +101,7 @@ async function viaStdio(server) {
79
101
  child.stderr.on('data', (chunk) => process.stderr.write(chunk));
80
102
  child.stdin.on('error', () => {});
81
103
  lines(child.stdout, (message) => write(filterOutbound(message)));
82
- lines(process.stdin, (message) => { if (admit(message)) child.stdin.write(`${JSON.stringify(message)}\n`); });
104
+ lines(process.stdin, (message) => { const passed = admit(message); if (passed) child.stdin.write(`${JSON.stringify(passed)}\n`); });
83
105
  process.stdin.on('end', () => { child.stdin.end(); setTimeout(() => child.kill('SIGTERM'), 2000).unref(); });
84
106
  }
85
107
 
@@ -148,9 +170,10 @@ async function viaHttp(server) {
148
170
  };
149
171
  let queue = Promise.resolve();
150
172
  lines(process.stdin, (message) => {
151
- if (!admit(message)) return;
173
+ const passed = admit(message);
174
+ if (!passed) return;
152
175
  // In order, as a stdio server would read them: the handshake has to land before the rest.
153
- queue = queue.then(() => send(message)).catch((error) => { say(error.message); fail(message.id, `could not reach the server: ${error.message}`); });
176
+ queue = queue.then(() => send(passed)).catch((error) => { say(error.message); fail(passed.id, `could not reach the server: ${error.message}`); });
154
177
  });
155
178
  process.stdin.on('end', () => { void queue.finally(() => process.exit(0)); });
156
179
  }
@@ -11,9 +11,16 @@ export const MEMORY_TOOLS = ['memory_search', 'memory_recall', 'memory_notes', '
11
11
 
12
12
  // The same server, told who is calling: memory_note signs its notes with the
13
13
  // agent and the turn, and a GHOST turn is refused any write.
14
- export function memoryServerForTurn(server, { agent, messageId, mode = 1 }) {
14
+ // It embeds the agent's searches the way the room embeds its own, or not at all (2026-11-01,
15
+ // external review #20): `embedder` is the room's. Before, the server built its own from the Gemini
16
+ // key in the keychain, so «Memory › off» or «Ollama» in Settings still sent each search to Google,
17
+ // and an INCOGNITO search with them. Gemini only when the room uses Gemini; a room on Ollama or with
18
+ // no embedder searches by words here (the server has no Ollama of its own), and #0 always does.
19
+ export function memoryServerForTurn(server, { agent, messageId, mode = 1, embedder = null }) {
15
20
  if (!server) return null;
16
- return { ...server, env: { ...server.env, PULSE_MEMORY_AGENT: agent, PULSE_MEMORY_MESSAGE: messageId, PULSE_MEMORY_MODE: String(mode) } };
21
+ const same = Number(mode) !== 0 && (embedder?.provider === 'gemini' || embedder?.provider === 'fake');
22
+ const embed = same ? (embedder.provider === 'gemini' ? { PULSE_EMBED_PROVIDER: 'gemini' } : {}) : { PULSE_EMBED: '0' };
23
+ return { ...server, env: { ...server.env, ...embed, PULSE_MEMORY_AGENT: agent, PULSE_MEMORY_MESSAGE: messageId, PULSE_MEMORY_MODE: String(mode) } };
17
24
  }
18
25
 
19
26
  export function memoryServerFor({ dbFile, projectRoot, env = process.env }) {
package/src/memory.mjs CHANGED
@@ -577,12 +577,17 @@ export class RoomMemory {
577
577
  // The bar is high on purpose: almost every distinctive word of one has to be in the other.
578
578
  // A merely related note is not the same claim, and taking down the wrong one is worse than
579
579
  // taking down none.
580
+ // The words are not the whole claim, though: «we do not deploy on Fridays» and «we deploy on
581
+ // Fridays» share every long word and say opposite things (2026-11-01, external review #17). A note
582
+ // whose sense is the negation of the claim is never the claim, so it is never the one taken down.
580
583
  #refutedBy(text) {
581
584
  const terms = new Set(normalizeMemory(text).split(' ').filter((word) => word.length > 2));
582
585
  if (terms.size < 3) return null;
586
+ const denies = negates(text);
583
587
  let best = null;
584
588
  const standing = this.#db.prepare(`SELECT id, text FROM memories WHERE ${ZONE_GATE} ORDER BY id DESC LIMIT 200`).all();
585
589
  for (const row of standing) {
590
+ if (negates(row.text) !== denies) continue;
586
591
  const other = new Set(normalizeMemory(row.text).split(' ').filter((word) => word.length > 2));
587
592
  if (other.size < 3) continue;
588
593
  let shared = 0;
@@ -1117,6 +1122,16 @@ export class RoomMemory {
1117
1122
  }
1118
1123
  }
1119
1124
 
1125
+ // Whether a note says that something is not so, in Spanish or English: the short words the
1126
+ // matching above drops for being short are the ones that turn a claim around. Read in the first
1127
+ // clause only, where the claim is: «on port 7100 by default, not another» still says port 7100.
1128
+ const NEGATIONS = new Set(['no', 'not', 'never', 'nunca', 'jamas', 'sin', 'without', 'ni', 'nor', 'none', 'nadie', 'nada', 'nothing', 'nobody', 'tampoco', 'cannot']);
1129
+ export function negates(text) {
1130
+ const words = normalizeMemory(String(text).split(/[,;:.()\u2013\u2014]/)[0]).split(' ');
1131
+ // «don't», «isn't»: the apostrophe became a space, so the word ends in n and a lone t follows.
1132
+ return words.some((word, index) => NEGATIONS.has(word) || (word === 't' && /n$/.test(words[index - 1] ?? '')));
1133
+ }
1134
+
1120
1135
  export function normalizeMemory(text) {
1121
1136
  return String(text).toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
1122
1137
  }
@@ -1126,6 +1141,7 @@ export function formatMemories(list) {
1126
1141
  if (!list?.length) return '';
1127
1142
  return list.map((memory) => {
1128
1143
  const span = memory.fromSequence === memory.throughSequence ? `#${memory.fromSequence}` : `#${memory.fromSequence}–#${memory.throughSequence}`;
1144
+ if (memory.kind === ABERRATION) return `- [${memory.kind} · ${span}] FALSE: ${memory.text}${memory.correction ? ` — what is true: ${memory.correction}` : ''}`;
1129
1145
  return `- [${memory.kind} · ${span}] ${memory.text}`;
1130
1146
  }).join('\n');
1131
1147
  }
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: BUSL-1.1
3
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
4
+ // What a module is, asked in a process of its own (2026-11-01, external review #1).
5
+ //
6
+ // node --permission --allow-fs-read=<its folder> --allow-fs-read=<MADRE> check-alone.mjs <file>
7
+ //
8
+ // A module says what it is only by loading, and loading runs its code. Checking used to load it
9
+ // inside MADRE, before the person had read what it does and accepted it: a file from the Market,
10
+ // a newer copy from a module's own address, ran with all of MADRE's rights just to be described.
11
+ // Here it loads in a node of its own that src/modules/index.mjs starts (verifyModuleText) with
12
+ // Node's permission model: it reads only its folder and MADRE's code, writes nothing, starts no
13
+ // process or thread, gets no environment, and is stopped if it does not finish. On Node 25 and
14
+ // later the network is closed as well. What comes back is words, never the module.
15
+ import { writeSync } from 'node:fs';
16
+ import { inspectModuleFile } from './index.mjs';
17
+
18
+ // Written whole before the process ends: on a pipe, process.stdout may still be writing.
19
+ const say = (answer) => writeSync(1, `\n${JSON.stringify(answer)}\n`);
20
+ try {
21
+ say({ ok: true, module: JSON.parse(JSON.stringify(await inspectModuleFile(process.argv[2]))) });
22
+ } catch (error) {
23
+ say({ ok: false, error: String(error?.message ?? error), code: error?.code ?? null });
24
+ }
25
+ process.exit(0);
@@ -6,9 +6,10 @@
6
6
  // (defineModule is applied here), a module already built with defineModule, or a function
7
7
  // receiving { defineModule } and returning either. Agents cannot write those folders: .madre/
8
8
  // is a forbidden zone, and ~/.pulse lives outside every project.
9
- import { readdir, readFile, writeFile, mkdir, unlink, mkdtemp, rm } from 'node:fs/promises';
9
+ import { readdir, readFile, writeFile, mkdir, unlink, mkdtemp, realpath, rm } from 'node:fs/promises';
10
+ import { execFile } from 'node:child_process';
10
11
  import { translate } from '../i18n.mjs';
11
- import { join, basename, resolve, sep } from 'node:path';
12
+ import { join, basename, dirname, resolve, sep } from 'node:path';
12
13
  import { tmpdir } from 'node:os';
13
14
  import { pathToFileURL, fileURLToPath } from 'node:url';
14
15
  import { clearDeclaredDestinations, declareDestinations } from '../outbound.mjs';
@@ -86,6 +87,37 @@ async function importModuleFile(file) {
86
87
  return typeof spec.describe === 'function' ? spec : defineModule(spec);
87
88
  }
88
89
 
90
+ // The same file, described in words that cross a process: what the check and the person need,
91
+ // never the module itself. src/modules/check-alone.mjs answers with it.
92
+ export async function inspectModuleFile(file) {
93
+ const module = await importModuleFile(file);
94
+ return {
95
+ id: module.id, name: module.name, vendor: module.vendor, version: module.version ?? null, summary: module.summary ?? '', words: module.words ?? null, credit: module.credit ?? null, updates: module.updates ?? null, unknown: module.unknown ?? [], declares: declaredBy(module),
96
+ routes: (module.routes ?? []).map((route) => ({ path: typeof route.path === 'string' ? route.path : { source: route.path?.source ?? '' } })),
97
+ };
98
+ }
99
+
100
+ // Loads a candidate in a node of its own, fenced by Node's permission model (check-alone.mjs says
101
+ // what it may and may not do), so that asking what a file is never runs it inside MADRE.
102
+ const CHECK_ALONE = fileURLToPath(new URL('./check-alone.mjs', import.meta.url));
103
+ const PACKAGE_ROOT = fileURLToPath(new URL('../..', import.meta.url));
104
+ export const CHECK_MS = 15000;
105
+ const FENCE = ['--permission', '--experimental-permission'].find((flag) => process.allowedNodeEnvironmentFlags.has(flag)) ?? null;
106
+ async function inspectAlone(probe) {
107
+ const [folder, root] = await Promise.all([realpath(dirname(probe)), realpath(PACKAGE_ROOT)]);
108
+ const fence = FENCE ? [FENCE, `--allow-fs-read=${folder}`, `--allow-fs-read=${root}`] : [];
109
+ return new Promise((done, fail) => {
110
+ execFile(process.execPath, [...fence, CHECK_ALONE, join(folder, basename(probe))], { env: {}, cwd: folder, timeout: CHECK_MS, maxBuffer: 1 << 20, windowsHide: true }, (error, stdout, stderr) => {
111
+ if (error?.killed) return fail(new Error(`it did not finish loading in ${CHECK_MS / 1000} s, so MADRE stopped it: a module only declares what it is, and loading it must not wait on anything`));
112
+ const said = String(stdout ?? '').split('\n').reverse().map((line) => { try { return JSON.parse(line); } catch { return null; } }).find((one) => one && typeof one.ok === 'boolean');
113
+ if (!said) return fail(new Error(String(stderr ?? '').trim().split('\n').at(-1) || error?.message || 'it ended before saying what it is'));
114
+ if (!said.ok) return fail(Object.assign(new Error(said.error), { code: said.code ?? undefined }));
115
+ if (!said.module || typeof said.module.id !== 'string' || !/^[a-z][a-z0-9-]*$/.test(said.module.id)) return fail(new Error('it did not say a module id MADRE can use'));
116
+ return done(said.module);
117
+ });
118
+ });
119
+ }
120
+
89
121
  export async function loadExternalModules({ stateRoot, projectRoot }) {
90
122
  for (let index = MODULES.length - 1; index >= 0; index -= 1) if (MODULES[index].external) MODULES.splice(index, 1);
91
123
  loadFailures.length = 0;
@@ -153,9 +185,11 @@ export async function adoptBuiltinUpdates({ stateRoot, enabled = true, factoryKe
153
185
  }
154
186
 
155
187
  // The one door every module comes through, whoever wrote it and wherever the text came from: it
156
- // is written to a scratch copy, imported there and checked against the house rules. A module runs
157
- // inside MADRE with the human's own permissions, so the check is the point. Checking installs
158
- // nothing and touches no registry — asking what a file is must never change what is loaded.
188
+ // is written to a scratch copy, loaded there in a fenced node of its own (inspectAlone) and checked
189
+ // against the house rules. An installed module runs inside MADRE with the human's own permissions,
190
+ // so the check is the point — and checking runs nothing in MADRE (2026-11-01, external review #1).
191
+ // Checking installs nothing and touches no registry — asking what a file is must never change
192
+ // what is loaded.
159
193
  export async function verifyModuleText({ text, name = null, replace = true }) {
160
194
  const scratch = await mkdtemp(join(tmpdir(), 'madre-module-check-'));
161
195
  try {
@@ -163,7 +197,7 @@ export async function verifyModuleText({ text, name = null, replace = true }) {
163
197
  await writeFile(probe, text);
164
198
  let module;
165
199
  try {
166
- module = checkExternal(await importModuleFile(probe), { replace });
200
+ module = checkExternal(await inspectAlone(probe), { replace });
167
201
  } catch (error) {
168
202
  // The one mistake that looks right and never works: MADRE's own modules import the SDK by
169
203
  // relative path because they live inside the package, and anyone — an agent most of all —
@@ -174,7 +208,7 @@ export async function verifyModuleText({ text, name = null, replace = true }) {
174
208
  }
175
209
  throw error;
176
210
  }
177
- return { id: module.id, name: module.name, vendor: module.vendor, version: module.version ?? null, summary: module.summary ?? '', words: module.words ?? null, credit: module.credit ?? null, updates: module.updates ?? null, unknown: module.unknown ?? [], declares: declaredBy(module) };
211
+ return { id: module.id, name: module.name, vendor: module.vendor, version: module.version ?? null, summary: module.summary ?? '', words: module.words ?? null, credit: module.credit ?? null, updates: module.updates ?? null, unknown: module.unknown ?? [], declares: module.declares };
178
212
  } finally { await rm(scratch, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 }); }
179
213
  }
180
214
 
@@ -26,6 +26,10 @@ export async function recommendedHere() {
26
26
  // changes format and size with each release, needs the GPU libraries beside it and a PATH the
27
27
  // running MADRE does not see, and gives no service. One person keeps this; the script keeps itself.)
28
28
  const LINUX_SCRIPT = 'curl -fsSL https://ollama.com/install.sh | sh';
29
+ // Ollama's script now unpacks a .zst archive and stops with «requires zstd» when the tool is
30
+ // missing, which a fresh Ubuntu (WSL included) is (WIN-029: 8 copies in 1.1.0's diagnostics). On a
31
+ // system with apt, the line that runs, or the one handed over, installs zstd first.
32
+ const withZstd = (script, zstd, apt) => (zstd || !apt ? script : `sudo -n apt-get install -y zstd && ${script}`);
29
33
  const NEEDS_PASSWORD = "Ollama's install script needs the administrator password, and MADRE cannot ask for it. Run the command in a terminal, then press RECHECK.";
30
34
 
31
35
  // `sudo -n true` answers at once: 0 when no password is needed, an error when one is (or when this
@@ -44,30 +48,32 @@ export async function adminHere({ platform = process.platform, uid = process.get
44
48
 
45
49
  // Ollama is not an npm package, so each system has its own way in. Where MADRE can run it, the
46
50
  // command is shown on the button before it runs; where it cannot, it hands over the download.
47
- export function ollamaInstallPlan({ platform = process.platform, brew = null, admin = true } = {}) {
51
+ export function ollamaInstallPlan({ platform = process.platform, brew = null, admin = true, zstd = true, apt = false } = {}) {
52
+ const script = withZstd(LINUX_SCRIPT, zstd, apt);
48
53
  if (platform === 'darwin') {
49
54
  return brew
50
55
  ? { command: brew, args: ['install', 'ollama'], display: 'brew install ollama', note: 'Installs Ollama with Homebrew, the package manager already on this computer.' }
51
56
  : { command: null, download: 'https://ollama.com/download', display: null, note: 'Homebrew is not on this computer. Download Ollama from ollama.com, open it once, and press RECHECK.' };
52
57
  }
53
58
  if (platform === 'linux') {
54
- if (!admin) return { command: null, manual: true, display: LINUX_SCRIPT, note: t(NEEDS_PASSWORD) };
55
- return { command: 'sh', args: ['-c', LINUX_SCRIPT], display: LINUX_SCRIPT, note: "Ollama's own install script, downloaded from ollama.com and run on this computer." };
59
+ if (!admin) return { command: null, manual: true, display: script.replace('sudo -n ', 'sudo '), note: t(NEEDS_PASSWORD) };
60
+ return { command: 'sh', args: ['-c', script], display: script, note: "Ollama's own install script, downloaded from ollama.com and run on this computer." };
56
61
  }
57
62
  return { command: null, download: 'https://ollama.com/download', display: null, note: 'Download the Ollama installer from ollama.com, run it, and press RECHECK.' };
58
63
  }
59
64
 
60
65
  // A newer Ollama. Where MADRE can do it, the command is shown before it runs; where it cannot,
61
66
  // it hands over the download rather than pretending.
62
- export function ollamaUpdatePlan({ platform = process.platform, brew = null, admin = true } = {}) {
67
+ export function ollamaUpdatePlan({ platform = process.platform, brew = null, admin = true, zstd = true, apt = false } = {}) {
68
+ const script = withZstd(LINUX_SCRIPT, zstd, apt);
63
69
  if (platform === 'darwin') {
64
70
  return brew
65
71
  ? { command: brew, args: ['upgrade', 'ollama'], display: 'brew upgrade ollama', note: 'Upgrades Ollama with Homebrew. Your models stay where they are.' }
66
72
  : { command: null, download: 'https://ollama.com/download', display: null, note: 'Ollama was not installed with Homebrew. Download the newer one from ollama.com, open it once, and press RECHECK. Your models stay where they are.' };
67
73
  }
68
74
  if (platform === 'linux') {
69
- if (!admin) return { command: null, manual: true, display: LINUX_SCRIPT, note: `${t(NEEDS_PASSWORD)} ${t('Your models stay where they are.')}` };
70
- return { command: 'sh', args: ['-c', LINUX_SCRIPT], display: LINUX_SCRIPT, note: "Ollama's own install script upgrades in place. Your models stay where they are." };
75
+ if (!admin) return { command: null, manual: true, display: script.replace('sudo -n ', 'sudo '), note: `${t(NEEDS_PASSWORD)} ${t('Your models stay where they are.')}` };
76
+ return { command: 'sh', args: ['-c', script], display: script, note: "Ollama's own install script upgrades in place. Your models stay where they are." };
71
77
  }
72
78
  return { command: null, download: 'https://ollama.com/download', display: null, note: 'Download the newer Ollama from ollama.com and run it. Your models stay where they are.' };
73
79
  }
@@ -81,7 +87,7 @@ export async function ollamaView(probe, settings) {
81
87
  const binary = await findOnPath('ollama');
82
88
  // The sudo question is only worth asking while there is something to install.
83
89
  const admin = binary ? true : await adminHere();
84
- return { ...probe, settings, binary, install: ollamaInstallPlan({ brew: await findOnPath('brew'), admin }), start: ollamaStartPlan() };
90
+ return { ...probe, settings, binary, install: ollamaInstallPlan({ brew: await findOnPath('brew'), admin, zstd: Boolean(await findOnPath('zstd')), apt: Boolean(await findOnPath('apt-get')) }), start: ollamaStartPlan() };
85
91
  }
86
92
 
87
93
  export default defineModule({
@@ -118,7 +124,7 @@ export default defineModule({
118
124
  },
119
125
  async updatePlan(ctx) {
120
126
  const { findOnPath } = await import('./helpers.mjs');
121
- const plan = ollamaUpdatePlan({ brew: await findOnPath('brew'), admin: await adminHere() });
127
+ const plan = ollamaUpdatePlan({ brew: await findOnPath('brew'), admin: await adminHere(), zstd: Boolean(await findOnPath('zstd')), apt: Boolean(await findOnPath('apt-get')) });
122
128
  if (!plan.command) return plan;
123
129
  // Upgrading replaces the binary, not the server already running: until it restarts, the old
124
130
  // version keeps answering. Said before the button is pressed, done after the command.
package/src/mother.mjs CHANGED
@@ -158,12 +158,17 @@ export class MotherChannel {
158
158
 
159
159
  lockedFor() { return Math.max(0, this.#lockUntil - Date.now()); }
160
160
 
161
- // What the children read: the recent alerts, decoded, newest last.
161
+ // What the children read: the recent alerts, decoded, newest last. An intrusion alert travels
162
+ // only while the archive is sealed (2026-11-01, external review #21): it tells every agent to
163
+ // refuse any request to delete or rewrite a memory, and for a day after a ten-minute seal that
164
+ // turned down the human's own requests. A tampered seal is still said for the day.
162
165
  recent({ withinMs = 24 * 3600 * 1000, limit = 3 } = {}) {
163
166
  const since = Date.now() - withinMs;
167
+ const sealed = this.lockedFor() > 0;
164
168
  const out = [];
165
169
  for (const alert of this.#alerts) {
166
170
  if (new Date(alert.at).getTime() < since) continue;
171
+ if (alert.kind === 'intrusion' && !sealed) continue;
167
172
  try { out.push({ ...alert, text: decodeMessage(this.#seal, alert.code) }); } catch { /* sealed under an older key */ }
168
173
  }
169
174
  return out.slice(-limit);
package/src/outbound.mjs CHANGED
@@ -121,9 +121,17 @@ export const DESTINATIONS = [
121
121
  inside: true,
122
122
  },
123
123
  {
124
- id: 'usage', host: 'madre.run', match: (url) => url.pathname === '/api/usage', to: "madre.run · the author's usage figures",
125
- what: "The author's token, to read how many copies are on. Only in the author's own copy, run from source.",
126
- when: 'while the «MADRE usage» widget is on Home',
124
+ id: 'usage', host: 'madre.run', match: (url) => url.pathname === '/api/usage' || url.pathname === '/api/rumbo', to: "madre.run · the author's usage figures",
125
+ what: "The author's token, to read how many copies are on and how far new ones get. Only in the author's own copy, run from source.",
126
+ when: 'while the «MADRE usage» or «MADRE\'s course» widget is on Home',
127
+ where: "Only in the author's copy",
128
+ inside: true,
129
+ },
130
+ {
131
+ // MADRE's course (src/rumbo.mjs, 2026-11-01): npm's public download counts of the package.
132
+ id: 'npm-stats', host: 'api.npmjs.org', to: "npm · the package's download counts",
133
+ what: 'Nothing but the name of MADRE\'s package, to read how many times it was downloaded. Only in the author\'s own copy, run from source.',
134
+ when: 'while the «MADRE\'s course» widget is on Home, every half hour at most',
127
135
  where: "Only in the author's copy",
128
136
  inside: true,
129
137
  },
@@ -8,6 +8,12 @@
8
8
  import { pickDistiller, distillPrompt, parseDistillation, OLLAMA_ARCHIVIST } from '../distiller.mjs';
9
9
 
10
10
  export const BENCH_MS = 30 * 60 * 1000;
11
+ // A failure that says nothing about the batch: no network, a provider's limit or a timeout
12
+ // (2026-11-01, external review #18). Before, three of those in a row — a day offline — set the
13
+ // batch aside for good, as if it could never be distilled, and its notes were never written. Those
14
+ // stay in the queue and are tried again; only a batch that keeps failing for itself is skipped.
15
+ const PASSING = /ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ENETUNREACH|fetch failed|network|timed? ?out|\b(429|502|503|504)\b|rate.?limit|quota|usage limit|overloaded|unavailable/i;
16
+ export const passingFailure = (error) => PASSING.test(`${error?.code ?? ''} ${error?.message ?? error ?? ''}`);
11
17
 
12
18
  export function distillDefaults(distill = {}, env = process.env) {
13
19
  return {
@@ -134,7 +140,7 @@ export class Archivist {
134
140
  } catch (error) {
135
141
  const attempts = (this.#failures.get(batch.fromSequence) ?? 0) + 1;
136
142
  this.#failures.set(batch.fromSequence, attempts);
137
- const skipped = attempts >= 3;
143
+ const skipped = attempts >= 3 && !passingFailure(error);
138
144
  if (skipped) { this.#memory.markDistilled(batch.sequences); this.#failures.delete(batch.fromSequence); }
139
145
  this.#bench.set(agent.id, Date.now() + BENCH_MS);
140
146
  const next = pickDistiller(candidates, { preferred: this.#settings.agent, busy: new Set(), invokers, benched: new Set(this.#bench.keys()) });
@@ -6,7 +6,7 @@
6
6
 
7
7
  import { buildConversationContext } from '../conversation-context.mjs';
8
8
 
9
- export async function contextFor({ memory, priorEvents, messageId, text, contextMaxChars, recallShare, remember = () => {}, omitSynthetic = false, anchor = null, by = null, cascade = true, track = true }) {
9
+ export async function contextFor({ memory, priorEvents, messageId, text, contextMaxChars, recallShare, remember = () => {}, omitSynthetic = false, anchor = null, by = null, cascade = true, track = true, ghost = false }) {
10
10
  const full = buildConversationContext(priorEvents, { excludeMessageId: messageId, maxChars: contextMaxChars, omitSynthetic, anchor });
11
11
  const none = { context: full, recall: null, memories: null };
12
12
  if (!memory || !full.omittedMessages || recallShare <= 0) return none;
@@ -20,9 +20,12 @@ export async function contextFor({ memory, priorEvents, messageId, text, context
20
20
  let recall = null;
21
21
  try {
22
22
  // One embedding of the request lets both lookups match meaning; without it they match words.
23
- const queryVector = await memory.embedQuery(text);
23
+ // An INCOGNITO turn (#0) matches words only (2026-11-01, external review #20): embedding its
24
+ // request would send it to the embedder's provider, and tracking it would write down a turn
25
+ // that is off the record.
26
+ const queryVector = ghost ? null : await memory.embedQuery(text);
24
27
  // Distilled notes first (dense, cheap), exact quotes with what is left.
25
- memories = memory.recallMemories(text, { beforeSequence: before, maxChars: Math.floor(recallBudget * 0.4), queryVector, by, cascade, track });
28
+ memories = memory.recallMemories(text, { beforeSequence: before, maxChars: Math.floor(recallBudget * 0.4), queryVector, by, cascade, track: track && !ghost });
26
29
  const spent = memories.reduce((sum, item) => sum + item.text.length + 24, 0);
27
30
  recall = memory.recall(text, { beforeSequence: before, excludeMessageId: messageId, maxChars: recallBudget - spent, queryVector });
28
31
  } catch (error) {