@jossuealcala/madre 1.0.5 → 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 (278) hide show
  1. package/ADDITIONAL-TERMS.md +7 -2
  2. package/CHANGELOG.en.md +47 -1
  3. package/CHANGELOG.md +47 -1
  4. package/CONTRIBUTING.md +2 -2
  5. package/LICENSE +111 -661
  6. package/NOTICE +28 -23
  7. package/README.en.md +30 -101
  8. package/README.md +30 -103
  9. package/SECURITY.md +1 -0
  10. package/TRADEMARKS.en.md +13 -14
  11. package/TRADEMARKS.md +24 -26
  12. package/bin/madre.cjs +2 -2
  13. package/bin/madre.mjs +112 -40
  14. package/docs/REFERENCE.md +52 -5
  15. package/docs/SDK.md +21 -3
  16. package/docs/en/REFERENCE.md +52 -5
  17. package/docs/en/SDK.md +22 -3
  18. package/docs/sdk/hello-module.mjs +3 -0
  19. package/package.json +3 -2
  20. package/public/abduction.js +6 -6
  21. package/public/activity.js +425 -0
  22. package/public/app.js +2468 -435
  23. package/public/assets/abduction-cat-blink.webp +0 -0
  24. package/public/assets/abduction-cat-control-left.webp +0 -0
  25. package/public/assets/abduction-cat-control-right.webp +0 -0
  26. package/public/assets/abduction-cat.webp +0 -0
  27. package/public/assets/manual/shots/en-agents.webp +0 -0
  28. package/public/assets/manual/shots/en-chats.webp +0 -0
  29. package/public/assets/manual/shots/en-code.webp +0 -0
  30. package/public/assets/manual/shots/en-composer.webp +0 -0
  31. package/public/assets/manual/shots/en-connectors.webp +0 -0
  32. package/public/assets/manual/shots/en-continuity.webp +0 -0
  33. package/public/assets/manual/shots/en-coordinator.webp +0 -0
  34. package/public/assets/manual/shots/en-copilot.webp +0 -0
  35. package/public/assets/manual/shots/en-diagnostics.webp +0 -0
  36. package/public/assets/manual/shots/en-home.webp +0 -0
  37. package/public/assets/manual/shots/en-local.webp +0 -0
  38. package/public/assets/manual/shots/en-market.webp +0 -0
  39. package/public/assets/manual/shots/en-memory.webp +0 -0
  40. package/public/assets/manual/shots/en-modes.webp +0 -0
  41. package/public/assets/manual/shots/en-notes.webp +0 -0
  42. package/public/assets/manual/shots/en-settings.webp +0 -0
  43. package/public/assets/manual/shots/en-welcome.webp +0 -0
  44. package/public/assets/manual/shots/en-windows.webp +0 -0
  45. package/public/assets/manual/shots/es-agents.webp +0 -0
  46. package/public/assets/manual/shots/es-chats.webp +0 -0
  47. package/public/assets/manual/shots/es-code.webp +0 -0
  48. package/public/assets/manual/shots/es-composer.webp +0 -0
  49. package/public/assets/manual/shots/es-connectors.webp +0 -0
  50. package/public/assets/manual/shots/es-continuity.webp +0 -0
  51. package/public/assets/manual/shots/es-coordinator.webp +0 -0
  52. package/public/assets/manual/shots/es-copilot.webp +0 -0
  53. package/public/assets/manual/shots/es-diagnostics.webp +0 -0
  54. package/public/assets/manual/shots/es-home.webp +0 -0
  55. package/public/assets/manual/shots/es-local.webp +0 -0
  56. package/public/assets/manual/shots/es-market.webp +0 -0
  57. package/public/assets/manual/shots/es-memory.webp +0 -0
  58. package/public/assets/manual/shots/es-modes.webp +0 -0
  59. package/public/assets/manual/shots/es-notes.webp +0 -0
  60. package/public/assets/manual/shots/es-settings.webp +0 -0
  61. package/public/assets/manual/shots/es-welcome.webp +0 -0
  62. package/public/assets/manual/shots/es-windows.webp +0 -0
  63. package/public/assets/news/1.1/en/chats.webp +0 -0
  64. package/public/assets/news/1.1/en/home.webp +0 -0
  65. package/public/assets/news/1.1/en/maps.webp +0 -0
  66. package/public/assets/news/1.1/en/market.webp +0 -0
  67. package/public/assets/news/1.1/en/permissions.webp +0 -0
  68. package/public/assets/news/1.1/en/privacy.webp +0 -0
  69. package/public/assets/news/1.1/en/welcome.webp +0 -0
  70. package/public/assets/news/1.1/es/chats.webp +0 -0
  71. package/public/assets/news/1.1/es/home.webp +0 -0
  72. package/public/assets/news/1.1/es/maps.webp +0 -0
  73. package/public/assets/news/1.1/es/market.webp +0 -0
  74. package/public/assets/news/1.1/es/permissions.webp +0 -0
  75. package/public/assets/news/1.1/es/privacy.webp +0 -0
  76. package/public/assets/news/1.1/es/welcome.webp +0 -0
  77. package/public/attribution.js +15 -16
  78. package/public/brands.js +2 -2
  79. package/public/code-tools.js +2 -2
  80. package/public/editor.js +13 -13
  81. package/public/en.js +413 -4
  82. package/public/es.js +1345 -483
  83. package/public/hardware.js +2 -2
  84. package/public/i18n.js +2 -2
  85. package/public/icons.js +158 -0
  86. package/public/index.html +66 -48
  87. package/public/inquiry.js +2 -2
  88. package/public/loader.js +271 -2
  89. package/public/macroverso.js +60 -21
  90. package/public/manual-content.js +412 -169
  91. package/public/manual-shots.js +38 -34
  92. package/public/manual.css +20 -2
  93. package/public/manual.html +1 -1
  94. package/public/manual.js +54 -25
  95. package/public/market-art.js +47 -45
  96. package/public/market-view.js +111 -33
  97. package/public/market.js +132 -30
  98. package/public/mcp-catalog.js +2 -2
  99. package/public/neural.js +64 -8
  100. package/public/nostromo-engine.js +709 -40
  101. package/public/page-errors.js +29 -0
  102. package/public/power.js +350 -11
  103. package/public/remedy.js +89 -0
  104. package/public/resay.js +3 -2
  105. package/public/review-ask.js +12 -7
  106. package/public/routing.js +3 -3
  107. package/public/salas-mac.css +703 -24
  108. package/public/salas-mac.html +26 -14
  109. package/public/salas-mac.js +1254 -289
  110. package/public/salas.css +2 -2
  111. package/public/salas.html +3 -3
  112. package/public/salas.js +3 -3
  113. package/public/styles.css +2404 -291
  114. package/public/syntax.js +2 -2
  115. package/public/terms.js +152 -0
  116. package/public/touch.js +2 -2
  117. package/public/tour-chapters.js +10 -10
  118. package/public/tour.js +56 -8
  119. package/public/troubleshooting.js +182 -11
  120. package/public/wallpaper.js +4 -3
  121. package/public/welcome.js +923 -0
  122. package/src/activity.mjs +85 -0
  123. package/src/adapters/claude.mjs +61 -35
  124. package/src/adapters/codex.mjs +18 -5
  125. package/src/adapters/cursor.mjs +5 -3
  126. package/src/adapters/gemini.mjs +5 -3
  127. package/src/adapters/madre.mjs +3 -3
  128. package/src/adapters/opencode.mjs +73 -10
  129. package/src/adapters/process.mjs +14 -13
  130. package/src/adapters/subagents.mjs +159 -0
  131. package/src/asking.mjs +8 -2
  132. package/src/auth-probe.mjs +27 -10
  133. package/src/bridge/devices.mjs +2 -2
  134. package/src/bridge/handoff.mjs +2 -2
  135. package/src/bridge/host.mjs +2 -2
  136. package/src/bridge/network.mjs +2 -2
  137. package/src/bridge/policy.mjs +3 -3
  138. package/src/bridge/qr.mjs +2 -2
  139. package/src/bridge/server.mjs +2 -2
  140. package/src/builtin-updates.mjs +87 -0
  141. package/src/capabilities.mjs +2 -2
  142. package/src/chats.mjs +51 -2
  143. package/src/checkpoint.mjs +67 -9
  144. package/src/choices.mjs +2 -2
  145. package/src/cli-args.mjs +2 -2
  146. package/src/cold.mjs +2 -2
  147. package/src/commands.mjs +2 -2
  148. package/src/config.mjs +2 -2
  149. package/src/conversation-context.mjs +2 -2
  150. package/src/credentials.mjs +56 -16
  151. package/src/dataset.mjs +2 -2
  152. package/src/directives.mjs +2 -2
  153. package/src/distiller.mjs +2 -2
  154. package/src/embeddings.mjs +2 -2
  155. package/src/enlaces.mjs +2 -2
  156. package/src/environment.mjs +147 -0
  157. package/src/event-store.mjs +2 -2
  158. package/src/exam.mjs +2 -2
  159. package/src/extensions.mjs +2 -2
  160. package/src/eyecat-watch.mjs +2 -2
  161. package/src/eyecat.mjs +2 -2
  162. package/src/file-ops.mjs +2 -2
  163. package/src/files.mjs +2 -2
  164. package/src/github.mjs +2 -2
  165. package/src/heartbeat.mjs +2 -2
  166. package/src/history.mjs +2 -2
  167. package/src/i18n.mjs +9 -2
  168. package/src/image-studio.mjs +2 -2
  169. package/src/install-metrics.mjs +109 -0
  170. package/src/json-file.mjs +2 -2
  171. package/src/launch.mjs +2 -2
  172. package/src/lease.mjs +15 -4
  173. package/src/lobby-work.mjs +11 -4
  174. package/src/local-ai.mjs +2 -2
  175. package/src/looks.mjs +2 -2
  176. package/src/market-check.mjs +165 -0
  177. package/src/market-key.mjs +10 -2
  178. package/src/market-license.mjs +4 -4
  179. package/src/market-remote.mjs +54 -12
  180. package/src/maturity.mjs +2 -2
  181. package/src/mcp/connect.mjs +2 -2
  182. package/src/mcp/github-server.mjs +2 -2
  183. package/src/mcp/image-server.mjs +2 -2
  184. package/src/mcp/memory-server.mjs +2 -2
  185. package/src/mcp/proxy.mjs +2 -2
  186. package/src/mcp/smtp-server.mjs +2 -2
  187. package/src/memory-dashboard.mjs +2 -2
  188. package/src/memory-tools.mjs +2 -2
  189. package/src/memory.mjs +2 -2
  190. package/src/models.mjs +33 -3
  191. package/src/module-scope.mjs +2 -2
  192. package/src/modules/ahp.mjs +2 -2
  193. package/src/modules/ash-policy.mjs +2 -2
  194. package/src/modules/ash.mjs +2 -2
  195. package/src/modules/bishop-exam.mjs +2 -2
  196. package/src/modules/bishop-plan.mjs +2 -2
  197. package/src/modules/bishop.mjs +9 -3
  198. package/src/modules/choices.mjs +2 -2
  199. package/src/modules/correo.mjs +2 -2
  200. package/src/modules/enlaces.mjs +2 -2
  201. package/src/modules/git-pulse.mjs +2 -2
  202. package/src/modules/github.mjs +2 -2
  203. package/src/modules/helpers.mjs +2 -2
  204. package/src/modules/image-studio.mjs +2 -2
  205. package/src/modules/index.mjs +90 -5
  206. package/src/modules/intents-calibration.mjs +2 -2
  207. package/src/modules/intents-desk.mjs +4 -3
  208. package/src/modules/intents-observe.mjs +2 -2
  209. package/src/modules/intents-policy.mjs +2 -2
  210. package/src/modules/intents-try.mjs +2 -2
  211. package/src/modules/intents.mjs +2 -2
  212. package/src/modules/local-models.mjs +14 -11
  213. package/src/modules/mcp-connect.mjs +2 -2
  214. package/src/modules/notes.mjs +159 -20
  215. package/src/modules/ollama.mjs +9 -3
  216. package/src/modules/playwright.mjs +2 -2
  217. package/src/modules/reminders.mjs +356 -37
  218. package/src/modules/ripley.mjs +3 -3
  219. package/src/modules/runs.mjs +2 -2
  220. package/src/modules/sdk.mjs +38 -6
  221. package/src/modules/updates.mjs +2 -2
  222. package/src/mother.mjs +2 -2
  223. package/src/npm-launch.mjs +2 -2
  224. package/src/ollama.mjs +6 -4
  225. package/src/opencode-health.mjs +26 -6
  226. package/src/outbound.mjs +10 -2
  227. package/src/override.mjs +27 -22
  228. package/src/ports.mjs +2 -2
  229. package/src/prices.mjs +2 -2
  230. package/src/privacy.mjs +2 -2
  231. package/src/quota-monitor.mjs +2 -2
  232. package/src/quota-sources.mjs +2 -2
  233. package/src/request-guard.mjs +2 -2
  234. package/src/review-ask.mjs +4 -3
  235. package/src/room/archivist.mjs +2 -2
  236. package/src/room/attachments.mjs +2 -2
  237. package/src/room/budget.mjs +2 -2
  238. package/src/room/context.mjs +2 -2
  239. package/src/room/control.mjs +2 -2
  240. package/src/room/copilot.mjs +2 -2
  241. package/src/room/economy.mjs +2 -2
  242. package/src/room/escalation.mjs +2 -2
  243. package/src/room/ghost.mjs +2 -2
  244. package/src/room/guard.mjs +6 -4
  245. package/src/room/prompt.mjs +3 -3
  246. package/src/room/returns.mjs +2 -2
  247. package/src/room/runs.mjs +6 -4
  248. package/src/room/vectors.mjs +2 -2
  249. package/src/room.mjs +127 -31
  250. package/src/router.mjs +2 -2
  251. package/src/runs.mjs +2 -2
  252. package/src/runtime-detection.mjs +31 -5
  253. package/src/salas.mjs +31 -6
  254. package/src/sentinel-errors.mjs +13 -4
  255. package/src/server-sentinel.mjs +2 -2
  256. package/src/server.mjs +689 -80
  257. package/src/setup-trouble.mjs +33 -0
  258. package/src/setup.mjs +4 -4
  259. package/src/smtp.mjs +2 -2
  260. package/src/telemetry.mjs +266 -0
  261. package/src/terms.mjs +43 -0
  262. package/src/tour.mjs +39 -5
  263. package/src/uninstall.mjs +225 -0
  264. package/src/updates.mjs +2 -2
  265. package/src/usage-sentinel.mjs +2 -2
  266. package/src/vault.mjs +2 -2
  267. package/src/verdict.mjs +13 -10
  268. package/src/whats-new.mjs +97 -3
  269. package/public/assets/abduction-cat-blink.png +0 -0
  270. package/public/assets/abduction-cat-control-left.png +0 -0
  271. package/public/assets/abduction-cat-control-right.png +0 -0
  272. package/public/assets/abduction-cat.png +0 -0
  273. package/public/assets/manual/madre-manual-en.pdf +0 -0
  274. package/public/assets/manual/madre-manual-es.pdf +0 -0
  275. package/public/assets/manual/shots/en-modules.webp +0 -0
  276. package/public/assets/manual/shots/es-modules.webp +0 -0
  277. package/src/mcp/notes-server.mjs +0 -120
  278. package/src/reminder-time.mjs +0 -127
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 { hostFacts, inRoomLanguage, 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,6 +80,7 @@ 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';
@@ -80,7 +89,9 @@ import { CHAPTERS, HINTS, NEWS_LEVEL, TOUR_VERSION, cameBefore, changeTour, read
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
97
  import { discoverModels, groupOpenCode, openCodeHidden, parseCursorModels, parseGeminiModels, parseOpenCodeVerbose, providerLabel, OPENCODE_OWN } from './models.mjs';
@@ -92,7 +103,7 @@ const cursorModels = { at: 0, ids: [] };
92
103
  const geminiModels = { at: 0, ids: [] };
93
104
  import { observable } from './modules/intents-observe.mjs';
94
105
  import { summarizeHistory } from './history.mjs';
95
- import { noteOpenCodeTurn, openCodeHealth, suggestOpenCodeModel } from './opencode-health.mjs';
106
+ import { migrateOpenCodeHealth, noteOpenCodeTurn, openCodeHealth, suggestOpenCodeModel } from './opencode-health.mjs';
96
107
  import { normalizeMode, setImageModule } from './capabilities.mjs';
97
108
  import { resolveGeminiKey } from './image-studio.mjs';
98
109
  import { commandByName, listCommands, parseCommand } from './commands.mjs';
@@ -116,13 +127,16 @@ import { readHandoff, writeHandoff } from './bridge/handoff.mjs';
116
127
  import { changeHome, changeLooks, readHome, readLooks, changeRoomLook, roomLooks, WALLPAPER_BYTES, dropWallpaper, frameWallpaper, readWallpaper, saveWallpaper, wallpaperBytes } from './looks.mjs';
117
128
  import { localAiConfig, localAiFor, localAiPatch } from './local-ai.mjs';
118
129
  import { moduleOnIn, scopeView, settingsIn } from './module-scope.mjs';
130
+ import { COMMUNITY_LICENSES, COMMUNITY_SHELVES, MARKET_REPO, checkSubmission, submissionDraft, writeSubmission } from './market-check.mjs';
119
131
  import { forgetFromMarket, installFromMarket, installedFromMarket, keptCatalog, marketAnnounced, marketAnnouncements, marketNews, marketNewsSeen, refreshCatalog, updateFromMarket } from './market-remote.mjs';
120
132
  // Not moved project by project: the Coordinator is Home's, Git has no switch, and Local AI keeps
121
133
  // its own list of projects (local-ai.mjs).
122
134
  const NOT_BY_PROJECT = new Set(['bishop', 'git-pulse', 'ollama']);
123
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';
124
138
  import { activateLicense, licensedIds, releaseLicense } from './market-license.mjs';
125
- import { askRoom, associateProject, createProject, ensureSalasProject, forgetProject, isSalasRoom, knownRooms, listFolders, markProject, projectRoomId, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
139
+ import { askRoom, associateProject, createProject, defaultProjectsFolder, ensureSalasProject, forgetProject, isSalasRoom, knownRooms, listFolders, markProject, projectRoomId, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
126
140
  import { parseWork, recentWork, WORK_SYSTEM, workPrompt } from './lobby-work.mjs';
127
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';
128
142
  import { readContinuity } from './modules/ahp.mjs';
@@ -185,10 +199,15 @@ async function body(request, { limit = BODY_LIMIT } = {}) {
185
199
  return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
186
200
  }
187
201
 
188
- export function openUrl(url) {
189
- const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';
190
- const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
191
- 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;
192
211
  }
193
212
 
194
213
  // PULSE_AGENT_TIMEOUT_MS applies to every agent; PULSE_<AGENT>_TIMEOUT_MS
@@ -255,12 +274,17 @@ export async function createPulseServer({
255
274
  // fake, and the key their catalog is signed with.
256
275
  marketFetch = globalThis.fetch,
257
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,
258
279
  // Where a paid module's license is checked (src/market-license.mjs); tests hand in their own.
259
280
  licenseApi = null,
260
281
  // Ollama detection; tests hand in a fake probe. PULSE_OLLAMA=0 leaves Ollama alone entirely.
261
282
  ollamaProbe = process.env.PULSE_OLLAMA === '0' ? async () => ({ running: false, host: null, models: [], embedModel: null, chatModel: null, disabled: true }) : probeOllama,
262
283
  }) {
263
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'));
264
288
  // Read before this run creates anything: whether this person used MADRE before decides whether
265
289
  // an update has news to show them, or this is a first install with nothing to catch up on.
266
290
  const novelty = await bootWhatsNew({ root, version: PACKAGE.version }).catch(() => ({ returning: false }));
@@ -357,6 +381,28 @@ export async function createPulseServer({
357
381
  }
358
382
  return { closed: others.length - left.length, stuck: left.map((one) => one.name) };
359
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
+ }
360
406
  // How many memories of each kind, and how many travel into turns. Counted, never read out.
361
407
  function memoryCensus() {
362
408
  const all = memory ? memory.memories({ limit: 20000 }) : [];
@@ -403,6 +449,7 @@ export async function createPulseServer({
403
449
  // says so once, the next time a page asks (market/updates.json).
404
450
  const marketOn = () => process.env.PULSE_MARKET !== '0' && updatesEnabled();
405
451
  const marketKeyed = marketKey ? { publicKey: marketKey } : {};
452
+ const factoryKeyed = factoryKey ? { factoryKey } : {};
406
453
  const licenseKeyed = licenseApi ? { api: licenseApi } : {};
407
454
  // OpenCode's own free models, as its CLI lists them, read again at most every ten minutes.
408
455
  const openCodeOwn = { names: null, at: 0 };
@@ -412,11 +459,21 @@ export async function createPulseServer({
412
459
  if (!marketOn()) return Promise.resolve({ catalog: null, off: true });
413
460
  marketSync ??= (async () => {
414
461
  const read = await refreshCatalog({ stateRoot: root, fetchImpl: marketFetch, force, ...marketKeyed });
415
- 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
+ }
416
470
  return read;
417
471
  })().finally(() => { marketSync = null; });
418
472
  return marketSync;
419
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}`));
420
477
  void syncMarket().catch(() => null);
421
478
  const install = detectInstall({ projectRoot: canonicalProjectRoot });
422
479
  async function versionView({ force = false } = {}) {
@@ -525,7 +582,7 @@ export async function createPulseServer({
525
582
  async function homeWidget(kind) {
526
583
  const kept = widgetReadings.get(kind);
527
584
  // madre.run's count moves once a day: the author's reading is kept ten minutes, the Mac's thirty seconds.
528
- 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;
529
586
  let reading;
530
587
  if (kind === 'system') {
531
588
  const total = totalmem();
@@ -561,6 +618,27 @@ export async function createPulseServer({
561
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);
562
619
  const body = answer?.ok ? await answer.json().catch(() => null) : null;
563
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;
639
+ reading = body?.ok ? { available: true, ...body } : { available: false, status: answer?.status ?? 0 };
640
+ widgetReadings.set('metrics', { at: Date.now(), reading });
641
+ return reading;
564
642
  } else if (kind === 'coordinator' && !salasRoom) {
565
643
  // Home's page is served by every project too: the Coordinator's record is its own room's.
566
644
  const coordinator = (await knownRooms(root)).find((one) => one.id === salasRoomId(root));
@@ -788,6 +866,8 @@ export async function createPulseServer({
788
866
  memory.metaSet('local.announced', fifth.version);
789
867
  await room.record('local.present', {
790
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 } : {}),
791
871
  checked: checked?.ran ? { passed: Boolean(checked.passed), matched: checked.matched ?? 0, n: checked.n ?? 0, at: checked.at ?? null } : null,
792
872
  });
793
873
  }
@@ -804,6 +884,23 @@ export async function createPulseServer({
804
884
  return view;
805
885
  };
806
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));
807
904
  await wireOllama();
808
905
  const memoryServer = memory ? memoryServerFor({ dbFile: memory.file, projectRoot: canonicalProjectRoot }) : null;
809
906
  // MOTHER's channel to the crew: her seal's fingerprint lives in the memory
@@ -821,6 +918,16 @@ export async function createPulseServer({
821
918
  // a restart take them all back. Wrong keys are counted: a program trying words is slowed down.
822
919
  const passes = new Map(); // token -> { agent, mode, until, once }
823
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');
824
931
  const PASS_ONCE_MS = 30 * 60 * 1000;
825
932
  // `asked` is a window the human chose on an agent's request for this mode (2026-10-14): one of
826
933
  // the windows the project allows, never longer, and only for that agent and mode.
@@ -904,11 +1011,30 @@ export async function createPulseServer({
904
1011
  // Session state per agent, refreshed on demand from the connections panel.
905
1012
  let sessions = {};
906
1013
  let sessionsAt = null;
907
- async function refreshSessions() {
908
- 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;
909
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;
910
1033
  return sessions;
911
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(() => {});
912
1038
  void refreshSessions().catch((error) => console.error(`MADRE session probe failed: ${error.message}`));
913
1039
 
914
1040
  // Effective settings = environment + config file + live changes; the file
@@ -1021,6 +1147,8 @@ export async function createPulseServer({
1021
1147
  }
1022
1148
 
1023
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();
1024
1152
  // A sign-in in flight, as the room is allowed to see it: which door, the address to open, and
1025
1153
  // whether the CLI is waiting to be told the code that page gave back. Never the code itself.
1026
1154
  // A device sign-in's code is the opposite case: it is shown to be typed on the provider's page.
@@ -1029,12 +1157,12 @@ export async function createPulseServer({
1029
1157
 
1030
1158
  async function loginAgent(id, { method = null } = {}) {
1031
1159
  const agent = agents.find((item) => item.id === id);
1032
- if (!agent) return { status: 404, body: { error: `Unknown agent: ${id}.` } };
1033
- 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 ?? [] } };
1034
1162
  const plan = loginRunners[id]?.(agent, { method }) ?? loginPlanFor(agent, { method });
1035
- if (!plan) return { status: 404, body: { error: `No sign-in flow known for ${id}.` } };
1036
- 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 } };
1037
- 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 }) } };
1038
1166
  // A CLI with no sign-in command of its own (Gemini) signs in on its first question: its settings
1039
1167
  // are set before, and the run is stopped as soon as the credentials are written. It runs in an
1040
1168
  // empty folder, so that question never sees the project.
@@ -1046,7 +1174,7 @@ export async function createPulseServer({
1046
1174
  cwd = await mkdtemp(join(tmpdir(), 'madre-signin-'));
1047
1175
  } catch (error) {
1048
1176
  await flow.undo().catch(() => {});
1049
- 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 }) } };
1050
1178
  }
1051
1179
  }
1052
1180
  const env = { ...process.env, ...(plan.env ?? {}) };
@@ -1119,7 +1247,10 @@ export async function createPulseServer({
1119
1247
  const error = refused
1120
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.')
1121
1249
  : finished ? null : result.error ?? null;
1122
- 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) });
1123
1254
  loggingIn = null;
1124
1255
  loginRun = null;
1125
1256
  })();
@@ -1142,7 +1273,8 @@ export async function createPulseServer({
1142
1273
  }
1143
1274
 
1144
1275
  async function cancelLogin(id) {
1145
- 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);
1146
1278
  loginRun.child?.cancel?.();
1147
1279
  await room.record('connection.login.cancelled', { agent: id });
1148
1280
  return { status: 202, body: { cancelled: true } };
@@ -1177,13 +1309,13 @@ export async function createPulseServer({
1177
1309
  // other install, and looks again when it finishes. Nothing is written into the project.
1178
1310
  async function installAgent(id) {
1179
1311
  const agent = agents.find((item) => item.id === id);
1180
- if (!agent) return { status: 404, body: { error: `Unknown agent: ${id}.` } };
1181
- 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 }) } };
1182
1314
  const plan = installPlanFor(agent, { prefix: toolsPrefix() });
1183
- if (!plan) return { status: 404, body: { error: `MADRE does not know how to install ${id}.` } };
1315
+ if (!plan) return { status: 404, body: { error: t('MADRE does not know how to install {id}.', { id }) } };
1184
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 }) } };
1185
- if (installing) return { status: 409, body: { error: `Another install is running (${installing}).` } };
1186
- installing = `agent:${id}`;
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();
1187
1319
  await room.record('connection.install.started', { agent: id, label: agent.label, command: plan.display });
1188
1320
  void (async () => {
1189
1321
  const lines = [];
@@ -1198,7 +1330,7 @@ export async function createPulseServer({
1198
1330
  let where = 'system';
1199
1331
  // Walled out of the system folders: install into MADRE's own, where it will be found.
1200
1332
  if (result.code !== 0 && plan.fallback && looksLikeAdminProblem(`${lines.join('\n')}\n${result.error ?? ''}`)) {
1201
- 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() }) });
1202
1334
  result = await attempt(plan.fallback);
1203
1335
  where = 'madre';
1204
1336
  }
@@ -1214,6 +1346,8 @@ export async function createPulseServer({
1214
1346
  detected: Boolean(found?.detected),
1215
1347
  version: found?.version ?? null,
1216
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')}`),
1217
1351
  tail: lines.slice(-6),
1218
1352
  });
1219
1353
  installing = null;
@@ -1296,13 +1430,38 @@ export async function createPulseServer({
1296
1430
  const broadcastPending = () => pump(mainFeed);
1297
1431
  let unsubscribe = () => {};
1298
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
+ }
1299
1456
  // The error sentinel: failures MU/TH/UR cannot classify, and crashes, become
1300
1457
  // redacted reports in the ledger. Sending them anywhere is the human's call.
1301
- const telemetry = (await readConfig(root)).telemetry ?? {};
1302
1458
  const sentinel = new ErrorSentinel({
1459
+ told: (input) => diagnostics.error(input),
1303
1460
  pkg: PACKAGE,
1304
1461
  agents,
1305
- 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 },
1306
1465
  fetchImpl: reportFetch,
1307
1466
  emit: (type, payload) => writeFromOutside(room, type, payload),
1308
1467
  save: async (settings) => { const current = await readConfig(root); await updateConfig(root, { telemetry: { ...(current.telemetry ?? {}), ...settings } }); },
@@ -1421,11 +1580,32 @@ export async function createPulseServer({
1421
1580
  });
1422
1581
  }
1423
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
+ }
1424
1604
  function wireRoom() {
1425
1605
  unsubscribe = room.subscribe(() => { void broadcastPending(); });
1426
1606
  unsubscribeModules = wireModules(room, chatId);
1427
1607
  unsubscribeAsks = trackAsks(room, historicalEvents);
1428
- unsubscribeSentinel = room.subscribe((event) => { void sentinel.observe(event).catch(() => null); });
1608
+ unsubscribeSentinel = room.subscribe((event) => { void sentinel.observe(event).catch(() => null); countForDiagnostics(event); });
1429
1609
  unsubscribeEyecat = room.subscribe((event) => { void eyecat.observe(event).catch(() => null); });
1430
1610
  unsubscribeGhost = room.subscribeGhost((event) => { for (const client of clients.keys()) writeEvent(client, event); });
1431
1611
  unsubscribeLive = room.subscribeLive((event) => { for (const client of clients.keys()) writeEvent(client, event); });
@@ -1467,6 +1647,32 @@ export async function createPulseServer({
1467
1647
  // always: opening a held conversation takes the room that is already there. When nothing is
1468
1648
  // running in it and nobody is watching, it closes itself.
1469
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
+ }
1470
1676
  const sayToAll = (type, payload) => {
1471
1677
  const event = { id: `live-${randomUUID()}`, sequence: null, live: true, timestamp: new Date().toISOString(), type, payload };
1472
1678
  for (const client of clients.keys()) writeEvent(client, event);
@@ -1494,9 +1700,39 @@ export async function createPulseServer({
1494
1700
  // every few hours; the day it was already said, nothing goes.
1495
1701
  // The author's own copies say nothing (2026-10-20): a copy that holds the author's usage key is
1496
1702
  // one of his, and it would only count him in his own figures.
1497
- const sayAlive = () => { void readSecret(root, OWNER_VAULT, 'usage').catch(() => null).then((owner) => (owner ? null : heartbeat({ root, version: PACKAGE.version, fetchImpl: reportFetch }))); };
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
+ };
1498
1725
  const aliveTimers = testMode ? [] : [setTimeout(sayAlive, 20_000), setInterval(sayAlive, 6 * 60 * 60 * 1000)];
1499
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?.();
1500
1736
  const endClients = (feed) => { for (const client of [...feed.clients.keys()]) { feed.clients.delete(client); try { client.end(); } catch { /* already gone */ } } };
1501
1737
  async function closeHeld(id) {
1502
1738
  const held = parked.get(id);
@@ -1703,6 +1939,10 @@ export async function createPulseServer({
1703
1939
  poller.unref();
1704
1940
 
1705
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
+
1706
1946
  // Intenciones' reading of every conversation, kept per ledger file until that file changes.
1707
1947
  const observedLedgers = new Map();
1708
1948
  // The context a module works in: the project, its settings, the room, and what this server offers.
@@ -1712,6 +1952,8 @@ export async function createPulseServer({
1712
1952
  projectRoot: canonicalProjectRoot, stateRoot: root, config, env: process.env, agents, room,
1713
1953
  // The language the room speaks, 'es' or 'en': a module answers in it (SDK, 2026-10-20).
1714
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,
1715
1957
  // Where this project's conversations are kept (~/.pulse/rooms/<id>): a module's own small
1716
1958
  // files about the project live beside them, never in the project's folder.
1717
1959
  roomDir,
@@ -1807,22 +2049,29 @@ export async function createPulseServer({
1807
2049
  }),
1808
2050
  ollama: {
1809
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
+ },
1810
2059
  project: () => localAiHere(),
1811
2060
  setProject: (on) => setLocalAiHere(on),
1812
2061
  wire: (options) => wireOllama(options),
1813
2062
  // Getting Ollama onto this computer, with the command in plain sight, and waking it.
1814
2063
  install: async () => {
1815
- if (installing) return { ok: false, error: `Another install is running (${installing}).` };
2064
+ if (installing) return { ok: false, error: t('Another install is running. Wait for it to finish and try again.') };
1816
2065
  const { ollamaInstallPlan, adminHere } = await import('./modules/ollama.mjs');
1817
2066
  const plan = ollamaInstallPlan({ brew: await findOnPath('brew'), admin: await adminHere() });
1818
2067
  if (!plan.command) return { ok: false, error: plan.note, download: plan.download, manual: plan.manual ? plan.display : null };
1819
- installing = 'ollama';
2068
+ installing = 'ollama'; installingSince = Date.now();
1820
2069
  await room.record('extension.install.started', { id: 'ollama', name: 'OLLAMA', command: plan.display, platforms: [], alreadyInstalled: false });
1821
2070
  void (async () => {
1822
2071
  const lines = [];
1823
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)] }); } });
1824
2073
  const status = await wireOllama();
1825
- 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 });
1826
2075
  installing = null;
1827
2076
  })();
1828
2077
  return { ok: true, command: plan.display };
@@ -1866,27 +2115,38 @@ export async function createPulseServer({
1866
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 }) };
1867
2116
  return this.start();
1868
2117
  },
1869
- // 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).
1870
2120
  pull: async (model) => {
1871
- if (installing) return { ok: false, error: `Another install is running (${installing}).` };
1872
- 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 };
1873
2125
  await room.record('extension.install.started', { id: 'ollama', name: 'OLLAMA', command: `ollama pull ${model}`, platforms: [], alreadyInstalled: false });
1874
2126
  void (async () => {
1875
2127
  let pending = [];
1876
2128
  let flushTimer = null;
1877
2129
  const flush = async () => { flushTimer = null; if (!pending.length) return; const batch = pending; pending = []; await room.record('extension.install.output', { id: 'ollama', lines: batch }); };
1878
2130
  try {
1879
- 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); } });
1880
2132
  await flush();
1881
2133
  const status = await wireOllama();
1882
- 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 });
1883
2135
  } catch (error) {
1884
2136
  await flush();
1885
- await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: error.message });
1886
- } 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; }
1887
2142
  })();
