agentic-mobile-kit 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,19 +9,17 @@ Tested with Claude Code, Codex and Antigravity. `--tools` also sets up Cursor, O
9
9
  1. In your app's root folder, on a clean git branch, run:
10
10
 
11
11
  ```sh
12
- npx agentic-mobile-kit init
12
+ npx agentic-mobile-kit
13
13
  ```
14
14
 
15
- If the app uses CI, add `--ci github`, `--ci codemagic` or both. To pick AI tools, add `--tools claude,codex,antigravity`, which is the default. `--help` lists every option.
15
+ It asks what to do, one step at a time: install with the recommended setup (Claude Code, Codex and Antigravity, no CI), or choose the AI tools and CI. There's nothing to `npm install`: the kit copies its files into the app and isn't a dependency. If you ran `npm i agentic-mobile-kit`, commit or undo that first, because the kit needs a clean working tree.
16
16
 
17
- 2. Check the project and your machine. `doctor` lists each problem with its fix:
18
-
19
- ```sh
20
- npx agentic-mobile-kit doctor
21
- ```
17
+ 2. Run it again and choose **Check this project and machine**. It lists each problem with its fix.
22
18
 
23
19
  3. Fill in `docs/ai/product.md`, `tech.md`, `structure.md` and `conventions.md`, then commit and open a PR.
24
20
 
21
+ Each choice prints the command it runs, for scripts and CI: `init` (with `--ci github`, `--ci codemagic` or `--tools claude,codex,antigravity`), `sync`, `doctor` and `uninstall`. `--help` lists every option.
22
+
25
23
  `init` never overwrites your files, is safe to run again, and can be undone with git. The [team guide](docs/team-guide.md#setup) lists everything it changes.
26
24
 
27
25
  ## How work flows
@@ -49,6 +47,8 @@ Apps that already use Superpowers, BMAD, proAgents or similar keep them as they
49
47
 
50
48
  ## Update or remove
51
49
 
50
+ Run `npx agentic-mobile-kit` in an app that has the kit. It offers to update it, add CI, check the setup or remove the kit, and tells you when a newer version is out. The same as commands:
51
+
52
52
  ```sh
53
53
  npx agentic-mobile-kit@latest sync # update the kit's files, merging in your own changes
54
54
  npx agentic-mobile-kit uninstall # remove the kit; files you changed are kept and listed
package/bin/cli.js CHANGED
@@ -2,17 +2,12 @@
2
2
  const { version } = require('../package.json');
3
3
  const { init, sync, uninstall, printSummary, printSync, printUninstall, InitError, TOOLS, CI } = require('../lib/init');
4
4
  const { doctor, printDoctor } = require('../lib/doctor');
5
-
6
- const [cmd, ...rest] = process.argv.slice(2);
7
- const flag = name => {
8
- const i = rest.indexOf(`--${name}`);
9
- return i >= 0 ? rest[i + 1] : undefined;
10
- };
11
- const list = name => (flag(name) ? flag(name).split(',').map(s => s.trim()).filter(Boolean) : undefined);
5
+ const { menu } = require('../lib/menu');
12
6
 
13
7
  const help = `agentic-mobile-kit ${version}
14
8
 
15
9
  Usage:
10
+ npx agentic-mobile-kit In a terminal: pick what to do in this app, step by step
16
11
  npx agentic-mobile-kit init [--tools claude,codex,antigravity] [--ci github,codemagic] [--pm yarn|npm|pnpm|bun]
17
12
  npx agentic-mobile-kit sync [--ci github,codemagic] [--from <version>]
18
13
  npx agentic-mobile-kit uninstall [--from <version>]
@@ -39,19 +34,32 @@ function run(name, fn) {
39
34
  }
40
35
  }
41
36
 
