@jossuealcala/madre 1.0.5 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/ADDITIONAL-TERMS.md +7 -2
  2. package/CHANGELOG.en.md +47 -1
  3. package/CHANGELOG.md +47 -1
  4. package/CONTRIBUTING.md +2 -2
  5. package/LICENSE +111 -661
  6. package/NOTICE +28 -23
  7. package/README.en.md +30 -101
  8. package/README.md +30 -103
  9. package/SECURITY.md +1 -0
  10. package/TRADEMARKS.en.md +13 -14
  11. package/TRADEMARKS.md +24 -26
  12. package/bin/madre.cjs +2 -2
  13. package/bin/madre.mjs +112 -40
  14. package/docs/REFERENCE.md +52 -5
  15. package/docs/SDK.md +21 -3
  16. package/docs/en/REFERENCE.md +52 -5
  17. package/docs/en/SDK.md +22 -3
  18. package/docs/sdk/hello-module.mjs +3 -0
  19. package/package.json +3 -2
  20. package/public/abduction.js +6 -6
  21. package/public/activity.js +425 -0
  22. package/public/app.js +2468 -435
  23. package/public/assets/abduction-cat-blink.webp +0 -0
  24. package/public/assets/abduction-cat-control-left.webp +0 -0
  25. package/public/assets/abduction-cat-control-right.webp +0 -0
  26. package/public/assets/abduction-cat.webp +0 -0
  27. package/public/assets/manual/shots/en-agents.webp +0 -0
  28. package/public/assets/manual/shots/en-chats.webp +0 -0
  29. package/public/assets/manual/shots/en-code.webp +0 -0
  30. package/public/assets/manual/shots/en-composer.webp +0 -0
  31. package/public/assets/manual/shots/en-connectors.webp +0 -0
  32. package/public/assets/manual/shots/en-continuity.webp +0 -0
  33. package/public/assets/manual/shots/en-coordinator.webp +0 -0
  34. package/public/assets/manual/shots/en-copilot.webp +0 -0
  35. package/public/assets/manual/shots/en-diagnostics.webp +0 -0
  36. package/public/assets/manual/shots/en-home.webp +0 -0
  37. package/public/assets/manual/shots/en-local.webp +0 -0
  38. package/public/assets/manual/shots/en-market.webp +0 -0
  39. package/public/assets/manual/shots/en-memory.webp +0 -0
  40. package/public/assets/manual/shots/en-modes.webp +0 -0
  41. package/public/assets/manual/shots/en-notes.webp +0 -0
  42. package/public/assets/manual/shots/en-settings.webp +0 -0
  43. package/public/assets/manual/shots/en-welcome.webp +0 -0
  44. package/public/assets/manual/shots/en-windows.webp +0 -0
  45. package/public/assets/manual/shots/es-agents.webp +0 -0
  46. package/public/assets/manual/shots/es-chats.webp +0 -0
  47. package/public/assets/manual/shots/es-code.webp +0 -0
  48. package/public/assets/manual/shots/es-composer.webp +0 -0
  49. package/public/assets/manual/shots/es-connectors.webp +0 -0
  50. package/public/assets/manual/shots/es-continuity.webp +0 -0
  51. package/public/assets/manual/shots/es-coordinator.webp +0 -0
  52. package/public/assets/manual/shots/es-copilot.webp +0 -0
  53. package/public/assets/manual/shots/es-diagnostics.webp +0 -0
  54. package/public/assets/manual/shots/es-home.webp +0 -0
  55. package/public/assets/manual/shots/es-local.webp +0 -0
  56. package/public/assets/manual/shots/es-market.webp +0 -0
  57. package/public/assets/manual/shots/es-memory.webp +0 -0
  58. package/public/assets/manual/shots/es-modes.webp +0 -0
  59. package/public/assets/manual/shots/es-notes.webp +0 -0
  60. package/public/assets/manual/shots/es-settings.webp +0 -0
  61. package/public/assets/manual/shots/es-welcome.webp +0 -0
  62. package/public/assets/manual/shots/es-windows.webp +0 -0
  63. package/public/assets/news/1.1/en/chats.webp +0 -0
  64. package/public/assets/news/1.1/en/home.webp +0 -0
  65. package/public/assets/news/1.1/en/maps.webp +0 -0
  66. package/public/assets/news/1.1/en/market.webp +0 -0
  67. package/public/assets/news/1.1/en/permissions.webp +0 -0
  68. package/public/assets/news/1.1/en/privacy.webp +0 -0
  69. package/public/assets/news/1.1/en/welcome.webp +0 -0
  70. package/public/assets/news/1.1/es/chats.webp +0 -0
  71. package/public/assets/news/1.1/es/home.webp +0 -0
  72. package/public/assets/news/1.1/es/maps.webp +0 -0
  73. package/public/assets/news/1.1/es/market.webp +0 -0
  74. package/public/assets/news/1.1/es/permissions.webp +0 -0
  75. package/public/assets/news/1.1/es/privacy.webp +0 -0
  76. package/public/assets/news/1.1/es/welcome.webp +0 -0
  77. package/public/attribution.js +15 -16
  78. package/public/brands.js +2 -2
  79. package/public/code-tools.js +2 -2
  80. package/public/editor.js +13 -13
  81. package/public/en.js +413 -4
  82. package/public/es.js +1345 -483
  83. package/public/hardware.js +2 -2
  84. package/public/i18n.js +2 -2
  85. package/public/icons.js +158 -0
  86. package/public/index.html +66 -48
  87. package/public/inquiry.js +2 -2
  88. package/public/loader.js +271 -2
  89. package/public/macroverso.js +60 -21
  90. package/public/manual-content.js +412 -169
  91. package/public/manual-shots.js +38 -34
  92. package/public/manual.css +20 -2
  93. package/public/manual.html +1 -1
  94. package/public/manual.js +54 -25
  95. package/public/market-art.js +47 -45
  96. package/public/market-view.js +111 -33
  97. package/public/market.js +132 -30
  98. package/public/mcp-catalog.js +2 -2
  99. package/public/neural.js +64 -8
  100. package/public/nostromo-engine.js +709 -40
  101. package/public/page-errors.js +29 -0
  102. package/public/power.js +350 -11
  103. package/public/remedy.js +89 -0
  104. package/public/resay.js +3 -2
  105. package/public/review-ask.js +12 -7
  106. package/public/routing.js +3 -3
  107. package/public/salas-mac.css +703 -24
  108. package/public/salas-mac.html +26 -14
  109. package/public/salas-mac.js +1254 -289
  110. package/public/salas.css +2 -2
  111. package/public/salas.html +3 -3
  112. package/public/salas.js +3 -3
  113. package/public/styles.css +2404 -291
  114. package/public/syntax.js +2 -2
  115. package/public/terms.js +152 -0
  116. package/public/touch.js +2 -2
  117. package/public/tour-chapters.js +10 -10
  118. package/public/tour.js +56 -8
  119. package/public/troubleshooting.js +182 -11
  120. package/public/wallpaper.js +4 -3
  121. package/public/welcome.js +923 -0
  122. package/src/activity.mjs +85 -0
  123. package/src/adapters/claude.mjs +61 -35
  124. package/src/adapters/codex.mjs +18 -5
  125. package/src/adapters/cursor.mjs +5 -3
  126. package/src/adapters/gemini.mjs +5 -3
  127. package/src/adapters/madre.mjs +3 -3
  128. package/src/adapters/opencode.mjs +73 -10
  129. package/src/adapters/process.mjs +14 -13
  130. package/src/adapters/subagents.mjs +159 -0
  131. package/src/asking.mjs +8 -2
  132. package/src/auth-probe.mjs +27 -10
  133. package/src/bridge/devices.mjs +2 -2
  134. package/src/bridge/handoff.mjs +2 -2
  135. package/src/bridge/host.mjs +2 -2
  136. package/src/bridge/network.mjs +2 -2
  137. package/src/bridge/policy.mjs +3 -3
  138. package/src/bridge/qr.mjs +2 -2
  139. package/src/bridge/server.mjs +2 -2
  140. package/src/builtin-updates.mjs +87 -0
  141. package/src/capabilities.mjs +2 -2
  142. package/src/chats.mjs +51 -2
  143. package/src/checkpoint.mjs +67 -9
  144. package/src/choices.mjs +2 -2
  145. package/src/cli-args.mjs +2 -2
  146. package/src/cold.mjs +2 -2
  147. package/src/commands.mjs +2 -2
  148. package/src/config.mjs +2 -2
  149. package/src/conversation-context.mjs +2 -2
  150. package/src/credentials.mjs +56 -16
  151. package/src/dataset.mjs +2 -2
  152. package/src/directives.mjs +2 -2
  153. package/src/distiller.mjs +2 -2
  154. package/src/embeddings.mjs +2 -2
  155. package/src/enlaces.mjs +2 -2
  156. package/src/environment.mjs +147 -0
  157. package/src/event-store.mjs +2 -2
  158. package/src/exam.mjs +2 -2
  159. package/src/extensions.mjs +2 -2
  160. package/src/eyecat-watch.mjs +2 -2
  161. package/src/eyecat.mjs +2 -2
  162. package/src/file-ops.mjs +2 -2
  163. package/src/files.mjs +2 -2
  164. package/src/github.mjs +2 -2
  165. package/src/heartbeat.mjs +2 -2
  166. package/src/history.mjs +2 -2
  167. package/src/i18n.mjs +9 -2
  168. package/src/image-studio.mjs +2 -2
  169. package/src/install-metrics.mjs +109 -0
  170. package/src/json-file.mjs +2 -2
  171. package/src/launch.mjs +2 -2
  172. package/src/lease.mjs +15 -4
  173. package/src/lobby-work.mjs +11 -4
  174. package/src/local-ai.mjs +2 -2
  175. package/src/looks.mjs +2 -2
  176. package/src/market-check.mjs +165 -0
  177. package/src/market-key.mjs +10 -2
  178. package/src/market-license.mjs +4 -4
  179. package/src/market-remote.mjs +54 -12
  180. package/src/maturity.mjs +2 -2
  181. package/src/mcp/connect.mjs +2 -2
  182. package/src/mcp/github-server.mjs +2 -2
  183. package/src/mcp/image-server.mjs +2 -2
  184. package/src/mcp/memory-server.mjs +2 -2
  185. package/src/mcp/proxy.mjs +2 -2
  186. package/src/mcp/smtp-server.mjs +2 -2
  187. package/src/memory-dashboard.mjs +2 -2
  188. package/src/memory-tools.mjs +2 -2
  189. package/src/memory.mjs +2 -2
  190. package/src/models.mjs +33 -3
  191. package/src/module-scope.mjs +2 -2
  192. package/src/modules/ahp.mjs +2 -2
  193. package/src/modules/ash-policy.mjs +2 -2
  194. package/src/modules/ash.mjs +2 -2
  195. package/src/modules/bishop-exam.mjs +2 -2
  196. package/src/modules/bishop-plan.mjs +2 -2
  197. package/src/modules/bishop.mjs +9 -3
  198. package/src/modules/choices.mjs +2 -2
  199. package/src/modules/correo.mjs +2 -2
  200. package/src/modules/enlaces.mjs +2 -2
  201. package/src/modules/git-pulse.mjs +2 -2
  202. package/src/modules/github.mjs +2 -2
  203. package/src/modules/helpers.mjs +2 -2
  204. package/src/modules/image-studio.mjs +2 -2
  205. package/src/modules/index.mjs +90 -5
  206. package/src/modules/intents-calibration.mjs +2 -2
  207. package/src/modules/intents-desk.mjs +4 -3
  208. package/src/modules/intents-observe.mjs +2 -2
  209. package/src/modules/intents-policy.mjs +2 -2
  210. package/src/modules/intents-try.mjs +2 -2
  211. package/src/modules/intents.mjs +2 -2
  212. package/src/modules/local-models.mjs +14 -11
  213. package/src/modules/mcp-connect.mjs +2 -2
  214. package/src/modules/notes.mjs +159 -20
  215. package/src/modules/ollama.mjs +9 -3
  216. package/src/modules/playwright.mjs +2 -2
  217. package/src/modules/reminders.mjs +356 -37
  218. package/src/modules/ripley.mjs +3 -3
  219. package/src/modules/runs.mjs +2 -2
  220. package/src/modules/sdk.mjs +38 -6
  221. package/src/modules/updates.mjs +2 -2
  222. package/src/mother.mjs +2 -2
  223. package/src/npm-launch.mjs +2 -2
  224. package/src/ollama.mjs +6 -4
  225. package/src/opencode-health.mjs +26 -6
  226. package/src/outbound.mjs +10 -2
  227. package/src/override.mjs +27 -22
  228. package/src/ports.mjs +2 -2
  229. package/src/prices.mjs +2 -2
  230. package/src/privacy.mjs +2 -2
  231. package/src/quota-monitor.mjs +2 -2
  232. package/src/quota-sources.mjs +2 -2
  233. package/src/request-guard.mjs +2 -2
  234. package/src/review-ask.mjs +4 -3
  235. package/src/room/archivist.mjs +2 -2
  236. package/src/room/attachments.mjs +2 -2
  237. package/src/room/budget.mjs +2 -2
  238. package/src/room/context.mjs +2 -2
  239. package/src/room/control.mjs +2 -2
  240. package/src/room/copilot.mjs +2 -2
  241. package/src/room/economy.mjs +2 -2
  242. package/src/room/escalation.mjs +2 -2
  243. package/src/room/ghost.mjs +2 -2
  244. package/src/room/guard.mjs +6 -4
  245. package/src/room/prompt.mjs +3 -3
  246. package/src/room/returns.mjs +2 -2
  247. package/src/room/runs.mjs +6 -4
  248. package/src/room/vectors.mjs +2 -2
  249. package/src/room.mjs +127 -31
  250. package/src/router.mjs +2 -2
  251. package/src/runs.mjs +2 -2
  252. package/src/runtime-detection.mjs +31 -5
  253. package/src/salas.mjs +31 -6
  254. package/src/sentinel-errors.mjs +13 -4
  255. package/src/server-sentinel.mjs +2 -2
  256. package/src/server.mjs +689 -80
  257. package/src/setup-trouble.mjs +33 -0
  258. package/src/setup.mjs +4 -4
  259. package/src/smtp.mjs +2 -2
  260. package/src/telemetry.mjs +266 -0
  261. package/src/terms.mjs +43 -0
  262. package/src/tour.mjs +39 -5
  263. package/src/uninstall.mjs +225 -0
  264. package/src/updates.mjs +2 -2
  265. package/src/usage-sentinel.mjs +2 -2
  266. package/src/vault.mjs +2 -2
  267. package/src/verdict.mjs +13 -10
  268. package/src/whats-new.mjs +97 -3
  269. package/public/assets/abduction-cat-blink.png +0 -0
  270. package/public/assets/abduction-cat-control-left.png +0 -0
  271. package/public/assets/abduction-cat-control-right.png +0 -0
  272. package/public/assets/abduction-cat.png +0 -0
  273. package/public/assets/manual/madre-manual-en.pdf +0 -0
  274. package/public/assets/manual/madre-manual-es.pdf +0 -0
  275. package/public/assets/manual/shots/en-modules.webp +0 -0
  276. package/public/assets/manual/shots/es-modules.webp +0 -0
  277. package/src/mcp/notes-server.mjs +0 -120
  278. package/src/reminder-time.mjs +0 -127
