@jossuealcala/madre 1.1.1 → 1.1.3

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.
Files changed (108) hide show
  1. package/CHANGELOG.en.md +42 -1
  2. package/CHANGELOG.md +42 -1
  3. package/README.en.md +4 -4
  4. package/README.md +4 -4
  5. package/SECURITY.md +11 -6
  6. package/bin/madre.mjs +74 -11
  7. package/docs/REFERENCE.md +15 -8
  8. package/docs/SDK.md +8 -8
  9. package/docs/en/REFERENCE.md +12 -7
  10. package/docs/en/SDK.md +8 -8
  11. package/docs/en/training/README.md +1 -1
  12. package/docs/sdk/connector-module.mjs +1 -1
  13. package/docs/sdk/hello-module.mjs +1 -1
  14. package/docs/training/README.md +1 -1
  15. package/docs/training/train.sh +3 -0
  16. package/package.json +4 -2
  17. package/public/activity.js +9 -0
  18. package/public/app.js +990 -173
  19. package/public/attribution.js +9 -0
  20. package/public/brands.js +27 -13
  21. package/public/en.js +2 -3
  22. package/public/es.js +968 -258
  23. package/public/index.html +3 -0
  24. package/public/macroverso.js +24 -5
  25. package/public/manual-content.js +38 -8
  26. package/public/market-view.js +116 -9
  27. package/public/market.js +28 -2
  28. package/public/news-scenes.js +185 -0
  29. package/public/notices.js +66 -0
  30. package/public/power.js +1 -1
  31. package/public/resay.js +3 -0
  32. package/public/salas-mac.css +294 -22
  33. package/public/salas-mac.html +3 -0
  34. package/public/salas-mac.js +760 -38
  35. package/public/styles.css +393 -17
  36. package/public/tips.js +124 -0
  37. package/public/tour-chapters.js +75 -75
  38. package/public/tour.js +36 -8
  39. package/public/troubleshooting.js +215 -22
  40. package/public/welcome-scene.js +358 -0
  41. package/public/welcome.js +523 -254
  42. package/src/adapters/gemini-rest.mjs +236 -0
  43. package/src/adapters/gemini.mjs +9 -7
  44. package/src/adapters/grok.mjs +288 -0
  45. package/src/adapters/process.mjs +14 -3
  46. package/src/auth-probe.mjs +32 -0
  47. package/src/bridge/policy.mjs +1 -1
  48. package/src/capabilities.mjs +30 -0
  49. package/src/checkpoint.mjs +115 -1
  50. package/src/codex-route.mjs +113 -0
  51. package/src/credentials.mjs +46 -8
  52. package/src/dataset.mjs +21 -8
  53. package/src/embeddings.mjs +2 -2
  54. package/src/event-store.mjs +10 -2
  55. package/src/ficha.mjs +142 -0
  56. package/src/file-ops.mjs +9 -3
  57. package/src/files.mjs +36 -2
  58. package/src/github.mjs +5 -3
  59. package/src/lease.mjs +5 -0
  60. package/src/market-check.mjs +1 -1
  61. package/src/market-remote.mjs +170 -3
  62. package/src/mcp/image-server.mjs +1 -1
  63. package/src/mcp/memory-server.mjs +22 -3
  64. package/src/mcp/proxy.mjs +31 -8
  65. package/src/memory-tools.mjs +12 -2
  66. package/src/memory.mjs +44 -3
  67. package/src/models.mjs +21 -3
  68. package/src/modules/ahp.mjs +8 -3
  69. package/src/modules/bishop-exam.mjs +41 -12
  70. package/src/modules/bishop.mjs +2 -2
  71. package/src/modules/check-alone.mjs +25 -0
  72. package/src/modules/choices.mjs +12 -10
  73. package/src/modules/fetch-alone.mjs +7 -0
  74. package/src/modules/helpers.mjs +23 -5
  75. package/src/modules/image-studio.mjs +13 -27
  76. package/src/modules/index.mjs +88 -11
  77. package/src/modules/isolated.mjs +160 -0
  78. package/src/modules/ollama.mjs +35 -6
  79. package/src/modules/playwright.mjs +46 -17
  80. package/src/modules/run-alone.mjs +122 -0
  81. package/src/modules/runs.mjs +11 -8
  82. package/src/modules/sdk.mjs +4 -2
  83. package/src/mother.mjs +6 -1
  84. package/src/notices-key.mjs +8 -0
  85. package/src/notices.mjs +185 -0
  86. package/src/ollama.mjs +57 -15
  87. package/src/outbound.mjs +56 -11
  88. package/src/room/archivist.mjs +36 -5
  89. package/src/room/busy.mjs +16 -0
  90. package/src/room/context.mjs +6 -3
  91. package/src/room/control.mjs +36 -6
  92. package/src/room/copilot.mjs +22 -28
  93. package/src/room/guard.mjs +32 -2
  94. package/src/room/prompt.mjs +32 -5
  95. package/src/room/vectors.mjs +7 -1
  96. package/src/room.mjs +98 -32
  97. package/src/router.mjs +1 -1
  98. package/src/runs.mjs +39 -0
  99. package/src/runtime-detection.mjs +46 -6
  100. package/src/salas.mjs +253 -15
  101. package/src/server.mjs +686 -87
  102. package/src/service.mjs +116 -0
  103. package/src/setup-trouble.mjs +20 -1
  104. package/src/skill-check.mjs +269 -0
  105. package/src/skills-import.mjs +128 -0
  106. package/src/skills.mjs +492 -0
  107. package/src/tour.mjs +15 -4
  108. package/src/whats-new.mjs +71 -0
