@jossuealcala/madre 1.1.1 → 1.1.2

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.
package/src/rumbo.mjs ADDED
@@ -0,0 +1,337 @@
1
+ // SPDX-License-Identifier: BUSL-1.1
2
+ // MADRE · © 2026 Jossue Alcalá · Business Source License 1.1: LICENSE
3
+ // MADRE's course (2026-11-01): the author's model of the variables that decide where the project
4
+ // goes. Only for the author, in a copy run from source with the author's token (src/server.mjs,
5
+ // homeWidget, kind «rumbo»); Home draws it as the widget «MADRE's course».
6
+ //
7
+ // Three sources, each read on its own clock and each allowed to be missing:
8
+ // madre.run's /api/rumbo — the funnel of every new copy (diagnostics on), the weeks, the return
9
+ // by system, the AIs, the failures. Counts only: no copy leaves madre.run by its identifier.
10
+ // GitHub — stars (with the day each was given), forks, the 14 days of visits and clones GitHub
11
+ // keeps, where visitors came from, and the installer's downloads. Through the author's gh
12
+ // session (src/github.mjs); without one, nothing from GitHub.
13
+ // npm — the package's downloads by day and last week's by version. Every publish is pulled by
14
+ // mirrors and caches, so a release day reads high: it is said as downloads, never as people.
15
+ // GitHub forgets visits after 14 days; each reading is kept in the state root
16
+ // (rumbo-history.json), so the history grows from the first time the widget is read.
17
+ //
18
+ // `rumboModel` is pure: it turns the three readings into variables, each with its value, how sure
19
+ // it is (a 90% interval and the size of what it counts), a signal against a threshold and the
20
+ // decision it informs, and into the decisions themselves. The page says it in words.
21
+
22
+ import { readFile } from 'node:fs/promises';
23
+ import { join } from 'node:path';
24
+ import { cachedSession, githubRequest } from './github.mjs';
25
+ import { oneAtATime, writeWhole } from './json-file.mjs';
26
+
27
+ export const REPO = 'jossuealcacao-exe/madre';
28
+ const DAY = 86_400_000;
29
+ const dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
30
+
31
+ // ── The thresholds ─────────────────────────────────────────────────────────────────────────────
32
+ // Where a rate turns good or bad, for a tool people install and then have to set up. They are
33
+ // starting points from early-stage developer tools, not laws: change them here and the widget
34
+ // follows. `lower` marks a rate where less is better.
35
+ export const THRESHOLDS = {
36
+ ready: { good: 0.7, bad: 0.4 }, // new copies with an AI ready
37
+ used: { good: 0.5, bad: 0.25 }, // new copies that asked an AI something
38
+ readyToUse: { good: 0.6, bad: 0.3 }, // of those with an AI ready, the ones that used it
39
+ firstProject: { good: 0.7, bad: 0.4 }, // copies with at least one project
40
+ d1: { good: 0.4, bad: 0.2 }, // came back the next day or later
41
+ d7: { good: 0.2, bad: 0.1 }, // came back a week later or more
42
+ habit: { good: 0.2, bad: 0.08 }, // used an AI on two days or more
43
+ failing: { good: 0.1, bad: 0.25, lower: true }, // copies that met a failure
44
+ uninstall: { good: 0.05, bad: 0.15, lower: true }, // uninstalls for every install
45
+ starRate: { good: 0.04, bad: 0.015 }, // stars for every unique visitor of the repository
46
+ growth: { good: 0.1, bad: -0.1 }, // activated copies, this week against the one before
47
+ };
48
+ // What «paying for MADRE Pro» and «enough traction to show an investor» ask for.
49
+ export const PRO_BAR = { activatedWeek: 100, d7: 0.2, habit: 0.15, heavy: 0.1 };
50
+ export const INVEST_BAR = { weeksGrowing: 4, d7: 0.2, activatedWeek: 250 };
51
+
52
+ // A 90% Wilson interval for k of n: honest with small samples, where k/n alone is not.
53
+ const Z = 1.645;
54
+ export function wilson(k, n) {
55
+ if (!n) return null;
56
+ const p = k / n;
57
+ const d = 1 + (Z * Z) / n;
58
+ const center = (p + (Z * Z) / (2 * n)) / d;
59
+ const half = (Z * Math.sqrt((p * (1 - p)) / n + (Z * Z) / (4 * n * n))) / d;
60
+ return { low: Math.max(0, center - half), high: Math.min(1, center + half) };
61
+ }
62
+ export const confidence = (n) => (n >= 100 ? 'high' : n >= 30 ? 'medium' : 'low');
63
+ export function signalOf(value, { good, bad, lower = false }) {
64
+ if (value === null || value === undefined || !Number.isFinite(value)) return 'none';
65
+ if (lower) return value <= good ? 'good' : value > bad ? 'bad' : 'watch';
66
+ return value >= good ? 'good' : value < bad ? 'bad' : 'watch';
67
+ }
68
+ // A rate: k of n, its interval, how sure, and its signal.
69
+ function rate(id, group, k, n, threshold) {
70
+ const value = n ? k / n : null;
71
+ return { id, group, kind: 'rate', k, n, value, interval: wilson(k, n), confidence: confidence(n), signal: threshold ? signalOf(value, threshold) : 'info', threshold: threshold ?? null };
72
+ }
73
+ // A change: this period against the one before.
74
+ function change(id, group, now, before, threshold) {
75
+ const value = before ? (now - before) / before : null;
76
+ return { id, group, kind: 'change', now, before, value, confidence: confidence(Math.min(now, before)), signal: before ? signalOf(value, threshold) : 'none', threshold };
77
+ }
78
+
79
+ const sum = (list, field) => list.reduce((total, one) => total + Number(one?.[field] ?? 0), 0);
80
+
81
+ // ── The model ──────────────────────────────────────────────────────────────────────────────────
82
+ export function rumboModel({ madre = null, github = null, npm = null, history = null, now = Date.now() } = {}) {
83
+ const variables = [];
84
+ const add = (one) => { variables.push(one); return one; };
85
+ const today = dayOf(now);
86
+ const since = (n) => dayOf(now - (n - 1) * DAY);
87
+
88
+ // GitHub's visits: the 14 days it keeps, and the ones kept before them.
89
+ const views = mergeDays(history?.views, github?.views?.days);
90
+ const lastDays = (map, n) => Object.entries(map).filter(([day]) => day >= since(n)).map(([, one]) => one);
91
+ // Without GitHub's own figure (traffic asks for push rights) and nothing kept, there is no figure:
92
+ // never a zero that reads as nobody came.
93
+ const kept14 = lastDays(views, 14);
94
+ const visits14 = github?.views ? { count: Number(github.views.count ?? sum(kept14, 'count')), uniques: Number(github.views.uniques ?? sum(kept14, 'uniques')) } : kept14.length ? { count: sum(kept14, 'count'), uniques: sum(kept14, 'uniques') } : null;
95
+ const starDays = github?.stars?.days ?? [];
96
+ const starsIn = (from, to = today) => starDays.filter((one) => one.day >= from && one.day <= to).reduce((total, one) => total + one.n, 0);
97
+
98
+ // THE FUNNEL: from a visit to a habit.
99
+ const f = madre?.funnel ?? null;
100
+ const weeks = madre?.weeks ?? [];
101
+ const thisWeek = weeks.at(-1) ?? null;
102
+ const lastWeek = weeks.at(-2) ?? null;
103
+ const new14 = weeks.length >= 2 ? Number(thisWeek.new) + Number(lastWeek.new) : null;
104
+ const funnel = [
105
+ { id: 'visits', n: visits14?.uniques ?? null, window: 14 },
106
+ { id: 'downloads', n: npm ? sum((npm.days ?? []).filter((one) => one.day >= since(14)), 'downloads') : null, window: 14, side: true },
107
+ { id: 'new', n: f?.new ?? null, window: 30 },
108
+ { id: 'told', n: f?.told ?? null, window: 30 },
109
+ { id: 'ready', n: f?.ready ?? null, window: 30 },
110
+ { id: 'used', n: f?.used ?? null, window: 30 },
111
+ { id: 'back', n: f?.back ?? null, of: f?.aged ?? null, window: 30 },
112
+ { id: 'habit', n: f?.habit ?? null, of: f?.aged ?? null, window: 30 },
113
+ ];
114
+
115
+ // ACTIVATION: does a new copy get to use MADRE?
116
+ if (f) {
117
+ add(rate('ready', 'activation', f.ready, f.told, THRESHOLDS.ready));
118
+ add(rate('used', 'activation', f.used, f.told, THRESHOLDS.used));
119
+ add(rate('readyToUse', 'activation', f.used, f.ready, THRESHOLDS.readyToUse));
120
+ }
121
+ const projects = madre?.projects ?? null;
122
+ if (projects?.known) add(rate('firstProject', 'activation', projects.known - projects.none, projects.known, THRESHOLDS.firstProject));
123
+
124
+ // RETENTION: does it stay?
125
+ if (madre?.retention) {
126
+ add(rate('d1', 'retention', madre.retention.d1.back, madre.retention.d1.cohort, THRESHOLDS.d1));
127
+ add(rate('d7', 'retention', madre.retention.d7.back, madre.retention.d7.cohort, THRESHOLDS.d7));
128
+ }
129
+ if (f) add(rate('habit', 'retention', f.habit, f.aged, THRESHOLDS.habit));
130
+
131
+ // MOMENTUM: is it growing?
132
+ if (thisWeek && lastWeek) {
133
+ add(change('growth', 'momentum', Number(thisWeek.activated), Number(lastWeek.activated), THRESHOLDS.growth));
134
+ add(change('newGrowth', 'momentum', Number(thisWeek.new), Number(lastWeek.new), THRESHOLDS.growth));
135
+ }
136
+ if (github) add(change('starGrowth', 'momentum', starsIn(since(7)), starsIn(since(14), since(8)), THRESHOLDS.growth));
137
+ if (visits14?.uniques) add(rate('starRate', 'momentum', starsIn(since(14)), visits14.uniques, THRESHOLDS.starRate));
138
+
139
+ // QUALITY: does it hold up?
140
+ if (madre?.errors) add(rate('failing', 'quality', madre.errors.failing, madre.errors.copies, THRESHOLDS.failing));
141
+ if (madre?.lifecycle?.installs) add(rate('uninstall', 'quality', madre.lifecycle.uninstalls, madre.lifecycle.installs, THRESHOLDS.uninstall));
142
+
143
+ // MARKET: who it is reaching. No good or bad here: they point where to build.
144
+ const systems = f?.bySystem ?? null;
145
+ if (systems) {
146
+ const windows = Number(systems.wsl?.new ?? 0) + Number(systems.win32?.new ?? 0);
147
+ add(rate('windowsShare', 'market', windows, f.new, null));
148
+ }
149
+ const language = madre?.language ?? null;
150
+ if (language) {
151
+ const known = Object.entries(language).filter(([name]) => name !== '?').reduce((total, [, n]) => total + n, 0);
152
+ add(rate('englishShare', 'market', Number(language.en ?? 0), known, null));
153
+ }
154
+ if (f) add(rate('coverage', 'market', f.told, f.new, null));
155
+ const referrers = github?.referrers ?? [];
156
+ if (referrers.length) {
157
+ // Facebook's several doors (l., lm., m., www.) are one source.
158
+ const family = (name) => (/facebook\.com$/.test(name) ? 'facebook.com' : /instagram\.com$/.test(name) ? 'instagram.com' : name);
159
+ const grouped = {};
160
+ for (const one of referrers) grouped[family(one.referrer)] = (grouped[family(one.referrer)] ?? 0) + Number(one.uniques ?? 0);
161
+ const ranked = Object.entries(grouped).map(([name, n]) => ({ name, n })).sort((a, b) => b.n - a.n);
162
+ const total = sum(ranked, 'n');
163
+ add({ ...rate('topSource', 'market', ranked[0].n, total, { good: 0.5, bad: 0.7, lower: true }), source: ranked[0].name, sources: ranked.slice(0, 5) });
164
+ }
165
+
166
+ const byId = Object.fromEntries(variables.map((one) => [one.id, one]));
167
+ const decisions = decide({ byId, madre, f, weeks, systems, projects });
168
+
169
+ // THE NORTH STAR: copies that asked an AI something this week.
170
+ const north = thisWeek ? { activated: Number(thisWeek.activated), before: lastWeek ? Number(lastWeek.activated) : null, active: Number(thisWeek.active), new: Number(thisWeek.new) } : null;
171
+
172
+ // HISTORY: what GitHub and npm say over time, for the project's record.
173
+ const record = {
174
+ stars: github?.repo?.stars ?? null,
175
+ forks: github?.repo?.forks ?? null,
176
+ watchers: github?.repo?.watchers ?? null,
177
+ stars7: github ? starsIn(since(7)) : null,
178
+ starsByDay: starDays,
179
+ visits: visits14,
180
+ clones: github?.clones ?? null,
181
+ views: Object.entries(views).sort(([a], [b]) => a.localeCompare(b)).slice(-60).map(([day, one]) => ({ day, ...one })),
182
+ installer: github?.installer ?? null,
183
+ npm: npm ? { lastWeek: npm.lastWeek ?? null, byVersion: npm.byVersion ?? [], days: (npm.days ?? []).slice(-60), total: sum(npm.days ?? [], 'downloads') } : null,
184
+ new14,
185
+ };
186
+
187
+ return { at: new Date(now).toISOString(), north, funnel, variables, decisions, weeks, agents: madre?.agents ?? null, systems, record, thresholds: THRESHOLDS };
188
+ }
189
+
190
+ // The decisions, each from the variables that inform it. Every one says its verdict as an id the
191
+ // page puts in words, the figures it rests on, and a signal.
192
+ function decide({ byId, madre, f, weeks, systems, projects }) {
193
+ const out = [];
194
+ const v = (id) => byId[id]?.value ?? null;
195
+
196
+ // Where people are lost: the first step in the red, in the order a person walks them (a leak
197
+ // upstream empties every step below it, so it is fixed first); with none in the red, the step
198
+ // furthest under its own threshold.
199
+ if (f) {
200
+ const steps = ['ready', 'firstProject', 'readyToUse', 'd1', 'habit'].map((id) => byId[id]).filter((one) => one?.n);
201
+ const worst = steps.find((one) => one.signal === 'bad') ?? steps.map((one) => ({ one, gap: (one.value ?? 0) / one.threshold.good })).sort((a, b) => a.gap - b.gap)[0]?.one;
202
+ if (worst) out.push({ id: 'bottleneck', verdict: worst.id, signal: worst.signal, figures: { value: worst.value, k: worst.k, n: worst.n, noProject: projects ? projects.none : null, projectsKnown: projects?.known ?? null } });
203
+ }
204
+
205
+ // Product or reach: while new copies do not get to use it, more visitors only fill the leak.
206
+ if (byId.used || byId.d1) {
207
+ const leaking = byId.used?.signal === 'bad' || byId.d1?.signal === 'bad';
208
+ const flat = byId.growth && byId.growth.signal === 'bad';
209
+ out.push({ id: 'focus', verdict: leaking ? 'product' : flat ? 'reach' : 'both', signal: leaking ? 'bad' : flat ? 'watch' : 'good', figures: { used: v('used'), d1: v('d1'), growth: v('growth') } });
210
+ }
211
+
212
+ // Windows: how many come from it, and whether they get as far as the rest.
213
+ if (systems && f?.new) {
214
+ const win = { told: Number(systems.wsl?.told ?? 0) + Number(systems.win32?.told ?? 0), used: Number(systems.wsl?.used ?? 0) + Number(systems.win32?.used ?? 0) };
215
+ const rest = { told: f.told - win.told, used: f.used - win.used };
216
+ const share = v('windowsShare');
217
+ const winUse = win.told ? win.used / win.told : null;
218
+ const restUse = rest.told ? rest.used / rest.told : null;
219
+ out.push({ id: 'windows', verdict: share >= 0.35 ? 'priority' : share >= 0.15 ? 'relevant' : 'minor', signal: share >= 0.35 ? 'watch' : 'info', figures: { share, winUse, restUse, winTold: win.told, restTold: rest.told } });
220
+ }
221
+
222
+ // MADRE Pro: four bars, each met or not.
223
+ if (madre) {
224
+ const heavyShare = projects?.known ? (Number(projects.few ?? 0) + Number(projects.many ?? 0)) / projects.known : null;
225
+ const activated = Number(weeks.at(-1)?.activated ?? 0);
226
+ const bars = [
227
+ { id: 'activatedWeek', value: activated, need: PRO_BAR.activatedWeek, met: activated >= PRO_BAR.activatedWeek },
228
+ { id: 'd7', value: v('d7'), need: PRO_BAR.d7, met: (v('d7') ?? 0) >= PRO_BAR.d7 },
229
+ { id: 'habit', value: v('habit'), need: PRO_BAR.habit, met: (v('habit') ?? 0) >= PRO_BAR.habit },
230
+ { id: 'heavy', value: heavyShare, need: PRO_BAR.heavy, met: (heavyShare ?? 0) >= PRO_BAR.heavy },
231
+ ];
232
+ const met = bars.filter((one) => one.met).length;
233
+ out.push({ id: 'pro', verdict: met === bars.length ? 'ready' : met >= 2 ? 'close' : 'early', signal: met === bars.length ? 'good' : met >= 2 ? 'watch' : 'bad', figures: { bars, met } });
234
+
235
+ // Traction to show: weeks in a row that activated copies grew (only weeks with diagnostics count).
236
+ const told = weeks.filter((one) => one.activated > 0);
237
+ let growing = 0;
238
+ for (let i = weeks.length - 1; i > 0 && weeks[i].activated > 0; i -= 1) {
239
+ if (weeks[i].activated > weeks[i - 1].activated && weeks[i - 1].activated > 0) growing += 1;
240
+ else break;
241
+ }
242
+ const invest = [
243
+ { id: 'weeksGrowing', value: growing, need: INVEST_BAR.weeksGrowing, met: growing >= INVEST_BAR.weeksGrowing },
244
+ { id: 'd7', value: v('d7'), need: INVEST_BAR.d7, met: (v('d7') ?? 0) >= INVEST_BAR.d7 },
245
+ { id: 'activatedWeek', value: activated, need: INVEST_BAR.activatedWeek, met: activated >= INVEST_BAR.activatedWeek },
246
+ ];
247
+ const done = invest.filter((one) => one.met).length;
248
+ out.push({ id: 'invest', verdict: done === invest.length ? 'ready' : told.length < 2 ? 'waiting' : done >= 2 ? 'close' : 'early', signal: done === invest.length ? 'good' : told.length < 2 ? 'none' : done >= 2 ? 'watch' : 'bad', figures: { bars: invest, met: done, weeksTold: told.length } });
249
+ }
250
+
251
+ // English: whether the copies that speak it are worth building for.
252
+ if (byId.englishShare?.n) {
253
+ const share = v('englishShare');
254
+ out.push({ id: 'english', verdict: share >= 0.3 ? 'invest' : share >= 0.1 ? 'keep' : 'spanish', signal: 'info', figures: { share, n: byId.englishShare.n } });
255
+ }
256
+
257
+ // Quality: whether failures reach enough copies to stop and fix.
258
+ if (byId.failing?.n) out.push({ id: 'quality', verdict: byId.failing.signal === 'bad' ? 'fix' : byId.failing.signal === 'watch' ? 'watch' : 'fine', signal: byId.failing.signal, figures: { value: v('failing'), k: byId.failing.k, n: byId.failing.n } });
259
+
260
+ return out;
261
+ }
262
+
263
+ // A map {day: {count, uniques}} from what was kept and what GitHub says now (GitHub's own figure
264
+ // for a day wins: the newest day grows until it is over).
265
+ function mergeDays(kept = {}, fresh = []) {
266
+ const out = { ...(kept ?? {}) };
267
+ for (const one of fresh ?? []) out[one.day] = { count: Number(one.count ?? 0), uniques: Number(one.uniques ?? 0) };
268
+ return out;
269
+ }
270
+
271
+ // ── The readings ───────────────────────────────────────────────────────────────────────────────
272
+
273
+ // GitHub, through the author's gh session; null without one. Every part is asked on its own, and
274
+ // a part that fails (traffic needs push rights) is left out, not the whole.
275
+ export async function readGithub({ repo = REPO, env = process.env, auth = undefined } = {}) {
276
+ const session = auth === undefined ? await cachedSession({ env }) : auth;
277
+ if (!session) return null;
278
+ const get = async (path, accept) => (await githubRequest({ path, auth: session, env, timeoutMs: 15000, ...(accept ? { accept } : {}) }).catch(() => null))?.data ?? null;
279
+ const base = `/repos/${repo}`;
280
+ const [info, views, clones, referrers, releases] = await Promise.all([
281
+ get(base), get(`${base}/traffic/views`), get(`${base}/traffic/clones`), get(`${base}/traffic/popular/referrers`), get(`${base}/releases?per_page=50`),
282
+ ]);
283
+ if (!info) return null;
284
+ // The day each star was given: a hundred a page, as many pages as there are stars.
285
+ const starred = [];
286
+ for (let page = 1; page <= 20; page += 1) {
287
+ const list = await get(`${base}/stargazers?per_page=100&page=${page}`, 'application/vnd.github.star+json');
288
+ if (!Array.isArray(list)) break;
289
+ for (const one of list) if (one?.starred_at) starred.push(String(one.starred_at).slice(0, 10));
290
+ if (list.length < 100) break;
291
+ }
292
+ const byDay = {};
293
+ for (const day of starred) byDay[day] = (byDay[day] ?? 0) + 1;
294
+ const installer = Array.isArray(releases) ? releases.flatMap((release) => (release.assets ?? []).filter((asset) => /\.exe$/i.test(asset.name)).map((asset) => ({ tag: release.tag_name, downloads: Number(asset.download_count ?? 0) }))) : null;
295
+ return {
296
+ repo: { stars: Number(info.stargazers_count ?? 0), forks: Number(info.forks_count ?? 0), watchers: Number(info.subscribers_count ?? 0), issues: Number(info.open_issues_count ?? 0) },
297
+ views: views ? { count: Number(views.count ?? 0), uniques: Number(views.uniques ?? 0), days: (views.views ?? []).map((one) => ({ day: String(one.timestamp).slice(0, 10), count: one.count, uniques: one.uniques })) } : null,
298
+ clones: clones ? { count: Number(clones.count ?? 0), uniques: Number(clones.uniques ?? 0) } : null,
299
+ referrers: Array.isArray(referrers) ? referrers.map((one) => ({ referrer: one.referrer, count: Number(one.count ?? 0), uniques: Number(one.uniques ?? 0) })) : [],
300
+ stars: { days: Object.entries(byDay).sort(([a], [b]) => a.localeCompare(b)).map(([day, n]) => ({ day, n })) },
301
+ installer: installer ? { total: sum(installer, 'downloads'), byTag: installer } : null,
302
+ };
303
+ }
304
+
305
+ // npm: the downloads of every day in the last 90 (npm's figures come a day or two late) and last
306
+ // week's by version.
307
+ export async function readNpm({ name, fetchImpl = globalThis.fetch, base = process.env.PULSE_NPM_API_URL ?? 'https://api.npmjs.org', now = Date.now() } = {}) {
308
+ const get = async (url) => {
309
+ const answer = await fetchImpl(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(10000) }).catch(() => null);
310
+ return answer?.ok ? answer.json().catch(() => null) : null;
311
+ };
312
+ const [range, versions] = await Promise.all([
313
+ get(`${base}/downloads/range/${dayOf(now - 89 * DAY)}:${dayOf(now)}/${name}`),
314
+ get(`${base}/versions/${encodeURIComponent(name)}/last-week`),
315
+ ]);
316
+ if (!range && !versions) return null;
317
+ const byVersion = Object.entries(versions?.downloads ?? {}).map(([version, n]) => ({ version, n: Number(n) })).sort((a, b) => b.n - a.n);
318
+ return { days: (range?.downloads ?? []).map((one) => ({ day: one.day, downloads: Number(one.downloads ?? 0) })), byVersion, lastWeek: byVersion.length ? sum(byVersion, 'n') : null };
319
+ }
320
+
321
+ // What GitHub forgets after 14 days, kept here a year: the visits of each day.
322
+ const KEEP_DAYS = 400;
323
+ export const historyFile = (root) => join(root, 'rumbo-history.json');
324
+ export async function readHistory(root) {
325
+ try { const raw = JSON.parse(await readFile(historyFile(root), 'utf8')); return raw && typeof raw === 'object' ? raw : {}; } catch { return {}; }
326
+ }
327
+ export async function keepHistory(root, github, now = Date.now()) {
328
+ if (!github?.views?.days?.length) return readHistory(root);
329
+ return oneAtATime(historyFile(root), async () => {
330
+ const kept = await readHistory(root);
331
+ const cutoff = dayOf(now - KEEP_DAYS * DAY);
332
+ const views = Object.fromEntries(Object.entries(mergeDays(kept.views, github.views.days)).filter(([day]) => day >= cutoff));
333
+ const next = { views, updated: new Date(now).toISOString() };
334
+ await writeWhole(historyFile(root), `${JSON.stringify(next)}\n`);
335
+ return next;
336
+ });
337
+ }
package/src/salas.mjs CHANGED
@@ -13,7 +13,7 @@
13
13
  import { spawn } from 'node:child_process';
