@jossuealcala/madre 1.1.2 → 1.1.4

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 (166) hide show
  1. package/CHANGELOG.en.md +40 -1
  2. package/CHANGELOG.md +40 -1
  3. package/README.en.md +3 -3
  4. package/README.md +3 -3
  5. package/SECURITY.md +11 -6
  6. package/TRADEMARKS.md +6 -2
  7. package/bin/madre.mjs +76 -11
  8. package/docs/REFERENCE.md +16 -10
  9. package/docs/SDK.md +36 -9
  10. package/docs/en/REFERENCE.md +12 -8
  11. package/docs/en/SDK.md +34 -8
  12. package/docs/en/training/README.md +1 -1
  13. package/docs/sdk/connector-module.mjs +1 -1
  14. package/docs/sdk/hello-module.mjs +39 -4
  15. package/docs/training/README.md +1 -1
  16. package/docs/training/train.sh +3 -0
  17. package/habilidades/explicamelo-facil/HABILIDAD.md +19 -0
  18. package/habilidades/hojas-de-calculo/HABILIDAD.md +18 -0
  19. package/habilidades/mensajes-a-clientes/HABILIDAD.md +19 -0
  20. package/habilidades/publicaciones-para-redes/HABILIDAD.md +19 -0
  21. package/habilidades/resumen-y-pendientes/HABILIDAD.md +18 -0
  22. package/habilidades/tu-pagina-paso-a-paso/HABILIDAD.md +19 -0
  23. package/package.json +7 -4
  24. package/public/activity.js +66 -22
  25. package/public/app.js +4947 -894
  26. package/public/assets/brand/OFL-SpaceGrotesk.txt +93 -0
  27. package/public/assets/brand/SpaceGrotesk-latin-ext.woff2 +0 -0
  28. package/public/assets/brand/SpaceGrotesk-latin.woff2 +0 -0
  29. package/public/assets/brand/madre-app-180.png +0 -0
  30. package/public/assets/brand/madre-app-192.png +0 -0
  31. package/public/assets/brand/madre-app-512.png +0 -0
  32. package/public/assets/brand/madre-app.svg +1 -1
  33. package/public/assets/brand/madre-favicon.svg +1 -1
  34. package/public/attribution.js +29 -19
  35. package/public/auto-open.js +102 -0
  36. package/public/brands.js +36 -19
  37. package/public/changes.js +63 -0
  38. package/public/en.js +1085 -102
  39. package/public/es.js +2940 -1656
  40. package/public/i18n.js +11 -0
  41. package/public/index.html +31 -27
  42. package/public/loader.js +322 -117
  43. package/public/macroverso.js +57 -355
  44. package/public/manual-content.js +69 -9
  45. package/public/manual.js +21 -6
  46. package/public/market-view.js +298 -84
  47. package/public/market.js +25 -2
  48. package/public/mcp-catalog.js +7 -2
  49. package/public/missions.js +169 -0
  50. package/public/news-scenes.js +292 -0
  51. package/public/nostromo-engine.js +935 -654
  52. package/public/notices.js +78 -0
  53. package/public/notifications.js +119 -0
  54. package/public/power.js +1 -1
  55. package/public/provider-marks.js +170 -0
  56. package/public/provider-pick.js +147 -0
  57. package/public/resay.js +4 -0
  58. package/public/review-ask.js +16 -13
  59. package/public/routing.js +29 -3
  60. package/public/salas-mac.css +467 -47
  61. package/public/salas-mac.html +8 -5
  62. package/public/salas-mac.js +805 -109
  63. package/public/salas.css +2 -2
  64. package/public/salas.html +2 -2
  65. package/public/salas.js +1 -1
  66. package/public/starters.js +128 -0
  67. package/public/styles.css +3036 -340
  68. package/public/subscription.js +303 -0
  69. package/public/terms-field.js +170 -0
  70. package/public/terms.js +117 -19
  71. package/public/tips.js +158 -0
  72. package/public/tour-chapters.js +88 -88
  73. package/public/tour.js +364 -46
  74. package/public/troubleshooting.js +313 -27
  75. package/public/welcome-scene.js +446 -0
  76. package/public/welcome.js +827 -282
  77. package/src/adapters/claude.mjs +2 -1
  78. package/src/adapters/codex.mjs +2 -1
  79. package/src/adapters/cursor.mjs +9 -6
  80. package/src/adapters/gemini-rest.mjs +236 -0
  81. package/src/adapters/gemini.mjs +13 -7
  82. package/src/adapters/grok.mjs +290 -0
  83. package/src/adapters/madre.mjs +71 -23
  84. package/src/adapters/opencode.mjs +15 -2
  85. package/src/adapters/process.mjs +14 -3
  86. package/src/adapters/steps.mjs +176 -0
  87. package/src/app-invite.mjs +90 -0
  88. package/src/auth-probe.mjs +32 -0
  89. package/src/billing-key.mjs +8 -0
  90. package/src/billing.mjs +317 -0
  91. package/src/bridge/policy.mjs +1 -1
  92. package/src/capabilities.mjs +46 -10
  93. package/src/chats.mjs +44 -2
  94. package/src/checkpoint.mjs +119 -1
  95. package/src/codex-route.mjs +113 -0
  96. package/src/commands.mjs +5 -2
  97. package/src/credentials.mjs +46 -8
  98. package/src/dataset.mjs +18 -7
  99. package/src/directives.mjs +1 -0
  100. package/src/event-store.mjs +25 -2
  101. package/src/extensions.mjs +5 -1
  102. package/src/ficha.mjs +158 -0
  103. package/src/files.mjs +36 -2
  104. package/src/image-studio.mjs +13 -3
  105. package/src/install-metrics.mjs +9 -3
  106. package/src/lease.mjs +6 -1
  107. package/src/looks.mjs +4 -1
  108. package/src/market-check.mjs +1 -1
  109. package/src/market-remote.mjs +135 -1
  110. package/src/mcp/image-server.mjs +59 -90
  111. package/src/mcp/memory-server.mjs +10 -0
  112. package/src/memory-tools.mjs +3 -0
  113. package/src/memory.mjs +29 -4
  114. package/src/models.mjs +21 -3
  115. package/src/modules/ahp.mjs +10 -4
  116. package/src/modules/bishop-exam.mjs +41 -12
  117. package/src/modules/bishop.mjs +2 -2
  118. package/src/modules/choices.mjs +12 -10
  119. package/src/modules/fetch-alone.mjs +7 -0
  120. package/src/modules/github.mjs +6 -2
  121. package/src/modules/helpers.mjs +23 -5
  122. package/src/modules/image-providers.mjs +281 -0
  123. package/src/modules/image-studio.mjs +106 -39
  124. package/src/modules/index.mjs +61 -12
  125. package/src/modules/intents-observe.mjs +3 -1
  126. package/src/modules/isolated.mjs +160 -0
  127. package/src/modules/ollama.mjs +35 -6
  128. package/src/modules/playwright.mjs +78 -20
  129. package/src/modules/reminders.mjs +42 -2
  130. package/src/modules/ripley.mjs +2 -1
  131. package/src/modules/run-alone.mjs +122 -0
  132. package/src/modules/runs.mjs +11 -8
  133. package/src/modules/sdk.mjs +10 -3
  134. package/src/notices-key.mjs +8 -0
  135. package/src/notices.mjs +185 -0
  136. package/src/ollama.mjs +57 -15
  137. package/src/opencode-health.mjs +1 -1
  138. package/src/outbound.mjs +124 -13
  139. package/src/quota-sources.mjs +148 -3
  140. package/src/review-ask.mjs +55 -31
  141. package/src/room/archivist.mjs +30 -5
  142. package/src/room/busy.mjs +16 -0
  143. package/src/room/changes.mjs +79 -0
  144. package/src/room/control.mjs +36 -6
  145. package/src/room/economy.mjs +1 -1
  146. package/src/room/guard.mjs +39 -2
  147. package/src/room/prompt.mjs +49 -6
  148. package/src/room/vectors.mjs +7 -1
  149. package/src/room.mjs +181 -49
  150. package/src/router.mjs +1 -1
  151. package/src/runs.mjs +39 -0
  152. package/src/runtime-detection.mjs +46 -6
  153. package/src/salas.mjs +181 -18
  154. package/src/server.mjs +1101 -118
  155. package/src/service.mjs +116 -0
  156. package/src/setup-trouble.mjs +20 -1
  157. package/src/setup.mjs +1 -1
  158. package/src/skill-check.mjs +269 -0
  159. package/src/skills-import.mjs +128 -0
  160. package/src/skills.mjs +502 -0
  161. package/src/terms.mjs +23 -5
  162. package/src/tour.mjs +31 -5
  163. package/src/updates.mjs +47 -4
  164. package/src/web-preview.mjs +181 -0
  165. package/src/whats-new.mjs +121 -1
  166. package/src/rumbo.mjs +0 -337
package/src/server.mjs CHANGED
@@ -2,7 +2,7 @@
2
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
- import { existsSync, openSync, rmSync } from 'node:fs';
5
+ import { closeSync, existsSync, rmSync } from 'node:fs';
6
6
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
7
7
  import { probePort, framable } from './ports.mjs';
8
8
  import { ControlDesk } from './room/control.mjs';
@@ -15,16 +15,17 @@ import { promisify } from 'node:util';
15
15
 
16
16
  const execFileAsync = promisify(execFile);
17
17
  import { detectAgents, toolsPrefix } from './runtime-detection.mjs';
18
+ import { codexRoute } from './codex-route.mjs';
18
19
  import { EventStore } from './event-store.mjs';
19
20
  import { RoomMemory, travels as memoryTravels } from './memory.mjs';
20
21
  import { createEmbedder } from './embeddings.mjs';
21
22
  import { memoryServerFor } from './memory-tools.mjs';
22
23
  import { MotherChannel, CODE000_STRIKES } from './mother.mjs';
23
24
  import { ErrorSentinel } from './sentinel-errors.mjs';
24
- import { probeOllama, ollamaEmbedder, ollamaGenerate, ollamaInvoker, pullModel, ollamaVersions, ownOllamaServers } from './ollama.mjs';
25
+ import { probeOllama, ollamaEmbedder, ollamaGenerate, ollamaInvoker, patientFetch, pullModel, ollamaVersions, ownOllamaServers } from './ollama.mjs';
25
26
  import { recallForTurn } from './modules/enlaces.mjs';
26
27
  import { hardwareOnce, MODEL_TIERS } from './modules/local-models.mjs';
27
- import { browserAdvice, environmentOnce, openBrowser as openInBrowser } from './environment.mjs';
28
+ import { browserAdvice, browserWays, environmentOnce, openBrowser as openInBrowser } from './environment.mjs';
28
29
  import { installTrouble, loginTrouble } from './setup-trouble.mjs';
29
30
  import { MODULES, moduleById, describeModules, findModuleRoute, toolsForTurn as modulesToolsForTurn, loadExternalModules, loadFailures, moduleFolders, moduleCommands, installModuleFile, installModuleText, verifyModuleText, moduleOrigin, removeExternalModule, adoptBuiltinUpdates, packagedVersions } from './modules/index.mjs';
30
31
  import { understandsSdk } from './modules/sdk.mjs';
@@ -32,8 +33,11 @@ import { updateBuiltins } from './builtin-updates.mjs';
32
33
  import { madreAgent, madreInvoker, MADRE_AGENT_ID, MADRE_ADAPTER } from './adapters/madre.mjs';
33
34
  import { exportDataset, forgetCorpus, keepCorpus, keptCorpus, pruneCorpora, readiness as datasetReadiness } from './dataset.mjs';
34
35
  import { OutboundLog, outboundView, DEFAULT_REPORT_URL } from './outbound.mjs';
36
+ import { webPreview } from './web-preview.mjs';
35
37
  import { Telemetry, telemetryOn } from './telemetry.mjs';
36
38
  import { hostFacts, inRoomLanguage, language as roomLanguage, say, setLanguage as setRoomLanguage, t } from './i18n.mjs';
39
+ import { BILLING_PUBLIC_KEY } from './billing-key.mjs';
40
+ import { ORDER_EVERY_MS, ORDER_FAST_MS, PRICE_MXN, RECOVERY_KEEP_MS, SWITCH_EVERY_MS, TRIAL_DAYS, askOrder, askRecovery, askSwitch, billingInApp, billingSite, chooseProject, claimProject, dueMoment, loadBilling, markSeen as markBillingSeen, newOrder, portalUrl, renewKey, signSwitch, startRecovery, stopRecovery, verifiedSwitch } from './billing.mjs';
37
41
 
38
42
  // One per start of this process: a restart is a new one, a reload of the page is not.
39
43
  const BOOT_ID = `${process.pid}-${Date.now().toString(36)}`;
@@ -48,6 +52,9 @@ const OWN_MODULE_IDS = new Set(MODULES.map((one) => one.id));
48
52
  // Where the author's token for the usage widget is kept: a vault name no module can take (module
49
53
  // ids are kebab-case, src/modules/sdk.mjs), so no module ever reads it.
50
54
  export const OWNER_VAULT = 'madre_owner';
55
+ // What a room that found its project already open writes in start.log, in either language MADRE
56
+ // speaks (Q-1): Home reads the address that follows to say where the project is open.
57
+ export const ALREADY_OPEN = /(?:already open for this project|ya está abierta para este proyecto)(?:\s+(?:at|en))?\s+(http:\/\/127\.0\.0\.1:\d+)/g;
51
58
  let crashHandlersInstalled = false;
52
59
 
53
60
  // RIPLEY's bridge, injected into every page it renders: reports the page's path
@@ -81,33 +88,46 @@ import { forgetSecret, readSecret, summary as vaultSummary, writeSecret } from '
81
88
  import { applyConfigToEnv, loadConfig as readConfig, updateConfig } from './config.mjs';
82
89
  import { Privacy, normalizeTerms, privacySettings } from './privacy.mjs';
83
90
  import { planView, removeMadre, uninstallPlan } from './uninstall.mjs';
84
- import { checkForUpdate, detectInstall, updateCommand, releaseUrl, applyCommand, fetchCommand } from './updates.mjs';
91
+ import { canReplace, checkForUpdate, detectInstall, updateCommand, releaseUrl, applyCommand, fetchCommand, nextProcess, opensBrowser, roomsBehind, takesItsPlace } from './updates.mjs';
85
92
  import { INVITE_ANSWERS, bootWhatsNew, cameFromOlder, invitedFor, markInvited, markSeen, newestNotes, notesFor, whatsNew } from './whats-new.mjs';
86
- import { answerAsk, tickAsk } from './review-ask.mjs';
87
- import { CHAPTERS, HINTS, NEWS_LEVEL, TOUR_VERSION, WELCOME_STEPS, cameBefore, changeTour, readTour, recoverProject, roomsWithoutProject } from './tour.mjs';
93
+ import { answerAppInvite, appInvite } from './app-invite.mjs';
94
+ import { answerAsk, askVia, tickAsk } from './review-ask.mjs';
95
+ import { CHAPTERS, HINTS, MISSIONS, NEWS_LEVEL, TOUR_VERSION, WELCOME_STEPS, cameBefore, changeTour, readTour, recoverProject, roomsWithoutProject } from './tour.mjs';
88
96
 
89
97
  // Where a person reads the module contract, in the language the room is speaking.
90
98
  const SDK_PAGE = { es: 'https://madre.run/sdk/', en: 'https://madre.run/en/sdk/' };
99
+ // The kinds of notification of the system a person turns on or off (/api/notifications), and `enabled`,
100
+ // MADRE's own switch for all of them (2026-11-14). A new version and the author's notices are not among
101
+ // them: they always go out (public/notifications.js).
102
+ const NOTIFICATION_KINDS = ['enabled', 'conversations'];
103
+ // @madre is offered a test once agents answered this many real questions in a conversation, and
104
+ // offered again after these days while it has not been measured (offerLocalTry).
105
+ const LOCAL_TRY_MIN = 6;
106
+ const LOCAL_TRY_AGAIN_MS = 3 * 24 * 60 * 60 * 1000;
91
107
  import { moduleUpdate } from './modules/updates.mjs';
92
108
  import { ACTIVITY_SOON_MS, recentInProject } from './activity.mjs';
93
109
  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';
110
+ import { adoptStrays, chatIndex, chatLedger, createChat, deleteChat, isChatId, listChats, openChat as openChatIndex, archiveChat, carryChat, pinChat, searchChats, projectFloor, renameChat, touchChat } from './chats.mjs';
95
111
  import { spawn } from 'node:child_process';
96
112
  import { cpus, freemem, loadavg, totalmem } from 'node:os';
97
113
  import { discoverModels, groupOpenCode, openCodeHidden, parseCursorModels, parseGeminiModels, parseOpenCodeVerbose, providerLabel, OPENCODE_OWN } from './models.mjs';
98
114
  import { cursorOnlyAuto } from './adapters/cursor.mjs';
115
+ import { parseGrokModels } from './adapters/grok.mjs';
99
116
  // Cursor's own list of models (`cursor-agent --list-models`), kept a few minutes: reading it asks
100
117
  // Cursor's servers.
101
118
  const cursorModels = { at: 0, ids: [] };
119
+ // Grok's (`grok models`, 2026-11-06), kept as long: it asks xAI for the account's list.
120
+ const grokModels = { at: 0, list: null };
102
121
  // And Gemini's, from Google with the person's key.
103
122
  const geminiModels = { at: 0, ids: [] };
104
123
  import { observable } from './modules/intents-observe.mjs';
105
124
  import { summarizeHistory } from './history.mjs';
106
125
  import { migrateOpenCodeHealth, noteOpenCodeTurn, openCodeHealth, suggestOpenCodeModel } from './opencode-health.mjs';
107
- import { normalizeMode, setImageModule } from './capabilities.mjs';
126
+ import { normalizeMode, setAgentsViaApi, setImageModule } from './capabilities.mjs';
108
127
  import { resolveGeminiKey } from './image-studio.mjs';
128
+ import { findImageSources } from './modules/image-providers.mjs';
109
129
  import { commandByName, listCommands, parseCommand } from './commands.mjs';
110
- import { listDirectory, searchFiles, readServable, storeAttachment, resolveInside, createEmptyFile, writeEdited, MAX_ATTACHMENT_BYTES, MAX_EDIT_BYTES } from './files.mjs';
130
+ import { listDirectory, searchFiles, readServable, storeAttachment, keepAttachment, attachmentPlaceRefused, ATTACHMENT_REFUSED, resolveInside, createEmptyFile, writeEdited, MAX_ATTACHMENT_BYTES, MAX_EDIT_BYTES } from './files.mjs';
111
131
  import { planFileOp, freeCopyPath, needsDesignationOnDisk, CREATIONS } from './file-ops.mjs';
112
132
  import { ServerSentinel } from './server-sentinel.mjs';
113
133
  import { Eyecat } from './eyecat-watch.mjs';
@@ -126,22 +146,27 @@ import { qrSvg } from './bridge/qr.mjs';
126
146
  import { readHandoff, writeHandoff } from './bridge/handoff.mjs';
127
147
  import { changeHome, changeLooks, readHome, readLooks, changeRoomLook, roomLooks, WALLPAPER_BYTES, dropWallpaper, frameWallpaper, readWallpaper, saveWallpaper, wallpaperBytes } from './looks.mjs';
128
148
  import { localAiConfig, localAiFor, localAiPatch } from './local-ai.mjs';
129
- import { moduleOnIn, scopeView, settingsIn } from './module-scope.mjs';
149
+ import { moduleOnIn, scopeView, settingsIn, switchIn } from './module-scope.mjs';
150
+ import { chooseSkills, declaredBy as skillDeclares, installSkill, isSkillFile, loadSkills, readSkillText, removeSkill, shareSkill, skillState, skillStateIn, skillIdOf, SKILL_FILES, SKILL_STATES } from './skills.mjs';
151
+ import { findSkills, importSkills } from './skills-import.mjs';
152
+ import { ASKS as SKILL_ASKS, SKILL_LICENSES, SKILL_SHELVES, submissionDraft as skillDraft, writeSubmission as writeSkillSubmission } from './skill-check.mjs';
130
153
  import { COMMUNITY_LICENSES, COMMUNITY_SHELVES, MARKET_REPO, checkSubmission, submissionDraft, writeSubmission } from './market-check.mjs';
131
- import { forgetFromMarket, installFromMarket, installedFromMarket, keptCatalog, marketAnnounced, marketAnnouncements, marketNews, marketNewsSeen, refreshCatalog, updateFromMarket } from './market-remote.mjs';
154
+ import { currentNotices, noticeSeen, noticesUrl, readFeed, readNotice, refreshNotices, signNotice, signRetire } from './notices.mjs';
155
+ import { forgetFromMarket, installFromMarket, installSkillFromMarket, installedFromMarket, installedSkills, keptCatalog, marketAnnounced, marketAnnouncements, marketNews, marketNewsSeen, refreshCatalog, updateFromMarket, updateSkillsFromMarket } from './market-remote.mjs';
132
156
  // Not moved project by project: the Coordinator is Home's, Git has no switch, and Local AI keeps
133
157
  // its own list of projects (local-ai.mjs).
134
158
  const NOT_BY_PROJECT = new Set(['bishop', 'git-pulse', 'ollama']);
135
159
  import { heartbeat, installId } from './heartbeat.mjs';
136
160
  import { PRESENCE_EVERY_MS, environmentGauges, noteLifecycle, sayPresent } from './install-metrics.mjs';
137
- import { keepHistory, readGithub, readHistory, readNpm, rumboModel } from './rumbo.mjs';
138
- import { TERMS_LINKS, acceptTerms, cameFromBefore, readTerms } from './terms.mjs';
161
+ import { acceptTerms, cameFromBefore, readTerms, termsKind, termsLinks } from './terms.mjs';
139
162
  import { activateLicense, licensedIds, releaseLicense } from './market-license.mjs';
