agentic-mobile-kit 0.7.19 → 0.14.1

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 (69) hide show
  1. package/README.md +18 -3
  2. package/bin/cli.js +5 -3
  3. package/lib/doctor.js +31 -5
  4. package/lib/init.js +21 -25
  5. package/lib/menu.js +3 -3
  6. package/package.json +1 -1
  7. package/stacks/react-native/expo/.eas/workflows/pr-preview.yml +54 -0
  8. package/stacks/react-native/expo/AGENTS.md +30 -17
  9. package/stacks/react-native/expo/docs/amk/expo.md +11 -1
  10. package/stacks/react-native/template/.agents/skills/m-bugfix/SKILL.md +8 -5
  11. package/stacks/react-native/template/.agents/skills/m-change/SKILL.md +3 -2
  12. package/stacks/react-native/template/.agents/skills/m-continue/SKILL.md +6 -4
  13. package/stacks/react-native/template/.agents/skills/m-explore/SKILL.md +1 -1
  14. package/stacks/react-native/template/.agents/skills/m-feature/SKILL.md +29 -26
  15. package/stacks/react-native/template/.agents/skills/m-feature/build.md +35 -0
  16. package/stacks/react-native/template/.agents/skills/m-feature/plan.md +43 -0
  17. package/stacks/react-native/template/.agents/skills/m-learn/SKILL.md +3 -1
  18. package/stacks/react-native/template/.agents/skills/m-onboard/SKILL.md +3 -1
  19. package/stacks/react-native/template/.agents/skills/m-pause/SKILL.md +2 -0
  20. package/stacks/react-native/template/.agents/skills/m-prototype/SKILL.md +1 -1
  21. package/stacks/react-native/template/.agents/skills/m-release/SKILL.md +5 -4
  22. package/stacks/react-native/template/.agents/skills/m-report/SKILL.md +25 -0
  23. package/stacks/react-native/template/.agents/skills/m-review/SKILL.md +4 -3
  24. package/stacks/react-native/template/.agents/skills/m-test/SKILL.md +24 -0
  25. package/stacks/react-native/template/.agents/skills/m-test/agents/openai.yaml +3 -0
  26. package/stacks/react-native/template/.githooks/pre-commit +12 -0
  27. package/stacks/react-native/template/.github/pull_request_template.md +4 -0
  28. package/stacks/react-native/template/.github/workflows/amk-ai-deps.yml +90 -0
  29. package/stacks/react-native/template/.github/workflows/amk-ai-review.yml +82 -0
  30. package/stacks/react-native/template/.github/workflows/amk-kit-update.yml +95 -0
  31. package/stacks/react-native/template/.github/workflows/amk-ready.yml +39 -0
  32. package/stacks/react-native/template/.github/workflows/ci.yml +79 -13
  33. package/stacks/react-native/template/.github/workflows/e2e.yml +10 -1
  34. package/stacks/react-native/template/.rulesync/hooks.jsonc +3 -1
  35. package/stacks/react-native/template/.rulesync/subagents/m-device-checker.md +2 -1
  36. package/stacks/react-native/template/.rulesync/subagents/m-reviewer.md +4 -2
  37. package/stacks/react-native/template/.rulesync/subagents/m-spec-writer.md +15 -0
  38. package/stacks/react-native/template/.rulesync/subagents/m-tester.md +23 -0
  39. package/stacks/react-native/template/AGENTS.md +23 -10
  40. package/stacks/react-native/template/codemagic.yaml +82 -1
  41. package/stacks/react-native/template/docs/amk/codemagic.md +8 -0
  42. package/stacks/react-native/template/docs/amk/react-native.md +11 -1
  43. package/stacks/react-native/template/docs/amk/team-process.md +33 -1
  44. package/stacks/react-native/template/rulesync.jsonc +1 -1
  45. package/stacks/react-native/template/scripts/amk/ai-job.js +106 -0
  46. package/stacks/react-native/template/scripts/amk/autopilot.js +837 -0
  47. package/stacks/react-native/template/scripts/amk/baseline.js +19 -7
  48. package/stacks/react-native/template/scripts/amk/ci-scope.js +59 -0
  49. package/stacks/react-native/template/scripts/amk/coverage.js +111 -0
  50. package/stacks/react-native/template/scripts/amk/guard.js +42 -0
  51. package/stacks/react-native/template/scripts/amk/handoff-check.js +87 -14
  52. package/stacks/react-native/template/scripts/amk/issue.js +31 -0
  53. package/stacks/react-native/template/scripts/amk/metrics.js +164 -0
  54. package/stacks/react-native/template/scripts/amk/pr.js +244 -0
  55. package/stacks/react-native/template/scripts/amk/redact.js +57 -0
  56. package/stacks/react-native/template/scripts/amk/release-build.sh +14 -0
  57. package/stacks/react-native/template/scripts/amk/report.js +48 -11
  58. package/stacks/react-native/template/scripts/amk/rn-check.js +195 -47
  59. package/stacks/react-native/template/scripts/amk/shots.js +131 -0
  60. package/stacks/react-native/template/scripts/amk/specs.js +717 -34
  61. package/stacks/react-native/template/scripts/amk/tool-configs.js +41 -0
  62. package/stacks/react-native/template/scripts/amk/verify.sh +127 -23
  63. package/stacks/react-native/template/specs/_templates/design.md +22 -0
  64. package/stacks/react-native/template/specs/_templates/flow.yaml +2 -1
  65. package/stacks/react-native/template/specs/_templates/plan.md +54 -0
  66. package/stacks/react-native/template/specs/_templates/progress.md +1 -1
  67. package/stacks/react-native/template/specs/_templates/requirements.md +40 -0
  68. package/stacks/react-native/template/specs/_templates/test-report.md +25 -0
  69. package/stacks/react-native/template/.github/workflows/ios.yml +0 -41
@@ -1,19 +1,96 @@
1
1
  #!/usr/bin/env node
2
- // Specs: check their format, fold a finished feature into the living spec, and show progress.
2
+ // Specs: check their format, fold a finished feature into the living spec, find a change's tests, and show progress.
3
3
  // node scripts/amk/specs.js check [--skip-drafts] [files…] format of specs/<id>/requirements.md and specs/current/*.md
4
4
  // (default: all; --skip-drafts leaves out specs whose work hasn't started)
5
5
  // node scripts/amk/specs.js merge <id> apply specs/<id>/requirements.md's ADDED/MODIFIED/REMOVED sections to specs/current/
6
- // node scripts/amk/specs.js status each spec's status and task progress, and the living spec's size
6
+ // node scripts/amk/specs.js tests [<id>] the tests of the areas <id> changes (every area, for a release): the specs and
7
+ // flows behind them, what to change or retire, scenarios with no check, flows
8
+ // no spec links to, and the verify.sh command that runs them
9
+ // node scripts/amk/specs.js flow <id> write .maestro/<id>.yaml with a "# Scenario" block for each scenario; with a
10
+ // flow already there, list the blocks it's missing instead
11
+ // node scripts/amk/specs.js status each spec's status and task progress, the living spec's size, and the plan's
12
+ // features (specs/plan.md on the plan branch): where each stands, and sizes
13
+ // node scripts/amk/specs.js check --plan the plan: its features table, each planned spec, and what they get wrong
14
+ // together (a requirement added twice, a missing dependency, a loop, …)
15
+ // node scripts/amk/specs.js plan-folder a second folder of this repository on the plan branch, to plan in while a
16
+ // build runs here, with the kit's files git doesn't track copied in
17
+ // node scripts/amk/specs.js start [<id>] build a planned feature: the next ready one (approved, not taken, its
18
+ // dependencies built or on the build's stack), or <id>. Makes feature/<id>
19
+ // from main or the top of the stack, with the spec as of its approval commit.
20
+ // Exits 3 when none is ready, 4 when the living spec changed under it
21
+ // node scripts/amk/specs.js import <file> a CSV export (a spreadsheet saved as CSV) or a Trello board's JSON export,
22
+ // a line per row or open card, as outside text to plan from
7
23
  // A requirement is "### Requirement: <name>", a sentence with SHALL or MUST, and at least one
8
24
  // "#### Scenario: <case>" with WHEN and THEN. Changes are "## ADDED Requirements: <area>" (and MODIFIED, REMOVED),
9
- // where <area> names the file specs/current/<area>.md. Format: specs/current/README.md.
25
+ // where <area> names the file specs/current/<area>.md. User stories and use cases, when a spec has them, name its
26
+ // requirements and scenarios. Format: specs/current/README.md and specs/_templates/requirements.md.
10
27
  'use strict';
11
28
  const fs = require('fs');
29
+ const os = require('os');
12
30
  const path = require('path');