1888
2143
  return { ok: true };
1889
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
+ },
1890
2150
  },
1891
2151
  },
1892
2152
  };
@@ -1904,7 +2164,7 @@ export async function createPulseServer({
1904
2164
  return toggled;
1905
2165
  }
1906
2166
  if (confirm !== true) return { status: 400, body: { error: t('Installing a module writes into the project; send { "confirm": true } to proceed.') } };
1907
- 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.') } };
1908
2168
  const preflight = extension.preflight ? await extension.preflight(canonicalProjectRoot) : { ok: true, problems: [] };
1909
2169
  if (!preflight.ok && !installers[id]) {
1910
2170
  await room.record('extension.install.refused', { id, name: extension.name, problems: preflight.problems });
@@ -1915,7 +2175,7 @@ export async function createPulseServer({
1915
2175
  // What the module asked MADRE to do first (Continuity: `git init` in a project with no git),
1916
2176
  // shown in the same confirmation and run before the install, each step stopping the next.
1917
2177
  const prepare = Array.isArray(preflight.prepare) ? preflight.prepare : [];
1918
- installing = id;
2178
+ installing = id; installingSince = Date.now();
1919
2179
  await room.record('extension.install.started', { id, name: extension.name, command: plan.display, platforms: plan.platforms ?? [], alreadyInstalled: before.installed });
1920
2180
  void (async () => {
1921
2181
  const lines = [];
@@ -1979,7 +2239,7 @@ export async function createPulseServer({
1979
2239
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...PAGE_GUARDS });
1980
2240
  return response.end(html);
1981
2241
  }
1982
- 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', '/mcp-catalog.js', '/manual.js', '/manual-content.js', '/manual-shots.js', '/en.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)) {
1983
2243
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'text/javascript; charset=utf-8');
1984
2244
  }
1985
2245
  if (request.method === 'GET' && url.pathname === '/styles.css') {
@@ -1996,18 +2256,24 @@ export async function createPulseServer({
1996
2256
  return sendAsset(request, response, join(publicDirectory, 'manual.css'), 'text/css; charset=utf-8');
1997
2257
  }
1998
2258
  if (request.method === 'GET' && (url.pathname === '/assets/manual/madre-manual-es.pdf' || url.pathname === '/assets/manual/madre-manual-en.pdf')) {
1999
- return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'application/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();
2000
2265
  }
2001
2266
  // Its pictures: MADRE itself, photographed in each language (scripts/manual-shots.mjs). Only
2002
2267
  // a name of letters and dashes, so no path leaves the folder.
2003
2268
  if (request.method === 'GET' && /^\/assets\/manual\/shots\/(es|en)-[a-z]+\.webp$/.test(url.pathname)) {
2004
2269
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'image/webp');
2005
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.
2006
2272
  const abductionAssets = new Map([
2007
- ['/assets/abduction-cat.png', 'abduction-cat.png'],
2008
- ['/assets/abduction-cat-blink.png', 'abduction-cat-blink.png'],
2009
- ['/assets/abduction-cat-control-left.png', 'abduction-cat-control-left.png'],
2010
- ['/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'],
2011
2277
  ]);
2012
2278
  // The brand: its typefaces (SIL OFL, licences beside them) and the favicon, served from the
2013
2279
  // package itself. Nothing is fetched from a font service: the room never leaves this machine
@@ -2043,6 +2309,21 @@ export async function createPulseServer({
2043
2309
  ['/assets/wallpapers/tradicion.webp', 'image/webp'],
2044
2310
  ['/assets/wallpapers/urbania.webp', 'image/webp'],
2045
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'],
2046
2327
  ['/assets/news/1.0/settings.webp', 'image/webp'],
2047
2328
  ['/assets/news/1.0/mother.webp', 'image/webp'],
2048
2329
  ['/assets/news/1.0/intents.webp', 'image/webp'],
@@ -2064,7 +2345,7 @@ export async function createPulseServer({
2064
2345
  if (request.method === 'GET' && abductionAssets.has(url.pathname)) {
2065
2346
  const image = await readFile(join(publicDirectory, 'assets', abductionAssets.get(url.pathname)));
2066
2347
  response.writeHead(200, {
2067
- 'content-type': 'image/png',
2348
+ 'content-type': 'image/webp',
2068
2349
  'content-length': image.length,
2069
2350
  'cache-control': 'public, max-age=86400',
2070
2351
  });
@@ -2152,6 +2433,17 @@ export async function createPulseServer({
2152
2433
  return sendJson(response, 403, { error: t('This is done on the Mac.') });
2153
2434
  }
2154
2435
  if (request.method === 'GET' && url.pathname === '/salas') {
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
+ }
2155
2447
  const html = withHost(await readFile(join(publicDirectory, 'salas-mac.html'), 'utf8'));
2156
2448
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache', ...PAGE_GUARDS });
2157
2449
  return response.end(html);
@@ -2174,6 +2466,17 @@ export async function createPulseServer({
2174
2466
  widgetReadings.delete('usage');
2175
2467
  return sendJson(response, 200, { ok: true });
2176
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
+ }
2177
2480
  if (request.method === 'GET' && url.pathname === '/api/salas/widget') {
2178
2481
  const reading = await homeWidget(String(url.searchParams.get('kind') ?? ''));
2179
2482
  if (!reading) return sendJson(response, 404, { error: t('Home has no widget by that name.') });
@@ -2319,7 +2622,7 @@ export async function createPulseServer({
2319
2622
  const listed = await listFolders({ path: url.searchParams.get('path') || null, home, stateRoot: root });
2320
2623
  if (listed.error === 'outside') return sendJson(response, 403, { error: t('Only folders inside your home folder.') });
2321
2624
  if (listed.error) return sendJson(response, 404, { error: t('That folder is not there.') });
2322
- return sendJson(response, 200, listed);
2625
+ return sendJson(response, 200, { ...listed, defaultParent: await defaultProjectsFolder(home) });
2323
2626
  }
2324
2627
  if (request.method === 'GET' && url.pathname === '/api/salas/suggestions') {
2325
2628
  return sendJson(response, 200, { suggestions: await suggestProjects({ home, stateRoot: root }) });
@@ -2343,6 +2646,10 @@ export async function createPulseServer({
2343
2646
  const settings = await ollamaSettings();
2344
2647
  const model = ollama.madreModel ?? ollama.chatModel;
2345
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 });
2346
2653
  const key = createHash('sha256').update(items.map((item) => `${item.room}:${item.chat}:${item.at}:${item.messages}`).join('|')).digest('hex').slice(0, 16);
2347
2654
  const asked = request.method === 'POST';
2348
2655
  const due = !lobbyWork.bullets || (lobbyWork.key !== key && Date.now() - lobbyWork.tried > 5 * 60 * 1000);
@@ -2446,6 +2753,26 @@ export async function createPulseServer({
2446
2753
  setTimeout(() => server.emit('madre:close'), 150);
2447
2754
  return undefined;
2448
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
+ }
2449
2776
  // This room, asked to close by Salas: what is running stops and the room closes the way a
2450
2777
  // signal closes it (startPulse listens). Nothing here ends the process itself.
2451
2778
  if (request.method === 'POST' && url.pathname === '/api/room/close') {
@@ -2453,6 +2780,27 @@ export async function createPulseServer({
2453
2780
  setTimeout(() => server.emit('madre:close'), 150);
2454
2781
  return undefined;
2455
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
+ }
2456
2804
  // ---------- ENLACES (docs/MACROVERSO.md, fase 3b) ----------
2457
2805
  // The side that serves a link. Another room on this Mac asks, from its own process, for the
2458
2806
  // notes a signed contract lets it read; every lock is here, in the room that hands them over,
@@ -2865,7 +3213,9 @@ export async function createPulseServer({
2865
3213
  // The project's name as this system writes paths (WEB-11): the page cut it at «/», and on
2866
3214
  // Windows the name was the whole path, so the key for #3 never matched.
2867
3215
  projectName: basename(canonicalProjectRoot),
2868
- 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),
2869
3219
  // Behind the bridge, the page is on a phone and knows it. On the Mac it learns whether a
2870
3220
  // phone is paired, so it keeps its place for the phone only when there is one.
2871
3221
  device: viaPhone ? { kind: phoneKind } : null,
@@ -3131,7 +3481,8 @@ export async function createPulseServer({
3131
3481
  const now = Date.now();
3132
3482
  while (keyMisses.length && keyMisses[0] < now - 60000) keyMisses.shift();
3133
3483
  if (keyMisses.length >= 8) return sendJson(response, 429, { error: t('Too many wrong confirmations. Wait a minute and try again.') });
3134
- 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 })) {
3135
3486
  keyMisses.push(now);
3136
3487
  return sendJson(response, 403, { error: t('That is not it. Try again, or cancel.'), denied: true });
3137
3488
  }
@@ -3147,7 +3498,8 @@ export async function createPulseServer({
3147
3498
  const now = Date.now();
3148
3499
  while (keyMisses.length && keyMisses[0] < now - 60000) keyMisses.shift();
3149
3500
  if (keyMisses.length >= 8) return sendJson(response, 429, { error: t('Too many wrong confirmations. Wait a minute and try again.') });
3150
- 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 })) {
3151
3503
  keyMisses.push(now);
3152
3504
  return sendJson(response, 403, { error: t('That is not it. Try again, or cancel.'), denied: true });
3153
3505
  }
@@ -3165,8 +3517,95 @@ export async function createPulseServer({
3165
3517
  // This project's switch for the local AI (src/local-ai.mjs). In «auto» Home decides and the
3166
3518
  // switch does not move; /apply is how Home tells an open project the choice changed.
3167
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
+ }
3168
3605
  if (request.method === 'POST' && url.pathname === '/api/local-ai/apply') {
3169
- // Probed again: the model chosen in Home may have been downloaded after this project last looked.
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));
3170
3609
  const status = await wireOllama();
3171
3610
  return sendJson(response, 200, { project: status.project });
3172
3611
  }
@@ -3197,6 +3636,59 @@ export async function createPulseServer({
3197
3636
  }
3198
3637
  return sendJson(response, 200, { settings: await applySettings(patch) });
3199
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
+ }
3200
3692
  // NOSTROMO: the archive is behind the project designation, like CONTROL.
3201
3693
  // Sentinel: reports, settings, the manual road (a prefilled issue) and the automatic one.
3202
3694
  if (request.method === 'GET' && url.pathname === '/api/sentinel') {
@@ -3533,7 +4025,8 @@ export async function createPulseServer({
3533
4025
  // Where this person comes from: the tour of 1.0 (path «since»), 0.7.2 (their words in a room's
3534
4026
  // record, path «back»), or nowhere — a first install.
3535
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;
3536
- return sendJson(response, 200, { version: TOUR_VERSION, state, owed: !state.bonjourAt, returning: Boolean(from), from, chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
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 });
3537
4030
  }
3538
4031
  if (viaPhone || !fromHere || (request.method === 'POST' && request.headers.origin !== `http://${host}`)) return sendJson(response, 403, { error: t('This is done on the Mac.') });
3539
4032
  if (request.method === 'POST' && url.pathname === '/api/tour') {
@@ -3552,10 +4045,21 @@ export async function createPulseServer({
3552
4045
  }
3553
4046
  return sendJson(response, 404, { error: 'Not found' });
3554
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
+ }
3555
4057
  if (request.method === 'GET' && url.pathname === '/api/version') {
3556
4058
  // With the one thing the daily notice says about this copy: its random identifier, shown so the
3557
4059
  // person can see it, and so the author can leave out a copy of his own (the usage widget).
3558
- return sendJson(response, 200, { ...(await versionView({ force: url.searchParams.get('force') === '1' })), install: await installId(root).catch(() => null) });
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) });
3559
4063
  }
3560
4064
  // One click: install the newer version and come back on the same port. The room records it,
3561
4065
  // closes its listener so the port is free, hands the command to a detached shell and exits.
@@ -3597,7 +4101,7 @@ export async function createPulseServer({
3597
4101
  }
3598
4102
  if (request.method === 'POST' && url.pathname === '/api/updates/settings') {
3599
4103
  const patch = await body(request).catch(() => ({}));
3600
- 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(() => []); }
3601
4105
  return sendJson(response, 200, { updates: { check: updatesEnabled(), envWins: process.env.PULSE_UPDATE_CHECK !== undefined } });
3602
4106
  }
3603
4107
  if (request.method === 'GET' && url.pathname === '/api/mother') {
@@ -3668,6 +4172,10 @@ export async function createPulseServer({
3668
4172
  if (request.method === 'GET' && url.pathname === '/api/chats') {
3669
4173
  return sendJson(response, 200, await chatsView());
3670
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
+ }
3671
4179
  if (request.method === 'POST' && url.pathname === '/api/chats') {
3672
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.') });
3673
4181
  const payload = await body(request).catch(() => ({}));
@@ -3784,8 +4292,8 @@ export async function createPulseServer({
3784
4292
  const plan = await module.updatePlan(context, { latest: known?.latest ?? null, current: item.version ?? null });
3785
4293
  if (!plan?.command) return sendJson(response, 412, { error: plan?.note ?? 'There is no way to update this from here.', download: plan?.download ?? null });
3786
4294
  if (payload.confirm !== true) return sendJson(response, 200, { plan: { display: plan.display, note: plan.note ?? '' }, update: known });
3787
- if (installing) return sendJson(response, 409, { error: `Another install is running (${installing}).` });
3788
- 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();
3789
4297
  await room.record('extension.install.started', { id: module.id, name: item.name, command: plan.display, platforms: [], alreadyInstalled: true });
3790
4298
  void (async () => {
3791
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)] }); } });
@@ -3872,8 +4380,8 @@ export async function createPulseServer({
3872
4380
  return sendJson(response, 403, { error: t('A key is only accepted from this computer, never over the network.') });
3873
4381
  }
3874
4382
  const agent = agents.find((item) => item.id === id);
3875
- if (!agent?.detected) return sendJson(response, 412, { error: `${agent?.label ?? id} is not installed on this computer.` });
3876
- 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 }) });
3877
4385
  const payload = await body(request).catch(() => ({}));
3878
4386
  const result = await applyKey({
3879
4387
  agent: id,
@@ -4031,16 +4539,63 @@ export async function createPulseServer({
4031
4539
  return sendJson(response, 200, { turns: await turnsPolicy() });
4032
4540
  }
4033
4541
  if (request.method === 'POST' && url.pathname === '/api/stop-all') {
4034
- // Every conversation at work, not only the one on screen: the brake is the room's, not the chat's.
4035
- const result = await room.stopAll();
4036
- passes.clear();
4037
- await endCopilot('stopall');
4038
- for (const held of parked.values()) {
4039
- const more = await held.room.stopAll().catch(() => ({ plans: 0, turns: 0 }));
4040
- result.plans += more.plans ?? 0;
4041
- 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);
4042
4576
  }
4043
- return sendJson(response, 202, { stopped: true, ...result });
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;
4597
+ }
4598
+ return sendJson(response, 202, { stopped: true, ...result, projects });
4044
4599
  }
4045
4600
  const stopMatch = request.method === 'POST' && url.pathname.match(/^\/api\/plans\/([0-9a-f-]+)\/stop$/);
4046
4601
  if (stopMatch) {
@@ -4153,14 +4708,40 @@ export async function createPulseServer({
4153
4708
  const catalog = (await keptCatalog({ stateRoot: root, ...marketKeyed })) ?? (await syncMarket({ force: true }).catch(() => ({}))).catalog;
4154
4709
  if (!catalog) return sendJson(response, 503, { error: t('MADRE could not reach the Market. Check your internet connection and try again.') });
4155
4710
  try {
4156
- const done = await installFromMarket({ ...marketTools(), id: String(payload.id ?? ''), catalog });
4157
- 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' });
4158
4718
  for (const one of await knownRooms(root)) {
4159
4719
  if (!one.open?.port || one.id === thisRoomId) continue;
4160
4720
  await fetch(`http://127.0.0.1:${one.open.port}/api/extensions/reload`, { method: 'POST' }).catch(() => null);
4161
4721
  }
4162
4722
  return sendJson(response, 200, { installed: done, extensions: await describeModules(await moduleContext()) });
4163
- } catch (error) { return sendJson(response, 422, { error: error.message }); }
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 });
4164
4745
  }
4165
4746
  // A paid module's license (src/market-license.mjs): checked once with Lemon Squeezy when the
4166
4747
  // person activates it, kept here, and given back when they release it. Only from this Mac.
@@ -4305,6 +4886,9 @@ export async function createPulseServer({
4305
4886
  return sendJson(response, result.ok ? 200 : 409, result);
4306
4887
  }
4307
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 });
4308
4892
  const payload = await body(request);
4309
4893
  // A phone asks up to #2. The bridge already said so; the room says it again, and records
4310
4894
  // where the message came from. Only the bridge's word counts for that, never the body's.
@@ -4362,6 +4946,13 @@ export async function createPulseServer({
4362
4946
  }
4363
4947
  sendJson(response, 404, { error: t('Not found.') });
4364
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
+ }
4365
4956
  sendJson(response, 400, { error: error.message });
4366
4957
  }
4367
4958
  });
@@ -4403,7 +4994,8 @@ export async function createPulseServer({
4403
4994
  return server;
4404
4995
  };
4405
4996
  server.on('close', () => quotaMonitor.stop());
4406
- 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); });
4407
4999
 
4408
5000
  server.on('close', () => { void phone.stop(); });
4409
5001
  return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms };
@@ -4423,10 +5015,14 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
4423
5015
  const url = `http://127.0.0.1:${address.port}`;
4424
5016
  // Installed is all this line knows: whether each one is signed in is asked in the room, and
4425
5017
  // «Ready: Codex, Claude…» before any sign-in told a newcomer the opposite (2026-10-19).
4426
- const ready = agents.filter((agent) => agent.ready).map((agent) => agent.label).join(', ') || 'none';
5018
+ const ready = agents.filter((agent) => agent.ready).map((agent) => agent.label).join(', ') || t('none');
4427
5019
  const broken = agents.filter((agent) => agent.detected && !agent.ready).map((agent) => agent.label).join(', ');
4428
- console.log(`\nMADRE is ready\n\n ${url}${openPath}\n Project: ${projectRoot}\n Agents installed: ${ready} (who is signed in: Settings › Agents)\n${broken ? ` Found but not answering: ${broken}\n` : ''}`);
4429
- if (openBrowser) openUrl(`${url}${openPath}`);
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}`);
4430
5026
  // SIGHUP too: closing the Terminal the room was started in is a way of closing it.
4431
5027
  // Home closed this way closes what Turn MADRE off closes (2026-10-21): every open project, also
4432
5028
  // one opened from another project, whose process outlives Home on its own. A second signal while
@@ -4439,5 +5035,18 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
4439
5035
  }
4440
5036
  // Salas asked this room to close: the same as a signal.
4441
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
+ }));
4442
5051
  return { server, url };
4443
5052
  }