@jossuealcala/madre 1.0.4 → 1.1.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.
Files changed (273) hide show
  1. package/ADDITIONAL-TERMS.md +7 -2
  2. package/CHANGELOG.en.md +152 -1
  3. package/CHANGELOG.md +152 -1
  4. package/CONTRIBUTING.md +2 -2
  5. package/LICENSE +111 -661
  6. package/NOTICE +59 -24
  7. package/README.en.md +36 -204
  8. package/README.md +36 -210
  9. package/SECURITY.md +1 -0
  10. package/TRADEMARKS.en.md +13 -14
  11. package/TRADEMARKS.md +42 -26
  12. package/bin/madre.cjs +2 -2
  13. package/bin/madre.mjs +114 -42
  14. package/docs/REFERENCE.md +53 -6
  15. package/docs/SDK.md +44 -5
  16. package/docs/en/REFERENCE.md +53 -6
  17. package/docs/en/SDK.md +43 -4
  18. package/docs/madre-banner.png +0 -0
  19. package/docs/sdk/hello-module.mjs +3 -0
  20. package/package.json +3 -2
  21. package/public/abduction.js +6 -6
  22. package/public/activity.js +425 -0
  23. package/public/app.js +3519 -647
  24. package/public/assets/abduction-cat-blink.webp +0 -0
  25. package/public/assets/abduction-cat-control-left.webp +0 -0
  26. package/public/assets/abduction-cat-control-right.webp +0 -0
  27. package/public/assets/abduction-cat.webp +0 -0
  28. package/public/assets/manual/shots/en-agents.webp +0 -0
  29. package/public/assets/manual/shots/en-chats.webp +0 -0
  30. package/public/assets/manual/shots/en-code.webp +0 -0
  31. package/public/assets/manual/shots/en-composer.webp +0 -0
  32. package/public/assets/manual/shots/en-connectors.webp +0 -0
  33. package/public/assets/manual/shots/en-continuity.webp +0 -0
  34. package/public/assets/manual/shots/en-coordinator.webp +0 -0
  35. package/public/assets/manual/shots/en-copilot.webp +0 -0
  36. package/public/assets/manual/shots/en-diagnostics.webp +0 -0
  37. package/public/assets/manual/shots/en-home.webp +0 -0
  38. package/public/assets/manual/shots/en-local.webp +0 -0
  39. package/public/assets/manual/shots/en-market.webp +0 -0
  40. package/public/assets/manual/shots/en-memory.webp +0 -0
  41. package/public/assets/manual/shots/en-modes.webp +0 -0
  42. package/public/assets/manual/shots/en-notes.webp +0 -0
  43. package/public/assets/manual/shots/en-settings.webp +0 -0
  44. package/public/assets/manual/shots/en-welcome.webp +0 -0
  45. package/public/assets/manual/shots/en-windows.webp +0 -0
  46. package/public/assets/manual/shots/es-agents.webp +0 -0
  47. package/public/assets/manual/shots/es-chats.webp +0 -0
  48. package/public/assets/manual/shots/es-code.webp +0 -0
  49. package/public/assets/manual/shots/es-composer.webp +0 -0
  50. package/public/assets/manual/shots/es-connectors.webp +0 -0
  51. package/public/assets/manual/shots/es-continuity.webp +0 -0
  52. package/public/assets/manual/shots/es-coordinator.webp +0 -0
  53. package/public/assets/manual/shots/es-copilot.webp +0 -0
  54. package/public/assets/manual/shots/es-diagnostics.webp +0 -0
  55. package/public/assets/manual/shots/es-home.webp +0 -0
  56. package/public/assets/manual/shots/es-local.webp +0 -0
  57. package/public/assets/manual/shots/es-market.webp +0 -0
  58. package/public/assets/manual/shots/es-memory.webp +0 -0
  59. package/public/assets/manual/shots/es-modes.webp +0 -0
  60. package/public/assets/manual/shots/es-notes.webp +0 -0
  61. package/public/assets/manual/shots/es-settings.webp +0 -0
  62. package/public/assets/manual/shots/es-welcome.webp +0 -0
  63. package/public/assets/manual/shots/es-windows.webp +0 -0
  64. package/public/assets/news/1.1/en/chats.webp +0 -0
  65. package/public/assets/news/1.1/en/home.webp +0 -0
  66. package/public/assets/news/1.1/en/maps.webp +0 -0
  67. package/public/assets/news/1.1/en/market.webp +0 -0
  68. package/public/assets/news/1.1/en/permissions.webp +0 -0
  69. package/public/assets/news/1.1/en/privacy.webp +0 -0
  70. package/public/assets/news/1.1/en/welcome.webp +0 -0
  71. package/public/assets/news/1.1/es/chats.webp +0 -0
  72. package/public/assets/news/1.1/es/home.webp +0 -0
  73. package/public/assets/news/1.1/es/maps.webp +0 -0
  74. package/public/assets/news/1.1/es/market.webp +0 -0
  75. package/public/assets/news/1.1/es/permissions.webp +0 -0
  76. package/public/assets/news/1.1/es/privacy.webp +0 -0
  77. package/public/assets/news/1.1/es/welcome.webp +0 -0
  78. package/public/attribution.js +15 -16
  79. package/public/brands.js +2 -2
  80. package/public/code-tools.js +2 -2
  81. package/public/editor.js +13 -13
  82. package/public/en.js +483 -0
  83. package/public/es.js +1817 -598
  84. package/public/hardware.js +2 -2
  85. package/public/i18n.js +47 -9
  86. package/public/icons.js +158 -0
  87. package/public/index.html +68 -51
  88. package/public/inquiry.js +2 -2
  89. package/public/loader.js +271 -2
  90. package/public/macroverso.js +60 -21
  91. package/public/manual-content.js +900 -0
  92. package/public/manual-shots.js +47 -0
  93. package/public/manual.css +246 -0
  94. package/public/manual.html +15 -0
  95. package/public/manual.js +427 -0
  96. package/public/market-art.js +99 -41
  97. package/public/market-view.js +243 -47
  98. package/public/market.js +139 -26
  99. package/public/mcp-catalog.js +62 -0
  100. package/public/neural.js +64 -8
  101. package/public/nostromo-engine.js +709 -40
  102. package/public/page-errors.js +29 -0
  103. package/public/power.js +350 -11
  104. package/public/remedy.js +89 -0
  105. package/public/resay.js +4 -2
  106. package/public/review-ask.js +12 -7
  107. package/public/routing.js +3 -3
  108. package/public/salas-mac.css +875 -48
  109. package/public/salas-mac.html +27 -15
  110. package/public/salas-mac.js +1668 -338
  111. package/public/salas.css +2 -2
  112. package/public/salas.html +3 -3
  113. package/public/salas.js +3 -3
  114. package/public/styles.css +2694 -323
  115. package/public/syntax.js +2 -2
  116. package/public/terms.js +152 -0
  117. package/public/touch.js +2 -2
  118. package/public/tour-chapters.js +100 -92
  119. package/public/tour.js +118 -28
  120. package/public/troubleshooting.js +327 -21
  121. package/public/wallpaper.js +4 -3
  122. package/public/welcome.js +923 -0
  123. package/src/activity.mjs +85 -0
  124. package/src/adapters/claude.mjs +61 -35
  125. package/src/adapters/codex.mjs +18 -5
  126. package/src/adapters/cursor.mjs +60 -9
  127. package/src/adapters/gemini.mjs +17 -4
  128. package/src/adapters/madre.mjs +30 -9
  129. package/src/adapters/opencode.mjs +73 -10
  130. package/src/adapters/process.mjs +19 -15
  131. package/src/adapters/subagents.mjs +159 -0
  132. package/src/asking.mjs +8 -2
  133. package/src/auth-probe.mjs +47 -11
  134. package/src/bridge/devices.mjs +2 -2
  135. package/src/bridge/handoff.mjs +2 -2
  136. package/src/bridge/host.mjs +2 -2
  137. package/src/bridge/network.mjs +2 -2
  138. package/src/bridge/policy.mjs +3 -3
  139. package/src/bridge/qr.mjs +2 -2
  140. package/src/bridge/server.mjs +3 -3
  141. package/src/builtin-updates.mjs +87 -0
  142. package/src/capabilities.mjs +5 -5
  143. package/src/chats.mjs +51 -2
  144. package/src/checkpoint.mjs +67 -9
  145. package/src/choices.mjs +2 -2
  146. package/src/cli-args.mjs +2 -2
  147. package/src/cold.mjs +2 -2
  148. package/src/commands.mjs +2 -2
  149. package/src/config.mjs +2 -2
  150. package/src/conversation-context.mjs +2 -2
  151. package/src/credentials.mjs +80 -18
  152. package/src/dataset.mjs +2 -2
  153. package/src/directives.mjs +2 -2
  154. package/src/distiller.mjs +2 -2
  155. package/src/embeddings.mjs +2 -2
  156. package/src/enlaces.mjs +2 -2
  157. package/src/environment.mjs +147 -0
  158. package/src/event-store.mjs +2 -2
  159. package/src/exam.mjs +2 -2
  160. package/src/extensions.mjs +2 -2
  161. package/src/eyecat-watch.mjs +2 -2
  162. package/src/eyecat.mjs +2 -2
  163. package/src/file-ops.mjs +2 -2
  164. package/src/files.mjs +2 -2
  165. package/src/github.mjs +2 -2
  166. package/src/heartbeat.mjs +2 -2
  167. package/src/history.mjs +76 -0
  168. package/src/i18n.mjs +32 -3
  169. package/src/image-studio.mjs +2 -2
  170. package/src/install-metrics.mjs +109 -0
  171. package/src/json-file.mjs +2 -2
  172. package/src/launch.mjs +2 -2
  173. package/src/lease.mjs +15 -4
  174. package/src/lobby-work.mjs +11 -4
  175. package/src/local-ai.mjs +12 -4
  176. package/src/looks.mjs +19 -7
  177. package/src/market-check.mjs +165 -0
  178. package/src/market-key.mjs +10 -2
  179. package/src/market-license.mjs +104 -0
  180. package/src/market-remote.mjs +71 -13
  181. package/src/maturity.mjs +2 -2
  182. package/src/mcp/connect.mjs +2 -2
  183. package/src/mcp/github-server.mjs +2 -2
  184. package/src/mcp/image-server.mjs +2 -2
  185. package/src/mcp/memory-server.mjs +2 -2
  186. package/src/mcp/proxy.mjs +16 -5
  187. package/src/mcp/smtp-server.mjs +2 -2
  188. package/src/memory-dashboard.mjs +2 -2
  189. package/src/memory-tools.mjs +2 -2
  190. package/src/memory.mjs +2 -2
  191. package/src/models.mjs +115 -12
  192. package/src/module-scope.mjs +2 -2
  193. package/src/modules/ahp.mjs +2 -2
  194. package/src/modules/ash-policy.mjs +2 -2
  195. package/src/modules/ash.mjs +2 -2
  196. package/src/modules/bishop-exam.mjs +2 -2
  197. package/src/modules/bishop-plan.mjs +2 -2
  198. package/src/modules/bishop.mjs +9 -3
  199. package/src/modules/choices.mjs +2 -2
  200. package/src/modules/correo.mjs +2 -2
  201. package/src/modules/enlaces.mjs +2 -2
  202. package/src/modules/git-pulse.mjs +2 -2
  203. package/src/modules/github.mjs +2 -2
  204. package/src/modules/helpers.mjs +2 -2
  205. package/src/modules/image-studio.mjs +2 -2
  206. package/src/modules/index.mjs +92 -5
  207. package/src/modules/intents-calibration.mjs +2 -2
  208. package/src/modules/intents-desk.mjs +4 -3
  209. package/src/modules/intents-observe.mjs +2 -2
  210. package/src/modules/intents-policy.mjs +2 -2
  211. package/src/modules/intents-try.mjs +2 -2
  212. package/src/modules/intents.mjs +2 -2
  213. package/src/modules/local-models.mjs +41 -10
  214. package/src/modules/mcp-connect.mjs +2 -2
  215. package/src/modules/notes.mjs +281 -0
  216. package/src/modules/ollama.mjs +48 -13
  217. package/src/modules/playwright.mjs +16 -5
  218. package/src/modules/reminders.mjs +664 -0
  219. package/src/modules/ripley.mjs +3 -3
  220. package/src/modules/runs.mjs +2 -2
  221. package/src/modules/sdk.mjs +57 -9
  222. package/src/modules/updates.mjs +2 -2
  223. package/src/mother.mjs +13 -3
  224. package/src/npm-launch.mjs +2 -2
  225. package/src/ollama.mjs +8 -6
  226. package/src/opencode-health.mjs +83 -0
  227. package/src/outbound.mjs +35 -3
  228. package/src/override.mjs +27 -22
  229. package/src/ports.mjs +2 -2
  230. package/src/prices.mjs +2 -2
  231. package/src/privacy.mjs +2 -2
  232. package/src/quota-monitor.mjs +2 -2
  233. package/src/quota-sources.mjs +2 -2
  234. package/src/request-guard.mjs +2 -2
  235. package/src/review-ask.mjs +4 -3
  236. package/src/room/archivist.mjs +2 -2
  237. package/src/room/attachments.mjs +2 -2
  238. package/src/room/budget.mjs +2 -2
  239. package/src/room/context.mjs +2 -2
  240. package/src/room/control.mjs +2 -2
  241. package/src/room/copilot.mjs +2 -2
  242. package/src/room/economy.mjs +2 -2
  243. package/src/room/escalation.mjs +2 -2
  244. package/src/room/ghost.mjs +2 -2
  245. package/src/room/guard.mjs +6 -4
  246. package/src/room/prompt.mjs +3 -3
  247. package/src/room/returns.mjs +2 -2
  248. package/src/room/runs.mjs +6 -4
  249. package/src/room/vectors.mjs +2 -2
  250. package/src/room.mjs +144 -36
  251. package/src/router.mjs +2 -2
  252. package/src/runs.mjs +2 -2
  253. package/src/runtime-detection.mjs +36 -6
  254. package/src/salas.mjs +31 -6
  255. package/src/sentinel-errors.mjs +17 -7
  256. package/src/server-sentinel.mjs +2 -2
  257. package/src/server.mjs +980 -139
  258. package/src/setup-trouble.mjs +33 -0
  259. package/src/setup.mjs +4 -4
  260. package/src/smtp.mjs +2 -2
  261. package/src/telemetry.mjs +266 -0
  262. package/src/terms.mjs +43 -0
  263. package/src/tour.mjs +60 -7
  264. package/src/uninstall.mjs +225 -0
  265. package/src/updates.mjs +2 -2
  266. package/src/usage-sentinel.mjs +2 -2
  267. package/src/vault.mjs +2 -2
  268. package/src/verdict.mjs +13 -10
  269. package/src/whats-new.mjs +97 -3
  270. package/public/assets/abduction-cat-blink.png +0 -0
  271. package/public/assets/abduction-cat-control-left.png +0 -0
  272. package/public/assets/abduction-cat-control-right.png +0 -0
  273. package/public/assets/abduction-cat.png +0 -0