14
14
  import { createHash } from 'node:crypto';
15
15
  import { closeSync, openSync, realpathSync } from 'node:fs';
16
- import { mkdir, readdir, readFile, rename, stat } from 'node:fs/promises';
16
+ import { mkdir, readdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
17
17
  import * as nodePath from 'node:path';
18
18
  import { basename, dirname, join, resolve } from 'node:path';
19
19
  import { fileURLToPath } from 'node:url';
@@ -237,6 +237,108 @@ export async function createProject({ name, parent = null, home, stateRoot, now
237
237
  return { ...(await associateProject({ root: folder, home, stateRoot, now })), created: true };
238
238
  }
239
239
 
240
+ // A project to try MADRE with (2026-11-01): 90 of 147 copies never opened a project, and «I read it
241
+ // all and do not know what I would do with MADRE» was said on Facebook. One page, a list of tasks,
242
+ // small enough to read and safe to break, and a README with what to ask the agents about it. Made
243
+ // in the projects folder under a name that is free, in the person's language.
244
+ const SAMPLE = {
245
+ es: {
246
+ names: ['mi-primer-proyecto'],
247
+ readme: `# Mi primer proyecto
248
+
249
+ Una lista de tareas en una sola página, \`index.html\`, para probar MADRE sin miedo a romper nada. Ábrela con doble clic para verla en tu navegador.
250
+
251
+ ## Cosas para pedirle a tus IAs
252
+
253
+ - Explícame este proyecto.
254
+ - Agrega un botón para borrar las tareas terminadas.
255
+ - Haz que las tareas se guarden aunque cierre la página.
256
+ - Revisa el código y dime qué mejorarías primero.
257
+ - Pídele a una IA que lo cambie y a otra que revise lo que hizo.
258
+
259
+ Si algo sale mal, DESHACER en MADRE lo regresa a como estaba.
260
+ `,
261
+ title: 'Mis tareas', placeholder: 'Escribe una tarea', add: 'Agregar', empty: 'Nada pendiente.',
262
+ },
263
+ en: {
264
+ names: ['my-first-project'],
265
+ readme: `# My first project
266
+
267
+ A to-do list on a single page, \`index.html\`, to try MADRE without fear of breaking anything. Double-click it to see it in your browser.
268
+
269
+ ## Things to ask your AIs
270
+
271
+ - Explain this project to me.
272
+ - Add a button that clears the finished tasks.
273
+ - Make the tasks stay when I close the page.
274
+ - Read the code and tell me what you would improve first.
275
+ - Ask one AI to change it and another to review what it did.
276
+
277
+ If something goes wrong, UNDO in MADRE puts it back as it was.
278
+ `,
279
+ title: 'My tasks', placeholder: 'Write a task', add: 'Add', empty: 'Nothing pending.',
280
+ },
281
+ };
282
+ const samplePage = (words, lang) => `<!doctype html>
283
+ <html lang="${lang}">
284
+ <head>
285
+ <meta charset="utf-8">
286
+ <meta name="viewport" content="width=device-width, initial-scale=1">
287
+ <title>${words.title}</title>
288
+ <style>
289
+ body { font-family: system-ui, sans-serif; max-width: 32rem; margin: 3rem auto; padding: 0 1rem; color: #222; }
290
+ form { display: flex; gap: .5rem; }
291
+ input[type=text] { flex: 1; padding: .5rem; }
292
+ li { list-style: none; padding: .35rem 0; }
293
+ .done span { text-decoration: line-through; color: #888; }
294
+ </style>
295
+ </head>
296
+ <body>
297
+ <h1>${words.title}</h1>
298
+ <form id="new">
299
+ <input id="text" type="text" placeholder="${words.placeholder}" autocomplete="off">
300
+ <button>${words.add}</button>
301
+ </form>
302
+ <p id="empty">${words.empty}</p>
303
+ <ul id="list"></ul>
304
+ <script>
305
+ const list = document.getElementById('list');
306
+ const empty = document.getElementById('empty');
307
+ document.getElementById('new').addEventListener('submit', (event) => {
308
+ event.preventDefault();
309
+ const input = document.getElementById('text');
310
+ const text = input.value.trim();
311
+ if (!text) return;
312
+ const item = document.createElement('li');
313
+ const box = document.createElement('input');
314
+ box.type = 'checkbox';
315
+ box.addEventListener('change', () => item.classList.toggle('done', box.checked));
316
+ const words = document.createElement('span');
317
+ words.textContent = ' ' + text;
318
+ item.append(box, words);
319
+ list.append(item);
320
+ empty.hidden = true;
321
+ input.value = '';
322
+ });
323
+ </script>
324
+ </body>
325
+ </html>
326
+ `;
327
+ export async function createSampleProject({ home, stateRoot, language = 'es', now = new Date() }) {
328
+ const lang = SAMPLE[language] ? language : 'en';
329
+ const words = SAMPLE[lang];
330
+ for (let n = 1; n <= 9; n += 1) {
331
+ const name = n === 1 ? words.names[0] : `${words.names[0]}-${n}`;
332
+ const made = await createProject({ name, home, stateRoot, now });
333
+ if (made.error === 'exists') continue;
334
+ if (made.error) return made;
335
+ await writeFile(join(made.root, 'README.md'), words.readme);
336
+ await writeFile(join(made.root, 'index.html'), samplePage(words, lang));
337
+ return { ...made, sample: true };
338
+ }
339
+ return { error: 'exists' };
340
+ }
341
+
240
342
  // Takes a project out of MADRE (2026-10-10): its record of where it is goes aside, so Home no
241
343
  // longer lists it. Nothing in the project's folder is touched, and its conversations and its
242
344
  // memory stay beside the record: added again, the folder gets the same id and finds them there.