31
+ const { execFileSync, spawnSync } = require('child_process');
13
32
 
14
33
  const [cmd, ...args] = process.argv.slice(2);
15
34
  const read = f => { try { return fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n'); } catch { return null; } };
16
35
  const key = name => name.trim().toLowerCase();
36
+ const bare = s => s.trim().replace(/^["'`*_]+|["'`*_.]+$/g, '').trim();
37
+
38
+ // ---------- scenarios, and the flow blocks that check them (rn-check.js uses these too) ----------
39
+ const norm = s => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
40
+ // two names of the same scenario: one holds the other, whatever the case and punctuation
41
+ const same = (a, b) => { a = norm(a || ''); b = norm(b || ''); return Boolean(a && b) && (a.includes(b) || b.includes(a)); };
42
+ // a flow without its comments (each comment character a space, so positions stay): # outside quotes starts one
43
+ function stripYamlComments(text) {
44
+ return text.split('\n').map(l => {
45
+ let quote = null;
46
+ for (let i = 0; i < l.length; i++) {
47
+ const c = l[i];
48
+ if (quote) { if (c === quote) quote = null; } else if (c === '"' || c === "'") quote = c;
49
+ else if (c === '#' && (i === 0 || /\s/.test(l[i - 1]))) return l.slice(0, i) + ' '.repeat(l.length - i);
50
+ }
51
+ return l;
52
+ }).join('\n');
53
+ }
54
+ // a spec's "#### Scenario: <name>" headings in order: number, name, line, and its steps (GIVEN, WHEN, THEN)
55
+ function scenarios(text) {
56
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
57
+ const out = [];
58
+ for (let i = 0; i < lines.length; i++) {
59
+ const m = /^#### Scenario:\s*(.*)$/.exec(lines[i]);
60
+ if (!m) continue;
61
+ const steps = [];
62
+ for (let j = i + 1; j < lines.length && !/^#{1,4} /.test(lines[j]); j++) if (lines[j].trim()) steps.push(lines[j].trim().replace(/^[-*]\s*/, ''));
63
+ out.push({ n: out.length + 1, name: m[1].trim(), line: i + 1, steps });
64
+ }
65
+ return out;
66
+ }
67
+ // a flow's "# Scenario <n>: <name>" blocks: number (0 without one), name, line, and its steps without comments
68
+ function flowBlocks(text) {
69
+ text = text.replace(/\r\n/g, '\n');
70
+ const code = stripYamlComments(text).split('\n');
71
+ const out = [];
72
+ text.split('\n').forEach((l, i) => {
73
+ const m = /^\s*#\s*Scenario\b\s*(\d+)?\s*[:.)-]?\s*(.*)$/i.exec(l);
74
+ if (m) out.push({ n: Number(m[1]) || 0, name: m[2].trim(), line: i + 1, code: '' });
75
+ else if (out.length) out[out.length - 1].code += `${code[i]}\n`;
76
+ });
77
+ return out;
78
+ }
79
+ // the block that checks scenario n (its number in its own spec) named name: by number, else by name
80
+ const blockFor = (bs, n, name) => (n && bs.find(b => b.n === n)) || bs.find(b => same(b.name, name));
81
+ // the flows verify.sh runs (not the copies it makes for a moment, .amk-*), and a spec's: those named <id>…
82
+ const allFlows = (dir = '.maestro') => (fs.existsSync(dir) ? fs.readdirSync(dir).filter(f => /\.ya?ml$/.test(f) && !f.startsWith('.amk-')).sort() : []);
83
+ const flowsOf = (id, flows) => flows.filter(f => f.toLowerCase().startsWith(id.toLowerCase()));
84
+ // a flow's tags, from its header: tags: [smoke, login], or one a line below tags:
85
+ function tagsOf(text) {
86
+ const head = text.replace(/\r\n/g, '\n').split(/^---\s*$/m)[0].split('\n');
87
+ const at = head.findIndex(l => /^tags\s*:/.test(l));
88
+ if (at < 0) return [];
89
+ const inline = head[at].replace(/^tags\s*:/, '').trim();
90
+ const below = [];
91
+ for (let i = at + 1; i < head.length && /^\s+-\s*\S/.test(head[i]); i++) below.push(head[i].replace(/^\s+-\s*/, ''));
92
+ return (inline ? inline.replace(/^\[|\]$/g, '').split(',') : below).map(s => s.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
93
+ }
17
94
 
18
95
  // "### Requirement:" blocks between lines [from, to): each runs to the next heading of level 1-3
19
96
  function blocks(lines, from = 0, to = lines.length) {
@@ -49,7 +126,9 @@ function blockProblems(b) {
49
126
  return p;
50
127
  }
51
128
 
52
- // the ADDED/MODIFIED/REMOVED sections of a feature's requirements.md
129
+ // the template's own placeholders, left as they are until the requirements are written: "<area>", "<name>"
130
+ const placeholder = t => /^<[^>]*>$/.test(t.trim());
131
+ // the ADDED/MODIFIED/REMOVED sections of a feature's requirements.md (a section the template left untouched is none yet)
53
132
  function deltas(text) {
54
133
  const lines = text.split('\n');
55
134
  const sections = [];
@@ -58,23 +137,26 @@ function deltas(text) {
58
137
  for (let i = 0; i < lines.length; i++) {
59
138
  const h = /^## (ADDED|MODIFIED|REMOVED) Requirements\b(.*)$/.exec(lines[i]);
60
139
  if (!h) continue;
61
- const area = (/^:\s*([a-z0-9][a-z0-9-]*)\s*$/.exec(h[2]) || [])[1];
62
- if (!area) problems.push(`line ${i + 1}: name the area, e.g. "## ${h[1]} Requirements: login" (the file specs/current/login.md)`);
140
+ const named = (/^:\s*(.*?)\s*$/.exec(h[2]) || [])[1] || '';
141
+ const area = (/^([a-z0-9][a-z0-9-]*)$/.exec(named) || [])[1];
63
142
  let j = i + 1;
64
143
  while (j < lines.length && !/^#{1,2} /.test(lines[j])) j++;
65
- const bs = blocks(lines, i + 1, j);
66
- bs.forEach(b => inSection.add(b.start));
67
- sections.push({ op: h[1], area, blocks: bs });
144
+ const all = blocks(lines, i + 1, j);
145
+ all.forEach(b => inSection.add(b.start));
146
+ const bs = all.filter(b => !placeholder(b.name));
147
+ if (!(placeholder(named) && !bs.length)) {
148
+ if (!area) problems.push(`line ${i + 1}: name the area, e.g. "## ${h[1]} Requirements: login" (the file specs/current/login.md)`);
149
+ sections.push({ op: h[1], area, blocks: bs });
150
+ }
68
151
  i = j - 1;
69
152
  }
70
153
  for (const b of blocks(lines)) {
71
- if (!inSection.has(b.start)) problems.push(`line ${b.line}: "${b.name}" isn't under an "## ADDED/MODIFIED/REMOVED Requirements: <area>" heading`);
154
+ if (!inSection.has(b.start) && !placeholder(b.name)) problems.push(`line ${b.line}: "${b.name}" isn't under an "## ADDED/MODIFIED/REMOVED Requirements: <area>" heading`);
72
155
  }
73
156
  return { lines, sections, problems };
74
157
  }
75
158
 
76
- function checkFile(file) {
77
- const text = read(file);
159
+ function checkFile(file, text = read(file)) {
78
160
  if (text === null) return [`${file}: not found`];
79
161
  const problems = [];
80
162
  const where = (b, p) => `${file}:${b.line} "${b.name}": ${p}`;
@@ -97,14 +179,75 @@ function checkFile(file) {
97
179
  seen.add(key(b.name));
98
180
  }
99
181
  }
182
+ storyProblems(text, d).forEach(p => problems.push(`${file}: ${p}`));
100
183
  return problems;
101
184
  }
102
185
 
186
+ // the "### US-<n>" (or UC-<n>) entries under "## <heading>", each with its text; null without the section
187
+ function entries(lines, heading, prefix) {
188
+ const at = lines.findIndex(l => l.trim().toLowerCase() === `## ${heading.toLowerCase()}`);
189
+ if (at < 0) return null;
190
+ const out = [];
191
+ for (let i = at + 1; i < lines.length && !/^#{1,2} /.test(lines[i]); i++) {
192
+ const m = new RegExp(`^### (${prefix}-\\d+)\\b`, 'i').exec(lines[i]);
193
+ if (m) out.push({ id: m[1].toUpperCase(), line: i + 1, text: '' });
194
+ else if (out.length) out[out.length - 1].text += `${lines[i]}\n`;
195
+ }
196
+ return out;
197
+ }
198
+
199
+ // the names after "- <label>:" in an entry ("- Requirements: a, b; c"), where a known name may hold a comma itself
200
+ function listed(text, label, known) {
201
+ let s = (new RegExp(`^\\s*-?\\s*${label}:(.*)$`, 'im').exec(text) || ['', ''])[1];
202
+ const long = [...known.values()].filter(n => /[,;]/.test(n));
203
+ long.forEach((n, i) => { s = s.split(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')).join(`\0${i}\0`); });
204
+ // the template's placeholder, or a note in brackets ("(written with the requirements)"), names none
205
+ return s.split(/[,;]/).map(x => bare(x.replace(/\0(\d+)\0/g, (_, i) => long[i]))).filter(n => n && !/^[<(].*[>)]$/.test(n));
206
+ }
207
+
208
+ // user stories and use cases, when a spec has them: each story is its sentence and names requirements of this spec,
209
+ // each ADDED or MODIFIED requirement is in a story, and a use case's stories and scenarios exist. An empty list is fine:
210
+ // a plan approves stories before their requirements are written
211
+ function storyProblems(text, d) {
212
+ // the template's guidance is in HTML comments: left out, keeping the line numbers
213
+ const lines = text.replace(/<!--[\s\S]*?-->/g, c => c.replace(/[^\n]/g, '')).split('\n');
214
+ const stories = entries(lines, 'User stories', 'US');
215
+ const cases = entries(lines, 'Use cases', 'UC');
216
+ const p = [];
217
+ const known = new Map(d.sections.flatMap(s => s.blocks).map(b => [key(b.name), b.name]));
218
+ const linked = new Set();
219
+ for (const s of stories || []) {
220
+ if (!/\bAs an?\b/i.test(s.text) || !/\bI want\b/i.test(s.text) || !/\bso that\b/i.test(s.text)) p.push(`line ${s.line}: ${s.id} needs its sentence: "As a <user>, I want <capability>, so that <benefit>."`);
221
+ for (const n of listed(s.text, 'Requirements', known)) {
222
+ if (known.has(key(n))) linked.add(key(n));
223
+ else p.push(`line ${s.line}: ${s.id} names "${n}", which isn't a requirement in this spec`);
224
+ }
225
+ }
226
+ for (const b of stories ? d.sections.filter(s => s.op !== 'REMOVED').flatMap(s => s.blocks) : []) {
227
+ if (!linked.has(key(b.name))) p.push(`line ${b.line}: "${b.name}" is in no user story: name it in a story's Requirements line`);
228
+ }
229
+ const ids = new Set((stories || []).map(s => s.id));
230
+ const names = scenarios(text).map(s => norm(s.name));
231
+ for (const c of cases || []) {
232
+ for (const id of (/^\s*-?\s*Stories:(.*)$/im.exec(c.text) || ['', ''])[1].match(/\bUS-\d+\b/gi) || []) {
233
+ if (!ids.has(id.toUpperCase())) p.push(`line ${c.line}: ${c.id} names ${id}, which isn't a story in this spec`);
234
+ }
235
+ // one a line, or several: "3a. … → Scenario: <name>; 4a. …" or "… → Scenario: <name>. 4a. …"
236
+ for (const m of c.text.matchAll(/\bScenario:\s*(.+?)(?=\s*(?:;|$|\.?\s+\d+[a-z]\.\s))/gm)) {
237
+ const n = bare(m[1]);
238
+ if (n && !/^[<(].*[>)]$/.test(n) && !names.includes(norm(n))) p.push(`line ${c.line}: ${c.id} names the scenario "${n}", which isn't in this spec`);
239
+ }
240
+ }
241
+ return p;
242
+ }
243
+
244
+ // the feature specs' folders: specs/<id>/
245
+ const specDirs = () => (fs.existsSync('specs') ? fs.readdirSync('specs', { withFileTypes: true })
246
+ .filter(e => e.isDirectory() && !['_templates', 'current'].includes(e.name)).map(e => e.name) : []);
247
+
103
248
  function allSpecFiles() {
104
249
  if (!fs.existsSync('specs')) return [];
105
- const features = fs.readdirSync('specs', { withFileTypes: true })
106
- .filter(e => e.isDirectory() && !['_templates', 'current'].includes(e.name))
107
- .map(e => `specs/${e.name}/requirements.md`).filter(f => fs.existsSync(f));
250
+ const features = specDirs().map(id => `specs/${id}/requirements.md`).filter(f => fs.existsSync(f));
108
251
  const current = fs.existsSync('specs/current')
109
252
  ? fs.readdirSync('specs/current').filter(f => f.endsWith('.md') && f !== 'README.md').map(f => `specs/current/${f}`) : [];
110
253
  return [...features, ...current];
@@ -175,12 +318,15 @@ function merge(id) {
175
318
  return 0;
176
319
  }
177
320
 
321
+ // a handoff's status: the template's placeholder until work starts
322
+ const stateOf = p => { const s = (/^Status:\s*(.*?)\s*$/m.exec(p) || [])[1] || ''; return !s || s.startsWith('<') ? 'not started' : s; };
323
+
178
324
  function status() {
179
- const dirs = fs.existsSync('specs') ? fs.readdirSync('specs', { withFileTypes: true })
180
- .filter(e => e.isDirectory() && !['_templates', 'current'].includes(e.name)).map(e => e.name) : [];
181
- const rows = dirs.map(name => {
325
+ if (branch() === 'plan') { planStatus(); return 0; }
326
+ const rows = specDirs().map(name => {
182
327
  const dir = `specs/${name}`;
183
- const state = ((read(`${dir}/progress.md`) || '').match(/^Status:\s*(.*?)\s*$/m) || [])[1] || 'no progress.md';
328
+ const progress = read(`${dir}/progress.md`);
329
+ const state = progress === null ? 'no progress.md' : stateOf(progress);
184
330
  const tasks = read(`${dir}/tasks.md`) || '';
185
331
  const done = (tasks.match(/^\s*- \[[xX]\]/gm) || []).length;
186
332
  const total = done + (tasks.match(/^\s*- \[ \]/gm) || []).length;
@@ -193,6 +339,477 @@ function status() {
193
339
  const current = allSpecFiles().filter(f => f.startsWith('specs/current/'));
194
340
  const count = current.reduce((n, f) => n + blocks(read(f).split('\n')).length, 0);
195
341
  console.log(`\nLiving spec: ${current.length} area(s), ${count} requirement(s) in specs/current/`);
342
+ planStatus();
343
+ return 0;
344
+ }
345
+
346
+ // ---------- a change's tests, or a release's ----------
347
+ const areasNow = () => (fs.existsSync('specs/current') ? fs.readdirSync('specs/current')
348
+ .filter(f => f.endsWith('.md') && f !== 'README.md').map(f => f.slice(0, -3)).sort() : []);
349
+ // the living spec's requirements in these areas: the spec that last changed each one (its Source: line), and its scenarios
350
+ const livingReqs = areas => areas.flatMap(area => blocks((read(`specs/current/${area}.md`) || '').split('\n')).map(b => ({
351
+ area, name: b.name, source: (/^Source:\s*specs\/([^\s/]+)/m.exec(b.lines.join('\n')) || [])[1] || null, scenarios: scenarios(b.lines.join('\n')),
352
+ })));
353
+ // the app's Jest tests, it() and test(), whose titles name the scenario they check
354
+ function jestTests() {
355
+ let files = [];
356
+ try { files = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 2 ** 28 }).split('\n'); } catch {}
357
+ return files.filter(f => /(^|\/)__tests__\/.+\.[jt]sx?$|\.(test|spec)\.[jt]sx?$/.test(f) && !/(^|\/)node_modules\//.test(f))
358
+ .flatMap(f => [...(read(f) || '').matchAll(/\b(?:it|test)(?:\.(?:only|skip|concurrent|failing))?\s*\(\s*(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)].map(m => ({ file: f, title: m[2] })));
359
+ }
360
+
361
+ function tests(id) {
362
+ let own = null;
363
+ if (id) {
364
+ const text = read(`specs/${id}/requirements.md`);
365
+ if (text === null) { console.error(`specs/${id}/requirements.md: not found`); return 1; }
366
+ own = deltas(text);
367
+ }
368
+ const areas = own ? [...new Set(own.sections.map(s => s.area).filter(Boolean))] : areasNow();
369
+ const everywhere = livingReqs(areasNow());
370
+ const reqs = everywhere.filter(r => areas.includes(r.area));
371
+ // the requirements this change modifies or removes: what tests them now tests the old behavior
372
+ const replaced = own ? own.sections.filter(s => s.op !== 'ADDED').flatMap(s => s.blocks.map(b => ({ op: s.op, area: s.area, name: b.name }))) : [];
373
+ const isReplaced = r => replaced.some(x => x.area === r.area && key(x.name) === key(r.name));
374
+ const flows = allFlows();
375
+ const jest = jestTests();
376
+ const memo = (fn, m = new Map()) => k => (m.has(k) ? m.get(k) : m.set(k, fn(k)).get(k));
377
+ const specScenarios = memo(s => scenarios(read(`specs/${s}/requirements.md`) || ''));
378
+ const blocksOf = memo(s => (s ? flowsOf(s, flows) : flows).flatMap(f => flowBlocks(read(`.maestro/${f}`) || '').map(b => ({ ...b, flow: `.maestro/${f}` }))));
379
+ // what checks scenario name of spec s (any spec, without one): its flow block, and Jest tests named after it
380
+ const checks = (s, name) => {
381
+ const b = blockFor(blocksOf(s), s && (specScenarios(s).find(x => norm(x.name) === norm(name)) || {}).n, name);
382
+ return [...(b ? [`${b.flow}:${b.line}`] : []), ...jest.filter(t => norm(t.title).includes(norm(name))).map(t => `${t.file} "${t.title}"`)];
383
+ };
384
+ const say = (title, rows) => { if (rows.length) console.log(`\n${title}\n${rows.map(r => ` ${r}`).join('\n')}`); };
385
+
386
+ console.log(id ? `Tests for ${id}: ${areas.length ? `the area${areas.length === 1 ? '' : 's'} ${areas.join(', ')}` : 'it names no area yet'}`
387
+ : `Tests for a release: every area of the living spec (${areas.length})`);
388
+ const sources = [...new Set(reqs.map(r => r.source).filter(s => s && s !== id))].sort();
389
+ const run = [...(id ? [id] : []), ...sources];
390
+ say('Specs, and their flows:', run.map(s => `${s}${s === id ? ' (this change)' : ''}: ${flowsOf(s, flows).map(f => `.maestro/${f}`).join(', ') || 'no flow'}`));
391
+ say('To change or retire: this change modifies or removes these requirements, so what checks them checks the old behavior:', replaced.map(x => {
392
+ const r = everywhere.find(y => y.area === x.area && key(y.name) === key(x.name));
393
+ const found = r ? r.scenarios.flatMap(sc => checks(r.source, sc.name).map(c => `${c} (scenario "${sc.name}")`)) : [];
394
+ return `${x.op} "${x.name}" (${x.area}${r && r.source ? `, from specs/${r.source}` : ''}): ${found.join('; ') || 'nothing checks it'}`;
395
+ }));
396
+ say('No check: no flow block, and no Jest test named after the scenario:', [
397
+ ...reqs.filter(r => !isReplaced(r)).flatMap(r => r.scenarios.filter(sc => !checks(r.source, sc.name).length)
398
+ .map(sc => `${r.area}: "${r.name}", scenario "${sc.name}"${r.source ? ` (specs/${r.source})` : ''}`)),
399
+ ...(own ? own.sections.filter(s => s.op !== 'REMOVED').flatMap(s => s.blocks.flatMap(b => scenarios(b.lines.join('\n'))
400
+ .filter(sc => !checks(id, sc.name).length).map(sc => `${s.area}: "${b.name}", scenario "${sc.name}" (this change)`))) : []),
401
+ ]);
402
+ // scenarios there are now: the living spec's, and those of specs not merged yet (their work isn't done)
403
+ const ids = [...new Set([...specDirs(), ...everywhere.map(r => r.source).filter(Boolean)])];
404
+ const now = [...everywhere.flatMap(r => r.scenarios.map(sc => sc.name)),
405
+ ...specDirs().filter(s => !/^Status:\s*done/im.test(read(`specs/${s}/progress.md`) || '')).flatMap(s => specScenarios(s).map(sc => sc.name))];
406
+ // (a spec whose id starts another's, as LOGIN-1 and LOGIN-12, shares that one's flows: each block once)
407
+ say('To retire: flow blocks whose scenario isn\'t in the living spec any more:', [...new Set((id ? run : ids).flatMap(s => blocksOf(s).filter(b => {
408
+ const name = /[a-z0-9]/i.test(b.name) ? b.name : (specScenarios(s).find(x => x.n === b.n) || {}).name;
409
+ return name && !now.some(n => same(n, name));
410
+ }).map(b => `${b.flow}:${b.line} # Scenario${b.n ? ` ${b.n}` : ''}: ${b.name}`)))]);
411
+ say(`Flows no spec links to${id ? ' (add the names of those this change touches to --spec)' : ''}:`, flows.filter(f => !ids.some(s => f.toLowerCase().startsWith(s.toLowerCase())))
412
+ .map(f => { const t = tagsOf(read(`.maestro/${f}`) || ''); return `.maestro/${f}${t.length ? ` (tags: ${t.join(', ')})` : ''}`; }));
413
+ const list = run.filter(s => s === id || flowsOf(s, flows).length);
414
+ console.log(`\nRun them: sh scripts/amk/verify.sh all ${id ? `--spec ${list.join(',')}${list.length > 1 ? ` --label ${id}` : ''}` : '--label release'}`);
415
+ return 0;
416
+ }
417
+
418
+ // a flow to start from: a block for each scenario with its steps as comments and a screenshot, its assertion left to write
419
+ function flow(id) {
420
+ const text = read(`specs/${id}/requirements.md`);
421
+ if (text === null) { console.error(`specs/${id}/requirements.md: not found`); return 1; }
422
+ const list = scenarios(text);
423
+ if (!list.length) { console.error(`specs/${id}/requirements.md has no scenarios yet`); return 1; }
424
+ const mine = flowsOf(id, allFlows());
425
+ if (mine.length) {
426
+ const missing = list.filter(s => !blockFor(mine.flatMap(f => flowBlocks(read(`.maestro/${f}`) || '')), s.n, s.name));
427
+ console.log(`${mine.map(f => `.maestro/${f}`).join(', ')} already there, so nothing was written. ${missing.length
428
+ ? `Blocks missing, each with an assertion for its THEN and a screenshot:\n${missing.map(s => ` # Scenario ${s.n}: ${s.name}`).join('\n')}`
429
+ : `Each of the ${list.length} scenarios has a block.`}`);
430
+ return 0;
431
+ }
432
+ const tpl = (read('specs/_templates/flow.yaml') || '').split('\n');
433
+ const from = tpl.findIndex(l => /^appId:/.test(l));
434
+ const to = tpl.findIndex(l => /^# Scenario\b/.test(l));
435
+ const slug = s => norm(s).replace(/ /g, '-').slice(0, 40).replace(/-+$/, '');
436
+ const body = list.flatMap(s => [`# Scenario ${s.n}: ${s.name}`, ...s.steps.map(l => `# ${l}`),
437
+ '# - tapOn:', '# id: "<testID>"', '# - assertVisible:', '# id: "<testID of what THEN expects>"', `- takeScreenshot: ${id}-${s.n}-${slug(s.name)}`]);
438
+ fs.mkdirSync('.maestro', { recursive: true });
439
+ fs.writeFileSync(`.maestro/${id}.yaml`, `${[`# specs/${id}: a block per scenario. Write its steps and its assertion (left as comments here): until then`,
440
+ '# rn-check warns that the scenario has no assertion. How to write them: specs/_templates/flow.yaml',
441
+ ...(from >= 0 && to > from ? tpl.slice(from, to) : ['appId: ${APP_ID}', '---', '- launchApp']), ...body].join('\n')}\n`);
442
+ console.log(`.maestro/${id}.yaml: a block for each of the ${list.length} scenarios, with its screenshot. Write each one's steps and the assertion for its THEN.`);
443
+ return 0;
444
+ }
445
+
446
+ // ---------- the plan: plan all, then build ----------
447
+ // specs/plan.md and the planned specs live on the plan branch, which is never merged: each spec reaches main with its
448
+ // feature's PR. Built means on main: the living spec names it (Source:), or its progress.md there says done.
449
+ const git = (...a) => {
450
+ try { return execFileSync('git', a, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 2 ** 28 }).replace(/\r\n/g, '\n').replace(/\n$/, ''); } catch { return null; }
451
+ };
452
+ const show = (ref, f) => git('show', `${ref}:${f}`);
453
+ const branch = () => git('symbolic-ref', '--quiet', '--short', 'HEAD');
454
+ const exists = ref => git('rev-parse', '--verify', '--quiet', `${ref}^{commit}`) !== null;
455
+ const isAncestor = (a, b) => git('merge-base', '--is-ancestor', a, b) !== null;
456
+ // main, as the kit's other checks see it (the remote's when there is one)
457
+ const mainRef = () => {
458
+ try { return execFileSync(process.execPath, [path.join(__dirname, 'baseline.js'), 'base'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null; } catch { return null; }
459
+ };
460
+ // the plan branch, or the remote's when it's further on (planning in another place pushes it)
461
+ function planRef() {
462
+ const [local, remote] = ['plan', 'origin/plan'].map(r => (exists(r) ? r : null));
463
+ return local && remote && git('rev-parse', local) !== git('rev-parse', remote) && isAncestor(local, remote) ? remote : local || remote;
464
+ }
465
+ // where the plan is read from: this folder when it's on the plan branch, else the plan branch
466
+ const planSource = () => (branch() === 'plan' ? { where: 'this folder', read } : (r => r && { where: r, ref: r, read: f => show(r, f) })(planRef()));
467
+
468
+ const STATUSES = ['drafting', 'questions open', 'ready for approval', 'approved', 'changes requested', 'held'];
469
+ // a handoff or summary line that says nothing is there: none, nothing, n/a, dashes, the template's placeholder, or empty
470
+ const NONE = /^(?:(?:none|nobody|nothing|n\/a)\b|-+(?:\s|$)|<.*>|$)/i;
471
+ // the features whose summary (### <id> under ## Summaries) still waits on someone: "- Waiting on: the client, …"
472
+ function waitingOn(text) {
473
+ const out = new Map();
474
+ const body = (/^## Summaries\s*$([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(text.replace(/<!--[\s\S]*?-->/g, '')) || [])[1] || '';
475
+ let id = null;
476
+ for (const l of body.split('\n')) {
477
+ const h = /^###\s+(.+?)\s*$/.exec(l);
478
+ if (h) { id = cell(h[1]); continue; }
479
+ const w = /^\s*-\s*Waiting on:\s*(.*?)\s*$/i.exec(l);
480
+ if (id && w && !NONE.test(w[1])) out.set(id, w[1]);
481
+ }
482
+ return out;
483
+ }
484
+ const cell = c => bare(c.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1'));
485
+ // the "## Features" table: a row per feature, by its columns' names
486
+ function planFeatures(text) {
487
+ const lines = text.replace(/<!--[\s\S]*?-->/g, c => c.replace(/[^\n]/g, '')).split('\n');
488
+ const at = lines.findIndex(l => /^## Features\s*$/i.test(l));
489
+ if (at < 0) return { rows: [], problems: ['specs/plan.md has no "## Features" table'] };
490
+ const rows = [];
491
+ let head = null;
492
+ for (let i = at + 1; i < lines.length && !/^#{1,2} /.test(lines[i]); i++) {
493
+ if (!/^\s*\|/.test(lines[i])) continue;
494
+ const cells = lines[i].trim().replace(/^\||\|$/g, '').split('|').map(c => c.trim());
495
+ if (!head) { head = cells.map(c => c.toLowerCase()); continue; }
496
+ if (cells.every(c => /^:?-+:?$/.test(c))) continue;
497
+ const get = name => cells[head.indexOf(name)] || '';
498
+ const id = cell(get('feature'));
499
+ if (!id || /^<.*>$/.test(id)) continue;
500
+ const status = get('status');
501
+ rows.push({ line: i + 1, id, goal: get('goal'), batch: Number(get('batch')) || null, size: get('size'), status,
502
+ word: STATUSES.find(w => status.toLowerCase().startsWith(w)) || null,
503
+ deps: get('depends on').split(/[,;]/).map(cell).filter(d => d && !/^(none|n\/a|[-—–]+)$/i.test(d)) });
504
+ }
505
+ const missing = ['feature', 'depends on', 'batch', 'status'].filter(c => !(head || []).includes(c));
506
+ return { rows, problems: missing.length ? [`specs/plan.md: the Features table needs the columns ${missing.join(', ')}`] : [] };
507
+ }
508
+ // the features built on ref (main)
509
+ function builtOn(ref) {
510
+ const ids = new Set();
511
+ for (const l of (git('grep', '-h', '-E', '^Source: specs/', ref, '--', 'specs/current/') || '').split('\n')) {
512
+ const m = /^Source:\s*specs\/([^\s/]+)/.exec(l);
513
+ if (m) ids.add(m[1]);
514
+ }
515
+ for (const l of (git('grep', '-l', '-E', '^Status:[[:space:]]*done', ref, '--', 'specs/*/progress.md') || '').split('\n')) {
516
+ const m = /specs\/([^/]+)\/progress\.md$/.exec(l);
517
+ if (m) ids.add(m[1]);
518
+ }
519
+ return ids;
520
+ }
521
+ // a feature's dependencies in the plan, theirs too
522
+ function depsOf(rows, id, seen = new Set()) {
523
+ for (const d of (rows.find(r => r.id === id) || { deps: [] }).deps) if (!seen.has(d)) { seen.add(d); depsOf(rows, d, seen); }
524
+ return seen;
525
+ }
526
+ // a feature's progress where it's being built: its branch, the status in its handoff, and what blocks it
527
+ function building(id) {
528
+ const b = [`feature/${id}`, `origin/feature/${id}`].find(exists);
529
+ if (!b) return null;
530
+ const p = show(b, `specs/${id}/progress.md`);
531
+ const blocked = (/^Blocked:\s*(.*?)\s*$/m.exec(p || '') || [])[1] || '';
532
+ return { branch: b, status: p === null ? 'no handoff yet' : stateOf(p), blocked: NONE.test(blocked) ? '' : blocked };
533
+ }
534
+ // stories, requirements, scenarios and tasks of a spec on the plan
535
+ function counts(src, id) {
536
+ const req = src.read(`specs/${id}/requirements.md`);
537
+ if (req === null) return null;
538
+ const lines = req.replace(/<!--[\s\S]*?-->/g, c => c.replace(/[^\n]/g, '')).split('\n');
539
+ const tasks = src.read(`specs/${id}/tasks.md`) || '';
540
+ return { stories: (entries(lines, 'User stories', 'US') || []).length, reqs: deltas(req).sections.reduce((n, x) => n + x.blocks.length, 0),
541
+ scenarios: scenarios(req).length, tasks: (tasks.match(/^\s*- \[[ xX]\] \d/gm) || []).length };
542
+ }
543
+ // the commit that approved a feature: the first of the commits since which specs/plan.md has said "approved" for it
544
+ function approvalCommit(ref, id) {
545
+ let found = null;
546
+ for (const c of (git('log', '--format=%H', ref, '--', 'specs/plan.md') || '').split('\n').filter(Boolean)) {
547
+ const row = planFeatures(show(c, 'specs/plan.md') || '').rows.find(r => r.id === id);
548
+ if (!row || row.word !== 'approved') break;
549
+ found = c;
550
+ }
551
+ return found;
552
+ }
553
+
554
+ // the words the glossary, or the plan's new words, say not to use: "**Visit**: … _Not:_ appointment, call."
555
+ function avoidedWords(text) {
556
+ const out = [];
557
+ let term = null;
558
+ for (const l of (text || '').replace(/<!--[\s\S]*?-->/g, '').split('\n')) {
559
+ const t = /\*\*([^*]+)\*\*\s*:/.exec(l);
560
+ if (t) term = t[1].trim();
561
+ const m = /_Not:_\s*(.*)$/.exec(l);
562
+ if (m && term) for (const w of m[1].split(/[,;]/).map(x => bare(x).replace(/\.$/, '')).filter(Boolean)) out.push({ word: w, use: term });
563
+ }
564
+ return out;
565
+ }
566
+
567
+ function checkPlan() {
568
+ const src = planSource();
569
+ const text = src && src.read('specs/plan.md');
570
+ if (!text) { console.error('No plan: specs/plan.md isn\'t on a plan branch here (/m-feature plan makes one).'); return 1; }
571
+ const { rows, problems } = planFeatures(text);
572
+ const main = mainRef();
573
+ const built = main ? builtOn(main) : new Set();
574
+ const at = new Map(rows.map((r, i) => [r.id, i]));
575
+ const p = [...problems];
576
+ const waits = waitingOn(text);
577
+ rows.forEach((r, i) => {
578
+ if (r.word === 'approved' && waits.has(r.id)) p.push(`specs/plan.md:${r.line} ${r.id} is approved, but its summary waits on ${waits.get(r.id)}: hold it (held: <who>) until the answer comes, or set its Waiting on: to none to build on the working assumptions`);
579
+ if (rows.findIndex(x => x.id === r.id) !== i) p.push(`specs/plan.md:${r.line} ${r.id} is listed twice`);
580
+ if (!r.word) p.push(`specs/plan.md:${r.line} ${r.id}: status "${r.status}" isn't one of: ${STATUSES.join(', ')}`);
581
+ if (!r.batch) p.push(`specs/plan.md:${r.line} ${r.id}: give it a batch number`);
582
+ for (const d of r.deps) {
583
+ if (!at.has(d)) { if (!built.has(d)) p.push(`specs/plan.md:${r.line} ${r.id} depends on ${d}, which is neither in the plan nor built on ${main || 'main'}`); continue; }
584
+ const dep = rows[at.get(d)];
585
+ if (at.get(d) > i) p.push(`specs/plan.md:${r.line} ${r.id} depends on ${d}, which comes after it`);
586
+ else if (dep.batch && r.batch && dep.batch > r.batch) p.push(`specs/plan.md:${r.line} ${r.id} depends on ${d}, which is in a later batch`);
587
+ }
588
+ if (depsOf(rows, r.id).has(r.id)) p.push(`specs/plan.md:${r.line} ${r.id} is in a dependency loop`);
589
+ });
590
+ // each planned spec on its own, then what the specs get wrong together
591
+ const specs = rows.map(r => ({ r, text: src.read(`specs/${r.id}/requirements.md`) })).filter(x => x.text !== null);
592
+ for (const r of rows) {
593
+ if (['ready for approval', 'approved'].includes(r.word) && !(specs.find(x => x.r === r) && counts(src, r.id).reqs && counts(src, r.id).tasks)) {
594
+ p.push(`specs/${r.id}: ${r.word}, but its requirements or tasks aren't written yet`);
595
+ }
596
+ }
597
+ const added = new Map();
598
+ const living = new Map();
599
+ const inMain = (area, name) => {
600
+ if (!living.has(area)) living.set(area, blocks(((main && show(main, `specs/current/${area}.md`)) || '').split('\n')).map(b => key(b.name)));
601
+ return living.get(area).includes(key(name));
602
+ };
603
+ for (const { r, text: t } of specs) {
604
+ checkFile(`specs/${r.id}/requirements.md`, t).forEach(x => p.push(x));
605
+ const d = deltas(t);
606
+ const lines = t.replace(/<!--[\s\S]*?-->/g, c => c.replace(/[^\n]/g, '')).split('\n');
607
+ const known = new Map(d.sections.flatMap(x => x.blocks).map(b => [key(b.name), b.name]));
608
+ if (known.size) {
609
+ for (const st of entries(lines, 'User stories', 'US') || []) {
610
+ if (!listed(st.text, 'Requirements', known).length) p.push(`specs/${r.id}/requirements.md:${st.line} ${st.id} names no requirement`);
611
+ }
612
+ }
613
+ for (const x of d.sections.filter(y => y.op === 'ADDED' && y.area)) {
614
+ for (const b of x.blocks) {
615
+ const k = `${x.area}\0${key(b.name)}`;
616
+ added.set(k, [...(added.get(k) || []), r.id]);
617
+ if (inMain(x.area, b.name)) p.push(`specs/${r.id} adds "${b.name}" (${x.area}), which the living spec on ${main} already has: list it under MODIFIED`);
618
+ }
619
+ }
620
+ }
621
+ for (const [k, ids] of added) if (ids.length > 1) p.push(`"${k.split('\0')[1]}" (${k.split('\0')[0]}) is added by both ${ids.join(' and ')}`);
622
+ for (const { r, text: t } of specs) {
623
+ for (const x of deltas(t).sections.filter(y => y.op !== 'ADDED' && y.area)) {
624
+ for (const b of x.blocks) {
625
+ const by = (added.get(`${x.area}\0${key(b.name)}`) || []).filter(id => id !== r.id);
626
+ if (inMain(x.area, b.name)) continue;
627
+ if (!by.length) p.push(`specs/${r.id} ${x.op === 'MODIFIED' ? 'modifies' : 'removes'} "${b.name}" (${x.area}), which neither the living spec on ${main || 'main'} nor another planned feature has`);
628
+ for (const g of by) if (!depsOf(rows, r.id).has(g)) p.push(`specs/${r.id} ${x.op === 'MODIFIED' ? 'modifies' : 'removes'} "${b.name}", which ${g} adds: add ${g} to its Depends on`);
629
+ }
630
+ }
631
+ }
632
+ const shared = (/^## Shared design\s*$([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(text) || [])[1];
633
+ // a warning only: a word to avoid can be right in another sense (an API "call" in an app whose Visits aren't calls)
634
+ const avoid = [...avoidedWords(main && show(main, 'docs/amk/glossary.md')), ...avoidedWords(shared)];
635
+ // the spec's own words: not the template's comments, or its section headings ("## User stories")
636
+ const own = t => t.replace(/<!--[\s\S]*?-->/g, '').replace(/^## .*$/gm, '').replace(/<[^<>\n]*>/g, '');
637
+ const words = specs.flatMap(({ r, text: t }) => avoid.filter(a => new RegExp(`\\b${a.word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}s?\\b`, 'i')
638
+ .test(own(t))).map(a => `specs/${r.id} says "${a.word}": the glossary's word is ${a.use}, unless it means something else here`));
639
+ // the plan branch never takes main's changes, so a kit update there doesn't reach it
640
+ const kit = branch() === 'plan' && main && show(main, 'scripts/amk/specs.js') !== null;
641
+ if (kit && git('diff', '--quiet', main, '--', 'scripts/amk/specs.js') === null) words.push(`the kit's scripts here aren't ${main}'s (a kit update there?): git checkout ${main} -- scripts/amk .agents/skills .rulesync, then commit`);
642
+ p.forEach(x => console.error(`✗ ${x}`));
643
+ words.forEach(x => console.error(`! ${x}`));
644
+ if (!p.length) console.log(`✓ plan: ${rows.length} feature(s), ${specs.length} with a spec, checked together${main ? ` against ${main}` : ''}`);
645
+ return p.length ? 1 : 0;
646
+ }
647
+
648
+ // the plan's features, where each stands, and the sizes added up per batch
649
+ function planStatus() {
650
+ const src = planSource();
651
+ const text = src && src.read('specs/plan.md');
652
+ if (!text) return;
653
+ const { rows } = planFeatures(text);
654
+ const waits = waitingOn(text);
655
+ const main = mainRef();
656
+ const built = main ? builtOn(main) : new Set();
657
+ const out = rows.map(r => {
658
+ const b = building(r.id);
659
+ const c = (b && b.branch && counts({ read: f => show(b.branch, f) }, r.id)) || counts(src, r.id);
660
+ const state = built.has(r.id) ? 'built' : b ? `being built on ${b.branch}: ${b.status}${b.blocked ? `; blocked: ${b.blocked}` : ''}`
661
+ : `${r.status || 'no status'}${r.word === 'approved' && waits.has(r.id) ? `, but waits on ${waits.get(r.id)}` : ''}`;
662
+ const hours = c && c.tasks ? c.tasks : Number((r.size.match(/\d+(?:\.\d+)?/) || [])[0]) || 0;
663
+ return { r, state, c, hours, rough: !(c && c.tasks) };
664
+ });
665
+ console.log(`\nPlan (specs/plan.md on ${src.where}): ${rows.length} feature(s)`);
666
+ const w = Math.max(7, ...rows.map(r => r.id.length));
667
+ for (const x of out) {
668
+ const what = x.c ? `${x.c.stories} stories, ${x.c.reqs} requirements, ${x.c.scenarios} scenarios, ${x.c.tasks ? `${x.c.tasks} tasks` : `~${x.hours} h`}` : `no spec yet, ~${x.hours} h`;
669
+ console.log(` ${x.r.id.padEnd(w)} batch ${String(x.r.batch || '?').padEnd(2)} ${x.state} (${what})`);
670
+ }
671
+ const batches = [...new Set(rows.map(r => r.batch || 0))].sort((a, b) => a - b);
672
+ console.log(` Size: ${batches.map(n => { const xs = out.filter(x => (x.r.batch || 0) === n); return `batch ${n || '?'} ${xs.some(x => x.rough) ? '~' : ''}${xs.reduce((t, x) => t + x.hours, 0)} h`; }).join(', ')} (a task is about an hour)`);
673
+ }
674
+
675
+ // requirements a feature modifies or removes that changed on main after the plan approved it, other than through the
676
+ // features it depends on: building it as approved would undo that change
677
+ function changedSince(id, approved, from, main, deps) {
678
+ const when = git('log', '-1', '--format=%cI', approved);
679
+ const then = when && git('rev-list', '-1', '--first-parent', `--before=${when}`, main);
680
+ if (!then) return [];
681
+ const out = [];
682
+ for (const x of deltas(show(approved, `specs/${id}/requirements.md`) || '').sections.filter(y => y.op !== 'ADDED' && y.area)) {
683
+ const at = ref => blocks((show(ref, `specs/current/${x.area}.md`) || '').split('\n'));
684
+ const [before, now] = [at(then), at(from)];
685
+ for (const b of x.blocks) {
686
+ const was = before.find(y => key(y.name) === key(b.name));
687
+ const is = now.find(y => key(y.name) === key(b.name));
688
+ if (normalize(was ? was.lines : []) === normalize(is ? is.lines : [])) continue;
689
+ const by = is && (/^Source:\s*specs\/([^\s/]+)/m.exec(is.lines.join('\n')) || [])[1];
690
+ if (by && deps.has(by)) continue;
691
+ out.push(`"${b.name}" (${x.area}) ${is ? `changed after the plan approved ${id}${by ? `, in specs/${by}` : ''}` : 'isn\'t in the living spec any more'}`);
692
+ }
693
+ }
694
+ return out;
695
+ }
696
+
697
+ // on the plan branch, which never takes main's changes, a planned spec's tests are found in main as it is now: in a
698
+ // temporary worktree of main, with the spec copied in
699
+ function testsOnMain(id) {
700
+ const main = mainRef();
701
+ const text = read(`specs/${id}/requirements.md`);
702
+ if (!main || text === null) return tests(id);
703
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'amk-plan-'));
704
+ try {
705
+ execFileSync('git', ['worktree', 'add', '--detach', '--force', dir, main], { stdio: 'ignore' });
706
+ fs.mkdirSync(path.join(dir, 'specs', id), { recursive: true });
707
+ fs.writeFileSync(path.join(dir, 'specs', id, 'requirements.md'), text);
708
+ console.log(`(the living spec, flows and tests as they are on ${main}: this branch's copies are older)`);
709
+ return spawnSync(process.execPath, [process.argv[1], 'tests', id], { cwd: dir, stdio: 'inherit' }).status;
710
+ } finally {
711
+ git('worktree', 'remove', '--force', dir);
712
+ fs.rmSync(dir, { recursive: true, force: true });
713
+ }
714
+ }
715
+
716
+ // a second folder of this repository on the plan branch: a git worktree, which holds only what git tracks, so the kit's
717
+ // files an app keeps out of git (its skills, tool settings and hooks) are copied in from this folder
718
+ const KIT_FOLDERS = ['.agents', '.claude', '.codex', '.antigravity', '.githooks', '.rulesync', 'rulesync.jsonc', '.kiro', '.cursor', '.opencode'];
719
+ function planFolder() {
720
+ const top = git('rev-parse', '--show-toplevel');
721
+ if (!top) { console.error('Not in a git repository.'); return 1; }
722
+ const dir = path.join(path.dirname(top), `${path.basename(top)}-plan`);
723
+ if (fs.existsSync(dir)) { console.log(`${dir} is there already: open a session there, and run /m-feature plan.`); return 0; }
724
+ const main = exists('plan') || exists('origin/plan') ? null : mainRef();
725
+ const how = exists('plan') ? [dir, 'plan'] : exists('origin/plan') ? ['-b', 'plan', dir, 'origin/plan'] : main && ['--no-track', '-b', 'plan', dir, main];
726
+ if (!how) { console.error('No main branch found: set AMK_BASE to the branch features start from.'); return 1; }
727
+ try { execFileSync('git', ['worktree', 'add', ...how], { cwd: top, stdio: ['ignore', 'ignore', 'pipe'] }); } catch (e) { console.error(`git worktree add: ${String(e.stderr || e.message).trim()}`); return 1; }
728
+ const files = (git('-C', top, 'ls-files', '--others', '--ignored', '--exclude-standard', '--', ...KIT_FOLDERS) || '').split('\n').filter(Boolean);
729
+ const missed = [];
730
+ for (const f of files) {
731
+ const from = path.join(top, f);
732
+ const to = path.join(dir, f);
733
+ fs.mkdirSync(path.dirname(to), { recursive: true });
734
+ try {
735
+ if (fs.lstatSync(from).isSymbolicLink()) fs.symlinkSync(fs.readlinkSync(from), to);
736
+ else fs.copyFileSync(from, to); // its mode too: a hook stays executable
737
+ } catch { missed.push(f); }
738
+ }
739
+ console.log(`${dir}: on the plan branch${files.length ? `, with the ${files.length - missed.length} kit file(s) git doesn't track here` : ''}. It needs no installs or devices: open a session there and run /m-feature plan.`);
740
+ if (missed.length) console.log(` not copied (copy them by hand): ${missed.join(', ')}`);
741
+ return 0;
742
+ }
743
+
744
+ // the remote's branches as they are now, never waiting on a password or passphrase prompt: offline, it goes on with what's here
745
+ function fetchOrigin() {
746
+ if (!git('remote')) return;
747
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND || 'ssh -o BatchMode=yes' };
748
+ try { execFileSync('git', ['fetch', '--quiet', 'origin'], { stdio: 'ignore', timeout: 60000, env }); } catch {}
749
+ }
750
+
751
+ function start(want) {
752
+ if (branch() === 'plan') { console.error('This folder is on the plan branch: build in a folder on main or a feature branch.'); return 1; }
753
+ if (git('status', '--porcelain', '--untracked-files=no')) { console.error('Commit the changes here first (git status): a feature starts from a clean folder.'); return 1; }
754
+ fetchOrigin();
755
+ const ref = planRef();
756
+ const plan = ref && show(ref, 'specs/plan.md');
757
+ if (!plan) { console.error('No plan branch with specs/plan.md here: /m-feature plan makes one.'); return 1; }
758
+ const main = mainRef();
759
+ if (!main) { console.error('No main branch found: set AMK_BASE to the branch features start from.'); return 1; }
760
+ const { rows } = planFeatures(plan);
761
+ const waits = waitingOn(plan);
762
+ const built = builtOn(main);
763
+ // the build's stack: planned features done on their own branch whose PR isn't merged yet, the highest first (holding
764
+ // the most of the others, then the latest in the plan)
765
+ const stack = rows.filter(r => !built.has(r.id) && exists(`feature/${r.id}`) && /^done/i.test((building(r.id) || {}).status || ''));
766
+ const holds = (a, b) => isAncestor(`feature/${b}`, `feature/${a}`);
767
+ const high = stack.map((r, i) => ({ r, i, n: stack.filter(o => o !== r && holds(r.id, o.id)).length })).sort((a, b) => b.n - a.n || b.i - a.i).map(x => x.r);
768
+ // where a feature starts: the highest branch of the stack that holds the dependencies it has there, or main
769
+ const baseFor = r => {
770
+ const need = r.deps.filter(d => !built.has(d) && stack.some(o => o.id === d));
771
+ const s = high.find(o => need.every(d => d === o.id || holds(o.id, d)));
772
+ return s ? `feature/${s.id}` : need.length ? null : main;
773
+ };
774
+ const why = r => {
775
+ if (built.has(r.id)) return 'built';
776
+ const b = building(r.id);
777
+ if (b) return `taken: ${b.branch}, ${b.status}${b.blocked ? `; blocked: ${b.blocked}` : ''}`;
778
+ if (r.word !== 'approved') return r.status || 'no status';
779
+ if (waits.has(r.id)) return `approved, but waits on ${waits.get(r.id)}`;
780
+ const missing = r.deps.filter(d => !built.has(d) && !stack.some(o => o.id === d));
781
+ if (missing.length) return `waits for ${missing.join(', ')}`;
782
+ return baseFor(r) ? null : `waits for ${r.deps.join(', ')} to be merged: no one branch holds them all`;
783
+ };
784
+ const pick = want ? rows.find(r => r.id === want) : rows.find(r => !why(r));
785
+ if (want && !pick) { console.error(`${want} isn't in specs/plan.md on ${ref}.`); return 1; }
786
+ if (!pick || why(pick)) {
787
+ console.log(`${want ? `${want} can't start` : 'Waiting for the plan: no feature is ready'} (specs/plan.md on ${ref}):`);
788
+ for (const r of want ? [pick] : rows.filter(x => why(x) !== 'built')) console.log(` ${r.id}: ${why(r)}`);
789
+ return 3;
790
+ }
791
+ const approved = approvalCommit(ref, pick.id);
792
+ if (!approved || !show(approved, `specs/${pick.id}/requirements.md`)) { console.error(`${pick.id}: no approved spec on ${ref} (specs/${pick.id}/ in the commit that approved it).`); return 1; }
793
+ const short = approved.slice(0, 7);
794
+ const name = `feature/${pick.id}`;
795
+ const from = baseFor(pick);
796
+ for (const a of [['switch', '--quiet', '--no-track', '-c', name, from], ['checkout', approved, '--', `specs/${pick.id}/`]]) {
797
+ try { execFileSync('git', a, { stdio: ['ignore', 'ignore', 'pipe'] }); } catch (e) { console.error(`git ${a.join(' ')}: ${String(e.stderr || e.message).trim()}`); return 1; }
798
+ }
799
+ const progress = `specs/${pick.id}/progress.md`;
800
+ const log = `- ${new Date().toISOString().slice(0, 16).replace('T', ' ')}: started from ${from} (its PR goes to ${from.replace(/^origin\//, '')}), with the spec as approved in ${short} on ${ref}`;
801
+ const p = read(progress) || read('specs/_templates/progress.md') || '## Log\n';
802
+ fs.writeFileSync(progress, /^## Log\s*$/m.test(p) ? p.replace(/^## Log\s*\n(\s*<!--[\s\S]*?-->\s*\n)?/m, m => `${m.replace(/\n*$/, '\n')}\n${log}\n`) : `${p.replace(/\n*$/, '\n')}\n## Log\n\n${log}\n`);
803
+ try {
804
+ execFileSync('git', ['add', '--', `specs/${pick.id}/`], { stdio: 'ignore' });
805
+ execFileSync('git', ['commit', '--quiet', '-m', `docs(spec): ${pick.id} from the plan, as approved in ${short}\n\nSpec: specs/${pick.id}`], { stdio: ['ignore', 'ignore', 'pipe'] });
806
+ } catch (e) { console.error(`git commit: ${String(e.stderr || e.message).trim()}`); return 1; }
807
+ console.log(`Started ${pick.id} on ${name}, from ${from} (its PR's base), with the spec as approved in ${short}.`);
808
+ const changed = changedSince(pick.id, approved, from, main, depsOf(rows, pick.id));
809
+ if (changed.length) {
810
+ console.log(`Stop: the living spec changed under it, so it needs approving again (a change after approval):\n${changed.map(c => ` ${c}`).join('\n')}`);
811
+ return 4;
812
+ }
196
813
  return 0;
197
814
  }
198
815
 
@@ -200,19 +817,85 @@ function status() {
200
817
  const isDraft = f => /^specs\/[^/]+\/requirements\.md$/.test(f) && !f.startsWith('specs/current/')
201
818
  && !/^Status:\s*(in progress|done)/im.test(read(f.replace(/requirements\.md$/, 'progress.md')) || '');
202
819
 
203
- if (cmd === 'check') {
204
- const skipDrafts = args.includes('--skip-drafts');
205
- const named = args.filter(a => a !== '--skip-drafts');
206
- const files = (named.length ? named : allSpecFiles()).filter(f => !(skipDrafts && isDraft(f)));
207
- const problems = files.flatMap(checkFile);
208
- problems.forEach(p => console.error(`✗ ${p}`));
209
- if (!problems.length) console.log(`✓ ${files.length} spec file(s) checked`);
210
- process.exitCode = problems.length ? 1 : 0;
211
- } else if (cmd === 'merge' && args[0]) {
212
- process.exitCode = merge(args[0]);
213
- } else if (cmd === 'status') {
214
- process.exitCode = status();
215
- } else {
216
- console.log(fs.readFileSync(process.argv[1], 'utf8').split('\n').slice(1, 9).map(l => l.replace(/^\/\/ ?/, '')).join('\n'));
217
- process.exitCode = 1;
820
+ // ---------- a feature list exported from a spreadsheet (CSV) or Trello (its JSON), for /m-feature plan ----------
821
+ // RFC 4180 CSV, with the separator Excel used (a comma, or a semicolon or tab in some locales): rows of fields
822
+ function csv(text) {
823
+ const first = text.split('\n')[0].replace(/"[^"]*"/g, '');
824
+ const sep = [',', ';', '\t'].sort((a, b) => first.split(b).length - first.split(a).length)[0];
825
+ const rows = [[]];
826
+ let f = '';
827
+ let q = false;
828
+ for (let i = 0; i < text.length; i++) {
829
+ const c = text[i];
830
+ if (q) {
831
+ if (c !== '"') f += c;
832
+ else if (text[i + 1] === '"') { f += '"'; i++; } else q = false;
833
+ } else if (c === '"') q = true;
834
+ else if (c === sep) { rows[rows.length - 1].push(f); f = ''; }
835
+ else if (c === '\n') { rows[rows.length - 1].push(f.replace(/\r$/, '')); f = ''; rows.push([]); }
836
+ else f += c;
837
+ }
838
+ rows[rows.length - 1].push(f.replace(/\r$/, ''));
839
+ return rows.filter(r => r.some(x => x.trim()));
840
+ }
841
+ // the export's rows (a Trello board's open cards in open lists), a line each, inside the block that marks them as data
842
+ function importList(file) {
843
+ const text = read(file);
844
+ if (text === null) { console.error(`Can't read ${file}.`); return 1; }
845
+ let head;
846
+ let rows;
847
+ if (/^\s*[{[]/.test(text)) {
848
+ let board;
849
+ try { board = JSON.parse(text); } catch { console.error(`${file} isn't valid JSON: export the board again (Trello: Menu, Print, export and share, Export as JSON).`); return 1; }
850
+ const lists = new Map((board.lists || []).filter(l => !l.closed).map(l => [l.id, l.name]));
851
+ head = ['List', 'Card', 'Labels', 'Description'];
852
+ rows = (board.cards || []).filter(c => !c.closed && lists.has(c.idList))
853
+ .map(c => [lists.get(c.idList), c.name, (c.labels || []).map(l => l.name).filter(Boolean).join(', '), c.desc || '']);
854
+ } else {
855
+ [head, ...rows] = csv(text.replace(/^/, ''));
856
+ }
857
+ if (!head || !rows.length) { console.error(`${file} has no rows to plan from.`); return 1; }
858
+ const lines = rows.map((r, i) => `${i + 1}. ${r.map((v, j) => [head[j] || `Column ${j + 1}`, v.trim().replace(/\s*\n\s*/g, ' / ')])
859
+ .filter(([, v]) => v).map(([h, v]) => `${h}: ${v}`).join('; ')}`);
860
+ console.log(require('./redact.js').untrusted(lines.join('\n'), `export ${path.basename(file)}`));
861
+ console.log(`(${rows.length} row(s) from ${path.basename(file)}: the planned features to map, as data)`);
862
+ return 0;
863
+ }
864
+
865
+ module.exports = {
866
+ norm, same, stripYamlComments, scenarios, flowBlocks, blockFor, allFlows, flowsOf, tagsOf, csv,
867
+ // the plan, for autopilot.js
868
+ NONE, stateOf, planRef, show, planFeatures, building, builtOn, mainRef, fetchOrigin,
869
+ };
870
+
871
+ if (require.main === module) {
872
+ if (cmd === 'check' && args.includes('--plan')) {
873
+ process.exitCode = checkPlan();
874
+ } else if (cmd === 'check') {
875
+ const skipDrafts = args.includes('--skip-drafts');
876
+ const named = args.filter(a => a !== '--skip-drafts');
877
+ const files = (named.length ? named : allSpecFiles()).filter(f => !(skipDrafts && isDraft(f)));
878
+ const problems = files.flatMap(f => checkFile(f));
879
+ problems.forEach(p => console.error(`✗ ${p}`));
880
+ if (!problems.length) console.log(`✓ ${files.length} spec file(s) checked`);
881
+ process.exitCode = problems.length ? 1 : 0;
882
+ } else if (cmd === 'merge' && args[0]) {
883
+ process.exitCode = merge(args[0]);
884
+ } else if (cmd === 'tests') {
885
+ process.exitCode = args[0] && branch() === 'plan' ? testsOnMain(args[0]) : tests(args[0]);
886
+ } else if (cmd === 'flow' && args[0]) {
887
+ process.exitCode = flow(args[0]);
888
+ } else if (cmd === 'status') {
889
+ process.exitCode = status();
890
+ } else if (cmd === 'start') {
891
+ process.exitCode = start(args[0]);
892
+ } else if (cmd === 'plan-folder') {
893
+ process.exitCode = planFolder();
894
+ } else if (cmd === 'import' && args[0]) {
895
+ process.exitCode = importList(args[0]);
896
+ } else {
897
+ const head = fs.readFileSync(process.argv[1], 'utf8').split('\n').slice(1);
898
+ console.log(head.slice(0, head.findIndex(l => !l.startsWith('//'))).map(l => l.replace(/^\/\/ ?/, '')).join('\n'));
899
+ process.exitCode = 1;
900
+ }
218
901
  }