@jossuealcala/madre 1.1.3 → 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 (121) hide show
  1. package/CHANGELOG.en.md +20 -1
  2. package/CHANGELOG.md +20 -1
  3. package/TRADEMARKS.md +6 -2
  4. package/bin/madre.mjs +4 -2
  5. package/docs/REFERENCE.md +3 -3
  6. package/docs/SDK.md +28 -1
  7. package/docs/en/REFERENCE.md +2 -2
  8. package/docs/en/SDK.md +26 -0
  9. package/docs/sdk/hello-module.mjs +38 -3
  10. package/habilidades/explicamelo-facil/HABILIDAD.md +19 -0
  11. package/habilidades/hojas-de-calculo/HABILIDAD.md +18 -0
  12. package/habilidades/mensajes-a-clientes/HABILIDAD.md +19 -0
  13. package/habilidades/publicaciones-para-redes/HABILIDAD.md +19 -0
  14. package/habilidades/resumen-y-pendientes/HABILIDAD.md +18 -0
  15. package/habilidades/tu-pagina-paso-a-paso/HABILIDAD.md +19 -0
  16. package/package.json +4 -3
  17. package/public/activity.js +57 -22
  18. package/public/app.js +3998 -762
  19. package/public/assets/brand/OFL-SpaceGrotesk.txt +93 -0
  20. package/public/assets/brand/SpaceGrotesk-latin-ext.woff2 +0 -0
  21. package/public/assets/brand/SpaceGrotesk-latin.woff2 +0 -0
  22. package/public/assets/brand/madre-app-180.png +0 -0
  23. package/public/assets/brand/madre-app-192.png +0 -0
  24. package/public/assets/brand/madre-app-512.png +0 -0
  25. package/public/assets/brand/madre-app.svg +1 -1
  26. package/public/assets/brand/madre-favicon.svg +1 -1
  27. package/public/attribution.js +28 -27
  28. package/public/auto-open.js +102 -0
  29. package/public/brands.js +9 -6
  30. package/public/changes.js +63 -0
  31. package/public/en.js +1085 -101
  32. package/public/es.js +2395 -1688
  33. package/public/i18n.js +11 -0
  34. package/public/index.html +28 -27
  35. package/public/loader.js +322 -117
  36. package/public/macroverso.js +33 -350
  37. package/public/manual-content.js +37 -7
  38. package/public/manual.js +21 -6
  39. package/public/market-view.js +212 -105
  40. package/public/market.js +10 -2
  41. package/public/mcp-catalog.js +7 -2
  42. package/public/missions.js +169 -0
  43. package/public/news-scenes.js +110 -3
  44. package/public/nostromo-engine.js +935 -654
  45. package/public/notices.js +14 -2
  46. package/public/notifications.js +119 -0
  47. package/public/provider-marks.js +170 -0
  48. package/public/provider-pick.js +147 -0
  49. package/public/resay.js +1 -0
  50. package/public/review-ask.js +16 -13
  51. package/public/routing.js +29 -3
  52. package/public/salas-mac.css +257 -40
  53. package/public/salas-mac.html +5 -5
  54. package/public/salas-mac.js +376 -97
  55. package/public/salas.css +2 -2
  56. package/public/salas.html +2 -2
  57. package/public/salas.js +1 -1
  58. package/public/starters.js +128 -0
  59. package/public/styles.css +2656 -336
  60. package/public/subscription.js +303 -0
  61. package/public/terms-field.js +170 -0
  62. package/public/terms.js +117 -19
  63. package/public/tips.js +41 -7
  64. package/public/tour-chapters.js +35 -35
  65. package/public/tour.js +333 -43
  66. package/public/troubleshooting.js +100 -7
  67. package/public/welcome-scene.js +117 -29
  68. package/public/welcome.js +364 -60
  69. package/src/adapters/claude.mjs +2 -1
  70. package/src/adapters/codex.mjs +2 -1
  71. package/src/adapters/cursor.mjs +9 -6
  72. package/src/adapters/gemini.mjs +4 -0
  73. package/src/adapters/grok.mjs +6 -4
  74. package/src/adapters/madre.mjs +71 -23
  75. package/src/adapters/opencode.mjs +15 -2
  76. package/src/adapters/steps.mjs +176 -0
  77. package/src/app-invite.mjs +90 -0
  78. package/src/billing-key.mjs +8 -0
  79. package/src/billing.mjs +317 -0
  80. package/src/bridge/policy.mjs +1 -1
  81. package/src/capabilities.mjs +17 -11
  82. package/src/chats.mjs +44 -2
  83. package/src/checkpoint.mjs +5 -1
  84. package/src/commands.mjs +5 -2
  85. package/src/directives.mjs +1 -0
  86. package/src/event-store.mjs +15 -0
  87. package/src/extensions.mjs +5 -1
  88. package/src/ficha.mjs +16 -0
  89. package/src/image-studio.mjs +13 -3
  90. package/src/install-metrics.mjs +9 -3
  91. package/src/lease.mjs +1 -1
  92. package/src/looks.mjs +4 -1
  93. package/src/mcp/image-server.mjs +59 -90
  94. package/src/modules/ahp.mjs +2 -1
  95. package/src/modules/github.mjs +6 -2
  96. package/src/modules/image-providers.mjs +281 -0
  97. package/src/modules/image-studio.mjs +100 -19
  98. package/src/modules/index.mjs +7 -1
  99. package/src/modules/intents-observe.mjs +3 -1
  100. package/src/modules/playwright.mjs +33 -4
  101. package/src/modules/reminders.mjs +42 -2
  102. package/src/modules/ripley.mjs +2 -1
  103. package/src/modules/sdk.mjs +6 -1
  104. package/src/opencode-health.mjs +1 -1
  105. package/src/outbound.mjs +80 -6
  106. package/src/quota-sources.mjs +148 -3
  107. package/src/review-ask.mjs +55 -31
  108. package/src/room/changes.mjs +79 -0
  109. package/src/room/economy.mjs +1 -1
  110. package/src/room/guard.mjs +8 -1
  111. package/src/room/prompt.mjs +20 -4
  112. package/src/room.mjs +87 -21
  113. package/src/salas.mjs +30 -3
  114. package/src/server.mjs +545 -59
  115. package/src/setup.mjs +1 -1
  116. package/src/skills.mjs +10 -0
  117. package/src/terms.mjs +23 -5
  118. package/src/tour.mjs +18 -3
  119. package/src/updates.mjs +47 -4
  120. package/src/web-preview.mjs +181 -0
  121. package/src/whats-new.mjs +76 -4