42
- if (cmd === '--version' || cmd === '-v') {
43
- console.log(version);
44
- } else if (cmd === 'init') {
45
- run('init', () => {
46
- printSummary(init(process.cwd(), { tools: list('tools'), ci: list('ci'), pm: flag('pm') }));
47
- });
48
- } else if (cmd === 'sync') {
49
- run('sync', () => printSync(sync(process.cwd(), { from: flag('from'), ci: list('ci'), pm: flag('pm') })));
50
- } else if (cmd === 'uninstall') {
51
- run('uninstall', () => printUninstall(uninstall(process.cwd(), { from: flag('from'), pm: flag('pm') })));
52
- } else if (cmd === 'doctor') {
53
- if (printDoctor(doctor(process.cwd())) > 0) process.exitCode = 1;
54
- } else {
55
- console.log(help);
56
- if (cmd && cmd !== 'help' && cmd !== '--help' && cmd !== '-h') process.exitCode = 1;
37
+ function main([cmd, ...rest]) {
38
+ const flag = name => {
39
+ const i = rest.indexOf(`--${name}`);
40
+ return i >= 0 ? rest[i + 1] : undefined;
41
+ };
42
+ const list = name => (flag(name) ? flag(name).split(',').map(s => s.trim()).filter(Boolean) : undefined);
43
+
44
+ if (cmd === '--version' || cmd === '-v') {
45
+ console.log(version);
46
+ } else if (cmd === 'init') {
47
+ run('init', () => {
48
+ printSummary(init(process.cwd(), { tools: list('tools'), ci: list('ci'), pm: flag('pm') }));
49
+ });
50
+ } else if (cmd === 'sync') {
51
+ run('sync', () => printSync(sync(process.cwd(), { from: flag('from'), ci: list('ci'), pm: flag('pm') })));
52
+ } else if (cmd === 'uninstall') {
53
+ run('uninstall', () => printUninstall(uninstall(process.cwd(), { from: flag('from'), pm: flag('pm') })));
54
+ } else if (cmd === 'doctor') {
55
+ if (printDoctor(doctor(process.cwd())) > 0) process.exitCode = 1;
56
+ } else {
57
+ console.log(help);
58
+ if (cmd && cmd !== 'help' && cmd !== '--help' && cmd !== '-h') process.exitCode = 1;
59
+ }
57
60
  }
61
+
62
+ // no command: the menu, but only for a person at a terminal. CI and AI agents get the help instead of a question
63
+ const args = process.argv.slice(2);
64
+ if (!args.length && process.stdin.isTTY && process.stdout.isTTY) menu(process.cwd()).then(chosen => chosen && main(chosen));
65
+ else main(args);
package/lib/doctor.js CHANGED
@@ -66,7 +66,7 @@ function projectChecks(cwd, opts) {
66
66
  out.push(r.status === 0 ? ok('File names match git') : fail(`Renamed only in letter case, and git missed it:${lines.slice(1, -1).join(',')}`, lines.pop()));
67
67
  }
68
68
 
69
- const tracked = (run('git', ['ls-files'], { cwd }) || '').split('\n').filter(f => /(^|\/)\.env(\.(?!example$)[\w.-]+)?$/.test(f));
69
+ const tracked = (run('git', ['ls-files'], { cwd }) || '').split('\n').filter(f => /(^|\/)\.env(\.[\w.-]+)?$/.test(f) && !/\.(example|sample|template)$/.test(f));
70
70
  out.push(tracked.length ? fail(`Secret files tracked by git: ${tracked.join(', ')}`, 'git rm --cached them, rotate the secrets, keep them out of the repo') : ok('No .env files in git'));
71
71
 
72
72
  const claudeLink = path.join(cwd, '.claude/skills');
package/lib/init.js CHANGED
@@ -16,6 +16,9 @@ const FILLED = ['AGENTS.md', 'codemagic.yaml'];
16
16
  // docs each team rewrites for its app: sync replaces them only while they're untouched, and never merges into them
17
17
  const PROJECT_DOCS = ['product', 'tech', 'structure', 'conventions'].map(n => `docs/ai/${n}.md`);
18
18
  const HOOKS_CMD = 'git config core.hooksPath .githooks || true';
19
+ // the app's own ESLint skips the kit's scripts: they follow the kit's style, not each app's rules
20
+ const ESLINT_IGNORE = 'scripts/ai/';
21
+ const ESLINT_NOTE = "# agentic-mobile-kit: its scripts follow the kit's style, not this app's lint rules";
19
22
  // optional parts, installed only when a project chooses them with --ci: not every app uses CI
20
23
  const CI = {
21
24
  github: rel => rel.startsWith('.github/'),
@@ -79,18 +82,19 @@ function detectPm(cwd, forced) {
79
82
  return pms.npm;
80
83
  }
81
84
 
85
+ // the app's folder first: in the wrong folder, "run git init" would be the wrong advice
82
86
  function checkProject(cwd) {
87
+ const pkgFile = path.join(cwd, 'package.json');
88
+ if (!fs.existsSync(pkgFile)) throw new InitError('No package.json here. Run this in the root of your React Native app.');
89
+ const pkg = readJson(pkgFile);
90
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
91
+ if (!deps['react-native']) throw new InitError('This is not a React Native project (no "react-native" dependency).');
83
92
  try { git(cwd, 'rev-parse', '--is-inside-work-tree'); } catch {
84
93
  throw new InitError('This folder is not a git repository. Run "git init" and commit first; git is how init can be undone.');
85
94
  }
86
95
  if (git(cwd, 'status', '--porcelain')) {
87
96
  throw new InitError('You have uncommitted changes. Commit or stash them first, so this can be undone with git.');
88
97
  }
89
- const pkgFile = path.join(cwd, 'package.json');
90
- if (!fs.existsSync(pkgFile)) throw new InitError('No package.json here. Run this in the root of your React Native app.');
91
- const pkg = readJson(pkgFile);
92
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
93
- if (!deps['react-native']) throw new InitError('This is not a React Native project (no "react-native" dependency).');
94
98
  const stack = detectStack(cwd, deps);
95
99
  if (stack === 'bare' && (!fs.existsSync(path.join(cwd, 'ios')) || !fs.existsSync(path.join(cwd, 'android')))) {
96
100
  throw new InitError('No ios/ and android/ folders found, and this isn\'t an Expo app. The kit supports bare React Native and Expo apps.');
@@ -430,7 +434,7 @@ function finish(cwd, { pkg, deps, tools, files, stack, skipGenerate }) {
430
434
  const gi = path.join(cwd, '.gitignore');
431
435
  const giText = readIf(gi) || '';
432
436
  // Expo: ios/ and android/ are generated by prebuild, so they stay out of git too
433
- const ignored = ['.env', '.env.*', '!.env.example', '.ai/', ...(stack === 'expo' ? ['/ios', '/android'] : [])];
437
+ const ignored = ['.env', '.env.*', '!.env*.example', '!.env*.sample', '!.env*.template', '.ai/', ...(stack === 'expo' ? ['/ios', '/android'] : [])];
434
438
  const missing = ignored.filter(l => !giText.split('\n').includes(l));
435
439
  if (missing.length) {
436
440
  fs.writeFileSync(gi, `${giText.replace(/\n*$/, giText ? '\n' : '')}\n# agentic-mobile-kit: secrets stay out of git; .ai/ holds local evidence (screenshots, logs)${stack === 'expo' ? '; ios/ and android/ are generated' : ''}\n${missing.join('\n')}\n`);
@@ -446,6 +450,16 @@ function finish(cwd, { pkg, deps, tools, files, stack, skipGenerate }) {
446
450
  done.merged.push('.gitattributes');
447
451
  }
448
452
 
453
+ // 3c. .eslintignore, for apps on ESLint's eslintrc config (ESLint 9's flat config doesn't read the file;
454
+ // the kit's scripts pass React Native's default rules, but stricter configs such as Airbnb's flag them)
455
+ const eslintrc = fs.readdirSync(cwd).some(f => /^\.eslintrc(\.\w+)?$/.test(f)) || Boolean(pkg.eslintConfig);
456
+ const ei = path.join(cwd, '.eslintignore');
457
+ const eiText = readIf(ei) || '';
458
+ if (eslintrc && !eiText.split('\n').includes(ESLINT_IGNORE)) {
459
+ fs.writeFileSync(ei, `${eiText.replace(/\n*$/, eiText ? '\n' : '')}${eiText ? '\n' : ''}${ESLINT_NOTE}\n${ESLINT_IGNORE}\n`);
460
+ (eiText ? done.merged : done.created).push('.eslintignore');
461
+ }
462
+
449
463
  // 4. package.json scripts: typecheck, and hooks path on install (never overwrite existing scripts)
450
464
  const scripts = (pkg.scripts = pkg.scripts || {});
451
465
  let pkgChanged = false;
@@ -491,11 +505,10 @@ function finish(cwd, { pkg, deps, tools, files, stack, skipGenerate }) {
491
505
  }
492
506
 
493
507
  function init(cwd, opts = {}) {
508
+ const { pkg, deps, stack } = checkProject(cwd);
494
509
  // monorepos: git runs hooks from the repository root, and GitHub reads workflows only there
495
- let prefix = '';
496
- try { prefix = git(cwd, 'rev-parse', '--show-prefix').replace(/\/$/, ''); } catch {}
510
+ const prefix = git(cwd, 'rev-parse', '--show-prefix').replace(/\/$/, '');
497
511
  if (prefix) throw new InitError(`This app is in a subfolder of its git repository (${prefix}), as in a monorepo. The kit doesn't support that yet: git runs hooks from the repository root, and GitHub reads workflows only there.`);
498
- const { pkg, deps, stack } = checkProject(cwd);
499
512
  const pm = detectPm(cwd, opts.pm);
500
513
  const tools = opts.tools || TESTED;
501
514
  for (const t of tools) if (!TOOLS[t]) throw new InitError(`Unknown tool "${t}". Choose from: ${Object.keys(TOOLS).join(', ')}.`);
@@ -579,7 +592,9 @@ function sync(cwd, opts = {}) {
579
592
  const { done, generated, generateError } = finish(cwd, { pkg, deps, tools, files: newFiles, stack, skipGenerate: opts.skipGenerate });
580
593
  report.added.push(...done.created);
581
594
  report.updated.push(...done.merged);
582
- return { report, warnings: done.warnings, from, to: KIT_VERSION, tools, generated, generateError };
595
+ // it started from a clean working tree, so git shows everything it changed (tool configs too)
596
+ const changed = git(cwd, 'status', '--porcelain') !== '';
597
+ return { report, warnings: done.warnings, from, to: KIT_VERSION, tools, changed, generated, generateError };
583
598
  }
584
599
 
585
600
  // what rulesync generates from the project's kit sources, regenerated in an empty folder: [[path, text]]
@@ -649,6 +664,14 @@ function uninstall(cwd, opts = {}) {
649
664
  if (pkgChanged) fs.writeFileSync(path.join(cwd, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`);
650
665
  try { if (git(cwd, 'config', 'core.hooksPath') === '.githooks') git(cwd, 'config', '--unset', 'core.hooksPath'); } catch {}
651
666
 
667
+ // .eslintignore: the kit's lines, and the file if nothing else is in it
668
+ const eiText = readIf(path.join(cwd, '.eslintignore'));
669
+ if (eiText !== null && eiText.split('\n').includes(ESLINT_IGNORE)) {
670
+ const rest = eiText.split('\n').filter(l => l !== ESLINT_IGNORE && l !== ESLINT_NOTE).join('\n').replace(/\n{3,}/g, '\n\n');
671
+ if (!rest.trim()) fs.unlinkSync(path.join(cwd, '.eslintignore')); else fs.writeFileSync(path.join(cwd, '.eslintignore'), rest.replace(/\n*$/, '\n'));
672
+ report.removed.push('.eslintignore (the kit\'s lines)');
673
+ }
674
+
652
675
  report.left.push('.gitignore lines for .env files and .ai/ (they keep secrets and local evidence out of git)');
653
676
  if (scripts.typecheck === 'tsc --noEmit') report.left.push('the "typecheck" script in package.json');
654
677
  return { report, from };
@@ -674,17 +697,17 @@ function printSummary({ report, warnings = [], values, tools, ci, generated, gen
674
697
  more.forEach((m, i) => log(` ${i + 3}. ${m}`));
675
698
  }
676
699
 
677
- function printSync({ report, warnings = [], from, to, generated, generateError }, log = console.log) {
678
- log(`agentic-mobile-kit updated from ${from} to ${to}.`);
700
+ function printSync({ report, warnings = [], from, to, changed, generated, generateError }, log = console.log) {
701
+ log(from === to ? `agentic-mobile-kit is already ${to}.` : `agentic-mobile-kit updated from ${from} to ${to}.`);
679
702
  const lines = [
680
703
  ['updated', report.updated], ['added', report.added], ['removed', report.removed],
681
704
  ['merged with your changes', report.merged], ['CONFLICTS, resolve the <<<<<<< markers', report.conflicts], ['left alone', report.kept],
682
705
  ];
683
706
  for (const [label, files] of lines) if (files.length) log(` ${label}: ${files.join(', ')}`);
684
- if (!Object.values(report).some(a => a.length)) log(' Nothing to change.');
707
+ if (!changed) log(' Nothing changed.');
685
708
  for (const w of warnings) log(` ! ${w}`);
686
709
  if (!generated) log(` ! could not generate tool configs; run: npx -y ${RULESYNC} generate\n${generateError.replace(/^/gm, ' ')}`);
687
- log('\nReview it with "git diff", run the checks, then commit on a branch and open a PR.');
710
+ if (changed) log('\nReview it with "git diff", run the checks, then commit on a branch and open a PR.');
688
711
  }
689
712
 
690
713
  function printUninstall({ report }, log = console.log) {
@@ -694,4 +717,7 @@ function printUninstall({ report }, log = console.log) {
694
717
  log('\nReview it with "git status" and "git diff", then commit. Undo it with git if you change your mind.');
695
718
  }
696
719
 
697
- module.exports = { init, sync, uninstall, printSummary, printSync, printUninstall, InitError, TOOLS, CI, KIT_VERSION, tool, hookManager, hooksWired };
720
+ module.exports = {
721
+ init, sync, uninstall, printSummary, printSync, printUninstall, InitError, TOOLS, TESTED, CI, KIT_VERSION, tool, cleanEnv,
722
+ hookManager, hooksWired, checkProject, recorded, installedCi,
723
+ };
package/lib/menu.js ADDED
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+ // `npx agentic-mobile-kit` with no command, in a terminal: what the kit can do in this app, asked one step at a time.
3
+ // It returns the command to run and prints it, so people learn the commands that scripts, CI and agents use.
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const readline = require('readline');
7
+ const { checkProject, recorded, installedCi, InitError, TOOLS, TESTED, CI, KIT_VERSION, tool, cleanEnv } = require('./init');
8
+
9
+ const NAMES = { claude: 'Claude Code', codex: 'Codex', antigravity: 'Antigravity', cursor: 'Cursor', opencode: 'OpenCode', kiro: 'Kiro' };
10
+ const CI_NAMES = { github: 'GitHub Actions', codemagic: 'Codemagic' };
11
+ const CI_LABELS = { github: 'GitHub Actions: checks on every pull request', codemagic: 'Codemagic: signed store builds' };
12
+ const and = a => (a.length > 1 ? `${a.slice(0, -1).join(', ')} and ${a[a.length - 1]}` : a[0]);
13
+ const newer = (a, b) => a.localeCompare(b, 'en', { numeric: true }) > 0;
14
+ class Closed extends Error {}
15
+
16
+ // the version npm installs now; null when that can't be checked (offline, no npm)
17
+ function latestVersion(cwd) {
18
+ const r = tool('npm', ['view', 'agentic-mobile-kit', 'version'], { cwd, env: cleanEnv(), encoding: 'utf8', timeout: 8000 });
19
+ const v = (r.stdout || '').trim();
20
+ return r.status === 0 && /^\d+\.\d+\.\d+$/.test(v) ? v : null;
21
+ }
22
+
23
+ async function menu(cwd, { input = process.stdin, output = process.stdout, latest = latestVersion } = {}) {
24
+ const rl = readline.createInterface({ input, output });
25
+ // Ctrl-C ends the menu, like Ctrl-D (readline alone would only pause)
26
+ rl.on('SIGINT', () => rl.close());
27
+ let closed = false;
28
+ rl.on('close', () => { closed = true; });
29
+ const lines = rl[Symbol.asyncIterator]();
30
+ const say = s => output.write(`${s}\n`);
31
+ const ask = async q => {
32
+ // piped answers can outlast the input, which closes readline
33
+ if (closed) output.write(q);
34
+ else {
35
+ rl.setPrompt(q);
36
+ rl.prompt();
37
+ }
38
+ const { value, done } = await lines.next();
39
+ if (done) throw new Closed();
40
+ return value.trim();
41
+ };
42
+ const show = (question, items) => {
43
+ say(`\n${question}`);
44
+ items.forEach((it, i) => say(` ${i + 1}. ${it.label}`));
45
+ };
46
+ // one item: Enter takes the default, anything else is asked again
47
+ const pick = async (question, items, def = 0) => {
48
+ show(question, items);
49
+ for (;;) {
50
+ const item = items[Number((await ask(`Choose 1-${items.length} [${def + 1}]: `)) || def + 1) - 1];
51
+ if (item) return item;
52
+ }
53
+ };
54
+ const pickSome = async (question, items, defaults) => {
55
+ show(question, items);
56
+ const def = items.flatMap((it, i) => (defaults.includes(it.value) ? [i + 1] : [])).join(',');
57
+ for (;;) {
58
+ const chosen = ((await ask(`Numbers, separated by commas [${def}]: `)) || def).split(/[\s,]+/).filter(Boolean).map(n => items[Number(n) - 1]);
59
+ if (chosen.length && chosen.every(Boolean)) return items.filter(it => chosen.includes(it)).map(it => it.value);
60
+ }
61
+ };
62
+ const yes = async (question, def) => {
63
+ const a = (await ask(`${question} [${def ? 'Y/n' : 'y/N'}]: `)).toLowerCase();
64
+ return a ? a.startsWith('y') : def;
65
+ };
66
+ const ciItems = groups => [...groups.map(g => ({ label: CI_LABELS[g], value: [g] })), ...(groups.length > 1 ? [{ label: 'Both', value: groups }] : [])];
67
+
68
+ try {
69
+ say(`agentic-mobile-kit ${KIT_VERSION}`);
70
+ // npx can run an older copy it keeps in its cache
71
+ const next = latest(cwd);
72
+ if (next && newer(next, KIT_VERSION) && await yes(`Version ${next} is out. Use it?`, true)) {
73
+ rl.close();
74
+ process.exitCode = tool('npx', ['-y', `agentic-mobile-kit@${next}`], { cwd, stdio: 'inherit', env: cleanEnv() }).status ?? 1;
75
+ return null;
76
+ }
77
+
78
+ let problem = '';
79
+ try { checkProject(cwd); } catch (e) {
80
+ if (!(e instanceof InitError)) throw e;
81
+ problem = e.message;
82
+ }
83
+ let agents = '';
84
+ try { agents = fs.readFileSync(path.join(cwd, 'AGENTS.md'), 'utf8'); } catch {}
85
+ const doctor = { label: 'Check this project and machine (doctor)', args: ['doctor'] };
86
+ const quit = { label: 'Quit', args: null };
87
+ let items;
88
+ let def = 0;
89
+ if (!/<!-- KIT:START/.test(agents)) {
90
+ say('The kit isn\'t installed here.');
91
+ items = [
92
+ { label: `Install it for ${and(TESTED.map(t => NAMES[t]))}, without CI (init)`, args: ['init'], changes: true },
93
+ {
94
+ label: 'Install it and choose the AI tools and CI',
95
+ changes: true,
96
+ steps: async () => {
97
+ const tools = await pickSome('Which AI tools does your team use?',
98
+ Object.keys(TOOLS).map(t => ({ value: t, label: `${NAMES[t]}${TESTED.includes(t) ? '' : ' (not tested yet)'}` })), TESTED);
99
+ const ci = (await pick('Set up CI? Only if the app uses it.', [{ label: 'No CI', value: [] }, ...ciItems(Object.keys(CI))])).value;
100
+ return ['init', ...(String(tools) === String(TESTED) ? [] : ['--tools', tools.join(',')]), ...(ci.length ? ['--ci', ci.join(',')] : [])];
101
+ },
102
+ },
103
+ doctor, quit,
104
+ ];
105
+ } else {
106
+ const from = recorded(agents).version;
107
+ const ci = installedCi(cwd, agents);
108
+ const missing = Object.keys(CI).filter(g => !ci.includes(g));
109
+ const update = !from || newer(KIT_VERSION, from);
110
+ say(`Kit ${from || '(an early version)'} is installed here. CI: ${ci.length ? and(ci.map(g => CI_NAMES[g])) : 'none'}.`);
111
+ if (from && newer(from, KIT_VERSION)) problem ||= `This app has kit ${from}, newer than this copy (${KIT_VERSION}). Run: npx agentic-mobile-kit@latest`;
112
+ items = [
113
+ { label: update ? `Update the kit${from ? ` from ${from}` : ''} to ${KIT_VERSION} (sync)` : 'Sync the kit again; it\'s up to date (sync)', args: ['sync'], changes: true },
114
+ missing.length && {
115
+ label: `Add CI: ${missing.map(g => CI_NAMES[g]).join(' or ')}${update ? ', and update the kit' : ''} (sync --ci)`,
116
+ changes: true,
117
+ steps: async () => ['sync', '--ci', (missing.length > 1 ? (await pick('Which CI?', ciItems(missing))).value : missing).join(',')],
118
+ },
119
+ doctor,
120
+ { label: 'Remove the kit (uninstall)', args: ['uninstall'], changes: true, confirm: 'Remove the kit from this app? Files you changed are kept, and git can undo it.' },
121
+ quit,
122
+ ].filter(Boolean);
123
+ def = update ? 0 : items.indexOf(doctor);
124
+ }
125
+ // installing, updating and removing need a clean git repository: say why they aren't offered
126
+ if (problem) {
127
+ say(`! ${problem}`);
128
+ items = items.filter(it => !it.changes);
129
+ def = 0;
130
+ }
131
+
132
+ const choice = await pick('What would you like to do?', items, def);
133
+ if (choice.confirm && !(await yes(choice.confirm, false))) {
134
+ say('Nothing changed.');
135
+ return null;
136
+ }
137
+ const args = choice.steps ? await choice.steps() : choice.args;
138
+ if (args) say(`\nRunning: npx agentic-mobile-kit ${args.join(' ')}\n`);
139
+ return args;
140
+ } catch (e) {
141
+ if (!(e instanceof Closed)) throw e;
142
+ say('');
143
+ return null;
144
+ } finally {
145
+ rl.close();
146
+ }
147
+ }
148
+
149
+ module.exports = { menu };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-mobile-kit",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "One setup for AI-assisted development of React Native apps, bare or Expo: shared rules and workflows for Claude Code, Codex and Antigravity, git hooks, device checks with screenshots, and release tooling for the App Store and Google Play.",
5
5
  "license": "MIT",
6
6
  "author": "prakashpro1",
@@ -20,14 +20,14 @@ This project may also use other AI workflow frameworks (for example Superpowers,
20
20
  | Lint, typecheck, test (each skips what the app doesn't have yet) | `sh scripts/ai/pm-run.sh lint`, `sh scripts/ai/pm-run.sh typecheck`, `sh scripts/ai/pm-run.sh test` |
21
21
  | Check dependency versions and the app config | `npx expo install --check`, `npx expo-doctor` |
22
22
  | Check on devices (release builds, Maestro flows, screenshots) | `sh scripts/ai/verify.sh all --spec <id>`; another iOS scheme: `--scheme <name>` |
23
- | Specs: progress, format check, fold a finished feature into the living spec | `node scripts/ai/spec.js status`, `node scripts/ai/spec.js check`, `node scripts/ai/spec.js merge <id>` |
23
+ | Specs: progress, format check, fold a finished feature into the living spec | `node scripts/ai/specs.js status`, `node scripts/ai/specs.js check`, `node scripts/ai/specs.js merge <id>` |
24
24
  | Check a release before tagging it (versions, permission texts, debug leftovers) | `node scripts/ai/release-check.js` |
25
25
  | Signed release builds (a person runs them: they use the signing keys) | `sh scripts/ai/release-build.sh android`, `sh scripts/ai/release-build.sh ios` |
26
26
 
27
27
  ## Definition of done
28
28
 
29
29
  A task is done only when:
30
- 1. lint, typecheck and tests pass, and you show the command output from this session;
30
+ 1. `sh scripts/ai/verify.sh quick` passes (lint, typecheck, tests) and you show its output from this session. In an app whose base branch already fails some of them, it passes when your change adds no new failure, and lists the old ones: leave those alone unless the task is to fix them;
31
31
  2. UI changes were checked with `sh scripts/ai/verify.sh all --spec <id>` on both iOS and Android, and you looked at the screenshots. On Windows or Linux, that covers Android only: write in `progress.md` and the PR that iOS still needs checking on a Mac, and the PR isn't merged until a teammate with a Mac has done it;
32
32
  3. the change stays inside the task's scope;
33
33
  4. `specs/<id>/progress.md` is updated, when working from a spec.
@@ -21,5 +21,5 @@ Input: $ARGUMENTS (what's wrong, steps to reproduce, error text, screenshots, ta
21
21
  5. **Make the smallest fix.** Don't refactor or touch unrelated code.
22
22
  6. **Verify.** The new test passes, and lint, typecheck and all tests pass. Paste the output. For UI or native bugs, run `sh scripts/ai/verify.sh ios` and/or `android` and look at the screenshots.
23
23
  7. **Two attempts at most.** If two fixes didn't work, stop. Report what you tried, what you learned and what you suspect next.
24
- 8. **Record it.** If this kind of error could come back, add an entry to `docs/ai/known-issues.md` (error, cause, fix, prevention). If the fix changes what the app is meant to do, not just makes it work as specified, update that requirement in `specs/current/<area>.md` in the same format, and run `node scripts/ai/spec.js check`.
24
+ 8. **Record it.** If this kind of error could come back, add an entry to `docs/ai/known-issues.md` (error, cause, fix, prevention). If the fix changes what the app is meant to do, not just makes it work as specified, update that requirement in `specs/current/<area>.md` in the same format, and run `node scripts/ai/specs.js check`.
25
25
  9. **Commit** with a message ending in `Assisted-by: <tool>/<model>`. Ask the user before pushing, then open a PR with the evidence.
@@ -13,7 +13,7 @@ Input: $ARGUMENTS (a spec ID, or empty).
13
13
  1. **Check git first.** Run `git fetch` and `git status`.
14
14
  - If the branch is behind its remote, say so and ask before pulling.
15
15
  - If there are uncommitted changes, list them; they may be half-done work.
16
- 2. **Find the spec.** Use the given ID; otherwise run `node scripts/ai/spec.js status` and take the spec in progress that was updated most recently. If unsure, ask.
16
+ 2. **Find the spec.** Use the given ID; otherwise run `node scripts/ai/specs.js status` and take the spec in progress that was updated most recently. If unsure, ask.
17
17
  3. **Read** `requirements.md`, `design.md`, `tasks.md` and `progress.md` in that spec folder, plus `git log --oneline -15`.
18
18
  4. **Report back, in this order:**
19
19
  1. any open question or blocker from the handoff;
@@ -21,7 +21,7 @@ If the input describes a bug rather than new behavior, suggest `m-bugfix` and st
21
21
  1. Pick an ID: the task's ID if it has one, otherwise `YYYYMMDD-<slug>`. Copy `specs/_templates/` to `specs/<id>/`.
22
22
  2. Read `specs/current/<area>.md` for each area this touches: it says what the app does now. In an area with no living spec yet, read the code that implements it.
23
23
  3. **One intent.** The feature should be one thing you can say in a sentence. If it needs "and also", suggest splitting it into separate features, and ask.
24
- 4. Fill `requirements.md`: the goal; the requirements under `## ADDED`, `## MODIFIED` and `## REMOVED Requirements: <area>` (the format is in `specs/current/README.md`), with one SHALL per requirement and scenarios for the cases that matter; every edge-case line (or "n/a"); out of scope; open questions. Then run `node scripts/ai/spec.js check specs/<id>/requirements.md`.
24
+ 4. Fill `requirements.md`: the goal; the requirements under `## ADDED`, `## MODIFIED` and `## REMOVED Requirements: <area>` (the format is in `specs/current/README.md`), with one SHALL per requirement and scenarios for the cases that matter; every edge-case line (or "n/a"); out of scope; open questions. Then run `node scripts/ai/specs.js check specs/<id>/requirements.md`.
25
25
  5. If something is unclear, ask the user **one question at a time**. Don't fill gaps with guesses.
26
26
  6. Show the requirements and **stop until the user approves them**. Give the user these questions to check them against:
27
27
  - Is this the problem you asked me to solve, with nothing extra in scope?
@@ -55,7 +55,7 @@ When all tasks are done:
55
55
 
56
56
  ## 6. Update the living spec
57
57
 
58
- Run `node scripts/ai/spec.js merge <id>`. It applies the ADDED, MODIFIED and REMOVED requirements to `specs/current/` and notes the source of each. If it refuses, the reason is usually that a requirement listed as ADDED already exists, or one listed as MODIFIED doesn't. Fix `requirements.md` and run it again. Commit `specs/current/` with the feature, so reviewers see the change in behavior.
58
+ Run `node scripts/ai/specs.js merge <id>`. It applies the ADDED, MODIFIED and REMOVED requirements to `specs/current/` and notes the source of each. If it refuses, the reason is usually that a requirement listed as ADDED already exists, or one listed as MODIFIED doesn't. Fix `requirements.md` and run it again. Commit `specs/current/` with the feature, so reviewers see the change in behavior.
59
59
 
60
60
  ## 7. Review and pull request
61
61
 
@@ -17,7 +17,7 @@ If your tool has subagents, hand the review to the `m-reviewer` subagent, so it
17
17
  - **Against the spec**, when there is one:
18
18
  - *Complete:* every task is ticked, every requirement is implemented, and every scenario has evidence (a test or a screenshot).
19
19
  - *Correct:* the code does what each requirement says, edge cases included, and nothing outside the agreed scope.
20
- - *Coherent:* the decisions in `design.md` show up in the code, and `specs/current/` was updated (`node scripts/ai/spec.js merge <id>`) if behavior changed.
20
+ - *Coherent:* the decisions in `design.md` show up in the code, and `specs/current/` was updated (`node scripts/ai/specs.js merge <id>`) if behavior changed.
21
21
  - **No spec:** does the diff do what was asked, and nothing unrelated?
22
22
  - **Tests:** were tests added for new logic? Were any tests deleted, skipped or weakened?
23
23
  - **Both platforms:** anything iOS-only or Android-only (insets, back button, permissions, keyboard)?
@@ -9,7 +9,7 @@ staged=$(git diff --cached --name-only --diff-filter=ACMR)
9
9
  fail() { echo "pre-commit: $*" >&2; exit 1; }
10
10
 
11
11
  # 1. files that must never be committed
12
- if echo "$staged" | grep -E '(^|/)\.env(\..+)?$' | grep -qv '\.env\.example$'; then
12
+ if echo "$staged" | grep -E '(^|/)\.env(\..+)?$' | grep -qvE '\.(example|sample|template)$'; then
13
13
  fail "don't commit .env files; keep secrets out of git"
14
14
  fi
15
15
  if echo "$staged" | grep -qE '\.(keystore|jks|p8|p12|mobileprovision)$'; then
@@ -30,8 +30,8 @@ if command -v plutil > /dev/null; then
30
30
  done
31
31
  fi
32
32
 
33
- # 4. lint the staged JS/TS files with the project's own ESLint config
34
- files=$(echo "$staged" | grep -E '\.(js|jsx|ts|tsx)$' || true)
33
+ # 4. lint the staged JS/TS files with the project's own ESLint config (the kit's own scripts aren't the app's code)
34
+ files=$(echo "$staged" | grep -E '\.(js|jsx|ts|tsx)$' | grep -v '^scripts/ai/' || true)
35
35
  if [ -n "$files" ]; then
36
36
  if [ -x node_modules/.bin/eslint ]; then
37
37
  # ponytail: file names with spaces aren't supported here; split on newlines if that ever matters
@@ -43,8 +43,8 @@ fi
43
43
 
44
44
  # 5. spec format: requirements in force need a SHALL and a scenario (format: specs/current/README.md)
45
45
  specs=$(echo "$staged" | grep -E '^specs/([^_/][^/]*/requirements|current/[^/]+)\.md$' | grep -v '^specs/current/README\.md$' || true)
46
- if [ -n "$specs" ] && [ -f scripts/ai/spec.js ]; then
47
- node scripts/ai/spec.js check --skip-drafts $specs || fail "fix the spec format above (format: specs/current/README.md)"
46
+ if [ -n "$specs" ] && [ -f scripts/ai/specs.js ]; then
47
+ node scripts/ai/specs.js check --skip-drafts $specs || fail "fix the spec format above (format: specs/current/README.md)"
48
48
  fi
49
49
 
50
50
  # 6. files renamed only in letter case on macOS or Windows: git still has the old name, so other machines can't find them
@@ -2,5 +2,6 @@
2
2
  # agentic-mobile-kit pre-push: typecheck and tests before code leaves the machine.
3
3
  set -eu
4
4
  [ -d node_modules ] || { echo "pre-push: dependencies aren't installed; run: sh scripts/ai/install-deps.sh" >&2; exit 1; }
5
- sh scripts/ai/pm-run.sh typecheck || { echo "pre-push: fix the type errors above" >&2; exit 1; }
6
- CI=true sh scripts/ai/pm-run.sh test || { echo "pre-push: fix the failing tests above" >&2; exit 1; }
5
+ # each passes when the app's script passes, or when all its failures were already on the base branch
6
+ node scripts/ai/baseline.js typecheck || { echo "pre-push: fix the new type errors above" >&2; exit 1; }
7
+ node scripts/ai/baseline.js test || { echo "pre-push: fix the new test failures above" >&2; exit 1; }
@@ -25,9 +25,14 @@ jobs:
25
25
  with:
26
26
  node-version: 24
27
27
  - run: sh scripts/ai/install-deps.sh
28
- - run: sh scripts/ai/pm-run.sh lint
29
- - run: sh scripts/ai/pm-run.sh typecheck
30
- - run: CI=true sh scripts/ai/pm-run.sh test
28
+ # each passes when the app's script passes, or when all its failures were already on the base branch
29
+ - name: Lint, typecheck and tests
30
+ env:
31
+ AMK_BASE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || github.event.before }}
32
+ run: |
33
+ node scripts/ai/baseline.js lint
34
+ node scripts/ai/baseline.js typecheck
35
+ node scripts/ai/baseline.js test
31
36
  - name: Tool configs match .rulesync/ (run "npx -y rulesync@27.0.0 generate" and commit if this fails)
32
37
  if: hashFiles('rulesync.jsonc') != ''
33
38
  run: npx -y rulesync@27.0.0 generate > /dev/null && git diff --exit-code -- .claude .codex .agents .antigravity
@@ -20,14 +20,14 @@ This project may also use other AI workflow frameworks (for example Superpowers,
20
20
  | iOS build (simulator, no signing) | `sh scripts/ai/ios-build.sh` |
21
21
  | Android build | `cd android && ./gradlew assembleDebug` |
22
22
  | Check on devices (release builds, Maestro flows, screenshots) | `sh scripts/ai/verify.sh all --spec <id>`; with product flavors it checks the first unless `--flavor <name>`; another iOS scheme: `--scheme <name>` |
23
- | Specs: progress, format check, fold a finished feature into the living spec | `node scripts/ai/spec.js status`, `node scripts/ai/spec.js check`, `node scripts/ai/spec.js merge <id>` |
23
+ | Specs: progress, format check, fold a finished feature into the living spec | `node scripts/ai/specs.js status`, `node scripts/ai/specs.js check`, `node scripts/ai/specs.js merge <id>` |
24
24
  | Check a release before tagging it (versions, permission texts, debug leftovers) | `node scripts/ai/release-check.js` |
25
25
  | Signed release builds (a person runs them: they use the signing keys) | `sh scripts/ai/release-build.sh android [flavor]`, `sh scripts/ai/release-build.sh ios [scheme]` |
26
26
 
27
27
  ## Definition of done
28
28
 
29
29
  A task is done only when:
30
- 1. lint, typecheck and tests pass, and you show the command output from this session;
30
+ 1. `sh scripts/ai/verify.sh quick` passes (lint, typecheck, tests) and you show its output from this session. In an app whose base branch already fails some of them, it passes when your change adds no new failure, and lists the old ones: leave those alone unless the task is to fix them;
31
31
  2. UI changes were checked with `sh scripts/ai/verify.sh all --spec <id>` on both iOS and Android, and you looked at the screenshots. On Windows or Linux, that covers Android only: write in `progress.md` and the PR that iOS still needs checking on a Mac, and the PR isn't merged until a teammate with a Mac has done it;
32
32
  3. the change stays inside the task's scope;
33
33
  4. `specs/<id>/progress.md` is updated, when working from a spec.
@@ -0,0 +1,201 @@
1
+ #!/usr/bin/env node
2
+ // Runs the app's lint, typecheck or test script. When it fails, it compares the problems with the base branch and
3
+ // passes if all of them were there already: an app that starts with lint errors or failing tests can still show
4
+ // that a change made nothing worse. What counts as new:
5
+ // lint ESLint errors in the files changed since the base, compared with those files at the base
6
+ // typecheck TypeScript errors (file, code, message), compared with a type check of the base
7
+ // test failing Jest tests and test files, compared with a test run of the base
8
+ // The base: AMK_BASE, else the remote's default branch, else main or master. Its merge base is checked out once
9
+ // into a temporary git worktree that shares node_modules, and its results are kept for the next run.
10
+ // Usage: node scripts/ai/baseline.js lint|typecheck|test
11
+ 'use strict';
12
+ const fs = require('fs');
13
+ const os = require('os');
14
+ const path = require('path');
15
+ const crypto = require('crypto');
16
+ const { spawnSync, execFileSync } = require('child_process');
17
+
18
+ const check = process.argv[2];
19
+ if (!['lint', 'typecheck', 'test'].includes(check)) {
20
+ console.error('usage: node scripts/ai/baseline.js lint|typecheck|test');
21
+ process.exit(2);
22
+ }
23
+ const root = process.cwd();
24
+ const git = (...args) => {
25
+ try {
26
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 2 ** 28 }).trim();
27
+ } catch {
28
+ return '';
29
+ }
30
+ };
31
+ const hash = s => crypto.createHash('sha1').update(s).digest('hex').slice(0, 12);
32
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
33
+ const jest = check === 'test' && /\bjest\b/.test((pkg.scripts || {}).test || '');
34
+ // the real path: on macOS the temp folder is behind a symlink, and test runners report real paths
35
+ const scratch = path.join(fs.realpathSync(os.tmpdir()), 'amk-baseline', hash(root));
36
+ const slash = p => p.split(path.sep).join('/');
37
+ // a minus b, counting duplicates
38
+ const minus = (a, b) => {
39
+ const left = [...b];
40
+ return a.filter(x => {
41
+ const i = left.indexOf(x);
42
+ if (i < 0) return true;
43
+ left.splice(i, 1);
44
+ return false;
45
+ });
46
+ };
47
+
48
+ // the package.json script, through pm-run.sh, in dir (the app, or the base's worktree)
49
+ function runScript(dir) {
50
+ fs.mkdirSync(scratch, { recursive: true });
51
+ const json = path.join(scratch, `jest-${hash(dir)}.json`);
52
+ fs.rmSync(json, { force: true });
53
+ const r = spawnSync('sh', [path.join(root, 'scripts/ai/pm-run.sh'), check, ...(jest ? ['--json', `--outputFile=${json}`] : [])],
54
+ { cwd: dir, encoding: 'utf8', env: { ...process.env, CI: 'true' }, maxBuffer: 2 ** 28 });
55
+ return { code: r.status, out: `${r.stdout || ''}${r.stderr || ''}`, json, dir };
56
+ }
57
+
58
+ // TypeScript errors without their position, which moves when lines are added above them
59
+ function typeErrors(r) {
60
+ const errors = [...r.out.matchAll(/^(\S.*?)\(\d+,\d+\): error (TS\d+): (.*)$/gm)].map(m => `${slash(m[1])}: ${m[2]} ${m[3]}`);
61
+ return errors.length ? errors : null;
62
+ }
63
+
64
+ // failing tests, and test files that fail to run, from Jest's JSON report
65
+ function failingTests(r) {
66
+ let report;
67
+ try {
68
+ report = JSON.parse(fs.readFileSync(r.json, 'utf8'));
69
+ } catch {
70
+ return null;
71
+ }
72
+ return report.testResults.flatMap(suite => {
73
+ const file = slash(path.relative(r.dir, suite.name));
74
+ const failed = (suite.assertionResults || []).filter(a => a.status === 'failed').map(a => `${file} › ${a.fullName}`);
75
+ return failed.length || suite.status !== 'failed' ? failed : [`${file} (the file fails to run)`];
76
+ });
77
+ }
78
+
79
+ function baseRef() {
80
+ if (process.env.AMK_BASE) return process.env.AMK_BASE;
81
+ const remoteDefault = git('symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD');
82
+ return [remoteDefault, 'origin/main', 'origin/master', 'main', 'master'].find(r => r && git('rev-parse', '--verify', '--quiet', `${r}^{commit}`));
83
+ }
84
+
85
+ // the base commit, checked out once into a temporary worktree that shares the app's node_modules
86
+ function baseWorktree(sha) {
87
+ const dir = path.join(scratch, sha);
88
+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
89
+ for (const old of fs.readdirSync(scratch).filter(f => !f.startsWith(sha) && /^[0-9a-f]{40}/.test(f))) {
90
+ git('worktree', 'remove', '--force', path.join(scratch, old));
91
+ fs.rmSync(path.join(scratch, old), { recursive: true, force: true });
92
+ }
93
+ git('worktree', 'prune');
94
+ execFileSync('git', ['worktree', 'add', '--detach', '--force', dir, sha], { cwd: root, stdio: 'ignore' });
95
+ if (fs.existsSync(path.join(root, 'node_modules'))) fs.symlinkSync(path.join(root, 'node_modules'), path.join(dir, 'node_modules'), 'junction');
96
+ return dir;
97
+ }
98
+
99
+ function baseProblems(sha, extract) {
100
+ const cache = path.join(scratch, `${sha}.${check}.json`);
101
+ try {
102
+ return JSON.parse(fs.readFileSync(cache, 'utf8'));
103
+ } catch {}
104
+ const dir = baseWorktree(sha);
105
+ // the same check on the old code: the app's current script, which the base may not have yet (the kit adds typecheck)
106
+ const basePkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
107
+ if ((basePkg.scripts || {})[check] !== pkg.scripts[check]) {
108
+ basePkg.scripts = { ...basePkg.scripts, [check]: pkg.scripts[check] };
109
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(basePkg, null, 2));
110
+ }
111
+ const r = runScript(dir);
112
+ const problems = r.code === 0 ? [] : extract(r);
113
+ if (problems) fs.writeFileSync(cache, JSON.stringify(problems));
114
+ return problems;
115
+ }
116
+
117
+ // ESLint errors in the files changed since the base, minus the errors those files had at the base. Errors in
118
+ // files the change didn't touch were there before, unless the change edits the ESLint setup itself.
119
+ function newLintErrors(sha) {
120
+ const changed = [...new Set([...git('diff', '--name-only', '--diff-filter=ACMR', sha).split('\n'),
121
+ ...git('ls-files', '--others', '--exclude-standard').split('\n')])].filter(Boolean);
122
+ // the kit's own .eslintignore lines (for scripts/ai/) don't change how the app's code is checked
123
+ const withoutKit = t => t.split('\n').filter(l => l.trim() !== 'scripts/ai/' && !l.startsWith('# agentic-mobile-kit')).join('\n').trim();
124
+ const setup = changed.filter(f => /(^|\/)(\.eslintrc(\.\w+)?|eslint\.config\.\w+|\.eslintignore)$/.test(f))
125
+ .filter(f => path.basename(f) !== '.eslintignore' || withoutKit(git('show', `${sha}:${f}`)) !== withoutKit(fs.readFileSync(path.join(root, f), 'utf8')));
126
+ if (setup.length) return { reason: `the change edits the ESLint setup (${setup.join(', ')}), so any error could be new` };
127
+ // ESLint 8 and 9 export only package.json, so find the CLI next to it
128
+ let eslint;
129
+ try {
130
+ eslint = path.join(path.dirname(require.resolve('eslint/package.json', { paths: [root] })), 'bin', 'eslint.js');
131
+ if (!fs.existsSync(eslint)) throw new Error('no CLI');
132
+ } catch {
133
+ return { reason: 'ESLint isn\'t installed' };
134
+ }
135
+ const lint = (args, input) => {
136
+ const r = spawnSync(process.execPath, [eslint, '--format', 'json', ...args], { cwd: root, input, encoding: 'utf8', maxBuffer: 2 ** 28 });
137
+ try {
138
+ return JSON.parse(r.stdout);
139
+ } catch {
140
+ return null;
141
+ }
142
+ };
143
+ const errors = results => (results || []).flatMap(f => f.messages.filter(m => m.severity === 2).map(m => `${m.ruleId || 'parsing'}: ${m.message}`));
144
+ const files = changed.filter(f => /\.(js|jsx|ts|tsx)$/.test(f) && !f.startsWith('scripts/ai/') && fs.existsSync(path.join(root, f)));
145
+ const results = files.length ? lint(files) : [];
146
+ if (!results) return { reason: 'ESLint gave no report' };
147
+ const fresh = [];
148
+ for (const result of results) {
149
+ const file = slash(path.relative(root, result.filePath));
150
+ const now = errors([result]);
151
+ if (!now.length) continue;
152
+ let before = [];
153
+ if (git('rev-parse', '--verify', '--quiet', `${sha}:${file}`)) {
154
+ const text = execFileSync('git', ['show', `${sha}:${file}`], { cwd: root, encoding: 'utf8', maxBuffer: 2 ** 28 });
155
+ before = errors(lint(['--stdin', '--stdin-filename', file], text));
156
+ }
157
+ fresh.push(...minus(now, before).map(p => `${file}: ${p}`));
158
+ }
159
+ return { fresh, files: files.length };
160
+ }
161
+
162
+ const now = runScript(root);
163
+ process.stdout.write(now.out);
164
+ if (now.code === 0) process.exit(0);
165
+
166
+ const base = baseRef();
167
+ const sha = base && git('merge-base', 'HEAD', base);
168
+ if (!sha) {
169
+ console.log(`${check}: failed, and there's no base branch to compare with (set AMK_BASE)`);
170
+ process.exit(1);
171
+ }
172
+ const label = `${base} (${sha.slice(0, 7)})`;
173
+ let fresh;
174
+ let summary;
175
+ if (check === 'lint') {
176
+ const r = newLintErrors(sha);
177
+ if (r.reason) {
178
+ console.log(`lint: failed, and it can't be compared with ${label}: ${r.reason}`);
179
+ process.exit(1);
180
+ }
181
+ fresh = r.fresh;
182
+ summary = `lint: failed, but the ${r.files} file(s) changed since ${label} have no new errors: the failures were there already`;
183
+ } else {
184
+ const extract = check === 'typecheck' ? typeErrors : failingTests;
185
+ const mine = check === 'test' && !jest ? null : extract(now);
186
+ const old = mine && baseProblems(sha, extract);
187
+ if (!mine || !old) {
188
+ console.log(`${check}: failed, and it can't be compared with ${label}: ${check === 'test' && !jest ? 'only Jest results can be compared' : 'its output couldn\'t be read'}`);
189
+ process.exit(1);
190
+ }
191
+ fresh = minus(mine, old);
192
+ summary = `${check}: ${mine.length} problem(s), all already on ${label}: this change adds none`;
193
+ }
194
+ if (!fresh.length) {
195
+ console.log(summary);
196
+ process.exit(0);
197
+ }
198
+ console.log(`${check}: ${fresh.length} new compared with ${label}:`);
199
+ for (const p of fresh.slice(0, 30)) console.log(` ${p}`);
200
+ if (fresh.length > 30) console.log(` … and ${fresh.length - 30} more`);
201
+ process.exit(1);
@@ -6,7 +6,7 @@
6
6
  const fs = require('fs');
7
7
  const { execFileSync } = require('child_process');
8
8
 
9
- const tracked = execFileSync('git', ['ls-files', '-z'], { encoding: 'utf8', maxBuffer: 1 << 30 }).split('\0').filter(Boolean);
9
+ const tracked = execFileSync('git', ['ls-files', '-z'], { encoding: 'utf8', maxBuffer: 2 ** 30 }).split('\0').filter(Boolean);
10
10
  const listings = new Map();
11
11
  const names = dir => {
12
12
  if (!listings.has(dir)) { try { listings.set(dir, new Set(fs.readdirSync(dir || '.'))); } catch { listings.set(dir, null); } }
@@ -22,7 +22,8 @@ const paths = [];
22
22
  })(payload, '');
23
23
 
24
24
  const destructive = /\brm\s+(-[a-z]*r[a-z]*f|-[a-z]*f[a-z]*r|-r\s+-f|-f\s+-r)\b|git\s+reset\s+--hard|git\s+push\s+(.*\s)?(--force|-f)\b|git\s+clean\s+-[a-z]*f|--no-verify|xcrun\s+simctl\s+erase/;
25
- const secretFile = /(^|[\s/'"=])\.env(\.(?!example\b)[\w.-]+)?(?=$|[\s'";|&)])|\.(keystore|jks|p8|p12|mobileprovision)\b/;
25
+ // example files (.env.example, .env.local.example, .env.sample, .env.template) aren't secrets
26
+ const secretFile = /(^|[\s/'"=])\.env(?![\w.-]*\.(?:example|sample|template)(?=$|[\s'";|&)]))(\.[\w.-]+)?(?=$|[\s'";|&)])|\.(keystore|jks|p8|p12|mobileprovision)\b/;
26
27
 
27
28
  const block = reason => { process.stderr.write(`Blocked by scripts/ai/guard.js: ${reason}\n`); process.exit(2); };
28
29
  for (const c of commands) {
@@ -15,7 +15,15 @@ if [ "$config" = Release ]; then
15
15
  [ -n "$config" ] || config=Release
16
16
  fi
17
17
 
18
+ # only this Mac's simulator architecture: a Release build would otherwise compile Intel and Apple silicon both,
19
+ # and fail to link libraries that ship without an Intel simulator slice. Not when the project or a pod excludes it
20
+ # for the simulator (Google's ML Kit pods exclude arm64): then Xcode builds what the project allows.
21
+ arch=x86_64
22
+ [ "$(sysctl -n hw.optional.arm64 2> /dev/null)" != 1 ] || arch=arm64
23
+ set -- ARCHS="$arch"
24
+ ! grep -rqsE "EXCLUDED_ARCHS\[sdk=iphonesimulator\*\]\"? = [^;]*$arch" ios/*.xcodeproj/project.pbxproj "ios/Pods/Target Support Files" || set --
25
+
18
26
  xcodebuild -workspace "$workspace" -scheme "$scheme" -configuration "$config" \
19
27
  -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' \
20
- -derivedDataPath ios/DerivedData CODE_SIGNING_ALLOWED=NO -quiet build
28
+ -derivedDataPath ios/DerivedData "$@" CODE_SIGNING_ALLOWED=NO -quiet build
21
29
  echo "iOS simulator build OK ($scheme, $config)"
@@ -0,0 +1,20 @@
1
+ # Sourced by verify.sh. Test logins and other values that Maestro flows read as ${MAESTRO_…} come from a local,
2
+ # gitignored .maestro/.env.local (or .maestro/.env), as KEY=value lines. Only MAESTRO_ keys are read: the values
3
+ # are never evaluated or printed, and a value already set in the shell wins. Maestro passes MAESTRO_ variables to flows.
4
+ for amk_file in .maestro/.env.local .maestro/.env; do
5
+ [ -f "$amk_file" ] || continue
6
+ while IFS= read -r amk_line || [ -n "$amk_line" ]; do
7
+ amk_line=$(printf %s "$amk_line" | tr -d '\r')
8
+ case $amk_line in MAESTRO_*=*) ;; *) continue ;; esac
9
+ amk_key=${amk_line%%=*}
10
+ amk_value=${amk_line#*=}
11
+ case $amk_key in *[!A-Za-z0-9_]*) continue ;; esac
12
+ [ -z "$(printenv "$amk_key")" ] || continue
13
+ case $amk_value in
14
+ \"*\") amk_value=${amk_value#\"}; amk_value=${amk_value%\"} ;;
15
+ \'*\') amk_value=${amk_value#\'}; amk_value=${amk_value%\'} ;;
16
+ esac
17
+ export "$amk_key=$amk_value"
18
+ done < "$amk_file"
19
+ done
20
+ unset amk_file amk_line amk_key amk_value
@@ -44,7 +44,7 @@ function expoConfig() {
44
44
  fail('Expo isn\'t installed, so the app config can\'t be read', 'install dependencies first: sh scripts/ai/install-deps.sh');
45
45
  return null;
46
46
  }
47
- const r = spawnSync(process.execPath, [cli, 'config', '--type', 'introspect', '--json'], { encoding: 'utf8', maxBuffer: 1 << 28 });
47
+ const r = spawnSync(process.execPath, [cli, 'config', '--type', 'introspect', '--json'], { encoding: 'utf8', maxBuffer: 2 ** 28 });
48
48
  try { return JSON.parse(r.stdout); } catch {
49
49
  fail('Couldn\'t read the Expo app config', (r.stderr || '').trim().split('\n').pop() || 'run: npx expo config');
50
50
  return null;
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  // Specs: check their format, fold a finished feature into the living spec, and show progress.
3
- // node scripts/ai/spec.js check [--skip-drafts] [files…] format of specs/<id>/requirements.md and specs/current/*.md
4
- // (default: all; --skip-drafts leaves out specs whose work hasn't started)
5
- // node scripts/ai/spec.js merge <id> apply specs/<id>/requirements.md's ADDED/MODIFIED/REMOVED sections to specs/current/
6
- // node scripts/ai/spec.js status each spec's status and task progress, and the living spec's size
3
+ // node scripts/ai/specs.js check [--skip-drafts] [files…] format of specs/<id>/requirements.md and specs/current/*.md
4
+ // (default: all; --skip-drafts leaves out specs whose work hasn't started)
5
+ // node scripts/ai/specs.js merge <id> apply specs/<id>/requirements.md's ADDED/MODIFIED/REMOVED sections to specs/current/
6
+ // node scripts/ai/specs.js status each spec's status and task progress, and the living spec's size
7
7
  // A requirement is "### Requirement: <name>", a sentence with SHALL or MUST, and at least one
8
8
  // "#### Scenario: <case>" with WHEN and THEN. Changes are "## ADDED Requirements: <area>" (and MODIFIED, REMOVED),
9
9
  // where <area> names the file specs/current/<area>.md. Format: specs/current/README.md.
@@ -14,7 +14,6 @@ const path = require('path');
14
14
  const [cmd, ...args] = process.argv.slice(2);
15
15
  const read = f => { try { return fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n'); } catch { return null; } };
16
16
  const key = name => name.trim().toLowerCase();
17
- const isRequirement = l => /^### Requirement:/.test(l);
18
17
 
19
18
  // "### Requirement:" blocks between lines [from, to): each runs to the next heading of level 1-3
20
19
  function blocks(lines, from = 0, to = lines.length) {
@@ -214,6 +213,6 @@ if (cmd === 'check') {
214
213
  } else if (cmd === 'status') {
215
214
  process.exitCode = status();
216
215
  } else {
217
- console.log(fs.readFileSync(__filename, 'utf8').split('\n').slice(1, 10).map(l => l.replace(/^\/\/ ?/, '')).join('\n'));
216
+ console.log(fs.readFileSync(process.argv[1], 'utf8').split('\n').slice(1, 9).map(l => l.replace(/^\/\/ ?/, '')).join('\n'));
218
217
  process.exitCode = 1;
219
218
  }
@@ -14,6 +14,7 @@
14
14
  # (no flows found: a smoke check that launches the app and takes a screenshot)
15
15
  # Env: AMK_ANDROID_FLAVOR, AMK_IOS_SCHEME (defaults for the two options), AMK_IOS_DEVICE (simulator name
16
16
  # or UDID), AMK_ANDROID_DEVICE (adb serial, when several are connected), AMK_ANDROID_AVD (emulator to start)
17
+ # Flows that log in read ${MAESTRO_EMAIL} and the like from a local, gitignored .maestro/.env.local (never committed).
17
18
  set -eu
18
19
 
19
20
  mode=${1:-all}
@@ -34,6 +35,7 @@ while [ $# -gt 0 ]; do
34
35
  done
35
36
 
36
37
  root=$(pwd)
38
+ . scripts/ai/maestro-env.sh
37
39
  evidence="$root/.ai/evidence/${label:-${spec:-$(date +%Y%m%d-%H%M%S)}}"
38
40
  mkdir -p "$evidence"
39
41
  status=0
@@ -77,14 +79,17 @@ run_flows() { # platform device app_id
77
79
  }
78
80
 
79
81
  quick() {
80
- if sh scripts/ai/pm-run.sh lint > "$evidence/lint.log" 2>&1 &&
81
- sh scripts/ai/pm-run.sh typecheck > "$evidence/typecheck.log" 2>&1 &&
82
- CI=true sh scripts/ai/pm-run.sh test > "$evidence/test.log" 2>&1; then
82
+ # each one passes when the app's script passes, or when all its failures were already on the base branch
83
+ if node scripts/ai/baseline.js lint > "$evidence/lint.log" 2>&1 &&
84
+ node scripts/ai/baseline.js typecheck > "$evidence/typecheck.log" 2>&1 &&
85
+ node scripts/ai/baseline.js test > "$evidence/test.log" 2>&1; then
83
86
  echo "quick: lint, typecheck and tests passed"
84
- # what didn't run (no such script, or an Expo app without ESLint yet)
85
- cat "$evidence/lint.log" "$evidence/typecheck.log" "$evidence/test.log" | sed -n 's/^skip: / skipped: /p'
87
+ # what didn't run (no such script, or an Expo app without ESLint yet), and failures the base branch already had
88
+ cat "$evidence/lint.log" "$evidence/typecheck.log" "$evidence/test.log" |
89
+ sed -n -E -e 's/^skip: / skipped: /p' -e 's/^(lint|typecheck|test): / \1: /p'
86
90
  else
87
91
  echo "quick: FAILED, see the logs in ${evidence#"$root"/}"
92
+ cat "$evidence/lint.log" "$evidence/typecheck.log" "$evidence/test.log" 2> /dev/null | sed -n -E '/^(lint|typecheck|test): /,/^[^ ]/p' | head -n 20
88
93
  status=1
89
94
  fi
90
95
  }
@@ -1,5 +1,6 @@
1
1
  # Copy to .maestro/<id>.yaml. verify.sh runs it on iOS and Android and keeps the screenshots as evidence.
2
2
  # Tap by testID (give every interactive element one); tapping by text can hit a label instead of the control.
3
+ # Test logins: ${MAESTRO_EMAIL}, ${MAESTRO_PASSWORD} and the like, set in .maestro/.env.local, which isn't committed.
3
4
  appId: ${APP_ID} # set by verify.sh
4
5
  ---
5
6
  - launchApp:
@@ -2,7 +2,7 @@
2
2
 
3
3
  One file per area of the app (for example `login.md` or `tasks.md`) that describes how the app behaves today, requirement by requirement. AI tools read it before they change an area, so they don't have to work out the current behavior from the code.
4
4
 
5
- It starts empty and grows one change at a time; there's no need to describe the whole app up front. Each feature's `specs/<id>/requirements.md` lists what it adds, changes and removes, and when the feature is done, `node scripts/ai/spec.js merge <id>` applies those changes here. People can edit these files too.
5
+ It starts empty and grows one change at a time; there's no need to describe the whole app up front. Each feature's `specs/<id>/requirements.md` lists what it adds, changes and removes, and when the feature is done, `node scripts/ai/specs.js merge <id>` applies those changes here. People can edit these files too.
6
6
 
7
7
  ## Format
8
8
 
@@ -37,4 +37,4 @@ A feature's `requirements.md` groups its requirements under these headings, wher
37
37
  - `## MODIFIED Requirements: <area>`: behavior that changes. Copy the current requirement, keep its name, and edit it. Merging replaces the old one.
38
38
  - `## REMOVED Requirements: <area>`: behavior that goes away, with a line on why. Merging deletes it, and deletes the file when its last requirement goes.
39
39
 
40
- `node scripts/ai/spec.js check` checks the format; the git pre-commit hook runs it on staged specs once their work has started. `node scripts/ai/spec.js status` lists every feature's state and task progress.
40
+ `node scripts/ai/specs.js check` checks the format; the git pre-commit hook runs it on staged specs once their work has started. `node scripts/ai/specs.js status` lists every feature's state and task progress.