@@ -0,0 +1,85 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // «En marcha» (2026-10-30): what MADRE is doing, in one place, so a person never has to open a
4
+ // terminal to know it. A room says what runs in it now (Room#activity); this file reads what ended a
5
+ // moment ago from the end of each conversation's record, and puts a project's answer together.
6
+ import { chatLedger, listChats, tailOf } from './chats.mjs';
7
+
8
+ // A text cut to its first `max` characters, at a word when one is near, and saying it was cut.
9
+ export function clip(text, max) {
10
+ const whole = String(text ?? '').replace(/\s+/g, ' ').trim();
11
+ if (whole.length <= max) return whole;
12
+ const cut = whole.slice(0, max - 1);
13
+ const space = cut.lastIndexOf(' ');
14
+ return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,.;:]+$/, '')}…`;
15
+ }
16
+
17
+ // What ended in the last half hour counts as «a moment ago».
18
+ export const RECENT_MS = 30 * 60 * 1000;
19
+ // Enough of a record's end for half an hour of an ordinary conversation, and cheap to read often.
20
+ const RECENT_READ = 384 * 1024;
21
+ const RECENT_MAX = 10;
22
+ // The reminders due in the next day are what comes («Por venir»).
23
+ export const ACTIVITY_SOON_MS = 24 * 60 * 60 * 1000;
24
+
25
+ // The turns that ended since `since`, from the lines of one conversation's record, newest first:
26
+ // answered, failed or stopped, with what they were asked and how long they took.
27
+ export function recentFromLines(text, { since, chat = null, chatTitle = null } = {}) {
28
+ const asked = new Map(); // messageId → what the person (or the plan) asked, and whether it closes a plan
29
+ const started = new Map(); // messageId → when its turn started
30
+ const ended = [];
31
+ for (const line of String(text ?? '').split('\n')) {
32
+ if (!line) continue;
33
+ const kind = line.match(/"type":"([a-z.]+)"/)?.[1];
34
+ if (!['message.created', 'agent.started', 'agent.completed', 'message.failed'].includes(kind)) continue;
35
+ let event;
36
+ try { event = JSON.parse(line); } catch { continue; }
37
+ const payload = event?.payload ?? {};
38
+ const at = Date.parse(event.timestamp ?? '');
39
+ // What started a turn: the person's message, or a plan's step (written by the agent that made
40
+ // the plan, to the one doing the step). Its last step goes from that agent to itself: the
41
+ // closing, whose words are MADRE's instruction and are not shown.
42
+ if (kind === 'message.created') { if (payload.messageId) asked.set(payload.messageId, { text: clip(payload.text, 200), closing: Boolean(payload.planId) && payload.sender === payload.target }); continue; }
43
+ if (kind === 'agent.started') { started.set(payload.messageId, at); continue; }
44
+ if (!Number.isFinite(at) || at < since) continue;
45
+ const agent = kind === 'agent.completed' ? payload.agent : payload.target;
46
+ // A failure MADRE caused by closing is no failure of the turn, and one with no agent is no turn.
47
+ if (!agent || payload.closing) continue;
48
+ if (kind === 'message.failed' && !started.has(payload.messageId)) continue;
49
+ const from = started.get(payload.messageId);
50
+ ended.push({
51
+ state: kind === 'agent.completed' ? 'ok' : payload.stopped ? 'stopped' : 'failed',
52
+ messageId: payload.messageId ?? null,
53
+ agent,
54
+ planId: payload.planId ?? null,
55
+ at: event.timestamp,
56
+ tookMs: Number.isFinite(from) ? Math.max(0, at - from) : null,
57
+ error: kind === 'message.failed' && !payload.stopped ? String(payload.error ?? '').slice(0, 240) : null,
58
+ timeout: Boolean(payload.timeout),
59
+ chat,
60
+ chatTitle,
61
+ });
62
+ }
63
+ for (const one of ended) {
64
+ const said = asked.get(one.messageId);
65
+ one.text = said?.closing ? '' : said?.text ?? '';
66
+ if (said?.closing) one.closing = true;
67
+ }
68
+ return ended.reverse();
69
+ }
70
+
71
+ // What ended a moment ago across every conversation of a project, newest first.
72
+ export async function recentInProject(roomDir, { now = Date.now(), also = [] } = {}) {
73
+ const since = now - RECENT_MS;
74
+ const { chats } = await listChats(roomDir);
75
+ const out = [];
76
+ for (const chat of chats) {
77
+ const touched = Date.parse(chat.updatedAt ?? '');
78
+ if (!(touched >= since) && !also.includes(chat.id)) continue;
79
+ out.push(...recentFromLines(await tailOf(chatLedger(roomDir, chat.id), RECENT_READ), { since, chat: chat.id, chatTitle: chat.title ?? null }));
80
+ }
81
+ return out.sort((a, b) => String(b.at).localeCompare(String(a.at))).slice(0, RECENT_MAX);
82
+ }
83
+
84
+ // How many things a project's answer has running: the key's number.
85
+ export const runningCount = (answer) => (answer?.now ?? []).filter((one) => one.kind !== 'turn' || !one.planId).length;
@@ -1,15 +1,22 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ import { ENV_SECRETS } from '../checkpoint.mjs';
3
4
  import { runReadonlyProcess } from './process.mjs';
5
+ import { claudeSubagents, jsonLines } from './subagents.mjs';
4
6
 
5
7
  // dontAsk denies any tool use that is not pre-approved, so under a lease the
6
8
  // Write/Edit tools exist but only paths inside the lease directory are
7
9
  // allowed; everything else in the project is refused without a prompt.
10
+ // Claude's own subagents (the Agent tool), from #1 to #3 (2026-10-29): a subagent gets exactly the
11
+ // tools of this run and answers to the same allow and deny rules (verified with the real CLI: in
12
+ // #1 the subagent read and could not write). In #4 only the agent itself works.
13
+ export const claudeMaySpawn = (lease = null) => !lease?.airlock;
8
14
  export function claudeTools({ lease = null, scopes = null } = {}) {
9
15
  const tools = ['Read', 'Glob', 'Grep'];
10
16
  if (lease) tools.push('Write', 'Edit');
11
17
  if (lease?.airlock) tools.push('Bash'); // AIRLOCK (#4): commands, git, deploy CLIs
12
18
  if (scopes?.web) tools.push('WebFetch', 'WebSearch');
19
+ if (claudeMaySpawn(lease)) tools.push('Agent');
13
20
  return tools;
14
21
  }
15
22
 
@@ -43,6 +50,7 @@ export function buildClaudeArgs({ prompt, model = null, effort = null, attachmen
43
50
  ...(lease ? leaseRoots(lease).flatMap((root) => [`Write(//${root}/**)`, `Edit(//${root}/**)`]) : []),
44
51
  ...(lease?.airlock ? ['Bash'] : []),
45
52
  ...(scopes?.web ? ['WebFetch', 'WebSearch'] : []),
53
+ ...(claudeMaySpawn(lease) ? ['Agent'] : []),
46
54
  ...mcpTools,
47
55
  ];
