@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/skills.mjs ADDED
@@ -0,0 +1,502 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // SKILLS (2026-11-08, H-1 of docs/private/HABILIDADES-MERCADO.md). A skill is a way of working that
4
+ // MADRE hands to whichever agent answers. A module adds buttons and pages and runs on this computer;
5
+ // a skill only tells an agent how to do something — and because MADRE is the one that writes the
6
+ // prompt (src/room/prompt.mjs), the same skill works on all six agents. A skill of Claude's works
7
+ // only in Claude; Codex has its own prompts, Gemini its commands, OpenCode its agents. MADRE already
8
+ // keeps every one of those out of a turn on purpose (--setting-sources '' and no Skill tool for
9
+ // Claude, --pure for OpenCode, --ephemeral for Codex, SKILLS_ENABLED=false for Grok), so what a
10
+ // person already had never reached the room. This is the hole that fills.
11
+ //
12
+ // <folder>/<id>/HABILIDAD.md its header and its instructions. SKILL.md is read the same way, so
13
+ // a skill a person already has is imported without being rewritten.
14
+ // <folder>/<id>/referencias/ what the agent reads when it needs it: templates, examples, data.
15
+ // <folder>/<id>/guiones/ what an agent MAY RUN, and only at #4.
16
+ //
17
+ // Two folders, the same two a module has: ~/.pulse/habilidades (every project) and
18
+ // <project>/.madre/habilidades (this one). Agents never write in either — .madre/ is a forbidden
19
+ // zone and ~/.pulse lives outside every project — so a skill is proposed by an agent and installed
20
+ // by the person, like a module.
21
+ //
22
+ // WHAT CONTAINS A SKILL. The body travels in the prompt, so it is capped: what does not fit goes in
23
+ // referencias/ and the agent reads it when it needs it, which is how skills work everywhere. A
24
+ // script is never run by MADRE: an agent runs it, with the permission of its turn, so below #4 no
25
+ // agent can run anything at all and every script is inert on its own. Nothing is read from outside
26
+ // the skill's own folder: no symlinks, no paths that climb out, no hidden files.
27
+
28
+ import { lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
29
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
30
+ import { fileURLToPath } from 'node:url';
31
+ import { t } from './i18n.mjs';
32
+
33
+ export const SKILL_FILES = ['HABILIDAD.md', 'SKILL.md'];
34
+ // A file an agent wrote that means «install me as a skill»: <id>.habilidad.md, as a module's own is
35
+ // <id>.module.mjs (src/modules/index.mjs). The agent writes it in its draft folder and cannot
36
+ // install it: the person does, from the room.
37
+ export const isSkillFile = (path) => /\.habilidad\.md$/i.test(String(path ?? ''));
38
+ export const skillIdOf = (path) => String(path ?? '').split(/[\\/]/).pop().replace(/\.habilidad\.md$/i, '');
39
+ // Where the guide an agent writing a skill is pointed at lives in this installation.
40
+ export const skillGuide = () => fileURLToPath(new URL('../docs/HABILIDADES.md', import.meta.url));
41
+ export const ID = /^[a-z][a-z0-9-]{1,39}$/;
42
+ const SEMVER = /^\d+\.\d+\.\d+$/;
43
+ // The body is in every turn this skill enters, so it is the one thing with a tight cap: about two
44
+ // thousand tokens. A skill with more to say puts it in referencias/ and points at it.
45
+ export const MAX_BODY = 8000;
46
+ // `when` never travels in the prompt — only the body does — so its only cost is the matching, and a
47
+ // truncated trigger loses exactly the half that matters: the «and NOT when…» at the end. Measured
48
+ // against the skills on a real computer (H-7, 2026-11-08), where Claude's run to about 900.
49
+ export const MAX_WHEN = 1000;
50
+ export const MAX_NAME = 60;
51
+ // What a skill may weigh ON THIS DISK, which is a different question from what may travel through
52
+ // the Market (src/market-remote.mjs keeps its own, tighter bound: one signed download each). The
53
+ // real ones measured on 2026-11-08 reach 61 files and 1158 KB — Claude's xlsx, pptx and docx carry
54
+ // their own libraries — and refusing those on a number nobody had measured would have been a guess
55
+ // dressed as a rule.
56
+ export const MAX_FILES = 200;
57
+ export const MAX_BYTES = 4 * 1024 * 1024;
58
+ // And what may be SENT to the Market: there each file is a download of its own, signed and pinned.
59
+ export const MARKET_MAX_FILES = 40;
60
+ // What an agent could run, and therefore what only #4 could ever reach. Read from the name, and
61
+ // from the executable bit for anything else.
62
+ const RUNNABLE = /\.(?:sh|bash|zsh|py|rb|pl|mjs|cjs|js|ts)$/i;
63
+ // Read from the name alone, for a file that is not on this disk yet (the Market's, H-4). On disk the
64
+ // executable bit counts too (readSkillFiles).
65
+ export const runnable = (path) => RUNNABLE.test(String(path ?? ''));
66
+
67
+ // Whether a skill may carry a file at this path. The paths come from outside MADRE — a file the
68
+ // person dropped in, an entry of the Market's catalog — so they are checked before anything is
69
+ // written: nothing climbs out, nothing is absolute, nothing hides.
70
+ export const safePath = (path) => {
71
+ const said = String(path ?? '');
72
+ if (!said || said.length > 200 || said.startsWith('/') || said.startsWith('\\')) return false;
73
+ if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(said)) return false;
74
+ return said.split(/[\\/]/).every((part) => part && !part.startsWith('.'));
75
+ };
76
+
77
+ // Three folders, read in this order so the later one wins: the skills that come with MADRE (1.1.4,
78
+ // D-H8: for whoever is starting out with AI), every project's, and this project's. MADRE's own are
79
+ // never written or removed from here: a person turns one off, or keeps a copy of their own with
80
+ // the same id, which stands in for it.
81
+ // PULSE_MADRE_SKILLS points elsewhere (the suite points it at nothing, test/setup.mjs).
82
+ export const MADRE_SKILLS = fileURLToPath(new URL('../habilidades', import.meta.url));
83
+ export const skillFolders = ({ stateRoot, projectRoot }) => ({
84
+ madre: process.env.PULSE_MADRE_SKILLS || MADRE_SKILLS,
85
+ user: join(stateRoot, 'habilidades'),
86
+ project: join(projectRoot, '.madre', 'habilidades'),
87
+ });
88
+
89
+ // The header between the first two «---» lines, one «key: value» per line, as a skill of Claude's
90
+ // has it and as madre-logs has it. A value may be plain, quoted, or the two languages at once:
91
+ // `name: { es: "Cotizaciones", en: "Quotes" }`.
92
+ export function readHeader(text) {
93
+ const match = String(text ?? '').match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
94
+ if (!match) return null;
95
+ const fields = {};
96
+ for (const line of match[1].split(/\r?\n/)) {
97
+ const at = line.indexOf(':');
98
+ if (at <= 0 || /^\s/.test(line)) continue;
99
+ fields[line.slice(0, at).trim()] = line.slice(at + 1).trim();
100
+ }
101
+ return fields;
102
+ }
103
+ export const bodyOf = (text) => String(text ?? '').replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '').trim();
104
+
105
+ const unquote = (value) => String(value ?? '').trim().replace(/^(["'])([\s\S]*)\1$/, '$2').trim();
106
+ // One word or the two languages. `{ es: "…", en: "…" }` is read without a YAML reader: a header is
107
+ // one line per field and this is the only shape of value that is not plain text.
108
+ export function words(value, max) {
109
+ const said = String(value ?? '').trim();
110
+ if (!said) return null;
111
+ if (said.startsWith('{')) {
112
+ const out = {};
113
+ for (const lang of ['es', 'en']) {
114
+ const hit = said.match(new RegExp(`\\b${lang}\\s*:\\s*(?:"([^"]*)"|'([^']*)'|([^,}]*))`));
115
+ const one = unquote(hit?.[1] ?? hit?.[2] ?? hit?.[3] ?? '');
116
+ if (one) out[lang] = one.slice(0, max);
117
+ }
118
+ return Object.keys(out).length ? out : null;
119
+ }
120
+ return unquote(said).slice(0, max) || null;
121
+ }
122
+ // Who made it: a name, or `{ name: "Ana Ruiz", github: "anaruiz" }`. The name is what the Market
123
+ // shows; the GitHub user is only how a pull request is signed, so it is read and never demanded.
124
+ export function author(value) {
125
+ const said = unquote(value ?? '');
126
+ if (!said) return null;
127
+ if (!said.startsWith('{')) return { name: said.slice(0, MAX_NAME), github: null };
128
+ const of = (key) => {
129
+ const hit = said.match(new RegExp(`\\b${key}\\s*:\\s*(?:"([^"]*)"|'([^']*)'|([^,}]*))`));
130
+ return unquote(hit?.[1] ?? hit?.[2] ?? hit?.[3] ?? '') || null;
131
+ };
132
+ const name = of('name') ?? of('nombre');
133
+ return name ? { name: name.slice(0, MAX_NAME), github: of('github') } : null;
134
+ }
135
+
136
+ // Whichever language the room speaks, for a name that may be one word or two.
137
+ export const pick = (value, language = 'es') => (value && typeof value === 'object' ? value[language] ?? value.es ?? value.en ?? null : value ?? null);
138
+
139
+ // WHAT A SKILL DECLARES. English keys, as a module's contract has them, with the Spanish ones a
140
+ // person writing by hand will reach for, and the ones a skill of Claude's already carries:
141
+ // `description` is its `when`. MADRE's own words are in English and the room speaks the person's
142
+ // language (src/i18n.mjs), here as everywhere.
143
+ // The last four are only needed to PUBLISH one (src/skill-check.mjs, H-5): what the Market shows.
144
+ // A skill is one file, so they live in its own header — asking for a second file with the same
145
+ // facts in JSON is work for whoever sends it and one more place for the two to disagree.
146
+ const KEYS = {
147
+ id: ['id'], name: ['name', 'nombre'], when: ['when', 'cuando', 'description'],
148
+ version: ['version', 'versión'], minMadre: ['minMadre', 'minmadre'],
149
+ credit: ['credit', 'credito', 'crédito'], license: ['license', 'licencia'],
150
+ line: ['line', 'linea', 'línea'], summary: ['summary', 'resumen'], shelf: ['shelf', 'estante'],
151
+ author: ['author', 'autor', 'autora'],
152
+ // Its drawing on the shelf of skills: the name of one of MADRE's Trazo icons (public/icons.js).
153
+ icon: ['icon', 'icono', 'ícono'],
154
+ };
155
+ export const KNOWN = new Set(Object.values(KEYS).flat());
156
+ const field = (fields, key) => KEYS[key].map((name) => fields[name]).find((value) => String(value ?? '').trim());
157
+
158
+ // One skill read from its text, with what is wrong said in words the person can act on. The id is
159
+ // the folder's name when the header does not say one, so importing a skill of Claude's — which
160
+ // names no id — works as it is.
161
+ export function readSkillText(text, { id = null } = {}) {
162
+ const fields = readHeader(text);
163
+ if (!fields) throw new Error(t('A skill starts with its header between two «---» lines: id, name and when it is for.'));
164
+ const said = unquote(field(fields, 'id') ?? '') || String(id ?? '');
165
+ if (!ID.test(said)) throw new Error(t('«{id}» is not a name MADRE can use for a skill: lowercase letters, numbers and dashes, 2 to 40, starting with a letter.', { id: said || '—' }));
166
+ const body = bodyOf(text);
167
+ if (!body) throw new Error(t('The skill says nothing: under the header go the instructions the agents will read.'));
168
+ if (body.length > MAX_BODY) throw new Error(t('The skill is too long ({has} characters, at most {max}). What does not fit goes in referencias/, and the instructions point at it: the agent reads it when it needs it.', { has: body.length, max: MAX_BODY }));
169
+ const version = unquote(field(fields, 'version') ?? '');
170
+ if (version && !SEMVER.test(version)) throw new Error(t('version: like 1.0.0.'));
171
+ const minMadre = unquote(field(fields, 'minMadre') ?? '');
172
+ if (minMadre && !SEMVER.test(minMadre)) throw new Error(t('minMadre: the oldest MADRE it works with, like 1.1.0.'));
173
+ return {
174
+ id: said,
175
+ name: words(field(fields, 'name'), MAX_NAME) ?? said,
176
+ // Without it, the skill only ever enters a turn because the person turned it on.
177
+ when: words(field(fields, 'when'), MAX_WHEN),
178
+ version: version || null,
179
+ minMadre: minMadre || null,
180
+ credit: words(field(fields, 'credit'), MAX_NAME),
181
+ license: unquote(field(fields, 'license') ?? '') || null,
182
+ // Only for the Market, and only when it is going there (H-5).
183
+ line: words(field(fields, 'line'), 140),
184
+ summary: words(field(fields, 'summary'), 1200),
185
+ shelf: unquote(field(fields, 'shelf') ?? '') || null,
186
+ icon: /^[a-z][a-z0-9-]{1,30}$/.test(unquote(field(fields, 'icon') ?? '')) ? unquote(field(fields, 'icon')) : null,
187
+ author: author(field(fields, 'author')),
188
+ body,
189
+ // Said, never ignored in silence, as a module's unknown fields are said when it is installed.
190
+ unknown: Object.keys(fields).filter((key) => !KNOWN.has(key)),
191
+ };
192
+ }
193
+
194
+ // EVERY FILE OF A SKILL, and nothing else. A link is not followed and a file that is not under the
195
+ // skill's own folder is not read: a skill travels, and what travels names its own paths.
196
+ export async function readSkillFiles(dir, { maxFiles = MAX_FILES, maxBytes = MAX_BYTES } = {}) {
197
+ const root = resolve(dir);
198
+ const files = [];
199
+ let bytes = 0;
200
+ const walk = async (at) => {
201
+ for (const entry of (await readdir(at, { withFileTypes: true }).catch(() => []))) {
202
+ if (entry.name.startsWith('.')) continue;
203
+ const path = join(at, entry.name);
204
+ const info = await lstat(path).catch(() => null);
205
+ if (!info) continue;
206
+ if (info.isSymbolicLink()) throw new Error(t('{file} is a link, and a skill carries only its own files.', { file: relative(root, path) }));
207
+ const inside = resolve(path);
208
+ if (inside !== root && !inside.startsWith(root + sep)) throw new Error(t('{file} is outside the skill\'s folder.', { file: entry.name }));
209
+ if (info.isDirectory()) { await walk(path); continue; }
210
+ if (!info.isFile()) continue;
211
+ files.push({ path: relative(root, path), bytes: info.size, runs: RUNNABLE.test(entry.name) || Boolean(info.mode & 0o111) });
212
+ bytes += info.size;
213
+ if (files.length > maxFiles) throw new Error(t('A skill carries at most {max} files.', { max: maxFiles }));
214
+ if (bytes > maxBytes) throw new Error(t('A skill weighs at most {max} KB.', { max: Math.round(maxBytes / 1024) }));
215
+ }
216
+ };
217
+ await walk(root);
218
+ return { files: files.sort((a, b) => a.path.localeCompare(b.path)), bytes };
219
+ }
220
+
221
+ // One skill from a folder on this computer: its text, its files, and the scripts an agent could only
222
+ // ever run at #4. Nothing is run here, and nothing is installed: asking what a folder is must not
223
+ // change anything.
224
+ export async function readSkill(dir, { origin = null } = {}) {
225
+ const root = resolve(dir);
226
+ let text = null;
227
+ let from = null;
228
+ for (const candidate of SKILL_FILES) {
229
+ text = await readFile(join(root, candidate), 'utf8').catch(() => null);
230
+ if (text !== null) { from = candidate; break; }
231
+ }
232
+ if (text === null) throw new Error(t('{folder} has no {file}.', { folder: basename(root), file: SKILL_FILES[0] }));
233
+ const skill = readSkillText(text, { id: basename(root) });
234
+ const { files, bytes } = await readSkillFiles(root);
235
+ return { ...skill, dir: root, file: join(root, from), origin, files, bytes, scripts: files.filter((one) => one.runs).map((one) => one.path) };
236
+ }
237
+
238
+ // WHAT A SKILL SAYS IT DOES, for the person to read before accepting it (H-3). Only what is there:
239
+ // when it says it is for, how long what it tells the agents is, what it carries, and every script —
240
+ // because a script is the one thing that could ever run, and only at #4.
241
+ export const declaredBy = (skill) => ({
242
+ when: skill.when ?? null,
243
+ chars: skill.body.length,
244
+ files: skill.files.length,
245
+ references: skill.files.filter((one) => !one.runs).map((one) => one.path),
246
+ scripts: skill.scripts,
247
+ credit: skill.credit ?? null,
248
+ license: skill.license ?? null,
249
+ });
250
+
251
+ // Every skill of both folders, newest reading each time. One that cannot be read is left out with
252
+ // why, as a module that fails to load is: a bad skill never keeps the others out of the room.
253
+ export async function loadSkills({ stateRoot, projectRoot }) {
254
+ const folders = skillFolders({ stateRoot, projectRoot });
255
+ const loaded = [];
256
+ const failures = [];
257
+ for (const [origin, dir] of Object.entries(folders)) {
258
+ for (const entry of (await readdir(dir, { withFileTypes: true }).catch(() => []))) {
259
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
260
+ const at = join(dir, entry.name);
261
+ try {
262
+ const skill = await readSkill(at, { origin });
263
+ // A skill of this project stands in for one of the same name from every project, the way
264
+ // installing a newer copy of a module replaces it.
265
+ const already = loaded.findIndex((one) => one.id === skill.id);
266
+ if (already >= 0) loaded[already] = skill; else loaded.push(skill);
267
+ } catch (error) {
268
+ failures.push({ dir: at, origin, error: error.message });
269
+ }
270
+ }
271
+ }
272
+ return { loaded: loaded.sort((a, b) => a.id.localeCompare(b.id)), failures, folders };
273
+ }
274
+
275
+ // INSTALLING ONE. The files are checked before a single one is written, and written to a folder of
276
+ // the skill's own name: a skill is never spread over the folder of another. `files` is what the
277
+ // person accepted — its text and whatever came with it — each path relative to the skill's folder.
278
+ export async function installSkill({ files, scope = 'user', stateRoot, projectRoot, source = null }) {
279
+ const main = files.find((one) => SKILL_FILES.includes(one.path));
280
+ if (!main) throw new Error(t('A skill needs its {file}.', { file: SKILL_FILES[0] }));
281
+ const folders = skillFolders({ stateRoot, projectRoot });
282
+ const dir = folders[scope === 'project' ? 'project' : 'user'];
283
+ const skill = readSkillText(main.text ?? main.content ?? '', { id: source?.id ?? null });
284
+ if (files.length > MAX_FILES) throw new Error(t('A skill carries at most {max} files.', { max: MAX_FILES }));
285
+ const safe = [];
286
+ let bytes = 0;
287
+ for (const one of files) {
288
+ const path = String(one.path ?? '');
289
+ if (!safePath(path)) throw new Error(t('{file} is not a path a skill may carry.', { file: path || '—' }));
290
+ const text = one.text ?? one.content ?? '';
291
+ const data = Buffer.isBuffer(text) ? text : Buffer.from(String(text), 'utf8');
292
+ bytes += data.length;
293
+ if (bytes > MAX_BYTES) throw new Error(t('A skill weighs at most {max} KB.', { max: Math.round(MAX_BYTES / 1024) }));
294
+ safe.push({ path, data });
295
+ }
296
+ // Written beside it and moved into place at the end: a write that fails halfway must not leave
297
+ // the person without the skill they had.
298
+ const target = join(dir, skill.id);
299
+ const fresh = `${target}.nuevo`;
300
+ await rm(fresh, { recursive: true, force: true }).catch(() => {});
301
+ try {
302
+ for (const one of safe) {
303
+ await mkdir(dirname(join(fresh, one.path)), { recursive: true });
304
+ await writeFile(join(fresh, one.path), one.data);
305
+ }
306
+ if (source) await writeFile(join(fresh, 'origen.json'), `${JSON.stringify({ ...source, at: new Date().toISOString(), version: skill.version ?? null }, null, 2)}\n`);
307
+ await rm(target, { recursive: true, force: true }).catch(() => {});
308
+ await rename(fresh, target);
309
+ } catch (error) {
310
+ await rm(fresh, { recursive: true, force: true }).catch(() => {});
311
+ throw error;
312
+ }
313
+ return { ...(await readSkill(target, { origin: scope === 'project' ? 'project' : 'user' })), installed: true };
314
+ }
315
+
316
+ // Removing one is the person's, as removing a module is: the folder goes, and nothing a skill's
317
+ // scripts may have written elsewhere is touched.
318
+ export async function removeSkill({ id, stateRoot, projectRoot }) {
319
+ if (!ID.test(String(id ?? ''))) throw new Error(t('No skill «{id}».', { id }));
320
+ const folders = skillFolders({ stateRoot, projectRoot });
321
+ const removed = [];
322
+ for (const dir of [folders.project, folders.user]) {
323
+ const target = join(dir, id);
324
+ if (!(await lstat(target).catch(() => null))?.isDirectory()) continue;
325
+ await rm(target, { recursive: true, force: true });
326
+ removed.push(target);
327
+ }
328
+ if (!removed.length) throw new Error(t('No skill «{id}».', { id }));
329
+ return { id, removed };
330
+ }
331
+
332
+ // ---- WHICH SKILLS A TURN GETS (H-2). Two ways, and the person decides which per skill:
333
+ //
334
+ // always the person turned it on here, so it is in every turn of this project.
335
+ // match the default: it enters when what was asked looks like what its `when` describes.
336
+ // off it is kept, and it enters nothing.
337
+ //
338
+ // MATCHED BY WORDS, not by meaning. A word match is free, works with no internet and no model, is
339
+ // the same every time, and — this is what decided it — it can be SHOWN: the room can say «this
340
+ // entered because you said “cotización”», which a number from an embedder cannot. A meaning pass
341
+ // is worth having on top, and it waits for a cutoff measured against real use rather than guessed
342
+ // (the recall's cut was measured; this one would not be). `nearness` is where it will plug in.
343
+ //
344
+ // Every skill's own words count against one budget, so however many match, a turn pays about what
345
+ // one skill costs and never more. The person's own «always» are seated first: their word before
346
+ // MADRE's guess.
347
+
348
+ // Words that say nothing about which skill is wanted. The ones almost every `when` carries are in
349
+ // here on purpose: without them, «cuando el usuario pide algo» would match every message.
350
+ const STOP = new Set(`
351
+ a acerca al algo alguien algun alguna alguno ante antes aqui asi aun cada como con contra cual
352
+ cuando cuanto de del desde donde dos el ella ellas ellos en entre era eran eres es esa ese eso
353
+ esta estan este esto estos favor hace hacer hacia hasta hay las les lo los mas mientras muy nada
354
+ ni nos nuestra nuestro para pero pide piden pides poco por porque pues que quien quiere quieren
355
+ quieres saber se sea segun ser si sin sobre solo son su sus tal tambien tiene tienen todo todos
356
+ tras una uno unos usa usar usuario ver vez vos
357
+ about after all almost already also always and any anyone anything are ask asked asking asks
358
+ because been before being between both but can cannot does doing done down each else even every
359
+ everything first for from gets getting give given goes going has have having her him his how
360
+ however into its just like made make makes making many may more most much must need needs never
361
+ not now off once one only onto other our out over own same she should since some something such
362
+ than that the their them then there these they this those through thus too under until use used
363
+ user users uses using very wants want was were what when where which while who whom why will with
364
+ within without would you your
365
+ `.trim().split(/\s+/));
366
+ const NO_MARKS = /\p{M}/gu;
367
+ export const MIN_WORD = 4;
368
+ // How many skills one turn may carry, before the budget has anything to say. Three is already more
369
+ // than a person keeps in their head about one request.
370
+ export const MAX_PER_TURN = 3;
371
+
372
+ // The words of a sentence that could tell one skill from another: no accents, no punctuation, no
373
+ // words everybody uses. Short ones are dropped, with two exceptions that carry a whole request on
374
+ // their own: anything with a digit in it («1099», «#4») and a word written in capitals, which is
375
+ // how a person writes the acronym their work turns on — IVA, SAT, RFC, PDF, SEO, API.
376
+ export function keywords(text) {
377
+ const out = new Set();
378
+ for (const raw of String(text ?? '').split(/[^\p{L}\p{N}_-]+/u)) {
379
+ if (!raw) continue;
380
+ const word = raw.normalize('NFD').replace(NO_MARKS, '').toLowerCase();
381
+ if (!word || STOP.has(word)) continue;
382
+ if (word.length >= MIN_WORD || /\d/.test(word) || (word.length >= 3 && raw === raw.toUpperCase())) out.add(word);
383
+ }
384
+ return out;
385
+ }
386
+
387
+ // Only the words that are words, as a module's switch keeps only the booleans (module-scope.mjs).
388
+ export const roomsIn = (block = {}) => Object.fromEntries(Object.entries(block?.rooms ?? {}).filter(([id, said]) => /^[\w.:-]{1,200}$/.test(id) && SKILL_STATES.includes(said)));
389
+
390
+ // The block written when a skill's switch moves. From Home, with no project, it is the word for
391
+ // every project and each project follows it again; from a project, that project's own word, which
392
+ // wins. The whole block, because updateConfig merges one level down.
393
+ export function skillStateIn(block = {}, roomId = null, state) {
394
+ if (!SKILL_STATES.includes(state)) throw new Error(t('A skill is off, matched or always on; nothing else.'));
395
+ if (!roomId) return { ...block, state, rooms: {} };
396
+ return { ...block, rooms: { ...roomsIn(block), [roomId]: state } };
397
+ }
398
+
399
+ // What the person said about this skill, in this project. The shape is the one a module's switch
400
+ // has (src/module-scope.mjs): a word for every project, and a project's own word that wins.
401
+ export const SKILL_STATES = ['off', 'match', 'always'];
402
+ export function skillState(config = {}, id = null, roomId = null) {
403
+ const block = config?.skills?.[id] ?? {};
404
+ const own = roomId ? block?.rooms?.[roomId] : null;
405
+ return SKILL_STATES.includes(own) ? own : SKILL_STATES.includes(block?.state) ? block.state : 'match';
406
+ }
407
+
408
+ // The skills this turn carries, in the order they will be read, each with why it is here.
409
+ // `nearness(skill, text)` is the meaning pass when there is one: a number from 0 to 1, consulted
410
+ // only for a skill no word matched, and only above `near`.
411
+ export function chooseSkills({ skills = [], text = '', config = {}, roomId = null, budget = MAX_BODY, limit = MAX_PER_TURN, nearness = null, near = 1 } = {}) {
412
+ const asked = keywords(text);
413
+ const seats = [];
414
+ for (const skill of skills) {
415
+ const state = skillState(config, skill.id, roomId);
416
+ if (state === 'off') continue;
417
+ if (state === 'always') { seats.push({ skill, state, why: [], score: Infinity }); continue; }
418
+ if (!skill.when) continue; // nothing to match on: only «always» ever seats it
419
+ const why = [...keywords(pick(skill.when, 'es') ?? skill.when)].filter((word) => asked.has(word));
420
+ const close = why.length ? 1 : typeof nearness === 'function' ? Number(nearness(skill, text)) || 0 : 0;
421
+ if (!why.length && !(close >= near && near <= 1)) continue;
422
+ seats.push({ skill, state, why, score: why.length || close });
423
+ }
424
+ seats.sort((a, b) => (b.score - a.score) || a.skill.id.localeCompare(b.skill.id));
425
+ const chosen = [];
426
+ let chars = 0;
427
+ for (const seat of seats) {
428
+ if (chosen.length >= limit) break;
429
+ if (chars + seat.skill.body.length > budget && chosen.length) break;
430
+ chars += seat.skill.body.length;
431
+ chosen.push({ ...seat.skill, state: seat.state, why: seat.why });
432
+ }
433
+ return { chosen, left: seats.slice(chosen.length).map((seat) => seat.skill.id), chars };
434
+ }
435
+
436
+ // ---- THE SKILLS OF ONE TURN, WRITTEN FOR THE AGENT (H-2). Model-facing, so it is in English like
437
+ // the rest of a briefing (src/room/prompt.mjs) and never goes through the catalogue.
438
+ //
439
+ // A skill carries files MADRE does not hand over: its folder lives outside the project, and whether
440
+ // an agent may read there is its own CLI's answer, not MADRE's. So the files are named with their
441
+ // folder and the agent is told what to do when it cannot reach them, which is true for every agent
442
+ // instead of being a promise only some keep.
443
+ const english = (value) => (value && typeof value === 'object' ? value.en ?? value.es ?? null : value ?? null);
444
+ const attribute = (value) => String(value ?? '').replace(/[<>"&\n]/g, ' ').trim().slice(0, 240);
445
+
446
+ export function formatSkills(skills = [], { mode = 1 } = {}) {
447
+ const lines = [];
448
+ for (const skill of skills) {
449
+ const why = skill.state === 'always' ? 'the human turned it on for this project' : skill.why?.length ? `the human said: ${skill.why.join(', ')}` : 'it matches what was asked';
450
+ lines.push(`<skill name="${attribute(english(skill.name) ?? skill.id)}" why="${attribute(why)}">`);
451
+ lines.push(skill.body.trim());
452
+ const carried = (skill.files ?? []).filter((one) => !one.runs && !SKILL_FILES.includes(one.path)).map((one) => one.path);
453
+ if (carried.length) lines.push(`It carries ${carried.join(', ')}, in ${skill.dir}: read one when its instructions point at it. If you cannot reach that folder, say so in one line rather than guessing, and the human will attach what you need.`);
454
+ if (skill.scripts?.length) {
455
+ lines.push(mode === 4
456
+ ? `It carries ${skill.scripts.join(', ')}, in ${skill.dir}: you may run one this turn, and as with any command, say in one line what it does before you do.`
457
+ : `It carries ${skill.scripts.join(', ')}, which nothing runs in this mode: #4 AIRLOCK is the only turn that could, so do not try and do not ask the human to run one for you unless its instructions depend on it.`);
458
+ }
459
+ lines.push('</skill>');
460
+ }
461
+ return lines.join('\n');
462
+ }
463
+
464
+ // ---- SHARING ONE, HAND TO HAND (2026-11-08, C-1). The Market is the curated road: the author of
465
+ // MADRE reads a skill, signs it, and every MADRE can get it and be told when it is taken back. This
466
+ // is the other road, the one things actually travel on: somebody sends a colleague the file that
467
+ // solved their afternoon.
468
+ //
469
+ // What is prepared is the skill as it is, without MADRE's own record of where it came from, in a
470
+ // folder of its own so the person can find it. A skill of ONE file is written as `<id>.habilidad.md`
471
+ // — the same name an agent writes and the room already recognises — so the other side only has to
472
+ // drag it in. One that carries more says so: those files travel together or not at all, and nothing
473
+ // here builds an archive, because MADRE has nothing that opens one.
474
+ //
475
+ // Decided by the author on 2026-11-08: SKILLS ONLY. A module hand to hand would be code running with
476
+ // the permissions of whoever installed it, with nobody having read it.
477
+ export const shareFolder = (stateRoot, id) => join(stateRoot, 'compartir', id);
478
+ export async function shareSkill({ stateRoot, projectRoot, id }) {
479
+ const { loaded } = await loadSkills({ stateRoot, projectRoot });
480
+ const skill = loaded.find((one) => one.id === id);
481
+ if (!skill) throw new Error(t('No skill «{id}».', { id }));
482
+ const folder = shareFolder(stateRoot, id);
483
+ await rm(folder, { recursive: true, force: true }).catch(() => {});
484
+ await mkdir(folder, { recursive: true });
485
+ const carried = skill.files.filter((file) => file.path !== 'origen.json');
486
+ const alone = carried.length === 1 && SKILL_FILES.includes(carried[0].path);
487
+ const written = [];
488
+ for (const file of carried) {
489
+ // Alone, it travels under the name the other side knows; with company, under its own.
490
+ const name = alone ? `${skill.id}.habilidad.md` : file.path;
491
+ const to = join(folder, name);
492
+ await mkdir(dirname(to), { recursive: true });
493
+ await writeFile(to, await readFile(join(skill.dir, file.path)));
494
+ written.push(name);
495
+ }
496
+ return {
497
+ id: skill.id, folder, files: written, alone,
498
+ // What the other side will not get, said here and not discovered there.
499
+ scripts: skill.scripts,
500
+ file: alone ? join(folder, written[0]) : null,
501
+ };
502
+ }
package/src/terms.mjs CHANGED
@@ -18,20 +18,38 @@ export const TERMS_LINKS = {
18
18
  privacy: { es: 'https://madre.run/privacidad/', en: 'https://madre.run/en/privacy/' },
19
19
  };
20
20
 
21
+ // THE DESKTOP APP HAS ITS OWN LICENSE (2026-11-11, the author): MADRE for Mac and Linux, the app
22
+ // (~/madre-app, private), is closed code, so inside it the person accepts the app's license of use —
23
+ // not the source code's. The MADRE on GitHub and npm keeps the Business Source License, unchanged. A
24
+ // text of its own is a version of its own: whoever accepted the source's in a browser is asked again
25
+ // the first time MADRE opens inside the app, and the other way round.
26
+ // 2026-11-13: the personal license (free for a person, not for organizations; ~/madre-app/LICENCIA-DE-USO.md).
27
+ export const APP_TERMS_VERSION = 'app-2026-11-13';
28
+ export const APP_TERMS_LINKS = {
29
+ license: { es: 'https://madre.run/app/licencia/', en: 'https://madre.run/en/app/license/' },
30
+ privacy: TERMS_LINKS.privacy,
31
+ };
32
+ export const inApp = (env = process.env) => env.MADRE_APP === '1';
33
+ export const termsVersion = (env = process.env) => (inApp(env) ? APP_TERMS_VERSION : TERMS_VERSION);
34
+ export const termsLinks = (env = process.env) => (inApp(env) ? APP_TERMS_LINKS : TERMS_LINKS);
35
+ export const termsKind = (env = process.env) => (inApp(env) ? 'app' : 'source');
36
+
21
37
  export const termsWaived = (env = process.env) => env.PULSE_TEST_MODE === '1' || env.PULSE_TERMS === 'accepted';
22
38
 
23
39
  export async function readTerms(root, { env = process.env } = {}) {
24
- if (termsWaived(env)) return { accepted: true, version: TERMS_VERSION, at: null, waived: true };
40
+ const version = termsVersion(env);
41
+ const kind = termsKind(env);
42
+ if (termsWaived(env)) return { accepted: true, version, kind, at: null, waived: true };
25
43
  try {
26
44
  const kept = JSON.parse(await readFile(join(root, 'terms.json'), 'utf8'));
27
- return { accepted: kept?.version === TERMS_VERSION, version: TERMS_VERSION, at: typeof kept?.at === 'string' ? kept.at : null, previous: kept?.version ?? null };
45
+ return { accepted: kept?.version === version, version, kind, at: typeof kept?.at === 'string' ? kept.at : null, previous: kept?.version ?? null };
28
46
  } catch {
29
- return { accepted: false, version: TERMS_VERSION, at: null, previous: null };
47
+ return { accepted: false, version, kind, at: null, previous: null };
30
48
  }
31
49
  }
32
50
 
33
- export async function acceptTerms(root, { now = new Date() } = {}) {
34
- const kept = { version: TERMS_VERSION, at: now.toISOString() };
51
+ export async function acceptTerms(root, { now = new Date(), env = process.env } = {}) {
52
+ const kept = { version: termsVersion(env), at: now.toISOString() };
35
53
  await writeFile(join(root, 'terms.json'), `${JSON.stringify(kept)}\n`);
36
54
  return { accepted: true, ...kept };
37
55
  }
package/src/tour.mjs CHANGED
@@ -37,7 +37,7 @@ export const CHAPTERS = ['moved', 'home', 'renamed', 'board', 'widgets', 'projec
37
37
  // one port, and a project takes the first free port when it opens: the cards came back whenever it
38
38
  // got another one, and the project that got the old port inherited them (2026-10-19).)
39
39
  export const HINTS = ['switch', 'links', 'key4',
40
- 'home-links', 'home-map', 'home-settings', 'home-add', 'new-add-widgets',
40
+ 'home-links', 'home-map', 'home-settings', 'home-add', 'new-add-widgets', 'home-widgets',
41
41
  'w-system', 'w-servers', 'w-memory', 'w-coordinator', 'w-models', 'w-usage', 'w-agenda',
42
42
  // The author's own widgets (2026-10-30): their first-time card came back on every start, never kept.
43
43
  'w-errors', 'w-live', 'w-installs', 'w-environments', 'w-rumbo',
@@ -51,7 +51,9 @@ export const HINTS = ['switch', 'links', 'key4',
51
51
  'guide-code', 'guide-manual', 'home-coordinator', 'home-manual',
52
52
  'new-code-ask', 'new-notes', 'new-connectors', 'new-manual',
53
53
  // The two drawings of a map, planets and neurons (2026-10-28): said once, by the key that switches them.
54
- 'map-views'];
54
+ 'map-views',
55
+ // The first press of the main keys (1.1, 2026-11-08): Home's and a project's.
56
+ 'home-activity', 'home-market', 'home-modules', 'home-agents', 'touch-activity', 'touch-attach', 'touch-options', 'touch-copilot'];
55
57
  const PATHS = ['new', 'back', 'since'];
56
58
  // The news this code knows (2026-10-21): written on the bonjour as the version a person MET MADRE
57
59
  // with (`met`). The cards of what is new are for whoever met it before a version; someone who meets
@@ -65,9 +67,20 @@ const BEFORE = ['1.0'];
65
67
  // ready after `npx madre` — agents, local AI, memory, the first project — in their order. Where the
66
68
  // person is, what they finished and what they left for later are kept here too, so closing the page
67
69
  // halfway brings them back to the same step, from whichever project or port they open next.
68
- export const WELCOME_STEPS = ['hello', 'machine', 'agents', 'project', 'ai', 'memory', 'ready'];
69
- const freshWelcome = () => ({ at: null, done: [], skipped: [], finished: null });
70
- const fresh = (before = null) => ({ version: TOUR_VERSION, path: null, bonjourAt: null, done: [], at: null, closed: false, finished: null, hints: {}, held: null, before, met: null, welcome: freshWelcome() });
70
+ // 1.1 (2026-11-08, docs/private/BIENVENIDA-1.1.md): six steps. What the computer is goes into the
71
+ // greeting and the memory into the local AI; «what it is for» comes in, and is kept as `profile`, so
72
+ // the examples MADRE gives are this person's and not a programmer's.
73
+ export const WELCOME_STEPS = ['hello', 'use', 'agents', 'project', 'ai', 'ready'];
74
+ export const WELCOME_PROFILES = ['business', 'social', 'numbers', 'office', 'study', 'notes', 'code', 'curious'];
75
+ const freshWelcome = () => ({ at: null, done: [], skipped: [], finished: null, profile: [] });
76
+ // THE FIRST WEEK'S MISSIONS (2026-11-11, the author: «missions instead of a tour»): five things to do,
77
+ // each with a result the person sees, each teaching a piece of MADRE on the way. Kept here with the
78
+ // tour, one person's, whichever project or port a mission was done in: the day it was done, or
79
+ // nothing. `missionsHidden` is the person putting them away.
80
+ // The fifth was «install a skill» until the author tried it with none left to install (2026-11-11):
81
+ // now it is anything got from the Market — a module, a skill, a connector.
82
+ export const MISSIONS = ['page', 'two-ais', 'undo', 'local-ai', 'market'];
83
+ const fresh = (before = null) => ({ version: TOUR_VERSION, path: null, bonjourAt: null, done: [], at: null, closed: false, finished: null, hints: {}, held: null, before, met: null, welcome: freshWelcome(), missions: {}, missionsHidden: null });
71
84
  // A tab that shows the bonjour or the chapters says so every few seconds; another tab that finds it
72
85
  // said within this long tells the person it is open there, instead of a second bonjour.
73
86
  export const HELD_MS = 45 * 1000;
@@ -100,7 +113,10 @@ export async function readTour(stateRoot) {
100
113
  done: Array.isArray(raw.welcome?.done) ? WELCOME_STEPS.filter((id) => raw.welcome.done.includes(id)) : [],
101
114
  skipped: Array.isArray(raw.welcome?.skipped) ? WELCOME_STEPS.filter((id) => raw.welcome.skipped.includes(id)) : [],
102
115
  finished: iso(raw.welcome?.finished),
116
+ profile: Array.isArray(raw.welcome?.profile) ? WELCOME_PROFILES.filter((id) => raw.welcome.profile.includes(id)) : [],
103
117
  },
118
+ missions: Object.fromEntries(MISSIONS.filter((id) => iso(raw.missions?.[id])).map((id) => [id, raw.missions[id]])),
119
+ missionsHidden: iso(raw.missionsHidden),
104
120
  };
105
121
  }
106
122
 
@@ -150,6 +166,12 @@ async function applyChange(stateRoot, change, now) {
150
166
  }
151
167
  // The welcome: where the person is, a step done or left for later (one undoes the other), done
152
168
  // with it, or from the start again (Settings › «See the welcome again»).
169
+ // A mission done (the first time counts), or all of them put away or back.
170
+ if (change.mission !== undefined) {
171
+ if (!MISSIONS.includes(change.mission)) return { error: 'mission' };
172
+ state.missions[change.mission] ??= at;
173
+ }
174
+ if (change.missionsHidden !== undefined) state.missionsHidden = change.missionsHidden === true ? at : null;
153
175
  if (change.welcome !== undefined) {
154
176
  const said = change.welcome;
155
177
  if (!said || typeof said !== 'object') return { error: 'welcome' };
@@ -165,6 +187,10 @@ async function applyChange(stateRoot, change, now) {
165
187
  if (said.done !== undefined) mark('done', 'skipped', said.done);
166
188
  if (said.skipped !== undefined) mark('skipped', 'done', said.skipped);
167
189
  if (said.finished === true) state.welcome.finished ??= at;
190
+ if (said.profile !== undefined) {
191
+ if (!Array.isArray(said.profile) || said.profile.some((id) => !WELCOME_PROFILES.includes(id))) return { error: 'profile' };
192
+ state.welcome.profile = WELCOME_PROFILES.filter((id) => said.profile.includes(id));
193
+ }
168
194
  }
169
195
  return writeTour(stateRoot, state);
170
196
  }