@@ -0,0 +1,159 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // WHAT THE SUBAGENTS DID (2026-10-29). Claude, OpenCode and Codex may hand part of a turn to their
4
+ // own subagents from #1 to #3 (src/lease.mjs, subagentsAllowed). Each CLI says so in its own way;
5
+ // these readers turn what it said into one list the room shows the same way for all three: a chip
6
+ // per subagent while the turn runs, and «Helped by N subagents» folded under the answer.
7
+ //
8
+ // One entry: { id, kind, task, status: 'running' | 'done' | 'failed', seconds, reads, searches,
9
+ // changed: [paths], report }. A field the CLI does not say is null, never a guess:
10
+ // · Claude says everything — when each one starts, each tool it uses, when it ends and what it
11
+ // reported (stream-json: task_started, task_progress, task_notification, and the subagent's
12
+ // own tool calls carry its parent_tool_use_id).
13
+ // · OpenCode says each one once, when it ends: its kind, its task, how long and what it reported.
14
+ // · Codex says only that it is waiting on its subagents: no task, no report (exec --json, 0.161).
15
+
16
+ const KIND_LIMIT = 40;
17
+ const TASK_LIMIT = 160;
18
+ const REPORT_LIMIT = 2400;
19
+ const FILES_LIMIT = 20;
20
+ const clip = (text, limit) => {
21
+ const said = String(text ?? '').replace(/\u200b/g, '').replace(/\s+/g, ' ').trim();
22
+ return said.length > limit ? `${said.slice(0, limit - 1)}…` : said || null;
23
+ };
24
+ // A report keeps its lines (it is markdown, shown as markdown); only its length is bounded.
25
+ const clipBlock = (text, limit) => {
26
+ // A report that opens with a zero-width space (OpenCode's) read as «​# Review», not as a heading.
27
+ const said = String(text ?? '').replace(/\u200b/g, '').replace(/\r/g, '').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
28
+ return said.length > limit ? `${said.slice(0, limit - 1).trimEnd()}…` : said || null;
29
+ };
30
+ const relative = (path, root) => {
31
+ const said = String(path ?? '');
32
+ if (!root) return said;
33
+ const base = String(root).replace(/\/+$/, '');
34
+ return said.startsWith(`${base}/`) ? said.slice(base.length + 1) : said;
35
+ };
36
+ // The project's own paths said from the project, as the rest of the room says them.
37
+ const inProject = (text, root) => {
38
+ if (!root || !text) return text;
39
+ const base = String(root).replace(/\/+$/, '');
40
+ return String(text).split(`${base}/`).join('').split(base).join('.');
41
+ };
42
+ const READ_TOOLS = new Set(['Read', 'NotebookRead']);
43
+ const SEARCH_TOOLS = new Set(['Grep', 'Glob', 'LS', 'WebSearch', 'WebFetch']);
44
+ const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
45
+
46
+ // Claude, from its stream (one JSON object per line). `root` makes the changed paths the project's.
47
+ export function claudeSubagents(events, { root = null } = {}) {
48
+ const byTool = new Map();
49
+ const byTask = new Map();
50
+ const of = (toolId) => byTool.get(toolId) ?? null;
51
+ for (const event of events) {
52
+ if (event?.type === 'assistant') {
53
+ for (const part of event.message?.content ?? []) {
54
+ if (part?.type !== 'tool_use') continue;
55
+ if (part.name === 'Agent' || part.name === 'Task') {
56
+ if (byTool.has(part.id)) continue;
57
+ byTool.set(part.id, { id: part.id, kind: clip(part.input?.subagent_type ?? 'general-purpose', KIND_LIMIT), task: clip(part.input?.description ?? part.input?.prompt, TASK_LIMIT), status: 'running', seconds: null, reads: 0, searches: 0, changed: [], report: null, parent: event.parent_tool_use_id ?? null });
58
+ continue;
59
+ }
60
+ const owner = of(event.parent_tool_use_id);
61
+ if (!owner) continue;
62
+ if (READ_TOOLS.has(part.name)) owner.reads += 1;
63
+ else if (SEARCH_TOOLS.has(part.name)) owner.searches += 1;
64
+ else if (WRITE_TOOLS.has(part.name)) {
65
+ const file = relative(part.input?.file_path ?? part.input?.notebook_path, root);
66
+ if (file && !owner.changed.includes(file) && owner.changed.length < FILES_LIMIT) owner.changed.push(file);
67
+ }
68
+ }
69
+ continue;
70
+ }
71
+ if (event?.type !== 'system') continue;
72
+ if (event.subtype === 'task_started' && event.tool_use_id) {
73
+ byTask.set(event.task_id, event.tool_use_id);
74
+ const owner = of(event.tool_use_id);
75
+ if (owner && !owner.task) owner.task = clip(event.description, TASK_LIMIT);
76
+ }
77
+ const owner = of(event.tool_use_id ?? byTask.get(event.task_id));
78
+ if (!owner) continue;
79
+ const ms = Number(event.usage?.duration_ms);
80
+ if (Number.isFinite(ms) && ms > 0) owner.seconds = Math.round(ms / 1000);
81
+ if (event.subtype === 'task_notification' || (event.subtype === 'task_updated' && event.patch?.status)) {
82
+ const status = event.status ?? event.patch?.status;
83
+ if (status) owner.status = status === 'completed' ? 'done' : status === 'running' ? 'running' : 'failed';
84
+ if (event.summary) owner.report = clipBlock(inProject(event.summary, root), REPORT_LIMIT);
85
+ }
86
+ }
87
+ // A subagent of a subagent is still the turn's: listed, after the one that called it.
88
+ return [...byTool.values()].map(({ parent, ...entry }) => entry);
89
+ }
90
+
91
+ // OpenCode, from its --format json events: a `task` tool call, said once it is over.
92
+ export function openCodeSubagents(events, { root = null } = {}) {
93
+ const out = [];
94
+ for (const event of events) {
95
+ const part = event?.part;
96
+ if (event?.type !== 'tool_use' || part?.tool !== 'task') continue;
97
+ const state = part.state ?? {};
98
+ const took = Number(state.time?.end) - Number(state.time?.start);
99
+ const said = String(state.output ?? '').replace(/<\/?task[^>]*>|<\/?task_result>/g, '').trim();
100
+ out.push({
101
+ id: part.callID ?? part.id ?? `task-${out.length}`,
102
+ kind: clip(state.input?.subagent_type ?? 'general', KIND_LIMIT),
103
+ task: clip(state.input?.description ?? state.title ?? state.input?.prompt, TASK_LIMIT),
104
+ status: state.status === 'completed' ? 'done' : state.status === 'error' ? 'failed' : 'running',
105
+ seconds: Number.isFinite(took) && took > 0 ? Math.round(took / 1000) : null,
106
+ reads: null,
107
+ searches: null,
108
+ changed: [],
109
+ report: clipBlock(inProject(state.status === 'error' ? state.error ?? said : said, root), REPORT_LIMIT),
110
+ });
111
+ }
112
+ return out;
113
+ }
114
+
115
+ // Codex, from its exec --json events: its collaboration calls. It names no task and hands back no
116
+ // report, so the room can only say it is working with subagents, and while it waits on them.
117
+ export function codexSubagents(events) {
118
+ const calls = new Map();
119
+ for (const event of events) {
120
+ const item = event?.item;
121
+ if (item?.type !== 'collab_tool_call') continue;
122
+ calls.set(item.id, { tool: item.tool, done: event.type === 'item.completed' || item.status === 'completed', failed: item.status === 'failed', threads: item.receiver_thread_ids ?? [], prompt: item.prompt ?? null });
123
+ }
124
+ if (!calls.size) return [];
125
+ const threads = new Set();
126
+ for (const call of calls.values()) for (const id of call.threads) threads.add(id);
127
+ const running = [...calls.values()].some((call) => !call.done);
128
+ const failed = [...calls.values()].every((call) => call.failed);
129
+ const asked = [...calls.values()].map((call) => call.prompt).find(Boolean) ?? null;
130
+ return [{ id: 'codex-subagents', kind: null, task: clip(asked, TASK_LIMIT), status: running ? 'running' : failed ? 'failed' : 'done', seconds: null, reads: null, searches: null, changed: [], report: null, count: threads.size || null }];
131
+ }
132
+
133
+ // What the room keeps and shows of a list: bounded, and each text through the room's privacy guard.
134
+ export function keptSubagents(list, { redact = (text) => text } = {}) {
135
+ if (!Array.isArray(list) || !list.length) return undefined;
136
+ return list.slice(0, 12).map((one) => ({
137
+ id: String(one.id ?? '').slice(0, 80),
138
+ kind: one.kind ? clip(redact(one.kind), KIND_LIMIT) : null,
139
+ task: one.task ? clip(redact(one.task), TASK_LIMIT) : null,
140
+ status: ['running', 'done', 'failed'].includes(one.status) ? one.status : 'done',
141
+ seconds: Number.isFinite(one.seconds) ? one.seconds : null,
142
+ reads: Number.isFinite(one.reads) ? one.reads : null,
143
+ searches: Number.isFinite(one.searches) ? one.searches : null,
144
+ changed: Array.isArray(one.changed) ? one.changed.slice(0, FILES_LIMIT).map((file) => String(file).slice(0, 200)) : [],
145
+ report: one.report ? clipBlock(redact(one.report), REPORT_LIMIT) : null,
146
+ ...(Number.isFinite(one.count) ? { count: one.count } : {}),
147
+ }));
148
+ }
149
+
150
+ // One JSON object per line; a line that is not one (a CLI's own note) is stepped over.
151
+ export function jsonLines(output) {
152
+ const events = [];
153
+ for (const line of String(output ?? '').split('\n')) {
154
+ const text = line.trim();
155
+ if (!text.startsWith('{')) continue;
156
+ try { events.push(JSON.parse(text)); } catch { /* not an event */ }
157
+ }
158
+ return events;
159
+ }
package/src/asking.mjs CHANGED
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // What the room should ask next.
4
4
  //
