bokata 3.0.0-beta.3 → 3.0.0-beta.5

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 (38) hide show
  1. package/.agents/skills/bokata-acceptance-criteria/SKILL.md +6 -7
  2. package/.agents/skills/bokata-acceptance-criteria/resources/output-template-functional.md +3 -3
  3. package/.agents/skills/bokata-acceptance-criteria/resources/output-template.md +1 -1
  4. package/.agents/skills/bokata-feature-map/SKILL.md +10 -11
  5. package/.agents/skills/bokata-feature-mapper/SKILL.md +4 -5
  6. package/.agents/skills/bokata-feature-mapper/resources/output-template.md +1 -1
  7. package/.agents/skills/bokata-feature-slicer/SKILL.md +16 -12
  8. package/.agents/skills/bokata-feature-slicer/resources/output-template-bites.md +12 -4
  9. package/.agents/skills/bokata-feature-slicer/resources/phase-2-increments.md +29 -51
  10. package/.agents/skills/bokata-feature-slicer/resources/{phase-3-baby-steps.md → phase-3-skeleton.md} +3 -3
  11. package/.agents/skills/bokata-feature-slicer/resources/phase-4-bites.md +8 -7
  12. package/.agents/skills/bokata-plan/SKILL.md +21 -15
  13. package/.agents/skills/bokata-plan/resources/plan-template.md +7 -5
  14. package/.agents/skills/bokata-render/SKILL.md +71 -138
  15. package/.agents/skills/bokata-render/assets/story-map.html +590 -0
  16. package/.agents/skills/bokata-render/scripts/render.mjs +784 -0
  17. package/.agents/skills/bokata-shape/SKILL.md +12 -2
  18. package/.agents/skills/bokata-shape/resources/pitch-template.md +3 -0
  19. package/.agents/skills/bokata-slice/SKILL.md +193 -100
  20. package/.agents/skills/bokata-slice/resources/inc-template.md +36 -0
  21. package/.agents/skills/bokata-slice/resources/slice-template.md +36 -84
  22. package/.agents/skills/bokata-status/SKILL.md +27 -15
  23. package/.agents/skills/bokata-tdd/resources/evidence-rules.md +2 -2
  24. package/LICENSE +21 -0
  25. package/README.md +54 -40
  26. package/agents/bokata-product-designer.md +2 -2
  27. package/agents/bokata-product-engineer.md +2 -2
  28. package/agents/bokata-product-manager.md +3 -3
  29. package/agents/code-executor.md +27 -16
  30. package/agents/design-reviewer.md +2 -2
  31. package/agents/feature-slicer.md +21 -9
  32. package/bin/bokata.js +17 -5
  33. package/package.json +1 -1
  34. package/src/agents.js +36 -11
  35. package/src/config.js +8 -7
  36. package/src/install.js +12 -3
  37. package/.agents/skills/bokata-render/resources/story-map-template.md +0 -835
  38. package/agents/story-map-renderer.md +0 -19
