@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
package/src/server.mjs CHANGED
@@ -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 http from 'node:http';
4
4
  import { readFile, realpath, writeFile, mkdir, mkdtemp, cp, rename, access, rm, stat } from 'node:fs/promises';
5
5
  import { existsSync, openSync, rmSync } from 'node:fs';
@@ -24,11 +24,16 @@ import { ErrorSentinel } from './sentinel-errors.mjs';
24
24
  import { probeOllama, ollamaEmbedder, ollamaGenerate, ollamaInvoker, pullModel, ollamaVersions, ownOllamaServers } from './ollama.mjs';
25
25
  import { recallForTurn } from './modules/enlaces.mjs';
26
26
  import { hardwareOnce, MODEL_TIERS } from './modules/local-models.mjs';
27
- import { MODULES, moduleById, describeModules, findModuleRoute, toolsForTurn as modulesToolsForTurn, loadExternalModules, loadFailures, moduleFolders, moduleCommands, installModuleFile, installModuleText, verifyModuleText, moduleOrigin, removeExternalModule } from './modules/index.mjs';
27
+ import { browserAdvice, environmentOnce, openBrowser as openInBrowser } from './environment.mjs';
28
+ import { installTrouble, loginTrouble } from './setup-trouble.mjs';
29
+ import { MODULES, moduleById, describeModules, findModuleRoute, toolsForTurn as modulesToolsForTurn, loadExternalModules, loadFailures, moduleFolders, moduleCommands, installModuleFile, installModuleText, verifyModuleText, moduleOrigin, removeExternalModule, adoptBuiltinUpdates, packagedVersions } from './modules/index.mjs';
30
+ import { understandsSdk } from './modules/sdk.mjs';
31
+ import { updateBuiltins } from './builtin-updates.mjs';
28
32
  import { madreAgent, madreInvoker, MADRE_AGENT_ID, MADRE_ADAPTER } from './adapters/madre.mjs';
29
33
  import { exportDataset, forgetCorpus, keepCorpus, keptCorpus, pruneCorpora, readiness as datasetReadiness } from './dataset.mjs';
30
34
  import { OutboundLog, outboundView, DEFAULT_REPORT_URL } from './outbound.mjs';
31
- import { language as roomLanguage, setLanguage as setRoomLanguage, t } from './i18n.mjs';
35
+ import { Telemetry, telemetryOn } from './telemetry.mjs';
36
+ import { hostFacts, inRoomLanguage, language as roomLanguage, say, setLanguage as setRoomLanguage, t } from './i18n.mjs';
32
37
 
33
38
  // One per start of this process: a restart is a new one, a reload of the page is not.
34
39
  const BOOT_ID = `${process.pid}-${Date.now().toString(36)}`;