5
5
  // The maturity reading says where the archive is thin; it does not say what to do about it on a
@@ -76,6 +76,8 @@ export function questionsFor({ notes = [], cold = new Map(), dismissed = [], lim
76
76
  why: Number(note.recalled ?? 0) > 0
77
77
  ? `the room has carried this open question into ${note.recalled} turn${Number(note.recalled) === 1 ? '' : 's'} and still has no answer`
78
78
  : 'the archivist recorded this as open and nothing has answered it',
79
+ // The why as the page says it, in the person's language (2026-10-28).
80
+ reason: Number(note.recalled ?? 0) > 0 ? { key: 'carried', n: Number(note.recalled) } : { key: 'recorded' },
79
81
  weight: 100 + Number(note.recalled ?? 0),
80
82
  });
81
83
  }
@@ -90,6 +92,8 @@ export function questionsFor({ notes = [], cold = new Map(), dismissed = [], lim
90
92
  memoryId: note.id,
91
93
  text: `Is this still true, and does it still matter here? ${quote(note.text)}`,
92
94
  why: `the archive has been opened ${chill.chances} times since this was written and never once carried it`,
95
+ reason: { key: 'cold', n: chill.chances },
96
+ subject: String(note.text ?? '').replace(/\s+/g, ' ').trim(),
93
97
  weight: 50 + chill.chances,
94
98
  });