package/src/ficha.mjs ADDED
@@ -0,0 +1,142 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // The ficha: what a request to MADRE carries to show it comes from the person (2026-11-02,
4
+ // external review #5).
5
+ //
6
+ // MADRE listens on 127.0.0.1, and request-guard.mjs keeps other web pages out. It did not keep out
7
+ // other programs: any process of this computer — of any user, and in WSL2 any program of Windows —
8
+ // could read a project's conversations, install a module that runs with the person's permissions,
9
+ // or open #4 by writing an Origin header by hand. Now every request that reads or changes something
10
+ // carries the ficha: a random secret in `~/.pulse/credentials/ficha.json`, readable only by the
11
+ // person's own user (0600 inside 0700), as Jupyter does with its token.
12
+ //
13
+ // · The browser gets it once, in the address MADRE opens (`?ficha=…`): the page answers with a
14
+ // cookie (HttpOnly, SameSite=Strict) and the same address without it. Cookies do not tell ports
15
+ // apart, so the one cookie serves Home and every project of this computer.
16
+ // · MADRE's own processes (the CLI, Home asking a project, a project asking another) read the file
17
+ // and send it in the `x-madre-ficha` header.
18
+ // · Home makes a new one each time it starts and opens the browser itself, so a ficha lives as
19
+ // long as that run. A restart with no browser (an update, a project Home opens) keeps it, and
20
+ // so do the tabs already open.
21
+ //
22
+ // What it does not stop, and is said in SECURITY.md: a program running as the person can read the
23
+ // file, as it can read everything else of theirs; and the cookie travels to any other port of
24
+ // 127.0.0.1 this browser visits.
25
+ import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
26
+ import { fchmodSync, openSync } from 'node:fs';
27
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
28
+ import { homedir } from 'node:os';
29
+ import { join } from 'node:path';
30
+
31
+ export const FICHA_HEADER = 'x-madre-ficha';
32
+ export const FICHA_COOKIE = 'madre_ficha';
33
+ export const FICHA_PARAM = 'ficha';
34
+ // What a 401 says in its headers, so the page knows to reload into the page that explains it.
35
+ export const FICHA_NEEDED = 'needed';
36
+ const OWNER_ONLY = 0o600;
37
+ const OWNER_DIR = 0o700;
38
+ const FICHA_HEX = /^[0-9a-f]{64}$/;
39
+
40
+ export const defaultStateRoot = (env = process.env) => env.PULSE_HOME ?? join(homedir(), '.pulse');
41
+ export const fichaFile = (stateRoot) => join(stateRoot, 'credentials', 'ficha.json');
42
+
43
+ // The ficha on file, or null when there is none (or it is not one).
44
+ export async function readFicha(stateRoot) {
45
+ try {
46
+ const parsed = JSON.parse(await readFile(fichaFile(stateRoot), 'utf8'));
47
+ return typeof parsed?.ficha === 'string' && FICHA_HEX.test(parsed.ficha) ? parsed.ficha : null;
48
+ } catch { return null; }
49
+ }
50
+
51
+ // The ficha this run uses: the one on file, or a new one when there is none or `renew` asks for it.
52
+ // Written whole beside the name and renamed over it, so nobody reads half a ficha.
53
+ export async function ensureFicha(stateRoot, { renew = false } = {}) {
54
+ if (!renew) {
55
+ const kept = await readFicha(stateRoot);
56
+ if (kept) return kept;
57
+ }
58
+ const dir = join(stateRoot, 'credentials');
59
+ await mkdir(dir, { recursive: true, mode: OWNER_DIR });
60
+ // An older credentials directory may predate this mode (src/vault.mjs does the same).
61
+ await chmod(dir, OWNER_DIR).catch(() => {});
62
+ const file = fichaFile(stateRoot);
63
+ const draft = `${file}.${process.pid}.${randomUUID()}.tmp`;
64
+ const ficha = randomBytes(32).toString('hex');
65
+ try {
66
+ await writeFile(draft, `${JSON.stringify({ ficha, at: new Date().toISOString() })}\n`, { mode: OWNER_ONLY });
67
+ await rename(draft, file);
68
+ } finally {
69
+ await rm(draft, { force: true });
70
+ }
71
+ await chmod(file, OWNER_ONLY).catch(() => {});
72
+ return ficha;
73
+ }
74
+
75
+ // The ficha as the server checks it: read again when the file changes (Home renewed it while this
76
+ // project was open), never more than once a second.
77
+ export function fichaReader(stateRoot, { everyMs = 1000 } = {}) {
78
+ let value = null;
79
+ let seen = null;
80
+ let checked = 0;
81
+ return async () => {
82
+ const now = Date.now();
83
+ if (value && now - checked < everyMs) return value;
84
+ checked = now;
85
+ const info = await stat(fichaFile(stateRoot)).catch(() => null);
86
+ const stamp = info ? `${info.mtimeMs}:${info.size}` : null;
87
+ if (stamp !== seen || !value) { value = await readFicha(stateRoot); seen = stamp; }
88
+ return value;
89
+ };
90
+ }
91
+
92
+ // A log a MADRE process writes on its way up (start.log, restart.log, update.log) holds the address
93
+ // with the ficha that process prints: kept for the person alone, as the ficha is. One written
94
+ // before this rule, open to every user of the computer, is closed the next time it is opened
95
+ // (2026-11-03, the ficha's test).
96
+ export function openPrivateLog(file) {
97
+ const fd = openSync(file, 'a', OWNER_ONLY);
98
+ try { fchmodSync(fd, OWNER_ONLY); } catch { /* a filesystem without modes */ }
99
+ return fd;
100
+ }
101
+
102
+ // The header a MADRE process sends to another, or nothing when this computer has no ficha yet (a
103
+ // MADRE that does not ask for one does not need it).
104
+ export async function fichaHeaders(stateRoot = defaultStateRoot()) {
105
+ const ficha = await readFicha(stateRoot);
106
+ return ficha ? { [FICHA_HEADER]: ficha } : {};
107
+ }
108
+
109
+ // The address MADRE opens and prints: the page's own, with the ficha for the browser to keep.
110
+ export function withFicha(url, ficha) {
111
+ if (!ficha) return url;
112
+ const address = new URL(url);
113
+ address.searchParams.set(FICHA_PARAM, ficha);
114
+ return address.toString();
115
+ }
116
+
117
+ // Constant time, and never a throw on something that is not a string.
118
+ export function sameFicha(given, ficha) {
119
+ if (typeof given !== 'string' || typeof ficha !== 'string' || !given || given.length !== ficha.length) return false;
120
+ return timingSafeEqual(Buffer.from(given), Buffer.from(ficha));
121
+ }
122
+
123
+ export function cookieFicha(cookieHeader) {
124
+ for (const part of String(cookieHeader ?? '').split(';')) {
125
+ const [name, ...rest] = part.trim().split('=');
126
+ if (name === FICHA_COOKIE) return rest.join('=');
127
+ }
128
+ return null;
129
+ }
130
+
131
+ // Whether a request carries this ficha, in its header or in the page's cookie.
132
+ export function carriesFicha(headers = {}, ficha) {
133
+ return sameFicha(headers[FICHA_HEADER], ficha) || sameFicha(cookieFicha(headers.cookie), ficha);
134
+ }
135
+
136
+ export const fichaCookie = (ficha) => `${FICHA_COOKIE}=${ficha}; Path=/; HttpOnly; SameSite=Strict; Max-Age=2592000`;
137
+
138
+ // RIPLEY's preview runs in a sealed frame, whose requests carry no cookie, and the agents' headless
139
+ // browser (src/modules/playwright.mjs) has none either. Its pages are served under a key of their own,
140
+ // made from the ficha: it opens the preview of this project's files and nothing else, and it says
141
+ // nothing of the ficha it comes from.
142
+ export const previewKey = (ficha) => createHmac('sha256', ficha).update('madre preview').digest('hex').slice(0, 32);
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/files.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // SPDX-License-Identifier: BUSL-1.1
2
2
  // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