140
- import { askRoom, associateProject, createProject, createSampleProject, defaultProjectsFolder, ensureSalasProject, forgetProject, isSalasRoom, knownRooms, listFolders, markProject, projectRoomId, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
163
+ import { askRoom, associateProject, createProject, createSampleProject, defaultProjectsFolder, ensureSalasProject, forgetProject, isSalasRoom, keepOpenProject, knownRooms, listFolders, markProject, projectRoomId, projectTitle, renameProject, roomComesUp, salasRoomId, startRoom, suggestProjects, universeOf } from './salas.mjs';
164
+ import { UNIT_NAME, disableService, enableService, launcherScript, refreshLauncher, serviceState } from './service.mjs';
141
165
  import { parseWork, recentWork, WORK_SYSTEM, workPrompt } from './lobby-work.mjs';
142
166
  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';
143
167
  import { readContinuity } from './modules/ahp.mjs';
144
168
  import { readAt } from './checkpoint.mjs';
169
+ import { FICHA_HEADER, FICHA_NEEDED, FICHA_PARAM, carriesFicha, defaultStateRoot, ensureFicha, fichaCookie, fichaHeaders, fichaReader, fichaShown, openPrivateLog, previewKey, withoutFicha, readFicha, sameFicha, withFicha } from './ficha.mjs';
145
170
 
146
171
  const sourceDirectory = dirname(fileURLToPath(import.meta.url));
147
172
  const publicDirectory = join(sourceDirectory, '..', 'public');
@@ -193,14 +218,20 @@ function sendJson(response, status, value) {
193
218
  // A request's JSON, read whole before it is decoded (2026-10-12, SRV-08): a «ñ» split between two
194
219
  // packets came out as «��». The limit is in bytes; a route that takes more says so (the editor).
195
220
  const BODY_LIMIT = 100_000;
196
- async function body(request, { limit = BODY_LIMIT } = {}) {
221
+ // A message takes a long paste — a log, a file pasted whole (D-40, 2026-11-10: refused at 100 KB).
222
+ const MESSAGE_LIMIT = 1_000_000;
223
+ async function body(request, { limit = BODY_LIMIT, tooLarge = null } = {}) {
197
224
  const chunks = [];
198
225
  let size = 0;
199
226
  for await (const chunk of request) {
200
227
  size += chunk.length;
201
- if (size > limit) throw Object.assign(new Error('Request too large.'), { status: 413 });
202
- chunks.push(chunk);
228
+ if (size <= limit) { chunks.push(chunk); continue; }
229
+ // Past the limit the rest is read and dropped, so the answer that says why reaches the page: cut
230
+ // in the middle of the upload, Node 22 lost it and the page waited forever (CI of 1.1.4,
231
+ // D-40). Only something many times the limit is cut.
232
+ if (size > limit * 8) break;
203
233
  }
234
+ if (size > limit) throw Object.assign(new Error(tooLarge ?? t('That is too much to send at once.')), { status: 413 });
204
235
  return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
205
236
  }
206
237
 
@@ -217,7 +248,7 @@ export async function openUrl(url) {
217
248
 
218
249
  // PULSE_AGENT_TIMEOUT_MS applies to every agent; PULSE_<AGENT>_TIMEOUT_MS
219
250
  // (e.g. PULSE_CLAUDE_TIMEOUT_MS) overrides it for one.
220
- export function agentTimeoutsFromEnv(env = process.env, agentIds = ['codex', 'claude', 'gemini', 'opencode', 'cursor']) {
251
+ export function agentTimeoutsFromEnv(env = process.env, agentIds = ['codex', 'claude', 'gemini', 'opencode', 'cursor', 'grok']) {
221
252
  const timeouts = {};
222
253
  const shared = Number(env.PULSE_AGENT_TIMEOUT_MS);
223
254
  if (Number.isFinite(shared) && shared > 0) timeouts.default = shared;
@@ -273,6 +304,8 @@ export async function createPulseServer({
273
304
  credentialHome = homedir(),
274
305
  probe = probeAll,
275
306
  imageKey = resolveGeminiKey,
307
+ // Where Images finds each provider's key (src/modules/image-providers.mjs); null reads this computer.
308
+ imageSources = null,
276
309
  // The sentinel's outbound channel; tests hand in a fake.
277
310
  reportFetch = globalThis.fetch,
278
311
  // The Market's catalog and module files from madre.run (src/market-remote.mjs); tests hand in a
@@ -285,8 +318,21 @@ export async function createPulseServer({
285
318
  licenseApi = null,
286
319
  // Ollama detection; tests hand in a fake probe. PULSE_OLLAMA=0 leaves Ollama alone entirely.
287
320
  ollamaProbe = process.env.PULSE_OLLAMA === '0' ? async () => ({ running: false, host: null, models: [], embedModel: null, chatModel: null, disabled: true }) : probeOllama,
321
+ // When Ollama did not answer the first look, how long until it is asked again; the last wait
322
+ // repeats (L-14). Tests hand in short ones.
323
+ ollamaRetryMs = [10_000, 30_000, 90_000, 300_000],
324
+ // Whether every request has to carry the ficha (src/ficha.mjs). Only the CLI entry point
325
+ // (startPulse) turns it on, as it does the quota sources; a test that checks it turns it on too.
326
+ // `renewFicha`: asked when the browser is opened by this start; only Home acts on it, and makes a
327
+ // new one for this run. A project Home opens keeps Home's.
328
+ ficha: fichaOn = false,
329
+ renewFicha = false,
330
+ // The keys MADRE App's subscription checks against (src/billing.mjs). Only a test passes its own;
331
+ // no environment variable changes them.
332
+ billingKeys = {},
288
333
  }) {
289
334
  const root = stateRoot ?? process.env.PULSE_HOME ?? join(homedir(), '.pulse');
335
+ const currentFicha = fichaOn ? fichaReader(root) : async () => null;
290
336
  // Whether this copy had its random identifier before this run: without one it is a new install
291
337
  // (src/install-metrics.mjs, noteLifecycle).
292
338
  const hadInstallId = existsSync(join(root, 'install-id'));
@@ -302,23 +348,40 @@ export async function createPulseServer({
302
348
  // opens it (public/i18n.js, browserLanguage), once, and keeps it as if it had been chosen.
303
349
  let languageChosen = Boolean(process.env.PULSE_LANGUAGE || (await readConfig(root)).language);
304
350
  // RIPLEY renders HTML in the viewer only while the human has it switched on; read live, the switch is the module's.
305
- const ripleyOn = async () => moduleOnHere(await readConfig(root), 'ripley');
351
+ // On unless the person turned it off (2026-11-14): the module's own default (src/modules/ripley.mjs).
352
+ const ripleyOn = async () => moduleOnHere(await readConfig(root), 'ripley', true);
306
353
  agentTimeouts ??= agentTimeoutsFromEnv();
307
354
  const detector = detect ?? (providedAgents ? null : detectAgents);
308
- const agents = providedAgents ?? await detector();
355
+ const refreshCodexRoute = async (agent) => agent.id === 'codex' && agent.route
356
+ ? { ...agent, route: await codexRoute() }
357
+ : agent;
358
+ const agents = await Promise.all((providedAgents ?? await detector()).map(refreshCodexRoute));
359
+ setAgentsViaApi(agents);
309
360
  const canonicalProjectRoot = await realpath(projectRoot).catch(() => resolve(projectRoot));
310
361
  const roomDir = join(root, 'rooms', projectRoomId(canonicalProjectRoot));
311
362
  // Whether this is the room of Salas (docs/MACROVERSO.md, fase 3d): the room whose project is
312
363
  // the notebook of Salas, decided once from real paths; the page carries the MACROVERSO key there.
313
364
  const salasRoom = isSalasRoom(canonicalProjectRoot, root);
365
+ if (fichaOn) await ensureFicha(root, { renew: renewFicha && salasRoom });
314
366
  // What left this machine. Every fetch this process makes — MADRE's own and any a module makes,
315
367
  // because a module runs in here and cannot opt out — goes through one wrapper and lands in a
316
368
  // line beside the ledger. Bodies, headers and query values are never in it. One room per
317
369
  // process holds the watch; a second would only log what the first already logged.
318
370
  const outbound = await new OutboundLog({ file: join(roomDir, 'outbound.jsonl') }).load();
371
+ // The local AI's own channel: the same watch, without Node's 300 s wait for a first byte
372
+ // (patientFetch in src/ollama.mjs, L-7). A test's fake reportFetch is used as it is.
373
+ let localFetch = reportFetch === globalThis.fetch ? patientFetch : reportFetch;
374
+ // Whether git is on this computer (D-5): the restore point taken before an AI writes needs it,
375
+ // and without it every #2, #3 and #4 failed with a bare «spawn git ENOENT». Asked when the room
376
+ // opens and again, at most once a minute, when a page is served; the page marks those modes.
377
+ let gitHere = true;
378
+ let gitAsked = 0;
379
+ const askGit = () => { gitAsked = Date.now(); execFile('git', ['--version'], { timeout: 5000 }, (error) => { gitHere = error?.code !== 'ENOENT'; }); };
380
+ askGit();
319
381
  const unwatchOutbound = outbound.install();
320
382
  process.env.PULSE_OUTBOUND_LOG = join(roomDir, 'outbound.jsonl');
321
383
  reportFetch = outbound.watch(reportFetch);
384
+ localFetch = outbound.watch(localFetch);
322
385
  marketFetch = outbound.watch(marketFetch);
323
386
 
324
387
  // Attachments live beside the room log, never inside the project, and belong to the project
@@ -337,8 +400,9 @@ export async function createPulseServer({
337
400
  // is taken only if that room also answers on its port.
338
401
  const answers = async (port) => Number.isInteger(port) && await fetch(`http://127.0.0.1:${port}/api/version`, { signal: AbortSignal.timeout(1500) }).then((response) => response.ok, () => false);
339
402
  if (held && Number.isInteger(held.pid) && held.pid !== process.pid && alive(held.pid) && await answers(held.port)) {
340
- const error = new Error(`MADRE is already open for this project at http://127.0.0.1:${held.port} (process ${held.pid}). Close that room first, or open another conversation inside it.`);
403
+ const error = new Error(t('MADRE is already open for this project at {address} (process {pid}). Close that room first, or open another conversation inside it.', { address: `http://127.0.0.1:${held.port}`, pid: held.pid }));
341
404
  error.code = 'ROOM_IN_USE';
405
+ error.port = held.port;
342
406
  throw error;
343
407
  }
344
408
  // The room is this one's now. A room that died in the middle of a turn left the project's .env
@@ -348,7 +412,7 @@ export async function createPulseServer({
348
412
  // The mark also says which project and which MADRE, for the bridge's list of rooms on the phone.
349
413
  let openPort = null;
350
414
  // Where the project is, too (src/salas.mjs): a room that is closed can be opened again from Salas.
351
- const markOpen = async (port) => { openPort = port; await mkdir(roomDir, { recursive: true }).catch(() => {}); await writeFile(openMark, JSON.stringify({ pid: process.pid, port, at: new Date().toISOString(), project: basename(canonicalProjectRoot), version: PACKAGE.version ?? null })).catch(() => {}); await markProject(roomDir, canonicalProjectRoot).catch(() => {}); };
415
+ const markOpen = async (port) => { openPort = port; await mkdir(roomDir, { recursive: true }).catch(() => {}); await writeFile(openMark, JSON.stringify({ pid: process.pid, port, at: new Date().toISOString(), project: basename(canonicalProjectRoot), version: PACKAGE.version ?? null })).catch(() => {}); await markProject(roomDir, canonicalProjectRoot, { port, keepOpen: true }).catch(() => {}); };
352
416
  // The phone (docs/MOBILE.md) is not offered in MADRE 1.0 (2026-10-11, hidden 2026-10-12): Safari
353
417
  // in HTTPS-only mode refuses the bridge's http, and the relay that fixes it is not built. Only a
354
418
  // copy run from source (FROM_SOURCE, above) on a Mac that turned it on — `phone.preview` in
@@ -377,7 +441,7 @@ export async function createPulseServer({
377
441
  async function closeOtherRooms() {
378
442
  const here = basename(roomDir);
379
443
  const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
380
- await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/close', { method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null)));
444
+ await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/close', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null)));
381
445
  let left = others;
382
446
  for (let tries = 0; tries < 60 && left.length; tries += 1) {
383
447
  await new Promise((resolve) => setTimeout(resolve, 250));
@@ -386,6 +450,51 @@ export async function createPulseServer({
386
450
  }
387
451
  return { closed: others.length - left.length, stuck: left.map((one) => one.name) };
388
452
  }
453
+ // UPDATING ALL OF MADRE (L-13, Carlos's server, 2026-11-10). An update restarted only the room it
454
+ // was pressed in: Carlos updated a project, Home and the other projects stayed on the older MADRE,
455
+ // and with the ficha of the new one in between he was left outside. The start that comes from an
456
+ // update now brings every other open room on an older MADRE to this one: asked to close the way
457
+ // Home closes one, and opened again by this copy's own script on the port it had. The older one is
458
+ // only asked to close, so this works from any version before it. A room with something running is
459
+ // left for the next round (every minute, for an hour). Home as a service of this Linux comes back
460
+ // through systemd, its launcher saying the new version first. A copy installed inside a project
461
+ // is not the MADRE of the others, and is left alone.
462
+ async function bringOthersAlong({ rounds = 60, everyMs = 60000 } = {}) {
463
+ if (install !== 'npx' && install !== 'global') return;
464
+ const here = basename(roomDir);
465
+ for (let round = 0; round < rounds; round += 1) {
466
+ const behind = roomsBehind(await knownRooms(root), { here, version: PACKAGE.version });
467
+ if (!behind.length) return;
468
+ for (const one of behind) await bringAlong(one).catch(() => false);
469
+ if (round < rounds - 1) await new Promise((resolve) => setTimeout(resolve, everyMs));
470
+ }
471
+ }
472
+ async function bringAlong(one) {
473
+ const home = one.id === salasRoomId(root);
474
+ if (!one.root) return false;
475
+ const running = await askRoom(one.open.port, '/api/activity', { stateRoot: root, timeoutMs: 3000 });
476
+ if (running.unreachable || running.now?.length) return false;
477
+ const service = home && process.platform === 'linux' ? await serviceState().catch(() => null) : null;
478
+ if (service?.active) await refreshLauncher({ stateRoot: root, launcher: launcherScript({ install, name: PACKAGE.name, version: PACKAGE.version, port: one.open.port, env: process.env }) }).catch(() => false);
479
+ await askRoom(one.open.port, '/api/room/close', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).catch(() => null);
480
+ let gone = false;
481
+ for (let tries = 0; tries < 60 && !gone; tries += 1) {
482
+ await new Promise((resolve) => setTimeout(resolve, 250));
483
+ gone = !(await knownRooms(root)).find((room) => room.id === one.id)?.open;
484
+ }
485
+ if (!gone) return false;
486
+ if (service?.active) await execFileAsync('systemctl', ['--user', 'start', UNIT_NAME], { timeout: 15000 }).catch(() => null);
487
+ else startRoom({ projectRoot: one.root, roomDir: join(root, 'rooms', one.id), port: one.open.port, home });
488
+ await room.record('room.update.along', { name: one.name, from: one.open.version, to: PACKAGE.version }).catch(() => null);
489
+ return Boolean(await roomComesUp(root, one.id));
490
+ }
491
+ // What is running in the other open rooms, by name: an update now restarts all of MADRE (L-13).
492
+ async function busyElsewhere() {
493
+ const here = basename(roomDir);
494
+ const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
495
+ const answers = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/activity', { stateRoot: root, timeoutMs: 3000 })));
496
+ return others.filter((_, index) => answers[index].now?.length).map((one) => one.name);
497
+ }
389
498
  // RESTARTING MADRE (2026-10-28): this process goes and a new one takes its place — the same
390
499
  // command, the same project, on the same port so every page open on it finds it again, and
391
500
  // without opening the browser a second time. Its listener is closed first, so the port is free
@@ -397,17 +506,38 @@ export async function createPulseServer({
397
506
  if (!args.includes('--no-open')) next.push('--no-open');
398
507
  setTimeout(() => {
399
508
  server.close(() => {
400
- let log = 'ignore';
401
- try { log = openSync(join(roomDir, 'restart.log'), 'a'); } catch { /* no witness, still restart */ }
402
509
  const env = { ...process.env, PULSE_RESTARTED: '1' };
403
510
  delete env.PULSE_UPDATE_RESTART;
404
- const child = spawn(process.execPath, [...process.execArgv, ...next], { cwd: process.cwd(), detached: process.platform !== 'win32', windowsHide: true, stdio: ['ignore', log, log], env });
511
+ // On Linux the new one takes this process's place (Q-23, src/updates.mjs takesItsPlace): it
512
+ // comes back here only when it could not.
513
+ becomeNext({ file: process.execPath, args: [...process.execArgv, ...next], env, cwd: process.cwd(), log: join(roomDir, 'restart.log') });
514
+ let log = 'ignore';
515
+ try { log = openPrivateLog(join(roomDir, 'restart.log')); } catch { /* no witness, still restart */ }
516
+ // Inside the app the new process keeps the app's pipe (the watch below): given none, it read
517
+ // the app as gone the moment it started and closed, and MADRE did not come back (2026-11-10).
518
+ const watched = process.env.MADRE_APP === '1' && salasRoom;
519
+ const child = spawn(process.execPath, [...process.execArgv, ...next], { cwd: process.cwd(), detached: process.platform !== 'win32', windowsHide: true, stdio: [watched ? 'inherit' : 'ignore', log, log], env });
405
520
  child.unref();
406
521
  setTimeout(() => process.exit(0), 200);
407
522
  });
408
523
  for (const client of clients.keys()) { try { client.end(); } catch { /* gone */ } }
409
524
  }, 300);
410
525
  }
526
+ // This process becomes the next MADRE, same PID (Q-23): on Linux with a Node that can. When it
527
+ // cannot, it returns and the caller starts a new one as before. Its log is made private first; the
528
+ // shell only adds to it.
529
+ function becomeNext({ file, args, env, cwd, log }) {
530
+ if (!takesItsPlace()) return;
531
+ const terminal = Boolean(process.stdout.isTTY);
532
+ if (!terminal) { try { closeSync(openPrivateLog(log)); } catch { /* the shell makes it */ } }
533
+ const [program, argv] = nextProcess({ file, args, log, terminal });
534
+ try {
535
+ process.chdir(cwd);
536
+ process.execve(program, argv, Object.fromEntries(Object.entries(env).filter(([, value]) => typeof value === 'string')));
537
+ } catch (error) {
538
+ console.error(`MADRE: could not take its own place (${error.message}); starting a new process instead.`);
539
+ }
540
+ }
411
541
  // How many memories of each kind, and how many travel into turns. Counted, never read out.
412
542
  function memoryCensus() {
413
543
  const all = memory ? memory.memories({ limit: 20000 }) : [];
@@ -447,7 +577,9 @@ export async function createPulseServer({
447
577
  // and never a reason for the room not to open.
448
578
  // Release channel: one registry read a day, cached for every room on this machine. On by
449
579
  // default; PULSE_UPDATE_CHECK=0 or the switch in MU/TH/UR turns it off. Never self-updates.
450
- const updatesEnabled = () => (process.env.PULSE_UPDATE_CHECK !== undefined ? process.env.PULSE_UPDATE_CHECK !== '0' : updatesConfig.check !== false);
580
+ // Always (2026-11-17, the author: every person hears of a new version and decides whether to install
581
+ // it). Only PULSE_UPDATE_CHECK=0 turns it off, for tests and QA houses; a switch saved before is not read.
582
+ const updatesEnabled = () => process.env.PULSE_UPDATE_CHECK !== '0';
451
583
  let updatesConfig = { ...((await readConfig(root)).updates ?? {}) };
452
584
  // THE MARKET from madre.run (src/market-remote.mjs): read when MADRE opens, while Look for new
453
585
  // versions is on (PULSE_MARKET=0 says no to it alone). A module got from it updates itself and
@@ -466,6 +598,9 @@ export async function createPulseServer({
466
598
  const read = await refreshCatalog({ stateRoot: root, fetchImpl: marketFetch, force, ...marketKeyed });
467
599
  const names = Object.fromEntries(MODULES.map((one) => [one.id, one.name]));
468
600
  if (read.catalog) await updateFromMarket({ ...marketTools(), catalog: read.catalog, names, remove: (id) => removeExternalModule({ id, stateRoot: root, projectRoot: canonicalProjectRoot }) }).catch(() => []);
601
+ // The ways of working got from the Market (H-4): a newer version installs itself, one taken
602
+ // back is removed, and one that would bring a program nobody accepted waits for the person.
603
+ if (read.catalog) await updateSkillsFromMarket({ stateRoot: root, projectRoot: canonicalProjectRoot, catalog: read.catalog, madre: PACKAGE.version, fetchImpl: marketFetch }).catch(() => null);
469
604
  // MADRE's own modules, newer from the Market and signed with the factory key (src/builtin-updates.mjs):
470
605
  // what came or was taken back is run from now on, in this project and in Home.
471
606
  if (read.catalog) {
@@ -481,6 +616,20 @@ export async function createPulseServer({
481
616
  await adoptBuiltinUpdates({ stateRoot: root, enabled: marketOn(), ...factoryKeyed }).catch((error) => console.error(`MADRE modules: ${error.message}`));
482
617
  void syncMarket().catch(() => null);
483
618
  const install = detectInstall({ projectRoot: canonicalProjectRoot });
619
+ // Home as a service of this computer (src/service.mjs, L-3): the script it starts with says the
620
+ // version and the PATH of now, and when the service started it the projects that were open come
621
+ // back, each on the port it keeps (L-6). Not waited for by the start.
622
+ const homeLauncher = () => launcherScript({ install, name: PACKAGE.name, version: PACKAGE.version, port: openPort ?? 4317, env: process.env });
623
+ const afterOpen = async () => {
624
+ if (!salasRoom || testMode) return;
625
+ await refreshLauncher({ stateRoot: root, launcher: homeLauncher() }).catch(() => false);
626
+ if (process.env.MADRE_SERVICE !== '1') return;
627
+ const here = basename(roomDir);
628
+ for (const one of await knownRooms(root).catch(() => [])) {
629
+ if (one.id === here || one.open || !one.keepOpen || !one.root) continue;
630
+ try { startRoom({ projectRoot: one.root, roomDir: join(root, 'rooms', one.id) }); } catch (error) { console.error(`MADRE could not reopen ${one.name}: ${error.message}`); }
631
+ }
632
+ };
484
633
  async function versionView({ force = false } = {}) {
485
634
  const check = await checkForUpdate({ name: PACKAGE.name, current: PACKAGE.version, cacheFile: join(root, 'updates.json'), fetchImpl: reportFetch, enabled: updatesEnabled(), force });
486
635
  return { project: canonicalProjectRoot, ...check, notes: Boolean(notesFor(PACKAGE.version)), name: PACKAGE.name, install, command: updateCommand(install, PACKAGE.name, check.latest ?? 'latest'), release: check.latest ? releaseUrl(PACKAGE.repository, check.latest, roomLanguage()) : null, envWins: process.env.PULSE_UPDATE_CHECK !== undefined };
@@ -587,7 +736,121 @@ export async function createPulseServer({
587
736
  } catch { /* the plain count below */ }
588
737
  return { bytes: freemem(), source: 'freemem' };
589
738
  }
739
+ let logsSyncedAt = 0;
740
+ // The author's own reading of what fails in every copy (src/telemetry.mjs, madre.run's
741
+ // /api/telemetry): the same token as the usage, the same copy run from source. Read once every ten
742
+ // minutes for the two that use it, the errors widget and madre-logs' filing: behind it is a heavy
743
+ // query, and madre.run's reads of the day ran out once (2026-11-04).
744
+ async function errorsReading() {
745
+ const kept = widgetReadings.get('errors');
746
+ if (kept && Date.now() - kept.at < 600000) return kept.reading;
747
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
748
+ if (!token) return null;
749
+ 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);
750
+ const body = answer?.ok ? await answer.json().catch(() => null) : null;
751
+ const reading = body?.ok ? { available: true, ...body } : { available: false, status: answer?.status ?? 0 };
752
+ widgetReadings.set('errors', { at: Date.now(), reading });
753
+ return reading;
754
+ }
755
+ // The sentinel's reports kept at madre.run (its /v1/reports, functions/v1 of the landing), read with
756
+ // the same token as the diagnostics, only by the author's copy run from source.
757
+ async function sentinelReading() {
758
+ const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
759
+ if (!token) return null;
760
+ const answer = await reportFetch(process.env.PULSE_SENTINEL_READ_URL ?? 'https://madre.run/v1/reports', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) }).catch(() => null);
761
+ const body = answer?.ok ? await answer.json().catch(() => null) : null;
762
+ return Array.isArray(body?.reports) ? body.reports : null;
763
+ }
764
+ // THE AUTHOR'S NOTICES (Q-11, src/notices.mjs). Every copy asks madre.run for them on its own,
765
+ // with or without the diagnostics, and shows the ones signed with the author's key that are for it.
766
+ const NOTICES_KEY_FILE = process.env.MADRE_NOTICES_KEY_DIR ? join(process.env.MADRE_NOTICES_KEY_DIR, 'ed25519.pem') : join(homedir(), '.madre', 'avisos', 'ed25519.pem');
767
+ // The author's notices always arrive (2026-11-17): a new version, a fix or a service stop is for everyone.
768
+ const noticesEnabled = async () => true;
769
+ async function noticesForPage() {
770
+ void refreshNotices({ stateRoot: root }).catch(() => null);
771
+ const place = await environmentOnce().catch(() => null);
772
+ const enabled = await noticesEnabled();
773
+ return { enabled, notices: await currentNotices({ stateRoot: root, version: PACKAGE.version, wsl: Boolean(place?.wsl), enabled }).catch(() => []) };
774
+ }
775
+ void refreshNotices({ stateRoot: root }).catch(() => null);
776
+ // Only the author writes them: the copy run from source, with the author's token and the private key.
777
+ async function ownerCanNotify() {
778
+ if (!FROM_SOURCE) return false;
779
+ const token = await readSecret(root, OWNER_VAULT, 'usage').catch(() => null);
780
+ return Boolean(token) && existsSync(NOTICES_KEY_FILE);
781
+ }
782
+ // MADRE App's subscription (src/billing.mjs, docs/private/SUSCRIPCION.md): only inside the app and
783
+ // only once the author's signed switch says so. Every server of the house reads the same files;
784
+ // Home alone asks madre.run, so a copy asks once however many projects are open.
785
+ let billing = { view: { state: 'off' }, saved: {}, at: 0 };
786
+ const switchKey = billingKeys.switchKey ?? undefined;
787
+ const billingKey = billingKeys.billingKey ?? BILLING_PUBLIC_KEY;
788
+ const billingView = () => billing.view;
789
+ // The days with everything the author's switch gives, or null while it is off (Q-26): the gate
790
+ // and the manual name them only when they exist.
791
+ const trialDaysNow = async () => {
792
+ const now = await billingNow().catch(() => billing);
793
+ return now.view.state === 'off' ? null : now.view.trialDays ?? null;
794
+ };
795
+ async function billingNow({ ask = false } = {}) {
796
+ if (!billingInApp()) return billing;
797
+ if (ask && salasRoom) {
798
+ const due = Date.now() - billingAsked > SWITCH_EVERY_MS;
799
+ if (due) { billingAsked = Date.now(); await askSwitch(root, { switchKey }).catch(() => null); }
800
+ if (billing.saved?.order && Date.now() - orderAsked > ORDER_EVERY_MS) { orderAsked = Date.now(); await askOrder(root, { billingKey }).catch(() => null); }
801
+ // Turning it on with the email of the payment (2026-11-18): the key arrives once the button is confirmed.
802
+ if (billing.saved?.recovery && Date.now() - recoveryAsked > ORDER_EVERY_MS) { recoveryAsked = Date.now(); await askRecovery(root, { billingKey }).catch(() => null); }
803
+ }
804
+ billing = { ...(await loadBilling(root, { switchKey, billingKey }).catch(() => ({ view: { state: 'off' }, saved: {} }))), at: Date.now() };
805
+ return billing;
806
+ }
807
+ let billingAsked = 0;
808
+ let orderAsked = 0;
809
+ let recoveryAsked = 0;
810
+ // Home keeps the copy current: the switch every half hour, a key it waits for every few seconds,
811
+ // and a fresh key every twelve hours.
812
+ if (billingInApp() && salasRoom && !testMode) {
813
+ const tick = async () => {
814
+ await billingNow({ ask: true }).catch(() => null);
815
+ if (billing.key) { await renewKey(root, { billingKey }).catch(() => null); await billingNow().catch(() => null); }
816
+ };
817
+ void tick();
818
+ const billingTimer = setInterval(() => void tick(), 60000);
819
+ billingTimer.unref?.();
820
+ const orderTimer = setInterval(() => {
821
+ const paying = billing.saved?.order && Date.now() - Date.parse(billing.saved.order.at) < ORDER_FAST_MS;
822
+ const recovering = billing.saved?.recovery && Date.now() - Date.parse(billing.saved.recovery.at) < RECOVERY_KEEP_MS;
823
+ if (paying || recovering) void billingNow({ ask: true }).catch(() => null);
824
+ }, ORDER_EVERY_MS);
825
+ orderTimer.unref?.();
826
+ } else void billingNow().catch(() => null);
827
+ // What the page reads: where this copy stands and the one thing to tell the person now, if any.
828
+ async function billingForPage({ ask = true } = {}) {
829
+ const now = await billingNow({ ask });
830
+ return { ...now.view, moment: dueMoment(now.view, now.saved), project: salasRoom ? null : { room: projectRoomId(canonicalProjectRoot), name: basename(canonicalProjectRoot) }, site: billingSite() };
831
+ }
590
832
  async function homeWidget(kind) {
833
+ // The author's error log (src/madre-logs.mjs): read from this disk every time, so Home shows it
834
+ // as agents add and close errors. Only in the author's copy run from source, and only Home serves it.
835
+ if (kind === 'madrelogs') {
836
+ // And only in the author's own copy, with the author's token (2026-11-10): a clean copy run from
837
+ // this same source (a test house, the Mac app pointed at it) showed it too.
838
+ if (!FROM_SOURCE || !salasRoom || !(await readSecret(root, OWNER_VAULT, 'usage').catch(() => null))) return null;
839
+ const { keepSync, readLogs, syncDiagnostics, syncSentinel } = await import('./madre-logs.mjs');
840
+ // The diagnostics filed on their own (src/madre-logs.mjs, syncDiagnostics): every ten minutes
841
+ // while the widget is read, with the author's token, never waited for by the reading.
842
+ // And the sentinel's reports, the failures people's copies could not explain (2026-11-08).
843
+ if (Date.now() - logsSyncedAt > 600000) {
844
+ logsSyncedAt = Date.now();
845
+ void (async () => {
846
+ const reading = await errorsReading();
847
+ if (Array.isArray(reading?.errors)) await keepSync(await syncDiagnostics({ groups: reading.errors }));
848
+ const reports = await sentinelReading();
849
+ if (Array.isArray(reports)) await keepSync({ ...(await syncSentinel({ reports })), label: 'Centinela' });
850
+ })().catch((error) => console.error(`MADRE could not file the diagnostics in madre-logs: ${error.message}`));
851
+ }
852
+ return readLogs();
853
+ }
591
854
  const kept = widgetReadings.get(kind);
592
855
  // madre.run's count moves once a day: the author's reading is kept ten minutes, the Mac's thirty seconds.
593
856
  if (kept && Date.now() - kept.at < (kind === 'usage' || kind === 'errors' ? 600000 : 30000)) return kept.reading;
@@ -599,7 +862,7 @@ export async function createPulseServer({
599
862
  } else if (kind === 'servers') {
600
863
  const rooms = await openProjects();
601
864
  const projects = await Promise.all(rooms.map(async (one) => {
602
- const answer = await askRoom(one.open.port, '/api/ports', { timeoutMs: 4000 });
865
+ const answer = await askRoom(one.open.port, '/api/ports', { stateRoot: root, timeoutMs: 4000 });
603
866
  if (answer.unreachable && answer.status === 412) return { id: one.id, name: one.name, preview: false, ports: [] };
604
867
  if (answer.unreachable || answer.outdated) return { id: one.id, name: one.name, unreachable: true, ports: [] };
605
868
  return { id: one.id, name: one.name, preview: true, ports: (answer.ports ?? []).map((port) => ({ port: port.port, status: port.status ?? null, command: port.command ?? null })) };
@@ -607,7 +870,7 @@ export async function createPulseServer({
607
870
  reading = { available: projects.some((one) => one.preview), projects };
608
871
  } else if (kind === 'memory' || kind === 'models') {
609
872
  const rooms = await openProjects();
610
- const projects = await Promise.all(rooms.map(async (one) => ({ id: one.id, name: one.name, ...(readinessOf(await askRoom(one.open.port, '/api/dataset', { timeoutMs: 6000 })) ?? { unreachable: true }) })));
873
+ const projects = await Promise.all(rooms.map(async (one) => ({ id: one.id, name: one.name, ...(readinessOf(await askRoom(one.open.port, '/api/dataset', { stateRoot: root, timeoutMs: 6000 })) ?? { unreachable: true }) })));
611
874
  reading = kind === 'memory'
612
875
  ? { available: projects.some((one) => !one.unreachable), projects }
613
876
  : { available: true, ollama: { running: Boolean(ollama.running), models: (ollama.models ?? []).map((model) => model.name).filter(Boolean) }, projects: await withLocalAi(projects) };
@@ -627,13 +890,8 @@ export async function createPulseServer({
627
890
  const body = answer?.ok ? await answer.json().catch(() => null) : null;
628
891
  reading = body?.ok ? { available: true, ...body, mine } : { available: false, status: answer?.status ?? 0 };
629
892
  } else if (kind === 'errors') {
630
- // The author's own reading of what fails in every copy (src/telemetry.mjs, madre.run's
631
- // /api/telemetry): the same token as the usage, the same copy run from source.
632
- const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
633
- if (!token) return null;
634
- 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);
635
- const body = answer?.ok ? await answer.json().catch(() => null) : null;
636
- reading = body?.ok ? { available: true, ...body } : { available: false, status: answer?.status ?? 0 };
893
+ reading = await errorsReading();
894
+ if (!reading) return null;
637
895
  } else if (kind === 'live' || kind === 'installs' || kind === 'environments') {
638
896
  // The author's board (madre.run's /api/metrics, 2026-10-30): copies on now and off, installs,
639
897
  // updates and uninstalls by day, and where they run. One reading for the three widgets, kept a
@@ -654,6 +912,7 @@ export async function createPulseServer({
654
912
  // day) — and a source that fails keeps its last good reading, said as old.
655
913
  const token = FROM_SOURCE ? await readSecret(root, OWNER_VAULT, 'usage') : null;
656
914
  if (!token) return null;
915
+ const { keepHistory, readGithub, readHistory, readNpm, rumboModel } = await import('./rumbo.mjs');
657
916
  const source = async (name, ttl, read) => {
658
917
  const kept = rumboSources.get(name);
659
918
  if (kept && Date.now() - (kept.tried ?? kept.at) < ttl) return kept;
@@ -675,10 +934,33 @@ export async function createPulseServer({
675
934
  reading = funnel.value || github.value || npm.value
676
935
  ? { available: true, ...rumboModel({ madre: funnel.value, github: github.value, npm: npm.value, history }), sources: { madre: { ...said(funnel), status: rumboStatus }, github: said(github), npm: said(npm) } }
677
936
  : { available: false, status: rumboStatus };
937
+ } else if (kind === 'notices') {
938
+ // The author's notices (Q-11, src/notices.mjs): what madre.run serves now, checked as every copy
939
+ // checks it. Only in the copy run from source that holds the author's token and the notices' key.
940
+ if (!(await ownerCanNotify())) return null;
941
+ const answer = await globalThis.fetch(noticesUrl(), { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) }).catch(() => null);
942
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
943
+ const feed = data ? readFeed(data) : null;
944
+ const now = Date.now();
945
+ reading = {
946
+ available: true,
947
+ read: Boolean(feed),
948
+ notices: (feed?.entries ?? []).map((entry) => readNotice(entry.notice)).filter(Boolean)
949
+ .map((one) => ({ ...one, when: now < Date.parse(one.from) ? 'later' : now >= Date.parse(one.until) ? 'over' : 'now' })),
950
+ unverified: Math.max(0, (data?.notices?.length ?? 0) - (feed?.entries?.length ?? 0)),
951
+ };
952
+ } else if (kind === 'billing') {
953
+ // The author's switch for MADRE App's subscription (src/billing.mjs): what madre.run serves now,
954
+ // checked as every app checks it, and whether the key of the subscription keys exists yet.
955
+ if (!(await ownerCanNotify())) return null;
956
+ const answer = await globalThis.fetch(`${billingSite()}/api/cobro`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) }).catch(() => null);
957
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
958
+ const served = data?.switch ? verifiedSwitch(data, switchKey) : null;
959
+ reading = { available: true, read: Boolean(data), switch: served, unverified: Boolean(data?.switch && !served), keyReady: Boolean(billingKey) };
678
960
  } else if (kind === 'coordinator' && !salasRoom) {
679
961
  // Home's page is served by every project too: the Coordinator's record is its own room's.
680
962
  const coordinator = (await knownRooms(root)).find((one) => one.id === salasRoomId(root));
681
- const answer = coordinator?.open ? await askRoom(coordinator.open.port, '/api/salas/widget?kind=coordinator', { timeoutMs: 6000 }) : null;
963
+ const answer = coordinator?.open ? await askRoom(coordinator.open.port, '/api/salas/widget?kind=coordinator', { stateRoot: root, timeoutMs: 6000 }) : null;
682
964
  reading = answer && !answer.unreachable && !answer.outdated ? answer : { available: false };
683
965
  } else if (kind === 'coordinator') {
684
966
  const notes = memory ? memory.memories({ limit: 5000 }) : [];
@@ -691,7 +973,7 @@ export async function createPulseServer({
691
973
  }
692
974
  async function lobbyGlance(one) {
693
975
  if (!one.open) { lobbyGlances.delete(one.id); return null; }
694
- const reading = await askRoom(one.open.port, '/api/glance?census=1', { timeoutMs: 1200 });
976
+ const reading = await askRoom(one.open.port, '/api/glance?census=1', { stateRoot: root, timeoutMs: 1200 });
695
977
  if (!reading.unreachable && !reading.outdated) {
696
978
  lobbyGlances.set(one.id, { port: one.open.port, reading, at: Date.now() });
697
979
  return reading;
@@ -735,7 +1017,7 @@ export async function createPulseServer({
735
1017
  function wireLocal(target) {
736
1018
  if (!target) return;
737
1019
  target.setInvoker('ollama', localWiring.archivist);
738
- target.setInvoker(MADRE_ADAPTER, localWiring.madre ? madreInvoker({ memory, ollama: () => ({ ...ollama, chatModel: ollama.madreModel ?? ollama.chatModel }), fetchImpl: reportFetch }) : null);
1020
+ target.setInvoker(MADRE_ADAPTER, localWiring.madre ? madreInvoker({ memory, ollama: () => ({ ...ollama, chatModel: ollama.madreModel ?? ollama.chatModel }), fetchImpl: localFetch }) : null);
739
1021
  }
740
1022
  const ollamaSettings = async () => ({ enabled: true, embeddings: true, archivist: true, agent: true, ...((await readConfig(root)).modules?.ollama ?? {}) });
741
1023
  // Whether this project uses the local AI at all, as Home decides it (src/local-ai.mjs).
@@ -857,6 +1139,28 @@ export async function createPulseServer({
857
1139
  const base = fit.recommended.train ?? MODEL_TIERS[1];
858
1140
  return { roomDir, recipeDir: fileURLToPath(new URL('../docs/training/', import.meta.url)), modelName: `madre-${slug}`, baseModel: base.base, memoryGb: fit.hardware?.memoryGb ?? Math.round(totalmem() / 1024 ** 3), fit };
859
1141
  }
1142
+ // TRYING @madre ON THIS PROJECT (2026-11-10, asked by the author). It used to be announced on a
1143
+ // project's first page, with its one key greyed out: there was nothing to compare it with yet. Now
1144
+ // it is offered in the conversation once agents have answered enough real questions here
1145
+ // (LOCAL_TRY_MIN), with «Try it» and «Remind me later»; unanswered or put off, it comes back after
1146
+ // a few days (LOCAL_TRY_AGAIN_MS), until the project has been measured.
1147
+ async function offerLocalTry(target, { now = Date.now() } = {}) {
1148
+ if (!target || !memory || !localWiring.madre) return;
1149
+ let exams = {};
1150
+ try { exams = JSON.parse(memory.metaGet('exams') ?? '{}'); } catch { exams = {}; }
1151
+ if (exams.match?.ran) return;
1152
+ const offered = Date.parse(memory.metaGet('local.offered') ?? '');
1153
+ if (Number.isFinite(offered) && now - offered < LOCAL_TRY_AGAIN_MS) return;
1154
+ if ((await target.answeredByAgents().catch(() => 0)) < LOCAL_TRY_MIN) return;
1155
+ memory.metaSet('local.offered', new Date(now).toISOString());
1156
+ const model = agents.find((agent) => agent.id === MADRE_AGENT_ID)?.version ?? null;
1157
+ await target.record('local.present', {
1158
+ model,
1159
+ offer: true,
1160
+ // Ollama on another computer of the network (NUE-07): the card does not say «on this Mac».
1161
+ ...(ollama.host && !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?\/?$/i.test(String(ollama.host)) ? { remote: true } : {}),
1162
+ });
1163
+ }
860
1164
  async function wireOllama({ probe: doProbe = true } = {}) {
861
1165
  if (doProbe) { ollama = await ollamaProbe(); ollama.autoModel = ollama.chatModel; }
862
1166
  // A model trained on this room (docs/training) is named madre-<project>: @madre uses it when it exists.
@@ -879,7 +1183,7 @@ export async function createPulseServer({
879
1183
  const embedder = createEmbedder({ key, env: embedEnvFor(await memoryConfig()), ollama: useEmbeddings ? ollama : null, ollamaEmbedder });
880
1184
  if (room) room.setEmbedder(embedder); else memory.attachEmbedder(embedder);
881
1185
  }
882
- localWiring.archivist = useArchivist ? ollamaInvoker({ host: ollama.host, model: ollama.chatModel, fetchImpl: reportFetch }) : null;
1186
+ localWiring.archivist = useArchivist ? ollamaInvoker({ host: ollama.host, model: ollama.chatModel, fetchImpl: localFetch }) : null;
883
1187
  // @madre: the fifth agent, present whenever Ollama has a chat model and the human left it on.
884
1188
  const fifth = madreAgent({ ...ollama, chatModel: ollama.madreModel ?? ollama.chatModel }, { enabled: settings.enabled && settings.agent !== false });
885
1189
  const index = agents.findIndex((agent) => agent.id === MADRE_AGENT_ID);
@@ -896,17 +1200,7 @@ export async function createPulseServer({
896
1200
  // the second thing is the one a person needs told. Said once per model, in the room, with
897
1201
  // the one button that settles it — the crew line above fires only when the crew CHANGES,
898
1202
  // and a room whose Ollama was already up when it opened would never have heard it.
899
- if (fifth.ready && memory && memory.metaGet('local.announced') !== fifth.version) {
900
- let checked = null;
901
- try { checked = JSON.parse(memory.metaGet('exams') ?? '{}').match ?? null; } catch { checked = null; }
902
- memory.metaSet('local.announced', fifth.version);
903
- await room.record('local.present', {
904
- model: fifth.version,
905
- // Ollama on another computer of the network (NUE-07): the card does not say «on this Mac».
906
- ...(ollama.host && !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?\/?$/i.test(String(ollama.host)) ? { remote: true } : {}),
907
- checked: checked?.ran ? { passed: Boolean(checked.passed), matched: checked.matched ?? 0, n: checked.n ?? 0, at: checked.at ?? null } : null,
908
- });
909
- }
1203
+ await offerLocalTry(room);
910
1204
  }
911
1205
  return { ...ollama, settings, project, embeddings: Boolean(useEmbeddings), archivist: Boolean(useArchivist), agent: fifth.ready };
912
1206
  }
@@ -938,6 +1232,30 @@ export async function createPulseServer({
938
1232
  };
939
1233
  adoptOllamaHost(await readConfig(root));
940
1234
  await wireOllama();
1235
+ // The first look gives Ollama 1.5 s. On a busy machine (a 14B loading, a knowledge load running)
1236
+ // that is not enough, and before this the local AI stayed off for the whole run: no @madre, the
1237
+ // archive written by a paid agent, until a restart (L-14, Carlos's server, 2026-11-12). Now it is
1238
+ // asked again on its own, with more time, until it answers.
1239
+ let ollamaRetry = null;
1240
+ let ollamaRetries = 0;
1241
+ const askOllamaAgain = () => {
1242
+ clearTimeout(ollamaRetry);
1243
+ ollamaRetry = null;
1244
+ if (ollama.running || ollama.disabled || !ollamaRetryMs.length) return;
1245
+ const wait = ollamaRetryMs[Math.min(ollamaRetries, ollamaRetryMs.length - 1)];
1246
+ ollamaRetries += 1;
1247
+ ollamaRetry = setTimeout(async () => {
1248
+ ollamaRetry = null;
1249
+ const seen = await ollamaProbe({ timeoutMs: 10_000 }).catch(() => null);
1250
+ if (seen?.running && !ollama.running) {
1251
+ ollama = { ...seen, autoModel: seen.chatModel };
1252
+ await wireOllama({ probe: false }).catch((error) => console.error(`MADRE could not wire Ollama: ${error.message}`));
1253
+ }
1254
+ askOllamaAgain();
1255
+ }, wait);
1256
+ ollamaRetry.unref?.();
1257
+ };
1258
+ askOllamaAgain();
941
1259
  const memoryServer = memory ? memoryServerFor({ dbFile: memory.file, projectRoot: canonicalProjectRoot }) : null;
942
1260
  // MOTHER's channel to the crew: her seal's fingerprint lives in the memory
943
1261
  // file, so a deleted or edited .pulse/mother.env is noticed.
@@ -964,6 +1282,19 @@ export async function createPulseServer({
964
1282
  return /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) && (site === undefined || site === 'same-origin' || site === 'none') && request.headers.origin === `http://${host}`;
965
1283
  };
966
1284
  const onlyPressed = (mode) => !overrideSettings(overrideConfig).keys[mode].startsWith('phrase');
1285
+ // Installing a module by hand still asks for the #4 key (2026-11-02, external review #5):
1286
+ // before, any program on the computer
1287
+ // installed one with a single POST and it ran the next time the modules loaded. The answer is
1288
+ // the refusal to send, or null when the key holds.
1289
+ const moduleKeyRefused = (request, payload) => {
1290
+ const now = Date.now();
1291
+ while (keyMisses.length && keyMisses[0] < now - 60000) keyMisses.shift();
1292
+ if (keyMisses.length >= 8) return [429, { error: t('Too many wrong confirmations. Wait a minute and try again.') }];
1293
+ if (onlyPressed(4) && !pressedHere(request)) return [403, { error: t('This is confirmed from MADRE\'s own page, on this computer.') }];
1294
+ if (keyHolds(overrideConfig, { mode: 4, words: payload?.words })) return null;
1295
+ keyMisses.push(now);
1296
+ return [403, { error: t('That is not it. Try again, or cancel.'), denied: true }];
1297
+ };
967
1298
  const PASS_ONCE_MS = 30 * 60 * 1000;
968
1299
  // `asked` is a window the human chose on an agent's request for this mode (2026-10-14): one of
969
1300
  // the windows the project allows, never longer, and only for that agent and mode.
@@ -995,6 +1326,12 @@ export async function createPulseServer({
995
1326
  }
996
1327
  let listening = null;
997
1328
  const listeningPort = () => listening?.address?.()?.port ?? Number(process.env.PULSE_PORT ?? 4317);
1329
+ // Where the agents' headless browser opens RIPLEY's preview (src/modules/playwright.mjs): under the
1330
+ // preview's key when the ficha is on, since that browser has no cookie.
1331
+ const previewBase = async () => {
1332
+ const ficha = fichaOn ? await currentFicha() : null;
1333
+ return ficha ? `/preview/${previewKey(ficha)}` : '/preview';
1334
+ };
998
1335
  // One CONTROL desk for the whole project, shared by every conversation alive at once: a single
999
1336
  // holder of the working tree whichever chat asked, and an UNDO that works from any of them.
1000
1337
  const controlDesk = new ControlDesk({ projectRoot, guardRecord: join(roomDir, 'guard.json') });
@@ -1007,7 +1344,19 @@ export async function createPulseServer({
1007
1344
  controlDesk,
1008
1345
  privacy,
1009
1346
  // Modules may hand tools to a turn; the room asks once per turn, the server knows the port.
1010
- toolsForTurn: async (turn) => modulesToolsForTurn(await moduleContext(), { ...turn, port: listeningPort(), roomDir }),
1347
+ toolsForTurn: async (turn) => modulesToolsForTurn(await moduleContext(), { ...turn, port: listeningPort(), roomDir, preview: await previewBase() }),
1348
+ // Ways of working this project keeps (H-2): read from disk each turn, so a skill the person just
1349
+ // installed or switched is in the very next message, and chosen against what was asked.
1350
+ skillsForTurn: async (turn) => {
1351
+ const { loaded, failures } = await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot });
1352
+ for (const one of failures) console.error(`MADRE skills: ${one.dir} was not read (${one.error})`);
1353
+ // Called by its name (2026-11-10, the author): «/habilidad explicamelo-facil …» brings that one
1354
+ // into this turn whatever its switch says; the rest are still chosen by what was asked.
1355
+ const called = /^\s*\/(?:habilidad|skill)\s+([a-z][a-z0-9-]{1,39})\b/i.exec(String(turn.text ?? ''))?.[1]?.toLowerCase();
1356
+ const named = called ? loaded.find((one) => one.id === called) : null;
1357
+ const rest = chooseSkills({ skills: named ? loaded.filter((one) => one !== named) : loaded, text: turn.text, config: await readConfig(root), roomId: scopeRoom }).chosen;
1358
+ return named ? [{ ...named, state: 'always', why: [`/habilidad ${named.id}`] }, ...rest].slice(0, 3) : rest;
1359
+ },
1011
1360
  // What BISHOP reads for a turn is recorded in that turn's conversation, not the open one.
1012
1361
  bishopForTurn: salasRoom ? async (turn) => moduleById('bishop').promptForTurn({ ...(await moduleContext()), record: (type, payload) => ((turn.turn && liveRooms().find((one) => one.runningTurn?.(turn.turn))) || room).record(type, payload) }, turn) : null,
1013
1362
  // Fase 3e: notes a link with automatic recall brings to a turn. Never in the room of Salas
@@ -1036,6 +1385,8 @@ export async function createPulseServer({
1036
1385
  // S-032: in the room of Salas nobody delegates. BISHOP speaks there, and what it sets in
1037
1386
  // motion goes through its own plans, never through a ```pulse plan of that room.
1038
1387
  delegation: salasRoom ? false : delegation,
1388
+ // In the limited mode of MADRE App (src/billing.mjs), no plan among several AIs.
1389
+ plansAllowed: () => billingView().state !== 'limited',
1039
1390
  maxPlanSteps,
1040
1391
  ...own,
1041
1392
  });
@@ -1117,6 +1468,18 @@ export async function createPulseServer({
1117
1468
  if (!Array.isArray(patch.opencode.hidden) || patch.opencode.hidden.some((id) => typeof id !== 'string' || !/^[\w.-]{1,60}$/.test(id))) throw new Error(t('Hidden providers must be a list of provider names.'));
1118
1469
  config.opencode = { ...(config.opencode ?? {}), hidden: [...new Set(patch.opencode.hidden)] };
1119
1470
  }
1471
+ // Up to three of OpenCode's models kept at the top of its chooser (2026-11-10), for every project.
1472
+ if (patch.opencode && 'favorites' in patch.opencode) {
1473
+ if (!Array.isArray(patch.opencode.favorites) || patch.opencode.favorites.some((name) => typeof name !== 'string' || !/^[\w.:@/+-]{1,200}$/.test(name))) throw new Error(t('Favourite models must be a list of model names.'));
1474
+ config.opencode = { ...(config.opencode ?? {}), favorites: [...new Set(patch.opencode.favorites)].slice(0, 3) };
1475
+ }
1476
+ // Every other agent's, the same way (2026-11-11): { agent, models }.
1477
+ if (patch.favorites) {
1478
+ const { agent, models } = patch.favorites;
1479
+ if (typeof agent !== 'string' || !/^[a-z][\w-]{0,30}$/.test(agent) || agent === 'opencode') throw new Error(t('Favourite models must be a list of model names.'));
1480
+ if (!Array.isArray(models) || models.some((name) => typeof name !== 'string' || !/^[\w.:@/+-]{1,200}$/.test(name))) throw new Error(t('Favourite models must be a list of model names.'));
1481
+ config.favorites = { ...(config.favorites ?? {}), [agent]: [...new Set(models)].slice(0, 3) };
1482
+ }
1120
1483
  if (patch.timeouts) {
1121
1484
  const timeouts = { ...room.settings().agentTimeouts };
1122
1485
  for (const [key, value] of Object.entries(patch.timeouts)) {
@@ -1321,15 +1684,19 @@ export async function createPulseServer({
1321
1684
  async function redetectAgents({ announce = true } = {}) {
1322
1685
  if (!detector) return { changed: false, agents };
1323
1686
  let changed = false;
1324
- for (const next of await detector()) {
1687
+ for (const found of await detector()) {
1688
+ const next = await refreshCodexRoute(found);
1325
1689
  const index = agents.findIndex((item) => item.id === next.id);
1326
1690
  if (index === -1) { agents.push(next); changed = true; continue; }
1327
1691
  const before = agents[index];
1328
- if (before.detected !== next.detected || before.ready !== next.ready || before.version !== next.version || before.path !== next.path || JSON.stringify(before.route ?? null) !== JSON.stringify(next.route ?? null)) {
1329
- agents[index] = { ...before, ...next };
1692
+ if (before.detected !== next.detected || before.ready !== next.ready || before.version !== next.version || before.path !== next.path || before.adapter !== next.adapter || JSON.stringify(before.route ?? null) !== JSON.stringify(next.route ?? null)) {
1693
+ // `viaApi` goes when the CLI arrives: a spread would keep the old one.
1694
+ agents[index] = { ...before, ...next, viaApi: next.viaApi };
1695
+ if (!next.viaApi) delete agents[index].viaApi;
1330
1696
  changed = true;
1331
1697
  }
1332
1698
  }
1699
+ setAgentsViaApi(agents);
1333
1700
  await refreshSessions();
1334
1701
  if (changed && announce) {
1335
1702
  await room.record('agents.updated', {
@@ -1346,7 +1713,8 @@ export async function createPulseServer({
1346
1713
  async function installAgent(id) {
1347
1714
  const agent = agents.find((item) => item.id === id);
1348
1715
  if (!agent) return { status: 404, body: { error: t('Unknown agent: {id}.', { id }) } };
1349
- if (agent.detected) return { status: 409, body: { error: t('{label} is already installed.', { label: agent.label }) } };
1716
+ // Gemini answering through its API with only a key is not its CLI: that one can still be installed.
1717
+ if (agent.detected && !agent.viaApi) return { status: 409, body: { error: t('{label} is already installed.', { label: agent.label }) } };
1350
1718
  const plan = installPlanFor(agent, { prefix: toolsPrefix() });
1351
1719
  if (!plan) return { status: 404, body: { error: t('MADRE does not know how to install {id}.', { id }) } };
1352
1720
  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 }) } };
@@ -1600,6 +1968,8 @@ export async function createPulseServer({
1600
1968
  // What OpenCode answered with, and what failed for which provider (src/opencode-health.mjs):
1601
1969
  // the next failure offers a model that works instead of a sentence in English.
1602
1970
  if (event.type === 'agent.completed' && event.payload?.agent === 'opencode') void noteOpenCodeTurn(root, { ok: true, model: event.payload.ranOn ?? null }).catch(() => null);
1971
+ // A turn answered by an agent may be the one that makes @madre worth trying here.
1972
+ if (event.type === 'agent.completed' && event.payload?.agent !== MADRE_AGENT_ID) void offerLocalTry(target).catch(() => null);
1603
1973
  if (event.type === 'message.failed' && event.payload?.target === 'opencode') void noteOpenCodeTurn(root, { ok: false, model: event.payload.ranOn ?? null, error: event.payload.error }).catch(() => null);
1604
1974
  const listening = MODULES.filter((module) => typeof module.onEvent === 'function');
1605
1975
  if (!listening.length) return;
@@ -1653,7 +2023,15 @@ export async function createPulseServer({
1653
2023
  unsubscribe = room.subscribe(() => { void broadcastPending(); });
1654
2024
  unsubscribeModules = wireModules(room, chatId);
1655
2025
  unsubscribeAsks = trackAsks(room, historicalEvents);
1656
- unsubscribeSentinel = room.subscribe((event) => { void sentinel.observe(event).catch(() => null); countForDiagnostics(event); });
2026
+ unsubscribeSentinel = room.subscribe((event) => {
2027
+ void sentinel.observe(event).catch(() => null);
2028
+ countForDiagnostics(event);
2029
+ if (event?.type === 'extension.install.started') installLine = null;
2030
+ else if (event?.type === 'extension.install.output') {
2031
+ const said = (event.payload?.lines ?? []).map((line) => String(line).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').trim()).filter((line) => line && !/^[\s{}\[\](),:;"'`]*$/.test(line)).at(-1);
2032
+ if (said) installLine = said.slice(0, 160);
2033
+ }
2034
+ });
1657
2035
  unsubscribeEyecat = room.subscribe((event) => { void eyecat.observe(event).catch(() => null); });
1658
2036
  unsubscribeGhost = room.subscribeGhost((event) => { for (const client of clients.keys()) writeEvent(client, event); });
1659
2037
  unsubscribeLive = room.subscribeLive((event) => { for (const client of clients.keys()) writeEvent(client, event); });
@@ -1717,7 +2095,7 @@ export async function createPulseServer({
1717
2095
  if (!one) continue;
1718
2096
  for (const item of one.activity()) now.push({ ...item, chat: id, chatTitle: titleOf(id) });
1719
2097
  }
1720
- if (installing) now.push({ kind: 'install', what: installing, model: pulling?.model ?? null, startedAt: installingSince || null });
2098
+ if (installing) now.push({ kind: 'install', what: installing, model: pulling?.model ?? null, startedAt: installingSince || null, line: installLine, stoppable: Boolean(pulling) });
1721
2099
  const done = await recentInProject(roomDir, { also: [chatId, ...parked.keys()] }).catch(() => []);
1722
2100
  return { room: thisRoomId, name: salasRoom ? null : basename(canonicalProjectRoot), home: salasRoom, version: PACKAGE.version ?? null, now, done };
1723
2101
  }
@@ -1919,16 +2297,21 @@ export async function createPulseServer({
1919
2297
  // The switches a room holds itself, as this project says them (module-scope.mjs). Read again
1920
2298
  // before every message, so a switch moved in Home reaches a project that is already open.
1921
2299
  function applyModuleSwitches(target, config) {
1922
- setImageModule(settingsIn(config.modules?.imageStudio ?? {}, scopeRoom));
2300
+ // Images, Options and Commands have no switch (2026-11-06): always on, whatever an old config says.
2301
+ // Where its server looks for the key: MADRE's own folder (a key pasted in Images) and the home
2302
+ // where each CLI keeps its own.
2303
+ setImageModule({ ...settingsIn(config.modules?.imageStudio ?? {}, scopeRoom), enabled: true, stateRoot: root, home: credentialHome });
1923
2304
  target.setAsh(moduleOnHere(config, 'ash'));
1924
- target.setChoices(moduleOnHere(config, 'choices'));
1925
- target.setRuns(moduleOnHere(config, 'runs'));
2305
+ target.setChoices(true);
2306
+ target.setRuns(true);
1926
2307
  }
1927
2308
 
1928
2309
  // Opening another conversation. The project keeps its memory, its crew, its modules, its
1929
2310
  // privacy list and its numbering; what changes is the record being shown. With TURNS on, a
1930
2311
  // conversation still at work is parked, not stopped; with it off, a turn in flight is a reason to
1931
2312
  // refuse, as it always was.
2313
+ // Conversations left while their memory work was still running, until it is done.
2314
+ const closing = new Set();
1932
2315
  async function mountChat(id) {
1933
2316
  if (!isChatId(id)) return { error: `No conversation "${id}".` };
1934
2317
  const policy = await turnsPolicy();
@@ -1947,8 +2330,13 @@ export async function createPulseServer({
1947
2330
  // Still writing its record and touching the list; only the page stops watching it.
1948
2331
  hold(chatId, leaving, store);
1949
2332
  } else if (leaving) {
1950
- await leaving.shutdown().catch(() => null);
1951
- retireLedger(store);
2333
+ // Q-29 (2026-11-18): the room left may still be distilling with the local model, half a
2334
+ // minute with qwen2.5:7b, and the new conversation waited for it. It finishes on its own;
2335
+ // closing MADRE still waits for it (`closing`, in server.close).
2336
+ const leavingStore = store;
2337
+ const closed = leaving.shutdown().catch(() => null).then(() => retireLedger(leavingStore));
2338
+ closing.add(closed);
2339
+ void closed.finally(() => closing.delete(closed));
1952
2340
  }
1953
2341
  chatId = id;
1954
2342
  const held = parked.get(id);
@@ -1990,6 +2378,10 @@ export async function createPulseServer({
1990
2378
  // When the install running now began, for «En marcha» (2026-10-30).
1991
2379
  let installingSince = 0;
1992
2380
  let pulling = null; // the model download running now, and how to stop it
2381
+ // What the install running now said last («pulling … 45%»), for «En marcha»: its row opened and
2382
+ // showed nothing (2026-11-06, the author). Ends with the install.
2383
+ let installLine = null;
2384
+ let lastPull = null; // what the last model download reported: { model, ok, detail, trouble }
1993
2385
 
1994
2386
  // Intenciones' reading of every conversation, kept per ledger file until that file changes.
1995
2387
  const observedLedgers = new Map();
@@ -2019,6 +2411,10 @@ export async function createPulseServer({
2019
2411
  },
2020
2412
  imageKey,
2021
2413
  setImageModule,
2414
+ // Images (2026-11-14): where each provider's key was found — never the key — and the home
2415
+ // a CLI keeps its own in. Tests hand in their own sources.
2416
+ imageSources: imageSources ?? (() => findImageSources({ env: process.env, home: credentialHome, stateRoot: root })),
2417
+ imageHome: credentialHome,
2022
2418
  // Intenciones keeps its measurements beside the project's room, reads the open
2023
2419
  // conversation, and asks agents through the same bench EYECAT and the archivist draw on.
2024
2420
  intents: {
@@ -2097,12 +2493,14 @@ export async function createPulseServer({
2097
2493
  }),
2098
2494
  ollama: {
2099
2495
  state: () => ollama,
2496
+ pulling: () => (pulling ? { model: pulling.model } : null),
2497
+ lastPull: () => lastPull,
2100
2498
  // One answer from the local model, for a module that reads something with it (SDK 2):
2101
2499
  // the model MADRE chose unless one is named. Nothing leaves this computer.
2102
2500
  generate: ({ model = null, system = null, prompt, json = false, timeoutMs = 60000, temperature = 0 } = {}) => {
2103
2501
  const chosen = model ?? ollama.madreModel ?? ollama.chatModel ?? null;
2104
2502
  if (!ollama.running || !chosen) return Promise.reject(new Error(t('The local AI is not running.')));
2105
- return ollamaGenerate({ host: ollama.host, model: chosen, system, prompt: String(prompt ?? ''), json, timeoutMs, temperature, fetchImpl: reportFetch });
2503
+ return ollamaGenerate({ host: ollama.host, model: chosen, system, prompt: String(prompt ?? ''), json, timeoutMs, temperature, fetchImpl: localFetch });
2106
2504
  },
2107
2505
  project: () => localAiHere(),
2108
2506
  setProject: (on) => setLocalAiHere(on),
@@ -2110,14 +2508,14 @@ export async function createPulseServer({
2110
2508
  // Getting Ollama onto this computer, with the command in plain sight, and waking it.
2111
2509
  install: async () => {
2112
2510
  if (installing) return { ok: false, error: t('Another install is running. Wait for it to finish and try again.') };
2113
- const { ollamaInstallPlan, adminHere } = await import('./modules/ollama.mjs');
2511
+ const { ollamaInstallPlan, adminHere, OLLAMA_INSTALL_MS } = await import('./modules/ollama.mjs');
2114
2512
  const plan = ollamaInstallPlan({ brew: await findOnPath('brew'), admin: await adminHere(), zstd: Boolean(await findOnPath('zstd')), apt: Boolean(await findOnPath('apt-get')) });
2115
2513
  if (!plan.command) return { ok: false, error: plan.note, download: plan.download, manual: plan.manual ? plan.display : null };
2116
2514
  installing = 'ollama'; installingSince = Date.now();
2117
2515
  await room.record('extension.install.started', { id: 'ollama', name: 'OLLAMA', command: plan.display, platforms: [], alreadyInstalled: false });
2118
2516
  void (async () => {
2119
2517
  const lines = [];
2120
- 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)] }); } });
2518
+ const result = await runInstaller({ command: plan.command, args: plan.args, projectRoot: canonicalProjectRoot, timeoutMs: OLLAMA_INSTALL_MS, onLine: (line) => { lines.push(line); void room.record('extension.install.output', { id: 'ollama', lines: [line.slice(0, 500)] }); } });
2121
2519
  const status = await wireOllama();
2122
2520
  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 });
2123
2521
  installing = null;
@@ -2192,13 +2590,19 @@ export async function createPulseServer({
2192
2590
  await pullModel({ host: ollama.host, model, fetchImpl: reportFetch, signal: stopper.signal, onLine: (line) => { pending.push(line); if (!flushTimer) flushTimer = setTimeout(() => void flush(), 400); } });
2193
2591
  await flush();
2194
2592
  const status = await wireOllama();
2593
+ lastPull = { model, ok: true, detail: `pulled ${model}` };
2195
2594
  await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: true, installed: true, detail: `pulled ${model}`, model, ollama: status });
2196
2595
  } catch (error) {
2197
2596
  await flush();
2198
2597
  // Stopped on purpose: said as that, not as a failure.
2598
+ if (stopper.signal.aborted) lastPull = { model, ok: false, cancelled: true };
2199
2599
  if (stopper.signal.aborted) await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: 'cancelled', model, cancelled: true });
2200
- // Why it stopped, in one word the page says in plain words (src/setup-trouble.mjs).
2201
- else await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: error.message, model, trouble: installTrouble(error.message) });
2600
+ else {
2601
+ const trouble = error.trouble ?? installTrouble(error.message);
2602
+ lastPull = { model, ok: false, detail: error.message, trouble };
2603
+ // Why it stopped, in one word the page says in plain words (src/setup-trouble.mjs).
2604
+ await room.record('extension.install.finished', { id: 'ollama', name: 'OLLAMA', ok: false, installed: false, detail: error.message, model, trouble });
2605
+ }
2202
2606
  } finally { installing = null; pulling = null; }
2203
2607
  })();
2204
2608
  return { ok: true };
@@ -2213,6 +2617,15 @@ export async function createPulseServer({
2213
2617
  };
2214
2618
  }
2215
2619
 
2620
+ // One of the first steps (public/missions.js): something got from the Market. Seen here, where
2621
+ // every way of getting one ends (the Market, MODULES, Settings), and counted the first time only.
2622
+ // The local AI has its own step, so turning it on is not this one.
2623
+ async function marketUsed() {
2624
+ const before = await readTour(root).catch(() => null);
2625
+ if (!before || before.missions?.market) return;
2626
+ await changeTour(root, { mission: 'market' }).catch(() => null);
2627
+ diagnostics.count('mission.market');
2628
+ }
2216
2629
  async function installExtension(id, payload = {}) {
2217
2630
  const { confirm } = payload;
2218
2631
  const extension = extensionById(id);
@@ -2265,30 +2678,100 @@ export async function createPulseServer({
2265
2678
  clearTimeout(flushTimer);
2266
2679
  await flush();
2267
2680
  const after = await extension.detect(canonicalProjectRoot);
2681
+ const ok = result.code === 0 && after.installed;
2682
+ // Why it failed, for the diagnostics (D-10: two copies said only «install failed · ahp»): the
2683
+ // installer's own code when it prints one (AHP+ writes `"error": "GIT_REQUIRED"`), else the
2684
+ // kind of trouble its last lines show, else a command that ended well and installed nothing.
2685
+ // Words and codes only: the lines themselves carry paths and stay in the conversation.
2686
+ const said = lines.map((line) => line.match(/^\s*"error":\s*"([A-Z][A-Z0-9_]{2,40})"/)?.[1]).filter(Boolean).at(-1);
2268
2687
  await room.record('extension.install.finished', {
2269
2688
  id,
2270
2689
  name: extension.name,
2271
2690
  code: result.code,
2272
2691
  error: result.error ?? null,
2273
- ok: result.code === 0 && after.installed,
2692
+ ok,
2274
2693
  status: after,
2275
2694
  tail: lines.slice(-12),
2695
+ trouble: ok ? null : said ?? (result.code === 0 ? 'not-installed' : installTrouble(`${result.error ?? ''}\n${lines.slice(-20).join('\n')}`)),
2276
2696
  });
2277
2697
  installing = null;
2278
2698
  })();
2279
2699
  return { status: 202, body: { accepted: true, command: plan.display } };
2280
2700
  }
2281
2701
 
2702
+ // THE FICHA (src/ficha.mjs, 2026-11-02, external review #5). With it on, a request passes when it
2703
+ // carries the ficha (the page's cookie, or the header MADRE's own processes send) or is one of
2704
+ // the few that say nothing: the page's code, styles and pictures, and whether a MADRE answers here.
2705
+ // Everything else — every read, every change, the pages themselves — waits for it.
2706
+ const FICHA_PAGES = new Set(['/', '/salas']);
2707
+ const fichaFree = (method, pathname) => (method === 'GET' || method === 'HEAD') && !pathname.startsWith('/api/') && !pathname.startsWith('/preview/') && !FICHA_PAGES.has(pathname);
2708
+ const PREVIEW_ROUTE = /^\/preview\/(?:([0-9a-f]{32})\/)?(project|attachments)\/(.*)$/;
2709
+ // true when the request was answered here.
2710
+ async function fichaDoor(request, response, url) {
2711
+ const ficha = await currentFicha();
2712
+ // A page opened with the ficha in its address: the browser keeps it in a cookie, and the address
2713
+ // it shows (and remembers) is the same one without it.
2714
+ if (request.method === 'GET' && FICHA_PAGES.has(url.pathname) && url.searchParams.has(FICHA_PARAM) && ficha && sameFicha(url.searchParams.get(FICHA_PARAM), ficha)) {
2715
+ url.searchParams.delete(FICHA_PARAM);
2716
+ response.writeHead(303, { location: `${url.pathname}${url.search}`, 'set-cookie': fichaCookie(ficha), 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' });
2717
+ response.end();
2718
+ return true;
2719
+ }
2720
+ if (ficha && carriesFicha(request.headers, ficha)) return false;
2721
+ if (fichaFree(request.method, url.pathname)) return false;
2722
+ // RIPLEY's preview, under the key made from the ficha: a sealed frame sends no cookie.
2723
+ const preview = request.method === 'GET' ? url.pathname.match(PREVIEW_ROUTE) : null;
2724
+ if (preview?.[1] && ficha && sameFicha(preview[1], previewKey(ficha))) return false;
2725
+ // A link between projects, or the Coordinator's channel, carries the key of its own
2726
+ // (src/enlaces.mjs), kept in a file as private as the ficha; those routes check it again.
2727
+ if ((url.pathname.startsWith('/api/enlace/') || url.pathname.startsWith('/api/x/bishop/')) && typeof request.headers[CHANNEL_HEADER] === 'string') {
2728
+ const key = await channelKey(root).catch(() => null);
2729
+ if (key && sameKey(request.headers[CHANNEL_HEADER], key)) return false;
2730
+ }
2731
+ // Whether a MADRE answers on this port, and which: Home and the CLI ask it before anything
2732
+ // else. Nothing more without the ficha — not the project's folder, not the copy's identifier.
2733
+ if (request.method === 'GET' && url.pathname === '/api/version') {
2734
+ sendJson(response, 200, { name: PACKAGE.name, current: PACKAGE.version });
2735
+ return true;
2736
+ }
2737
+ if (request.method === 'GET' && FICHA_PAGES.has(url.pathname)) {
2738
+ response.writeHead(401, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', [FICHA_HEADER]: FICHA_NEEDED, ...PAGE_GUARDS });
2739
+ response.end(fichaPage(request));
2740
+ return true;
2741
+ }
2742
+ response.writeHead(401, { 'content-type': 'application/json; charset=utf-8', [FICHA_HEADER]: FICHA_NEEDED });
2743
+ response.end(JSON.stringify({ error: t('This request does not carry MADRE\'s ficha. Open MADRE from its shortcut or from the address it wrote in the terminal.'), ficha: FICHA_NEEDED }));
2744
+ return true;
2745
+ }
2746
+ // What a tab without the ficha shows: where to open MADRE from, nothing of the project. Through an
2747
+ // SSH tunnel (L-13) MADRE cannot open that browser, so the page says how to get the address; and
2748
+ // when the tunnel uses another number on the person's side, which one to change.
2749
+ const fichaPage = (request) => {
2750
+ const seen = Number(String(request?.headers?.host ?? '').match(/:(\d+)$/)?.[1]) || null;
2751
+ const mine = request?.socket?.localPort ?? null;
2752
+ const escape = (text) => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
2753
+ return `<!doctype html><html lang="${roomLanguage()}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>MADRE</title>`
2754
+ + '<body style="font:16px/1.5 system-ui,sans-serif;background:#0b0c0b;color:#e8eae6;margin:0;display:grid;place-items:center;min-height:100vh"><main style="max-width:34rem;padding:32px">'
2755
+ + `<h1 style="font-size:22px;margin:0 0 12px">${escape(t('This tab needs to be opened from MADRE'))}</h1>`
2756
+ + `<p>${escape(t('MADRE only answers to the browser it opened itself, so that no other program on this computer can read your projects or act in them.'))}</p>`
2757
+ + `<p>${escape(t('Open it again from its shortcut, or with npx @jossuealcala/madre, or paste the full address MADRE wrote in the terminal (the one that ends in ?ficha=…).'))}</p>`
2758
+ + `<p>${escape(t('Reaching this computer through an SSH tunnel? On that computer, run npx @jossuealcala/madre and open here the address it writes (the one that ends in ?ficha=…).'))}</p>`
2759
+ + (seen && mine && seen !== mine ? `<p>${escape(t('Your tunnel brings port {theirs} to {yours} on your side: in that address, change {theirs} to {yours}.', { theirs: mine, yours: seen }))}</p>` : '')
2760
+ + '</main></body></html>';
2761
+ };
2762
+
2282
2763
  const server = http.createServer(async (request, response) => {
2283
2764
  const foreign = refuseForeign(request);
2284
2765
  if (foreign) return sendJson(response, 403, { error: t(foreign), guarded: true });
2285
2766
  const url = new URL(request.url, 'http://127.0.0.1');
2767
+ if (fichaOn && await fichaDoor(request, response, url)) return;
2286
2768
  // The project's own folder name, typed by the human. Declared at the top of the handler and
2287
2769
  // not beside the first route that happened to need it: a const sits in its temporal dead zone
2288
2770
  // until its own line runs, so any route above it threw instead of refusing.
2289
2771
  // Which machine serves the page, written into it (public/i18n.js, hostWords): the browser that
2290
2772
  // reads it may be on another one, a Mac looking at a Linux box, and must not say «Mac» there.
2291
- const withHost = (html) => html.replace('<head>', `<head>\n <meta name="madre-host" content="${JSON.stringify(hostFacts()).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')}">`);
2773
+ if (Date.now() - gitAsked > 60_000) askGit();
2774
+ const withHost = (html) => html.replace('<head>', `<head>\n <meta name="madre-host" content="${JSON.stringify({ ...hostFacts(), ...(gitHere ? {} : { git: false }) }).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')}">`);
2292
2775
  // A page of MADRE's own. Its files can vanish under a running copy (npx replaced its folder
2293
2776
  // with a newer version): then the page says so, instead of a failure (1.1.0 diagnostics).
2294
2777
  const pageHtml = async (name) => {
@@ -2309,7 +2792,7 @@ export async function createPulseServer({
2309
2792
  response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...PAGE_GUARDS });
2310
2793
  return response.end(html);
2311
2794
  }
2312
- 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)) {
2795
+ 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', '/missions.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', '/welcome-scene.js', '/news-scenes.js', '/remedy.js', '/icons.js', '/page-errors.js', '/auto-open.js', '/changes.js', '/activity.js', '/notices.js', '/subscription.js', '/tips.js', '/starters.js', '/provider-pick.js', '/notifications.js', '/provider-marks.js', '/terms.js', '/terms-field.js', '/mcp-catalog.js', '/manual.js', '/manual-content.js', '/manual-shots.js', '/en.js'].includes(url.pathname)) {
2313
2796
  return sendAsset(request, response, join(publicDirectory, url.pathname.slice(1)), 'text/javascript; charset=utf-8');
2314
2797
  }
2315
2798
  if (request.method === 'GET' && url.pathname === '/styles.css') {
@@ -2357,6 +2840,9 @@ export async function createPulseServer({
2357
2840
  ['/assets/brand/Geist-latin-ext.woff2', 'font/woff2'],
2358
2841
  ['/assets/brand/GeistMono-latin.woff2', 'font/woff2'],
2359
2842
  ['/assets/brand/GeistMono-latin-ext.woff2', 'font/woff2'],
2843
+ ['/assets/brand/SpaceGrotesk-latin.woff2', 'font/woff2'],
2844
+ ['/assets/brand/SpaceGrotesk-latin-ext.woff2', 'font/woff2'],
2845
+ ['/assets/brand/OFL-SpaceGrotesk.txt', 'text/plain; charset=utf-8'],
2360
2846
  ['/assets/brand/OFL-Geist.txt', 'text/plain; charset=utf-8'],
2361
2847
  ['/assets/brand/OFL-GeistMono.txt', 'text/plain; charset=utf-8'],
2362
2848
  ['/assets/brand/OFL-Sora.txt', 'text/plain; charset=utf-8'],
@@ -2585,7 +3071,7 @@ export async function createPulseServer({
2585
3071
  const later = [];
2586
3072
  if (request.method === 'POST') {
2587
3073
  await Promise.all(known.filter((one) => one.open && one.id !== thisRoomId).map(async (one) => {
2588
- const answer = await askRoom(one.open.port, '/api/local-ai/apply', { method: 'POST', timeoutMs: 6000 });
3074
+ const answer = await askRoom(one.open.port, '/api/local-ai/apply', { stateRoot: root, method: 'POST', timeoutMs: 6000 });
2589
3075
  if (answer.unreachable || answer.outdated) later.push(one.name);
2590
3076
  }));
2591
3077
  }
@@ -2632,7 +3118,7 @@ export async function createPulseServer({
2632
3118
  port: one.open.port,
2633
3119
  here: one.id === here,
2634
3120
  accent: owns[one.id]?.accent ?? homeAccent,
2635
- glance: one.id === here ? null : await askRoom(one.open.port, '/api/glance'),
3121
+ glance: one.id === here ? null : await askRoom(one.open.port, '/api/glance', { stateRoot: root }),
2636
3122
  })));
2637
3123
  return sendJson(response, 200, { here, salas: salasRoomId(root), rooms: seen });
2638
3124
  }
@@ -2645,7 +3131,7 @@ export async function createPulseServer({
2645
3131
  const room = (await knownRooms(root)).find((one) => one.id === id);
2646
3132
  if (!room) return sendJson(response, 404, { error: t('MADRE does not know that project on this Mac.') });
2647
3133
  if (!room.open) return sendJson(response, 200, { id, asleep: true });
2648
- const answer = await askRoom(room.open.port, `/api/memory?designation=${encodeURIComponent(room.name)}`, { timeoutMs: 4000 });
3134
+ const answer = await askRoom(room.open.port, `/api/memory?designation=${encodeURIComponent(room.name)}`, { stateRoot: root, timeoutMs: 4000 });
2649
3135
  if (answer.outdated) return sendJson(response, 200, { id, outdated: true });
2650
3136
  if (answer.unreachable) return sendJson(response, 200, { id, sealed: answer.status === 423, unreachable: answer.status !== 423 });
2651
3137
  return sendJson(response, 200, { id, ...universeOf(answer, { full: url.searchParams.get('full') === '1' }) });
@@ -2671,7 +3157,7 @@ export async function createPulseServer({
2671
3157
  // The commonest reason, said as itself: another MADRE (another Home, `madre start`) already
2672
3158
  // has this folder open, and one folder is one room. Where it is, so the person can go there.
2673
3159
  const said = (await readFile(join(root, 'rooms', room.id, 'start.log'), 'utf8').catch(() => '')).slice(logFrom);
2674
- const there = [...said.matchAll(/already open for this project\s+(http:\/\/127\.0\.0\.1:\d+)/g)].at(-1)?.[1];
3160
+ const there = [...said.matchAll(ALREADY_OPEN)].at(-1)?.[1];
2675
3161
  if (there) return sendJson(response, 409, { error: t('This project is already open in another MADRE, at {address}. Use that one, or close it there first.', { address: there }), address: there });
2676
3162
  return sendJson(response, 504, { error: t('The project did not open. What it said on the way up is in start.log, beside its record.') });
2677
3163
  }
@@ -2682,7 +3168,7 @@ export async function createPulseServer({
2682
3168
  // folders (Sec-Fetch-Site) or to add one (Origin), and so is any host name but this Mac's
2683
3169
  // own, so a name pointed at it from outside reaches nothing. Folders are listed inside the
2684
3170
  // home folder only; what is listed is names, never what a file says.
2685
- if (url.pathname === '/api/salas/folders' || url.pathname === '/api/salas/suggestions' || url.pathname === '/api/salas/projects' || url.pathname === '/api/salas/new' || url.pathname === '/api/salas/work' || url.pathname === '/api/salas/decisions') {
3171
+ if (url.pathname === '/api/salas/folders' || url.pathname === '/api/salas/suggestions' || url.pathname === '/api/salas/peek' || url.pathname === '/api/salas/projects' || url.pathname === '/api/salas/new' || url.pathname === '/api/salas/work' || url.pathname === '/api/salas/decisions') {
2686
3172
  const host = String(request.headers.host ?? '');
2687
3173
  const localHost = /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host);
2688
3174
  const site = request.headers['sec-fetch-site'];
@@ -2698,6 +3184,16 @@ export async function createPulseServer({
2698
3184
  if (request.method === 'GET' && url.pathname === '/api/salas/suggestions') {
2699
3185
  return sendJson(response, 200, { suggestions: await suggestProjects({ home, stateRoot: root }) });
2700
3186
  }
3187
+ // What the first level of a project Home knows holds, by name only (2026-11-10): the end of
3188
+ // the welcome writes its first ideas for what is in that folder (public/starters.js).
3189
+ if (request.method === 'GET' && url.pathname === '/api/salas/peek') {
3190
+ const asked = url.searchParams.get('room');
3191
+ const room = (await knownRooms(root)).find((one) => one.id === asked && one.root);
3192
+ if (!room) return sendJson(response, 404, { error: t('That folder is not there.') });
3193
+ const listing = await listDirectory(room.root, '.');
3194
+ if (listing.status !== 200) return sendJson(response, listing.status, { error: listing.error });
3195
+ return sendJson(response, 200, { entries: listing.entries.map(({ name, kind }) => ({ name, kind })) });
3196
+ }
2701
3197
  // WHAT WAS WORKED ON LAST: the newest conversations of every room the lobby knows (read from
2702
3198
  // their folders, open or asleep), and MADRE's summary of them with its local model. The
2703
3199
  // summary is written in the background and kept until what it summarises changes; it is
@@ -2727,7 +3223,7 @@ export async function createPulseServer({
2727
3223
  if (!lobbyWork.running && (asked || due)) {
2728
3224
  lobbyWork.tried = Date.now();
2729
3225
  const language = roomLanguage() === 'en' ? 'en' : 'es';
2730
- lobbyWork.running = ollamaGenerate({ host: ollama.host, model, system: WORK_SYSTEM[language], prompt: workPrompt(items, language), fetchImpl: reportFetch, timeoutMs: 120000, temperature: 0.1 })
3226
+ lobbyWork.running = ollamaGenerate({ host: ollama.host, model, system: WORK_SYSTEM[language], prompt: workPrompt(items, language), fetchImpl: localFetch, timeoutMs: 120000, temperature: 0.1 })
2731
3227
  .then(async (answer) => {
2732
3228
  const bullets = parseWork(answer.text, items);
2733
3229
  if (!bullets.length) throw new Error('MADRE answered nothing the lobby could check against the conversations.');
@@ -2749,7 +3245,7 @@ export async function createPulseServer({
2749
3245
  lobbyDecisions.running = (async () => {
2750
3246
  const open = (await knownRooms(root)).filter((one) => one.open);
2751
3247
  const lists = await Promise.all(open.map(async (one) => {
2752
- const answer = await askRoom(one.open.port, `/api/memory?designation=${encodeURIComponent(one.name)}`, { timeoutMs: 6000 });
3248
+ const answer = await askRoom(one.open.port, `/api/memory?designation=${encodeURIComponent(one.name)}`, { stateRoot: root, timeoutMs: 6000 });
2753
3249
  if (!Array.isArray(answer?.memories)) return [];
2754
3250
  return answer.memories
2755
3251
  .filter((note) => note.kind === 'decision' && (note.zone === 'hold' || note.zone === 'bridge') && typeof note.text === 'string')
@@ -2769,6 +3265,13 @@ export async function createPulseServer({
2769
3265
  if (payload.sample === true) {
2770
3266
  const sample = await createSampleProject({ home, stateRoot: root, language: payload.language === 'en' ? 'en' : 'es' });
2771
3267
  if (sample.error) return sendJson(response, 422, { error: t('The project to try MADRE could not be made.'), code: sample.error });
3268
+ // Its page is the point (2026-11-11): the first change opens beside the conversation as
3269
+ // the page it is, so Preview is on in this project — unless the person already said
3270
+ // otherwise, for every project or for this one.
3271
+ const ripleyBlock = (await readConfig(root)).modules?.ripley ?? {};
3272
+ if (sample.id && typeof ripleyBlock.enabled !== 'boolean' && typeof ripleyBlock.rooms?.[sample.id] !== 'boolean') {
3273
+ await updateConfig(root, { modules: { ripley: switchIn(ripleyBlock, sample.id, true) } }).catch(() => {});
3274
+ }
2772
3275
  diagnostics.count('project.sample');
2773
3276
  return sendJson(response, 200, { added: [sample] });
2774
3277
  }
@@ -2803,20 +3306,22 @@ export async function createPulseServer({
2803
3306
  if (request.method === 'POST' && url.pathname === '/api/salas/close') {
2804
3307
  const payload = await body(request).catch(() => ({}));
2805
3308
  const room = (await knownRooms(root)).find((one) => one.id === payload.room);
3309
+ // Closed by the person: it does not come back when MADRE starts as a service (L-3).
3310
+ if (room) await keepOpenProject(root, room.id, false).catch(() => false);
2806
3311
  if (!room?.open) return sendJson(response, 200, { room: payload.room ?? null, closed: true });
2807
3312
  if (room.id === basename(roomDir)) {
2808
3313
  sendJson(response, 202, { room: room.id, closing: true, here: true });
2809
3314
  setTimeout(() => server.emit('madre:close'), 150);
2810
3315
  return undefined;
2811
3316
  }
2812
- const answer = await askRoom(room.open.port, '/api/room/close', { method: 'POST', body: {} });
3317
+ const answer = await askRoom(room.open.port, '/api/room/close', { stateRoot: root, method: 'POST', body: {} });
2813
3318
  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 });
2814
3319
  if (answer.unreachable) return sendJson(response, 502, { error: t('That project did not answer.') });
2815
3320
  return sendJson(response, 202, { room: room.id, closing: true });
2816
3321
  }
2817
3322
  if (request.method === 'POST' && url.pathname === '/api/salas/stop-all') {
2818
3323
  const rooms = (await knownRooms(root)).filter((one) => one.open);
2819
- const stopped = await Promise.all(rooms.map((one) => askRoom(one.open.port, '/api/stop-all', { method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer.unreachable && !answer.outdated)));
3324
+ const stopped = await Promise.all(rooms.map((one) => askRoom(one.open.port, '/api/stop-all', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer.unreachable && !answer.outdated)));
2820
3325
  return sendJson(response, 200, { rooms: rooms.length, stopped: stopped.filter(Boolean).length });
2821
3326
  }
2822
3327
  // Turning MADRE off (2026-10-16), from a page of this Mac only, after the person confirmed it.
@@ -2832,6 +3337,19 @@ export async function createPulseServer({
2832
3337
  setTimeout(() => server.emit('madre:close'), 150);
2833
3338
  return undefined;
2834
3339
  }
3340
+ // MADRE as a service of this Linux (src/service.mjs, L-3), from Home's Settings on this computer.
3341
+ if (url.pathname === '/api/madre/service' && (request.method === 'GET' || request.method === 'POST')) {
3342
+ const host = String(request.headers.host ?? '');
3343
+ if (!salasRoom || viaPhone || !/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) return sendJson(response, 403, { error: t('This is done from Home, on this computer.') });
3344
+ if (request.method === 'GET') return sendJson(response, 200, await serviceState());
3345
+ const site = request.headers['sec-fetch-site'];
3346
+ if ((site !== undefined && site !== 'same-origin' && site !== 'none') || request.headers.origin !== `http://${host}`) return sendJson(response, 403, { error: t('This is done from Home, on this computer.') });
3347
+ const payload = await body(request).catch(() => ({}));
3348
+ const state = payload?.on === true ? await enableService({ stateRoot: root, launcher: homeLauncher() }) : await disableService({ stateRoot: root });
3349
+ if (state.refused === 'install') return sendJson(response, 409, { ...state, error: t('This copy of MADRE was installed inside a project; install it with npx or npm -g to start it with the computer.') });
3350
+ if (state.refused) return sendJson(response, 500, { ...state, error: t('systemd did not turn the service on: {detail}', { detail: state.detail ?? '' }) });
3351
+ return sendJson(response, 200, state);
3352
+ }
2835
3353
  // Uninstalling MADRE (2026-10-29), from Home's Settings only (src/uninstall.mjs). GET says what
2836
3354
  // would go and what stays; POST, from a page of this computer, closes every open project the
2837
3355
  // way turning MADRE off does and — only once all of them closed — closes Home and takes away
@@ -2863,6 +3381,10 @@ export async function createPulseServer({
2863
3381
  // This room, asked to close by Salas: what is running stops and the room closes the way a
2864
3382
  // signal closes it (startPulse listens). Nothing here ends the process itself.
2865
3383
  if (request.method === 'POST' && url.pathname === '/api/room/close') {
3384
+ // From its own page, by the person: it stays closed when MADRE starts as a service (L-3).
3385
+ // Home turning everything off asks without it, and those come back.
3386
+ const payload = await body(request).catch(() => ({}));
3387
+ if (payload?.forget === true) await keepOpenProject(root, basename(roomDir), false).catch(() => false);
2866
3388
  sendJson(response, 202, { closing: true });
2867
3389
  setTimeout(() => server.emit('madre:close'), 150);
2868
3390
  return undefined;
@@ -2875,7 +3397,7 @@ export async function createPulseServer({
2875
3397
  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.') });
2876
3398
  const here = basename(roomDir);
2877
3399
  const others = (await knownRooms(root)).filter((one) => one.open && one.id !== here);
2878
- 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)));
3400
+ const asked = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/room/restart', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer?.unreachable && !answer?.outdated).catch(() => false)));
2879
3401
  await room.record('room.restarting', { others: others.length });
2880
3402
  sendJson(response, 202, { restarting: true, others: others.length, stuck: others.filter((_, index) => !asked[index]).map((one) => one.name) });
2881
3403
  restartSelf(request.socket.localPort);
@@ -3244,6 +3766,19 @@ export async function createPulseServer({
3244
3766
  // adding one is. Never the Coordinator's own, never the room that is asked. Open, it is closed
3245
3767
  // first; its connections end with it, so none is left pointing at a project MADRE no longer
3246
3768
  // knows; then its record goes aside (forgetProject). Its folder on the Mac is not touched.
3769
+ // A name of the person's own for a project, from Home (2026-11-13). Its folder keeps its name.
3770
+ if (request.method === 'POST' && url.pathname === '/api/salas/rename') {
3771
+ const host = String(request.headers.host ?? '');
3772
+ const site = request.headers['sec-fetch-site'];
3773
+ if (!/^(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('This is done from Home, on this Mac.') });
3774
+ const payload = await body(request).catch(() => ({}));
3775
+ const id = String(payload.room ?? '');
3776
+ if (id === salasRoomId(root)) return sendJson(response, 422, { error: t('The Coordinator keeps its name.') });
3777
+ if (!(await knownRooms(root)).some((one) => one.id === id)) return sendJson(response, 404, { error: t('MADRE does not know that project on this Mac.') });
3778
+ const renamed = await renameProject({ stateRoot: root, id, title: payload.name });
3779
+ if (renamed.error) return sendJson(response, 404, { error: t('MADRE does not know that project on this Mac.') });
3780
+ return sendJson(response, 200, renamed);
3781
+ }
3247
3782
  if (request.method === 'POST' && url.pathname === '/api/salas/forget') {
3248
3783
  const host = String(request.headers.host ?? '');
3249
3784
  const site = request.headers['sec-fetch-site'];
@@ -3256,7 +3791,7 @@ export async function createPulseServer({
3256
3791
  let one = await find();
3257
3792
  if (!one) return sendJson(response, 404, { error: t('MADRE does not know that project on this Mac.') });
3258
3793
  if (one.open) {
3259
- const answer = await askRoom(one.open.port, '/api/room/close', { method: 'POST', body: {} });
3794
+ const answer = await askRoom(one.open.port, '/api/room/close', { stateRoot: root, method: 'POST', body: {} });
3260
3795
  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 });
3261
3796
  if (answer.unreachable) return sendJson(response, 502, { error: t('That project did not answer.') });
3262
3797
  for (let tries = 0; tries < 40 && one?.open; tries += 1) { await new Promise((resolve) => setTimeout(resolve, 250)); one = await find(); }
@@ -3300,6 +3835,8 @@ export async function createPulseServer({
3300
3835
  // The project's name as this system writes paths (WEB-11): the page cut it at «/», and on
3301
3836
  // Windows the name was the whole path, so the key for #3 never matched.
3302
3837
  projectName: basename(canonicalProjectRoot),
3838
+ // The name the person gave it in Home, if any (2026-11-13): shown in place of the folder's.
3839
+ projectTitle: await projectTitle(roomDir).catch(() => null),
3303
3840
  // The column Diagnostics reads its commands from (public/troubleshooting.js): WSL is Linux
3304
3841
  // inside Windows, and says so (2026-10-28).
3305
3842
  platform: await environmentOnce().then((one) => (one?.wsl ? 'wsl' : process.platform), () => process.platform),
@@ -3310,6 +3847,8 @@ export async function createPulseServer({
3310
3847
  phonePreview: viaPhone ? true : await phonePreview(),
3311
3848
  // The room of Salas knows it is: true only there, false in every other room.
3312
3849
  salas: salasRoom,
3850
+ // The longest message the room takes (D-15): a longer one goes as a text attachment.
3851
+ maxMessageChars,
3313
3852
  room: basename(roomDir),
3314
3853
  phones: viaPhone ? undefined : await phonePreview() ? (await readStore(root).catch(() => ({ devices: [] }))).devices.length : 0,
3315
3854
  // Which MADRE this is. The page prints it in the corner: the one fact a bug report
@@ -3513,11 +4052,19 @@ export async function createPulseServer({
3513
4052
  // (connect-src none), no forms, no top navigation, assets only from MADRE's
3514
4053
  // own host. Path-based, so a page's relative links to its CSS, JS and images
3515
4054
  // resolve to the same route.
3516
- const previewMatch = request.method === 'GET' && url.pathname.match(/^\/preview\/(project|attachments)\/(.*)$/);
4055
+ const previewMatch = request.method === 'GET' && url.pathname.match(PREVIEW_ROUTE);
3517
4056
  if (previewMatch) {
3518
4057
  if (!(await ripleyOn())) return sendJson(response, 412, { error: t('Preview is off. Enable it in MODULES to render files.') });
3519
- const which = previewMatch[1] === 'attachments' ? attachmentsRoot : canonicalProjectRoot;
3520
- const relative = decodeURIComponent(previewMatch[2]);
4058
+ // With the ficha on, the page's frame asks by the plain address (its cookie goes with it)
4059
+ // and is sent to the same one under the preview's key, where the sealed page's own CSS,
4060
+ // scripts and pictures — which carry no cookie — resolve by their relative links.
4061
+ const ficha = fichaOn ? await currentFicha() : null;
4062
+ if (ficha && !previewMatch[1]) {
4063
+ response.writeHead(307, { location: `/preview/${previewKey(ficha)}/${previewMatch[2]}/${previewMatch[3]}${url.search}`, 'cache-control': 'no-store' });
4064
+ return response.end();
4065
+ }
4066
+ const which = previewMatch[2] === 'attachments' ? attachmentsRoot : canonicalProjectRoot;
4067
+ const relative = decodeURIComponent(previewMatch[3]);
3521
4068
  const file = await readServable(which, relative);
3522
4069
  if (file.status !== 200) return sendJson(response, file.status, { error: file.error });
3523
4070
  const isPage = /\.(html?|xhtml)$/i.test(relative);
@@ -3552,10 +4099,42 @@ export async function createPulseServer({
3552
4099
  return sendJson(response, error.status ?? 400, { error: error.message });
3553
4100
  }
3554
4101
  const name = decodeURIComponent(request.headers['x-pulse-filename'] ?? url.searchParams.get('name') ?? 'attachment');
4102
+ // An empty file is the request's, not a broken route: refused in words, before it is stored,
4103
+ // and never counted as MADRE's failure in the diagnostics (D-8, one copy of 1.1.2).
4104
+ if (!bytes?.length) return sendJson(response, 400, { error: t('The file is empty: there is nothing to attach.') });
3555
4105
  const here = await scopeOf(url, response);
3556
4106
  if (here.error) return sendJson(response, 404, here);
3557
4107
  const record = await here.room.registerAttachment(await storeAttachment(attachmentsRoot, { name, bytes }));
3558
- return sendJson(response, 201, { attachment: { id: record.id, name: record.name, fileName: record.fileName, size: record.size, contentType: record.contentType, url: `/api/files?root=attachments&path=${encodeURIComponent(record.fileName)}` } });
4108
+ // A SKILL SOMEBODY SENT (C-1). The file a person drags in lands here, under the room, which
4109
+ // is one of the two places MADRE accepts a skill from; so what is left is recognising it.
4110
+ // Read from the bytes just stored: by its name (<id>.habilidad.md, as an agent writes one)
4111
+ // or because a .md turns out to read as a skill — which is what arrives by e-mail.
4112
+ let sent = null;
4113
+ if (/\.md$/i.test(record.name) && bytes.length <= 1024 * 1024) {
4114
+ try {
4115
+ const read = readSkillText(bytes.toString('utf8'), { id: skillIdOf(record.name) });
4116
+ sent = { id: read.id, name: read.name, when: read.when, version: read.version, body: read.body, unknown: read.unknown, declares: skillDeclares({ ...read, files: [], scripts: [] }), fileName: record.fileName };
4117
+ } catch { sent = isSkillFile(record.name) ? { error: t('That file is named like a skill, but MADRE cannot read it as one.') } : null; }
4118
+ }
4119
+ return sendJson(response, 201, { attachment: { id: record.id, name: record.name, fileName: record.fileName, size: record.size, contentType: record.contentType, url: `/api/files?root=attachments&path=${encodeURIComponent(record.fileName)}` }, ...(sent ? { skill: sent } : {}) });
4120
+ }
4121
+ // An attachment of the conversation, saved into the project where the person says (L-2,
4122
+ // src/files.mjs keepAttachment): a PDF into conocimiento/, a patient's photo into its folder.
4123
+ // The same steps as the attachment it comes from — the conversation it belongs to, MADRE's own
4124
+ // store — and the same guard as a new file from Archivos. Recorded in that conversation.
4125
+ if (request.method === 'POST' && url.pathname === '/api/attachments/keep') {
4126
+ const payload = await body(request).catch(() => ({}));
4127
+ const here = await scopeOf(url, response);
4128
+ if (here.error) return sendJson(response, 404, here);
4129
+ const to = String(payload.to ?? '').trim().replace(/^\/+/, '');
4130
+ if (attachmentPlaceRefused(to)) return sendJson(response, 403, { error: t(ATTACHMENT_REFUSED) });
4131
+ if (to && await needsDesignationOnDisk(canonicalProjectRoot, to) && !designationOk(payload.designation)) {
4132
+ return sendJson(response, 403, { error: t('This file is one the project guards. Type the project name to save it.'), guarded: true });
4133
+ }
4134
+ const kept = await keepAttachment({ attachmentsRoot, projectRoot: canonicalProjectRoot, fileName: String(payload.fileName ?? ''), to });
4135
+ if (kept.status !== 201) return sendJson(response, kept.status, { error: t(kept.error) });
4136
+ await here.room.record('project.file.created', { path: kept.path, from: 'attachment', bytes: kept.bytes });
4137
+ return sendJson(response, 201, { ok: true, path: kept.path, bytes: kept.bytes });
3559
4138
  }
3560
4139
  // The key for #3 and #4, checked here (src/override.mjs): what was typed, once or twice, and a
3561
4140
  // pass back for that agent and mode. Never from a phone: #3 and #4 are opened on the Mac.
@@ -3631,7 +4210,7 @@ export async function createPulseServer({
3631
4210
  await wireOllama();
3632
4211
  const later = [];
3633
4212
  await Promise.all((await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId).map(async (one) => {
3634
- const answer = await askRoom(one.open.port, '/api/local-ai/apply', { method: 'POST', timeoutMs: 6000 });
4213
+ const answer = await askRoom(one.open.port, '/api/local-ai/apply', { stateRoot: root, method: 'POST', timeoutMs: 6000 });
3635
4214
  if (answer.unreachable || answer.outdated) later.push(one.name);
3636
4215
  }));
3637
4216
  return sendJson(response, 200, { host, running: Boolean(ollama.running), models: (ollama.models ?? []).map((one) => one.name), later });
@@ -3729,7 +4308,7 @@ export async function createPulseServer({
3729
4308
  if (url.pathname === '/api/terms' && request.method === 'GET') {
3730
4309
  const terms = viaPhone ? { accepted: true, version: null } : await readTerms(root);
3731
4310
  const before = !terms.accepted && ((await cameFromBefore(root)) || (hadInstallId && !existsSync(join(root, 'lifecycle.json'))));
3732
- return sendJson(response, 200, { ...terms, before, language: roomLanguage(), languageChosen, diagnostics: await diagnosticsNow(), diagnosticsFixed: process.env.PULSE_TELEMETRY === '0', links: TERMS_LINKS });
4311
+ return sendJson(response, 200, { ...terms, before, language: roomLanguage(), languageChosen, diagnostics: await diagnosticsNow(), diagnosticsFixed: process.env.PULSE_TELEMETRY === '0', links: termsLinks(), trialDays: termsKind() === 'app' ? await trialDaysNow() : null });
3733
4312
  }
3734
4313
  if (url.pathname === '/api/terms' && request.method === 'POST') {
3735
4314
  const site = request.headers['sec-fetch-site'];
@@ -3854,6 +4433,15 @@ export async function createPulseServer({
3854
4433
  return sendJson(response, 200, { framable: true, status: null, unreachable: true });
3855
4434
  }
3856
4435
  }
4436
+ // The photo and title of a link an agent gave, only when the person pressed «Show photos»
4437
+ // (web-preview.mjs): a page on the internet, never one on this computer or its network.
4438
+ if (request.method === 'POST' && url.pathname === '/api/web/preview') {
4439
+ const asked = await body(request);
4440
+ const links = (Array.isArray(asked?.urls) ? asked.urls : [asked?.url]).filter((one) => typeof one === 'string' && /^https?:\/\//i.test(one)).slice(0, 12);
4441
+ if (!links.length) return sendJson(response, 400, { error: t('No link to show.') });
4442
+ const previews = await Promise.all(links.map((one) => webPreview(one)));
4443
+ return sendJson(response, 200, { previews: Object.fromEntries(links.map((one, index) => [one, previews[index]])) });
4444
+ }
3857
4445
  if (request.method === 'GET' && url.pathname === '/api/ports') {
3858
4446
  if (!(await ripleyOn())) return sendJson(response, 412, { error: t('Preview is off. Enable it in MODULES to render files.') });
3859
4447
  // Only this project's servers, read by the servers sentinel: the same reading its watch
@@ -3906,6 +4494,8 @@ export async function createPulseServer({
3906
4494
  anthropic: agents.some((agent) => agent.id === 'claude' && agent.ready),
3907
4495
  ollama: Boolean(ollama.running),
3908
4496
  alive: true,
4497
+ // The same gate as sayHere: with the diagnostics, never from the author's own copies.
4498
+ presence: Boolean(await diagnosticsNow()) && !(await readSecret(root, OWNER_VAULT, 'usage').catch(() => null)),
3909
4499
  usage: FROM_SOURCE && Boolean(await readSecret(root, OWNER_VAULT, 'usage')),
3910
4500
  },
3911
4501
  }));
@@ -4081,7 +4671,8 @@ export async function createPulseServer({
4081
4671
  const asked = url.searchParams.get('version');
4082
4672
  const version = any && asked && notesFor(asked) ? asked : PACKAGE.version;
4083
4673
  const news = await whatsNew({ root, version, returning: novelty.returning, any });
4084
- return sendJson(response, 200, { ...news, preview: version !== PACKAGE.version, newest: newestNotes(), changes: { es: releaseUrl(PACKAGE.repository, version, 'es'), en: releaseUrl(PACKAGE.repository, version, 'en') } });
4674
+ // `app`: read inside the desktop app, where the notes say what the app gives instead of asking for it.
4675
+ return sendJson(response, 200, { ...news, app: process.env.MADRE_APP === '1', preview: version !== PACKAGE.version, newest: newestNotes(), changes: { es: releaseUrl(PACKAGE.repository, version, 'es'), en: releaseUrl(PACKAGE.repository, version, 'en') } });
4085
4676
  }
4086
4677
  if (request.method === 'POST' && url.pathname === '/api/whats-new/seen') {
4087
4678
  await markSeen(root, PACKAGE.version);
@@ -4090,6 +4681,28 @@ export async function createPulseServer({
4090
4681
  // The invitation to a first project (src/whats-new.mjs): due on Home to a copy that came from an
4091
4682
  // older MADRE and has no project, once per version. Never on a phone. Its answers are counted
4092
4683
  // with the anonymous diagnostics, and «shown» is what spends it.
4684
+ // The choice of the app (src/app-invite.mjs): a window on Home for whoever updated MADRE and uses
4685
+ // it in the browser, once per version, once the app can be downloaded for their desktop. Never on a
4686
+ // phone. Its answers are counted with the anonymous diagnostics.
4687
+ if (url.pathname === '/api/invite/app') {
4688
+ if (viaPhone || !salasRoom) return sendJson(response, 200, { show: false });
4689
+ if (request.method === 'GET') {
4690
+ const place = await environmentOnce().catch(() => null);
4691
+ const said = await appInvite({ root, novelty, version: PACKAGE.version, wsl: Boolean(place?.wsl) });
4692
+ // The person's own projects, the ones opened last, so the window can speak of them by name.
4693
+ const projects = (await knownRooms(root)).filter((one) => one.id !== salasRoomId(root))
4694
+ .sort((a, b) => String(b.lastOpened ?? '').localeCompare(String(a.lastOpened ?? ''))).map((one) => one.name);
4695
+ return sendJson(response, 200, { ...said, projects: projects.slice(0, 3), count: projects.length });
4696
+ }
4697
+ if (request.method === 'POST') {
4698
+ const payload = await body(request).catch(() => ({}));
4699
+ const said = await answerAppInvite(root, { answer: payload.answer, version: PACKAGE.version });
4700
+ if (said.error) return sendJson(response, 422, { error: 'answer' });
4701
+ diagnostics.count(`invite.app.${payload.answer}`);
4702
+ return sendJson(response, 200, said);
4703
+ }
4704
+ return sendJson(response, 405, { error: 'method' });
4705
+ }
4093
4706
  if (url.pathname === '/api/invite/project') {
4094
4707
  if (viaPhone) return sendJson(response, 200, { show: false });
4095
4708
  if (request.method === 'GET') {
@@ -4111,8 +4724,11 @@ export async function createPulseServer({
4111
4724
  // is never asked.
4112
4725
  if (request.method === 'POST' && url.pathname === '/api/review-ask/tick') {
4113
4726
  if (viaPhone) return sendJson(response, 200, { due: null });
4114
- // Never on the day of the bonjour: one welcome is enough for a day.
4115
- return sendJson(response, 200, await tickAsk(root, Date.now(), { quietSince: (await readTour(root)).bonjourAt }));
4727
+ // Never on the day of the bonjour: one welcome is enough for a day. Only the minutes the page
4728
+ // says an AI is at work count (`using`); `via` says where the question sends the person.
4729
+ const payload = await body(request).catch(() => ({}));
4730
+ const ticked = await tickAsk(root, Date.now(), { quietSince: (await readTour(root)).bonjourAt, using: payload?.using === true });
4731
+ return sendJson(response, 200, { ...ticked, via: askVia() });
4116
4732
  }
4117
4733
  if (request.method === 'POST' && url.pathname === '/api/review-ask/answer') {
4118
4734
  if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
@@ -4131,15 +4747,19 @@ export async function createPulseServer({
4131
4747
  if (request.method === 'GET' && url.pathname === '/api/tour') {
4132
4748
  const state = await readTour(root);
4133
4749
  if (viaPhone || !fromHere) return sendJson(response, 200, { version: TOUR_VERSION, state, owed: false, returning: false, chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
4134
- // Where this person comes from: the tour of 1.0 (path «since»), 0.7.2 (their words in a room's
4135
- // record, path «back»), or nowhere — a first install.
4136
- 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;
4137
4750
  // `upgraded`: this copy was in use before 1.1.0 (src/terms.mjs): it meets the news, never the welcome of someone new.
4138
- 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 });
4751
+ const upgraded = await cameFromBefore(root);
4752
+ // Where this person comes from: the tour of 1.0 (path «since»), 0.7.2 (their words in a room's
4753
+ // record, path «back»), or nowhere — a first install. Words in a room are 0.7.2's only on a
4754
+ // copy from before 1.1.0 (Q-18, 2026-11-06): someone new who opened a project with `madre
4755
+ // start`, wrote, and reloaded before the bonjour was told «MADRE changed a lot since 0.7.2».
4756
+ const from = state.path === 'since' || (!state.path && state.before === '1.0') ? '1.0' : (state.path ? state.path === 'back' : upgraded && await cameBefore(root)) ? '0.7.2' : null;
4757
+ return sendJson(response, 200, { version: TOUR_VERSION, state, owed: !state.bonjourAt, returning: Boolean(from), from, upgraded, chapters: CHAPTERS, hints: HINTS, level: NEWS_LEVEL });
4139
4758
  }
4140
4759
  if (viaPhone || !fromHere || (request.method === 'POST' && request.headers.origin !== `http://${host}`)) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4141
4760
  if (request.method === 'POST' && url.pathname === '/api/tour') {
4142
4761
  const change = await body(request).catch(() => null);
4762
+ const already = MISSIONS.includes(change?.mission) && Boolean((await readTour(root)).missions?.[change.mission]);
4143
4763
  const changed = await changeTour(root, change);
4144
4764
  if (changed.error) return sendJson(response, 422, { error: t('That is not a change to the tour.') });
4145
4765
  // How far people get in the welcome, and what they leave for later (2026-11-01): 90 of 147
@@ -4151,6 +4771,8 @@ export async function createPulseServer({
4151
4771
  if (WELCOME_STEPS.includes(step.skipped)) diagnostics.count(`welcome.skip.${step.skipped}`);
4152
4772
  if (step.finished === true) diagnostics.count('welcome.finished');
4153
4773
  }
4774
+ // Which of the first steps people do (2026-11-11): the mission's id, nothing else.
4775
+ if (MISSIONS.includes(change?.mission) && !already) diagnostics.count(`mission.${change.mission}`);
4154
4776
  return sendJson(response, 200, { state: changed });
4155
4777
  }
4156
4778
  if (request.method === 'GET' && url.pathname === '/api/tour/projects') {
@@ -4191,7 +4813,14 @@ export async function createPulseServer({
4191
4813
  // Only a version semver would write reaches a shell, and the restart never runs without the
4192
4814
  // download first (src/updates.mjs): an unchecked one used to skip the download and run.
4193
4815
  if (!command || !fetching) return sendJson(response, 412, { error: t('The version the registry gave ({version}) is not one MADRE installs.', { version: String(info.latest).slice(0, 40) }) });
4816
+ // Installed with sudo (Q-22): npm -g cannot replace it from here, so the room says how and stays open.
4817
+ if (install === 'global' && !(await canReplace(await realpath(join(sourceDirectory, '..')).catch(() => join(sourceDirectory, '..'))))) {
4818
+ return sendJson(response, 412, { error: t('MADRE was installed with administrator permission, so it cannot update itself. In a terminal, run: {command}', { command: `sudo npm install -g ${PACKAGE.name}@${info.latest}` }) });
4819
+ }
4194
4820
  if (room.activeTurns().length || room.activePlans().length) return sendJson(response, 409, { error: t('Agents are still working. STOPALL or wait, then update.') });
4821
+ // The update brings every open project and Home along (L-13): none of them may be cut off.
4822
+ const busy = await busyElsewhere().catch(() => []);
4823
+ if (busy.length) return sendJson(response, 409, { error: t('Something is still running in {list}. Updating restarts all of MADRE: wait for it to finish or stop it, then update.', { list: busy.join(', ') }), busy });
4195
4824
  {
4196
4825
  // npm is a .cmd on Windows and needs a shell there; every argument here is fixed or checked above.
4197
4826
  const fetched = await new Promise((resolve) => execFile(fetching.command, fetching.args, { cwd: root, timeout: 180000, shell: process.platform === 'win32', windowsHide: true, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => resolve(error ? (String(stderr || error.message).split('\n').map((line) => line.trim()).find((line) => line && !/complete log|^npm (error|ERR!)(\s+code\b.*)?\s*$/i.test(line)) ?? error.message) : null)));
@@ -4204,12 +4833,15 @@ export async function createPulseServer({
4204
4833
  sendJson(response, 202, { restarting: true, from: info.current, to: info.latest, command });
4205
4834
  setTimeout(() => {
4206
4835
  server.close(() => {
4836
+ // On Linux the new version takes this process's place (Q-23, src/updates.mjs takesItsPlace):
4837
+ // it comes back here only when it could not.
4838
+ becomeNext({ file: '/bin/sh', args: ['-c', command], env: { ...process.env, PULSE_UPDATE_RESTART: '1' }, cwd: canonicalProjectRoot, log: join(roomDir, 'update.log') });
4207
4839
  // Each system has its own shell: the command is one line either way.
4208
4840
  const shell = process.platform === 'win32' ? { file: process.env.COMSPEC ?? 'cmd.exe', args: ['/d', '/s', '/c', command] } : { file: '/bin/sh', args: ['-c', command] };
4209
4841
  // What the new copy says on the way up lands beside the ledger: if it never comes back,
4210
4842
  // this file is the only witness.
4211
4843
  let log = 'ignore';
4212
- try { log = openSync(join(roomDir, 'update.log'), 'a'); } catch { /* no witness, still restart */ }
4844
+ try { log = openPrivateLog(join(roomDir, 'update.log')); } catch { /* no witness, still restart */ }
4213
4845
  const child = spawn(shell.file, shell.args, { cwd: canonicalProjectRoot, detached: process.platform !== 'win32', windowsHide: true, stdio: ['ignore', log, log], env: { ...process.env, PULSE_UPDATE_RESTART: '1' } });
4214
4846
  child.unref();
4215
4847
  setTimeout(() => process.exit(0), 200);
@@ -4218,6 +4850,130 @@ export async function createPulseServer({
4218
4850
  }, 300);
4219
4851
  return undefined;
4220
4852
  }
4853
+ // The author's notices (Q-11): the ones for this copy, «got it», and whether info and important
4854
+ // ones show (security ones always do).
4855
+ if (request.method === 'GET' && url.pathname === '/api/notices') {
4856
+ return sendJson(response, 200, await noticesForPage());
4857
+ }
4858
+ if (request.method === 'POST' && url.pathname === '/api/notices/seen') {
4859
+ const payload = await body(request).catch(() => ({}));
4860
+ if (!(await noticeSeen(root, payload.id))) return sendJson(response, 422, { error: t('No such notice.') });
4861
+ // Counted only where the anonymous diagnostics are on (src/telemetry.mjs decides): how many
4862
+ // copies saw a notice, never which.
4863
+ diagnostics.count(`notice.${payload.id}`);
4864
+ return sendJson(response, 200, { ok: true });
4865
+ }
4866
+ // NOTIFICATIONS OF THE SYSTEM (2026-11-10, asked by the author): which kinds this computer hands
4867
+ // to macOS (or the browser). A new version and the author's notices always do; the rest are the person's.
4868
+ // A module never reaches the system: it declares `notifies` (its permission) and MADRE's page
4869
+ // decides, with this, whether what it has to say goes out (public/notifications.js).
4870
+ if (url.pathname === '/api/notifications' && (request.method === 'GET' || request.method === 'POST')) {
4871
+ if (request.method === 'POST') {
4872
+ const payload = await body(request).catch(() => ({}));
4873
+ const patch = {};
4874
+ for (const key of NOTIFICATION_KINDS) if (typeof payload[key] === 'boolean') patch[key] = payload[key];
4875
+ if (payload.modules && typeof payload.modules === 'object' && !Array.isArray(payload.modules)) {
4876
+ const declared = new Set(MODULES.filter((one) => one.notifies).map((one) => one.id));
4877
+ const current = (await readConfig(root)).notifications?.modules ?? {};
4878
+ const modules = { ...current };
4879
+ for (const [id, on] of Object.entries(payload.modules)) if (declared.has(id) && typeof on === 'boolean') modules[id] = on;
4880
+ patch.modules = modules;
4881
+ }
4882
+ await updateConfig(root, { notifications: patch });
4883
+ }
4884
+ const kept = (await readConfig(root)).notifications ?? {};
4885
+ const prefs = Object.fromEntries(NOTIFICATION_KINDS.map((key) => [key, kept[key] !== false]));
4886
+ const modules = MODULES.filter((one) => one.notifies).map((one) => ({ id: one.id, name: say(one.name), about: say(one.notifies.label), note: one.notifies.note ? say(one.notifies.note) : null, on: kept.modules?.[one.id] !== false }));
4887
+ return sendJson(response, 200, { prefs, modules });
4888
+ }
4889
+ if (request.method === 'POST' && url.pathname === '/api/notices/settings') {
4890
+ const payload = await body(request).catch(() => ({}));
4891
+ if (typeof payload.enabled === 'boolean') await updateConfig(root, { notices: { enabled: payload.enabled } });
4892
+ return sendJson(response, 200, await noticesForPage());
4893
+ }
4894
+ // MADRE App's subscription (src/billing.mjs): read and changed from the pages of this computer only.
4895
+ if (url.pathname === '/api/subscription' || url.pathname.startsWith('/api/subscription/')) {
4896
+ if (viaPhone) return sendJson(response, 404, { error: t('Not found.') });
4897
+ if (request.method === 'GET' && url.pathname === '/api/subscription') return sendJson(response, 200, await billingForPage());
4898
+ if (request.method !== 'POST' || request.headers.origin !== `http://${request.headers.host}`) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4899
+ const payload = await body(request).catch(() => ({}));
4900
+ const now = await billingNow();
4901
+ if (now.view.state === 'off') return sendJson(response, 409, { error: t('There is no subscription in this copy of MADRE.') });
4902
+ if (url.pathname === '/api/subscription/subscribe') {
4903
+ if (!billingKey) return sendJson(response, 503, { error: t('Subscriptions are not open yet. Try again in a few days.') });
4904
+ const order = await newOrder(root, { language: roomLanguage() });
4905
+ orderAsked = 0;
4906
+ await billingNow();
4907
+ return sendJson(response, 200, { url: order.url });
4908
+ }
4909
+ // Already subscribed, on another computer or before (2026-11-18): the email of the payment gets a
4910
+ // button, and this copy's key arrives on its own once it is confirmed. Nothing to paste.
4911
+ if (url.pathname === '/api/subscription/recover') {
4912
+ if (!billingKey) return sendJson(response, 503, { error: t('Subscriptions are not open yet. Try again in a few days.') });
4913
+ const started = await startRecovery(root, { email: payload.email, language: roomLanguage() });
4914
+ if (started.error === 'email') return sendJson(response, 422, { error: t('Write the email you paid with.') });
4915
+ if (started.error === 'too_many') return sendJson(response, 429, { error: t('You asked several times already. Wait an hour and try again.') });
4916
+ if (started.error) return sendJson(response, 502, { error: t('madre.run did not answer. Try again in a moment.') });
4917
+ recoveryAsked = 0;
4918
+ return sendJson(response, 200, await billingForPage({ ask: false }));
4919
+ }
4920
+ if (url.pathname === '/api/subscription/recover/stop') {
4921
+ await stopRecovery(root);
4922
+ return sendJson(response, 200, await billingForPage({ ask: false }));
4923
+ }
4924
+ if (url.pathname === '/api/subscription/manage') {
4925
+ const where = await portalUrl(root, { language: roomLanguage() });
4926
+ return where ? sendJson(response, 200, { url: where }) : sendJson(response, 502, { error: t('madre.run did not answer. Try again in a moment.') });
4927
+ }
4928
+ if (url.pathname === '/api/subscription/seen') {
4929
+ await markBillingSeen(root, String(payload.moment ?? ''));
4930
+ return sendJson(response, 200, await billingForPage({ ask: false }));
4931
+ }
4932
+ if (url.pathname === '/api/subscription/project' && !salasRoom) {
4933
+ const chosen = await chooseProject(root, { room: projectRoomId(canonicalProjectRoot), name: basename(canonicalProjectRoot) });
4934
+ if (!chosen.ok) return sendJson(response, 409, { error: t('You can change the project that takes messages once a day. Next time: {when}.', { when: new Date(chosen.next).toLocaleString(roomLanguage() === 'en' ? 'en-US' : 'es-MX', { weekday: 'long', hour: 'numeric', minute: '2-digit' }) }), active: chosen.active });
4935
+ return sendJson(response, 200, await billingForPage({ ask: false }));
4936
+ }
4937
+ return sendJson(response, 404, { error: t('Not found.') });
4938
+ }
4939
+ // The author's switch for the subscription: signed here with the notices' key, sent to madre.run,
4940
+ // read by every app. Only in the author's copy run from source, from this computer.
4941
+ if (request.method === 'POST' && url.pathname === '/api/owner/billing') {
4942
+ const address = request.socket.remoteAddress ?? '';
4943
+ if (viaPhone || !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(address) || !(await ownerCanNotify())) return sendJson(response, 404, { error: t('Not found.') });
4944
+ if (request.headers.origin !== `http://${request.headers.host}`) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4945
+ const payload = await body(request).catch(() => ({}));
4946
+ if (typeof payload.on !== 'boolean') return sendJson(response, 422, { error: t('Say whether it is on or off.') });
4947
+ if (payload.on && !billingKey) return sendJson(response, 409, { error: t('First make the key of the subscription keys: node scripts/billing-key.mjs. Without it nobody could pay.') });
4948
+ const at = new Date().toISOString();
4949
+ const sent = signSwitch({ on: payload.on, from: at, trialDays: TRIAL_DAYS, price: { mxn: PRICE_MXN }, at }, await readFile(NOTICES_KEY_FILE, 'utf8'));
4950
+ const token = await readSecret(root, OWNER_VAULT, 'usage');
4951
+ const answer = await globalThis.fetch(`${billingSite()}/api/cobro`, { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify(sent), signal: AbortSignal.timeout(10000) }).catch(() => null);
4952
+ const said = answer ? await answer.json().catch(() => ({})) : {};
4953
+ if (!answer?.ok) return sendJson(response, 502, { error: said.error ? t('madre.run said: {error}', { error: said.error }) : t('madre.run did not answer.') });
4954
+ widgetReadings.delete('billing');
4955
+ return sendJson(response, 200, { ok: true, switch: sent.switch });
4956
+ }
4957
+ // Writing one, or taking it back: only from this computer, only in the author's copy.
4958
+ if (request.method === 'POST' && (url.pathname === '/api/owner/notices' || url.pathname === '/api/owner/notices/retire')) {
4959
+ const address = request.socket.remoteAddress ?? '';
4960
+ if (viaPhone || !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(address) || !(await ownerCanNotify())) return sendJson(response, 404, { error: t('Not found.') });
4961
+ const payload = await body(request).catch(() => ({}));
4962
+ const token = await readSecret(root, OWNER_VAULT, 'usage');
4963
+ const key = await readFile(NOTICES_KEY_FILE, 'utf8');
4964
+ let sent;
4965
+ try {
4966
+ sent = url.pathname.endsWith('/retire') ? { retire: signRetire(String(payload.id ?? ''), key) } : signNotice(payload.notice, key);
4967
+ } catch (error) {
4968
+ return sendJson(response, 422, { error: t(error.message) });
4969
+ }
4970
+ const answer = await globalThis.fetch(noticesUrl(), { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, body: JSON.stringify(sent), signal: AbortSignal.timeout(10000) }).catch(() => null);
4971
+ const said = answer ? await answer.json().catch(() => ({})) : {};
4972
+ if (!answer?.ok) return sendJson(response, 502, { error: said.error ? t('madre.run said: {error}', { error: said.error }) : t('madre.run did not answer.') });
4973
+ widgetReadings.delete('notices');
4974
+ void refreshNotices({ stateRoot: root, force: true }).catch(() => null);
4975
+ return sendJson(response, 200, { ok: true, id: sent.notice?.id ?? sent.retire?.id });
4976
+ }
4221
4977
  if (request.method === 'POST' && url.pathname === '/api/updates/settings') {
4222
4978
  const patch = await body(request).catch(() => ({}));
4223
4979
  if (typeof patch.check === 'boolean') { updatesConfig = { ...updatesConfig, check: patch.check }; await updateConfig(root, { updates: updatesConfig }); await adoptBuiltinUpdates({ stateRoot: root, enabled: marketOn(), ...factoryKeyed }).catch(() => []); }
@@ -4309,6 +5065,25 @@ export async function createPulseServer({
4309
5065
  if (mounted.error) return sendJson(response, 409, mounted);
4310
5066
  return sendJson(response, 200, { ...(await chatsView()), opened: made.id });
4311
5067
  }
5068
+ // Summarize and continue (2026-11-11): the summary its agent wrote opens a new conversation.
5069
+ const carryMatch = url.pathname.match(/^\/api\/chats\/([a-z0-9]+)\/carry$/);
5070
+ if (carryMatch && request.method === 'POST') {
5071
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5072
+ const payload = await body(request).catch(() => ({}));
5073
+ const index = await chatIndex(roomDir);
5074
+ const before = index.chats[carryMatch[1]];
5075
+ // Its name as the page saw it before the summary was asked for: an unnamed conversation took
5076
+ // the request itself as its name, and gets it back empty.
5077
+ const named = typeof payload.title === 'string' ? payload.title.trim().slice(0, 80) || null : (before?.title ?? null);
5078
+ if (before && typeof payload.title !== 'undefined' && !named) await renameChat(roomDir, carryMatch[1], '');
5079
+ // One that already continued another keeps one «· continued», not a chain of them.
5080
+ const title = named ? t('{title} · continued', { title: named.replace(/ · (?:continued|sigue)$/, '').slice(0, 60) }) : null;
5081
+ const made = await carryChat(roomDir, carryMatch[1], { title, summary: payload.summary, from: named });
5082
+ if (!made) return sendJson(response, 400, { error: t('There was no summary to carry.') });
5083
+ const mounted = await mountChat(made.id);
5084
+ if (mounted.error) return sendJson(response, 409, mounted);
5085
+ return sendJson(response, 200, { ...(await chatsView()), opened: made.id });
5086
+ }
4312
5087
  const chatMatch = url.pathname.match(/^\/api\/chats\/([a-z0-9]+)$/);
4313
5088
  if (chatMatch && request.method === 'POST') {
4314
5089
  if (viaPhone) return sendJson(response, 200, { ...(await chatsView()), opened: chatMatch[1] });
@@ -4318,7 +5093,11 @@ export async function createPulseServer({
4318
5093
  }
4319
5094
  if (chatMatch && request.method === 'PATCH') {
4320
5095
  const payload = await body(request).catch(() => ({}));
4321
- const named = await renameChat(roomDir, chatMatch[1], payload.title);
5096
+ // Its name, or whether it is pinned (2026-11-11), or both.
5097
+ let named = true;
5098
+ if ('title' in payload) named = await renameChat(roomDir, chatMatch[1], payload.title);
5099
+ if (named && 'pinned' in payload) named = await pinChat(roomDir, chatMatch[1], Boolean(payload.pinned));
5100
+ if (named && 'archived' in payload) named = await archiveChat(roomDir, chatMatch[1], Boolean(payload.archived));
4322
5101
  return named ? sendJson(response, 200, { ...(await chatsView()) }) : sendJson(response, 404, { error: t('No such conversation.') });
4323
5102
  }
4324
5103
  if (chatMatch && request.method === 'DELETE') {
@@ -4344,11 +5123,17 @@ export async function createPulseServer({
4344
5123
  const result = await room.runExam(String(payload.which ?? ''), { findings: eyecat.findings() });
4345
5124
  return sendJson(response, result?.error ? 409 : 200, { ...result, exams: await room.exams() });
4346
5125
  }
4347
- // Somebody's own module, handed to MADRE from the panel. It runs inside MADRE with the
4348
- // human's permissions, so it goes through the same door as everything else: written to a
4349
- // scratch copy, imported there, checked against the house rules, and only then installed.
5126
+ // «Remind me later» on @madre's test: asked again in a few days (offerLocalTry).
5127
+ if (request.method === 'POST' && url.pathname === '/api/local/later') {
5128
+ if (memory) memory.metaSet('local.offered', new Date().toISOString());
5129
+ return sendJson(response, 200, { ok: true, again: LOCAL_TRY_AGAIN_MS });
5130
+ }
5131
+ // Somebody's own module, handed to MADRE from the panel. It goes through the same door as
5132
+ // everything else: checked in a fenced scratch copy, then installed for isolated calls.
4350
5133
  if (request.method === 'POST' && url.pathname === '/api/extensions/upload') {
4351
5134
  const payload = await body(request).catch(() => ({}));
5135
+ const refused = moduleKeyRefused(request, payload);
5136
+ if (refused) return sendJson(response, ...refused);
4352
5137
  const text = String(payload.text ?? '');
4353
5138
  const name = String(payload.name ?? 'module.mjs');
4354
5139
  if (!text.trim()) return sendJson(response, 400, { error: t('That file is empty.') });
@@ -4391,6 +5176,8 @@ export async function createPulseServer({
4391
5176
  return sendJson(response, 200, { origin, current: module.version ?? null, candidate: candidate.version ?? null, same: (candidate.version ?? null) === (module.version ?? null) });
4392
5177
  } catch (error) { return sendJson(response, 422, { error: error.message, origin }); }
4393
5178
  }
5179
+ const refused = moduleKeyRefused(request, payload);
5180
+ if (refused) return sendJson(response, ...refused);
4394
5181
  try {
4395
5182
  const installed = await installModuleText({ text, name: `${module.id}.mjs`, scope: module.origin === 'project' ? 'project' : 'user', stateRoot: root, projectRoot: canonicalProjectRoot, source: origin });
4396
5183
  await room.record('extension.installed', { id: installed.id, name: installed.name, origin: installed.origin, file: installed.file, version: installed.version, by: 'refresh' });
@@ -4415,7 +5202,7 @@ export async function createPulseServer({
4415
5202
  installing = module.id; installingSince = Date.now();
4416
5203
  await room.record('extension.install.started', { id: module.id, name: item.name, command: plan.display, platforms: [], alreadyInstalled: true });
4417
5204
  void (async () => {
4418
- 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)] }); } });
5205
+ const result = await runInstaller({ command: plan.command, args: plan.args, projectRoot: canonicalProjectRoot, timeoutMs: plan.timeoutMs ?? 900000, onLine: (line) => { void room.record('extension.install.output', { id: module.id, lines: [String(line).slice(0, 500)] }); } });
4419
5206
  // What the plan does once the command is done (Ollama: restart the old server). If it could
4420
5207
  // not, that is the outcome: «now runs <the old version>» would read as an update that worked.
4421
5208
  const settled = result.code === 0 ? await (async () => plan.after?.())().catch((error) => ({ ok: false, error: error.message })) : null;
@@ -4499,7 +5286,7 @@ export async function createPulseServer({
4499
5286
  return sendJson(response, 403, { error: t('A key is only accepted from this computer, never over the network.') });
4500
5287
  }
4501
5288
  const agent = agents.find((item) => item.id === id);
4502
- if (!agent?.detected) return sendJson(response, 412, { error: t('{label} is not installed on this computer.', { label: agent?.label ?? id }) });
5289
+ if (!agent?.detected && id !== 'gemini') return sendJson(response, 412, { error: t('{label} is not installed on this computer.', { label: agent?.label ?? id }) });
4503
5290
  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 }) });
4504
5291
  const payload = await body(request).catch(() => ({}));
4505
5292
  const result = await applyKey({
@@ -4511,7 +5298,8 @@ export async function createPulseServer({
4511
5298
  probe: () => probeAgentAuth(agent),
4512
5299
  });
4513
5300
  if (!result.ok) return sendJson(response, 422, { error: result.error });
4514
- await refreshSessions();
5301
+ // A Gemini key with no CLI is how Gemini arrives (through its API): look again, not only at sessions.
5302
+ if (id === 'gemini' && !agent?.path) await redetectAgents(); else await refreshSessions();
4515
5303
  // What the room remembers: that a key was set, and for which provider. Never the key.
4516
5304
  await room.record('connection.key.set', { agent: id, label: agent.label, provider: payload.provider ?? null, detail: result.detail ?? null });
4517
5305
  return sendJson(response, 200, { ok: true, session: sessions[id] ?? null });
@@ -4571,7 +5359,20 @@ export async function createPulseServer({
4571
5359
  if (ids.length) Object.assign(cursorModels, { at: Date.now(), ids });
4572
5360
  return ids;
4573
5361
  };
4574
- return sendJson(response, 200, { models: await discoverModels({ agents, config: await readConfig(root), listOpenCode: url.searchParams.get('opencode') === '1' ? listOpenCode : async () => [], listCursor: url.searchParams.get('cursor') === '1' ? listCursor : async () => [], cursorOnlyAuto, listGemini: url.searchParams.get('gemini') === '1' ? listGemini : async () => [] }) });
5362
+ const listGrok = async (grok) => {
5363
+ if (grokModels.at && Date.now() - grokModels.at < 10 * 60 * 1000) return grokModels.list;
5364
+ const { stdout } = await execFileAsync(grok.path, ['models'], { timeout: 20000, env: { ...process.env, GROK_DISABLE_AUTOUPDATER: '1' } });
5365
+ const list = parseGrokModels(stdout);
5366
+ if (list.models.length) Object.assign(grokModels, { at: Date.now(), list });
5367
+ return list;
5368
+ };
5369
+ const config = await readConfig(root);
5370
+ const found = await discoverModels({ agents, config, listOpenCode: url.searchParams.get('opencode') === '1' ? listOpenCode : async () => [], listCursor: url.searchParams.get('cursor') === '1' ? listCursor : async () => [], cursorOnlyAuto, listGemini: url.searchParams.get('gemini') === '1' ? listGemini : async () => [], listGrok: url.searchParams.get('grok') === '1' ? listGrok : async () => ({ models: [], default: null }) });
5371
+ for (const [agent, list] of Object.entries(found)) {
5372
+ const kept = agent === 'opencode' ? config.opencode?.favorites : config.favorites?.[agent];
5373
+ if (list && typeof list === 'object') list.favorites = Array.isArray(kept) ? kept.slice(0, 3) : [];
5374
+ }
5375
+ return sendJson(response, 200, { models: found });
4575
5376
  }
4576
5377
  // OpenCode's providers for AJUSTES: who has a key or an account, what each offers, which are
4577
5378
  // left out of the chooser. Never a key: only that one is there and of what kind.
@@ -4667,7 +5468,7 @@ export async function createPulseServer({
4667
5468
  if (url.searchParams.get('everywhere') !== '1') return sendJson(response, 200, mine);
4668
5469
  const others = (await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId);
4669
5470
  const answers = await Promise.all(others.map(async (one) => {
4670
- const answer = await askRoom(one.open.port, '/api/activity', { timeoutMs: 1500 });
5471
+ const answer = await askRoom(one.open.port, '/api/activity', { stateRoot: root, timeoutMs: 1500 });
4671
5472
  if (answer.unreachable) return null;
4672
5473
  if (answer.outdated) return { room: one.id, name: one.name, port: one.open.port, outdated: true, now: [], done: [] };
4673
5474
  return { ...answer, room: one.id, name: answer.name ?? one.name, port: one.open.port };
@@ -4688,7 +5489,7 @@ export async function createPulseServer({
4688
5489
  if (viaPhone) return sendJson(response, 403, { error: t('Other projects are stopped from this computer.') });
4689
5490
  const there = (await knownRooms(root)).find((one) => one.id === payload.room && one.open);
4690
5491
  if (!there) return sendJson(response, 404, { error: t('That project is not open any more.') });
4691
- const answer = await askRoom(there.open.port, '/api/activity/stop', { method: 'POST', body: { ...payload, room: null }, timeoutMs: 8000 });
5492
+ const answer = await askRoom(there.open.port, '/api/activity/stop', { stateRoot: root, method: 'POST', body: { ...payload, room: null }, timeoutMs: 8000 });
4692
5493
  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 });
4693
5494
  if (answer.unreachable) return sendJson(response, answer.status ?? 502, { error: answer.error ?? t('That project did not answer.') });
4694
5495
  return sendJson(response, 200, answer);
@@ -4703,6 +5504,11 @@ export async function createPulseServer({
4703
5504
  const id = String(payload.id ?? '');
4704
5505
  const cut = id.lastIndexOf(':');
4705
5506
  stopped = cut > 0 && where.stopRun({ responseMessageId: id.slice(0, cut), index: Number(id.slice(cut + 1)) });
5507
+ } else if (payload.kind === 'install' && pulling) {
5508
+ // A model downloading: the same stop as the welcome's and Local AI's. Other installs run to
5509
+ // the end; the row offers no stop for them.
5510
+ pulling.stopper.abort();
5511
+ stopped = true;
4706
5512
  }
4707
5513
  return sendJson(response, stopped ? 200 : 404, stopped ? { stopped: true } : { error: t('That is not running any more.') });
4708
5514
  }
@@ -4711,7 +5517,7 @@ export async function createPulseServer({
4711
5517
  let projects = 0;
4712
5518
  if (!viaPhone) {
4713
5519
  const others = (await knownRooms(root)).filter((one) => one.open && one.id !== thisRoomId);
4714
- 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)));
5520
+ const stopped = await Promise.all(others.map((one) => askRoom(one.open.port, '/api/stop-all', { stateRoot: root, method: 'POST', body: {}, timeoutMs: 3000 }).then((answer) => !answer.unreachable && !answer.outdated)));
4715
5521
  projects = stopped.filter(Boolean).length;
4716
5522
  }
4717
5523
  return sendJson(response, 202, { stopped: true, ...result, projects });
@@ -4802,12 +5608,149 @@ export async function createPulseServer({
4802
5608
  void warmModuleUpdates(extensions);
4803
5609
  return sendJson(response, 200, { installing, extensions, failures: loadFailures, folders: moduleFolders({ stateRoot: root, projectRoot: canonicalProjectRoot }), sdk: SDK_PAGE[roomLanguage()] ?? SDK_PAGE.es });
4804
5610
  }
5611
+ // HABILIDADES (H-3): the ways of working this project keeps, each with what it tells the
5612
+ // agents, what it carries, and the word this project said about it. Read from disk every
5613
+ // time: a skill the person just dropped in is on the board without reloading anything.
5614
+ if (request.method === 'GET' && url.pathname === '/api/skills') {
5615
+ const config = await readConfig(root);
5616
+ const { loaded, failures, folders } = await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot });
5617
+ const fromMarket = await installedSkills(root);
5618
+ const skills = loaded.map((skill) => ({
5619
+ id: skill.id, name: skill.name, when: skill.when, line: skill.line, icon: skill.icon, version: skill.version, minMadre: skill.minMadre,
5620
+ credit: skill.credit, license: skill.license, origin: skill.origin, dir: skill.dir, unknown: skill.unknown,
5621
+ // What it says, whole: it is a page, and a person can actually read it before turning it on.
5622
+ body: skill.body, declares: skillDeclares(skill),
5623
+ state: skillState(config, skill.id, scopeRoom),
5624
+ everywhere: skillState(config, skill.id, null),
5625
+ // One the Market signed is not the person's to send: it is already there.
5626
+ market: Boolean(fromMarket[skill.id]),
5627
+ }));
5628
+ return sendJson(response, 200, { skills, failures, folders, project: Boolean(scopeRoom) });
5629
+ }
5630
+ // GIVING ONE TO SOMEBODY (C-1): its files, without MADRE's own record of where it came from,
5631
+ // in a folder the person can find. Nothing is sent anywhere: MADRE prepares, the person sends.
5632
+ if (request.method === 'POST' && url.pathname === '/api/skills/share') {
5633
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5634
+ const payload = await body(request).catch(() => ({}));
5635
+ try {
5636
+ const ready = await shareSkill({ stateRoot: root, projectRoot: canonicalProjectRoot, id: String(payload.id ?? '') });
5637
+ const shown = await openInBrowser(ready.folder, await environmentOnce().catch(() => null)).catch(() => false);
5638
+ return sendJson(response, 200, { ...ready, shown });
5639
+ } catch (error) { return sendJson(response, 404, { error: error.message }); }
5640
+ }
5641
+ // SENDING ONE'S OWN SKILL TO THE MARKET (H-8). A skill is one file, so this is not a form full
5642
+ // of what MADRE already knows: only what nobody but the person can say, written into its own
5643
+ // header. Asked once for the draft, then again to write the folder they will send.
5644
+ if (request.method === 'POST' && url.pathname === '/api/skills/submission') {
5645
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5646
+ const payload = await body(request).catch(() => ({}));
5647
+ const { loaded } = await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot });
5648
+ const mine = loaded.find((one) => one.id === String(payload.id ?? ''));
5649
+ if (!mine) return sendJson(response, 404, { error: t('No skill «{id}».', { id: payload.id }) });
5650
+ try {
5651
+ const draft = skillDraft(mine, { madre: PACKAGE.version });
5652
+ if (!payload.write) return sendJson(response, 200, { draft, asks: SKILL_ASKS, shelves: SKILL_SHELVES, licenses: SKILL_LICENSES });
5653
+ const written = await writeSkillSubmission({ stateRoot: root, dir: mine.dir, entry: payload.entry ?? {} });
5654
+ const shown = payload.reveal === true ? await openInBrowser(written.folder, await environmentOnce().catch(() => null)).catch(() => false) : false;
5655
+ return sendJson(response, 200, { draft, asks: SKILL_ASKS, shelves: SKILL_SHELVES, licenses: SKILL_LICENSES, ...written, shown });
5656
+ } catch (error) { return sendJson(response, 422, { error: error.message }); }
5657
+ }
5658
+ // THE SKILLS THIS COMPUTER ALREADY HAS (H-7): read where each CLI keeps them, with what would
5659
+ // happen to each one here. Nothing is brought over until the person says which.
5660
+ if (request.method === 'GET' && url.pathname === '/api/skills/import') {
5661
+ const found = await findSkills({ projectRoot: canonicalProjectRoot, stateRoot: root });
5662
+ return sendJson(response, 200, { found });
5663
+ }
5664
+ if (request.method === 'POST' && url.pathname === '/api/skills/import') {
5665
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5666
+ const payload = await body(request).catch(() => ({}));
5667
+ const ids = (Array.isArray(payload.ids) ? payload.ids : []).slice(0, 50).map((id) => String(id));
5668
+ if (!ids.length) return sendJson(response, 400, { error: t('Name which ones to bring over.') });
5669
+ const done = await importSkills({ ids, stateRoot: root, projectRoot: canonicalProjectRoot, scope: payload.scope === 'project' ? 'project' : 'user' });
5670
+ for (const one of done.brought) await room.record('skill.installed', { id: one.id, name: one.name, origin: payload.scope === 'project' ? 'project' : 'user', from: one.who, by: 'you' });
5671
+ return sendJson(response, 200, done);
5672
+ }
5673
+ // A skill an agent wrote in its draft folder (H-6): read it, say what it tells the agents, and
5674
+ // install it only when the person said so. The file is the agent's proposal; installing is
5675
+ // theirs. Two steps like every other door into the skills folder: `review` writes nothing.
5676
+ if (request.method === 'POST' && url.pathname === '/api/skills/install-file') {
5677
+ const payload = await body(request).catch(() => ({}));
5678
+ const relative = String(payload.path ?? '').replace(/^\/+/, '');
5679
+ // From the agent's draft inside the project, or from what the person dragged into the room
5680
+ // (C-1): those are the only two places, and they are the same two a module comes from.
5681
+ const sent = payload.root === 'attachments';
5682
+ if (!relative || relative.includes('..') || (!sent && !isSkillFile(relative))) return sendJson(response, 400, { error: t('Give the project-relative path of a <id>.habilidad.md file.') });
5683
+ const file = sent ? join(attachmentsRoot, relative) : join(canonicalProjectRoot, relative);
5684
+ try {
5685
+ const text = await readFile(file, 'utf8');
5686
+ const read = readSkillText(text, { id: skillIdOf(relative) });
5687
+ if (payload.review === true) {
5688
+ return sendJson(response, 200, { review: true, id: read.id, name: read.name, when: read.when, version: read.version, body: read.body, unknown: read.unknown, declares: skillDeclares({ ...read, files: [], scripts: [] }) });
5689
+ }
5690
+ const done = await installSkill({
5691
+ files: [{ path: SKILL_FILES[0], text }],
5692
+ scope: payload.scope === 'project' ? 'project' : 'user',
5693
+ stateRoot: root, projectRoot: canonicalProjectRoot,
5694
+ source: { kind: sent ? 'sent' : 'file', from: relative, id: read.id },
5695
+ });
5696
+ await room.record('skill.installed', { id: done.id, name: done.name, origin: done.origin, from: sent ? 'sent' : relative, by: 'you' });
5697
+ return sendJson(response, 200, { installed: done });
5698
+ } catch (error) { return sendJson(response, 422, { error: error.message }); }
5699
+ }
5700
+ // Off, matched or always on, for this project or for all of them. Nothing else changes.
5701
+ const skillState_ = request.method === 'POST' && url.pathname.match(/^\/api\/skills\/([a-z][a-z0-9-]{1,39})\/state$/);
5702
+ if (skillState_) {
5703
+ const payload = await body(request).catch(() => ({}));
5704
+ if (!SKILL_STATES.includes(payload.state)) return sendJson(response, 400, { error: t('A skill is off, matched or always on; nothing else.') });
5705
+ const id = skillState_[1];
5706
+ const config = await readConfig(root);
5707
+ const here = payload.scope === 'everywhere' ? null : scopeRoom;
5708
+ await updateConfig(root, { skills: { ...(config.skills ?? {}), [id]: skillStateIn(config.skills?.[id] ?? {}, here, payload.state) } });
5709
+ await room.record('skill.switched', { id, state: payload.state, scope: here ? 'project' : 'everywhere' });
5710
+ return sendJson(response, 200, { ok: true, id, state: payload.state });
5711
+ }
5712
+ // Removing one is the person's: the folder goes, and nothing a skill's scripts wrote is touched.
5713
+ const skillGone = request.method === 'POST' && url.pathname.match(/^\/api\/skills\/([a-z][a-z0-9-]{1,39})\/remove$/);
5714
+ if (skillGone) {
5715
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5716
+ try {
5717
+ const gone = await removeSkill({ id: skillGone[1], stateRoot: root, projectRoot: canonicalProjectRoot });
5718
+ await room.record('skill.removed', { id: gone.id, folders: gone.removed.length });
5719
+ return sendJson(response, 200, { ok: true, ...gone });
5720
+ } catch (error) { return sendJson(response, 404, { error: error.message }); }
5721
+ }
5722
+ // A skill from the Market onto this computer (H-4). Asked twice on purpose, as a module is:
5723
+ // first to read what it tells the agents, then to install the very files that were read.
5724
+ if (request.method === 'POST' && url.pathname === '/api/market/skills/install') {
5725
+ if (viaPhone) return sendJson(response, 403, { error: t('This is done on the Mac.') });
5726
+ const payload = await body(request).catch(() => ({}));
5727
+ const read = await syncMarket().catch(() => ({ catalog: null }));
5728
+ const catalog = read.catalog ?? await keptCatalog({ stateRoot: root, ...marketKeyed });
5729
+ if (!catalog) return sendJson(response, 503, { error: t('MADRE could not read the Market.') });
5730
+ try {
5731
+ const done = await installSkillFromMarket({
5732
+ stateRoot: root, projectRoot: canonicalProjectRoot, madre: PACKAGE.version, fetchImpl: marketFetch,
5733
+ id: String(payload.id ?? ''), catalog, review: payload.review === true, accept: payload.accept ?? null,
5734
+ });
5735
+ if (!done.review) { await room.record('skill.installed', { id: done.id, version: done.version ?? null, from: 'market' }); await marketUsed(); }
5736
+ return sendJson(response, 200, done);
5737
+ } catch (error) {
5738
+ return sendJson(response, error.code === 'REVIEW_FIRST' ? 409 : 400, { error: error.message, code: error.code ?? null });
5739
+ }
5740
+ }
4805
5741
  // THE MARKET's catalog for the page: the one kept here at once (and a fresh one asked for
4806
5742
  // behind it), what was got from it, and what it updated on its own that nobody was told yet.
4807
5743
  if (request.method === 'GET' && url.pathname === '/api/market') {
4808
5744
  const kept = await keptCatalog({ stateRoot: root, ...marketKeyed });
4809
5745
  const read = kept ? (void syncMarket().catch(() => null), { catalog: kept }) : await syncMarket().catch(() => ({ catalog: null }));
4810
- return sendJson(response, 200, { catalog: read.catalog ?? null, off: !marketOn(), installed: await installedFromMarket(root), licensed: await licensedIds(root), news: await marketNews(root), announce: await marketAnnouncements(root, read.catalog, MODULES.map((one) => one.id)), madre: PACKAGE.version });
5746
+ // The skills that come with MADRE (1.1.4), shown on the Market's shelf of skills as already here.
5747
+ const speak = (value) => (value && typeof value === 'object' ? value[roomLanguage()] ?? value.es ?? value.en ?? '' : String(value ?? ''));
5748
+ // And the ones this person already keeps (theirs, brought over, or got from the Market).
5749
+ const local = (await loadSkills({ stateRoot: root, projectRoot: canonicalProjectRoot }).catch(() => ({ loaded: [] }))).loaded;
5750
+ const shown = (one) => ({ id: one.id, name: speak(one.name), line: speak(one.line) || speak(one.when), version: one.version, icon: one.icon ?? null, origin: one.origin });
5751
+ const included = local.filter((one) => one.origin === 'madre').map(shown);
5752
+ const yours = local.filter((one) => one.origin !== 'madre').map(shown);
5753
+ return sendJson(response, 200, { catalog: read.catalog ?? null, off: !marketOn(), installed: await installedFromMarket(root), skills: await installedSkills(root), included, yours, licensed: await licensedIds(root), news: await marketNews(root), announce: await marketAnnouncements(root, read.catalog, MODULES.map((one) => one.id)), madre: PACKAGE.version });
4811
5754
  }
4812
5755
  if (request.method === 'POST' && url.pathname === '/api/market/seen') {
4813
5756
  await marketNewsSeen(root);
@@ -4836,7 +5779,7 @@ export async function createPulseServer({
4836
5779
  await room.record('extension.installed', { id: done.id, name: inRoomLanguage(listed?.name) || done.name, origin: 'market', version: done.version, by: 'you' });
4837
5780
  for (const one of await knownRooms(root)) {
4838
5781
  if (!one.open?.port || one.id === thisRoomId) continue;
4839
- await fetch(`http://127.0.0.1:${one.open.port}/api/extensions/reload`, { method: 'POST' }).catch(() => null);
5782
+ await fetch(`http://127.0.0.1:${one.open.port}/api/extensions/reload`, { method: 'POST', headers: await fichaHeaders(root) }).catch(() => null);
4840
5783
  }
4841
5784
  return sendJson(response, 200, { installed: done, extensions: await describeModules(await moduleContext()) });
4842
5785
  } catch (error) { return sendJson(response, error.code === 'REVIEW_FIRST' ? 409 : 422, { error: error.message, review: error.code === 'REVIEW_FIRST' }); }
@@ -4916,11 +5859,14 @@ export async function createPulseServer({
4916
5859
  const payload = await body(request).catch(() => ({}));
4917
5860
  const result = await module.scope(await moduleContext(), { all: payload.all, rooms: payload.rooms, confirm: payload.confirm });
4918
5861
  for (const held of parked.values()) await applyRoomSettings(held.room, null);
5862
+ if (result.status < 300 && (payload.all === true || Object.values(payload.rooms ?? {}).includes(true))) await marketUsed();
4919
5863
  return sendJson(response, result.status, result.body);
4920
5864
  }
4921
5865
  // The human installs a module file an agent wrote (or they did): checked first, then copied into the chosen folder.
4922
5866
  if (request.method === 'POST' && url.pathname === '/api/extensions/install-file') {
4923
5867
  const payload = await body(request).catch(() => ({}));
5868
+ const refused = moduleKeyRefused(request, payload);
5869
+ if (refused) return sendJson(response, ...refused);
4924
5870
  const relative = String(payload.path ?? '').replace(/^\/+/, '');
4925
5871
  if (!relative || relative.includes('..')) return sendJson(response, 400, { error: t('Give the project-relative path of a <id>.module.mjs file.') });
4926
5872
  try {
@@ -4981,6 +5927,7 @@ export async function createPulseServer({
4981
5927
  // A phone switches MADRE's own modules; installing one runs commands in the project.
4982
5928
  if (viaPhone && !extensionById(installMatch[1])?.toggle) return sendJson(response, 403, { error: t('This is done on the Mac.') });
4983
5929
  const result = await installExtension(installMatch[1], await body(request));
5930
+ if (result.status < 300 && result.body?.enabled !== false && installMatch[1] !== 'ollama') await marketUsed();
4984
5931
  return sendJson(response, result.status, result.body);
4985
5932
  }
4986
5933
  if (request.method === 'POST' && /^\/api\/control\/[\w-]+\/undo$/.test(url.pathname)) {
@@ -5008,7 +5955,17 @@ export async function createPulseServer({
5008
5955
  // No turn before MADRE's license is accepted on this computer (src/terms.mjs): a page left open
5009
5956
  // from before, or a script, is told where to accept it.
5010
5957
  if (!viaPhone && !(await readTerms(root)).accepted) return sendJson(response, 403, { error: t('Accept MADRE\'s license in Home to start.'), terms: true });
5011
- const payload = await body(request);
5958
+ // The limited mode of MADRE App (src/billing.mjs): the Coordinator comes with the subscription,
5959
+ // and one project takes messages; the others are read, never locked or emptied.
5960
+ if (billingInApp()) {
5961
+ const plan = await billingNow();
5962
+ if (plan.view.state === 'limited') {
5963
+ if (salasRoom) return sendJson(response, 402, { error: t('The Coordinator comes with the subscription. Your projects still work: write in the one you are using.'), subscription: { limit: 'coordinator' } });
5964
+ const claim = await claimProject(root, { room: projectRoomId(canonicalProjectRoot), name: basename(canonicalProjectRoot), view: plan.view });
5965
+ if (!claim.ok) return sendJson(response, 402, { error: t('Without the subscription, one project takes messages: {name}. This one stays as it is, to read.', { name: claim.active?.name ?? '' }), subscription: { limit: 'project', active: claim.active } });
5966
+ }
5967
+ }
5968
+ const payload = await body(request, { limit: MESSAGE_LIMIT, tooLarge: t('Your message is too long to send as text. Attach it as a file instead.') });
5012
5969
  // A phone asks up to #2. The bridge already said so; the room says it again, and records
5013
5970
  // where the message came from. Only the bridge's word counts for that, never the body's.
5014
5971
  if (viaPhone) {
@@ -5068,11 +6025,12 @@ export async function createPulseServer({
5068
6025
  // A route that broke is a failure of MADRE's, not of the request: told, with the route's shape
5069
6026
  // (its ids taken out) and MADRE's own lines it went through. A body that was not JSON is the
5070
6027
  // request's.
5071
- if (!(error instanceof SyntaxError)) {
6028
+ // Nor is one that was too big to take (D-40): said as it is, with its own status.
6029
+ if (!(error instanceof SyntaxError) && error?.status !== 413) {
5072
6030
  const shape = url.pathname.replace(/\/[0-9a-f]{6,}(?=\/|$)/gi, '/:id').replace(/\/\d+(?=\/|$)/g, '/:n');
5073
6031
  diagnostics.error({ kind: 'route', where: `${request.method} ${shape}`, message: error?.message ?? String(error), stack: error?.stack ?? null });
5074
6032
  }
5075
- sendJson(response, 400, { error: error.message });
6033
+ sendJson(response, error?.status === 413 ? 413 : 400, { error: error.message });
5076
6034
  }
5077
6035
  });
5078
6036
  listening = server;
@@ -5087,7 +6045,7 @@ export async function createPulseServer({
5087
6045
  unwatchOutbound();
5088
6046
  // In-flight agent processes are killed and their turns recorded as failed
5089
6047
  // before the SSE clients go away, so open pages see the outcome.
5090
- const shutdown = Promise.all([room, ...[...parked.values()].map((held) => held.room)].map((each) => each.shutdown().catch((error) => console.error(`MADRE shutdown error: ${error.message}`))));
6048
+ const shutdown = Promise.all([...[room, ...[...parked.values()].map((held) => held.room)].map((each) => each.shutdown().catch((error) => console.error(`MADRE shutdown error: ${error.message}`))), ...closing]);
5091
6049
  // off() also ends the streams of pages watching a conversation held open beside.
5092
6050
  for (const held of parked.values()) held.off();
5093
6051
  parked.clear();
@@ -5114,14 +6072,20 @@ export async function createPulseServer({
5114
6072
  };
5115
6073
  server.on('close', () => quotaMonitor.stop());
5116
6074
  server.on('close', () => clearTimeout(reprobe));
6075
+ server.on('close', () => clearTimeout(ollamaRetry));
5117
6076
  server.on('close', () => { for (const timer of [...aliveTimers, ...hereTimers]) clearTimeout(timer); });
5118
6077
 
5119
6078
  server.on('close', () => { void phone.stop(); });
5120
- return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms };
6079
+ return { server, store, agents, quotaMonitor, markOpen, releaseOpen, phone, salasRoom, closeOtherRooms, currentFicha, afterOpen, bringOthersAlong };
5121
6080
  }
5122
6081
 
5123
- export async function startPulse({ port, projectRoot, openBrowser, openPath = '' }) {
5124
- const { server, agents, markOpen, phone, salasRoom, closeOtherRooms } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources() });
6082
+ export async function startPulse({ port, projectRoot, openBrowser: asked, openPath = '' }) {
6083
+ // A start from an update to the first MADRE with a ficha opens the browser with it (Q-21).
6084
+ const openBrowser = opensBrowser({ asked, hadFicha: Boolean(await readFicha(defaultStateRoot())) });
6085
+ // A new ficha only where a browser can be opened to take it (L-13): over SSH, or on a Linux with no
6086
+ // screen, Home made one nobody received, and the tabs open through a tunnel lost theirs.
6087
+ const canOpen = Boolean(openBrowser) && browserWays(await environmentOnce().catch(() => null)).length > 0;
6088
+ const { server, agents, markOpen, phone, salasRoom, closeOtherRooms, currentFicha, afterOpen, bringOthersAlong } = await createPulseServer({ projectRoot, quotaSources: defaultQuotaSources(), ficha: true, renewFicha: canOpen });
5125
6089
  await new Promise((resolve, reject) => {
5126
6090
  server.once('error', reject);
5127
6091
  server.listen(port, '127.0.0.1', resolve);
@@ -5129,9 +6093,15 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
5129
6093
  const address = server.address();
5130
6094
  // The room is taken from here on, and says so on disk for anyone who tries to open it again.
5131
6095
  await markOpen(address.port);
6096
+ void afterOpen().catch(() => null);
6097
+ // Back from an update: the rest of MADRE comes to this version too (L-13). Not waited for.
6098
+ if (process.env.PULSE_UPDATE_RESTART === '1') void bringOthersAlong().catch(() => null);
5132
6099
  // From here this room offers to host the phone's bridge, when there is a phone to reach it.
5133
6100
  phone.start();
5134
6101
  const url = `http://127.0.0.1:${address.port}`;
6102
+ // The address with the ficha (src/ficha.mjs): the one the browser is opened at and the terminal
6103
+ // shows, so that pasting it into another browser works too.
6104
+ const opening = withFicha(`${url}${openPath}`, await currentFicha());
5135
6105
  // Installed is all this line knows: whether each one is signed in is asked in the room, and
5136
6106
  // «Ready: Codex, Claude…» before any sign-in told a newcomer the opposite (2026-10-19).
5137
6107
  const ready = agents.filter((agent) => agent.ready).map((agent) => agent.label).join(', ') || t('none');
@@ -5139,9 +6109,12 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
5139
6109
  // In the language MADRE speaks (QA 1.1.0, NUE-01): the terminal said «MADRE is ready» above
5140
6110
  // «Abre esta dirección…», and Home was called «Project: …/.pulse/salas», a folder of MADRE's own.
5141
6111
  const where = salasRoom ? t('Home: every project on this computer') : `${t('Project:')} ${projectRoot}`;
5142
- 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` : ''}`);
6112
+ // The key only where a person or the app reads it (L-15): a log gets the address without it.
6113
+ const shown = fichaShown() ? opening : withoutFicha(opening);
6114
+ const keyNote = shown === opening ? '' : ` ${t('The access key is not written here. To open MADRE, run npx @jossuealcala/madre in a terminal on this computer.')}\n`;
6115
+ console.log(`\n${t('MADRE is ready')}\n\n ${shown}\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` : ''}${keyNote}`);
5143
6116
  // Not waited for: the signals below are set up while the browser opens.
5144
- if (openBrowser) void openUrl(`${url}${openPath}`);
6117
+ if (openBrowser) void openUrl(opening);
5145
6118
  // SIGHUP too: closing the Terminal the room was started in is a way of closing it.
5146
6119
  // Home closed this way closes what Turn MADRE off closes (2026-10-21): every open project, also
5147
6120
  // one opened from another project, whose process outlives Home on its own. A second signal while
@@ -5152,6 +6125,16 @@ export async function startPulse({ port, projectRoot, openBrowser, openPath = ''
5152
6125
  server.close(() => process.exit(0));
5153
6126
  });
5154
6127
  }
6128
+ // Inside the app (MADRE.app, Tauri), the app holds this process's stdin open and never writes to it:
6129
+ // when the app dies — Force Quit, a crash — the pipe closes, and Home closes as it does for a signal,
6130
+ // projects first, instead of staying behind with nobody to see it (2026-11-09).
6131
+ if (process.env.MADRE_APP === '1' && salasRoom) {
6132
+ process.stdin.once('end', async () => {
6133
+ await closeOtherRooms().catch(() => null);
6134
+ server.close(() => process.exit(0));
6135
+ });
6136
+ process.stdin.resume();
6137
+ }
5155
6138
  // Salas asked this room to close: the same as a signal.
5156
6139
  server.once('madre:close', () => server.close(() => process.exit(0)));
5157
6140
  // Uninstalling (src/uninstall.mjs): the room closes as it does for a signal — every write done,