95
99
  }
@@ -107,6 +111,8 @@ export function questionsFor({ notes = [], cold = new Map(), dismissed = [], lim
107
111
  memoryId: null,
108
112
  text: KIND_ASK[kind],
109
113
  why: `${count} of ${standing.length} notes are ${KIND_WHY[kind]}`,
114
+ reason: { key: 'thin', count, of: standing.length },
115
+ kind,
110
116
  weight: 40 - count,
111
117
  });
112
118
  }
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  import { execFile } from 'node:child_process';
4
4
  import { t } from './i18n.mjs';
5
5
  import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
@@ -78,9 +78,12 @@ async function run(path, args, timeout = 6000) {
78
78
  const { stdout, stderr } = await execFileAsync(path, args, { timeout, env: { ...process.env, NO_COLOR: '1' } });
79
79
  return { stdout, stderr, code: 0 };
80
80
  } catch (error) {
81
- return { stdout: error.stdout ?? '', stderr: error.stderr ?? error.message, code: error.code ?? 1 };
81
+ // A CLI that did not answer in time is not a CLI without a session (QA 1.1.0, ACT-08): with
82
+ // several projects starting at once `opencode models` took 5 to 22 s and was read as signed out.
83
+ return { stdout: error.stdout ?? '', stderr: error.stderr ?? error.message, code: error.code ?? 1, timedOut: Boolean(error.killed) };
82
84
  }