- import { mkdir, readdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';
4
+ import { copyFile, mkdir, readdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
5
5
  import { dirname, extname, join, resolve, sep } from 'node:path';
6
6
 
7
7
  // Read-only file access for the room UI, and human attachments.
@@ -237,7 +237,41 @@ export async function createEmptyFile(root, relative) {
237
237
  return { status: 201, path: parts.join('/') };
238
238
  }
239
239
 
240
+ // Where an attachment never goes, whatever is typed after: judged part by part, as createEmptyFile
241
+ // splits them («datos\.env» is datos/.env too). Asked before the project's name, so nobody types it
242
+ // to be refused anyway.
243
+ export const ATTACHMENT_REFUSED = 'That place is MADRE\'s own or a secret\'s: choose another folder.';
244
+ export function attachmentPlaceRefused(to) {
245
+ return String(to ?? '').split(/[/\\]+/).some((part) => /^\.(pulse|madre|git)$/i.test(part) || /^\.env(\.|$)/i.test(part));
246
+ }
247
+
248
+ // An attachment of the conversation, saved into the project where the person says (L-2, Carlos's
249
+ // server, 2026-11-04): a patient's photo into pacientes/…/fotos/, a guide into conocimiento/. Until
250
+ // now a PDF or a photo stayed in MADRE's store; copying it in took a `cp`, which is #4. The person
251
+ // chooses the place, so no mode is asked. The same fence as a new file (createEmptyFile), never
252
+ // into MADRE's own folders, a repository's or a .env, and an existing file is never replaced.
253
+ export async function keepAttachment({ attachmentsRoot, projectRoot, fileName, to }) {
254
+ const from = await resolveInside(attachmentsRoot, String(fileName ?? ''));
255
+ if (!from || !(await stat(from).catch(() => null))?.isFile()) return { status: 404, error: 'That attachment is no longer here.' };
256
+ const clean = String(to ?? '').trim().replace(/^[/\\]+/, '');
257
+ if (attachmentPlaceRefused(clean)) return { status: 403, error: ATTACHMENT_REFUSED };
258
+ // Fenced and checked the way a new, empty file is; then the attachment is copied over it.
259
+ const made = await createEmptyFile(projectRoot, clean);
260
+ if (made.status !== 201) return made;
261
+ const canonicalRoot = await realpath(projectRoot);
262
+ const target = join(canonicalRoot, ...made.path.split('/'));
263
+ // A copy that fails takes back the empty file it was going into: the next try is not refused as
264
+ // «already there».
265
+ try { await copyFile(from, target); } catch (error) { await rm(target, { force: true }).catch(() => {}); return { status: 400, error: error.message }; }
266
+ const info = await stat(target);
267
+ return { status: 201, path: made.path, bytes: info.size };
268
+ }
269
+
240
270
  const safeName = (name) => String(name ?? 'file').replace(/[^\w.\- ]+/g, '_').replace(/^\.+/, '').slice(0, 120) || 'file';
271
+ // The name a person reads and is offered to save with (Q-5): «guía de curación.pdf» stays as it was
272
+ // written, accents and eñes included. Only what could break a line or a path is taken out; the file
273
+ // on disk keeps the plain name above.
274
+ const shownName = (name) => String(name ?? 'file').normalize('NFC').replace(/[\u0000-\u001f\u007f/\\]+/g, '_').replace(/^\.+/, '').trim().slice(0, 120) || 'file';
241
275
 
242
276
  export async function storeAttachment(attachmentsRoot, { name, bytes }) {
243
277
  if (!Buffer.isBuffer(bytes) || bytes.length === 0) throw new Error('Attachment is empty.');
@@ -249,7 +283,7 @@ export async function storeAttachment(attachmentsRoot, { name, bytes }) {
249
283
  await writeFile(path, bytes, { mode: 0o600 });
250
284
  return {
251
285
  id,
252
- name: safeName(name),
286
+ name: shownName(name),
253
287
  fileName,
254
288
  path,
255
289
  size: bytes.length,
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}`,
package/src/lease.mjs CHANGED
@@ -103,6 +103,10 @@ export function diffSnapshots(before, after, { relativeDir }) {
103
103
  // the ones whose adapter hands a subagent exactly the turn's permissions (src/adapters/claude.mjs,
104
104
  // opencode.mjs; Codex's subagents inherit its sandbox). Never in #4.
105
105
  export const SUBAGENT_AGENTS = new Set(['claude', 'opencode', 'codex']);
106
+ // Where MADRE puts the images Grok generates (2026-11-08, the author's choice): its image tool saves
107
+ // them in Grok's own folder, outside the project, and with no terminal below #4 it cannot copy them.
108
+ // At #2 the turn's draft folder; at #3 and #4 `imagenes/` at the project's root.
109
+ export const grokImagesDir = (lease = {}) => lease?.scratchDir || 'imagenes';
106
110
  export const subagentsAllowed = (agentId, { airlock = false } = {}) => !airlock && SUBAGENT_AGENTS.has(agentId);
107
111
 
108
112
  export function leaseInstructions({ outDir, agentId, scopes = { write: true, imageGen: agentId === 'codex' }, capable = null, imageStudio = null, control = false, create = false, airlock = false, scratchDir = null }) {
@@ -124,6 +128,7 @@ export function leaseInstructions({ outDir, agentId, scopes = { write: true, ima
124
128
  : 'Write every file you produce there (images, code, documents); paths elsewhere are denied.',
125
129
  airlock ? 'End with the commands you ran, what left the machine, and the files you changed.' : control ? 'End with a short list of the files you changed and why.' : create ? 'End with a short list of the files you created, with their paths, and why there.' : 'Reading the project stays allowed. Do not modify project files.',
126
130
  imageStudio ? `You can generate images with the MCP tool ${imageStudio.tool} (server ${imageStudio.name}): pass a detailed prompt and a file_name; it saves the PNG${scratch ? ` into ${scratch}` : ' into the lease directory'} and returns the path.`
131
+ : canImage && agentId === 'grok' ? `You can generate images with your image_gen tool. It saves each image in your own folder, outside this project; when your turn ends MADRE copies every image you generated into ${outDir}/${grokImagesDir({ scratchDir })}. Do not try to copy, convert or move it yourself, and do not write a file in its place: say what you generated and that it will be in ${grokImagesDir({ scratchDir })}/.`
127
132
  : canImage ? `You can generate images; save them${create ? ' where images live in this project, or in the scratch folder,' : ' into the lease directory'} with a descriptive file name.`
128
133
  : couldImage ? 'Image generation is switched off for this request; if asked for an image, say so and do not attempt it.'
129
134
  : 'You cannot generate images from this CLI; if asked for one, say so plainly instead of attempting it.',
@@ -122,7 +122,7 @@ export function submissionMarkdown(result, entry = {}) {
122
122
  lines.push(result.reaches.length ? result.reaches.map((one) => `- ${one.words}`).join('\n') : `- ${t('Nothing beyond what MADRE hands every module.')}`);
123
123
  for (const one of result.undeclared) lines.push(`- ⚠️ ${one}`);
124
124
  if (result.module?.unknown?.length) lines.push(`- ⚠️ ${t('Fields MADRE does not know: {list}', { list: result.module.unknown.join(', ') })}`);
125
- lines.push('', `_${t('Checked by MADRE (src/market-check.mjs). A person still reads the code before it is signed: a module runs with the permissions of whoever opens MADRE.')}_`);
125
+ lines.push('', `_${t('Checked by MADRE (src/market-check.mjs). A person still reads the code before it is signed: an installed module runs in a separate process, but Node cannot guarantee containment of malicious code.')}_`);
126
126
  return lines.join('\n');
127
127
  }
128
128
 
@@ -26,6 +26,7 @@ import { join } from 'node:path';
26
26
  import { t } from './i18n.mjs';
27
27
  import { MARKET_PUBLIC_KEY } from './market-key.mjs';
28
28
  import { mayInstall } from './market-license.mjs';
29
+ import { MARKET_MAX_FILES as MAX_SKILL_FILES, SKILL_FILES, installSkill, declaredBy as skillDeclares, readSkillText, removeSkill, runnable, safePath } from './skills.mjs';
29
30
 
30
31
  export const MARKET_URL = 'https://madre.run/mercado/catalogo.json';
31
32
  const MAX_CATALOG = 1024 * 1024;
@@ -147,10 +148,42 @@ export function readCatalog(text, { url = MARKET_URL } = {}) {
147
148
  if (!href || !SHA.test(raw.file?.sha256 ?? '') || typeof raw.file?.factory !== 'string' || raw.file.factory.length > MAX_SIGNATURE) continue;
148
149
  builtins.push({ id: raw.id, version: raw.version, sdk: raw.sdk, changes: words(raw.changes, 400), file: { url: href, sha256: raw.file.sha256, size: Number(raw.file.size) || null, factory: raw.file.factory.trim() } });
149
150
  }
151
+ // SKILLS (2026-11-08, H-4): ways of working, not code. A list of their own, like `builtins`, so a
152
+ // MADRE that does not know them (1.1.2 and before) never sees one as a module to install. Each
153
+ // file is pinned by its own sha256 — there is no archive to unpack, so there is no path to climb
154
+ // out of and no bomb to unzip — and every path is checked as the installer checks it.
155
+ const skills = [];
156
+ for (const raw of (Array.isArray(data.skills) ? data.skills : []).slice(0, 200)) {
157
+ if (!ID.test(raw?.id ?? '') || typeof raw.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(raw.version)) continue;
158
+ const files = [];
159
+ let weight = 0;
160
+ for (const file of (Array.isArray(raw.files) ? raw.files : []).slice(0, MAX_SKILL_FILES)) {
161
+ const href = fileUrl(file?.url, url);
162
+ if (!href || !safePath(file?.path) || !SHA.test(file?.sha256 ?? '')) { files.length = 0; break; }
163
+ weight += Number(file.size) || 0;
164
+ files.push({ path: String(file.path), url: href, sha256: file.sha256, size: Number(file.size) || null });
165
+ }
166
+ // Its own page is what makes it a skill; without it there is nothing to read and nothing to run.
167
+ if (!files.length || !files.some((file) => SKILL_FILES.includes(file.path)) || weight > MAX_MODULE) continue;
168
+ skills.push({
169
+ id: raw.id, version: raw.version, files,
170
+ shelf: ID.test(raw.shelf ?? '') ? raw.shelf : null,
171
+ name: words(raw.name, 60), line: words(raw.line, 140), summary: words(raw.summary, 1200),
172
+ changes: words(raw.changes, 400), credit: words(raw.credit, 60),
173
+ minMadre: typeof raw.minMadre === 'string' && /^\d+\.\d+\.\d+$/.test(raw.minMadre) ? raw.minMadre : null,
174
+ hue: Array.isArray(raw.hue) && raw.hue.length === 2 && raw.hue.every((one) => COLOR.test(one)) ? raw.hue : null,
175
+ icon: typeof raw.icon === 'string' && raw.icon.length <= 8000 ? raw.icon : null,
176
+ community: raw.community === true,
177
+ author: raw.author && typeof raw.author === 'object' && typeof raw.author.name === 'string' && raw.author.name.trim()
178
+ ? { name: raw.author.name.trim().slice(0, 60), github: /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(raw.author.github ?? '') ? raw.author.github : null }
179
+ : null,
180
+ spdx: typeof raw.spdx === 'string' && /^[A-Za-z0-9.+-]{2,40}$/.test(raw.spdx) ? raw.spdx : null,
181
+ });
182
+ }
150
183
  // TAKEN BACK: a module, or one version of it, that must not run anywhere any more. A module got
151
184
  // from the Market is removed; a newer file of one of MADRE's own goes back to the one MADRE came with.
152
185
  const revoked = (Array.isArray(data.revoked) ? data.revoked : []).filter((one) => ID.test(one?.id ?? '')).map((one) => ({ id: one.id, version: typeof one.version === 'string' && /^\d+\.\d+\.\d+$/.test(one.version) ? one.version : null, why: words(one.why, 240) })).slice(0, 100);
153
- return { schema: 1, issued: new Date(issued).toISOString(), shelves, featured, modules, news, builtins, revoked };
186
+ return { schema: 1, issued: new Date(issued).toISOString(), shelves, featured, modules, news, builtins, skills, revoked };
154
187
  }
155
188
 
156
189
  export async function bytesFrom(url, { fetchImpl, max }) {
@@ -262,12 +295,32 @@ export async function marketAnnounced(stateRoot, keys = []) {
262
295
  export const marketNews = async (stateRoot) => (await readJson(join(folder(stateRoot), 'updates.json'))) ?? [];
263
296
  export async function marketNewsSeen(stateRoot) { await writeAtomic(join(folder(stateRoot), 'updates.json'), '[]').catch(() => {}); }
264
297
 
298
+ // What a newer file declares that the one the person accepted did not (2026-11-01, external review
299
+ // #10): a place it reaches, a key it asks for, tools for the agents, reading the chats, writing in
300
+ // the project, a command. Empty when it asks for nothing more.
301
+ export function widens(before = {}, after = {}) {
302
+ const more = [];
303
+ const hosts = (said) => new Set((said?.reaches ?? []).map((one) => one.host ?? one.to).filter(Boolean));
304
+ const had = hosts(before);
305
+ for (const host of hosts(after)) if (!had.has(host)) more.push({ what: 'reaches', host });
306
+ const keys = new Set((before?.secrets ?? []).map((one) => one.name));
307
+ for (const secret of after?.secrets ?? []) if (!keys.has(secret.name)) more.push({ what: 'secret', name: secret.label ?? secret.name });
308
+ for (const flag of ['tools', 'reads', 'writes']) if (after?.[flag] && !before?.[flag]) more.push({ what: flag });
309
+ const commands = new Set(before?.commands ?? []);
310
+ for (const command of after?.commands ?? []) if (!commands.has(command)) more.push({ what: 'command', name: command });
311
+ return more;
312
+ }
313
+
265
314
  // 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.
315
+ // for the person. One that fails stays as it was and is tried again next time. One that declares
316
+ // more than the file the person accepted is not installed on its own: it waits, and the person is
317
+ // told once what it asks for (`held`), because accepting a module once is not accepting whatever
318
+ // it becomes.
267
319
  export async function updateFromMarket({ stateRoot, projectRoot, catalog, madre, fetchImpl = globalThis.fetch, verifyText, installText, names = {}, remove = null }) {
268
320
  const installed = await installedFromMarket(stateRoot);
269
321
  const updated = [];
270
322
  const removed = [];
323
+ const held = [];
271
324
  // Taken back (2026-10-25): a module, or the version of it this computer has, that the catalog says
272
325
  // must not run any more is removed and forgotten here, so no next catalog brings it back.
273
326
  for (const [id, have] of Object.entries(installed)) {
@@ -283,15 +336,129 @@ export async function updateFromMarket({ stateRoot, projectRoot, catalog, madre,
283
336
  const entry = catalog?.modules.find((one) => one.id === id && one.file);
284
337
  if (!entry || entry.file.sha256 === have.sha256 || !fitsVersion(madre, entry.minMadre)) continue;
285
338
  try {
339
+ if (have.held === entry.file.sha256) continue;
340
+ const fresh = await installFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl, verifyText, installText, review: true });
341
+ const kept = await readFile(join(stateRoot, 'modules', `${id}.mjs`), 'utf8').catch(() => null);
342
+ const accepted = kept ? await verifyText({ text: kept, name: `${id}.mjs`, replace: true }).catch(() => null) : null;
343
+ const more = accepted ? widens(accepted.declares, fresh.declares) : [];
344
+ if (more.length) {
345
+ // Read again: an update installed a moment ago in this same pass is already in the file.
346
+ const now = await installedFromMarket(stateRoot);
347
+ now[id] = { ...(now[id] ?? have), held: entry.file.sha256 };
348
+ await writeAtomic(join(folder(stateRoot), 'installed.json'), JSON.stringify(now, null, 2));
349
+ 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() });
350
+ continue;
351
+ }
286
352
  await installFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl, verifyText, installText, accepted: true });
287
353
  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
354
  } catch { /* tried again the next time MADRE opens */ }
289
355
  }
290
356
  // Said once each: what updated itself, and what was taken out of this computer and why.
291
- const told = [...updated, ...removed];
357
+ const told = [...updated, ...removed, ...held];
292
358
  if (told.length) {
293
359
  const news = [...(await marketNews(stateRoot)).filter((one) => !told.some((fresh) => fresh.id === one.id)), ...told];
294
360
  await writeAtomic(join(folder(stateRoot), 'updates.json'), JSON.stringify(news, null, 2));
295
361
  }
296
362
  return updated;
297
363
  }
364
+
365
+ // ---- SKILLS FROM THE MARKET (2026-11-08, H-4). The same chain of trust a module travels on: the
366
+ // catalog is signed with the author's key, each file is pinned by its own sha256, and a version the
367
+ // person never accepted is not installed on its own. What is different is what arrives — words, not
368
+ // code — and that it arrives as several files instead of one, so what the person accepts is a seal
369
+ // over all of them together.
370
+ const SKILL_SEAL = (files) => sha256(Buffer.from([...files].map((file) => `${file.path}\0${file.sha256}`).sort().join('\n')));
371
+ export const installedSkills = async (stateRoot) => (await readJson(join(folder(stateRoot), 'skills.json'))) ?? {};
372
+
373
+ // One skill from the catalog onto this computer, for every project (each one says when it comes in).
374
+ // Two steps, as a module's are: asked with `review`, every file is fetched and checked and what it
375
+ // says comes back with its seal, and nothing is written; installed only when the person accepted
376
+ // that very seal, so what is installed is what was read.
377
+ export async function installSkillFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl = globalThis.fetch, review = false, accept = null, accepted = false }) {
378
+ const entry = catalog?.skills?.find((one) => one.id === id);
379
+ if (!entry) throw new Error(t('The Market has no skill «{id}» to install.', { id }));
380
+ if (!fitsVersion(madre, entry.minMadre)) throw new Error(t('This skill needs MADRE {version} or newer.', { version: entry.minMadre }));
381
+ const files = [];
382
+ for (const file of entry.files) {
383
+ const bytes = await bytesFrom(file.url, { fetchImpl, max: MAX_MODULE });
384
+ if (sha256(bytes) !== file.sha256) throw new Error(t('A file of this skill is not the one the Market signed, so MADRE did not install it.'));
385
+ files.push({ path: file.path, text: bytes });
386
+ }
387
+ const main = files.find((file) => SKILL_FILES.includes(file.path));
388
+ const read = readSkillText(main.text.toString('utf8'), { id });
389
+ if (read.id !== id) throw new Error(t('The file says it is «{found}», not «{id}», so MADRE did not install it.', { found: read.id, id }));
390
+ if (read.version !== entry.version) throw new Error(t('The skill says {found} and the Market said {said}, so MADRE did not install it.', { found: read.version ?? '—', said: entry.version }));
391
+ const shape = files.map((file) => ({ path: file.path, bytes: file.text.length, runs: runnable(file.path) }));
392
+ const declares = skillDeclares({ ...read, files: shape, scripts: shape.filter((file) => file.runs).map((file) => file.path) });
393
+ const seal = SKILL_SEAL(entry.files);
394
+ if (review) return { review: true, id, name: read.name, version: entry.version, seal, declares, body: read.body, files: shape };
395
+ if (!accepted && accept !== seal) throw Object.assign(new Error(t('Read what {name} tells your agents before installing it.', { name: read.name ?? id })), { code: 'REVIEW_FIRST' });
396
+ const done = await installSkill({ files, scope: 'user', stateRoot, projectRoot, source: { kind: 'market', from: entry.files.find((file) => SKILL_FILES.includes(file.path))?.url ?? null, id } });
397
+ const kept = await installedSkills(stateRoot);
398
+ // The programs by name, not by how many: what the person accepted is these files, and a version
399
+ // that swaps one for another is asking for something new even when the count has not moved.
400
+ kept[id] = { version: entry.version, seal, scripts: declares.scripts, at: new Date().toISOString() };
401
+ await writeAtomic(join(folder(stateRoot), 'skills.json'), JSON.stringify(kept, null, 2));
402
+ return { ...done, version: entry.version, declares };
403
+ }
404
+
405
+ // A skill removed by hand is no longer the Market's to update.
406
+ export async function forgetSkillFromMarket(stateRoot, id) {
407
+ const kept = await installedSkills(stateRoot);
408
+ if (!kept[id]) return false;
409
+ delete kept[id];
410
+ await writeAtomic(join(folder(stateRoot), 'skills.json'), JSON.stringify(kept, null, 2));
411
+ return true;
412
+ }
413
+
414
+ // What a newer version asks for that the one the person accepted did not. For a skill there is one
415
+ // thing that matters: PROGRAMS. Its words can be read and changed freely between versions, and the
416
+ // mode of the turn still rules them; a file an agent could run at #4 is the one thing accepting
417
+ // version 1.0.0 never agreed to. One that brings a program, or more of them, waits for the person.
418
+ export function widensSkill(before = {}, after = {}) {
419
+ const had = new Set(before?.scripts ?? []);
420
+ return (after?.scripts ?? []).filter((path) => !had.has(path)).map((path) => ({ what: 'script', name: path }));
421
+ }
422
+
423
+ // Every skill got from the Market whose signed files changed: the new one, installed, and a line for
424
+ // the person. Taken back first. One that would bring a program the person never accepted is not
425
+ // installed on its own: it waits, and they are told once what it wants.
426
+ export async function updateSkillsFromMarket({ stateRoot, projectRoot, catalog, madre, fetchImpl = globalThis.fetch }) {
427
+ const kept = await installedSkills(stateRoot);
428
+ const updated = [];
429
+ const removed = [];
430
+ const held = [];
431
+ for (const [id, have] of Object.entries({ ...kept })) {
432
+ const taken = (catalog?.revoked ?? []).find((one) => one.id === id && (!one.version || one.version === have.version));
433
+ if (!taken) continue;
434
+ await removeSkill({ id, stateRoot, projectRoot }).catch(() => null);
435
+ await forgetSkillFromMarket(stateRoot, id);
436
+ delete kept[id];
437
+ removed.push({ id, name: catalog?.skills?.find((one) => one.id === id)?.name ?? id, kind: 'removed', version: have.version ?? null, why: taken.why ?? null, at: new Date().toISOString() });
438
+ }
439
+ for (const [id, have] of Object.entries(kept)) {
440
+ const entry = catalog?.skills?.find((one) => one.id === id);
441
+ if (!entry || SKILL_SEAL(entry.files) === have.seal || !fitsVersion(madre, entry.minMadre)) continue;
442
+ try {
443
+ const seal = SKILL_SEAL(entry.files);
444
+ if (have.held === seal) continue;
445
+ const fresh = await installSkillFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl, review: true });
446
+ const more = widensSkill({ scripts: Array.isArray(have.scripts) ? have.scripts : [] }, fresh.declares);
447
+ if (more.length) {
448
+ const now = await installedSkills(stateRoot);
449
+ now[id] = { ...(now[id] ?? have), held: seal };
450
+ await writeAtomic(join(folder(stateRoot), 'skills.json'), JSON.stringify(now, null, 2));
451
+ held.push({ id, name: fresh.name ?? id, kind: 'held', from: have.version ?? null, to: entry.version, more, at: new Date().toISOString() });
452
+ continue;
453
+ }
454
+ await installSkillFromMarket({ stateRoot, projectRoot, id, catalog, madre, fetchImpl, accepted: true });
455
+ updated.push({ id, name: fresh.name ?? id, from: have.version ?? null, to: entry.version, changes: entry.changes ?? null, at: new Date().toISOString() });
456
+ } catch { /* tried again the next time MADRE opens */ }
457
+ }
458
+ const told = [...updated, ...removed, ...held];
459
+ if (told.length) {
460
+ const news = [...(await marketNews(stateRoot)).filter((one) => !told.some((fresh) => fresh.id === one.id)), ...told];
461
+ await writeAtomic(join(folder(stateRoot), 'updates.json'), JSON.stringify(news, null, 2));
462
+ }
463
+ return { updated, removed, held };
464
+ }
@@ -34,7 +34,7 @@ const FAKE_PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADU
34
34
  // the CLI's own sign-in put it there. Leaving the file out meant MADRE saved a key in a place it
35
35
  // then refused to look, and on Linux, where there is no keychain, that was the only place it
36
36
  // could have been: Image Studio could never find a key there at all.
37
- async function keyFromGeminiEnvFile(env) {
37
+ export async function keyFromGeminiEnvFile(env) {
38
38
  const home = env.GEMINI_CLI_HOME ?? homedir();
39
39
  let text;
40
40
  try { text = await readFile(join(home, '.gemini', '.env'), 'utf8'); } catch { return null; }
@@ -15,11 +15,12 @@
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';
22
22
  import { resolveGeminiKey } from './image-server.mjs';
23
+ import { OutboundLog } from '../outbound.mjs';
23
24
 
24
25
  const SERVER_NAME = 'pulse-memory';
25
26
  const SERVER_VERSION = '0.1.0';
@@ -117,7 +118,10 @@ export async function callTool(name, args = {}, { memory, projectRoot = process.
117
118
  const text = String(args.text ?? '').replace(/\s+/g, ' ').trim();
118
119
  if (!text) return 'Give me the memory as one sentence.';
119
120
  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';
121
+ // An unknown kind is said back, not filed as a fact (2026-11-01, external review #13): the
122
+ // store drops it for the same reason (src/memory.mjs, addMemories).
123
+ if (!MEMORY_KINDS.includes(args.kind)) return `Say what kind of memory it is: one of ${MEMORY_KINDS.join(', ')}.`;
124
+ const kind = args.kind;
121
125
  const sources = (Array.isArray(args.sources) ? args.sources : []).map(Number).filter((n) => Number.isInteger(n) && n > 0);
122
126
  const last = memory.lastSequence();
123
127
  const before = memory.maxMemoryId();
@@ -154,7 +158,13 @@ export async function callTool(name, args = {}, { memory, projectRoot = process.
154
158
  return `${lines.join('\n\n')}${truncated ? '\n\n[truncated; ask for a narrower range]' : ''}`;
155
159
  }
156
160
  case 'memory_notes': {
157
- const notes = memory.memories({ limit: clamp(args.limit, 1, 100, 20), kind: MEMORY_KINDS.includes(args.kind) ? args.kind : null });
161
+ // What still stands, as the recall hands it (2026-11-01, external review #14): a note the
162
+ // human quarantined or one a later note refuted is archive, not knowledge, and listing it
163
+ // here put it back in the turn the recall had kept it out of. Asked by name, aberrations are
164
+ // listed for what they are — claims the room established are false — with what is true.
165
+ const limit = clamp(args.limit, 1, 100, 20);
166
+ const kind = MEMORY_KINDS.includes(args.kind) ? args.kind : null;
167
+ const notes = kind === ABERRATION ? memory.memories({ limit, kind }) : memory.memories({ limit: 500, kind }).filter(travels).slice(0, limit);
158
168
  return notes.length ? formatMemories(notes) : 'No distilled notes yet.';
159
169
  }
160
170
  case 'memory_timeline': {
@@ -219,9 +229,18 @@ export function serve({ input = process.stdin, output = process.stdout, context
219
229
  input.on('end', () => { ended = true; finish(); });
220
230
  }
221
231
 
232
+ // What this process sends lands in the room's «What leaves» (RX-20, external review #20): the
233
+ // searches it embeds with Gemini went to Google from here, outside the log that promises to see
234
+ // every fetch. Bodies and queries are never written, only where it went and whether it answered.
235
+ export function watchOutbound(env = process.env, target = globalThis) {
236
+ if (!env.PULSE_OUTBOUND_LOG) return null;
237
+ return new OutboundLog({ file: env.PULSE_OUTBOUND_LOG }).install(target);
238
+ }
239
+
222
240
  const invokedDirectly = process.argv[1] && (await realpath(process.argv[1]).catch(() => process.argv[1])) === (await realpath(new URL(import.meta.url).pathname).catch(() => null));
223
241
  if (invokedDirectly) {
224
242
  try {
243
+ watchOutbound();
225
244
  const memory = await openMemory();
226
245
  serve({ context: { memory, projectRoot: process.env.PULSE_PROJECT_ROOT, agent: process.env.PULSE_MEMORY_AGENT ?? 'agent', mode: process.env.PULSE_MEMORY_MODE ?? '1', messageId: process.env.PULSE_MEMORY_MESSAGE ?? null } });
227
246
  } catch (error) {