48
56
  // Only MADRE's own MCP servers ever reach Claude here; --strict-mcp-config
@@ -55,12 +63,14 @@ export function buildClaudeArgs({ prompt, model = null, effort = null, attachmen
55
63
  ...(effort ? ['--effort', effort] : []),
56
64
  // Attachments live outside the project; Read needs the folder allowed.
57
65
  ...(attachmentsDir ? ['--add-dir', attachmentsDir] : []),
58
- '--output-format', 'json',
66
+ // One event per line (2026-10-29): the answer as it is written, and what each subagent does
67
+ // while it does it (src/adapters/subagents.mjs). --verbose is what -p asks for to stream.
68
+ '--output-format', 'stream-json', '--verbose',
59
69
  '--permission-mode', 'dontAsk',
60
70
  '--tools', tools.join(','),
61
71
  ...(lease || scopes?.web || anyMcp ? ['--allowedTools', allowed.join(',')] : []),
62
72
  // CONTROL: the whole project is writable except MADRE's forbidden zones.
63
- ...(lease?.control || lease?.create ? ['--disallowedTools', ['.git/**', '.pulse/**', '.madre/**', '.env', '.env.*', '**/.env', '**/.env.*', '.claude/settings.local.json'].flatMap((glob) => leaseRoots(lease).flatMap((root) => [`Write(//${root}/${glob})`, `Edit(//${root}/${glob})`])).join(',')] : []),
73
+ ...(lease?.control || lease?.create ? ['--disallowedTools', ['.git/**', '.pulse/**', '.madre/**', ...ENV_SECRETS.flatMap((name) => [name, `**/${name}`]), '.claude/settings.local.json'].flatMap((glob) => leaseRoots(lease).flatMap((root) => [`Write(//${root}/${glob})`, `Edit(//${root}/${glob})`])).join(',')] : []),
64
74
  // --safe-mode disables every MCP server, ours included. With a MADRE server
65
75
  // attached we drop it and instead load no setting sources at all: no user
66
76
  // hooks, plugins or MCP servers, only the project's CLAUDE.md and ours.
@@ -76,41 +86,57 @@ export function buildClaudeArgs({ prompt, model = null, effort = null, attachmen
76
86
  ];
77
87
  }
78
88
 
79
- export function parseClaudeOutput(output) {
80
- try {
81
- const result = JSON.parse(output.trim());
82
- if (result.is_error) {
83
- return {
84
- text: '',
85
- usage: null,
86
- error: typeof result.result === 'string' ? result.result : 'Claude returned an error.',
87
- };
88
- }
89
- const tokens = result.usage;
90
- const usage = tokens
91
- ? {
92
- inputTokens: tokens.input_tokens ?? 0,
93
- cacheCreationInputTokens: tokens.cache_creation_input_tokens ?? 0,
94
- cachedInputTokens: tokens.cache_read_input_tokens ?? 0,
95
- outputTokens: tokens.output_tokens ?? 0,
96
- reasoningTokens: 0,
97
- totalTokens: (tokens.input_tokens ?? 0)
98
- + (tokens.cache_creation_input_tokens ?? 0)
99
- + (tokens.cache_read_input_tokens ?? 0)
100
- + (tokens.output_tokens ?? 0),
101
- costUsd: result.total_cost_usd ?? null,
102
- source: 'claude-json',
103
- }
104
- : null;
105
- return { text: typeof result.result === 'string' ? result.result.trim() : '', usage };
106
- } catch {
107
- return { text: '', usage: null };
89
+ // What Claude answered: one JSON object (the old --output-format json, still read) or its stream.
90
+ // A turn whose subagents ran in the background ends twice — a first answer while they work, and
91
+ // the last one once they are done (seen with Claude 2.1.267) — so the text is the last answer's,
92
+ // the cost is the last one's (Claude counts it whole), and the tokens are every answer's, summed.
93
+ export function parseClaudeOutput(output, { root = null } = {}) {
94
+ const events = jsonLines(output);
95
+ const results = events.filter((event) => event?.type === 'result');
96
+ if (!results.length) {
97
+ // The old format: the whole output is the one result.
98
+ try { const single = JSON.parse(String(output).trim()); if (single && typeof single === 'object' && !Array.isArray(single) && single.type !== 'assistant' && single.type !== 'system') results.push(single); } catch { /* nothing to read */ }
108
99
  }
100
+ const subagents = claudeSubagents(events, { root });
101
+ const last = results.at(-1);
102
+ if (!last) return { text: '', usage: null, ...(subagents.length ? { subagents } : {}) };
103
+ if (last.is_error) {
104
+ return {
105
+ text: '',
106
+ usage: null,
107
+ error: typeof last.result === 'string' ? last.result : 'Claude returned an error.',
108
+ };
109
+ }
110
+ const sum = (key) => results.reduce((total, one) => total + (one.usage?.[key] ?? 0), 0);
111
+ const usage = results.some((one) => one.usage)
112
+ ? {
113
+ inputTokens: sum('input_tokens'),
114
+ cacheCreationInputTokens: sum('cache_creation_input_tokens'),
115
+ cachedInputTokens: sum('cache_read_input_tokens'),
116
+ outputTokens: sum('output_tokens'),
117
+ reasoningTokens: 0,
118
+ totalTokens: sum('input_tokens') + sum('cache_creation_input_tokens') + sum('cache_read_input_tokens') + sum('output_tokens'),
119
+ costUsd: last.total_cost_usd ?? null,
120
+ source: 'claude-json',
121
+ }
122
+ : null;
123
+ return { text: typeof last.result === 'string' ? last.result.trim() : '', usage, ...(subagents.length ? { subagents } : {}) };
124
+ }
125
+
126
+ // While it runs: what the agent itself has written so far, and its subagents.
127
+ export function claudeProgress(output, { root = null } = {}) {
128
+ const events = jsonLines(output);
129
+ let chars = 0;
130
+ for (const event of events) {
131
+ if (event?.type !== 'assistant' || event.parent_tool_use_id) continue;
132
+ for (const part of event.message?.content ?? []) if (part?.type === 'text') chars += String(part.text ?? '').length;
133
+ }
134
+ return { chars, subagents: claudeSubagents(events, { root }) };
109
135
  }
110
136
 
111
137
  export function invokeClaude({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, effort = null, attachments = [], lease = null, scopes = null, imageStudio = null, memoryServer = null, mcpServers = [], onProgress = null }) {
112
138
  return runReadonlyProcess({
113
- onProgress: onProgress ? (out) => onProgress({ chars: (() => { try { return String(JSON.parse(out)?.result ?? '').length; } catch { return 0; } })() }) : null,
139
+ onProgress: onProgress ? (out) => onProgress(claudeProgress(out, { root: projectRoot })) : null,
114
140
  executable,
115
141
  args: buildClaudeArgs({ prompt, model, effort, attachmentsDir: attachments[0]?.dir ?? null, lease, scopes, imageStudio, memoryServer, mcpServers }),
116
142
  cwd: projectRoot,
@@ -118,6 +144,6 @@ export function invokeClaude({ executable, projectRoot, prompt, timeoutMs = 1200
118
144
  timeoutMs,
119
145
  signal,
120
146
  label: 'Claude',
121
- parse: parseClaudeOutput,
147
+ parse: (out) => parseClaudeOutput(out, { root: projectRoot }),
122
148
  });
123
149
  }
@@ -1,9 +1,10 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  import { readdir } from 'node:fs/promises';
4
4
  import { homedir } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
  import { runReadonlyProcess } from './process.mjs';
7
+ import { codexSubagents, jsonLines } from './subagents.mjs';
7
8
 
8
9
  // With a lease, the working root is the lease directory (the only writable
9
10
  // place) and the sandbox allows workspace writes; the project stays readable.
@@ -49,6 +50,11 @@ export function buildCodexArgs({ projectRoot, prompt, model = null, effort = nul
49
50
  // Image generation is a Codex feature; the human's scope decides per turn.
50
51
  ...(effort ? ['-c', `model_reasoning_effort=${tomlValue(effort)}`] : []),
51
52
  ...(lease && (scopes?.imageGen === false || lease.scopes?.imageGen === false) ? ['-c', 'features.image_generation=false'] : []),
53
+ // Codex's own subagents (on by default since 0.16x) inherit its sandbox, so from #1 to #3 they
54
+ // stay inside it. In #4 the sandbox is off and only the agent itself works (2026-10-29). With
55
+ // Codex 0.161 no feature switch takes `spawn_agent` away; a limit of one thread — the agent's
56
+ // own — does: «collab spawn failed: agent thread limit reached» (verified with the real CLI).
57
+ ...(lease?.airlock ? ['-c', 'features.multi_agent_v2.max_concurrent_threads_per_session=1'] : []),
52
58
  'exec',
53
59
  // Codex refuses to run outside a git repository it has not been told to trust, and a new
54
60
  // project is often a bare folder. The sandbox above is MADRE's to decide, not this check's.
@@ -106,7 +112,9 @@ export function parseCodexOutput(output) {
106
112
  // Ignore CLI diagnostics that are not JSON events.
107
113
  }
108
114
  }
109
- return { text: text.trim(), usage, ...(threadId ? { threadId } : {}), ...(error ? { error } : {}) };
115
+ // Whether it worked with its own subagents (src/adapters/subagents.mjs): Codex says no more.
116
+ const subagents = codexSubagents(jsonLines(output));
117
+ return { text: text.trim(), usage, ...(threadId ? { threadId } : {}), ...(error ? { error } : {}), ...(subagents.length ? { subagents } : {}) };
110
118
  }
111
119
 
112
120
  // Where Codex keeps the images its own tool made in a thread: ~/.codex/generated_images/<thread>.
@@ -119,11 +127,16 @@ export async function codexGeneratedImages(threadId, { home = process.env.CODEX_
119
127
  return names.filter((name) => /\.(png|jpe?g|webp|gif)$/i.test(name)).sort().map((name) => join(dir, name));
120
128
  }
121
129
 
130
+ // MADRE runs Codex with --ephemeral (it keeps no conversation of its own in ~/.codex), and a
131
+ // subagent asked to inherit the conversation finds nothing to inherit: «collab spawn failed … no
132
+ // rollout found». Codex then tries again without it, a step wasted every time (seen with 0.161).
133
+ // Said up front, the first subagent starts.
134
+ export const CODEX_SUBAGENT_NOTE = 'If you start a subagent: this run keeps no conversation history, so never ask the subagent to inherit or fork this conversation. Give it the whole task in its own message.';
122
135
  export async function invokeCodex({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, effort = null, attachments = [], lease = null, scopes = null, memoryServer = null, mcpServers = [], onProgress = null }) {
123
136
  const result = await runReadonlyProcess({
124
- onProgress: onProgress ? (out) => onProgress({ chars: parseCodexOutput(out).text.length }) : null,
137
+ onProgress: onProgress ? (out) => { const said = parseCodexOutput(out); onProgress({ chars: said.text.length, subagents: said.subagents ?? [] }); } : null,
125
138
  executable,
126
- args: buildCodexArgs({ projectRoot, prompt, model, effort, attachments, lease, scopes, memoryServer, mcpServers }),
139
+ args: buildCodexArgs({ projectRoot, prompt: lease?.airlock ? prompt : `${prompt}\n\n${CODEX_SUBAGENT_NOTE}`, model, effort, attachments, lease, scopes, memoryServer, mcpServers }),
127
140
  cwd: lease ? lease.outDir : projectRoot,
128
141
  env: process.env,
129
142
  timeoutMs,
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // Cursor's agent CLI (`cursor-agent`, 2026.05), added 2026-10-17. It reads only: every turn runs in
4
4
  // Cursor's own ask mode (`--mode ask`, «Q&A style, read-only») under a configuration made for the
5
5
  // turn and removed after it (CURSOR_CONFIG_DIR), which denies every command and every write and
@@ -10,10 +10,21 @@
10
10
  // Tried against the real CLI on 2026-10-17: it read and answered; asked to create a file and to run
11
11
  // `touch`, it wrote nothing and said it was in Ask mode. `--sandbox enabled` was dropped: on a Mac
12
12
  // where Cursor's sandbox is not available the run ends at once («Sandbox mode is enabled but not
13
- // available on this system»). Writing (#2 and up) waits for its own trial (capabilities.mjs).
13
+ // available on this system»).
14
+ //
15
+ // From 2026-10-21 it works at every mode, as the other agents do. #2 and #3 run in Cursor's agent
16
+ // mode with `--force` (in print mode, changes are only proposed without it), under a configuration
17
+ // that allows writing and denies every command and the places nobody writes; #4 allows commands
18
+ // too. Cursor's own rules are the first wall, not the only one: the room locks .env, .git and its
19
+ // own folders read-only for the turn and puts back whatever reaches them, and at #2 everything that
20
+ // existed before (room/control.mjs) — so a rule Cursor read differently could not cost a file. A
21
+ // command cannot be put back; that is why commands are denied below #4. Not yet run against a paid
22
+ // Cursor account (the author's is free and spent): built on Cursor's documented permissions and
23
+ // held by the room's own guard.
14
24
  import { mkdtemp, rm, writeFile } from 'node:fs/promises';
15
25
  import { tmpdir } from 'node:os';
16
26
  import { join } from 'node:path';
27
+ import { ENV_SECRETS } from '../checkpoint.mjs';
17
28
  import { runReadonlyProcess } from './process.mjs';
18
29
 
19
30
  // What the turn's own configuration allows: reading, and nothing else.
@@ -24,11 +35,36 @@ export const READONLY_CONFIG = {
24
35
  sandbox: { mode: 'disabled' },
25
36
  };
26
37
 
27
- export function buildCursorArgs({ projectRoot, prompt, model = process.env.PULSE_CURSOR_MODEL || null }) {
38
+ // The places no turn writes, whatever its mode (as OpenCode's FORBIDDEN_GLOBS). `.pulse` is left to
39
+ // the room when the turn has a draft folder there, because Cursor's denials win over its allowances
40
+ // and would shut that folder too; the room locks every other `.pulse` path itself.
41
+ // Every secret-bearing .env by name: its templates (.env.example…) are written and shared (NUE-21).
42
+ const NEVER_WRITTEN = ['.git/**', '.madre/**', ...ENV_SECRETS.flatMap((name) => [name, `**/${name}`]), '.claude/settings.local.json'];
43
+ // One configuration per turn, from the lease the room gave it: none, read only.
44
+ export function cursorConfigFor(lease = null) {
45
+ if (!lease) return READONLY_CONFIG;
46
+ const everywhere = Boolean(lease.create || lease.control || lease.airlock);
47
+ const dir = String(lease.relativeDir ?? '.').replace(/^\.\/+/, '').replace(/\/+$/, '');
48
+ const writes = everywhere || !dir || dir === '.' ? ['Write(**)'] : [`Write(${dir}/**)`];
49
+ const never = [...NEVER_WRITTEN, ...(lease.scratchDir ? [] : ['.pulse/**'])].map((glob) => `Write(${glob})`);
50
+ return {
51
+ version: 1,
52
+ permissions: {
53
+ allow: ['Read(**)', ...writes, ...(lease.airlock ? ['Shell(*)'] : [])],
54
+ deny: [...(lease.airlock ? [] : ['Shell(*)']), ...never],
55
+ },
56
+ approvalMode: 'allowlist',
57
+ sandbox: { mode: 'disabled' },
58
+ };
59
+ }
60
+
61
+ export function buildCursorArgs({ projectRoot, prompt, model = process.env.PULSE_CURSOR_MODEL || null, lease = null }) {
28
62
  return [
29
63
  '--print',
30
64
  '--output-format', 'stream-json',
31
- '--mode', 'ask',
65
+ // Reading: Cursor's own ask mode. Writing: its agent mode, with the changes applied (`--force`)
66
+ // under the turn's configuration above.
67
+ ...(lease ? ['--force'] : ['--mode', 'ask']),
32
68
  // A headless run cannot answer the «trust this folder?» question; the project is the human's.
33
69
  '--trust',
34
70
  '--workspace', projectRoot,
@@ -74,14 +110,21 @@ export function parseCursorOutput(output) {
74
110
  return { text, usage, ...(error ? { error } : {}) };
75
111
  }
76
112
 
77
- export async function invokeCursor({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, onProgress = null }) {
113
+ // A free plan answers only with Auto (2026-10-21): any named model is refused with «Named models
114
+ // unavailable · Free plans can only use Auto». The turn is asked again with Auto, and from then on
115
+ // this room offers Auto alone (models.mjs) — nothing says the plan before a turn does.
116
+ export const ONLY_AUTO = /Free plans can only use Auto|Named models unavailable/i;
117
+ let onlyAuto = false;
118
+ export const cursorOnlyAuto = () => onlyAuto;
119
+
120
+ export async function invokeCursor({ executable, projectRoot, prompt, timeoutMs = 120000, signal, model = null, lease = null, onProgress = null }) {
78
121
  const configDir = await mkdtemp(join(tmpdir(), 'madre-cursor-'));
79
122
  try {
80
- await writeFile(join(configDir, 'cli-config.json'), `${JSON.stringify(READONLY_CONFIG, null, 2)}\n`);
81
- return await runReadonlyProcess({
123
+ await writeFile(join(configDir, 'cli-config.json'), `${JSON.stringify(cursorConfigFor(lease), null, 2)}\n`);
124
+ const run = (named) => runReadonlyProcess({
82
125
  onProgress: onProgress ? (out) => onProgress({ chars: out.length }) : null,
83
126
  executable,
84
- args: buildCursorArgs({ projectRoot, prompt, ...(model ? { model } : {}) }),
127
+ args: buildCursorArgs({ projectRoot, prompt, lease, ...(named ? { model: named } : {}) }),
85
128
  cwd: projectRoot,
86
129
  env: cursorEnvironment(process.env, { configDir }),
87
130
  timeoutMs,
@@ -89,6 +132,14 @@ export async function invokeCursor({ executable, projectRoot, prompt, timeoutMs
89
132
  label: 'Cursor',
90
133
  parse: parseCursorOutput,
91
134
  });
135
+ const named = onlyAuto ? null : model;
136
+ try {
137
+ return await run(named);
138
+ } catch (error) {
139
+ if (!named || named === 'auto' || !ONLY_AUTO.test(String(error?.message ?? ''))) throw error;
140
+ onlyAuto = true;
141
+ return await run(null);
142
+ }
92
143
  } finally {
93
144
  // The chats and caches the CLI wrote there go with it: a turn keeps no session of its own.
94
145
  await rm(configDir, { recursive: true, force: true, maxRetries: 6, retryDelay: 60 }).catch(() => {});
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  import { priceTokens, PRICES_CHECKED } from '../prices.mjs';
4
4
  import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
5
5
  import { t } from '../i18n.mjs';
@@ -40,7 +40,9 @@ export const geminiCredentialFiles = ['oauth_creds.json', 'google_accounts.json'
40
40
  // block every write regardless of policy, so a lease uses approval "default":
41
41
  // headless Gemini cannot prompt, so anything the policy does not allow fails.
42
42
  export function geminiLeasePolicy(outDir, { control = false, create = false, airlock = false, alsoAt = null } = {}) {
43
- const quote = (path) => path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
43
+ // An apostrophe («Ana's site») would end the TOML literal string the pattern is written in: the
44
+ // regular expression says it as \x27, the same character, so the policy still reads.
45
+ const quote = (path) => path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/'/g, '\\x27');
44
46
  // Every spelling of the same directory. When the path MADRE was given goes through a symlink,
45
47
  // an agent that resolves before writing asks for a path that does not start with the one these
46
48
  // rules were built from: the allow rule misses and the write dies in silence. Both go in the
@@ -322,7 +324,9 @@ export async function invokeGemini({
322
324
  mcpServers = [],
323
325
  idleTimeoutMs = Number(process.env.PULSE_GEMINI_IDLE_MS ?? 90000),
324
326
  retries = Number(process.env.PULSE_GEMINI_RETRIES ?? 1),
325
- fallbackModel = process.env.PULSE_GEMINI_FALLBACK_MODEL ?? 'gemini-2.5-flash',
327
+ // The spare model a 503 or 429 tries once (2026-10-21): 2.5 Flash is no longer given to new
328
+ // accounts, so it failed again and its refusal hid why the chosen model had failed. Empty: no spare.
329
+ fallbackModel = process.env.PULSE_GEMINI_FALLBACK_MODEL ?? 'gemini-3-flash-preview',
326
330
  failFastMs = 15000,
327
331
  run = runReadonlyProcess,
328
332
  }) {
@@ -334,6 +338,7 @@ export async function invokeGemini({
334
338
  let attempt = 0;
335
339
  let currentModel = model;
336
340
  let switched = false;
341
+ let firstTrouble = null;
337
342
  for (;;) {
338
343
  attempt += 1;
339
344
  // The CLI retries a 503 or 429 with backoff for minutes while stderr
@@ -364,6 +369,13 @@ export async function invokeGemini({
364
369
  } catch (error) {
365
370
  const produced = parseGeminiOutput(error.partialOutput ?? '').text;
366
371
  const diagnosis = error.diagnosis ?? diagnoseGeminiStderr(error.partialStderr ?? error.stderr ?? '');
372
+ // The spare failed too, for whatever reason (a model this account is not given, say): what
373
+ // the person needs to read is why the model they chose failed, not why the spare did.
374
+ if (switched && firstTrouble && !produced && !signal?.aborted) {
375
+ error.message = `${firstTrouble.message} ${firstTrouble.hint} (also tried ${fallbackModel})`;
376
+ error.code = firstTrouble.code;
377
+ throw error;
378
+ }
367
379
  if (diagnosis?.code === 'AUTH' || diagnosis?.code === 'INELIGIBLE' || diagnosis?.code === 'CREDITS_DEPLETED') {
368
380
  error.message = `${diagnosis.message} ${diagnosis.hint}`;
369
381
  error.code = diagnosis.code;
@@ -373,6 +385,7 @@ export async function invokeGemini({
373
385
  // try on a lighter, explicit model before giving up.
374
386
  if ((diagnosis?.code === 'UNAVAILABLE' || diagnosis?.code === 'RATE_LIMITED') && !produced && !signal?.aborted && fallbackModel && !switched && currentModel !== fallbackModel) {
375
387
  switched = true;
388
+ firstTrouble = diagnosis;
376
389
  currentModel = fallbackModel;
377
390
  continue;
378
391
  }
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // @madre: the room's own intelligence. A local model (Ollama) that answers
4
4
  // from what the room remembers: the whole archive, not only the recent window,
5
5
  // plus the files the human points at. It never writes, never delegates, never
@@ -249,25 +249,40 @@ const COMPARE = `You compare the answers a round of agents gave to one question.
249
249
 
250
250
  const NO_USAGE = { inputTokens: 0, outputTokens: 0, cachedInputTokens: 0, reasoningTokens: 0, totalTokens: 0, costUsd: 0, source: 'madre', local: true };
251
251
 
252
- // What the whole archive says about this request: notes first, then exact quotes.
252
+ // What the whole archive says about this request: notes first, then exact quotes. The question
253
+ // itself is already in the ledger when @madre is asked, and it is not a memory: found as the only
254
+ // «quote», a 7B model took it for a source and cited it under a made-up answer (2026-10-19).
255
+ const sameWords = (a, b) => String(a ?? '').replace(/\s+/g, ' ').trim().slice(0, 200).toLowerCase() === String(b ?? '').replace(/\s+/g, ' ').trim().slice(0, 200).toLowerCase();
253
256
  export async function gather(memory, text, { maxChars = 7000 } = {}) {
254
257
  if (!memory) return { notes: [], quotes: [], text: '' };
255
258
  const queryVector = await memory.embedQuery(text);
256
259
  const notes = memory.recallMemories(text, { limit: 12, maxChars: Math.floor(maxChars * 0.35), queryVector, fallback: false });
257
260
  const spent = notes.reduce((sum, note) => sum + note.text.length + 24, 0);
258
261
  const recall = memory.recall(text, { limit: 12, maxChars: maxChars - spent, excerptChars: 420, queryVector });
262
+ const quotes = recall.entries.filter((entry) => !sameWords(entry.excerpt, text));
259
263
  const lines = [
260
264
  ...notes.map((note) => `- [note · ${note.kind} · #${note.fromSequence}–#${note.throughSequence}] ${note.text}`),
261
- ...recall.entries.map((entry) => `[#${entry.sequence} · ${(entry.timestamp ?? '').slice(0, 16).replace('T', ' ')} · ${entry.role === 'command' ? entry.sender : `@${entry.sender}`}] ${entry.excerpt}`),
265
+ ...quotes.map((entry) => `[#${entry.sequence} · ${(entry.timestamp ?? '').slice(0, 16).replace('T', ' ')} · ${entry.role === 'command' ? entry.sender : `@${entry.sender}`}] ${entry.excerpt}`),
262
266
  ];
263
- return { notes, quotes: recall.entries, text: lines.join('\n') };
267
+ return { notes, quotes, text: lines.join('\n') };
268
+ }
269
+
270
+ // Nothing remembered and nothing said before: there is nothing to cite, so the model is not asked.
271
+ // Rule 3 told it to say so and stop; qwen2.5:7b described a store with a cart, payments, src/app.js
272
+ // and index.html in a project of two files (2026-10-19). The agents that can read the code are named.
273
+ export function nothingYet(text, { crew = [] } = {}) {
274
+ const others = crew.filter((id) => id !== MADRE_AGENT_ID).map((id) => `@${id}`);
275
+ return lang(text) === 'es'
276
+ ? `Todavía no hay nada sobre esto en la memoria de este proyecto: la sala nunca lo discutió. Yo respondo solo con lo que la sala recuerda y no leo el código${others.length ? `; para eso pregúntale a ${others.join(', ')}` : ''}.`
277
+ : `There is nothing about this in this project's memory yet: the room never discussed it. I answer only from what the room remembers and I do not read the code${others.length ? `; for that, ask ${others.join(', ')}` : ''}.`;
264
278
  }
265
279
 
266
280
  // The invoker the room calls like any adapter. `text` is the human's request; `prompt` the room's full briefing.
267
281
  export function madreInvoker({ memory, ollama, fetchImpl = globalThis.fetch }) {
268
- return async ({ prompt, text = '', timeoutMs = 180000, model = null, requester = 'you', crew = [], delegation = false, maxSteps = 4, round = null, bishop = null }) => {
282
+ // `signal` is the room's STOP (2026-10-20): it reaches Ollama, so a stopped @madre does not answer after all.
283
+ return async ({ prompt, text = '', timeoutMs = 180000, model = null, requester = 'you', crew = [], delegation = false, maxSteps = 4, round = null, bishop = null, signal = null }) => {
269
284
  const state = typeof ollama === 'function' ? ollama() : ollama;
270
- if (!state?.running || !state.chatModel) throw new Error('@madre left the project: Ollama is not running. Start Ollama, or open Local AI in Modules.');
285
+ if (!state?.running || !state.chatModel) throw new Error('@madre left the project: Ollama is not running. Start Ollama, or set up Local AI in Settings.');
271
286
  const question = text || prompt.match(/User message: ([\s\S]*)$/)?.[1] || prompt.slice(-2000);
272
287
  const local = localReply(question, { requester, crew, delegation, maxSteps, model: model ?? state.chatModel });
273
288
  if (local) return { text: local.text, usage: { ...NO_USAGE }, grounded: { notes: 0, quotes: 0 }, synthetic: local.kind, declined: local.kind === 'declined' ? 'action' : undefined };
@@ -281,15 +296,21 @@ export function madreInvoker({ memory, ollama, fetchImpl = globalThis.fetch }) {
281
296
  let comparison = '';
282
297
  if (round.answers.filter((answer) => answer.sequence).length >= 2) {
283
298
  const full = round.answers.filter((answer) => answer.sequence).map((answer) => `@${answer.agent} [#${answer.sequence}]: ${gist(answer.text, 700)}`).join('\n\n');
284
- const compared = await ollamaGenerate({ host: state.host, model: model ?? state.chatModel, system: COMPARE, prompt: `${asked ? `QUESTION: ${asked}\n\n` : ''}ANSWERS:\n${full}\n\n${es ? 'Responde en español.' : 'Answer in English.'}`, fetchImpl, timeoutMs, temperature: 0.1 }).catch(() => null);
299
+ const compared = await ollamaGenerate({ host: state.host, model: model ?? state.chatModel, system: COMPARE, prompt: `${asked ? `QUESTION: ${asked}\n\n` : ''}ANSWERS:\n${full}\n\n${es ? 'Responde en español.' : 'Answer in English.'}`, fetchImpl, timeoutMs, temperature: 0.1, signal }).catch(() => null);
300
+ signal?.throwIfAborted();
285
301
  if (compared) usage = { ...compared.usage, local: true };
286
302
  if (compared && comparisonHolds(compared.text, round)) comparison = plain(compared.text);
287
303
  }
288
304
  return { text: [head, bullets, comparison].filter(Boolean).join('\n\n'), usage, grounded: { notes: 0, quotes: round.answers.filter((answer) => answer.sequence).length } };
289
305
  }
290
306
  const archive = await gather(memory, question);
307
+ // A dictated form (yes or no, one word) is still the model's: a paragraph would break it.
308
+ if (!archive.notes.length && !archive.quotes.length && !bishop && !FORM.test(question) && !/<context>\n[\s\S]*?\S[\s\S]*?\n<\/context>/.test(prompt)) {
309
+ return { text: nothingYet(question, { crew }), usage: { ...NO_USAGE }, grounded: { notes: 0, quotes: 0 }, synthetic: 'nothing-yet' };
310
+ }
291
311
  const briefing = briefingFor({ prompt, text: question, archive: archive.text, bishop });
292
- const answer = await ollamaGenerate({ host: state.host, model: model ?? state.chatModel, system: bishop ? BISHOP_SYSTEM : SYSTEM, prompt: briefing, fetchImpl, timeoutMs, temperature: 0.1 });
312
+ signal?.throwIfAborted();
313
+ const answer = await ollamaGenerate({ host: state.host, model: model ?? state.chatModel, system: bishop ? BISHOP_SYSTEM : SYSTEM, prompt: briefing, fetchImpl, timeoutMs, temperature: 0.1, signal });
293
314
  return { text: answer.text, usage: { ...answer.usage, local: true }, grounded: { notes: archive.notes.length, quotes: archive.quotes.length } };
294
315
  };
295
316
  }