83
85
  }
86
+ const UNANSWERED = { state: 'unknown', detail: 'no answer in time', timedOut: true };
84
87
 
85
88
  const exists = (path) => access(path).then(() => true, () => false);
86
89
 
@@ -115,6 +118,12 @@ export const AGENT_SETUP = {
115
118
  login: ['login'],
116
119
  loginNote: 'Opens your browser to sign in with ChatGPT.',
117
120
  browser: true,
121
+ // Two doors (2026-10-28): the browser, which comes back to this computer, and a code typed on
122
+ // OpenAI's page from any device — the one that works when MADRE runs on another computer (SSH).
123
+ methods: [
124
+ { id: 'chatgpt', label: 'ChatGPT account', args: ['login'], note: 'Opens your browser to sign in with your ChatGPT account.' },
125
+ { id: 'device', label: 'With a code', args: ['login', '--device-auth'], note: 'Gives you a code to type on OpenAI\'s page, from this or any other device. Use it when MADRE runs on another computer.', room: { deviceCode: true } },
126
+ ],
118
127
  // What a newcomer needs to know before choosing this door: which account, and whether
119
128
  // there is a way in without paying. `paid: null` means it depends on the provider you pick.
120
129
  vendor: 'OpenAI',
@@ -229,7 +238,7 @@ export const AGENT_PACKAGE = {
229
238
  };
230
239
  // One honest line per agent about the account it needs, for the bridge and for Settings › Agents.
231
240
  // Which agents take a pasted key instead of a browser flow.
232
- export const TAKES_KEY = new Set(['claude', 'gemini', 'opencode']);
241
+ export const TAKES_KEY = new Set(['codex', 'claude', 'gemini', 'opencode']);
233
242
 
234
243
  // A CLI that signs in through a page and then waits for the code that page gives back. The room
235
244
  // reads its output for both: the address to open, and the moment it starts waiting.
@@ -239,7 +248,10 @@ export const looksLikeCodePrompt = (line) => CODE_PROMPT.test(String(line ?? '')
239
248
  // The other way round: a device sign-in shows a code to type on the provider's page
240
249
  // ("Enter code: 3475-C193"), and the room has to show it, not ask for one.
241
250
  export const DEVICE_CODE = /enter\s+(?:the\s+|this\s+)?code:?\s+([A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+)/i;
242
- export const deviceCodeIn = (line) => String(line ?? '').match(DEVICE_CODE)?.[1] ?? null;
251
+ // Codex prints its code alone on the line under «Enter this one-time code» (2026-10-28): a line that is
252
+ // nothing but a code counts too. Read only from a sign-in that gives a code to type, never elsewhere.
253
+ const CODE_ALONE = /^\s*([A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+)\s*$/;
254
+ export const deviceCodeIn = (line) => String(line ?? '').match(DEVICE_CODE)?.[1] ?? String(line ?? '').match(CODE_ALONE)?.[1] ?? null;
243
255
 
244
256
  export function accountNoteFor(id) {
245
257
  // Said in the room's language when it is asked for, not when this file is imported.
@@ -355,18 +367,23 @@ export function geminiSignIn({ env = process.env, verifyMs = 30000 } = {}) {
355
367
  export async function probeAgentAuth(agent) {
356
368
  if (agent.id === 'madre') return agent.ready ? { state: 'signed-in', detail: `local · ${agent.version ?? 'Ollama'}` } : { state: 'signed-out', detail: 'Ollama is not running or has no chat model' };
357
369
  if (!agent.detected || !agent.path) return { state: 'not-installed', detail: 'not found on this computer' };
370
+ const answered = (result, read) => (result.timedOut ? UNANSWERED : read(result));
358
371
  switch (agent.id) {
359
- case 'codex': return parseCodexLoginStatus(await run(agent.path, ['login', 'status']));
360
- case 'claude': return parseClaudeAuthStatus(await run(agent.path, ['auth', 'status', '--json']));
372
+ case 'codex': return answered(await run(agent.path, ['login', 'status']), parseCodexLoginStatus);
373
+ case 'claude': return answered(await run(agent.path, ['auth', 'status', '--json']), parseClaudeAuthStatus);
361
374
  case 'opencode': {
362
- const listed = parseOpenCodeAuthList(await run(agent.path, ['auth', 'list']));
375
+ const asked = await run(agent.path, ['auth', 'list']);
376
+ if (asked.timedOut) return UNANSWERED;
377
+ const listed = parseOpenCodeAuthList(asked);
363
378
  if (listed.state === 'signed-in') return listed;
364
379
  // No provider of its own, and still it answers: OpenCode brings free models that need no account
365
380
  // (opencode/big-pickle by default). Called signed out, the one agent a newcomer could use
366
381
  // without signing in anywhere was the one MADRE would not let them write to (2026-10-19).
367
- return openCodeOwnModels(await run(agent.path, ['models', 'opencode'], 15000)) ?? listed;
382
+ const own = await run(agent.path, ['models', 'opencode'], 15000);
383
+ if (own.timedOut) return UNANSWERED;
384
+ return openCodeOwnModels(own) ?? listed;
368
385
  }
369
- case 'cursor': return parseCursorStatus(await run(agent.path, ['status']));
386
+ case 'cursor': return answered(await run(agent.path, ['status']), parseCursorStatus);
370
387
  case 'gemini': return probeGemini();
371
388
  default: return { state: 'unknown', detail: 'no probe for this agent' };
372
389
  }
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // The phones that may reach this Mac, and the networks where they may.
4
4
  //
5
5
  // One file, `~/.pulse/devices.json`, owner-only, shared by every room on this Mac: any of them can
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // Where the person was, on the Mac and on the phone (docs/MOBILE.md, MOV-005).
4
4
  //
5
5
  // One small file for the whole Mac, `~/.pulse/handoff.json`, owner-only: the last place each side
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // Who keeps the bridge up. Every room on this Mac offers to; the port decides.
4
4
  //
5
5
  // No process of its own and nothing to start: each room, every few seconds, asks whether a phone
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // Which network this Mac is on, and how a phone on it reaches the Mac.
4
4
  //
5
5
  // A network is known by its router: the hardware address of the default gateway, hashed. Two
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // What a phone may do in a room (docs/MOBILE.md, section 4).
4
4
  //
5
5
  // A list of what passes, not of what does not: a route the room grows tomorrow stays on the Mac
@@ -17,7 +17,7 @@ import { t } from '../i18n.mjs';
17
17
 
18
18
  // Every file the room's page loads: one missing here and app.js cannot import it, so the whole page
19
19
  // stops on the phone (test/phone-bridge.test.mjs reads app.js's imports to keep this whole).
20
- const STATIC = new Set(['/', '/app.js', '/nostromo-engine.js', '/brands.js', '/troubleshooting.js', '/inquiry.js', '/i18n.js', '/es.js', '/en.js', '/resay.js', '/syntax.js', '/editor.js', '/routing.js', '/abduction.js', '/styles.css', '/review-ask.js', '/loader.js', '/tour.js', '/tour-chapters.js', '/touch.js', '/attribution.js', '/power.js', '/wallpaper.js', '/neural.js', '/hardware.js', '/code-tools.js', '/market.js', '/market-view.js', '/market-art.js', '/mcp-catalog.js']);
20
+ const STATIC = new Set(['/', '/app.js', '/icons.js', '/page-errors.js', '/activity.js', '/terms.js', '/nostromo-engine.js', '/brands.js', '/troubleshooting.js', '/inquiry.js', '/i18n.js', '/es.js', '/en.js', '/resay.js', '/syntax.js', '/editor.js', '/routing.js', '/abduction.js', '/styles.css', '/review-ask.js', '/loader.js', '/tour.js', '/tour-chapters.js', '/touch.js', '/attribution.js', '/power.js', '/wallpaper.js', '/neural.js', '/hardware.js', '/code-tools.js', '/market.js', '/market-view.js', '/market-art.js', '/mcp-catalog.js']);
21
21
 
22
22
  const READ = new Set([
23
23
  '/api/state', '/api/events', '/api/chats', '/api/version', '/api/whats-new', '/api/glance', '/api/handoff',
package/src/bridge/qr.mjs CHANGED
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // The QR a phone scans to pair with this Mac: text in, a grid of dark and light modules out, and
4
4
  // an SVG of that grid the room sizes and colours with CSS.
5
5
  //
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // The bridge: the one thing on this Mac a phone can reach (docs/MOBILE.md, MOV-001).
4
4
  //
5
5
  // Rooms keep listening on 127.0.0.1 and keep refusing anything that does not call them by that
@@ -0,0 +1,87 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // MADRE'S OWN MODULES, KEPT UP TO DATE BY THE MARKET (2026-10-25, R-2 of the 1.1 road map).
4
+ //
5
+ // Notes, Reminders and the rest come with MADRE and work from the first day, without internet. A
6
+ // fix to one of them used to wait for a new MADRE on npm. Now the signed catalog can carry a newer
7
+ // file for it (`builtins`, src/market-remote.mjs), and MADRE runs that one instead of its own.
8
+ //
9
+ // Because such a file reaches every MADRE on its own — nobody chose to install it — it must pass
10
+ // more than a Market module does:
11
+ // · the catalog is signed with the Market's key, as always;
12
+ // · the file is the one the catalog pins (sha256), and
13
+ // · the file itself is signed with the FACTORY key (src/market-key.mjs), a second key kept apart
14
+ // from the Market's: whoever got the Market's key could still not replace Reminders anywhere;
15
+ // · it is written for a contract of the SDK this MADRE understands (`sdk`), says it is the same
16
+ // module, and is newer than the one MADRE came with.
17
+ // It is checked again every time it is loaded (src/modules/index.mjs, adoptBuiltinUpdates), and a
18
+ // file that fails to load leaves MADRE's own in place. A catalog that takes a version back
19
+ // (`revoked`) sends MADRE back to its own. Turning off «Look for new versions» does too.
20
+ //
21
+ // ~/.pulse/market/builtin/<id>.mjs the newer file
22
+ // ~/.pulse/market/builtin/builtin.json what each one is: version, sha256, factory signature
23
+
24
+ import { mkdir, rm } from 'node:fs/promises';
25
+ import { join } from 'node:path';
26
+ import { FACTORY_PUBLIC_KEY } from './market-key.mjs';
27
+ import { bytesFrom, fitsVersion, MAX_MODULE, marketNews, readJson, sha256, verifySigned, writeAtomic } from './market-remote.mjs';
28
+
29
+ export const builtinFolder = (stateRoot) => join(stateRoot, 'market', 'builtin');
30
+ const recordFile = (stateRoot) => join(builtinFolder(stateRoot), 'builtin.json');
31
+ export const builtinFile = (stateRoot, id) => join(builtinFolder(stateRoot), `${id}.mjs`);
32
+ export const readBuiltinRecord = async (stateRoot) => (await readJson(recordFile(stateRoot))) ?? {};
33
+
34
+ // «0.2.0» is newer than «0.1.0»; the same version is not.
35
+ export const newer = (have, than) => fitsVersion(have, than) && !fitsVersion(than, have);
36
+
37
+ // What the catalog offers for MADRE's own modules, fetched and kept when it passes. `packaged` is
38
+ // { id: version } of the modules this MADRE came with; `understands(sdk)` says whether a contract
39
+ // is one this MADRE speaks. Answers what changed: updated (with what the author wrote) and taken back.
40
+ export async function updateBuiltins({ stateRoot, catalog, packaged = {}, understands = () => false, fetchImpl = globalThis.fetch, factoryKey = FACTORY_PUBLIC_KEY, names = {}, now = () => new Date() }) {
41
+ if (!catalog || !factoryKey) return { updated: [], revoked: [] };
42
+ const record = await readBuiltinRecord(stateRoot);
43
+ const updated = [];
44
+ const revoked = [];
45
+ await mkdir(builtinFolder(stateRoot), { recursive: true });
46
+
47
+ for (const [id, have] of Object.entries(record)) {
48
+ const taken = (catalog.revoked ?? []).find((one) => one.id === id && (!one.version || one.version === have.version));
49
+ if (!taken) continue;
50
+ await rm(builtinFile(stateRoot, id), { force: true });
51
+ delete record[id];
52
+ revoked.push({ id, name: names[id] ?? id, kind: 'returned', version: have.version, why: taken.why ?? null, at: now().toISOString() });
53
+ }
54
+
55
+ for (const entry of catalog.builtins ?? []) {
56
+ const mine = packaged[entry.id];
57
+ if (!mine || !understands(entry.sdk) || !newer(entry.version, mine)) continue;
58
+ if ((catalog.revoked ?? []).some((one) => one.id === entry.id && (!one.version || one.version === entry.version))) continue;
59
+ if (record[entry.id]?.sha256 === entry.file.sha256) continue;
60
+ if (record[entry.id] && !newer(entry.version, record[entry.id].version)) continue;
61
+ try {
62
+ const bytes = await bytesFrom(entry.file.url, { fetchImpl, max: MAX_MODULE });
63
+ if (sha256(bytes) !== entry.file.sha256) continue;
64
+ if (!verifySigned(bytes, entry.file.factory, factoryKey)) continue;
65
+ await writeAtomic(builtinFile(stateRoot, entry.id), bytes);
66
+ const from = record[entry.id]?.version ?? mine;
67
+ record[entry.id] = { version: entry.version, sdk: entry.sdk, sha256: entry.file.sha256, factory: entry.file.factory, at: now().toISOString() };
68
+ updated.push({ id: entry.id, name: names[entry.id] ?? entry.id, from, to: entry.version, changes: entry.changes ?? null, at: now().toISOString() });
69
+ } catch { /* tried again the next time MADRE opens */ }
70
+ }
71
+
72
+ if (updated.length || revoked.length) {
73
+ await writeAtomic(recordFile(stateRoot), JSON.stringify(record, null, 2));
74
+ // Said once, the way a Market module's update is (market/updates.json): what came, and what
75
+ // went back to the one MADRE came with, and why.
76
+ const told = [...updated, ...revoked];
77
+ const news = [...(await marketNews(stateRoot)).filter((one) => !told.some((fresh) => fresh.id === one.id)), ...told];
78
+ await writeAtomic(join(stateRoot, 'market', 'updates.json'), JSON.stringify(news, null, 2));
79
+ }
80
+ return { updated, revoked };
81
+ }
82
+
83
+ // The file kept for one of MADRE's own modules, if it is still the one that was signed: its bytes
84
+ // against the sha256 and the factory signature recorded when it came. Anything else is not run.
85
+ export function trustedBytes(bytes, kept, factoryKey = FACTORY_PUBLIC_KEY) {
86
+ return Boolean(bytes && kept && factoryKey && sha256(bytes) === kept.sha256 && verifySigned(bytes, kept.factory, factoryKey));
87
+ }
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // What each CLI can do from MADRE, verified against the installed versions on
4
4
  // 2026-09-16 (Codex 0.153, Claude Code 2.1, Gemini CLI 0.60, OpenCode 1.18).
5
5
  // The room shows this so a human knows whom to ask for what, and an
package/src/chats.mjs CHANGED
@@ -1,5 +1,5 @@
1
- // SPDX-License-Identifier: AGPL-3.0-only
2
- // MADRE · © 2026 Jossue Alcalá · GNU AGPL v3 with additional terms (Section 7): ADDITIONAL-TERMS.md
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
3
  // A project has one memory and many conversations.
4
4
  //
5
5
  // The archive, the crew, the modules and the privacy list belong to the project: they are what
@@ -230,3 +230,52 @@ export async function projectFloor(roomDir, { except = null } = {}) {
230
230
  }
231
231
  return floor;
232
232
  }
233
+
234
+ // SEARCH (2026-10-30): the conversations of a project, by their name and by what was said in them,
235
+ // without regard to accents or capitals, so «envio» finds «Envío». Each record is read from its
236
+ // end, a few megabytes at most: what a person looks for is almost always recent.
237
+ const SEARCH_READ = 4 * 1024 * 1024;
238
+ export const searchWords = (text) => String(text ?? '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
239
+ // The end of one record, `bytes` at most, from a whole line on (also «En marcha», src/activity.mjs).
240
+ export async function tailOf(file, bytes = SEARCH_READ) {
241
+ const found = await stat(file).catch(() => null);
242
+ if (!found?.isFile()) return '';
243
+ const start = Math.max(0, found.size - bytes);
244
+ const handle = await open(file, 'r');
245
+ try {
246
+ const buffer = Buffer.alloc(found.size - start);
247
+ await handle.read(buffer, 0, buffer.length, start);
248
+ const text = buffer.toString('utf8');
249
+ return start ? text.slice(text.indexOf('\n') + 1) : text;
250
+ } finally { await handle.close(); }
251
+ }
252
+ function snippetAround(text, at, length) {
253
+ const from = Math.max(0, at - 50);
254
+ const to = Math.min(text.length, at + length + 90);
255
+ return { text: `${from ? '…' : ''}${text.slice(from, to).replace(/\s+/g, ' ')}${to < text.length ? '…' : ''}`, mark: [at - from + (from ? 1 : 0), length] };
256
+ }
257
+ export async function searchChats(roomDir, query, { limit = 40, perChat = 3 } = {}) {
258
+ const wanted = searchWords(query).trim();
259
+ if (wanted.length < 2) return { query: String(query ?? ''), results: [] };
260
+ const { chats } = await listChats(roomDir);
261
+ const results = [];
262
+ for (const chat of chats) {
263
+ const hits = [];
264
+ const titleAt = searchWords(chat.title).indexOf(wanted);
265
+ for (const line of (await tailOf(chatLedger(roomDir, chat.id))).split('\n').reverse()) {
266
+ if (hits.length >= perChat) break;
267
+ if (!line.includes('"message.created"')) continue;
268
+ let event;
269
+ try { event = JSON.parse(line); } catch { continue; }
270
+ const payload = event?.payload ?? {};
271
+ const said = typeof payload.text === 'string' ? payload.text : '';
272
+ const at = searchWords(said).indexOf(wanted);
273
+ if (at < 0) continue;
274
+ hits.push({ messageId: payload.messageId ?? null, sequence: event.sequence ?? null, who: payload.role === 'user' ? 'you' : String(payload.sender ?? ''), at: event.timestamp ?? null, ...snippetAround(said, at, wanted.length) });
275
+ }
276
+ if (titleAt < 0 && !hits.length) continue;
277
+ results.push({ id: chat.id, title: chat.title, updatedAt: chat.updatedAt ?? null, titleMatch: titleAt >= 0, hits });
278
+ if (results.length >= limit) break;
279
+ }
280
+ return { query: String(query ?? ''), results };
281
+ }