@@ -0,0 +1,90 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // THE INVITATION TO THE APP (2026-11-10, asked by the author): whoever updates MADRE and uses
4
+ // it in the browser is asked, once per version, whether to stay in the browser or download the app for
5
+ // their computer — a window on Home after the update (public/salas-mac.js, offerApp; it was a strip
6
+ // until the author asked for the choice, 2026-11-10). Someone new meets the app at madre.run, where
7
+ // they download it; nothing here speaks to them.
8
+ //
9
+ // Not inside the app, not to whoever already has MADRE.app in Applications, and not before the app can
10
+ // be downloaded for that desktop: madre.run/app/latest.json — what the app's own updater reads — has
11
+ // to list it (a Mac only, today). That file is asked for only when everything else says yes, at most
12
+ // once a day, and nothing goes with the request.
13
+
14
+ import { existsSync } from 'node:fs';
15
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
16
+ import { homedir } from 'node:os';
17
+ import { join } from 'node:path';
18
+ import { cameFromOlder } from './whats-new.mjs';
19
+ import { isVersion } from './updates.mjs';
20
+
21
+ export const APP_PAGE = 'https://madre.run/app/';
22
+ export const APP_MANIFEST = 'https://madre.run/app/latest.json';
23
+ export const APP_INVITE_ANSWERS = ['shown', 'open', 'later'];
24
+ const FILE = 'app-invite.json';
25
+ const DAY_MS = 24 * 60 * 60 * 1000;
26
+
27
+ // Where an installed MADRE.app would be: the Applications of the computer or of this person.
28
+ export const appInstalled = ({ home = homedir(), exists = existsSync } = {}) => ['/Applications/MADRE.app', join(home, 'Applications', 'MADRE.app')].some((path) => exists(path));
29
+
30
+ async function readKept(root) {
31
+ try { return JSON.parse(await readFile(join(root, FILE), 'utf8')) ?? {}; } catch { return {}; }
32
+ }
33
+ async function keep(root, change) {
34
+ await mkdir(root, { recursive: true });
35
+ await writeFile(join(root, FILE), `${JSON.stringify({ ...(await readKept(root)), ...change }, null, 2)}\n`);
36
+ }
37
+
38
+ // Which desktop the person is at (2026-11-10): a Mac, Windows — also when MADRE runs in WSL, since the
39
+ // person is at Windows and the app they would download is Windows' — or Linux.
40
+ export const DESKTOPS = ['mac', 'windows', 'linux'];
41
+ export const desktopOf = ({ platform = process.platform, wsl = false } = {}) => (platform === 'darwin' ? 'mac' : platform === 'win32' || wsl ? 'windows' : platform === 'linux' ? 'linux' : null);
42
+ // How the app's updater names each desktop in latest.json (`darwin-aarch64`, `windows-x86_64`…).
43
+ const MANIFEST_PREFIX = { mac: 'darwin-', windows: 'windows-', linux: 'linux-' };
44
+
45
+ // The desktops the app can be downloaded for: what madre.run/app/latest.json says, kept for a day. A
46
+ // manifest with a version and no list of platforms is a Mac's (the first app, 2026-11). A failed read
47
+ // is kept too, so a computer without internet does not ask on every visit.
48
+ export async function appDesktops({ root, fetchImpl = globalThis.fetch, url = process.env.PULSE_APP_MANIFEST_URL ?? APP_MANIFEST, now = Date.now() }) {
49
+ const kept = await readKept(root);
50
+ if (kept.checkedAt && now - kept.checkedAt < DAY_MS && Array.isArray(kept.desktops)) return kept.desktops;
51
+ let desktops = [];
52
+ try {
53
+ const response = await fetchImpl(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(5000) });
54
+ const manifest = response.ok ? await response.json().catch(() => null) : null;
55
+ if (isVersion(manifest?.version)) {
56
+ const keys = manifest.platforms && typeof manifest.platforms === 'object' ? Object.keys(manifest.platforms) : null;
57
+ desktops = keys ? DESKTOPS.filter((desktop) => keys.some((key) => key.startsWith(MANIFEST_PREFIX[desktop]))) : ['mac'];
58
+ }
59
+ } catch { /* not reachable: nothing to download today */ }
60
+ await keep(root, { desktops, checkedAt: now }).catch(() => null);
61
+ return desktops;
62
+ }
63
+
64
+ // Everything but the download, without touching the network: a desktop, outside the app, an update,
65
+ // no app installed here, and not yet answered in this version.
66
+ export function appInviteDue({ desktop, env = process.env, novelty, version, answeredFor = null, installed = false }) {
67
+ if (!desktop || env.MADRE_APP === '1') return false;
68
+ if (!cameFromOlder(novelty, version)) return false;
69
+ if (installed) return false;
70
+ return answeredFor !== version;
71
+ }
72
+
73
+ // What Home asks: whether to show the choice now, for which desktop, and where its link goes. Only
74
+ // for a desktop the app is published for: Windows and Linux see nothing until theirs is.
75
+ export async function appInvite({ root, novelty, version, platform, wsl = false, env, fetchImpl, installed }) {
76
+ const desktop = desktopOf({ platform, wsl });
77
+ const kept = await readKept(root);
78
+ const here = installed ?? (desktop === 'mac' && appInstalled());
79
+ if (!appInviteDue({ desktop, env, novelty, version, answeredFor: kept.answered ?? null, installed: here })) return { show: false, desktop };
80
+ const desktops = await appDesktops({ root, fetchImpl });
81
+ // The page can be another for a test on this computer (PULSE_APP_PAGE_URL), as the manifest can.
82
+ return desktops.includes(desktop) ? { show: true, desktop, url: env?.PULSE_APP_PAGE_URL ?? process.env.PULSE_APP_PAGE_URL ?? APP_PAGE } : { show: false, desktop };
83
+ }
84
+
85
+ // «Download» or «Stay in the browser» spends it for this version; «shown» only counts.
86
+ export async function answerAppInvite(root, { answer, version }) {
87
+ if (!APP_INVITE_ANSWERS.includes(answer)) return { error: 'answer' };
88
+ if (answer !== 'shown') await keep(root, { answered: version });
89
+ return { ok: true };
90
+ }
@@ -0,0 +1,8 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // The public half of the key madre.run signs subscription keys with (scripts/billing-key.mjs,
4
+ // docs/private/SUSCRIPCION.md). The private half lives only in madre.run's secrets and on the author's
5
+ // computer. Null: no key is ever accepted, and the author's switch refuses to turn the subscription on.
6
+ export const BILLING_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
7
+ MCowBQYDK2VwAyEAb69EhVG3QhRsB7uH6vxgyQYvt8tQ+lkOHTrrxl3RkMY=
8
+ -----END PUBLIC KEY-----`;
@@ -0,0 +1,317 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // MADRE App's subscription (2026-11-17, docs/private/SUSCRIPCION.md §12). Off everywhere except inside
4
+ // the desktop app (MADRE_APP=1), and there only once the author turns it on with a switch signed on
5
+ // their computer (the notices' key, src/notices-key.mjs) and served by madre.run. Then each copy gets
6
+ // thirty days with everything (TRIAL_DAYS), and after them a subscription (a key madre.run signs once Stripe says it
7
+ // was paid, src/billing-key.mjs) or the limited mode: one project takes messages, no plans among
8
+ // several AIs, no Coordinator. Never a lock and never a deletion: what is past the limit stays, to be
9
+ // read. MADRE from npm or from source never sees any of this.
10
+ //
11
+ // Kept in ~/.pulse/suscripcion/: interruptor.json (the last switch, as signed), estado.json (when this
12
+ // copy's trial began, the order waiting to be paid, the project chosen in the limited mode, what the
13
+ // person has already been told) and clave (the key, readable only by its owner).
14
+
15
+ import { createPrivateKey, createPublicKey, randomBytes, sign, verify } from 'node:crypto';
16
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
17
+ import { join } from 'node:path';
18
+ import { BILLING_PUBLIC_KEY } from './billing-key.mjs';
19
+ import { NOTICES_PUBLIC_KEY } from './notices-key.mjs';
20
+
21
+ // What the author's switch says (2026-11-18, the author: «Van a ser 30 días gratis y después el precio
22
+ // de la suscripción»): thirty days with everything, then $109 MXN a month, VAT included.
23
+ export const TRIAL_DAYS = 30;
24
+ export const PRICE_MXN = 109;
25
+
26
+ export const BILLING_SITE = 'https://madre.run';
27
+ export const billingSite = (env = process.env) => String(env.PULSE_COBRO_URL || BILLING_SITE).replace(/\/+$/, '');
28
+ export const billingInApp = (env = process.env) => env.MADRE_APP === '1';
29
+
30
+ const DAY = 24 * 60 * 60 * 1000;
31
+ // How often a copy asks madre.run for the switch, for a key it is waiting for, and for a fresh key.
32
+ export const SWITCH_EVERY_MS = 30 * 60 * 1000;
33
+ export const ORDER_EVERY_MS = 4000;
34
+ export const RENEW_EVERY_MS = 12 * 60 * 60 * 1000;
35
+ // The project that takes messages in the limited mode changes once a day at most.
36
+ export const CHOOSE_EVERY_MS = DAY;
37
+ // Settings › Subscription offers the plan; the price comes signed in the switch.
38
+ export const PLAN = 'mensual';
39
+
40
+ const isDate = (value) => typeof value === 'string' && Number.isFinite(Date.parse(value));
41
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
42
+ const ORDER = /^[A-Za-z0-9_-]{43}$/;
43
+
44
+ function checks(bytes, signature, publicKey) {
45
+ if (!publicKey) return false;
46
+ try { return verify(null, bytes, createPublicKey(publicKey), Buffer.from(String(signature ?? ''), 'base64')); } catch { return false; }
47
+ }
48
+
49
+ // ---- The author's switch -------------------------------------------------------------------------
50
+
51
+ // Read as MADRE reads it, or null: on or off, since when, how many days of trial, the monthly price.
52
+ export function readSwitch(raw) {
53
+ if (!raw || typeof raw !== 'object' || typeof raw.on !== 'boolean' || !isDate(raw.from) || !isDate(raw.at)) return null;
54
+ const trialDays = Number(raw.trialDays);
55
+ const mxn = Number(raw.price?.mxn);
56
+ if (!Number.isInteger(trialDays) || trialDays < 1 || trialDays > 30 || !Number.isFinite(mxn) || mxn <= 0) return null;
57
+ return { on: raw.on, from: raw.from, trialDays, price: { mxn }, at: raw.at };
58
+ }
59
+ // The exact bytes signed: a word of its own, so no notice's signature ever passes for a switch.
60
+ export const switchBytes = (one) => Buffer.from(`madre-cobro:${JSON.stringify({ on: one.on, from: one.from, trialDays: one.trialDays, price: { mxn: one.price.mxn }, at: one.at })}`);
61
+ export function signSwitch(raw, privateKeyPem) {
62
+ const one = readSwitch(raw);
63
+ if (!one) throw new Error('That is not a switch MADRE would read.');
64
+ return { switch: one, sig: sign(null, switchBytes(one), createPrivateKey(privateKeyPem)).toString('base64') };
65
+ }
66
+ export function verifiedSwitch(entry, publicKey = NOTICES_PUBLIC_KEY) {
67
+ const one = readSwitch(entry?.switch);
68
+ return one && checks(switchBytes(one), entry.sig, publicKey) ? one : null;
69
+ }
70
+
71
+ // ---- The key -------------------------------------------------------------------------------------
72
+
73
+ // MADRE1.<payload>.<signature>, both base64url; the signature is over «madre-clave:» and the payload's
74
+ // JSON exactly as it travels. Null when anything about it does not hold.
75
+ export function readKey(text, publicKey = BILLING_PUBLIC_KEY) {
76
+ const parts = String(text ?? '').trim().split('.');
77
+ if (parts.length !== 3 || parts[0] !== 'MADRE1' || !BASE64URL.test(parts[1]) || !BASE64URL.test(parts[2])) return null;
78
+ const json = Buffer.from(parts[1], 'base64url').toString('utf8');
79
+ if (!checks(Buffer.from(`madre-clave:${json}`), Buffer.from(parts[2], 'base64url').toString('base64'), publicKey)) return null;
80
+ let payload;
81
+ try { payload = JSON.parse(json); } catch { return null; }
82
+ if (payload?.v !== 1 || typeof payload.sub !== 'string' || !payload.sub || !isDate(payload.until) || !isDate(payload.at)) return null;
83
+ if (payload.equipo !== undefined && !ORDER.test(String(payload.equipo))) return null;
84
+ return { sub: payload.sub, plan: typeof payload.plan === 'string' ? payload.plan : PLAN, until: payload.until, at: payload.at, equipo: payload.equipo ?? null };
85
+ }
86
+ // The same format madre.run signs (its tests, and these). Since 2026-11-18 each key names the
87
+ // computer it was given to (`equipo`): this copy takes no key of another.
88
+ export function signKey({ sub, plan = PLAN, until, at = new Date().toISOString(), equipo }, privateKeyPem) {
89
+ const json = JSON.stringify(equipo === undefined ? { v: 1, sub, plan, until, at } : { v: 1, sub, plan, until, at, equipo });
90
+ return `MADRE1.${Buffer.from(json).toString('base64url')}.${sign(null, Buffer.from(`madre-clave:${json}`), createPrivateKey(privateKeyPem)).toString('base64url')}`;
91
+ }
92
+
93
+ // ---- What this copy keeps ------------------------------------------------------------------------
94
+
95
+ const folder = (root) => join(root, 'suscripcion');
96
+ const readJson = (file) => readFile(file, 'utf8').then((raw) => JSON.parse(raw)).catch(() => null);
97
+ async function writeAtomic(file, text, mode = 0o600) {
98
+ await mkdir(join(file, '..'), { recursive: true, mode: 0o700 });
99
+ const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
100
+ await writeFile(temp, text, { mode });
101
+ await rename(temp, file).catch(async (error) => { await rm(temp, { force: true }); throw error; });
102
+ await chmod(file, mode).catch(() => {});
103
+ }
104
+
105
+ export async function readBilling(root, { switchKey, billingKey } = {}) {
106
+ switchKey ??= NOTICES_PUBLIC_KEY;
107
+ billingKey ??= BILLING_PUBLIC_KEY;
108
+ const served = await readJson(join(folder(root), 'interruptor.json'));
109
+ const saved = (await readJson(join(folder(root), 'estado.json'))) ?? {};
110
+ const keyText = (await readFile(join(folder(root), 'clave'), 'utf8').catch(() => '')).trim();
111
+ const key = keyText ? readKey(keyText, billingKey) : null;
112
+ // A key given to another computer is no key here (copied over by hand, or a home folder restored).
113
+ const mine = key && (!key.equipo || key.equipo === saved.equipo) ? key : null;
114
+ return { sw: verifiedSwitch(served, switchKey), served, saved, key: mine, keyText };
115
+ }
116
+ export async function saveBilling(root, patch) {
117
+ const saved = { ...((await readJson(join(folder(root), 'estado.json'))) ?? {}), ...patch };
118
+ for (const [name, value] of Object.entries(patch)) if (value === undefined) delete saved[name];
119
+ await writeAtomic(join(folder(root), 'estado.json'), `${JSON.stringify(saved, null, 2)}\n`);
120
+ return saved;
121
+ }
122
+
123
+ // Where this copy stands. `off`: outside the app, or the author has not turned it on. `trial`: days
124
+ // left. `active`: paid, until when. `limited`: the trial is over and there is no live key.
125
+ export function billingState({ env = process.env, sw, saved = {}, key = null, now = Date.now() }) {
126
+ if (!billingInApp(env) || !sw?.on || now < Date.parse(sw.from)) return { state: 'off' };
127
+ const trialStart = isDate(saved.trial) ? Date.parse(saved.trial) : now;
128
+ const trialEnds = trialStart + sw.trialDays * DAY;
129
+ const live = key && Date.parse(key.until) > now;
130
+ const base = { price: sw.price, trialDays: sw.trialDays, trialEnds: new Date(trialEnds).toISOString(), waiting: Boolean(saved.order && !live), recovering: Boolean(saved.recovery && !live), moved: Boolean(saved.moved && !live) };
131
+ if (live) return { ...base, state: 'active', until: key.until, plan: key.plan };
132
+ if (now < trialEnds) return { ...base, state: 'trial', daysLeft: Math.max(1, Math.ceil((trialEnds - now) / DAY)) };
133
+ return { ...base, state: 'limited', active: saved.active ?? null, lapsed: Boolean(key) };
134
+ }
135
+
136
+ // The state, read from the disk, with the trial started the first time the switch is seen on. The
137
+ // author turning it off clears the trial: turned on again later, everyone gets their days again.
138
+ export async function loadBilling(root, { env = process.env, now = Date.now(), switchKey, billingKey } = {}) {
139
+ const read = await readBilling(root, { switchKey, billingKey });
140
+ let { saved } = read;
141
+ if (billingInApp(env) && read.sw?.on && now >= Date.parse(read.sw.from) && !isDate(saved.trial)) saved = await saveBilling(root, { trial: new Date(now).toISOString() });
142
+ else if (read.sw && !read.sw.on && (saved.trial || saved.seen)) saved = await saveBilling(root, { trial: undefined, seen: undefined, active: undefined });
143
+ return { ...read, saved, view: billingState({ env, sw: read.sw, saved, key: read.key, now }) };
144
+ }
145
+
146
+ // What the person is told once each, by the page: the switch just reached them, two days left, the
147
+ // last day, the trial over, and the thank-you once paid.
148
+ export function dueMoment(view, saved = {}) {
149
+ const seen = saved.seen ?? {};
150
+ if (view.state === 'trial') {
151
+ if (!seen.intro) return 'intro';
152
+ if (view.daysLeft <= 1 && !seen.last) return 'last';
153
+ if (view.daysLeft <= 2 && !seen.soon && !seen.last) return 'soon';
154
+ }
155
+ // The subscription turned on in two other computers, and this one went out (2026-11-18).
156
+ if (view.state === 'limited' && view.moved && !seen.moved) return 'moved';
157
+ if (view.state === 'limited' && !seen.limited) return 'limited';
158
+ if (view.state === 'active' && !seen.paid) return 'paid';
159
+ return null;
160
+ }
161
+ export const MOMENTS = ['intro', 'soon', 'last', 'limited', 'moved', 'paid'];
162
+ export async function markSeen(root, moment, now = Date.now()) {
163
+ if (!MOMENTS.includes(moment)) return null;
164
+ const { saved } = await readBilling(root);
165
+ return saveBilling(root, { seen: { ...(saved.seen ?? {}), [moment]: new Date(now).toISOString() } });
166
+ }
167
+
168
+ // ---- The limited mode ----------------------------------------------------------------------------
169
+
170
+ // Whether this project may take a message: the one chosen, or the first one written in once the
171
+ // limit began. Any other is read, not written: `active` names the one that is.
172
+ export async function claimProject(root, { room, name, view, now = Date.now() }) {
173
+ if (view?.state !== 'limited') return { ok: true };
174
+ const { saved } = await readBilling(root);
175
+ if (!saved.active?.room) {
176
+ const active = { room, name, at: new Date(now).toISOString() };
177
+ await saveBilling(root, { active });
178
+ return { ok: true, active };
179
+ }
180
+ return saved.active.room === room ? { ok: true, active: saved.active } : { ok: false, active: saved.active };
181
+ }
182
+ // Making another project the one that takes messages: once a day.
183
+ export async function chooseProject(root, { room, name, now = Date.now() }) {
184
+ const { saved } = await readBilling(root);
185
+ if (saved.active?.room === room) return { ok: true, active: saved.active };
186
+ const since = isDate(saved.active?.at) ? Date.parse(saved.active.at) : 0;
187
+ if (saved.active?.room && now - since < CHOOSE_EVERY_MS) return { ok: false, active: saved.active, next: new Date(since + CHOOSE_EVERY_MS).toISOString() };
188
+ const active = { room, name, at: new Date(now).toISOString() };
189
+ await saveBilling(root, { active });
190
+ return { ok: true, active };
191
+ }
192
+
193
+ // ---- Talking to madre.run ------------------------------------------------------------------------
194
+
195
+ const quiet = (ms) => AbortSignal.timeout(ms);
196
+
197
+ // The switch as madre.run serves it: kept when its signature holds and it is newer than the one here.
198
+ export async function askSwitch(root, { env = process.env, fetchImpl = globalThis.fetch, switchKey } = {}) {
199
+ switchKey ??= NOTICES_PUBLIC_KEY;
200
+ const answer = await fetchImpl(`${billingSite(env)}/api/cobro`, { headers: { accept: 'application/json' }, signal: quiet(8000) }).catch(() => null);
201
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
202
+ if (!data?.switch) return null;
203
+ const one = verifiedSwitch(data, switchKey);
204
+ if (!one) return null;
205
+ const { sw } = await readBilling(root, { switchKey });
206
+ if (!sw || Date.parse(one.at) > Date.parse(sw.at)) await writeAtomic(join(folder(root), 'interruptor.json'), `${JSON.stringify({ switch: data.switch, sig: data.sig })}\n`, 0o644);
207
+ return one;
208
+ }
209
+
210
+ // A new order: the page opens madre.run's payment with it, and this copy asks for its key meanwhile.
211
+ export async function newOrder(root, { env = process.env, language = 'es', now = Date.now() } = {}) {
212
+ const id = randomBytes(32).toString('base64url');
213
+ await saveBilling(root, { order: { id, at: new Date(now).toISOString() } });
214
+ return { id, url: `${billingSite(env)}/app/suscribirme/?pedido=${id}&idioma=${language === 'en' ? 'en' : 'es'}` };
215
+ }
216
+
217
+ export async function saveKey(root, text, { billingKey = BILLING_PUBLIC_KEY } = {}) {
218
+ const key = readKey(text, billingKey);
219
+ if (!key) return null;
220
+ await writeAtomic(join(folder(root), 'clave'), `${String(text).trim()}\n`);
221
+ await saveBilling(root, { order: undefined, recovery: undefined, moved: undefined, lapsed: undefined, renewedAt: new Date().toISOString() });
222
+ return key;
223
+ }
224
+
225
+ // The order waiting to be paid: its key once madre.run has it. madre.run does not know an order until
226
+ // the browser opens its page (404 meanwhile), and Stripe keeps a payment open for a day: the order is
227
+ // asked about for 24 hours, every few seconds in its first half hour (src/server.mjs), then every
228
+ // minute. One madre.run says ended (`vencida`: cancelled or never paid) is dropped.
229
+ export const ORDER_KEEP_MS = DAY;
230
+ export const ORDER_FAST_MS = 30 * 60 * 1000;
231
+ export async function askOrder(root, { env = process.env, fetchImpl = globalThis.fetch, billingKey = BILLING_PUBLIC_KEY, now = Date.now() } = {}) {
232
+ const { saved } = await readBilling(root, { billingKey });
233
+ if (!ORDER.test(saved.order?.id ?? '')) return null;
234
+ const equipo = await deviceId(root);
235
+ const answer = await fetchImpl(`${billingSite(env)}/api/suscripcion/clave?pedido=${saved.order.id}&equipo=${equipo}`, { headers: { accept: 'application/json' }, signal: quiet(8000) }).catch(() => null);
236
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
237
+ if (data?.estado === 'activa' && data.clave) return saveKey(root, data.clave, { billingKey });
238
+ const age = now - (isDate(saved.order.at) ? Date.parse(saved.order.at) : 0);
239
+ if (data?.estado === 'vencida' || age > ORDER_KEEP_MS) await saveBilling(root, { order: undefined });
240
+ return null;
241
+ }
242
+
243
+ // A fresh key for the one here, every twelve hours: `until` moves with each payment. A subscription
244
+ // that ended keeps its old key until it expires on its own.
245
+ export async function renewKey(root, { env = process.env, fetchImpl = globalThis.fetch, billingKey = BILLING_PUBLIC_KEY, now = Date.now(), force = false } = {}) {
246
+ const { keyText, key, saved } = await readBilling(root, { billingKey });
247
+ if (!key) return null;
248
+ const last = isDate(saved.renewedAt) ? Date.parse(saved.renewedAt) : 0;
249
+ if (!force && now - last < RENEW_EVERY_MS && Date.parse(key.until) - now > 3 * DAY) return key;
250
+ const answer = await fetchImpl(`${billingSite(env)}/api/suscripcion/renovar`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ clave: keyText, equipo: await deviceId(root) }), signal: quiet(8000) }).catch(() => null);
251
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
252
+ if (data?.estado === 'activa' && data.clave) return (await saveKey(root, data.clave, { billingKey })) ?? key;
253
+ if (data?.estado === 'vencida') await saveBilling(root, { renewedAt: new Date(now).toISOString(), lapsed: true });
254
+ // Turned on in two other computers since: this one goes back to the limited mode now, and is told why.
255
+ if (data?.estado === 'otra-computadora') {
256
+ await rm(join(folder(root), 'clave'), { force: true });
257
+ await saveBilling(root, { renewedAt: new Date(now).toISOString(), moved: new Date(now).toISOString() });
258
+ return null;
259
+ }
260
+ return key;
261
+ }
262
+
263
+ // This copy's name for madre.run (2026-11-18): 32 random bytes, made once and kept. It says nothing
264
+ // about the computer; it only lets a subscription count its computers (two at most) and give each
265
+ // its own key.
266
+ export async function deviceId(root) {
267
+ const { saved } = await readBilling(root);
268
+ if (ORDER.test(saved.equipo ?? '')) return saved.equipo;
269
+ const equipo = randomBytes(32).toString('base64url');
270
+ await saveBilling(root, { equipo });
271
+ return equipo;
272
+ }
273
+
274
+ // Turning the subscription on in this computer with the email it was paid with (2026-11-18, the
275
+ // author: «todo automático sin que tengan que pegar cosas»). madre.run sends that email a button;
276
+ // once it is pressed and confirmed, wherever it was opened, this copy's key arrives on its own.
277
+ // madre.run answers the same whether or not that email pays: so does this.
278
+ export const RECOVERY_KEEP_MS = 30 * 60 * 1000;
279
+ const EMAIL = /^[^\s@<>()]{1,64}@[^\s@<>()]{1,189}\.[^\s@<>()]{2,}$/;
280
+ export async function startRecovery(root, { email, env = process.env, fetchImpl = globalThis.fetch, language = 'es', now = Date.now() } = {}) {
281
+ const correo = String(email ?? '').trim().toLowerCase();
282
+ if (correo.length > 254 || !EMAIL.test(correo)) return { error: 'email' };
283
+ const solicitud = randomBytes(32).toString('base64url');
284
+ const answer = await fetchImpl(`${billingSite(env)}/api/suscripcion/recuperar`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ correo, equipo: await deviceId(root), solicitud, idioma: language === 'en' ? 'en' : 'es' }), signal: quiet(10000) }).catch(() => null);
285
+ if (answer?.status === 429) return { error: 'too_many' };
286
+ if (!answer?.ok) return { error: 'unreachable' };
287
+ await saveBilling(root, { recovery: { id: solicitud, at: new Date(now).toISOString() } });
288
+ return { ok: true };
289
+ }
290
+ // The recovery waiting: its key once the button in the email is confirmed. Dropped after half an
291
+ // hour, as madre.run drops it, or when madre.run says it ended.
292
+ export async function askRecovery(root, { env = process.env, fetchImpl = globalThis.fetch, billingKey = BILLING_PUBLIC_KEY, now = Date.now() } = {}) {
293
+ const { saved } = await readBilling(root, { billingKey });
294
+ if (!ORDER.test(saved.recovery?.id ?? '')) return null;
295
+ if (now - (isDate(saved.recovery.at) ? Date.parse(saved.recovery.at) : 0) > RECOVERY_KEEP_MS) {
296
+ await saveBilling(root, { recovery: undefined });
297
+ return null;
298
+ }
299
+ const answer = await fetchImpl(`${billingSite(env)}/api/suscripcion/recuperar?solicitud=${saved.recovery.id}&equipo=${await deviceId(root)}`, { headers: { accept: 'application/json' }, signal: quiet(8000) }).catch(() => null);
300
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
301
+ if (data?.estado === 'activa' && data.clave) return saveKey(root, data.clave, { billingKey });
302
+ if (data?.estado === 'vencida') await saveBilling(root, { recovery: undefined });
303
+ return null;
304
+ }
305
+ export async function stopRecovery(root) {
306
+ await saveBilling(root, { recovery: undefined });
307
+ }
308
+
309
+ // Where the person cancels, changes the card or reads the invoices: Stripe's own page, opened by
310
+ // madre.run for this key.
311
+ export async function portalUrl(root, { env = process.env, fetchImpl = globalThis.fetch, language = 'es' } = {}) {
312
+ const { keyText } = await readBilling(root);
313
+ if (!keyText) return null;
314
+ const answer = await fetchImpl(`${billingSite(env)}/api/suscripcion/portal`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ clave: keyText, idioma: language === 'en' ? 'en' : 'es' }), signal: quiet(10000) }).catch(() => null);
315
+ const data = answer?.ok ? await answer.json().catch(() => null) : null;
316
+ return typeof data?.url === 'string' && /^https:\/\//.test(data.url) ? data.url : null;
317
+ }
@@ -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', '/icons.js', '/page-errors.js', '/activity.js', '/notices.js', '/tips.js', '/news-scenes.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']);
20
+ const STATIC = new Set(['/', '/app.js', '/icons.js', '/page-errors.js', '/auto-open.js', '/changes.js', '/activity.js', '/notices.js', '/subscription.js', '/tips.js', '/starters.js', '/provider-pick.js', '/notifications.js', '/provider-marks.js', '/news-scenes.js', '/terms.js', '/terms-field.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', '/missions.js', '/touch.js', '/attribution.js', '/power.js', '/wallpaper.js', '/neural.js', '/hardware.js', '/code-tools.js', '/market.js', '/market-view.js', '/market-art.js', '/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',
@@ -19,21 +19,21 @@ export const CAPABILITIES = {
19
19
  imageIn: { how: '-i <file>', note: 'Images attach to the prompt directly.' },
20
20
  write: { how: '-C <outdir> --sandbox workspace-write', note: 'Reads the whole project, writes only inside the lease directory.' },
21
21
  imageGen: { how: 'features.image_generation (stable, enabled)', note: 'Generated with the ChatGPT account; saved into the lease directory.' },
22
- web: { how: '--search (live web_search tool)', note: 'Off until turned on in Settings › Agents › Web access.' },
22
+ web: { how: '--search (live web_search tool)', note: 'On by default; turned off per agent in Settings › Agents › Web access.' },
23
23
  },
24
24
  claude: {
25
25
  read: true,
26
26
  imageIn: { how: 'Read tool on the attachment path', note: 'The attachments folder is added with --add-dir.' },
27
27
  write: { how: '--tools Write,Edit + permission rules', note: 'Write/Edit allowed only under the lease directory.' },
28
28
  imageGen: false,
29
- web: { how: '--tools WebFetch,WebSearch', note: 'Off until turned on in Settings › Agents › Web access.' },
29
+ web: { how: '--tools WebFetch,WebSearch', note: 'On by default; turned off per agent in Settings › Agents › Web access.' },
30
30
  },
31
31
  gemini: {
32
32
  read: true,
33
33
  imageIn: { how: 'read_file on the attachment path', note: 'The attachments folder is added with --include-directories.' },
34
34
  write: { how: 'policy: allow write_file/edit with argsPattern', note: 'Paths outside the lease directory stay denied.' },
35
35
  imageGen: false,
36
- web: { how: 'policy: allow google_web_search, web_fetch', note: 'Off until turned on in Settings › Agents › Web access.' },
36
+ web: { how: 'policy: allow google_web_search, web_fetch', note: 'On by default; turned off per agent in Settings › Agents › Web access.' },
37
37
  },
38
38
  // Cursor reads in its own ask mode and, from 2026-10-21, writes and runs commands at the modes
39
39
  // that allow it (adapters/cursor.mjs). Attachments are named in the briefing.
@@ -42,7 +42,10 @@ export const CAPABILITIES = {
42
42
  imageIn: false,
43
43
  write: { how: 'agent mode with --force under a configuration made for the turn', note: 'Writes where the turn allows; commands only at #4. MADRE locks and puts back .env, .git and its own folders, and at #2 what existed.' },
44
44
  imageGen: false,
45
- web: false,
45
+ // Its own WebSearch and WebFetch (2026-11-10, tried against the real CLI): in print mode they wait
46
+ // for an approval nobody gives, so a reading turn with the web on runs ask mode with --force, while
47
+ // the turn's configuration still denies every command and every write (nothing was written or run).
48
+ web: { how: '--mode ask --force, Shell(*) and Write(**) denied', note: 'On by default; turned off per agent in Settings › Agents › Web access.' },
46
49
  },
47
50
  // Grok (adapters/grok.mjs, 2026-11-06): reads, and from the same day writes at #2 and #3 and runs
48
51
  // commands at #4, each mode tried against the real CLI first. Attachments are named in the briefing.
@@ -54,14 +57,14 @@ export const CAPABILITIES = {
54
57
  // draft folder at #2 and into imagenes/ at #3 and #4 (src/lease.mjs, grokImagesDir).
55
58
  imageGen: { how: 'image_gen, copied by MADRE into the project', note: 'Generated with the Grok account; MADRE copies each image into the draft folder at #2 and into imagenes/ at #3 and #4.' },
56
59
  // Its own search and page reader (2026-11-07): off until Web access is turned on for it.
57
- web: { how: '--tools …,web_search,web_fetch', note: 'Off until turned on in Settings › Agents › Web access.' },
60
+ web: { how: '--tools …,web_search,web_fetch', note: 'On by default; turned off per agent in Settings › Agents › Web access.' },
58
61
  },
59
62
  opencode: {
60
63
  read: true,
61
64
  imageIn: { how: '-f <file>', note: 'Files attach to the message.' },
62
65
  write: { how: 'permission.edit patterns', note: 'Edit allowed only under the lease directory.' },
63
66
  imageGen: false,
64
- web: { how: 'permission.webfetch / websearch = allow', note: 'Off until turned on in Settings › Agents › Web access.' },
67
+ web: { how: 'permission.webfetch / websearch = allow', note: 'On by default; turned off per agent in Settings › Agents › Web access.' },
65
68
  },
66
69
  };
67
70
 
@@ -83,11 +86,13 @@ export function setAgentsViaApi(agents = []) {
83
86
  }
84
87
 
85
88
  // MADRE modules can add abilities a CLI lacks. Image Studio (MADRE's own MCP
86
- // image server on the Gemini API) gives Gemini CLI, Claude Code and OpenCode
87
- // image generation; Codex keeps its native one.
89
+ // image server on the image model chosen in MODULES › Images: Gemini, OpenAI or
90
+ // Grok) gives Gemini CLI, Claude Code and OpenCode image generation; Codex and
91
+ // Grok keep their native one. `stateRoot` and `home` are where its server looks
92
+ // for the key (2026-11-14): paths, never a key.
88
93
  let imageModule = { enabled: false };
89
94
  export function setImageModule(state) {
90
- imageModule = { enabled: Boolean(state?.enabled), model: state?.model ?? null };
95
+ imageModule = { enabled: Boolean(state?.enabled), model: state?.model ?? null, stateRoot: state?.stateRoot ?? null, home: state?.home ?? null };
91
96
  }
92
97
  export const imageModuleState = () => ({ ...imageModule });
93
98
 
@@ -95,7 +100,7 @@ export const capabilityOf = (agentId) => {
95
100
  if (viaApi.has(agentId)) return API_ONLY;
96
101
  const base = CAPABILITIES[agentId] ?? { read: true, imageIn: false, write: false, imageGen: false, web: false };
97
102
  if (!base.imageGen && imageModule.enabled && ['gemini', 'claude', 'opencode'].includes(agentId)) {
98
- return { ...base, imageGen: { how: 'MADRE Image Studio (MCP tool generate_image, Gemini API)', note: `Attached only inside a creation lease with the image scope on${imageModule.model ? ` · model ${imageModule.model}` : ''}.`, module: 'image-studio' } };
103
+ return { ...base, imageGen: { how: 'MADRE Image Studio (MCP tool generate_image, the model chosen in Modules › Images)', note: `Attached only inside a creation lease with the image scope on${imageModule.model ? ` · model ${imageModule.model}` : ''}.`, module: 'image-studio' } };
99
104
  }
100
105
  return base;
101
106
  };
@@ -143,7 +148,8 @@ export function resolveScopes(agentId, configured = {}) {
143
148
  const scopes = {};
144
149
  for (const scope of SCOPES) {
145
150
  const capable = Boolean(caps[scope]);
146
- const wanted = configured[scope] ?? (scope !== 'web');
151
+ // Web access is on unless the person turns it off in Settings › Agents (2026-11-14, the author).
152
+ const wanted = configured[scope] ?? true;
147
153
  scopes[scope] = { capable, enabled: capable && wanted, wired: true };
148
154
  }
149
155
  // One ceiling per agent: MAX MODE. Writing follows from it: an agent capped at #1 never
package/src/chats.mjs CHANGED
@@ -77,15 +77,20 @@ const shape = (id, entry, active) => ({
77
77
  updatedAt: entry.updatedAt ?? entry.createdAt ?? null,
78
78
  messages: Number(entry.messages ?? 0),
79
79
  preview: withoutRelayHeader(entry.preview) ?? null,
80
+ pinned: Boolean(entry.pinned),
81
+ archived: Boolean(entry.archived),
82
+ // What it brought from the conversation it continues (2026-11-11), until its first message uses it.
83
+ carried: entry.carried && !Number(entry.messages ?? 0) ? { from: entry.carried.from, title: entry.carried.title, summary: entry.carried.summary } : null,
80
84
  active: id === active,
81
85
  });
82
86
 
83
- // Newest first, because that is the order a person looks for a conversation in.
87
+ // Newest first, because that is the order a person looks for a conversation in; the ones the person
88
+ // pinned above the rest (2026-11-11), newest first among themselves too.
84
89
  export async function listChats(roomDir) {
85
90
  const index = await chatIndex(roomDir);
86
91
  const chats = Object.entries(index.chats)
87
92
  .map(([id, entry]) => shape(id, entry, index.active))
88
- .sort((a, b) => String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
93
+ .sort((a, b) => Number(b.pinned) - Number(a.pinned) || String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
89
94
  return { active: index.active, chats };
90
95
  }
91
96
 
@@ -103,6 +108,26 @@ async function createChatNow(roomDir, { title = null, now = new Date().toISOStri
103
108
  return shape(id, index.chats[id], index.active);
104
109
  }
105
110
 
111
+ // SUMMARIZE AND CONTINUE: a new conversation that carries what another one decided and left open,
112
+ // written by the agent that was in it. Its first message takes it along; MADRE adds nothing to it.
113
+ export const CARRY_MAX = 12000;
114
+ export function carryChat(roomDir, ...rest) {
115
+ return indexTurn(roomDir, () => carryChatNow(roomDir, ...rest));
116
+ }
117
+ async function carryChatNow(roomDir, from, { title = null, summary = '', from: named, now = new Date().toISOString() } = {}) {
118
+ const index = await chatIndex(roomDir);
119
+ const source = index.chats[from];
120
+ const said = String(summary ?? '').trim().slice(0, CARRY_MAX);
121
+ if (!source || !said) return null;
122
+ const id = randomUUID().replace(/-/g, '').slice(0, 16);
123
+ const before = named === undefined ? withoutRelayHeader(source.title) || null : named;
124
+ index.chats[id] = { title: title ? String(title).slice(0, CHAT_TITLE_MAX) : null, createdAt: now, updatedAt: now, messages: 0, preview: null, carried: { from, title: before, summary: said } };
125
+ index.active = id;
126
+ await mkdir(join(roomDir, 'chats', id), { recursive: true });
127
+ await writeIndex(roomDir, index);
128
+ return shape(id, index.chats[id], index.active);
129
+ }
130
+
106
131
  export function openChat(roomDir, ...rest) {
107
132
  return indexTurn(roomDir, () => openChatNow(roomDir, ...rest));
108
133
  }
@@ -126,6 +151,23 @@ async function renameChatNow(roomDir, id, title) {
126
151
  return shape(id, index.chats[id], index.active);
127
152
  }
128
153
 
154
+ // Pinned: kept at the top of the list, whatever came after it. Archived (2026-11-11): out of the
155
+ // list and under «Archived», kept whole; archiving one takes its pin off.
156
+ const FLAGS = new Set(['pinned', 'archived']);
157
+ function flagChat(roomDir, ...rest) {
158
+ return indexTurn(roomDir, () => flagChatNow(roomDir, ...rest));
159
+ }
160
+ async function flagChatNow(roomDir, id, flag, on) {
161
+ const index = await chatIndex(roomDir);
162
+ if (!index.chats[id] || !FLAGS.has(flag)) return null;
163
+ if (on) index.chats[id][flag] = true; else delete index.chats[id][flag];
164
+ if (flag === 'archived' && on) delete index.chats[id].pinned;
165
+ await writeIndex(roomDir, index);
166
+ return shape(id, index.chats[id], index.active);
167
+ }
168
+ export const pinChat = (roomDir, id, pinned) => flagChat(roomDir, id, 'pinned', pinned);
169
+ export const archiveChat = (roomDir, id, archived) => flagChat(roomDir, id, 'archived', archived);
170
+
129
171
  // Deleting a conversation takes its transcript and nothing else: whatever the archivist distilled
130
172
  // from it is the project's memory, not the conversation's, and it stays. The last conversation
131
173
  // cannot be deleted — a room always has somewhere to talk.
@@ -335,6 +335,10 @@ async function diffOne(root, before, prefix = '', exclude = []) {
335
335
  // own list of what it ignores, without walking what is ignored for its size (dependencies, builds,
336
336
  // caches), MADRE's own folders or the .env files the guard already puts back; bounded, because it
337
337
  // is a note on the card and not a record.
338
+ // Linux stamps a file with a coarse clock that can run a few milliseconds behind Date.now(): a file
339
+ // written right as the turn began looked older than the turn (CI, 2026-11-09). Its margin is small,
340
+ // and a file that was there before and did not change is told apart afterwards (sortIgnoredWrites).
341
+ const MTIME_SLACK_MS = 50;
338
342
  export async function ignoredWrittenSince(root, checkpoint, since, { limit = 500, budget = 20000 } = {}) {
339
343
  const listed = await git(root, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'], { via: checkpoint?.via }).catch(() => '');
340
344
  const nested = (checkpoint?.exclude ?? []).map((dir) => dir.replace(/\/$/, ''));
@@ -348,7 +352,7 @@ export async function ignoredWrittenSince(root, checkpoint, since, { limit = 500
348
352
  const info = await lstat(join(root, bare)).catch(() => null);
349
353
  if (info?.isDirectory()) {
350
354
  for (const entry of (await readdir(join(root, bare)).catch(() => [])).sort()) await walk(`${bare}/${entry}`);
351
- } else if (info?.isFile() && info.mtimeMs >= since) found.push(bare);
355
+ } else if (info?.isFile() && info.mtimeMs >= since - MTIME_SLACK_MS) found.push(bare);
352
356
  };
353
357
  for (const path of listed.split('\0').filter(Boolean)) await walk(path);
354
358
  return found;