@@ -37,6 +42,9 @@ const PACKAGE = JSON.parse(await readFile(new URL('../package.json', import.meta
37
42
  // run from its source, where the repository's `.git` sits beside `src/`. What npm installs never
38
43
  // carries a `.git` (`files` in package.json), so there no setting and no variable opens it.
39
44
  const FROM_SOURCE = existsSync(new URL('../.git', import.meta.url));
45
+ // MADRE's own modules, read before any module of the person's is loaded: only these are named in the
46
+ // anonymous diagnostics (src/install-metrics.mjs); one the person wrote counts as «another».
47
+ const OWN_MODULE_IDS = new Set(MODULES.map((one) => one.id));
40
48
  // Where the author's token for the usage widget is kept: a vault name no module can take (module
41
49
  // ids are kebab-case, src/modules/sdk.mjs), so no module ever reads it.
42
50
  export const OWNER_VAULT = 'madre_owner';
@@ -72,19 +80,30 @@ import { applyKey, keyPlanFor, openCodeKeyProviders, readOpenCodeProviders, remo
72
80
  import { forgetSecret, readSecret, summary as vaultSummary, writeSecret } from './vault.mjs';
73
81
  import { applyConfigToEnv, loadConfig as readConfig, updateConfig } from './config.mjs';
74
82
  import { Privacy, normalizeTerms, privacySettings } from './privacy.mjs';
83
+ import { planView, removeMadre, uninstallPlan } from './uninstall.mjs';
75
84
  import { checkForUpdate, detectInstall, updateCommand, releaseUrl, applyCommand, fetchCommand } from './updates.mjs';
76
85
  import { bootWhatsNew, markSeen, newestNotes, notesFor, whatsNew } from './whats-new.mjs';
77
86
  import { answerAsk, tickAsk } from './review-ask.mjs';
78
- import { CHAPTERS, HINTS, TOUR_VERSION, cameBefore, changeTour, readTour, recoverProject, roomsWithoutProject } from './tour.mjs';
87
+ import { CHAPTERS, HINTS, NEWS_LEVEL, TOUR_VERSION, cameBefore, changeTour, readTour, recoverProject, roomsWithoutProject } from './tour.mjs';
79
88
 
80
89
  // Where a person reads the module contract, in the language the room is speaking.
81
90
  const SDK_PAGE = { es: 'https://madre.run/sdk/', en: 'https://madre.run/en/sdk/' };
82
91
  import { moduleUpdate } from './modules/updates.mjs';
83
- import { adoptStrays, chatIndex, chatLedger, createChat, deleteChat, isChatId, listChats, openChat as openChatIndex, projectFloor, renameChat, touchChat } from './chats.mjs';
92
+ import { ACTIVITY_SOON_MS, recentInProject } from './activity.mjs';
93
+ import { readReminders } from './modules/reminders.mjs';
94
+ import { adoptStrays, chatIndex, chatLedger, createChat, deleteChat, isChatId, listChats, openChat as openChatIndex, searchChats, projectFloor, renameChat, touchChat } from './chats.mjs';
84
95
  import { spawn } from 'node:child_process';
85
96
  import { cpus, freemem, loadavg, totalmem } from 'node:os';
86
- import { discoverModels, groupOpenCode, openCodeHidden, parseOpenCodeVerbose, providerLabel, OPENCODE_OWN } from './models.mjs';
97
+ import { discoverModels, groupOpenCode, openCodeHidden, parseCursorModels, parseGeminiModels, parseOpenCodeVerbose, providerLabel, OPENCODE_OWN } from './models.mjs';
98
+ import { cursorOnlyAuto } from './adapters/cursor.mjs';
99
+ // Cursor's own list of models (`cursor-agent --list-models`), kept a few minutes: reading it asks
100
+ // Cursor's servers.
101
+ const cursorModels = { at: 0, ids: [] };
102
+ // And Gemini's, from Google with the person's key.
103
+ const geminiModels = { at: 0, ids: [] };
87
104
  import { observable } from './modules/intents-observe.mjs';
105
+ import { summarizeHistory } from './history.mjs';
106
+ import { migrateOpenCodeHealth, noteOpenCodeTurn, openCodeHealth, suggestOpenCodeModel } from './opencode-health.mjs';
88
107
  import { normalizeMode, setImageModule } from './capabilities.mjs';
89
108
  import { resolveGeminiKey } from './image-studio.mjs';
90
109
  import { commandByName, listCommands, parseCommand } from './commands.mjs';
@@ -108,12 +127,16 @@ import { readHandoff, writeHandoff } from './bridge/handoff.mjs';
108
127
  import { changeHome, changeLooks, readHome, readLooks, changeRoomLook, roomLooks, WALLPAPER_BYTES, dropWallpaper, frameWallpaper, readWallpaper, saveWallpaper, wallpaperBytes } from './looks.mjs';
109
128
  import { localAiConfig, localAiFor, localAiPatch } from './local-ai.mjs';
110
129
  import { moduleOnIn, scopeView, settingsIn } from './module-scope.mjs';
130
+ import { COMMUNITY_LICENSES, COMMUNITY_SHELVES, MARKET_REPO, checkSubmission, submissionDraft, writeSubmission } from './market-check.mjs';
111
131
  import { forgetFromMarket, installFromMarket, installedFromMarket, keptCatalog, marketAnnounced, marketAnnouncements, marketNews, marketNewsSeen, refreshCatalog, updateFromMarket } from './market-remote.mjs';
112
132
  // Not moved project by project: the Coordinator is Home's, Git has no switch, and Local AI keeps
113
133
  // its own list of projects (local-ai.mjs).
114
134
  const NOT_BY_PROJECT = new Set(['bishop', 'git-pulse', 'ollama']);
115
- import { heartbeat } from './heartbeat.mjs';
116
- import { askRoom, associateProject, createProject, ensureSalasProject, forgetProject, isSalasRoom, knownRooms, listFolders, markProject, projectRoomId, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
135
+ import { heartbeat, installId } from './heartbeat.mjs';
136
+ import { PRESENCE_EVERY_MS, environmentGauges, noteLifecycle, sayPresent } from './install-metrics.mjs';
137
+ import { TERMS_LINKS, acceptTerms, cameFromBefore, readTerms } from './terms.mjs';
138
+ import { activateLicense, licensedIds, releaseLicense } from './market-license.mjs';
139
+ import { askRoom, associateProject, createProject, defaultProjectsFolder, ensureSalasProject, forgetProject, isSalasRoom, knownRooms, listFolders, markProject, projectRoomId, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
117
140
  import { parseWork, recentWork, WORK_SYSTEM, workPrompt } from './lobby-work.mjs';
118
141
  import { CHANNEL_HEADER, CORPUS_MAX, CORPUS_PER_HOUR, DELIVER_MAX, MAX_LIMIT as ENLACE_MAX_LIMIT, NO_SUCH_LINK, NOTICES as ENLACE_NOTICES, activeContracts, allowContract, askCorpus, askEnlace, askState, channelKey, countRecent, decideDelivery, deliverable, deliverNotes, deliversTo, linkTraffic, mayServe, noteCrossing, noticeEnlace, readInbox, readsFrom, recallContract, receiveDelivery, revokeContract, sameKey, servingRooms, signContract, trainContract } from './enlaces.mjs';
119
142
  import { readContinuity } from './modules/ahp.mjs';
@@ -176,10 +199,15 @@ async function body(request, { limit = BODY_LIMIT } = {}) {
176
199
  return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
177
200
  }
178
201
 
179
- export function openUrl(url) {
180
- const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
181
- const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
182
- execFile(command, args, () => {});
202
+ // Opens a page of MADRE in this computer's browser, the way this place allows (src/environment.mjs):
203
+ // in WSL, Windows' own browser; over SSH or on a Linux with no screen, none. When none opened, the
204
+ // terminal says where to open it, and over SSH the one command that brings it to the person's own
205
+ // computer (2026-10-28). Answers whether it opened.
206
+ export async function openUrl(url) {
207
+ const environment = await environmentOnce().catch(() => null);
208
+ const opened = await openInBrowser(url, environment);
209
+ if (!opened) console.log(`${browserAdvice(environment, url, { t }).map((line) => ` ${line}`).join('\n')}\n`);
210
+ return opened;
183
211
  }
184
212
 
185
213
  // PULSE_AGENT_TIMEOUT_MS applies to every agent; PULSE_<AGENT>_TIMEOUT_MS
@@ -246,10 +274,17 @@ export async function createPulseServer({
246
274
  // fake, and the key their catalog is signed with.
247
275
  marketFetch = globalThis.fetch,
248
276
  marketKey = null,
277
+ // The factory key that signs newer files of MADRE's own modules (src/builtin-updates.mjs); tests hand in theirs.
278
+ factoryKey = null,
279
+ // Where a paid module's license is checked (src/market-license.mjs); tests hand in their own.
280
+ licenseApi = null,
249
281
  // Ollama detection; tests hand in a fake probe. PULSE_OLLAMA=0 leaves Ollama alone entirely.
250
282
  ollamaProbe = process.env.PULSE_OLLAMA === '0' ? async () => ({ running: false, host: null, models: [], embedModel: null, chatModel: null, disabled: true }) : probeOllama,
251
283
  }) {
252
284
  const root = stateRoot ?? process.env.PULSE_HOME ?? join(homedir(), '.pulse');
285
+ // Whether this copy had its random identifier before this run: without one it is a new install
286
+ // (src/install-metrics.mjs, noteLifecycle).
287
+ const hadInstallId = existsSync(join(root, 'install-id'));
253
288
  // Read before this run creates anything: whether this person used MADRE before decides whether
254
289
  // an update has news to show them, or this is a first install with nothing to catch up on.
255
290
  const novelty = await bootWhatsNew({ root, version: PACKAGE.version }).catch(() => ({ returning: false }));
@@ -330,6 +365,44 @@ export async function createPulseServer({
330
365
  };
331
366
  }
332
367
  const releaseOpen = () => { try { rmSync(openMark, { force: true }); } catch { /* it was already gone */ } };
368
+ // Every other open project of this Mac, asked to close the way Home closes one, and waited for.
369
+ // Found by its mark (knownRooms), not by who started its process: a project opened from another
370
+ // project hangs from that one, not from Home, and closes all the same (2026-10-21). Only rooms
371
+ // are asked, over their own port; no process is signalled from here.
372
+ async function closeOtherRooms() {
373
+ const here = basename(roomDir);
374
+ const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
375
+ await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/close', { method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null)));
376
+ let left = others;
377
+ for (let tries = 0; tries < 60 && left.length; tries += 1) {
378
+ await new Promise((resolve) => setTimeout(resolve, 250));
379
+ const now = await knownRooms(root);
380
+ left = left.filter((one) => now.find((room) => room.id === one.id)?.open);
381
+ }
382
+ return { closed: others.length - left.length, stuck: left.map((one) => one.name) };
383
+ }
384
+ // RESTARTING MADRE (2026-10-28): this process goes and a new one takes its place — the same
385
+ // command, the same project, on the same port so every page open on it finds it again, and
386
+ // without opening the browser a second time. Its listener is closed first, so the port is free
387
+ // for the new one; what it says on the way up lands beside the ledger (restart.log).
388
+ function restartSelf(port) {
389
+ const args = process.argv.slice(1);
390
+ const next = [...args];
391
+ if (!args.includes('--port')) next.push('--port', String(port));
392
+ if (!args.includes('--no-open')) next.push('--no-open');
393
+ setTimeout(() => {
394
+ server.close(() => {
395
+ let log = 'ignore';
396
+ try { log = openSync(join(roomDir, 'restart.log'), 'a'); } catch { /* no witness, still restart */ }
397
+ const env = { ...process.env, PULSE_RESTARTED: '1' };
398
+ delete env.PULSE_UPDATE_RESTART;
399
+ const child = spawn(process.execPath, [...process.execArgv, ...next], { cwd: process.cwd(), detached: process.platform !== 'win32', windowsHide: true, stdio: ['ignore', log, log], env });
400
+ child.unref();
401
+ setTimeout(() => process.exit(0), 200);
402
+ });
403
+ for (const client of clients.keys()) { try { client.end(); } catch { /* gone */ } }
404
+ }, 300);
405
+ }
333
406
  // How many memories of each kind, and how many travel into turns. Counted, never read out.
334
407
  function memoryCensus() {
335
408
  const all = memory ? memory.memories({ limit: 20000 }) : [];
@@ -376,17 +449,31 @@ export async function createPulseServer({
376
449
  // says so once, the next time a page asks (market/updates.json).
377
450
  const marketOn = () => process.env.PULSE_MARKET !== '0' && updatesEnabled();
378
451
  const marketKeyed = marketKey ? { publicKey: marketKey } : {};
452
+ const factoryKeyed = factoryKey ? { factoryKey } : {};
453
+ const licenseKeyed = licenseApi ? { api: licenseApi } : {};
454
+ // OpenCode's own free models, as its CLI lists them, read again at most every ten minutes.
455
+ const openCodeOwn = { names: null, at: 0 };
379
456
  const marketTools = () => ({ stateRoot: root, projectRoot: canonicalProjectRoot, madre: PACKAGE.version, fetchImpl: marketFetch, verifyText: verifyModuleText, installText: installModuleText });
380
457
  let marketSync = null;
381
458
  const syncMarket = ({ force = false } = {}) => {
382
459
  if (!marketOn()) return Promise.resolve({ catalog: null, off: true });
383
460
  marketSync ??= (async () => {
384
461
  const read = await refreshCatalog({ stateRoot: root, fetchImpl: marketFetch, force, ...marketKeyed });
385
- if (read.catalog) await updateFromMarket({ ...marketTools(), catalog: read.catalog, names: Object.fromEntries(MODULES.map((one) => [one.id, one.name])) }).catch(() => []);
462
+ const names = Object.fromEntries(MODULES.map((one) => [one.id, one.name]));
463
+ if (read.catalog) await updateFromMarket({ ...marketTools(), catalog: read.catalog, names, remove: (id) => removeExternalModule({ id, stateRoot: root, projectRoot: canonicalProjectRoot }) }).catch(() => []);
464
+ // MADRE's own modules, newer from the Market and signed with the factory key (src/builtin-updates.mjs):
465
+ // what came or was taken back is run from now on, in this project and in Home.
466
+ if (read.catalog) {
467
+ const changed = await updateBuiltins({ stateRoot: root, catalog: read.catalog, packaged: packagedVersions(), understands: understandsSdk, fetchImpl: marketFetch, names, ...factoryKeyed }).catch(() => ({ updated: [], revoked: [] }));
468
+ if (changed.updated.length || changed.revoked.length) await adoptBuiltinUpdates({ stateRoot: root, enabled: marketOn(), ...factoryKeyed }).catch(() => []);
469
+ }
386
470
  return read;
387
471
  })().finally(() => { marketSync = null; });
388
472
  return marketSync;
389
473
  };
474
+ // What this computer already kept for MADRE's own modules runs from the start; with «Look for new
475
+ // versions» off, the ones MADRE came with.
476
+ await adoptBuiltinUpdates({ stateRoot: root, enabled: marketOn(), ...factoryKeyed }).catch((error) => console.error(`MADRE modules: ${error.message}`));
390
477
  void syncMarket().catch(() => null);
391
478
  const install = detectInstall({ projectRoot: canonicalProjectRoot });
392
479
  async function versionView({ force = false } = {}) {
@@ -443,6 +530,8 @@ export async function createPulseServer({
443
530
  // Coordinator, and Ollama as this room probed it. A reading is kept 30 s, so a page that asks
444
531
  // every few seconds never makes the projects work for it.
445
532
  const widgetReadings = new Map();
533
+ // This copy's identifier once left out of the author's usage figures (the usage widget, below).
534
+ const usageExcluded = new Set();
446
535
  let cpuSeen = null;
447
536
  const cpuTimes = () => cpus().reduce((sum, one) => {
448
537
  const times = one.times;
@@ -493,7 +582,7 @@ export async function createPulseServer({
493
582
  async function homeWidget(kind) {
494
583
  const kept = widgetReadings.get(kind);
495
584
  // madre.run's count moves once a day: the author's reading is kept ten minutes, the Mac's thirty seconds.
496
- if (kept && Date.now() - kept.at < (kind === 'usage' ? 600000 : 30000)) return kept.reading;
585
+ if (kept && Date.now() - kept.at < (kind === 'usage' || kind === 'errors' ? 600000 : 30000)) return kept.reading;
497
586
  let reading;
498
587
  if (kind === 'system') {
499
588
  const total = totalmem();
@@ -520,9 +609,36 @@ export async function createPulseServer({
520
609
  // (scripts/owner-usage.mjs); anywhere else there is no such widget.
521
610
  const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
522
611
  if (!token) return null;
612
+ // This copy is the author's: left out of the figures the first time the widget reads them.
613
+ const mine = await installId(root).catch(() => null);
614
+ if (mine && !usageExcluded.has(mine)) {
615
+ const marked = await reportFetch(process.env.PULSE_USAGE_URL ?? 'https://madre.run/api/usage', { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify({ exclude: mine }), signal: AbortSignal.timeout(8000) }).catch(() => null);
616
+ if (marked?.ok) usageExcluded.add(mine);
617
+ }
523
618
  const answer = await reportFetch(process.env.PULSE_USAGE_URL ?? 'https://madre.run/api/usage', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) }).catch(() => null);
524
619
  const body = answer?.ok ? await answer.json().catch(() => null) : null;
620
+ reading = body?.ok ? { available: true, ...body, mine } : { available: false, status: answer?.status ?? 0 };
621
+ } else if (kind === 'errors') {
622
+ // The author's own reading of what fails in every copy (src/telemetry.mjs, madre.run's
623
+ // /api/telemetry): the same token as the usage, the same copy run from source.
624
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
625
+ if (!token) return null;
626
+ const answer = await reportFetch(process.env.PULSE_TELEMETRY_READ_URL ?? 'https://madre.run/api/telemetry', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) }).catch(() => null);
627
+ const body = answer?.ok ? await answer.json().catch(() => null) : null;
628
+ reading = body?.ok ? { available: true, ...body } : { available: false, status: answer?.status ?? 0 };
629
+ } else if (kind === 'live' || kind === 'installs' || kind === 'environments') {
630
+ // The author's board (madre.run's /api/metrics, 2026-10-30): copies on now and off, installs,
631
+ // updates and uninstalls by day, and where they run. One reading for the three widgets, kept a
632
+ // minute: «on now» is worth reading often.
633
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
634
+ if (!token) return null;
635
+ const shared = widgetReadings.get('metrics');
636
+ if (shared && Date.now() - shared.at < 60000) return shared.reading;
637
+ const answer = await reportFetch(process.env.PULSE_METRICS_URL ?? 'https://madre.run/api/metrics', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) }).catch(() => null);
638
+ const body = answer?.ok ? await answer.json().catch(() => null) : null;
525
639
  reading = body?.ok ? { available: true, ...body } : { available: false, status: answer?.status ?? 0 };
640
+ widgetReadings.set('metrics', { at: Date.now(), reading });
641
+ return reading;
526
642
  } else if (kind === 'coordinator' && !salasRoom) {
527
643
  // Home's page is served by every project too: the Coordinator's record is its own room's.
528
644
  const coordinator = (await knownRooms(root)).find((one) => one.id === salasRoomId(root));
@@ -706,11 +822,17 @@ export async function createPulseServer({
706
822
  return { roomDir, recipeDir: fileURLToPath(new URL('../docs/training/', import.meta.url)), modelName: `madre-${slug}`, baseModel: base.base, memoryGb: fit.hardware?.memoryGb ?? Math.round(totalmem() / 1024 ** 3), fit };
707
823
  }
708
824
  async function wireOllama({ probe: doProbe = true } = {}) {
709
- if (doProbe) ollama = await ollamaProbe();
825
+ if (doProbe) { ollama = await ollamaProbe(); ollama.autoModel = ollama.chatModel; }
710
826
  // A model trained on this room (docs/training) is named madre-<project>: @madre uses it when it exists.
711
827
  const slug = basename(canonicalProjectRoot).toLowerCase().replace(/[^a-z0-9]+/g, '-');
712
828
  const trained = (ollama.models ?? []).map((model) => model.name).find((name) => name.startsWith(`madre-${slug}`)) ?? null;
713
- ollama = { ...ollama, madreModel: trained };
829
+ // The model the person chose in Home, one for the whole computer (src/local-ai.mjs), while it
830
+ // is installed; otherwise the one MADRE picked. PULSE_OLLAMA_MODEL still wins over both.
831
+ const chosen = process.env.PULSE_OLLAMA_MODEL ? null : localAiConfig(await readConfig(root)).model;
832
+ const bare = (name) => String(name ?? '').replace(/:latest$/, '');
833
+ const installed = chosen ? (ollama.models ?? []).find((model) => bare(model.name) === bare(chosen))?.name ?? null : null;
834
+ const auto = ollama.autoModel !== undefined ? ollama.autoModel : ollama.chatModel;
835
+ ollama = { ...ollama, autoModel: auto, chosenModel: chosen, chatModel: installed ?? auto, madreModel: trained };
714
836
  const project = await localAiHere();
715
837
  // Off for this project reads exactly as the module switched off, and only here.
716
838
  const settings = { ...(await ollamaSettings()), enabled: project.on };
@@ -744,6 +866,8 @@ export async function createPulseServer({
744
866
  memory.metaSet('local.announced', fifth.version);
745
867
  await room.record('local.present', {
746
868
  model: fifth.version,
869
+ // Ollama on another computer of the network (NUE-07): the card does not say «on this Mac».
870
+ ...(ollama.host && !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?\/?$/i.test(String(ollama.host)) ? { remote: true } : {}),
747
871
  checked: checked?.ran ? { passed: Boolean(checked.passed), matched: checked.matched ?? 0, n: checked.n ?? 0, at: checked.at ?? null } : null,
748
872
  });
749
873
  }
@@ -760,6 +884,23 @@ export async function createPulseServer({
760
884
  return view;
761
885
  };
762
886
  let room = null;
887
+ // WHERE OLLAMA IS (2026-10-28): this computer's by default, or the one the person pointed MADRE to —
888
+ // Windows' own from inside WSL, or another computer with a graphics card — saved in Settings
889
+ // (config.ollama.host). A host given when MADRE was started (PULSE_OLLAMA_HOST, OLLAMA_HOST) wins,
890
+ // as it did before. Every reading of the host asks the environment, so it is set there.
891
+ // The host saved in Settings is written to the environment marked as such (PULSE_OLLAMA_HOST_FROM),
892
+ // so the projects Home opens and MADRE restarted read it as the saved one, still changeable, and
893
+ // not as one given at the start.
894
+ const inheritedFromConfig = process.env.PULSE_OLLAMA_HOST_FROM === 'config';
895
+ const ollamaHostFromLaunch = Boolean(process.env.OLLAMA_HOST || (process.env.PULSE_OLLAMA_HOST && !inheritedFromConfig));
896
+ let ollamaHostFromConfig = inheritedFromConfig;
897
+ const adoptOllamaHost = (config) => {
898
+ if (ollamaHostFromLaunch) return;
899
+ const host = typeof config?.ollama?.host === 'string' && config.ollama.host ? config.ollama.host : null;
900
+ if (host) { process.env.PULSE_OLLAMA_HOST = host; process.env.PULSE_OLLAMA_HOST_FROM = 'config'; ollamaHostFromConfig = true; }
901
+ else if (ollamaHostFromConfig) { delete process.env.PULSE_OLLAMA_HOST; delete process.env.PULSE_OLLAMA_HOST_FROM; ollamaHostFromConfig = false; }
902
+ };
903
+ adoptOllamaHost(await readConfig(root));
763
904
  await wireOllama();
764
905
  const memoryServer = memory ? memoryServerFor({ dbFile: memory.file, projectRoot: canonicalProjectRoot }) : null;
765
906
  // MOTHER's channel to the crew: her seal's fingerprint lives in the memory
@@ -777,6 +918,16 @@ export async function createPulseServer({
777
918
  // a restart take them all back. Wrong keys are counted: a program trying words is slowed down.
778
919
  const passes = new Map(); // token -> { agent, mode, until, once }
779
920
  const keyMisses = []; // when the last wrong keys were typed
921
+ const pageErrors = []; // when the page last told of a failure of its own (/api/telemetry/page-error)
922
+ // A key that is only pressed (2026-10-28) is pressed on MADRE's own page: a web page elsewhere
923
+ // cannot send it. (A program on the Mac could, as it could read a folder's name before; the
924
+ // phrase is the key for whoever wants one a program cannot know.)
925
+ const pressedHere = (request) => {
926
+ const host = String(request.headers.host ?? '');
927
+ const site = request.headers['sec-fetch-site'];
928
+ return /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) && (site === undefined || site === 'same-origin' || site === 'none') && request.headers.origin === `http://${host}`;
929
+ };
930
+ const onlyPressed = (mode) => !overrideSettings(overrideConfig).keys[mode].startsWith('phrase');
780
931
  const PASS_ONCE_MS = 30 * 60 * 1000;
781
932
  // `asked` is a window the human chose on an agent's request for this mode (2026-10-14): one of
782
933
  // the windows the project allows, never longer, and only for that agent and mode.
@@ -860,11 +1011,30 @@ export async function createPulseServer({
860
1011
  // Session state per agent, refreshed on demand from the connections panel.
861
1012
  let sessions = {};
862
1013
  let sessionsAt = null;
863
- async function refreshSessions() {
864
- sessions = await probe(agents);
1014
+ // The page drew its crew before this came back and kept the first agent installed, signed in or
1015
+ // not: a newcomer's first message went to a Codex without a session (QA 1.1.0, NUE-11). The
1016
+ // answer is now said to whoever is watching, and an agent that did not answer in time is asked
1017
+ // again a little later instead of staying «signed out» until a restart (ACT-08).
1018
+ let reprobe = null;
1019
+ let reprobes = 0;
1020
+ async function refreshSessions({ only = null } = {}) {
1021
+ const asked = only ? agents.filter((agent) => only.includes(agent.id)) : agents;
1022
+ const found = await probe(asked);
1023
+ sessions = only ? { ...sessions, ...found } : found;
865
1024
  sessionsAt = new Date().toISOString();
1025
+ room?.announce?.('sessions.updated', { sessions, sessionsAt });
1026
+ const late = Object.entries(sessions).filter(([, one]) => one?.timedOut).map(([id]) => id);
1027
+ clearTimeout(reprobe);
1028
+ if (late.length && reprobes < 3) {
1029
+ reprobes += 1;
1030
+ reprobe = setTimeout(() => void refreshSessions({ only: late }).catch(() => {}), 10000 * 3 ** (reprobes - 1));
1031
+ reprobe.unref?.();
1032
+ } else if (!late.length) reprobes = 0;
866
1033
  return sessions;
867
1034
  }
1035
+ // Before any OpenCode runs here: MADRE's notes about OpenCode no longer go by a name OpenCode
1036
+ // reads as its own configuration (ACT-01).
1037
+ await migrateOpenCodeHealth(root).catch(() => {});
868
1038
  void refreshSessions().catch((error) => console.error(`MADRE session probe failed: ${error.message}`));
869
1039
 
870
1040
  // Effective settings = environment + config file + live changes; the file
@@ -977,6 +1147,8 @@ export async function createPulseServer({
977
1147
  }
978
1148
 
979
1149
  let loggingIn = null;
1150
+ // Sign-ins the person stopped: their end is a choice, not a failure to explain.
1151
+ const cancelled = new Set();
980
1152
  // A sign-in in flight, as the room is allowed to see it: which door, the address to open, and
981
1153
  // whether the CLI is waiting to be told the code that page gave back. Never the code itself.
982
1154
  // A device sign-in's code is the opposite case: it is shown to be typed on the provider's page.
@@ -985,12 +1157,12 @@ export async function createPulseServer({
985
1157
 
986
1158
  async function loginAgent(id, { method = null } = {}) {
987
1159
  const agent = agents.find((item) => item.id === id);
988
- if (!agent) return { status: 404, body: { error: `Unknown agent: ${id}.` } };
989
- if (!agent.detected) return { status: 412, body: { error: `${agent.label} is not installed on this computer.`, install: loginPlanFor(agent)?.install ?? [] } };
1160
+ if (!agent) return { status: 404, body: { error: t('Unknown agent: {id}.', { id }) } };
1161
+ if (!agent.detected) return { status: 412, body: { error: t('{label} is not installed on this computer.', { label: agent.label }), install: loginPlanFor(agent)?.install ?? [] } };
990
1162
  const plan = loginRunners[id]?.(agent, { method }) ?? loginPlanFor(agent, { method });
991
- if (!plan) return { status: 404, body: { error: `No sign-in flow known for ${id}.` } };
992
- if (!plan.headless) return { status: 409, body: { error: `${agent.label} signs in from its own prompt. Run this in a terminal, then press RECHECK.`, command: plan.display, note: plan.note } };
993
- if (loggingIn) return { status: 409, body: { error: `A sign-in is already running (${loggingIn}).` } };
1163
+ if (!plan) return { status: 404, body: { error: t('MADRE does not know how to sign in to {id}.', { id }) } };
1164
+ if (!plan.headless) return { status: 409, body: { error: t('{label} signs in from its own window: run this in a terminal, then press Check again.', { label: agent.label }), command: plan.display, note: plan.note } };
1165
+ if (loggingIn) return { status: 409, body: { error: t('Another sign-in is running ({label}). Wait for it to finish or cancel it.', { label: agents.find((one) => one.id === loggingIn)?.label ?? loggingIn }) } };
994
1166
  // A CLI with no sign-in command of its own (Gemini) signs in on its first question: its settings
995
1167
  // are set before, and the run is stopped as soon as the credentials are written. It runs in an
996
1168
  // empty folder, so that question never sees the project.
@@ -1002,7 +1174,7 @@ export async function createPulseServer({
1002
1174
  cwd = await mkdtemp(join(tmpdir(), 'madre-signin-'));
1003
1175
  } catch (error) {
1004
1176
  await flow.undo().catch(() => {});
1005
- return { status: 500, body: { error: `The sign-in could not be prepared: ${error.message}` } };
1177
+ return { status: 500, body: { error: t('The sign-in could not be prepared: {error}', { error: error.message }) } };
1006
1178
  }
1007
1179
  }
1008
1180
  const env = { ...process.env, ...(plan.env ?? {}) };
@@ -1075,7 +1247,10 @@ export async function createPulseServer({
1075
1247
  const error = refused
1076
1248
  ? t('Google signed you in, but it refuses this account on Gemini CLI (free personal accounts are refused). Gemini was left as it was: paste a Gemini API key from Google AI Studio instead.')
1077
1249
  : finished ? null : result.error ?? null;
1078
- await room.record('connection.login.finished', { agent: id, code, error, session: sessions[id] ?? null, tail: lines.slice(-6) });
1250
+ // Why it did not finish, in one word the page turns into plain words (src/setup-trouble.mjs).
1251
+ const trouble = code === 0 && !error ? null : loginTrouble({ refused, text: `${cancelled.has(id) ? 'cancelled ' : ''}${error ?? ''}\n${lines.slice(-6).join('\n')}` });
1252
+ cancelled.delete(id);
1253
+ await room.record('connection.login.finished', { agent: id, code, error, trouble, session: sessions[id] ?? null, tail: lines.slice(-6) });
1079
1254
  loggingIn = null;
1080
1255
  loginRun = null;
1081
1256
  })();
@@ -1098,7 +1273,8 @@ export async function createPulseServer({
1098
1273
  }
1099
1274
 
1100
1275
  async function cancelLogin(id) {
1101
- if (!loginRun || loginRun.agent !== id) return { status: 409, body: { error: 'No sign-in is running for that agent.' } };
1276
+ if (!loginRun || loginRun.agent !== id) return { status: 409, body: { error: t('No sign-in is running for that agent.') } };
1277
+ cancelled.add(id);
1102
1278
  loginRun.child?.cancel?.();
1103
1279
  await room.record('connection.login.cancelled', { agent: id });
1104
1280
  return { status: 202, body: { cancelled: true } };
@@ -1133,12 +1309,13 @@ export async function createPulseServer({
1133
1309
  // other install, and looks again when it finishes. Nothing is written into the project.
1134
1310
  async function installAgent(id) {
1135
1311
  const agent = agents.find((item) => item.id === id);
1136
- if (!agent) return { status: 404, body: { error: `Unknown agent: ${id}.` } };
1137
- if (agent.detected) return { status: 409, body: { error: `${agent.label} is already installed.` } };
1312
+ if (!agent) return { status: 404, body: { error: t('Unknown agent: {id}.', { id }) } };
1313
+ if (agent.detected) return { status: 409, body: { error: t('{label} is already installed.', { label: agent.label }) } };
1138
1314
  const plan = installPlanFor(agent, { prefix: toolsPrefix() });
1139
- if (!plan) return { status: 404, body: { error: `MADRE does not know how to install ${id}.` } };
1140
- if (installing) return { status: 409, body: { error: `Another install is running (${installing}).` } };
1141
- installing = `agent:${id}`;
1315
+ if (!plan) return { status: 404, body: { error: t('MADRE does not know how to install {id}.', { id }) } };
1316
+ if (!plan.command) return { status: 409, body: { error: t('{label} installs with its own installer: copy the command into a terminal, then check again.', { label: agent.label }) } };
1317
+ if (installing) return { status: 409, body: { error: t('Another install is running. Wait for it to finish and try again.') } };
1318
+ installing = `agent:${id}`; installingSince = Date.now();
1142
1319
  await room.record('connection.install.started', { agent: id, label: agent.label, command: plan.display });
1143
1320
  void (async () => {
1144
1321
  const lines = [];
@@ -1153,7 +1330,7 @@ export async function createPulseServer({
1153
1330
  let where = 'system';
1154
1331
  // Walled out of the system folders: install into MADRE's own, where it will be found.
1155
1332
  if (result.code !== 0 && plan.fallback && looksLikeAdminProblem(`${lines.join('\n')}\n${result.error ?? ''}`)) {
1156
- await room.record('connection.install.output', { agent: id, line: `npm cannot write to this computer's system folder without an administrator. Installing into MADRE's own folder instead: ${toolsPrefix()}` });
1333
+ await room.record('connection.install.output', { agent: id, line: t('This computer does not let npm install in its system folder without an administrator. Installing in MADRE\'s own folder instead: {folder}', { folder: toolsPrefix() }) });
1157
1334
  result = await attempt(plan.fallback);
1158
1335
  where = 'madre';
1159
1336
  }
@@ -1169,6 +1346,8 @@ export async function createPulseServer({
1169
1346
  detected: Boolean(found?.detected),
1170
1347
  version: found?.version ?? null,
1171
1348
  session: sessions[id] ?? null,
1349
+ // Why it did not install, in one word the page turns into plain words (src/setup-trouble.mjs).
1350
+ trouble: found?.detected ? null : installTrouble(`${result.error ?? ''}\n${lines.join('\n')}`),
1172
1351
  tail: lines.slice(-6),
1173
1352
  });
1174
1353
  installing = null;
@@ -1251,15 +1430,40 @@ export async function createPulseServer({
1251
1430
  const broadcastPending = () => pump(mainFeed);
1252
1431
  let unsubscribe = () => {};
1253
1432
 
1433
+ // ANONYMOUS DIAGNOSTICS (src/telemetry.mjs, 2026-10-28): every failure, known or not, and how much
1434
+ // of MADRE is used, kept in ~/.pulse/telemetry and told to madre.run once a day, unless the person
1435
+ // turned it off. The setting is ~/.pulse's, one for Home and every project: each process reads it
1436
+ // again every few seconds, so turning it off in one turns it off in all of them, not only there.
1437
+ const telemetry = (await readConfig(root)).telemetry ?? {};
1438
+ let diagnosticsOn = telemetryOn({ telemetry });
1439
+ let diagnosticsReadAt = Date.now();
1440
+ const diagnosticsNow = async () => {
1441
+ if (Date.now() - diagnosticsReadAt > 5000) {
1442
+ diagnosticsReadAt = Date.now();
1443
+ const config = await readConfig(root).catch(() => null);
1444
+ if (config) diagnosticsOn = telemetryOn({ telemetry: config.telemetry ?? {} });
1445
+ }
1446
+ return diagnosticsOn;
1447
+ };
1448
+ const diagnostics = new Telemetry({ root, version: PACKAGE.version, enabled: diagnosticsNow });
1449
+ diagnostics.onSoon(() => diagnostics.flush({ fetchImpl: reportFetch }));
1450
+ // Installed, updated, Home started (src/install-metrics.mjs): counted once each, with the diagnostics.
1451
+ let lifeFirst = null;
1452
+ if (!testMode) {
1453
+ void noteLifecycle({ root, version: PACKAGE.version, hadId: hadInstallId }).then(({ event, first }) => { lifeFirst = first; if (event) diagnostics.count(`life.${event}`); }).catch(() => null);
1454
+ if (salasRoom) diagnostics.count('life.start');
1455
+ }
1254
1456
  // The error sentinel: failures MU/TH/UR cannot classify, and crashes, become
1255
1457
  // redacted reports in the ledger. Sending them anywhere is the human's call.
1256
- const telemetry = (await readConfig(root)).telemetry ?? {};
1257
1458
  const sentinel = new ErrorSentinel({
1459
+ told: (input) => diagnostics.error(input),
1258
1460
  pkg: PACKAGE,
1259
1461
  agents,
1260
- settings: { autoReport: process.env.PULSE_AUTO_REPORT === '1' || Boolean(telemetry.autoReport), reportUrl: process.env.PULSE_REPORT_URL ?? telemetry.reportUrl ?? DEFAULT_REPORT_URL },
1462
+ // On by default since 1.1.0, with the anonymous diagnostics (2026-10-28, the author's call): a new
1463
+ // error reaches the author with private details removed, unless the person turned either off.
1464
+ settings: { autoReport: process.env.PULSE_AUTO_REPORT === '1' || (process.env.PULSE_AUTO_REPORT !== '0' && (typeof telemetry.autoReport === 'boolean' ? telemetry.autoReport : diagnosticsOn)), reportUrl: process.env.PULSE_REPORT_URL ?? telemetry.reportUrl ?? DEFAULT_REPORT_URL },
1261
1465
  fetchImpl: reportFetch,
1262
- emit: (type, payload) => room.record(type, payload),
1466
+ emit: (type, payload) => writeFromOutside(room, type, payload),
1263
1467
  save: async (settings) => { const current = await readConfig(root); await updateConfig(root, { telemetry: { ...(current.telemetry ?? {}), ...settings } }); },
1264
1468
  });
1265
1469
  outbound.watchReportUrl(sentinel.settings().reportUrl);
@@ -1281,7 +1485,7 @@ export async function createPulseServer({
1281
1485
  research: () => room.memoryResearch(),
1282
1486
  entriesFor: (notes) => (memory ? memory.entriesAt(notes.flatMap((note) => note.sources ?? [])) : []),
1283
1487
  bench: () => room.bench(),
1284
- emit: (type, payload) => room.record(type, payload),
1488
+ emit: (type, payload) => writeFromOutside(room, type, payload),
1285
1489
  });
1286
1490
  let unsubscribeEyecat = () => {};
1287
1491
 
@@ -1292,6 +1496,22 @@ export async function createPulseServer({
1292
1496
  // when the room closes: a file that reappears while its folder is being removed is a test that
1293
1497
  // fails for a reason that has nothing to do with it.
1294
1498
  let chatWrites = Promise.resolve();
1499
+ // What the watchers outside the room (the error sentinel, EYECAT, the modules' onEvent) write
1500
+ // to a record. They hear an event and answer when they are done, which can be after the room
1501
+ // was told to close: a report written once the server said it was closed landed in a folder
1502
+ // being removed, and in a memory file already shut (2026-10-21). From the close on they write
1503
+ // nothing; what they had started writing is waited for. Their work itself is not: EYECAT may
1504
+ // be asking an agent, and closing does not wait for an answer.
1505
+ let serverClosing = false;
1506
+ const lateWrites = new Set();
1507
+ const writeFromOutside = (target, type, payload) => {
1508
+ if (serverClosing) return Promise.resolve(null);
1509
+ const write = Promise.resolve(target.record(type, payload));
1510
+ lateWrites.add(write);
1511
+ write.finally(() => lateWrites.delete(write)).catch(() => {});
1512
+ return write;
1513
+ };
1514
+ const lateWritesDone = async () => { while (lateWrites.size) await Promise.allSettled([...lateWrites]); };
1295
1515
 
1296
1516
  // Everything that listens to the open conversation, attached in one place so that opening
1297
1517
  // another attaches exactly the same things to it. Live readings go straight to whoever is
@@ -1341,25 +1561,51 @@ export async function createPulseServer({
1341
1561
  // event is its own business and never holds up the room: a failure is logged and dropped.
1342
1562
  function wireModules(target, id) {
1343
1563
  return target.subscribe((event) => {
1564
+ // What OpenCode answered with, and what failed for which provider (src/opencode-health.mjs):
1565
+ // the next failure offers a model that works instead of a sentence in English.
1566
+ if (event.type === 'agent.completed' && event.payload?.agent === 'opencode') void noteOpenCodeTurn(root, { ok: true, model: event.payload.ranOn ?? null }).catch(() => null);
1567
+ if (event.type === 'message.failed' && event.payload?.target === 'opencode') void noteOpenCodeTurn(root, { ok: false, model: event.payload.ranOn ?? null, error: event.payload.error }).catch(() => null);
1344
1568
  const listening = MODULES.filter((module) => typeof module.onEvent === 'function');
1345
1569
  if (!listening.length) return;
1346
1570
  void (async () => {
1347
1571
  const ctx = await moduleContext();
1348
1572
  for (const module of listening) {
1349
- const settings = module.settingsFrom(ctx.config);
1573
+ // This project's word on the module, not only the one for every project (module-scope.mjs).
1574
+ const settings = module.settingsFrom(ctx.config, ctx.roomId);
1350
1575
  if (module.kind === 'builtin' && !settings.enabled) continue;
1351
- await Promise.resolve(module.onEvent({ ...ctx, settings, room: target, chat: id, record: (type, payload) => target.record(type, payload) }, event))
1576
+ await Promise.resolve(module.onEvent({ ...ctx, settings, room: target, chat: id, record: (type, payload) => writeFromOutside(target, type, payload) }, event))
1352
1577
  .catch((error) => console.error(`MADRE module ${module.id}: onEvent failed: ${error.message}`));
1353
1578
  }
1354
1579
  })().catch((error) => console.error(`MADRE: a module could not hear an event: ${error.message}`));
1355
1580
  });
1356
1581
  }
1357
1582
  let unsubscribeModules = () => {};
1583
+ // What the anonymous diagnostics count of a room (src/telemetry.mjs): which agent got a turn and at
1584
+ // which mode, what ran, what failed to install. Names of MADRE's own parts and numbers, never words.
1585
+ function countForDiagnostics(event) {
1586
+ const said = event?.payload ?? {};
1587
+ if (event?.ghost) return;
1588
+ if (event?.type === 'message.created' && said.role === 'user' && !said.auto) {
1589
+ if (said.target) diagnostics.count(`turn.${said.target}`);
1590
+ if (Number.isInteger(said.mode)) diagnostics.count(`mode.${said.mode}`);
1591
+ if (said.via) diagnostics.count(`via.${said.via}`);
1592
+ if (said.attachments?.length) diagnostics.count('turn.attachments');
1593
+ if (said.ash?.active) diagnostics.count('turn.ash');
1594
+ } else if (event?.type === 'message.created' && said.role === 'assistant' && said.sender) {
1595
+ diagnostics.count(`answer.${said.sender}`);
1596
+ if (said.recalled?.length) diagnostics.count('answer.recalled');
1597
+ } else if (event?.type === 'plan.completed') diagnostics.count('plan.done');
1598
+ else if (event?.type === 'copilot.started') diagnostics.count('copilot.on');
1599
+ else if (event?.type === 'extension.install.finished') {
1600
+ if (said.ok) diagnostics.count(`install.${said.id ?? 'module'}`);
1601
+ else if (!said.cancelled) diagnostics.error({ kind: said.model ? 'model' : 'install', where: [said.id, said.trouble].filter(Boolean).join(' · ') || null, message: said.detail ?? 'install failed' });
1602
+ }
1603
+ }
1358
1604
  function wireRoom() {
1359
1605
  unsubscribe = room.subscribe(() => { void broadcastPending(); });
1360
1606
  unsubscribeModules = wireModules(room, chatId);
1361
1607
  unsubscribeAsks = trackAsks(room, historicalEvents);
1362
- unsubscribeSentinel = room.subscribe((event) => { void sentinel.observe(event).catch(() => null); });
1608
+ unsubscribeSentinel = room.subscribe((event) => { void sentinel.observe(event).catch(() => null); countForDiagnostics(event); });
1363
1609
  unsubscribeEyecat = room.subscribe((event) => { void eyecat.observe(event).catch(() => null); });
1364
1610
  unsubscribeGhost = room.subscribeGhost((event) => { for (const client of clients.keys()) writeEvent(client, event); });
1365
1611
  unsubscribeLive = room.subscribeLive((event) => { for (const client of clients.keys()) writeEvent(client, event); });
@@ -1401,6 +1647,32 @@ export async function createPulseServer({
1401
1647
  // always: opening a held conversation takes the room that is already there. When nothing is
1402
1648
  // running in it and nobody is watching, it closes itself.
1403
1649
  const busyChats = () => [...parked.entries()].filter(([, held]) => held.room.busy()).map(([id]) => id);
1650
+ // Every conversation at work, not only the one on screen: the brake is the room's, not the chat's.
1651
+ async function stopEverythingHere() {
1652
+ const result = await room.stopAll();
1653
+ passes.clear();
1654
+ await endCopilot('stopall');
1655
+ for (const held of parked.values()) {
1656
+ const more = await held.room.stopAll().catch(() => ({ plans: 0, turns: 0 }));
1657
+ result.plans += more.plans ?? 0;
1658
+ result.turns += more.turns ?? 0;
1659
+ }
1660
+ return result;
1661
+ }
1662
+ // What this project is doing, for «En marcha» (src/activity.mjs): every conversation's turns,
1663
+ // plans and commands, the install running, and what ended a moment ago.
1664
+ async function activityHere() {
1665
+ const { chats } = await listChats(roomDir);
1666
+ const titleOf = (id) => chats.find((one) => one.id === id)?.title ?? null;
1667
+ const now = [];
1668
+ for (const [id, one] of [[chatId, room], ...[...parked.entries()].map(([key, held]) => [key, held.room])]) {
1669
+ if (!one) continue;
1670
+ for (const item of one.activity()) now.push({ ...item, chat: id, chatTitle: titleOf(id) });
1671
+ }
1672
+ if (installing) now.push({ kind: 'install', what: installing, model: pulling?.model ?? null, startedAt: installingSince || null });
1673
+ const done = await recentInProject(roomDir, { also: [chatId, ...parked.keys()] }).catch(() => []);
1674
+ return { room: thisRoomId, name: salasRoom ? null : basename(canonicalProjectRoot), home: salasRoom, version: PACKAGE.version ?? null, now, done };
1675
+ }
1404
1676
  const sayToAll = (type, payload) => {
1405
1677
  const event = { id: `live-${randomUUID()}`, sequence: null, live: true, timestamp: new Date().toISOString(), type, payload };
1406
1678
  for (const client of clients.keys()) writeEvent(client, event);
@@ -1426,9 +1698,41 @@ export async function createPulseServer({
1426
1698
  if (!testMode) serverSentinel.start();
1427
1699
  // «Still in use», once a day per copy (src/heartbeat.mjs): a little after start, then looked at
1428
1700
  // every few hours; the day it was already said, nothing goes.
1429
- const sayAlive = () => { void heartbeat({ root, version: PACKAGE.version, fetchImpl: reportFetch }); };
1701
+ // The author's own copies say nothing (2026-10-20): a copy that holds the author's usage key is
1702
+ // one of his, and it would only count him in his own figures.
1703
+ // And with it, what the anonymous diagnostics kept (src/telemetry.mjs): the author's copies too,
1704
+ // their failures are failures; madre.run leaves them out of the figures of use.
1705
+ // And how this copy runs (src/install-metrics.mjs): numbers and names of MADRE's own parts, never a
1706
+ // path, a project's name or anything a person wrote.
1707
+ const gaugeEnvironment = async () => {
1708
+ const config = await readConfig(root).catch(() => ({}));
1709
+ const rooms = await knownRooms(root).catch(() => []);
1710
+ const projects = rooms.filter((one) => one.id !== salasRoomId(root));
1711
+ const modulesOn = MODULES.filter((module) => { try { return Boolean(module.settingsFrom(config).enabled); } catch { return false; } }).map((module) => module.id);
1712
+ const gauges = environmentGauges({
1713
+ cores: cpus().length, ramBytes: totalmem(), language: roomLanguage(), install, shell: process.env.SHELL ?? process.env.ComSpec ?? '',
1714
+ ollama: { running: Boolean(ollama.running), models: (ollama.models ?? []).length },
1715
+ agents, projects: { total: projects.length, open: projects.filter((one) => one.open).length },
1716
+ modules: modulesOn, ownModules: OWN_MODULE_IDS,
1717
+ ageDays: lifeFirst ? (Date.now() - Date.parse(lifeFirst)) / 86_400_000 : null,
1718
+ });
1719
+ for (const [key, value] of Object.entries(gauges)) diagnostics.gauge(key, value);
1720
+ };
1721
+ const sayAlive = () => {
1722
+ void readSecret(root, OWNER_VAULT, 'usage').catch(() => null).then((owner) => (owner ? null : heartbeat({ root, version: PACKAGE.version, fetchImpl: reportFetch })));
1723
+ void gaugeEnvironment().catch(() => null).then(() => diagnostics.flush({ fetchImpl: reportFetch }));
1724
+ };
1430
1725
  const aliveTimers = testMode ? [] : [setTimeout(sayAlive, 20_000), setInterval(sayAlive, 6 * 60 * 60 * 1000)];
1431
1726
  for (const timer of aliveTimers) timer.unref?.();
1727
+ // On right now (src/install-metrics.mjs): every few minutes while MADRE is open, with the diagnostics
1728
+ // and never from the author's own copies, as the daily notice.
1729
+ const sayHere = async () => {
1730
+ if (!(await diagnosticsNow())) return;
1731
+ if (await readSecret(root, OWNER_VAULT, 'usage').catch(() => null)) return;
1732
+ await sayPresent({ root, version: PACKAGE.version, fetchImpl: reportFetch }).catch(() => null);
1733
+ };
1734
+ const hereTimers = testMode ? [] : [setTimeout(() => void sayHere(), 15_000), setInterval(() => void sayHere(), PRESENCE_EVERY_MS)];
1735
+ for (const timer of hereTimers) timer.unref?.();
1432
1736
  const endClients = (feed) => { for (const client of [...feed.clients.keys()]) { feed.clients.delete(client); try { client.end(); } catch { /* already gone */ } } };
1433
1737
  async function closeHeld(id) {
1434
1738
  const held = parked.get(id);
@@ -1442,7 +1746,7 @@ export async function createPulseServer({
1442
1746
  async function releaseIfIdle(id, target = null) {
1443
1747
  const held = parked.get(id);
1444
1748
  if (!held || (target && held.room !== target)) return;
1445
- if (held.room.busy() || held.room.hasLiveRuns?.() || held.feed?.clients.size) return;
1749
+ if (held.room.busy() || held.room.hasLiveRuns?.() || held.feed?.clients.size || held.claims) return;
1446
1750
  await closeHeld(id);
1447
1751
  }
1448
1752
  // A conversation's turns starting and ending, said to every page whichever conversation it shows.
@@ -1497,7 +1801,24 @@ export async function createPulseServer({
1497
1801
  // mountChat builds one.
1498
1802
  // The room on screen, for the places where a route names its own conversation `room`.
1499
1803
  const openRoom = () => room;
1500
- async function scopeOf(url) {
1804
+ // A request about a conversation beside claims it until its response is over: a held room is not
1805
+ // let go while a request is still at work in it. The grace ran out between the room being found
1806
+ // and the request reaching it — a message read and checked before it was handed over, a page's
1807
+ // feed being built — and the room closed under it: the message was accepted and never answered,
1808
+ // the page heard nothing (2026-10-21). The last request to end gives it its grace again.
1809
+ function claimFor(entry, id, response) {
1810
+ if (!response) return;
1811
+ entry.claims = (entry.claims ?? 0) + 1;
1812
+ let done = false;
1813
+ const release = () => {
1814
+ if (done) return;
1815
+ done = true;
1816
+ entry.claims -= 1;
1817
+ if (!entry.claims) setTimeout(() => { void releaseIfIdle(id, entry.room); }, heldGraceMs).unref?.();
1818
+ };
1819
+ if (response.closed) release(); else response.once('close', release);
1820
+ }
1821
+ async function scopeOf(url, response = null) {
1501
1822
  const asked = url.searchParams.get('chat');
1502
1823
  if (!asked || asked === chatId) return { id: chatId, room, store, feed: mainFeed, main: true };
1503
1824
  if (!isChatId(asked)) return { error: `No conversation "${asked}".` };
@@ -1529,6 +1850,7 @@ export async function createPulseServer({
1529
1850
  }
1530
1851
  // It may have become the open one while it was being built.
1531
1852
  if (asked === chatId) return { id: chatId, room, store, feed: mainFeed, main: true };
1853
+ claimFor(entry, asked, response);
1532
1854
  return { id: asked, room: entry.room, store: entry.store, entry, main: false };
1533
1855
  }
1534
1856
  let unsubscribeActivity = () => {};
@@ -1617,6 +1939,10 @@ export async function createPulseServer({
1617
1939
  poller.unref();
1618
1940
 
1619
1941
  let installing = null;
1942
+ // When the install running now began, for «En marcha» (2026-10-30).
1943
+ let installingSince = 0;
1944
+ let pulling = null; // the model download running now, and how to stop it
1945
+
1620
1946
  // Intenciones' reading of every conversation, kept per ledger file until that file changes.
1621
1947
  const observedLedgers = new Map();
1622
1948
  // The context a module works in: the project, its settings, the room, and what this server offers.
@@ -1624,6 +1950,13 @@ export async function createPulseServer({
1624
1950
  const config = await readConfig(root);
1625
1951
  return {
1626
1952
  projectRoot: canonicalProjectRoot, stateRoot: root, config, env: process.env, agents, room,
1953
+ // The language the room speaks, 'es' or 'en': a module answers in it (SDK, 2026-10-20).
1954
+ language: roomLanguage(),
1955
+ // Its words in that language (SDK 2): a sentence MADRE knows, or the module's own { es, en }.
1956
+ t: say,
1957
+ // Where this project's conversations are kept (~/.pulse/rooms/<id>): a module's own small
1958
+ // files about the project live beside them, never in the project's folder.
1959
+ roomDir,
1627
1960
  // Which project's word a module's switch reads and writes; none in Home (module-scope.mjs).
1628
1961
  roomId: scopeRoom,
1629
1962
  readConfig: () => readConfig(root),
@@ -1694,28 +2027,51 @@ export async function createPulseServer({
1694
2027
  },
1695
2028
  // What a card knows about being up to date. Reading is free: it answers from the day's
1696
2029
  // cache. The button on a card is what forces a look outside.
2030
+ // The project's history over a period, in the shape docs/SDK.md promises (src/history.mjs):
2031
+ // every conversation's ledger and the memory's decisions, read on demand and never written.
2032
+ history: async ({ since = null, until = null } = {}) => {
2033
+ const chats = [];
2034
+ for (const chat of (await listChats(roomDir)).chats) {
2035
+ const text = await readFile(chatLedger(roomDir, chat.id), 'utf8').catch(() => '');
2036
+ const events = [];
2037
+ for (const line of text.split('\n')) {
2038
+ if (!line) continue;
2039
+ try { events.push(JSON.parse(line)); } catch { /* a torn last line */ }
2040
+ }
2041
+ chats.push({ id: chat.id, title: chat.title ?? null, events });
2042
+ }
2043
+ const memories = memory?.memories?.({ kind: 'decision', limit: 1000 }) ?? [];
2044
+ return { project: basename(canonicalProjectRoot), ...summarizeHistory({ chats, memories, since, until }) };
2045
+ },
1697
2046
  moduleUpdate: (item, { force = false, cacheOnly = !force } = {}) => moduleUpdate(item, {
1698
2047
  stateRoot: root, madre: { name: PACKAGE.name, version: PACKAGE.version },
1699
2048
  fetchImpl: reportFetch, enabled: updatesEnabled(), force, cacheOnly,
1700
2049
  }),
1701
2050
  ollama: {
1702
2051
  state: () => ollama,
2052
+ // One answer from the local model, for a module that reads something with it (SDK 2):
2053
+ // the model MADRE chose unless one is named. Nothing leaves this computer.
2054
+ generate: ({ model = null, system = null, prompt, json = false, timeoutMs = 60000, temperature = 0 } = {}) => {
2055
+ const chosen = model ?? ollama.madreModel ?? ollama.chatModel ?? null;
2056
+ if (!ollama.running || !chosen) return Promise.reject(new Error(t('The local AI is not running.')));
2057
+ return ollamaGenerate({ host: ollama.host, model: chosen, system, prompt: String(prompt ?? ''), json, timeoutMs, temperature, fetchImpl: reportFetch });
2058
+ },
1703
2059
  project: () => localAiHere(),
1704
2060
  setProject: (on) => setLocalAiHere(on),
1705
2061
  wire: (options) => wireOllama(options),
1706
2062
  // Getting Ollama onto this computer, with the command in plain sight, and waking it.
1707
2063
  install: async () => {
1708
- if (installing) return { ok: false, error: `Another install is running (${installing}).` };
1709
- const { ollamaInstallPlan } = await import('./modules/ollama.mjs');
1710
- const plan = ollamaInstallPlan({ brew: await findOnPath('brew') });
1711
- if (!plan.command) return { ok: false, error: plan.note, download: plan.download };
1712
- installing = 'ollama';
2064
+ if (installing) return { ok: false, error: t('Another install is running. Wait for it to finish and try again.') };
2065
+ const { ollamaInstallPlan, adminHere } = await import('./modules/ollama.mjs');
2066
+ const plan = ollamaInstallPlan({ brew: await findOnPath('brew'), admin: await adminHere() });
2067
+ if (!plan.command) return { ok: false, error: plan.note, download: plan.download, manual: plan.manual ? plan.display : null };
2068
+ installing = 'ollama'; installingSince = Date.now();
1713
2069
  await room.record('extension.install.started', { id: 'ollama', name: 'OLLAMA', command: plan.display, platforms: [], alreadyInstalled: false });
1714
2070
  void (async () => {
1715
2071
  const lines = [];
1716
2072
  const result = await runInstaller({ command: plan.command, args: plan.args, projectRoot: canonicalProjectRoot, timeoutMs: 900000, onLine: (line) => { lines.push(line); void room.record('extension.install.output', { id: 'ollama', lines: [line.slice(0, 500)] }); } });
1717
2073
  const status = await wireOllama();
1718
- await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: result.code === 0, installed: Boolean(await findOnPath('ollama')), detail: result.code === 0 ? 'Ollama installed · START it to wake it' : (result.error ?? `exit ${result.code}`), ollama: status });
2074
+ await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: result.code === 0, installed: Boolean(await findOnPath('ollama')), detail: result.code === 0 ? 'Ollama installed · START it to wake it' : (result.error ?? `exit ${result.code}`), trouble: result.code === 0 ? null : installTrouble(`${result.error ?? ''}\n${lines.slice(-20).join('\n')}`), ollama: status });
1719
2075
  installing = null;
1720
2076
  })();
1721
2077
  return { ok: true, command: plan.display };
@@ -1759,27 +2115,38 @@ export async function createPulseServer({
1759
2115
  if (down.running) return { ok: false, error: t('The old Ollama ({running}) did not stop. Quit it by hand, then press START OLLAMA.', { running: status.version }) };
1760
2116
  return this.start();
1761
2117
  },
1762
- // Pulls stream into the room like a module install; one at a time.
2118
+ // Pulls stream into the room like a module install; one at a time, and one can be stopped
2119
+ // (the welcome's «Cancel», 2026-10-28).
1763
2120
  pull: async (model) => {
1764
- if (installing) return { ok: false, error: `Another install is running (${installing}).` };
1765
- installing = 'ollama';
2121
+ if (installing) return { ok: false, error: t('Another install is running. Wait for it to finish and try again.') };
2122
+ installing = 'ollama'; installingSince = Date.now();
2123
+ const stopper = new AbortController();
2124
+ pulling = { model, stopper };
1766
2125
  await room.record('extension.install.started', { id: 'ollama', name: 'OLLAMA', command: `ollama pull ${model}`, platforms: [], alreadyInstalled: false });
1767
2126
  void (async () => {
1768
2127
  let pending = [];
1769
2128
  let flushTimer = null;
1770
2129
  const flush = async () => { flushTimer = null; if (!pending.length) return; const batch = pending; pending = []; await room.record('extension.install.output', { id: 'ollama', lines: batch }); };
1771
2130
  try {
1772
- await pullModel({ host: ollama.host, model, fetchImpl: reportFetch, onLine: (line) => { pending.push(line); if (!flushTimer) flushTimer = setTimeout(() => void flush(), 400); } });
2131
+ await pullModel({ host: ollama.host, model, fetchImpl: reportFetch, signal: stopper.signal, onLine: (line) => { pending.push(line); if (!flushTimer) flushTimer = setTimeout(() => void flush(), 400); } });
1773
2132
  await flush();
1774
2133
  const status = await wireOllama();
1775
- await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: true, installed: true, detail: `pulled ${model}`, ollama: status });
2134
+ await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: true, installed: true, detail: `pulled ${model}`, model, ollama: status });
1776
2135
  } catch (error) {
1777
2136
  await flush();
1778
- await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: error.message });
1779
- } finally { installing = null; }
2137
+ // Stopped on purpose: said as that, not as a failure.
2138
+ if (stopper.signal.aborted) await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: 'cancelled', model, cancelled: true });
2139
+ // Why it stopped, in one word the page says in plain words (src/setup-trouble.mjs).
2140
+ else await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: error.message, model, trouble: installTrouble(error.message) });
2141
+ } finally { installing = null; pulling = null; }
1780
2142
  })();
1781
2143
  return { ok: true };
1782
2144
  },
2145
+ cancelPull: (model = null) => {
2146
+ if (!pulling || (model && pulling.model !== model)) return { ok: false, error: t('No download is running.') };
2147
+ pulling.stopper.abort();
2148
+ return { ok: true, model: pulling.model };
2149
+ },
1783
2150
  },
1784
2151
  },
1785
2152
  };
@@ -1797,7 +2164,7 @@ export async function createPulseServer({
1797
2164
  return toggled;
1798
2165
  }
1799
2166
  if (confirm !== true) return { status: 400, body: { error: t('Installing a module writes into the project; send { "confirm": true } to proceed.') } };
1800
- if (installing) return { status: 409, body: { error: `Another install is running (${installing}).` } };
2167
+ if (installing) return { status: 409, body: { error: t('Another install is running. Wait for it to finish and try again.') } };
1801
2168
  const preflight = extension.preflight ? await extension.preflight(canonicalProjectRoot) : { ok: true, problems: [] };
1802
2169
  if (!preflight.ok && !installers[id]) {
1803
2170
  await room.record('extension.install.refused', { id, name: extension.name, problems: preflight.problems });
@@ -1808,7 +2175,7 @@ export async function createPulseServer({
1808
2175
  // What the module asked MADRE to do first (Continuity: `git init` in a project with no git),
1809
2176
  // shown in the same confirmation and run before the install, each step stopping the next.
1810
2177
  const prepare = Array.isArray(preflight.prepare) ? preflight.prepare : [];
1811
- installing = id;
2178
+ installing = id; installingSince = Date.now();
1812
2179
  await room.record('extension.install.started', { id, name: extension.name, command: plan.display, platforms: plan.platforms ?? [], alreadyInstalled: before.installed });
1813
2180
  void (async () => {
1814
2181
  const lines = [];
@@ -1858,6 +2225,9 @@ export async function createPulseServer({
1858
2225
  // The project's own folder name, typed by the human. Declared at the top of the handler and
1859
2226
  // not beside the first route that happened to need it: a const sits in its temporal dead zone
1860
2227
  // until its own line runs, so any route above it threw instead of refusing.
2228
+ // Which machine serves the page, written into it (public/i18n.js, hostWords): the browser that
2229
+ // reads it may be on another one, a Mac looking at a Linux box, and must not say «Mac» there.
2230
+ const withHost = (html) => html.replace('<head>', `<head>\n <meta name="madre-host" content="${JSON.stringify(hostFacts()).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')}">`);
1861
2231
  const designationOk = (given) => typeof given === 'string' && given.trim().toLowerCase() === basename(canonicalProjectRoot).toLowerCase();
1862
2232
  // A request the bridge passed on from a paired phone. It reaches the room from 127.0.0.1 like
1863
2233
  // anything on this Mac, so «only from this computer» has to ask this too.
@@ -1865,21 +2235,45 @@ export async function createPulseServer({
1865
2235
  const phoneKind = viaPhone ? String(request.headers['x-madre-device-kind'] ?? 'other').slice(0, 20) : null;
1866
2236
  try {
1867
2237
  if (request.method === 'GET' && url.pathname === '/') {
1868
- const html = await readFile(join(publicDirectory, 'index.html'));
2238
+ const html = withHost(await readFile(join(publicDirectory, 'index.html'), 'utf8'));
1869
2239
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...PAGE_GUARDS });
1870
2240
  return response.end(html);
1871
2241
  }
1872
- if (request.method === 'GET' && ['/app.js', '/nostromo-engine.js', '/brands.js', '/troubleshooting.js', '/inquiry.js', '/i18n.js', '/es.js', '/resay.js', '/syntax.js', '/editor.js', '/routing.js', '/abduction.js', '/review-ask.js', '/loader.js', '/tour.js', '/tour-chapters.js', '/touch.js', '/attribution.js', '/power.js', '/wallpaper.js', '/neural.js', '/hardware.js', '/code-tools.js', '/market.js', '/market-view.js', '/market-art.js'].includes(url.pathname)) {
2242
+ if (request.method === 'GET' && ['/app.js', '/nostromo-engine.js', '/brands.js', '/troubleshooting.js', '/inquiry.js', '/i18n.js', '/es.js', '/resay.js', '/syntax.js', '/editor.js', '/routing.js', '/abduction.js', '/review-ask.js', '/loader.js', '/tour.js', '/tour-chapters.js', '/touch.js', '/attribution.js', '/power.js', '/wallpaper.js', '/neural.js', '/hardware.js', '/code-tools.js', '/market.js', '/market-view.js', '/market-art.js', '/welcome.js', '/remedy.js', '/icons.js', '/page-errors.js', '/activity.js', '/terms.js', '/mcp-catalog.js', '/manual.js', '/manual-content.js', '/manual-shots.js', '/en.js'].includes(url.pathname)) {
1873
2243
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'text/javascript; charset=utf-8');
1874
2244
  }
1875
2245
  if (request.method === 'GET' && url.pathname === '/styles.css') {
1876
2246
  return sendAsset(request, response, join(publicDirectory, 'styles.css'), 'text/css; charset=utf-8');
1877
2247
  }
2248
+ // The user manual (public/manual.html, 1.0.5): read here, without a network, in the room's
2249
+ // language; and the same manual printed, in both languages (scripts/manual-pdf.mjs).
2250
+ if (request.method === 'GET' && url.pathname === '/manual') {
2251
+ const html = withHost(await readFile(join(publicDirectory, 'manual.html'), 'utf8'));
2252
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache', ...PAGE_GUARDS });
2253
+ return response.end(html);
2254
+ }
2255
+ if (request.method === 'GET' && url.pathname === '/manual.css') {
2256
+ return sendAsset(request, response, join(publicDirectory, 'manual.css'), 'text/css; charset=utf-8');
2257
+ }
2258
+ if (request.method === 'GET' && (url.pathname === '/assets/manual/madre-manual-es.pdf' || url.pathname === '/assets/manual/madre-manual-en.pdf')) {
2259
+ // The PDFs no longer travel in the package (QA 1.1.0, NUE-34: 5.7 MB of it): a copy run from
2260
+ // the source still has them; one installed from npm sends the browser to madre.run's.
2261
+ const local = join(publicDirectory, url.pathname.slice(1));
2262
+ if (await stat(local).then((found) => found.isFile(), () => false)) return sendAsset(request, response, local, 'application/pdf');
2263
+ response.writeHead(302, { location: `https://madre.run${url.pathname}`, 'cache-control': 'no-store' });
2264
+ return response.end();
2265
+ }
2266
+ // Its pictures: MADRE itself, photographed in each language (scripts/manual-shots.mjs). Only
2267
+ // a name of letters and dashes, so no path leaves the folder.
2268
+ if (request.method === 'GET' && /^\/assets\/manual\/shots\/(es|en)-[a-z]+\.webp$/.test(url.pathname)) {
2269
+ return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'image/webp');
2270
+ }
2271
+ // WebP since 1.1.0 (QA 1.1.0, NUE-34): four PNGs were 8.9 MB of a 22.5 MB package.
1878
2272
  const abductionAssets = new Map([
1879
- ['/assets/abduction-cat.png', 'abduction-cat.png'],
1880
- ['/assets/abduction-cat-blink.png', 'abduction-cat-blink.png'],
1881
- ['/assets/abduction-cat-control-left.png', 'abduction-cat-control-left.png'],
1882
- ['/assets/abduction-cat-control-right.png', 'abduction-cat-control-right.png'],
2273
+ ['/assets/abduction-cat.webp', 'abduction-cat.webp'],
2274
+ ['/assets/abduction-cat-blink.webp', 'abduction-cat-blink.webp'],
2275
+ ['/assets/abduction-cat-control-left.webp', 'abduction-cat-control-left.webp'],
2276
+ ['/assets/abduction-cat-control-right.webp', 'abduction-cat-control-right.webp'],
1883
2277
  ]);
1884
2278
  // The brand: its typefaces (SIL OFL, licences beside them) and the favicon, served from the
1885
2279
  // package itself. Nothing is fetched from a font service: the room never leaves this machine
@@ -1898,6 +2292,8 @@ export async function createPulseServer({
1898
2292
  ['/assets/brand/OFL-Sora.txt', 'text/plain; charset=utf-8'],
1899
2293
  ['/assets/brand/OFL-JetBrainsMono.txt', 'text/plain; charset=utf-8'],
1900
2294
  ['/assets/brand/madre-favicon.svg', 'image/svg+xml'],
2295
+ // The app's mark, on the user manual's cover (public/manual.js).
2296
+ ['/assets/brand/madre-app.svg', 'image/svg+xml'],
1901
2297
  // The conversation's wallpapers (Appearance): twelve pictures, encoded by hand from their
1902
2298
  // masters (cwebp), whose light and dark, layer or mesh and intensity are layers in the CSS.
1903
2299
  ['/assets/wallpapers/jarrito.webp', 'image/webp'],
@@ -1913,6 +2309,21 @@ export async function createPulseServer({
1913
2309
  ['/assets/wallpapers/tradicion.webp', 'image/webp'],
1914
2310
  ['/assets/wallpapers/urbania.webp', 'image/webp'],
1915
2311
  // The pictures of the «what's new» board, one per thing it tells (src/whats-new.mjs).
2312
+ // 1.1 says it in each language: the pictures are MADRE itself, photographed in Spanish and in English.
2313
+ ['/assets/news/1.1/es/home.webp', 'image/webp'],
2314
+ ['/assets/news/1.1/es/chats.webp', 'image/webp'],
2315
+ ['/assets/news/1.1/es/market.webp', 'image/webp'],
2316
+ ['/assets/news/1.1/es/welcome.webp', 'image/webp'],
2317
+ ['/assets/news/1.1/es/permissions.webp', 'image/webp'],
2318
+ ['/assets/news/1.1/es/maps.webp', 'image/webp'],
2319
+ ['/assets/news/1.1/es/privacy.webp', 'image/webp'],
2320
+ ['/assets/news/1.1/en/home.webp', 'image/webp'],
2321
+ ['/assets/news/1.1/en/chats.webp', 'image/webp'],
2322
+ ['/assets/news/1.1/en/market.webp', 'image/webp'],
2323
+ ['/assets/news/1.1/en/welcome.webp', 'image/webp'],
2324
+ ['/assets/news/1.1/en/permissions.webp', 'image/webp'],
2325
+ ['/assets/news/1.1/en/maps.webp', 'image/webp'],
2326
+ ['/assets/news/1.1/en/privacy.webp', 'image/webp'],
1916
2327
  ['/assets/news/1.0/settings.webp', 'image/webp'],
1917
2328
  ['/assets/news/1.0/mother.webp', 'image/webp'],
1918
2329
  ['/assets/news/1.0/intents.webp', 'image/webp'],
@@ -1934,7 +2345,7 @@ export async function createPulseServer({
1934
2345
  if (request.method === 'GET' && abductionAssets.has(url.pathname)) {
1935
2346
  const image = await readFile(join(publicDirectory, 'assets', abductionAssets.get(url.pathname)));
1936
2347
  response.writeHead(200, {
1937
- 'content-type': 'image/png',
2348
+ 'content-type': 'image/webp',
1938
2349
  'content-length': image.length,
1939
2350
  'cache-control': 'public, max-age=86400',
1940
2351
  });
@@ -2022,7 +2433,18 @@ export async function createPulseServer({
2022
2433
  return sendJson(response, 403, { error: t('This is done on the Mac.') });
2023
2434
  }
2024
2435
  if (request.method === 'GET' && url.pathname === '/salas') {
2025
- const html = await readFile(join(publicDirectory, 'salas-mac.html'));
2436
+ // Home is one place (2026-10-28): a project asked for it sends the page to Home's own address
2437
+ // when Home is open, so closing that project from there never takes Home's page with it.
2438
+ const homeId = salasRoomId(root);
2439
+ const host = String(request.headers.host ?? '');
2440
+ if (basename(roomDir) !== homeId && /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) {
2441
+ const home = (await knownRooms(root).catch(() => [])).find((one) => one.id === homeId && one.open?.port);
2442
+ if (home && String(home.open.port) !== String(request.socket.localPort)) {
2443
+ response.writeHead(302, { location: `http://${host.replace(/:\d+$/, '')}:${home.open.port}/salas${url.search}${url.hash ?? ''}`, 'cache-control': 'no-store' });
2444
+ return response.end();
2445
+ }
2446
+ }
2447
+ const html = withHost(await readFile(join(publicDirectory, 'salas-mac.html'), 'utf8'));
2026
2448
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache', ...PAGE_GUARDS });
2027
2449
  return response.end(html);
2028
2450
  }
@@ -2030,6 +2452,31 @@ export async function createPulseServer({
2030
2452
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), url.pathname.endsWith('.js') ? 'text/javascript; charset=utf-8' : 'text/css; charset=utf-8');
2031
2453
  }
2032
2454
  // A widget of Home, read here (homeWidget above): only from this Mac's own pages.
2455
+ // Another copy of the author's, left out of the usage figures by its identifier (Settings ›
2456
+ // Version on that copy). Only from this computer's page, and only with the author's key.
2457
+ if (request.method === 'POST' && url.pathname === '/api/salas/usage/exclude') {
2458
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
2459
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
2460
+ if (!token) return sendJson(response, 404, { error: t('Home has no widget by that name.') });
2461
+ const { id } = await body(request);
2462
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(String(id ?? '').trim())) return sendJson(response, 400, { error: t('That is not a copy\'s identifier. Copy it from Settings › Version on that copy.') });
2463
+ const answer = await reportFetch(process.env.PULSE_USAGE_URL ?? 'https://madre.run/api/usage', { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify({ exclude: String(id).trim().toLowerCase() }), signal: AbortSignal.timeout(8000) }).catch(() => null);
2464
+ const result = answer?.ok ? await answer.json().catch(() => null) : null;
2465
+ if (!result?.ok) return sendJson(response, 502, { error: t('madre.run did not answer. Try again in a moment.') });
2466
+ widgetReadings.delete('usage');
2467
+ return sendJson(response, 200, { ok: true });
2468
+ }
2469
+ // The author marks a failure as known, fixed or not worth it (the «MADRE errors» widget): the
2470
+ // same token, from this Mac's own page only.
2471
+ if (request.method === 'POST' && url.pathname === '/api/salas/errors/status') {
2472
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
2473
+ const site = request.headers['sec-fetch-site'];
2474
+ if (!token || viaPhone || (site !== undefined && site !== 'same-origin')) return sendJson(response, 404, { error: t('Not found.') });
2475
+ const payload = await body(request).catch(() => ({}));
2476
+ const answer = await reportFetch(process.env.PULSE_TELEMETRY_READ_URL ?? 'https://madre.run/api/telemetry', { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify({ fp: payload.fp, status: payload.status }), signal: AbortSignal.timeout(8000) }).catch(() => null);
2477
+ widgetReadings.delete('errors');
2478
+ return sendJson(response, answer?.ok ? 200 : 502, { ok: Boolean(answer?.ok) });
2479
+ }
2033
2480
  if (request.method === 'GET' && url.pathname === '/api/salas/widget') {
2034
2481
  const reading = await homeWidget(String(url.searchParams.get('kind') ?? ''));
2035
2482
  if (!reading) return sendJson(response, 404, { error: t('Home has no widget by that name.') });
@@ -2049,7 +2496,14 @@ export async function createPulseServer({
2049
2496
  if (!salasRoom) ids.push(thisRoomId);
2050
2497
  for (const id of ids) if (id !== salasId && !(id in rooms)) rooms[id] = localAiFor(before, id).chosen;
2051
2498
  }
2052
- await updateConfig(root, localAiPatch(before, { mode: patch?.mode, rooms }));
2499
+ // The model for the whole computer: one Ollama has installed, or null to let MADRE pick.
2500
+ let model;
2501
+ if (patch?.model === null) model = null;
2502
+ else if (typeof patch?.model === 'string') {
2503
+ if (!(ollama.models ?? []).some((one) => one.name === patch.model)) return sendJson(response, 400, { error: t('That model is not installed. Download it first.') });
2504
+ model = patch.model;
2505
+ }
2506
+ await updateConfig(root, localAiPatch(before, { mode: patch?.mode, rooms, model }));
2053
2507
  await wireOllama({ probe: false });
2054
2508
  widgetReadings.delete('models');
2055
2509
  }
@@ -2066,19 +2520,22 @@ export async function createPulseServer({
2066
2520
  }));
2067
2521
  }
2068
2522
  const projects = known.map((one) => ({ id: one.id, name: one.name, open: Boolean(one.open), ...localAiFor(config, one.id) }));
2069
- return sendJson(response, 200, { ...localAiConfig(config), master: localAiFor(config).master, ollama: { running: Boolean(ollama.running), models: (ollama.models ?? []).length }, projects, later });
2523
+ return sendJson(response, 200, { ...localAiConfig(config), master: localAiFor(config).master, ollama: { running: Boolean(ollama.running), models: (ollama.models ?? []).length, using: ollama.chatModel ?? null, auto: ollama.autoModel ?? null }, projects, later });
2070
2524
  }
2071
2525
  if (request.method === 'GET' && url.pathname === '/api/salas') {
2072
2526
  const rooms = await knownRooms(root);
2073
2527
  const here = basename(roomDir);
2074
2528
  const own = await roomLooks(root);
2075
2529
  // A project that never chose its own wears the wallpaper every page shared before.
2076
- const before = (await readLooks(root)).looks['pulse.wallpaper'] ?? null;
2530
+ const shared = (await readLooks(root)).looks;
2531
+ const before = shared['pulse.wallpaper'] ?? null;
2077
2532
  const seen = await Promise.all(rooms.map(async (one) => ({
2078
2533
  ...one,
2079
2534
  here: one.id === here,
2080
2535
  glance: await lobbyGlance(one),
2081
2536
  wallpaper: own[one.id]?.wallpaper ?? before,
2537
+ // Its accent: its own, or Home's while it has none (1.0.5).
2538
+ accent: own[one.id]?.accent ?? shared['pulse.accent'] ?? 'madre',
2082
2539
  })));
2083
2540
  // The links in force (docs/MACROVERSO.md, fase 3c), each with what crossed: counted from the
2084
2541
  // lines the serving room keeps beside its record, never from a ledger. `salas` is the id of
@@ -2096,11 +2553,15 @@ export async function createPulseServer({
2096
2553
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || (site !== undefined && site !== 'same-origin' && site !== 'none')) return sendJson(response, 403, { error: t('This is done from Home, on this Mac.') });
2097
2554
  const here = basename(roomDir);
2098
2555
  const rooms = (await knownRooms(root)).filter((one) => one.open);
2556
+ // Each project's accent (src/looks.mjs): its own, or Home's while it has none.
2557
+ const owns = await roomLooks(root);
2558
+ const homeAccent = (await readLooks(root)).looks['pulse.accent'] ?? 'madre';
2099
2559
  const seen = await Promise.all(rooms.map(async (one) => ({
2100
2560
  id: one.id,
2101
2561
  name: one.name,
2102
2562
  port: one.open.port,
2103
2563
  here: one.id === here,
2564
+ accent: owns[one.id]?.accent ?? homeAccent,
2104
2565
  glance: one.id === here ? null : await askRoom(one.open.port, '/api/glance'),
2105
2566
  })));
2106
2567
  return sendJson(response, 200, { here, salas: salasRoomId(root), rooms: seen });
@@ -2161,7 +2622,7 @@ export async function createPulseServer({
2161
2622
  const listed = await listFolders({ path: url.searchParams.get('path') || null, home, stateRoot: root });
2162
2623
  if (listed.error === 'outside') return sendJson(response, 403, { error: t('Only folders inside your home folder.') });
2163
2624
  if (listed.error) return sendJson(response, 404, { error: t('That folder is not there.') });
2164
- return sendJson(response, 200, listed);
2625
+ return sendJson(response, 200, { ...listed, defaultParent: await defaultProjectsFolder(home) });
2165
2626
  }
2166
2627
  if (request.method === 'GET' && url.pathname === '/api/salas/suggestions') {
2167
2628
  return sendJson(response, 200, { suggestions: await suggestProjects({ home, stateRoot: root }) });
@@ -2185,6 +2646,10 @@ export async function createPulseServer({
2185
2646
  const settings = await ollamaSettings();
2186
2647
  const model = ollama.madreModel ?? ollama.chatModel;
2187
2648
  if (!ollama.running || !model || !settings.enabled || settings.agent === false) return sendJson(response, 200, { state: 'unavailable', sources, bullets: lobbyWork.bullets, at: lobbyWork.at || null, model: lobbyWork.model });
2649
+ // A small local model (under 14B) wrote summaries that said what nobody decided: «Se decidió
2650
+ // revisar el archivo /recordatorios…» (QA 1.1.0, NUE-32). It leaves them as they are.
2651
+ const billions = Number(/[:\-_](\d+(?:\.\d+)?)b\b/i.exec(String(model))?.[1]);
2652
+ if (Number.isFinite(billions) && billions < 14) return sendJson(response, 200, { state: 'plain', sources, bullets: null, at: null, model });
2188
2653
  const key = createHash('sha256').update(items.map((item) => `${item.room}:${item.chat}:${item.at}:${item.messages}`).join('|')).digest('hex').slice(0, 16);
2189
2654
  const asked = request.method === 'POST';
2190
2655
  const due = !lobbyWork.bullets || (lobbyWork.key !== key && Date.now() - lobbyWork.tried > 5 * 60 * 1000);
@@ -2283,19 +2748,31 @@ export async function createPulseServer({
2283
2748
  const host = String(request.headers.host ?? '');
2284
2749
  const site = request.headers['sec-fetch-site'];
2285
2750
  if (viaPhone || !/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || (site !== undefined && site !== 'same-origin' && site !== 'none') || request.headers.origin !== `http://${host}`) return sendJson(response, 403, { error: t('MADRE is turned off from its own page, on this computer.') });
2286
- const here = basename(roomDir);
2287
- const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
2288
- await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/close', { method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null)));
2289
- let left = others;
2290
- for (let tries = 0; tries < 60 && left.length; tries += 1) {
2291
- await new Promise((resolve) => setTimeout(resolve, 250));
2292
- const now = await knownRooms(root);
2293
- left = left.filter((one) => now.find((room) => room.id === one.id)?.open);
2294
- }
2295
- sendJson(response, 202, { closing: true, closed: others.length - left.length, stuck: left.map((one) => one.name) });
2751
+ const { closed, stuck } = await closeOtherRooms();
2752
+ sendJson(response, 202, { closing: true, closed, stuck });
2296
2753
  setTimeout(() => server.emit('madre:close'), 150);
2297
2754
  return undefined;
2298
2755
  }
2756
+ // Uninstalling MADRE (2026-10-29), from Home's Settings only (src/uninstall.mjs). GET says what
2757
+ // would go and what stays; POST, from a page of this computer, closes every open project the
2758
+ // way turning MADRE off does and — only once all of them closed — closes Home and takes away
2759
+ // what the plan said (startPulse listens for «madre:uninstall»). A project that did not
2760
+ // close keeps everything where it was: nothing is removed while something could still write.
2761
+ if (url.pathname === '/api/madre/uninstall' && (request.method === 'GET' || request.method === 'POST')) {
2762
+ const host = String(request.headers.host ?? '');
2763
+ if (!salasRoom || viaPhone || !/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) return sendJson(response, 403, { error: t('MADRE is uninstalled from Home, on this computer.') });
2764
+ const plan = await uninstallPlan({ stateRoot: root, install, name: PACKAGE.name });
2765
+ if (!plan.ok) return sendJson(response, 409, { error: t(plan.error) });
2766
+ if (request.method === 'GET') return sendJson(response, 200, planView(plan));
2767
+ const site = request.headers['sec-fetch-site'];
2768
+ if ((site !== undefined && site !== 'same-origin' && site !== 'none') || request.headers.origin !== `http://${host}`) return sendJson(response, 403, { error: t('MADRE is uninstalled from Home, on this computer.') });
2769
+ const payload = await body(request).catch(() => ({}));
2770
+ const { stuck } = await closeOtherRooms();
2771
+ if (stuck.length) return sendJson(response, 409, { error: t('These projects did not close, so nothing was removed: {list}. Close them from Home and try again.', { list: stuck.join(', ') }), stuck });
2772
+ sendJson(response, 202, { uninstalling: true, ...planView(plan), madeGo: payload?.made === true });
2773
+ setTimeout(() => server.emit('madre:uninstall', { plan, made: payload?.made === true }), 150);
2774
+ return undefined;
2775
+ }
2299
2776
  // This room, asked to close by Salas: what is running stops and the room closes the way a
2300
2777
  // signal closes it (startPulse listens). Nothing here ends the process itself.
2301
2778
  if (request.method === 'POST' && url.pathname === '/api/room/close') {
@@ -2303,6 +2780,27 @@ export async function createPulseServer({
2303
2780
  setTimeout(() => server.emit('madre:close'), 150);
2304
2781
  return undefined;
2305
2782
  }
2783
+ // Restart MADRE, from its own page on this computer (public/power.js, askRestart): every other
2784
+ // open project restarts itself, then this one. Each comes back on its own port, open as it was.
2785
+ if (request.method === 'POST' && url.pathname === '/api/madre/restart') {
2786
+ const host = String(request.headers.host ?? '');
2787
+ const site = request.headers['sec-fetch-site'];
2788
+ if (viaPhone || !/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || (site !== undefined && site !== 'same-origin' && site !== 'none') || request.headers.origin !== `http://${host}`) return sendJson(response, 403, { error: t('MADRE is restarted from its own page, on this computer.') });
2789
+ const here = basename(roomDir);
2790
+ const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
2791
+ const asked = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/restart', { method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer?.unreachable && !answer?.outdated).catch(() => false)));
2792
+ await room.record('room.restarting', { others: others.length });
2793
+ sendJson(response, 202, { restarting: true, others: others.length, stuck: others.filter((_, index) => !asked[index]).map((one) => one.name) });
2794
+ restartSelf(request.socket.localPort);
2795
+ return undefined;
2796
+ }
2797
+ // This room, asked by another MADRE process on this computer to restart (never by a page).
2798
+ if (request.method === 'POST' && url.pathname === '/api/room/restart') {
2799
+ if (viaPhone || request.headers.origin !== undefined) return sendJson(response, 403, { error: t('MADRE is restarted from its own page, on this computer.') });
2800
+ sendJson(response, 202, { restarting: true });
2801
+ restartSelf(request.socket.localPort);
2802
+ return undefined;
2803
+ }
2306
2804
  // ---------- ENLACES (docs/MACROVERSO.md, fase 3b) ----------
2307
2805
  // The side that serves a link. Another room on this Mac asks, from its own process, for the
2308
2806
  // notes a signed contract lets it read; every lock is here, in the room that hands them over,
@@ -2705,7 +3203,7 @@ export async function createPulseServer({
2705
3203
  if (request.method === 'GET' && url.pathname === '/api/state') {
2706
3204
  // `?chat=` reads another conversation, held open beside the one on screen; the room-wide
2707
3205
  // parts are the same, the record and what is running in it are that conversation's.
2708
- const here = await scopeOf(url);
3206
+ const here = await scopeOf(url, response);
2709
3207
  if (here.error) return sendJson(response, 404, here);
2710
3208
  const room = here.room;
2711
3209
  const store = here.store;
@@ -2715,7 +3213,9 @@ export async function createPulseServer({
2715
3213
  // The project's name as this system writes paths (WEB-11): the page cut it at «/», and on
2716
3214
  // Windows the name was the whole path, so the key for #3 never matched.
2717
3215
  projectName: basename(canonicalProjectRoot),
2718
- platform: process.platform,
3216
+ // The column Diagnostics reads its commands from (public/troubleshooting.js): WSL is Linux
3217
+ // inside Windows, and says so (2026-10-28).
3218
+ platform: await environmentOnce().then((one) => (one?.wsl ? 'wsl' : process.platform), () => process.platform),
2719
3219
  // Behind the bridge, the page is on a phone and knows it. On the Mac it learns whether a
2720
3220
  // phone is paired, so it keeps its place for the phone only when there is one.
2721
3221
  device: viaPhone ? { kind: phoneKind } : null,
@@ -2770,7 +3270,7 @@ export async function createPulseServer({
2770
3270
  const sinceValue = request.headers['last-event-id'] ?? url.searchParams.get('since');
2771
3271
  const since = sinceValue === undefined || sinceValue === null || sinceValue === '' ? null : Number(sinceValue);
2772
3272
  // `?chat=` watches a conversation held open beside the one on screen, on a feed of its own.
2773
- const here = await scopeOf(url);
3273
+ const here = await scopeOf(url, response);
2774
3274
  if (here.error) return sendJson(response, 404, here);
2775
3275
  const feed = here.main ? mainFeed : await watchHeld(here.entry);
2776
3276
  response.writeHead(200, {
@@ -2965,7 +3465,7 @@ export async function createPulseServer({
2965
3465
  return sendJson(response, error.status ?? 400, { error: error.message });
2966
3466
  }
2967
3467
  const name = decodeURIComponent(request.headers['x-pulse-filename'] ?? url.searchParams.get('name') ?? 'attachment');
2968
- const here = await scopeOf(url);
3468
+ const here = await scopeOf(url, response);
2969
3469
  if (here.error) return sendJson(response, 404, here);
2970
3470
  const record = await here.room.registerAttachment(await storeAttachment(attachmentsRoot, { name, bytes }));
2971
3471
  return sendJson(response, 201, { attachment: { id: record.id, name: record.name, fileName: record.fileName, size: record.size, contentType: record.contentType, url: `/api/files?root=attachments&path=${encodeURIComponent(record.fileName)}` } });
@@ -2981,7 +3481,8 @@ export async function createPulseServer({
2981
3481
  const now = Date.now();
2982
3482
  while (keyMisses.length && keyMisses[0] < now - 60000) keyMisses.shift();
2983
3483
  if (keyMisses.length >= 8) return sendJson(response, 429, { error: t('Too many wrong confirmations. Wait a minute and try again.') });
2984
- if (!keyHolds(overrideConfig, { mode, words: payload.words, designation: basename(canonicalProjectRoot) })) {
3484
+ if (onlyPressed(mode) && !pressedHere(request)) return sendJson(response, 403, { error: t('This is confirmed from MADRE\'s own page, on this computer.') });
3485
+ if (!keyHolds(overrideConfig, { mode, words: payload.words })) {
2985
3486
  keyMisses.push(now);
2986
3487
  return sendJson(response, 403, { error: t('That is not it. Try again, or cancel.'), denied: true });
2987
3488
  }
@@ -2997,7 +3498,8 @@ export async function createPulseServer({
2997
3498
  const now = Date.now();
2998
3499
  while (keyMisses.length && keyMisses[0] < now - 60000) keyMisses.shift();
2999
3500
  if (keyMisses.length >= 8) return sendJson(response, 429, { error: t('Too many wrong confirmations. Wait a minute and try again.') });
3000
- if (!keyHolds(overrideConfig, { mode: 3, words: payload.words, designation: basename(canonicalProjectRoot) })) {
3501
+ if (onlyPressed(3) && !pressedHere(request)) return sendJson(response, 403, { error: t('This is confirmed from MADRE\'s own page, on this computer.') });
3502
+ if (!keyHolds(overrideConfig, { mode: 3, words: payload.words })) {
3001
3503
  keyMisses.push(now);
3002
3504
  return sendJson(response, 403, { error: t('That is not it. Try again, or cancel.'), denied: true });
3003
3505
  }
@@ -3015,8 +3517,96 @@ export async function createPulseServer({
3015
3517
  // This project's switch for the local AI (src/local-ai.mjs). In «auto» Home decides and the
3016
3518
  // switch does not move; /apply is how Home tells an open project the choice changed.
3017
3519
  if (request.method === 'GET' && url.pathname === '/api/local-ai') return sendJson(response, 200, { project: await localAiHere(), running: Boolean(ollama.running) });
3520
+ // Where Ollama is (2026-10-28): tried first, kept only when it answers, and every open project
3521
+ // told. Empty puts it back on this computer. Only from MADRE's own page on this computer, as
3522
+ // turning it off is: an address chosen by any other page would send the memory's text there.
3523
+ const ownPage = () => {
3524
+ const host = String(request.headers.host ?? '');
3525
+ const site = request.headers['sec-fetch-site'];
3526
+ return !viaPhone && /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) && (site === undefined || site === 'same-origin' || site === 'none') && request.headers.origin === `http://${host}`;
3527
+ };
3528
+ if (request.method === 'POST' && url.pathname === '/api/local-ai/host') {
3529
+ if (!ownPage()) return sendJson(response, 403, { error: t('This is done from MADRE\'s own page, on this computer.') });
3530
+ if (ollamaHostFromLaunch) return sendJson(response, 409, { error: t('MADRE was started with an Ollama address of its own (PULSE_OLLAMA_HOST or OLLAMA_HOST). Start it without it to choose one here.') });
3531
+ const payload = await body(request).catch(() => ({}));
3532
+ const said = String(payload.host ?? '').trim();
3533
+ let host = null;
3534
+ if (said) {
3535
+ let parsed = null;
3536
+ try { parsed = new URL(/^https?:\/\//i.test(said) ? said : `http://${said}`); } catch { /* said below */ }
3537
+ if (!parsed || !['http:', 'https:'].includes(parsed.protocol) || !parsed.hostname) return sendJson(response, 400, { error: t('Write an address like 192.168.1.40 or http://192.168.1.40:11434.') });
3538
+ host = `${parsed.protocol}//${parsed.hostname.includes(':') && !parsed.hostname.startsWith('[') ? `[${parsed.hostname}]` : parsed.hostname}:${parsed.port || '11434'}`;
3539
+ const found = await probeOllama({ host, timeoutMs: 3000 });
3540
+ if (!found.running) return sendJson(response, 422, { error: t('Nothing answers at {host}. Check that Ollama is open on that computer and accepts connections from your network.', { host }) });
3541
+ }
3542
+ await updateConfig(root, { ollama: { host } });
3543
+ adoptOllamaHost(await readConfig(root));
3544
+ await wireOllama();
3545
+ const later = [];
3546
+ await Promise.all((await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId).map(async (one) => {
3547
+ const answer = await askRoom(one.open.port, '/api/local-ai/apply', { method: 'POST', timeoutMs: 6000 });
3548
+ if (answer.unreachable || answer.outdated) later.push(one.name);
3549
+ }));
3550
+ return sendJson(response, 200, { host, running: Boolean(ollama.running), models: (ollama.models ?? []).map((one) => one.name), later });
3551
+ }
3552
+ // A first talk with the local AI (the welcome's «try it», 2026-10-28): the model in use answers as
3553
+ // it writes, word by word, and remembers the last few turns — so it reads as talking to it, not
3554
+ // as a form that comes back. Plain text streamed as Ollama hands it over.
3555
+ // What @madre knows about where it lives (QA 1.1.0, NUE-06): asked «what is MADRE» in the
3556
+ // welcome, it answered «a system that lets me talk to you naturally», which says nothing.
3557
+ const LOCAL_TRY_SYSTEM = 'You are @madre, the AI that runs on this computer inside MADRE. MADRE is a place where several AIs (Claude, Codex, Gemini, OpenCode, Cursor and you) work on the person\'s projects: each project is a folder with its own conversations and memory, the AIs read and write in it only with the permission the person gives (#1 chat only, #2 create, #3 edit, #4 full access), every change has a restore point, and MADRE remembers what was decided. You answer for free and in private, from this computer or one of its network. Answer in one or two short, friendly sentences, in the language the person writes in.';
3558
+ if (request.method === 'POST' && url.pathname === '/api/local-ai/try') {
3559
+ if (!ownPage()) return sendJson(response, 403, { error: t('This is done from MADRE\'s own page, on this computer.') });
3560
+ if (!ollama.running || !ollama.chatModel) return sendJson(response, 412, { error: t('The local AI has no model to answer with yet.') });
3561
+ const payload = await body(request).catch(() => ({}));
3562
+ const said = Array.isArray(payload.messages) ? payload.messages : [{ role: 'user', content: String(payload.text ?? '') || 'hola' }];
3563
+ const turns = said.filter((one) => one && (one.role === 'user' || one.role === 'assistant') && typeof one.content === 'string' && one.content.trim())
3564
+ .slice(-10).map((one) => ({ role: one.role, content: one.content.slice(0, 600) }));
3565
+ if (!turns.length || turns.at(-1).role !== 'user') return sendJson(response, 400, { error: t('Write something to the local AI first.') });
3566
+ const stop = new AbortController();
3567
+ // The response's close, not the request's: the request's was over once its body was read, so
3568
+ // a page that went away left Ollama answering it for up to two minutes.
3569
+ response.on('close', () => { if (!response.writableFinished) stop.abort(); });
3570
+ let upstream = null;
3571
+ try {
3572
+ upstream = await reportFetch(`${ollama.host}/api/chat`, {
3573
+ method: 'POST',
3574
+ headers: { 'content-type': 'application/json' },
3575
+ body: JSON.stringify({ model: ollama.chatModel, stream: true, options: { temperature: 0.5, num_ctx: 4096 }, messages: [{ role: 'system', content: LOCAL_TRY_SYSTEM }, ...turns] }),
3576
+ signal: AbortSignal.any([stop.signal, AbortSignal.timeout(120000)]),
3577
+ });
3578
+ } catch (error) {
3579
+ return sendJson(response, 502, { error: t('The local AI did not answer: {error}', { error: error.message }) });
3580
+ }
3581
+ if (!upstream.ok) return sendJson(response, 502, { error: t('The local AI did not answer: {error}', { error: `HTTP ${upstream.status}` }) });
3582
+ response.writeHead(200, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-cache', 'x-madre-model': ollama.chatModel });
3583
+ const reader = upstream.body.getReader();
3584
+ const decoder = new TextDecoder();
3585
+ let buffer = '';
3586
+ try {
3587
+ for (;;) {
3588
+ const { value, done } = await reader.read();
3589
+ if (done) break;
3590
+ buffer += decoder.decode(value, { stream: true });
3591
+ let at;
3592
+ while ((at = buffer.indexOf('\n')) >= 0) {
3593
+ const line = buffer.slice(0, at).trim();
3594
+ buffer = buffer.slice(at + 1);
3595
+ if (!line) continue;
3596
+ let event = null;
3597
+ try { event = JSON.parse(line); } catch { continue; }
3598
+ if (event.message?.content) response.write(event.message.content);
3599
+ }
3600
+ }
3601
+ } catch { /* the page went away, or the model stopped: what was said is what it said */ }
3602
+ response.end();
3603
+ return;
3604
+ }
3018
3605
  if (request.method === 'POST' && url.pathname === '/api/local-ai/apply') {
3019
- const status = await wireOllama({ probe: false });
3606
+ // Probed again: the model chosen in Home may have been downloaded after this project last looked,
3607
+ // and where Ollama is may have changed.
3608
+ adoptOllamaHost(await readConfig(root));
3609
+ const status = await wireOllama();
3020
3610
  return sendJson(response, 200, { project: status.project });
3021
3611
  }
3022
3612
  if (request.method === 'POST' && url.pathname === '/api/local-ai') {
@@ -3046,6 +3636,59 @@ export async function createPulseServer({
3046
3636
  }
3047
3637
  return sendJson(response, 200, { settings: await applySettings(patch) });
3048
3638
  }
3639
+ // MADRE'S LICENSE AND PRIVACY NOTICE (src/terms.mjs, 2026-10-30): whether they were accepted on
3640
+ // this computer, and accepting them, from MADRE's own page only, with the diagnostics' switch as
3641
+ // the person left it. A phone paired to a Mac that accepted is never asked.
3642
+ if (url.pathname === '/api/terms' && request.method === 'GET') {
3643
+ const terms = viaPhone ? { accepted: true, version: null } : await readTerms(root);
3644
+ const before = !terms.accepted && ((await cameFromBefore(root)) || (hadInstallId && !existsSync(join(root, 'lifecycle.json'))));
3645
+ return sendJson(response, 200, { ...terms, before, language: roomLanguage(), languageChosen, diagnostics: await diagnosticsNow(), diagnosticsFixed: process.env.PULSE_TELEMETRY === '0', links: TERMS_LINKS });
3646
+ }
3647
+ if (url.pathname === '/api/terms' && request.method === 'POST') {
3648
+ const site = request.headers['sec-fetch-site'];
3649
+ if (viaPhone || (site !== undefined && site !== 'same-origin')) return sendJson(response, 403, { error: t('This is done on the computer.') });
3650
+ const payload = await body(request).catch(() => ({}));
3651
+ if (payload.accept !== true) return sendJson(response, 400, { error: t('MADRE needs its license accepted to work.') });
3652
+ const kept = await acceptTerms(root);
3653
+ if (typeof payload.diagnostics === 'boolean') {
3654
+ const current = (await readConfig(root)).telemetry ?? {};
3655
+ await updateConfig(root, { telemetry: { ...current, diagnostics: payload.diagnostics } });
3656
+ diagnosticsOn = payload.diagnostics && process.env.PULSE_TELEMETRY !== '0';
3657
+ diagnosticsReadAt = Date.now();
3658
+ if (!payload.diagnostics) await diagnostics.forget();
3659
+ }
3660
+ return sendJson(response, 200, { ...kept, diagnostics: await diagnosticsNow() });
3661
+ }
3662
+ // ANONYMOUS DIAGNOSTICS (src/telemetry.mjs): whether it is on, and the exact batch that would go
3663
+ // next, for Settings › Version and reports to show as it is. Turning it off forgets what waits.
3664
+ if (url.pathname === '/api/telemetry' && request.method === 'GET') {
3665
+ return sendJson(response, 200, { on: await diagnosticsNow(), env: process.env.PULSE_TELEMETRY === '0', next: await diagnostics.preview() });
3666
+ }
3667
+ if (url.pathname === '/api/telemetry' && request.method === 'POST') {
3668
+ if (viaPhone) return sendJson(response, 403, { error: t('This is changed on the computer.') });
3669
+ const payload = await body(request).catch(() => ({}));
3670
+ if (typeof payload.on !== 'boolean') return sendJson(response, 400, { error: t('Say on or off.') });
3671
+ const current = (await readConfig(root)).telemetry ?? {};
3672
+ await updateConfig(root, { telemetry: { ...current, diagnostics: payload.on } });
3673
+ diagnosticsOn = payload.on && process.env.PULSE_TELEMETRY !== '0';
3674
+ diagnosticsReadAt = Date.now();
3675
+ if (!payload.on) await diagnostics.forget();
3676
+ return sendJson(response, 200, { on: diagnosticsOn });
3677
+ }
3678
+ // A failure of the page itself (public/app.js and salas-mac.js listen for them): from MADRE's own
3679
+ // page only, a few a minute at most, and kept as a failure like any other.
3680
+ if (url.pathname === '/api/telemetry/page-error' && request.method === 'POST') {
3681
+ const site = request.headers['sec-fetch-site'];
3682
+ if (site !== undefined && site !== 'same-origin') return sendJson(response, 403, { error: 'origin' });
3683
+ const now = Date.now();
3684
+ while (pageErrors.length && pageErrors[0] < now - 60_000) pageErrors.shift();
3685
+ if (pageErrors.length >= 20) return sendJson(response, 429, { error: 'later' });
3686
+ pageErrors.push(now);
3687
+ const payload = await body(request).catch(() => ({}));
3688
+ const page = ['room', 'home', 'manual', 'phone'].includes(payload.page) ? payload.page : 'room';
3689
+ diagnostics.error({ kind: 'page', where: page, message: String(payload.message ?? '').slice(0, 2000), stack: String(payload.stack ?? '').slice(0, 4000) });
3690
+ return sendJson(response, 202, { kept: true });
3691
+ }
3049
3692
  // NOSTROMO: the archive is behind the project designation, like CONTROL.
3050
3693
  // Sentinel: reports, settings, the manual road (a prefilled issue) and the automatic one.
3051
3694
  if (request.method === 'GET' && url.pathname === '/api/sentinel') {
@@ -3130,13 +3773,13 @@ export async function createPulseServer({
3130
3773
  }
3131
3774
  if (request.method === 'GET' && url.pathname === '/api/questions') {
3132
3775
  const limit = Math.min(5, Math.max(1, Number(url.searchParams.get('limit') ?? 3) || 3));
3133
- const here = await scopeOf(url);
3776
+ const here = await scopeOf(url, response);
3134
3777
  if (here.error) return sendJson(response, 404, here);
3135
3778
  return sendJson(response, 200, { questions: here.room.questions({ limit }) });
3136
3779
  }
3137
3780
  if (request.method === 'GET' && url.pathname === '/api/decisions') {
3138
3781
  const limit = Math.min(5, Math.max(1, Number(url.searchParams.get('limit') ?? 3) || 3));
3139
- const here = await scopeOf(url);
3782
+ const here = await scopeOf(url, response);
3140
3783
  if (here.error) return sendJson(response, 404, here);
3141
3784
  return sendJson(response, 200, { decisions: here.room.decisions({ limit }) });
3142
3785
  }
@@ -3266,7 +3909,10 @@ export async function createPulseServer({
3266
3909
  // This project's own wallpaper («only in this project»), or back to the shared one with null.
3267
3910
  if (request.method === 'POST' && url.pathname === '/api/looks/room') {
3268
3911
  const payload = await body(request).catch(() => ({}));
3269
- const answer = await changeRoomLook(root, basename(roomDir), payload?.wallpaper ?? null);
3912
+ const change = {};
3913
+ if (payload && 'wallpaper' in payload) change.wallpaper = payload.wallpaper ?? null;
3914
+ if (payload && 'accent' in payload) change.accent = payload.accent ?? null;
3915
+ const answer = await changeRoomLook(root, basename(roomDir), Object.keys(change).length ? change : { wallpaper: null });
3270
3916
  return sendJson(response, answer.error ? 400 : 200, answer);
3271
3917
  }
3272
3918
  // How Home is arranged (src/looks.mjs, home.json): the same on every port Home is shown from.
@@ -3330,7 +3976,7 @@ export async function createPulseServer({
3330
3976
  if (request.method === 'POST' && url.pathname === '/api/messages/rate') {
3331
3977
  const payload = await body(request).catch(() => ({}));
3332
3978
  try {
3333
- const here = await scopeOf(url);
3979
+ const here = await scopeOf(url, response);
3334
3980
  if (here.error) return sendJson(response, 404, here);
3335
3981
  const event = await here.room.rateMessage(String(payload.messageId ?? ''), String(payload.rating ?? ''));
3336
3982
  return sendJson(response, 200, { rated: event.payload });
@@ -3375,11 +4021,12 @@ export async function createPulseServer({
3375
4021
  const fromHere = /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) && (site === undefined || site === 'same-origin' || site === 'none');
3376
4022
  if (request.method === 'GET' && url.pathname === '/api/tour') {
3377
4023
  const state = await readTour(root);
3378
- if (viaPhone || !fromHere) return sendJson(response, 200, { version: TOUR_VERSION, state, owed: false, returning: false, chapters: CHAPTERS, hints: HINTS });
4024
+ if (viaPhone || !fromHere) return sendJson(response, 200, { version: TOUR_VERSION, state, owed: false, returning: false, chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
3379
4025
  // Where this person comes from: the tour of 1.0 (path «since»), 0.7.2 (their words in a room's
3380
4026
  // record, path «back»), or nowhere — a first install.
3381
4027
  const from = state.path === 'since' || (!state.path && state.before === '1.0') ? '1.0' : (state.path ? state.path === 'back' : await cameBefore(root)) ? '0.7.2' : null;
3382
- return sendJson(response, 200, { version: TOUR_VERSION, state, owed: !state.bonjourAt, returning: Boolean(from), from, chapters: CHAPTERS, hints: HINTS });
4028
+ // `upgraded`: this copy was in use before 1.1.0 (src/terms.mjs): it meets the news, never the welcome of someone new.
4029
+ return sendJson(response, 200, { version: TOUR_VERSION, state, owed: !state.bonjourAt, returning: Boolean(from), from, upgraded: await cameFromBefore(root), chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
3383
4030
  }
3384
4031
  if (viaPhone || !fromHere || (request.method === 'POST' && request.headers.origin !== `http://${host}`)) return sendJson(response, 403, { error: t('This is done on the Mac.') });
3385
4032
  if (request.method === 'POST' && url.pathname === '/api/tour') {
@@ -3398,8 +4045,21 @@ export async function createPulseServer({
3398
4045
  }
3399
4046
  return sendJson(response, 404, { error: 'Not found' });
3400
4047
  }
4048
+ // Where this MADRE runs and what the computer is (src/environment.mjs, local-models.mjs), for the
4049
+ // welcome to adapt its steps: the system, WSL, a virtual machine, SSH, a screen, free space.
4050
+ if (request.method === 'GET' && url.pathname === '/api/environment') {
4051
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4052
+ const [environment, hardware, geminiKey, memorySaid] = await Promise.all([environmentOnce(), hardwareOnce(), imageKey().then(Boolean, () => false), memoryConfig()]);
4053
+ // With what the welcome needs to choose the memory's search (src/embeddings.mjs): whether a
4054
+ // Gemini key is already on this computer, and what is chosen now.
4055
+ return sendJson(response, 200, { environment, hardware, port: request.socket.localPort, geminiKey, memory: { embedProvider: memorySaid.embedProvider ?? 'auto', embedder: memory?.embedder?.model ?? null } });
4056
+ }
3401
4057
  if (request.method === 'GET' && url.pathname === '/api/version') {
3402
- return sendJson(response, 200, await versionView({ force: url.searchParams.get('force') === '1' }));
4058
+ // With the one thing the daily notice says about this copy: its random identifier, shown so the
4059
+ // person can see it, and so the author can leave out a copy of his own (the usage widget).
4060
+ // Its own field: under `install` it hid how this copy was installed, and a copy run from
4061
+ // source was offered a restart into a new version it cannot take (2026-10-29).
4062
+ return sendJson(response, 200, { ...(await versionView({ force: url.searchParams.get('force') === '1' })), copyId: await installId(root).catch(() => null) });
3403
4063
  }
3404
4064
  // One click: install the newer version and come back on the same port. The room records it,
3405
4065
  // closes its listener so the port is free, hands the command to a detached shell and exits.
@@ -3441,7 +4101,7 @@ export async function createPulseServer({
3441
4101
  }
3442
4102
  if (request.method === 'POST' && url.pathname === '/api/updates/settings') {
3443
4103
  const patch = await body(request).catch(() => ({}));
3444
- if (typeof patch.check === 'boolean') { updatesConfig = { ...updatesConfig, check: patch.check }; await updateConfig(root, { updates: updatesConfig }); }
4104
+ if (typeof patch.check === 'boolean') { updatesConfig = { ...updatesConfig, check: patch.check }; await updateConfig(root, { updates: updatesConfig }); await adoptBuiltinUpdates({ stateRoot: root, enabled: marketOn(), ...factoryKeyed }).catch(() => []); }
3445
4105
  return sendJson(response, 200, { updates: { check: updatesEnabled(), envWins: process.env.PULSE_UPDATE_CHECK !== undefined } });
3446
4106
  }
3447
4107
  if (request.method === 'GET' && url.pathname === '/api/mother') {
@@ -3497,7 +4157,7 @@ export async function createPulseServer({
3497
4157
  const mode = Math.min(4, Math.max(0, Number(url.searchParams.get('mode') ?? 1) || 0));
3498
4158
  const text = String(url.searchParams.get('text') ?? '').slice(0, 2000);
3499
4159
  const ash = url.searchParams.get('ash') === 'true';
3500
- const here = await scopeOf(url);
4160
+ const here = await scopeOf(url, response);
3501
4161
  if (here.error) return sendJson(response, 404, here);
3502
4162
  const room = here.room;
3503
4163
  const briefing = await room.briefing({ agent: asked, mode, text, ash });
@@ -3512,6 +4172,10 @@ export async function createPulseServer({
3512
4172
  if (request.method === 'GET' && url.pathname === '/api/chats') {
3513
4173
  return sendJson(response, 200, await chatsView());
3514
4174
  }
4175
+ // Search in the conversations (2026-10-30): by name and by what was said.
4176
+ if (request.method === 'GET' && url.pathname === '/api/chats/search') {
4177
+ return sendJson(response, 200, await searchChats(roomDir, String(url.searchParams.get('q') ?? '').slice(0, 200)));
4178
+ }
3515
4179
  if (request.method === 'POST' && url.pathname === '/api/chats') {
3516
4180
  if (room.busy() && !(await turnsPolicy()).enabled) return sendJson(response, 409, { error: t('A turn is running in this conversation. Let it finish, or STOP ALL, and try again.') });
3517
4181
  const payload = await body(request).catch(() => ({}));
@@ -3628,8 +4292,8 @@ export async function createPulseServer({
3628
4292
  const plan = await module.updatePlan(context, { latest: known?.latest ?? null, current: item.version ?? null });
3629
4293
  if (!plan?.command) return sendJson(response, 412, { error: plan?.note ?? 'There is no way to update this from here.', download: plan?.download ?? null });
3630
4294
  if (payload.confirm !== true) return sendJson(response, 200, { plan: { display: plan.display, note: plan.note ?? '' }, update: known });
3631
- if (installing) return sendJson(response, 409, { error: `Another install is running (${installing}).` });
3632
- installing = module.id;
4295
+ if (installing) return sendJson(response, 409, { error: t('Another install is running. Wait for it to finish and try again.') });
4296
+ installing = module.id; installingSince = Date.now();
3633
4297
  await room.record('extension.install.started', { id: module.id, name: item.name, command: plan.display, platforms: [], alreadyInstalled: true });
3634
4298
  void (async () => {
3635
4299
  const result = await runInstaller({ command: plan.command, args: plan.args, projectRoot: canonicalProjectRoot, timeoutMs: 900000, onLine: (line) => { void room.record('extension.install.output', { id: module.id, lines: [String(line).slice(0, 500)] }); } });
@@ -3716,8 +4380,8 @@ export async function createPulseServer({
3716
4380
  return sendJson(response, 403, { error: t('A key is only accepted from this computer, never over the network.') });
3717
4381
  }
3718
4382
  const agent = agents.find((item) => item.id === id);
3719
- if (!agent?.detected) return sendJson(response, 412, { error: `${agent?.label ?? id} is not installed on this computer.` });
3720
- if (!TAKES_KEY.has(id)) return sendJson(response, 400, { error: `${agent.label} signs in with a click, not with a key.` });
4383
+ if (!agent?.detected) return sendJson(response, 412, { error: t('{label} is not installed on this computer.', { label: agent?.label ?? id }) });
4384
+ if (!TAKES_KEY.has(id)) return sendJson(response, 400, { error: t('{agent} does not take a key here: it signs in with a click.', { agent: agent.label }) });
3721
4385
  const payload = await body(request).catch(() => ({}));
3722
4386
  const result = await applyKey({
3723
4387
  agent: id,
@@ -3768,7 +4432,27 @@ export async function createPulseServer({
3768
4432
  await runInstaller({ command: opencode.path, args: ['models', '--verbose'], projectRoot: canonicalProjectRoot, timeoutMs: 30000, onLine: (line) => { lines.push(line); } });
3769
4433
  return parseOpenCodeVerbose(lines);
3770
4434
  };
3771
- return sendJson(response, 200, { models: await discoverModels({ agents, config: await readConfig(root), listOpenCode: url.searchParams.get('opencode') === '1' ? listOpenCode : async () => [] }) });
4435
+ // Gemini's, from Google with the person's own key, read once in a while (src/outbound.mjs,
4436
+ // gemini-models). Signed in with a Google account and no key, there is nothing to ask.
4437
+ const listGemini = async () => {
4438
+ if (geminiModels.at && Date.now() - geminiModels.at < 10 * 60 * 1000) return geminiModels.ids;
4439
+ const key = await imageKey().catch(() => null);
4440
+ if (!key) return [];
4441
+ const answer = await fetch('https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000', { headers: { 'x-goog-api-key': key }, signal: AbortSignal.timeout(8000) });
4442
+ if (!answer.ok) return [];
4443
+ const ids = parseGeminiModels(await answer.json());
4444
+ if (ids.length) Object.assign(geminiModels, { at: Date.now(), ids });
4445
+ return ids;
4446
+ };
4447
+ // Cursor's own list, read once in a while: it asks Cursor's servers, so not on every call.
4448
+ const listCursor = async (cursor) => {
4449
+ if (cursorModels.at && Date.now() - cursorModels.at < 10 * 60 * 1000) return cursorModels.ids;
4450
+ const { stdout } = await execFileAsync(cursor.path, ['--list-models'], { timeout: 20000, env: { ...process.env, NO_OPEN_BROWSER: '1' } });
4451
+ const ids = parseCursorModels(stdout);
4452
+ if (ids.length) Object.assign(cursorModels, { at: Date.now(), ids });
4453
+ return ids;
4454
+ };
4455
+ return sendJson(response, 200, { models: await discoverModels({ agents, config: await readConfig(root), listOpenCode: url.searchParams.get('opencode') === '1' ? listOpenCode : async () => [], listCursor: url.searchParams.get('cursor') === '1' ? listCursor : async () => [], cursorOnlyAuto, listGemini: url.searchParams.get('gemini') === '1' ? listGemini : async () => [] }) });
3772
4456
  }
3773
4457
  // OpenCode's providers for AJUSTES: who has a key or an account, what each offers, which are
3774
4458
  // left out of the chooser. Never a key: only that one is there and of what kind.
@@ -3791,8 +4475,27 @@ export async function createPulseServer({
3791
4475
  const via = own ? 'own' : signed.get(id) ?? null;
3792
4476
  return { id, label: known?.label ?? providerLabel(id), keyUrl: known?.keyUrl ?? null, takesKey: Boolean(known), featured: Boolean(known?.featured), via, models: groups.get(id)?.models ?? [], hidden: hidden.has(id) };
3793
4477
  }).sort((a, b) => Number(Boolean(b.via)) - Number(Boolean(a.via)) || Number(a.via === 'own') - Number(b.via === 'own') || a.label.localeCompare(b.label));
4478
+ // A provider whose last turn was refused (no credit, a dead key) says so beside its name.
4479
+ const { problems } = await openCodeHealth(root);
4480
+ for (const provider of providers) provider.problem = problems[provider.id]?.kind ?? null;
3794
4481
  return sendJson(response, 200, { providers, default: process.env.PULSE_OPENCODE_MODEL ?? null });
3795
4482
  }
4483
+ // What to offer when an OpenCode turn failed on its provider: the model that answered last, or
4484
+ // one of OpenCode's own free models (src/opencode-health.mjs). Its own models are asked of the
4485
+ // CLI at most every ten minutes.
4486
+ if (request.method === 'GET' && url.pathname === '/api/agents/opencode/suggest') {
4487
+ const opencode = agents.find((agent) => agent.id === 'opencode');
4488
+ if (!opencode?.detected) return sendJson(response, 404, { error: t('OpenCode is not installed.') });
4489
+ if (!openCodeOwn.names || Date.now() - openCodeOwn.at > 600000) {
4490
+ const names = [];
4491
+ await runInstaller({ command: opencode.path, args: ['models', OPENCODE_OWN], projectRoot: canonicalProjectRoot, timeoutMs: 20000, onLine: (line) => { if (/^opencode\/[\w.:-]+$/.test(line.trim())) names.push(line.trim()); } }).catch(() => null);
4492
+ openCodeOwn.names = names;
4493
+ openCodeOwn.at = Date.now();
4494
+ }
4495
+ const health = await openCodeHealth(root);
4496
+ const failed = url.searchParams.get('failed') || process.env.PULSE_OPENCODE_MODEL || null;
4497
+ return sendJson(response, 200, { suggestion: suggestOpenCodeModel(health, { failed, own: openCodeOwn.names }), default: process.env.PULSE_OPENCODE_MODEL ?? null, problems: health.problems });
4498
+ }
3796
4499
  // A provider's key out of OpenCode, from this computer only, the same rule as putting one in.
3797
4500
  if (request.method === 'POST' && url.pathname === '/api/agents/opencode/providers/remove') {
3798
4501
  const address = request.socket.remoteAddress ?? '';
@@ -3816,7 +4519,7 @@ export async function createPulseServer({
3816
4519
  // One answer, not the room. The master brake lives next door and means something else.
3817
4520
  if (request.method === 'POST' && url.pathname === '/api/stop-turn') {
3818
4521
  const payload = await body(request).catch(() => ({}));
3819
- const here = await scopeOf(url);
4522
+ const here = await scopeOf(url, response);
3820
4523
  if (here.error) return sendJson(response, 404, here);
3821
4524
  const stopped = await here.room.stopTurn(String(payload.messageId ?? ''));
3822
4525
  return sendJson(response, stopped ? 200 : 404, stopped ? { stopped: true } : { error: t('That turn is not running any more.') });
@@ -3836,20 +4539,67 @@ export async function createPulseServer({
3836
4539
  return sendJson(response, 200, { turns: await turnsPolicy() });
3837
4540
  }
3838
4541
  if (request.method === 'POST' && url.pathname === '/api/stop-all') {
3839
- // Every conversation at work, not only the one on screen: the brake is the room's, not the chat's.
3840
- const result = await room.stopAll();
3841
- passes.clear();
3842
- await endCopilot('stopall');
3843
- for (const held of parked.values()) {
3844
- const more = await held.room.stopAll().catch(() => ({ plans: 0, turns: 0 }));
3845
- result.plans += more.plans ?? 0;
3846
- result.turns += more.turns ?? 0;
4542
+ return sendJson(response, 202, { stopped: true, ...await stopEverythingHere() });
4543
+ }
4544
+ // «En marcha» (2026-10-30): what runs in this project — or, asked with ?everywhere=1, in every
4545
+ // project open on this computer — what ended a moment ago, and the reminders coming.
4546
+ if (request.method === 'GET' && url.pathname === '/api/activity') {
4547
+ const mine = await activityHere();
4548
+ if (url.searchParams.get('everywhere') !== '1') return sendJson(response, 200, mine);
4549
+ const others = (await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId);
4550
+ const answers = await Promise.all(others.map(async (one) => {
4551
+ const answer = await askRoom(one.open.port, '/api/activity', { timeoutMs: 1500 });
4552
+ if (answer.unreachable) return null;
4553
+ if (answer.outdated) return { room: one.id, name: one.name, port: one.open.port, outdated: true, now: [], done: [] };
4554
+ return { ...answer, room: one.id, name: answer.name ?? one.name, port: one.open.port };
4555
+ }));
4556
+ const reminders = await readReminders(root).catch(() => []);
4557
+ const soonUntil = Date.now() + ACTIVITY_SOON_MS;
4558
+ const soon = reminders
4559
+ .filter((one) => !one.done && Date.parse(one.due) > Date.now() && Date.parse(one.due) <= soonUntil)
4560
+ .sort((a, b) => a.due.localeCompare(b.due)).slice(0, 5)
4561
+ .map(({ id, text, due, room: where, project, chat }) => ({ id, text, due, room: where, project, chat }));
4562
+ return sendJson(response, 200, { at: new Date().toISOString(), here: thisRoomId, projects: [{ ...mine, here: true }, ...answers.filter(Boolean)], soon });
4563
+ }
4564
+ // A brake from «En marcha»: one turn, one plan or one command, here or in another open project
4565
+ // (passed on to it, never from a phone); or everything everywhere.
4566
+ if (request.method === 'POST' && url.pathname === '/api/activity/stop') {
4567
+ const payload = await body(request).catch(() => ({}));
4568
+ if (payload.room && payload.room !== thisRoomId) {
4569
+ if (viaPhone) return sendJson(response, 403, { error: t('Other projects are stopped from this computer.') });
4570
+ const there = (await knownRooms(root)).find((one) => one.id === payload.room && one.open);
4571
+ if (!there) return sendJson(response, 404, { error: t('That project is not open any more.') });
4572
+ const answer = await askRoom(there.open.port, '/api/activity/stop', { method: 'POST', body: { ...payload, room: null }, timeoutMs: 8000 });
4573
+ if (answer.outdated) return sendJson(response, 409, { error: t('That project runs an older MADRE. Update it, or close it from its terminal.'), outdated: true });
4574
+ if (answer.unreachable) return sendJson(response, answer.status ?? 502, { error: answer.error ?? t('That project did not answer.') });
4575
+ return sendJson(response, 200, answer);
4576
+ }
4577
+ const chat = String(payload.chat ?? chatId);
4578
+ const where = chat === chatId ? room : parked.get(chat)?.room;
4579
+ if (!where) return sendJson(response, 404, { error: t('That is not running any more.') });
4580
+ let stopped = false;
4581
+ if (payload.kind === 'turn') stopped = await where.stopTurn(String(payload.messageId ?? ''));
4582
+ else if (payload.kind === 'plan') stopped = await where.stopPlan(String(payload.planId ?? ''));
4583
+ else if (payload.kind === 'run') {
4584
+ const id = String(payload.id ?? '');
4585
+ const cut = id.lastIndexOf(':');
4586
+ stopped = cut > 0 && where.stopRun({ responseMessageId: id.slice(0, cut), index: Number(id.slice(cut + 1)) });
4587
+ }
4588
+ return sendJson(response, stopped ? 200 : 404, stopped ? { stopped: true } : { error: t('That is not running any more.') });
4589
+ }
4590
+ if (request.method === 'POST' && url.pathname === '/api/activity/stop-all') {
4591
+ const result = await stopEverythingHere();
4592
+ let projects = 0;
4593
+ if (!viaPhone) {
4594
+ const others = (await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId);
4595
+ const stopped = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/stop-all', { method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer.unreachable && !answer.outdated)));
4596
+ projects = stopped.filter(Boolean).length;
3847
4597
  }
3848
- return sendJson(response, 202, { stopped: true, ...result });
4598
+ return sendJson(response, 202, { stopped: true, ...result, projects });
3849
4599
  }
3850
4600
  const stopMatch = request.method === 'POST' && url.pathname.match(/^\/api\/plans\/([0-9a-f-]+)\/stop$/);
3851
4601
  if (stopMatch) {
3852
- const here = await scopeOf(url);
4602
+ const here = await scopeOf(url, response);
3853
4603
  if (here.error) return sendJson(response, 404, here);
3854
4604
  const stopped = await here.room.stopPlan(stopMatch[1]);
3855
4605
  return sendJson(response, stopped ? 202 : 404, stopped ? { stopped: true } : { error: t('No running plan with that id.') });
@@ -3861,7 +4611,7 @@ export async function createPulseServer({
3861
4611
  const payload = await body(request).catch(() => ({}));
3862
4612
  const index = Number(payload.index);
3863
4613
  if (typeof payload.responseMessageId !== 'string' || !Number.isInteger(index) || index < 0) return sendJson(response, 400, { error: t('Name the request and the line to run.') });
3864
- const here = await scopeOf(url);
4614
+ const here = await scopeOf(url, response);
3865
4615
  if (here.error) return sendJson(response, 404, here);
3866
4616
  return here.room.stopRun({ responseMessageId: payload.responseMessageId, index }) ? sendJson(response, 202, { stopped: true }) : sendJson(response, 404, { error: t('That command is not running.') });
3867
4617
  }
@@ -3869,7 +4619,7 @@ export async function createPulseServer({
3869
4619
  const payload = await body(request).catch(() => ({}));
3870
4620
  const index = Number(payload.index);
3871
4621
  if (typeof payload.responseMessageId !== 'string' || !Number.isInteger(index) || index < 0) return sendJson(response, 400, { error: t('Name the request and the line to run.') });
3872
- const here = await scopeOf(url);
4622
+ const here = await scopeOf(url, response);
3873
4623
  if (here.error) return sendJson(response, 404, here);
3874
4624
  const outcome = await here.room.runRequested({ responseMessageId: payload.responseMessageId, index, returnCap: viaPhone ? PHONE_MAX_MODE : 3 });
3875
4625
  return sendJson(response, outcome.status, outcome.ok ? outcome.result : { error: outcome.error });
@@ -3878,7 +4628,7 @@ export async function createPulseServer({
3878
4628
  if (request.method === 'POST' && url.pathname === '/api/runs/return') {
3879
4629
  const payload = await body(request).catch(() => ({}));
3880
4630
  if (typeof payload.responseMessageId !== 'string') return sendJson(response, 400, { error: t('Say which request to hand back.') });
3881
- const here = await scopeOf(url);
4631
+ const here = await scopeOf(url, response);
3882
4632
  if (here.error) return sendJson(response, 404, here);
3883
4633
  const outcome = await here.room.returnRun({ responseMessageId: payload.responseMessageId, returnCap: viaPhone ? PHONE_MAX_MODE : 3 });
3884
4634
  return sendJson(response, outcome.status, outcome.ok ? outcome : { error: outcome.error });
@@ -3886,11 +4636,11 @@ export async function createPulseServer({
3886
4636
  if (request.method === 'GET' && url.pathname === '/api/commands') {
3887
4637
  const ctx = await moduleContext();
3888
4638
  const fromModules = await Promise.all(moduleCommands().map(async (command) => {
3889
- const settings = command.module.settingsFrom(ctx.config);
4639
+ const settings = command.module.settingsFrom(ctx.config, ctx.roomId);
3890
4640
  const on = command.module.kind !== 'builtin' || Boolean(settings.enabled);
3891
4641
  let available = on;
3892
4642
  if (on && command.available) { try { available = Boolean(await command.available({ ...ctx, settings })); } catch { available = false; } }
3893
- return { name: command.name, module: command.module.id, title: command.title, usage: command.usage, summary: command.summary, available };
4643
+ return { name: command.name, module: command.module.id, title: inRoomLanguage(command.title), usage: inRoomLanguage(command.usage), summary: inRoomLanguage(command.summary), available };
3894
4644
  }));
3895
4645
  return sendJson(response, 200, { commands: [...(await listCommands({ projectRoot: canonicalProjectRoot })), ...fromModules] });
3896
4646
  }
@@ -3908,16 +4658,22 @@ export async function createPulseServer({
3908
4658
  const own = moduleCommands().find((item) => item.name === parsed.name);
3909
4659
  if (!own) return sendJson(response, 404, { error: `Unknown command /${parsed.name}.` });
3910
4660
  const ctx = await moduleContext();
3911
- const settings = own.module.settingsFrom(ctx.config);
4661
+ // Turned on only in this project is on here (2026-10-19): read without the project, a
4662
+ // module switched on from its project's Market never had its command.
4663
+ const settings = own.module.settingsFrom(ctx.config, ctx.roomId);
3912
4664
  if (own.module.kind === 'builtin' && !settings.enabled) return sendJson(response, 412, { error: `/${parsed.name} belongs to ${own.module.name}, which is off. Enable it in MODULES.` });
3913
- if (own.available && !(await own.available({ ...ctx, settings }).catch(() => false))) return sendJson(response, 412, { error: `/${parsed.name} is not available here (${own.title}).` });
4665
+ if (own.available && !(await own.available({ ...ctx, settings }).catch(() => false))) return sendJson(response, 412, { error: `/${parsed.name} is not available here (${inRoomLanguage(own.title)}).` });
3914
4666
  try {
3915
4667
  const answer = await own.execute({ ...ctx, settings }, parsed.args);
3916
- result = { ok: answer?.ok !== false, title: answer?.title ?? own.title, text: String(answer?.text ?? '') };
3917
- } catch (error) { result = { ok: false, title: own.title, text: `/${parsed.name} failed: ${error.message}` }; }
4668
+ result = { ok: answer?.ok !== false, title: inRoomLanguage(answer?.title ?? own.title), text: String(answer?.text ?? '') };
4669
+ // A page of the module's own (a report to print, say): the card offers it as a key. Only
4670
+ // its own routes, /api/x/<id>/, on this room; never an address elsewhere.
4671
+ const href = typeof answer?.link?.href === 'string' ? answer.link.href : '';
4672
+ if (href.startsWith(`/api/x/${own.module.id}/`) && !/[\s"'<>\\]/.test(href) && href.length <= 400) result.link = { href, label: String(inRoomLanguage(answer.link.label) ?? '').slice(0, 80) || inRoomLanguage(own.title) };
4673
+ } catch (error) { result = { ok: false, title: inRoomLanguage(own.title), text: `/${parsed.name} failed: ${error.message}` }; }
3918
4674
  command = own;
3919
4675
  }
3920
- const here = await scopeOf(url);
4676
+ const here = await scopeOf(url, response);
3921
4677
  if (here.error) return sendJson(response, 404, here);
3922
4678
  const event = await here.room.recordCommand({ name: parsed.name, args: parsed.args, ...result });
3923
4679
  return sendJson(response, result.ok ? 200 : 422, { command: parsed.name, title: result.title, ok: result.ok, sequence: event.sequence });
@@ -3932,7 +4688,7 @@ export async function createPulseServer({
3932
4688
  if (request.method === 'GET' && url.pathname === '/api/market') {
3933
4689
  const kept = await keptCatalog({ stateRoot: root, ...marketKeyed });
3934
4690
  const read = kept ? (void syncMarket().catch(() => null), { catalog: kept }) : await syncMarket().catch(() => ({ catalog: null }));
3935
- return sendJson(response, 200, { catalog: read.catalog ?? null, off: !marketOn(), installed: await installedFromMarket(root), news: await marketNews(root), announce: await marketAnnouncements(root, read.catalog, MODULES.map((one) => one.id)), madre: PACKAGE.version });
4691
+ return sendJson(response, 200, { catalog: read.catalog ?? null, off: !marketOn(), installed: await installedFromMarket(root), licensed: await licensedIds(root), news: await marketNews(root), announce: await marketAnnouncements(root, read.catalog, MODULES.map((one) => one.id)), madre: PACKAGE.version });
3936
4692
  }
3937
4693
  if (request.method === 'POST' && url.pathname === '/api/market/seen') {
3938
4694
  await marketNewsSeen(root);
@@ -3952,13 +4708,59 @@ export async function createPulseServer({
3952
4708
  const catalog = (await keptCatalog({ stateRoot: root, ...marketKeyed })) ?? (await syncMarket({ force: true }).catch(() => ({}))).catalog;
3953
4709
  if (!catalog) return sendJson(response, 503, { error: t('MADRE could not reach the Market. Check your internet connection and try again.') });
3954
4710
  try {
3955
- const done = await installFromMarket({ ...marketTools(), id: String(payload.id ?? ''), catalog });
3956
- await room.record('extension.installed', { id: done.id, name: done.name, origin: 'market', version: done.version, by: 'you' });
4711
+ // First what it declares, for the person to read; then, with their yes, that same file.
4712
+ if (payload.review === true) return sendJson(response, 200, await installFromMarket({ ...marketTools(), id: String(payload.id ?? ''), catalog, review: true }));
4713
+ const done = await installFromMarket({ ...marketTools(), id: String(payload.id ?? ''), catalog, accept: typeof payload.accept === 'string' ? payload.accept : null });
4714
+ // Its name as the Market says it in the room's language, not the file's English one (QA 1.1.0,
4715
+ // NUE-31: «Before you push» in a Spanish room); and on, as the Market turns it on.
4716
+ const listed = catalog.modules?.find((one) => one.id === done.id);
4717
+ await room.record('extension.installed', { id: done.id, name: inRoomLanguage(listed?.name) || done.name, origin: 'market', version: done.version, by: 'you' });
3957
4718
  for (const one of await knownRooms(root)) {
3958
4719
  if (!one.open?.port || one.id === thisRoomId) continue;
3959
4720
  await fetch(`http://127.0.0.1:${one.open.port}/api/extensions/reload`, { method: 'POST' }).catch(() => null);
3960
4721
  }
3961
4722
  return sendJson(response, 200, { installed: done, extensions: await describeModules(await moduleContext()) });
4723
+ } catch (error) { return sendJson(response, error.code === 'REVIEW_FIRST' ? 409 : 422, { error: error.message, review: error.code === 'REVIEW_FIRST' }); }
4724
+ }
4725
+ // SENDING ONE'S OWN MODULE TO THE MARKET (2026-10-28, src/market-check.mjs): its entry, drafted
4726
+ // from the module and from what the person wrote before, checked as the repository's CI checks
4727
+ // it; ready, the two files in a folder of their own, shown in the computer's file browser, and
4728
+ // GitHub's page to add them. Nothing leaves this computer from here.
4729
+ if (request.method === 'POST' && url.pathname === '/api/market/submission') {
4730
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4731
+ const payload = await body(request).catch(() => ({}));
4732
+ const module = moduleById(String(payload.id ?? ''));
4733
+ if (!module?.external) return sendJson(response, 404, { error: t('Only a module you made can be sent to the Market.') });
4734
+ if ((await installedFromMarket(root))[module.id]) return sendJson(response, 409, { error: t('{name} came from the Market: its author sends its new versions.', { name: module.name }) });
4735
+ const text = await readFile(module.file, 'utf8').catch(() => null);
4736
+ if (text === null) return sendJson(response, 410, { error: t('The file of {name} is no longer where it was.', { name: module.name }) });
4737
+ const entry = await submissionDraft({ stateRoot: root, module, text, madre: PACKAGE.version, entry: payload.entry && typeof payload.entry === 'object' ? payload.entry : null });
4738
+ const check = await checkSubmission({ text, entry, name: `${module.id}.mjs` });
4739
+ const answer = { entry, ok: check.ok, problems: check.problems, faults: check.faults, fields: check.fields, undeclared: check.undeclared, reaches: check.reaches, shelves: COMMUNITY_SHELVES, licenses: COMMUNITY_LICENSES, repo: MARKET_REPO };
4740
+ if (payload.write !== true) return sendJson(response, 200, answer);
4741
+ if (!check.ok) return sendJson(response, 422, { ...answer, error: t('Fix what is marked first.') });
4742
+ const written = await writeSubmission({ stateRoot: root, text, entry });
4743
+ const shown = payload.reveal === true ? await openInBrowser(written.folder, await environmentOnce().catch(() => null)).catch(() => false) : false;
4744
+ return sendJson(response, 200, { ...answer, ...written, shown });
4745
+ }
4746
+ // A paid module's license (src/market-license.mjs): checked once with Lemon Squeezy when the
4747
+ // person activates it, kept here, and given back when they release it. Only from this Mac.
4748
+ if (request.method === 'POST' && (url.pathname === '/api/market/license' || url.pathname === '/api/market/license/release')) {
4749
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4750
+ const payload = await body(request).catch(() => ({}));
4751
+ const id = String(payload.id ?? '');
4752
+ try {
4753
+ if (url.pathname === '/api/market/license/release') {
4754
+ await releaseLicense({ stateRoot: root, id, fetchImpl: marketFetch, ...licenseKeyed });
4755
+ await room.record('market.license.released', { id });
4756
+ return sendJson(response, 200, { released: id, licensed: await licensedIds(root) });
4757
+ }
4758
+ const catalog = (await keptCatalog({ stateRoot: root, ...marketKeyed })) ?? (await syncMarket({ force: true }).catch(() => ({}))).catalog;
4759
+ const entry = catalog?.modules.find((one) => one.id === id);
4760
+ if (!entry) return sendJson(response, 404, { error: t('The Market has no module «{id}» to install.', { id }) });
4761
+ const done = await activateLicense({ stateRoot: root, entry, key: payload.key, installId: await installId(root), fetchImpl: marketFetch, ...licenseKeyed });
4762
+ await room.record('market.license.activated', { id });
4763
+ return sendJson(response, 200, { activated: done.id, licensed: await licensedIds(root) });
3962
4764
  } catch (error) { return sendJson(response, 422, { error: error.message }); }
3963
4765
  }
3964
4766
  // Home's view of which projects each module is on in (module-scope.mjs), and where the
@@ -4063,7 +4865,7 @@ export async function createPulseServer({
4063
4865
  return sendJson(response, result.status, result.body);
4064
4866
  }
4065
4867
  if (request.method === 'POST' && /^\/api\/control\/[\w-]+\/undo$/.test(url.pathname)) {
4066
- const here = await scopeOf(url);
4868
+ const here = await scopeOf(url, response);
4067
4869
  if (here.error) return sendJson(response, 404, here);
4068
4870
  const result = await here.room.undoControl(url.pathname.split('/')[3]);
4069
4871
  return sendJson(response, result.ok ? 200 : result.status ?? 400, result);
@@ -4071,7 +4873,7 @@ export async function createPulseServer({
4071
4873
  if (request.method === 'POST' && /^\/api\/modes\/[\w-]+\/decide$/.test(url.pathname)) {
4072
4874
  const requestId = url.pathname.split('/')[3];
4073
4875
  const { decision, key } = await body(request);
4074
- const here = await scopeOf(url);
4876
+ const here = await scopeOf(url, response);
4075
4877
  if (here.error) return sendJson(response, 404, here);
4076
4878
  if (!['once', 'plan', 'deny'].includes(decision)) return sendJson(response, 400, { error: t('Decision must be once, plan or deny.') });
4077
4879
  const asked = here.room.modeRequest(requestId);
@@ -4084,6 +4886,9 @@ export async function createPulseServer({
4084
4886
  return sendJson(response, result.ok ? 200 : 409, result);
4085
4887
  }
4086
4888
  if (request.method === 'POST' && url.pathname === '/api/messages') {
4889
+ // No turn before MADRE's license is accepted on this computer (src/terms.mjs): a page left open
4890
+ // from before, or a script, is told where to accept it.
4891
+ if (!viaPhone && !(await readTerms(root)).accepted) return sendJson(response, 403, { error: t('Accept MADRE\'s license in Home to start.'), terms: true });
4087
4892
  const payload = await body(request);
4088
4893
  // A phone asks up to #2. The bridge already said so; the room says it again, and records
4089
4894
  // where the message came from. Only the bridge's word counts for that, never the body's.
@@ -4095,7 +4900,7 @@ export async function createPulseServer({
4095
4900
  } else delete payload.via;
4096
4901
  // `?chat=` sends into a conversation held open beside the one on screen. TURNS counts it
4097
4902
  // like any other: the conversation on screen is one of the "others" when it is working.
4098
- const here = await scopeOf(url);
4903
+ const here = await scopeOf(url, response);
4099
4904
  if (here.error) return sendJson(response, 404, here);
4100
4905
  // A switch moved in Home since this project opened reaches it here (module-scope.mjs).
4101
4906
  applyModuleSwitches(here.room, await readConfig(root));
@@ -4141,6 +4946,13 @@ export async function createPulseServer({
4141
4946
  }
4142
4947
  sendJson(response, 404, { error: t('Not found.') });
4143
4948
  } catch (error) {
4949
+ // A route that broke is a failure of MADRE's, not of the request: told, with the route's shape
4950
+ // (its ids taken out) and MADRE's own lines it went through. A body that was not JSON is the
4951
+ // request's.
4952
+ if (!(error instanceof SyntaxError)) {
4953
+ const shape = url.pathname.replace(/\/[0-9a-f]{6,}(?=\/|$)/gi, '/:id').replace(/\/\d+(?=\/|$)/g, '/:n');
4954
+ diagnostics.error({ kind: 'route', where: `${request.method} ${shape}`, message: error?.message ?? String(error), stack: error?.stack ?? null });
4955
+ }
4144
4956
  sendJson(response, 400, { error: error.message });
4145
4957
  }
4146
4958
  });
@@ -4149,6 +4961,7 @@ export async function createPulseServer({
4149
4961
  // long-lived SSE responses must be ended before the native close runs.
4150
4962
  const nativeClose = server.close.bind(server);
4151
4963
  server.close = (callback) => {
4964
+ serverClosing = true;
4152
4965
  clearInterval(poller);
4153
4966
  serverSentinel.stop();
4154
4967
  clearTimeout(embedKick);
@@ -4159,8 +4972,10 @@ export async function createPulseServer({
4159
4972
  // off() also ends the streams of pages watching a conversation held open beside.
4160
4973
  for (const held of parked.values()) held.off();
4161
4974
  parked.clear();
4162
- shutdown.then(() => {
4163
- void broadcastPending().then(() => chatWrites).then(() => {
4975
+ // The catalog asked of madre.run at start may still be on its way: when the ask fails, a note
4976
+ // of it is written to the state folder, and the outbound log says the request went out.
4977
+ shutdown.then(lateWritesDone).then(() => marketSync?.catch(() => null)).then(() => {
4978
+ void broadcastPending().then(() => chatWrites).then(async () => {
4164
4979
  unsubscribe();
4165
4980
  unsubscribeSentinel();
4166
4981
  unsubscribeEyecat();
@@ -4170,7 +4985,7 @@ export async function createPulseServer({
4170
4985
  clients.clear();
4171
4986
  // The memory file closes last, once nothing else writes to it; WAL and shm go with it.
4172
4987
  try { memory?.close(); } catch { /* already closed */ }
4173
- void outbound.drain();
4988
+ await outbound.close().catch(() => null);
4174
4989
  releaseOpen();
4175
4990
  nativeClose(callback);
4176
4991
  server.closeIdleConnections?.();
@@ -4179,14 +4994,15 @@ export async function createPulseServer({
4179
4994
  return server;
4180
4995
  };
4181
4996
  server.on('close', () => quotaMonitor.stop());
4182
- server.on('close', () => { for (const timer of aliveTimers) clearTimeout(timer); });
4997
+ server.on('close', () => clearTimeout(reprobe));
4998
+ server.on('close', () => { for (const timer of [...aliveTimers, ...hereTimers]) clearTimeout(timer); });
4183
4999
 
4184
5000
  server.on('close', () => { void phone.stop(); });
4185
- return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone };
5001
+ return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms };
4186
5002
  }
4187
5003
 
4188
5004
  export async function startPulse({ port, projectRoot, openBrowser, openPath = '' }) {
4189
- const { server, agents, markOpen, phone } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources() });
5005
+ const { server, agents, markOpen, phone, salasRoom, closeOtherRooms } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources() });
4190
5006
  await new Promise((resolve, reject) => {
4191
5007
  server.once('error', reject);
4192
5008
  server.listen(port, '127.0.0.1', resolve);
@@ -4197,15 +5013,40 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
4197
5013
  // From here this room offers to host the phone's bridge, when there is a phone to reach it.
4198
5014
  phone.start();
4199
5015
  const url = `http://127.0.0.1:${address.port}`;
4200
- const ready = agents.filter((agent) => agent.ready).map((agent) => agent.label).join(', ') || 'none';
4201
- const detected = agents.filter((agent) => agent.detected).map((agent) => agent.label).join(', ') || 'none';
4202
- console.log(`\nMADRE is ready\n\n ${url}${openPath}\n Project: ${projectRoot}\n Ready: ${ready}\n Detected: ${detected}\n`);
4203
- if (openBrowser) openUrl(`${url}${openPath}`);
5016
+ // Installed is all this line knows: whether each one is signed in is asked in the room, and
5017
+ // «Ready: Codex, Claude…» before any sign-in told a newcomer the opposite (2026-10-19).
5018
+ const ready = agents.filter((agent) => agent.ready).map((agent) => agent.label).join(', ') || t('none');
5019
+ const broken = agents.filter((agent) => agent.detected && !agent.ready).map((agent) => agent.label).join(', ');
5020
+ // In the language MADRE speaks (QA 1.1.0, NUE-01): the terminal said «MADRE is ready» above
5021
+ // «Abre esta dirección…», and Home was called «Project: …/.pulse/salas», a folder of MADRE's own.
5022
+ const where = salasRoom ? t('Home: every project on this computer') : `${t('Project:')} ${projectRoot}`;
5023
+ console.log(`\n${t('MADRE is ready')}\n\n ${url}${openPath}\n ${where}\n ${t('Agents installed: {list} (who is signed in: Settings › Agents)', { list: ready })}\n${broken ? ` ${t('Found but not answering: {list}', { list: broken })}\n` : ''}`);
5024
+ // Not waited for: the signals below are set up while the browser opens.
5025
+ if (openBrowser) void openUrl(`${url}${openPath}`);
4204
5026
  // SIGHUP too: closing the Terminal the room was started in is a way of closing it.
5027
+ // Home closed this way closes what Turn MADRE off closes (2026-10-21): every open project, also
5028
+ // one opened from another project, whose process outlives Home on its own. A second signal while
5029
+ // they close is not caught again and ends Home at once.
4205
5030
  for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
4206
- process.once(signal, () => server.close(() => process.exit(0)));
5031
+ process.once(signal, async () => {
5032
+ if (salasRoom) await closeOtherRooms().catch(() => null);
5033
+ server.close(() => process.exit(0));
5034
+ });
4207
5035
  }
4208
5036
  // Salas asked this room to close: the same as a signal.
4209
5037
  server.once('madre:close', () => server.close(() => process.exit(0)));
5038
+ // Uninstalling (src/uninstall.mjs): the room closes as it does for a signal — every write done,
5039
+ // the memory file closed — and only then is what the plan named taken away, last thing before the
5040
+ // process ends, so nothing of MADRE's writes it back.
5041
+ server.once('madre:uninstall', ({ plan, made }) => server.close(async () => {
5042
+ // Said before anything goes (src/install-metrics.mjs): a copy uninstalled, with the diagnostics.
5043
+ if (!testMode && await diagnosticsNow().catch(() => false)) {
5044
+ diagnostics.count('life.uninstall');
5045
+ await diagnostics.flush({ fetchImpl: reportFetch }).catch(() => null);
5046
+ }
5047
+ const done = await removeMadre(plan, { made }).catch((error) => ({ removed: [], failed: [{ path: null, error: error.message }] }));
5048
+ console.log(done.failed.length ? `\nMADRE was uninstalled, except:\n${done.failed.map((one) => ` ${one.path ?? ''} ${one.error}`).join('\n')}\n` : '\nMADRE was uninstalled.\n');
5049
+ process.exit(0);
5050
+ }));
4210
5051
  return { server, url };
4211
5052
  }