@@ -0,0 +1,784 @@
1
+ #!/usr/bin/env node
2
+ // Renders <docs>/<initiative>/story-map.html from features.md, slices/<nn>-<name>.md (+ its folder) and plan.md.
3
+ // Deterministic and stateless: the same markdown always gives the same HTML (apart from the date).
4
+ // No dependencies, Node >= 18. Usage:
5
+ // node render.mjs <initiative-dir> [--lang en|es] [--date YYYY-MM-DD] [--out file] [--check]
6
+ // Exit code 1 (message on stderr, "file:line: problem") when the markdown breaks the contract.
7
+ // --check parses everything with the same parser, prints every problem and writes nothing.
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { fileURLToPath, pathToFileURL } from 'node:url';
12
+
13
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
14
+ const TEMPLATE = path.join(HERE, '..', 'assets', 'story-map.html');
15
+
16
+ export class RenderError extends Error {
17
+ constructor(file, line, message) {
18
+ super(`${file}${line ? `:${line}` : ''}: ${message}`);
19
+ this.name = 'RenderError';
20
+ this.file = file;
21
+ this.line = line;
22
+ this.reason = message;
23
+ }
24
+ }
25
+
26
+ // Slices written by hand (or in Spanish) say the same things with other words.
27
+ const FIELD_ALIASES = { 'depende de': 'depends on', valor: 'value', comprobación: 'check' };
28
+ const OPTION_ID = /F\d+-\d+\.\d+/g;
29
+ // Bite IDs: letters per Feature (F1-a, F1-ab), d<n> for deferred, w<n> for the skeleton bites of Inc 1.
30
+ const BITE_ID = /\bF\d+-(?:[a-z]+|[dw]\d+)\b/g;
31
+ const PRIORITIES = ['skeleton', 'must-have', 'nice-to-have', 'deferred'];
32
+ const INC_STATES = ['sliced', 'planned', 'done'];
33
+
34
+ const read = (file) => fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n');
35
+ const esc = (s) =>
36
+ String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
37
+ const norm = (s) => s.toLowerCase().replace(/\s+/g, ' ').trim();
38
+ const plain = (s) => s.replace(/\*\*/g, '').replace(/`/g, '').trim();
39
+
40
+ // ——— a small markdown → HTML for the increment pages (the subset the slices use) ———
41
+
42
+ const inline = (s) =>
43
+ esc(s)
44
+ .replace(/`([^`]+)`/g, '<code>$1</code>')
45
+ .replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
46
+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1');
47
+
48
+ export function markdown(lines) {
49
+ const out = [];
50
+ let i = 0;
51
+ let ul = false;
52
+ const closeUl = () => {
53
+ if (ul) {
54
+ out.push('</ul>');
55
+ ul = false;
56
+ }
57
+ };
58
+ while (i < lines.length) {
59
+ const l = lines[i];
60
+ if (/^```/.test(l)) {
61
+ closeUl();
62
+ const buf = [];
63
+ i++;
64
+ while (i < lines.length && !/^```/.test(lines[i])) buf.push(lines[i++]);
65
+ i++;
66
+ out.push(
67
+ '<pre class="gh">' +
68
+ buf
69
+ .map((b) => {
70
+ const t = b.trim();
71
+ const pad = `style="padding-left:${b.match(/^\s*/)[0].length * 0.5}ch"`;
72
+ if (/^(Scenario Outline|Scenario|Background|Examples|Feature):/.test(t)) return `<span class="g-sc" ${pad}>${esc(t)}</span>`;
73
+ const k = t.match(/^(Given|When|Then|And|But)\b/);
74
+ if (k) return `<span class="g-st" ${pad}><i>${k[1]}</i>${esc(t.slice(k[1].length))}</span>`;
75
+ if (t.startsWith('#')) return `<span class="g-cm" ${pad}>${esc(t)}</span>`;
76
+ return `<span ${pad}>${esc(b)}</span>`;
77
+ })
78
+ .join('\n') +
79
+ '</pre>'
80
+ );
81
+ continue;
82
+ }
83
+ if (/^\s*<!--.*-->\s*$/.test(l) || l.trim() === '') {
84
+ closeUl();
85
+ i++;
86
+ continue;
87
+ }
88
+ let m;
89
+ if ((m = l.match(/^(#{1,6})\s+(.*)$/))) {
90
+ closeUl();
91
+ const n = Math.min(6, m[1].length + 1);
92
+ out.push(`<h${n}>${inline(m[2])}</h${n}>`);
93
+ i++;
94
+ continue;
95
+ }
96
+ if (/^\s*\|/.test(l)) {
97
+ closeUl();
98
+ const rows = [];
99
+ while (i < lines.length && /^\s*\|/.test(lines[i])) rows.push(lines[i++]);
100
+ const cells = (r) => r.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
101
+ const body = rows.filter((r) => !/^\s*\|[\s:|-]+\|\s*$/.test(r));
102
+ out.push('<table>' + body.map((r, k) => `<tr>${cells(r).map((c) => `<${k ? 'td' : 'th'}>${inline(c)}</${k ? 'td' : 'th'}>`).join('')}</tr>`).join('') + '</table>');
103
+ continue;
104
+ }
105
+ if ((m = l.match(/^(\s*)[-*]\s+(.*)$/))) {
106
+ if (!ul) {
107
+ ul = true;
108
+ out.push('<ul>');
109
+ }
110
+ let t = m[2];
111
+ i++;
112
+ while (i < lines.length && /^\s{2,}\S/.test(lines[i]) && !/^\s*[-*]\s/.test(lines[i])) t += ' ' + lines[i++].trim();
113
+ out.push(`<li class="n${Math.min(2, Math.floor(m[1].length / 2))}">${inline(t)}</li>`);
114
+ continue;
115
+ }
116
+ closeUl();
117
+ let t = l;
118
+ i++;
119
+ while (i < lines.length && lines[i].trim() !== '' && !/^(```|#|\s*[-*]\s|\s*\|)/.test(lines[i])) t += ' ' + lines[i++].trim();
120
+ out.push(/^\*\*Rule:/.test(t) ? `<p class="rule">${inline(t)}</p>` : `<p>${inline(t)}</p>`);
121
+ }
122
+ closeUl();
123
+ return out.join('\n');
124
+ }
125
+
126
+ // ——— features.md ———
127
+
128
+ export function parseFeatures(file) {
129
+ const lines = read(file).split('\n');
130
+ const features = [];
131
+ let initiative = null;
132
+ let feature = null;
133
+ let task = null;
134
+ let collecting = null;
135
+ let fence = false;
136
+
137
+ lines.forEach((raw, i) => {
138
+ const n = i + 1;
139
+ if (/^```/.test(raw)) fence = !fence;
140
+ if (fence) return;
141
+ let m;
142
+ if (!initiative && (m = raw.match(/^<!--\s*Initiative:\s*([^|]+?)\s*(?:\||-->)/))) initiative = m[1];
143
+ if (!initiative && (m = raw.match(/^# (.+?)(?: — Features)?\s*$/))) initiative = m[1];
144
+
145
+ if ((m = raw.match(/^#{2,6}\s+Feature(?:\s+\d+)?:\s*(.+?)\s*$/))) {
146
+ feature = { name: plain(m[1]), id: null, line: n, tasks: [], systemTasks: [] };
147
+ features.push(feature);
148
+ task = null;
149
+ collecting = 'feature';
150
+ return;
151
+ }
152
+ if ((m = raw.match(/^#{2,6}\s+User Task(?:\s+[\d.]+)?:\s*(.+?)\s*$/))) {
153
+ if (!feature) throw new RenderError(file, n, 'User Task before any "Feature:" heading');
154
+ task = { name: plain(m[1]), id: null, line: n, description: '' };
155
+ feature.tasks.push(task);
156
+ collecting = 'task';
157
+ return;
158
+ }
159
+ if ((m = raw.match(/^#{2,6}\s+System Task[^:]*:\s*(.+?)\s*$/))) {
160
+ if (feature) feature.systemTasks.push(plain(m[1]));
161
+ task = null;
162
+ collecting = null;
163
+ return;
164
+ }
165
+ if (/^#{1,6}\s/.test(raw)) {
166
+ collecting = null;
167
+ return;
168
+ }
169
+ if (collecting === 'feature' && feature && (m = raw.match(/<!--\s*ID:\s*(\S+?)\s*(?:\|[^>]*)?-->/))) feature.id = m[1];
170
+ if (collecting === 'task' && task) {
171
+ if ((m = raw.match(/<!--\s*Task ID:\s*(\S+?)\s*(?:\|[^>]*)?-->/))) task.id = m[1];
172
+ else if (!task.description && raw.trim() && !raw.trim().startsWith('<!--')) task.description = plain(raw);
173
+ }
174
+ });
175
+
176
+ if (features.length === 0) throw new RenderError(file, 0, 'no "Feature:" heading found');
177
+ features.forEach((f, idx) => {
178
+ f.code = `F${idx + 1}`;
179
+ f.id = f.id || `FEAT-${idx + 1}`;
180
+ if (f.tasks.length === 0) throw new RenderError(file, f.line, `Feature "${f.name}" has no User Task`);
181
+ f.tasks.forEach((t, k) => {
182
+ t.id = t.id || `${f.code}-T${k + 1}`;
183
+ t.feature = f;
184
+ });
185
+ });
186
+ return { initiative, features };
187
+ }
188
+
189
+ // ——— slices/<nn>-<name>.md ———
190
+
191
+ // ——— slices/<nn>-<name>.md (the index) + slices/<nn>-<name>/ (increments, slicing, notes) ———
192
+
193
+ const sectionName = (heading) => heading.split(/[\s—:]/)[0].toLowerCase();
194
+
195
+ // An option line of slicing/F<k>.md:
196
+ // - F1-1.2 <name> — <what changes> · <strategy> · [covers R1 …] · [skeleton | deferred (…) · F1-a] [→ Inc n] [→ target]
197
+ // Read from the end: the trailing "meta" pieces first, then the strategy, and what is left is the description.
198
+ // (Older slices wrote "paquete F6-e → objetivo" for "F6-e → target": both are accepted.)
199
+ const META = /^(?:covers\b.*|cubre\b.*|skeleton|esqueleto|deferred\b.*|(?:(?:paquete|package|bite)\s+)?(?:F\d+-(?:[a-z]+|[dw]\d+))?(?:\s*→\s*(?:Inc\s*\d+|target|objetivo))*)$/;
200
+ export function optionTail(raw, id) {
201
+ const text = raw.replace(/^\s*-\s+/, '').slice(id.length).trim();
202
+ const dash = text.indexOf(' — ');
203
+ // with no " — " the line is just the name and its trailing pieces
204
+ const parts = (dash < 0 ? text : text.slice(dash + 3)).split(' · ').map((s) => s.trim());
205
+ const name = dash < 0 ? parts.shift() : text.slice(0, dash);
206
+ const keep = dash < 0 ? 0 : 1; // the description is never a strategy or a meta piece
207
+ let target = false;
208
+ // "<strategy> → Inc 1": the arrows may be glued to the last piece with no " · " before them
209
+ const glued = parts.length > keep && !META.test(parts[parts.length - 1]) && parts[parts.length - 1].match(/(?:\s*→\s*(?:Inc\s*\d+|target|objetivo))+\s*$/);
210
+ if (glued) {
211
+ if (/target|objetivo/.test(glued[0])) target = true;
212
+ parts[parts.length - 1] = parts[parts.length - 1].slice(0, glued.index);
213
+ }
214
+ while (parts.length > keep && META.test(parts[parts.length - 1])) {
215
+ if (/→\s*(?:target|objetivo)/.test(parts[parts.length - 1])) target = true;
216
+ parts.pop();
217
+ }
218
+ const strategy = parts.length > keep ? parts.pop() : '';
219
+ return { name: plain(name), desc: plain(parts.join(' · ')), strategy: plain(strategy), target };
220
+ }
221
+
222
+ export function parseSlice(file) {
223
+ const base = path.basename(file, '.md');
224
+ const fm = base.match(/^(\d+)-(.+)$/);
225
+ if (!fm) throw new RenderError(file, 0, 'slice files are named <nn>-<name>.md');
226
+ const dir = path.join(path.dirname(file), base);
227
+ const slice = {
228
+ file,
229
+ base,
230
+ dir,
231
+ nn: parseInt(fm[1], 10),
232
+ status: 'open',
233
+ options: new Map(),
234
+ incs: [],
235
+ bites: [],
236
+ proposed: []
237
+ };
238
+
239
+ // ---- the index ----
240
+ let section = 'header';
241
+ let inc = null;
242
+ let fence = false;
243
+ read(file)
244
+ .split('\n')
245
+ .forEach((raw, i) => {
246
+ const n = i + 1;
247
+ let m;
248
+ if (/^```/.test(raw)) fence = !fence;
249
+ if (!fence && (m = raw.match(/^##\s+(.+?)\s*$/))) {
250
+ section = sectionName(m[1]);
251
+ inc = null;
252
+ return;
253
+ }
254
+ if (section === 'header' && (m = raw.match(/^-\s*Status:\s*(\w+)/))) slice.status = m[1].toLowerCase() === 'closed' ? 'done' : m[1].toLowerCase();
255
+
256
+ if (section === 'increments') {
257
+ if ((m = raw.match(/^###\s+Inc\s+(\d+)\s*(?:[—–:-]\s*)?(.*)$/))) {
258
+ const tags = [...m[2].matchAll(/\*\*\[([^\]]+)\]\*\*/g)].map((t) => t[1].trim());
259
+ const name = plain(m[2].replace(/\*\*\[[^\]]+\]\*\*/g, '')).replace(/\s+/g, ' ');
260
+ inc = { n: parseInt(m[1], 10), name, tags, outcome: '', bites: [], options: [], line: n };
261
+ if (slice.incs.some((x) => x.n === inc.n)) throw new RenderError(file, n, `Inc ${inc.n} appears twice`);
262
+ slice.incs.push(inc);
263
+ return;
264
+ }
265
+ if (/^###\s/.test(raw)) {
266
+ inc = null;
267
+ return;
268
+ }
269
+ if (inc && !fence) {
270
+ const clean = raw.replace(/<!--.*?-->/g, '');
271
+ if ((m = clean.match(/^-\s*Outcome:\s*(.*)$/))) inc.outcome = plain(m[1]);
272
+ else if ((m = clean.match(/^-\s*Bites:\s*(.*)$/))) inc.bites = m[1].match(BITE_ID) || [];
273
+ else if ((m = clean.match(/^-\s*Options:\s*(.*)$/))) inc.options = clean.match(OPTION_ID) || []; // an Inc with no bites: its options are drawn loose
274
+ }
275
+ }
276
+
277
+ if (section === 'backlog') {
278
+ // the proposed increments of `### Proposed increments`
279
+ if ((m = raw.match(/^\|\s*Inc\s+(\d+)\s*[—–:-]\s*(.+?)\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|\s*$/))) {
280
+ slice.proposed.push({ n: parseInt(m[1], 10), name: plain(m[2]), bites: m[3].match(BITE_ID) || [], gains: plain(m[4]), why: m[5], line: n });
281
+ }
282
+ // A bite line starts with its ID and a dot; older backlogs (flat option lists) have none and draw nothing.
283
+ if (/^\s*-\s+~?(?:\*\*)?F\d+-(?:[a-z]+|[dw]\d+)\s+·/.test(raw)) {
284
+ const b = raw.match(
285
+ /^\s*-\s+(~)?(?:\*\*)?(F\d+-(?:[a-z]+|[dw]\d+))\s+·\s+(.+?)(?:\*\*)?\s+\((skeleton|must-have|nice-to-have|deferred)(?::\s*([^)]*))?\)([^—]*?)\s+—\s+(.*)$/
286
+ );
287
+ if (!b) throw new RenderError(file, n, `not a bite line (expected "- **F1-a · <title>** (must-have) — F1-1.2 · depends on: … · value: … · check: …"): ${raw.trim().slice(0, 70)}`);
288
+ const [, , id, title, priority, reason, tail, rest] = b;
289
+ const taken = tail.match(/Inc\s*(\d+)/)?.[1]; // canonical "→ Inc n"; hand-edited slices vary
290
+ const parts = rest.split(' · ');
291
+ const fields = {};
292
+ for (const part of parts.slice(1)) {
293
+ const kv = part.match(/^(depends on|depende de|value|valor|check|comprobación):\s*(.*)$/);
294
+ if (kv) fields[FIELD_ALIASES[kv[1]] || kv[1]] = kv[2].trim();
295
+ }
296
+ if (slice.bites.some((x) => x.id === id)) throw new RenderError(file, n, `bite ${id} appears twice`);
297
+ slice.bites.push({
298
+ id,
299
+ title: plain(title),
300
+ priority,
301
+ reason: reason || '',
302
+ takenLine: taken ? parseInt(taken, 10) : null,
303
+ options: parts[0].match(OPTION_ID) || [],
304
+ dependsOn: fields['depends on'] || '',
305
+ value: fields.value || '',
306
+ check: fields.check || '',
307
+ line: n
308
+ });
309
+ }
310
+ }
311
+ });
312
+
313
+ // ---- slicing/F<k>.md: the Steps, the options (with what they say) and the User Task each belongs to ----
314
+ slice.steps = new Map(); // "F1-3" -> { f, n, name, kind, desc, note, ut }
315
+ const sdir = path.join(dir, 'slicing');
316
+ if (fs.existsSync(sdir)) {
317
+ for (const f of fs.readdirSync(sdir).filter((x) => x.endsWith('.md')).sort()) {
318
+ const sfile = path.join(sdir, f);
319
+ const code = f.match(/^(F\d+)/)?.[1] || null;
320
+ let currentUT = null;
321
+ read(sfile)
322
+ .split('\n')
323
+ .forEach((raw, i) => {
324
+ let m;
325
+ if ((m = raw.match(/^#{2,5}\s+User Task(?:\s+[\d.]+)?:\s*(.+?)\s*$/))) currentUT = plain(m[1]);
326
+ else if (code && (m = raw.match(/^\s*-\s+\*\*S(\d+)\s+(.+?)\*\*(?:\s+·\s+([A-Za-z]+))?(?:\s+—\s+(.*))?$/))) {
327
+ const [desc, note] = (m[4] || '').split(' · note: ');
328
+ slice.steps.set(`${code}-${m[1]}`, { f: code, n: parseInt(m[1], 10), name: plain(m[2]), kind: m[3] || '', desc: plain(desc), note: plain(note || ''), ut: currentUT });
329
+ } else if ((m = raw.match(/^\s*-\s+(F\d+-\d+\.\d+)\s+(.+?)(?:\s+—\s|$)/))) {
330
+ if (!currentUT) throw new RenderError(sfile, i + 1, `option ${m[1]} is not under a "### User Task:" heading`);
331
+ slice.options.set(m[1], { id: m[1], ut: currentUT, file: sfile, line: i + 1, ...optionTail(raw, m[1]) });
332
+ }
333
+ });
334
+ }
335
+ }
336
+
337
+ // ---- pruned.md: the options cut with a reason (they are gone from slicing/) ----
338
+ slice.pruned = [];
339
+ const pfile = path.join(dir, 'pruned.md');
340
+ if (fs.existsSync(pfile)) {
341
+ read(pfile)
342
+ .split('\n')
343
+ .forEach((raw, i) => {
344
+ const m = raw.match(/^\s*-\s+(F\d+-\d+\.\d+)\s+(.+?)\s+—\s+`(\w+)`:\s*(.*)$/);
345
+ if (m) slice.pruned.push({ id: m[1], name: plain(m[2]), cat: m[3], reason: m[4].trim(), file: pfile, line: i + 1 });
346
+ });
347
+ }
348
+
349
+ // ---- inc-<n>.md: State, Unknowns, scenarios, Pending and the body of each increment ----
350
+ for (const incRec of slice.incs) {
351
+ const ifile = path.join(dir, `inc-${incRec.n}.md`);
352
+ incRec.detailFile = fs.existsSync(ifile) ? ifile : null;
353
+ incRec.stateRaw = null;
354
+ incRec.stateLine = 0;
355
+ incRec.scenarios = [];
356
+ incRec.pending = [];
357
+ incRec.unknowns = '';
358
+ incRec.body = [];
359
+ if (!incRec.detailFile) continue;
360
+ const lines = read(ifile).split('\n');
361
+ incRec.body = lines.slice(1);
362
+ let sec = '';
363
+ let fenced = false;
364
+ lines.forEach((raw, i) => {
365
+ let m;
366
+ if (/^```/.test(raw)) fenced = !fenced;
367
+ if (!fenced && (m = raw.match(/^##\s+(.+?)\s*$/))) sec = sectionName(m[1]);
368
+ if (i < 12 && (m = raw.match(/^-\s*State:\s*(\S+)/))) {
369
+ incRec.stateRaw = m[1].toLowerCase();
370
+ incRec.stateLine = i + 1;
371
+ }
372
+ if (i < 12 && (m = raw.match(/^-\s*Unknowns:\s*(.*)$/))) incRec.unknowns = m[1].trim();
373
+ if ((m = raw.match(/^\s*Scenario(?: Outline)?:\s*(.+?)\s*$/))) incRec.scenarios.push(m[1]);
374
+ if (sec === 'pending' && !fenced && (m = raw.match(/^\s*-\s+(.*)$/))) incRec.pending.push(plain(m[1]));
375
+ });
376
+ }
377
+ return slice;
378
+ }
379
+
380
+
381
+ // ——— plan.md ———
382
+
383
+ export function parsePlan(file) {
384
+ const plan = { slices: new Map() };
385
+ if (!fs.existsSync(file)) return plan;
386
+ let slice = null;
387
+ let inc = null;
388
+ read(file).split('\n').forEach((raw) => {
389
+ let m;
390
+ if ((m = raw.match(/^##\s+Slice\s+(\d+)/))) {
391
+ slice = parseInt(m[1], 10);
392
+ if (!plan.slices.has(slice)) plan.slices.set(slice, new Map());
393
+ inc = null;
394
+ } else if ((m = raw.match(/^###\s+Inc\s+(\d+)/))) {
395
+ inc = parseInt(m[1], 10);
396
+ if (slice !== null) plan.slices.get(slice).set(inc, plan.slices.get(slice).get(inc) || []);
397
+ } else if (/^##\s/.test(raw)) {
398
+ slice = null;
399
+ inc = null;
400
+ } else if (slice !== null && inc !== null && (m = raw.match(/^\s*-\s+\[( |x|X)\]\s+(.*)$/))) {
401
+ plan.slices.get(slice).get(inc).push({ done: m[1] !== ' ', text: m[2].trim() });
402
+ }
403
+ });
404
+ return plan;
405
+ }
406
+
407
+ // ——— model ———
408
+
409
+ function stateOf(steps) {
410
+ if (!steps || steps.length === 0) return null;
411
+ const done = steps.filter((s) => s.done).length;
412
+ return { state: done === steps.length ? 'done' : done > 0 ? 'building' : 'planned', done, total: steps.length };
413
+ }
414
+
415
+ // The state of an increment: `State: done` in its inc-<n>.md (or a done slice) wins; otherwise the checked
416
+ // steps of its section in plan.md say planned / building / done; with no steps, its own State (default sliced).
417
+ function incState(slice, inc, steps) {
418
+ if (slice.status === 'done' || inc.stateRaw === 'done') return { state: 'done', done: 0, total: 0 };
419
+ const fromPlan = stateOf(steps);
420
+ if (fromPlan) return fromPlan;
421
+ return { state: inc.stateRaw === 'planned' ? 'planned' : 'sliced', done: 0, total: 0 };
422
+ }
423
+
424
+ export function buildModel(dir) {
425
+ const featuresFile = path.join(dir, 'features.md');
426
+ if (!fs.existsSync(featuresFile)) {
427
+ throw new RenderError(featuresFile, 0, 'not found — pass the initiative folder (<docs>/<slug>)');
428
+ }
429
+ const { initiative, features } = parseFeatures(featuresFile);
430
+ const tasks = features.flatMap((f) => f.tasks);
431
+ tasks.forEach((t, i) => {
432
+ t.col = i + 1;
433
+ });
434
+
435
+ const slicesDir = path.join(dir, 'slices');
436
+ const sliceFiles = fs.existsSync(slicesDir) ? fs.readdirSync(slicesDir).filter((f) => /^\d+-.+\.md$/.test(f)).sort() : [];
437
+ const slices = sliceFiles.map((f) => parseSlice(path.join(slicesDir, f))).sort((a, b) => a.nn - b.nn);
438
+ const planFile = path.join(dir, 'plan.md');
439
+ const plan = parsePlan(planFile);
440
+
441
+ const taskOf = (featureCode, ut) => (features.find((f) => f.code === featureCode)?.tasks || []).find((t) => norm(t.name) === norm(ut)) || null;
442
+ const issues = [];
443
+
444
+ for (const slice of slices) {
445
+ for (const opt of slice.options.values()) {
446
+ opt.feature = opt.id.match(/^(F\d+)-/)[1];
447
+ opt.task = taskOf(opt.feature, opt.ut);
448
+ if (!opt.task) throw new RenderError(opt.file, opt.line, `User Task "${opt.ut}" is not a User Task of ${opt.feature} in features.md`);
449
+ }
450
+ // the trace of the slice: its Steps in order, each with its live options and the ones pruned from it
451
+ const stepOf = (id) => id.replace(/\.\d+$/, '');
452
+ const trace = new Map();
453
+ const stepRec = (key, ut) => {
454
+ if (!trace.has(key)) {
455
+ const [f, n] = key.split('-');
456
+ const base = slice.steps.get(key) || { f, n: parseInt(n, 10), name: `Step ${n}`, kind: '', desc: '', note: '', ut };
457
+ const task = taskOf(f, base.ut);
458
+ if (!task && slice.steps.has(key)) issues.push({ file: slice.file, line: 0, text: `${slice.base}/slicing/${f}.md: Step S${n} is under User Task "${base.ut}", which is not a User Task of ${f} in features.md` });
459
+ trace.set(key, { ...base, task, options: [] });
460
+ }
461
+ return trace.get(key);
462
+ };
463
+ for (const key of slice.steps.keys()) stepRec(key);
464
+ for (const o of slice.options.values()) {
465
+ stepRec(stepOf(o.id), o.ut).options.push({ id: o.id, name: o.name, desc: o.desc, strategy: o.strategy, target: o.target, state: 'live' });
466
+ }
467
+ for (const p of slice.pruned) {
468
+ const st = trace.get(stepOf(p.id));
469
+ if (!st) {
470
+ if (slice.steps.size) issues.push({ file: p.file, line: p.line, text: `pruned option ${p.id} has no Step in ${slice.base}/slicing/` });
471
+ continue;
472
+ }
473
+ st.options.push({ id: p.id, name: p.name, cat: p.cat, reason: p.reason, state: 'pruned' });
474
+ }
475
+ const num = (id) => parseInt(id.match(/\.(\d+)$/)[1], 10);
476
+ for (const st of trace.values()) st.options.sort((a, b) => num(a.id) - num(b.id));
477
+ slice.trace = [...trace.values()].sort((a, b) => a.f.localeCompare(b.f, undefined, { numeric: true }) || a.n - b.n);
478
+
479
+ const byId = new Map(slice.bites.map((b) => [b.id, b]));
480
+ const optionOwner = new Map();
481
+ for (const bite of slice.bites) {
482
+ const first = slice.options.get(bite.options[0]);
483
+ if (!first) {
484
+ throw new RenderError(slice.file, bite.line, `bite ${bite.id}: its first option ${bite.options[0] || '(none)'} is not in ${slice.base}/slicing/`);
485
+ }
486
+ bite.feature = bite.id.match(/^(F\d+)-/)[1];
487
+ bite.task = first.task;
488
+ bite.resolved = bite.options.map((id) => {
489
+ const o = slice.options.get(id);
490
+ if (!o) issues.push({ file: slice.file, line: bite.line, text: `bite ${bite.id}: option ${id} is not in ${slice.base}/slicing/` });
491
+ if (optionOwner.has(id)) issues.push({ file: slice.file, line: bite.line, text: `option ${id} is in two bites (${optionOwner.get(id)} and ${bite.id})` });
492
+ optionOwner.set(id, bite.id);
493
+ return { id, name: o ? o.name : '(not in the slicing)', task: o ? o.task : null };
494
+ });
495
+ const others = [...new Set(bite.resolved.map((o) => o.task).filter(Boolean))].filter((t) => t.id !== bite.task.id);
496
+ bite.others = others;
497
+ }
498
+ const taker = new Map();
499
+ for (const inc of slice.incs) {
500
+ for (const id of inc.bites) {
501
+ if (!byId.has(id)) throw new RenderError(slice.file, inc.line, `Inc ${inc.n}: bite ${id} has no line in ## Backlog`);
502
+ if (taker.has(id)) issues.push({ file: slice.file, line: inc.line, text: `bite ${id} is taken by Inc ${taker.get(id)} and Inc ${inc.n}` });
503
+ taker.set(id, inc.n);
504
+ }
505
+ if (inc.bites.length === 0 && inc.options.length === 0 && inc.tags.length === 0) {
506
+ throw new RenderError(slice.file, inc.line, `Inc ${inc.n} has no Bites: line (every Inc is made of bites; the skeleton ones are F<n>-w<k>)`);
507
+ }
508
+ for (const id of inc.options) {
509
+ if (!slice.options.has(id)) issues.push({ file: slice.file, line: inc.line, text: `Inc ${inc.n}: option ${id} is not in ${slice.base}/slicing/` });
510
+ }
511
+ const steps = plan.slices.get(slice.nn)?.get(inc.n) || null;
512
+ inc.steps = steps;
513
+ inc.st = incState(slice, inc, steps);
514
+ if (!inc.detailFile) issues.push({ file: slice.file, line: inc.line, text: `Inc ${inc.n} has no ${slice.base}/inc-${inc.n}.md` });
515
+ else if (inc.stateRaw === null) issues.push({ file: inc.detailFile, line: 1, text: 'no "- State:" line in the first lines' });
516
+ else if (!INC_STATES.includes(inc.stateRaw)) issues.push({ file: inc.detailFile, line: inc.stateLine, text: `unknown State "${inc.stateRaw}" (sliced | planned | done)` });
517
+ if (steps && steps.length && inc.stateRaw === 'done') issues.push({ file: planFile, line: 0, text: `Slice ${slice.nn} · Inc ${inc.n} is done but still has a section in plan.md — delete it` });
518
+ if (steps && steps.length && steps.every((s) => s.done) && inc.stateRaw !== 'done') issues.push({ file: inc.detailFile || slice.file, line: inc.stateLine || inc.line, text: `every step of Inc ${inc.n} is checked: set "- State: done" and clean its section of plan.md` });
519
+ }
520
+ for (const bite of slice.bites) {
521
+ bite.takenBy = taker.get(bite.id) ?? bite.takenLine ?? null;
522
+ if (bite.takenLine !== null && taker.has(bite.id) && taker.get(bite.id) !== bite.takenLine) {
523
+ issues.push({ file: slice.file, line: bite.line, text: `bite ${bite.id} says → Inc ${bite.takenLine} but Inc ${taker.get(bite.id)} lists it` });
524
+ }
525
+ if (bite.takenLine !== null && !slice.incs.some((i) => i.n === bite.takenLine)) {
526
+ issues.push({ file: slice.file, line: bite.line, text: `bite ${bite.id} says → Inc ${bite.takenLine}, which is not in ## Increments` });
527
+ }
528
+ }
529
+ slice.proposed = slice.proposed.filter((p) => !slice.incs.some((i) => i.n === p.n));
530
+ for (const p of slice.proposed) {
531
+ for (const id of p.bites) {
532
+ const b = byId.get(id);
533
+ if (b && b.takenBy === null) b.proposedInc = p.n;
534
+ }
535
+ }
536
+ // the tasks each Inc touches
537
+ for (const inc of slice.incs) {
538
+ const ofBites = inc.bites.map((id) => byId.get(id));
539
+ inc.biteRecs = ofBites;
540
+ const opts = [];
541
+ const seen = new Set();
542
+ for (const b of ofBites) for (const o of b.resolved) if (!seen.has(o.id)) (seen.add(o.id), opts.push(o));
543
+ for (const id of inc.options) {
544
+ if (seen.has(id)) continue;
545
+ const o = slice.options.get(id);
546
+ seen.add(id);
547
+ opts.push({ id, name: o ? o.name : '(not in the slicing)', task: o ? o.task : null });
548
+ }
549
+ inc.resolvedOptions = opts;
550
+ const fromTags = [];
551
+ if (ofBites.length === 0 && opts.length === 0) {
552
+ // the oldest slices only name the User Tasks, as **[User Task]** tags of the Inc heading
553
+ for (const tag of inc.tags) {
554
+ const task = tasks.find((x) => norm(x.name) === norm(tag));
555
+ if (!task) throw new RenderError(slice.file, inc.line, `Inc ${inc.n}: User Task "${tag}" is not in features.md`);
556
+ fromTags.push(task);
557
+ }
558
+ }
559
+ const ids = new Set([...ofBites.flatMap((b) => [b.task, ...b.others]), ...opts.map((o) => o.task), ...fromTags].filter(Boolean).map((t) => t.id));
560
+ inc.taskIds = [...ids];
561
+ }
562
+ }
563
+ return { initiative, features, tasks, slices, plan, issues, planFile };
564
+ }
565
+
566
+ // ——— data for the page ———
567
+
568
+ const sliceName = (base) => base.replace(/^\d+-/, '');
569
+
570
+ function dataOf(model, lang, date) {
571
+ const { features, slices, plan } = model;
572
+ const out = {
573
+ lang,
574
+ date,
575
+ initiative: model.initiative || '',
576
+ next: nextStep(model),
577
+ features: features.map((f) => ({
578
+ code: f.code,
579
+ id: f.id,
580
+ name: f.name,
581
+ systemTasks: f.systemTasks,
582
+ tasks: f.tasks.map((t) => ({ id: t.id, name: t.name, desc: t.description }))
583
+ })),
584
+ slices: []
585
+ };
586
+ for (const s of slices) {
587
+ const k = (id) => `${s.nn}-${id}`;
588
+ const sl = {
589
+ nn: s.nn,
590
+ name: sliceName(s.base),
591
+ base: s.base,
592
+ status: s.status,
593
+ incs: [],
594
+ bites: [],
595
+ trace: s.trace.map((st) => ({ f: st.f, n: st.n, name: st.name, kind: st.kind, desc: st.desc, note: st.note, task: st.task ? st.task.id : null, options: st.options }))
596
+ };
597
+ for (const b of s.bites) {
598
+ sl.bites.push({
599
+ key: k(b.id),
600
+ id: b.id,
601
+ title: b.title,
602
+ priority: b.priority,
603
+ reason: b.reason,
604
+ taken: b.takenBy,
605
+ proposedInc: b.proposedInc || null,
606
+ value: b.value,
607
+ check: b.check,
608
+ dependsOn: b.dependsOn,
609
+ options: b.resolved.map((o) => ({ id: o.id, name: o.name, task: o.task ? o.task.id : null })),
610
+ anchor: b.task.id,
611
+ others: b.others.map((t) => t.id),
612
+ feature: b.feature,
613
+ source: `slices/${s.base}.md:${b.line}`
614
+ });
615
+ }
616
+ for (const i of s.incs) {
617
+ sl.incs.push({
618
+ key: `${s.nn}-${i.n}`,
619
+ n: i.n,
620
+ name: i.name,
621
+ outcome: i.outcome || i.name,
622
+ state: i.st.state,
623
+ progress: i.st.total ? `${i.st.done}/${i.st.total}` : '',
624
+ scenarios: i.scenarios.length,
625
+ bites: i.bites.map(k),
626
+ options: i.resolvedOptions.map((o) => ({ id: o.id, name: o.name, task: o.task ? o.task.id : null })),
627
+ tasks: i.taskIds,
628
+ unknowns: i.unknowns,
629
+ pending: i.pending,
630
+ body: markdown(i.body),
631
+ source: i.detailFile ? `slices/${s.base}/inc-${i.n}.md` : `slices/${s.base}.md:${i.line}`,
632
+ proposed: false
633
+ });
634
+ }
635
+ for (const p of s.proposed) {
636
+ sl.incs.push({
637
+ key: `${s.nn}-${p.n}`,
638
+ n: p.n,
639
+ name: p.name,
640
+ outcome: p.gains,
641
+ state: 'proposed',
642
+ progress: '',
643
+ scenarios: 0,
644
+ bites: p.bites.map(k),
645
+ options: [],
646
+ tasks: [],
647
+ unknowns: '',
648
+ pending: [],
649
+ body: p.why ? `<p><b>Why this order:</b> ${inline(p.why)}</p>` : '',
650
+ source: `slices/${s.base}.md:${p.line} (## Backlog › Proposed increments)`,
651
+ proposed: true
652
+ });
653
+ }
654
+ out.slices.push(sl);
655
+ }
656
+ return out;
657
+ }
658
+
659
+ function nextStep(model) {
660
+ for (const slice of model.slices) {
661
+ if (slice.status !== 'open') continue;
662
+ const sections = model.plan.slices.get(slice.nn);
663
+ if (!sections) continue;
664
+ for (const steps of sections.values()) {
665
+ const open = steps.find((s) => !s.done);
666
+ if (open) return { text: `${open.text.replace(/`/g, '')} — ${slice.base}`, link: 'plan.md' };
667
+ }
668
+ }
669
+ return null;
670
+ }
671
+
672
+ function counts(model) {
673
+ let incTotal = 0;
674
+ let incDone = 0;
675
+ let stepTotal = 0;
676
+ let stepDone = 0;
677
+ let bitesLeft = 0;
678
+ for (const s of model.slices) {
679
+ for (const i of s.incs) {
680
+ incTotal += 1;
681
+ if (i.st.state === 'done') incDone += 1;
682
+ stepTotal += i.st.total;
683
+ stepDone += i.st.done;
684
+ }
685
+ bitesLeft += s.bites.filter((b) => b.takenBy === null).length;
686
+ }
687
+ return { incTotal, incDone, stepTotal, stepDone, bitesLeft };
688
+ }
689
+
690
+ export function render(dir, { lang = 'en', date = new Date().toISOString().slice(0, 10) } = {}) {
691
+ const model = buildModel(dir);
692
+ const c = counts(model);
693
+ const title = `${model.initiative || path.basename(path.resolve(dir))} — Story Map`;
694
+ const json = JSON.stringify(dataOf(model, lang, date))
695
+ .replace(/</g, '\\u003c')
696
+ .replace(/\u2028/g, '\\u2028')
697
+ .replace(/\u2029/g, '\\u2029');
698
+ const values = { LANG: esc(lang), TITLE: esc(title), DATA: json };
699
+ const html = fs.readFileSync(TEMPLATE, 'utf8').replace(/\{\{(\w+)\}\}/g, (_, key) => String(values[key] ?? ''));
700
+ return {
701
+ html,
702
+ summary: `story-map.html updated (${c.incDone}/${c.incTotal} increments, ${c.stepDone}/${c.stepTotal} steps, ${c.bitesLeft} bites left)`
703
+ };
704
+ }
705
+
706
+ // Everything the parser can say about the markdown, without writing anything.
707
+ export function check(dir) {
708
+ let model;
709
+ try {
710
+ model = buildModel(dir);
711
+ } catch (err) {
712
+ if (!(err instanceof RenderError)) throw err;
713
+ return { problems: [{ file: err.file, line: err.line, text: err.reason }], summary: '' };
714
+ }
715
+ const bites = model.slices.reduce((n, s) => n + s.bites.length, 0);
716
+ const incs = model.slices.reduce((n, s) => n + s.incs.length, 0);
717
+ return {
718
+ problems: model.issues,
719
+ summary: `ok — ${model.features.length} Features, ${model.slices.length} slices, ${incs} increments, ${bites} bites`
720
+ };
721
+ }
722
+
723
+ function storyMapEnabled(dir) {
724
+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {
725
+ const config = path.join(d, '.bokata.json');
726
+ if (fs.existsSync(config)) {
727
+ try {
728
+ return JSON.parse(fs.readFileSync(config, 'utf8')).story_map !== false;
729
+ } catch {
730
+ return true;
731
+ }
732
+ }
733
+ if (path.dirname(d) === d) return true;
734
+ }
735
+ }
736
+
737
+ const USAGE = 'Usage: render.mjs <initiative-dir> [--lang en|es] [--date YYYY-MM-DD] [--out file] [--check]';
738
+
739
+ export function main(argv) {
740
+ const args = { dir: null, lang: 'en', date: undefined, out: null, check: false };
741
+ for (let i = 0; i < argv.length; i++) {
742
+ const a = argv[i];
743
+ if (a === '--lang') args.lang = argv[++i];
744
+ else if (a === '--date') args.date = argv[++i];
745
+ else if (a === '--out') args.out = argv[++i];
746
+ else if (a === '--check') args.check = true;
747
+ else if (a === '-h' || a === '--help') {
748
+ console.log(USAGE);
749
+ return 0;
750
+ } else if (a.startsWith('-')) {
751
+ console.error(`unknown option "${a}"`);
752
+ return 1;
753
+ } else args.dir = a;
754
+ }
755
+ if (!args.dir) {
756
+ console.error(USAGE);
757
+ return 1;
758
+ }
759
+ if (args.check) {
760
+ const { problems, summary } = check(args.dir);
761
+ for (const p of problems) console.error(`✖ ${p.file}${p.line ? `:${p.line}` : ''}: ${p.text}`);
762
+ if (problems.length) return 1;
763
+ console.log(summary);
764
+ return 0;
765
+ }
766
+ if (!storyMapEnabled(args.dir)) {
767
+ console.log('story map disabled (.bokata.json: "story_map": false) — nothing rendered');
768
+ return 0;
769
+ }
770
+ try {
771
+ const { html, summary } = render(args.dir, { lang: args.lang, ...(args.date ? { date: args.date } : {}) });
772
+ fs.writeFileSync(args.out || path.join(args.dir, 'story-map.html'), html);
773
+ console.log(summary);
774
+ return 0;
775
+ } catch (err) {
776
+ if (!(err instanceof RenderError)) throw err;
777
+ console.error(`✖ ${err.message}`);
778
+ return 1;
779
+ }
780
+ }
781
+
782
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
783
+ process.exitCode = main(process.argv.slice(2));
784
+ }