agentic-mobile-kit 0.7.11 → 0.7.13

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/lib/doctor.js CHANGED
@@ -4,7 +4,7 @@ const fs = require('fs');
4
4
  const os = require('os');
5
5
  const path = require('path');
6
6
  const { spawnSync } = require('child_process');
7
- const { tool, hookManager, hooksWired, checkProject, emptyFolder } = require('./init');
7
+ const { tool, hookManager, hooksWired, kitRun, checkProject, emptyFolder } = require('./init');
8
8
  const screens = require('../stacks/react-native/template/scripts/amk/screens.js');
9
9
 
10
10
  const RULESYNC = 'rulesync@27.0.0';
@@ -57,7 +57,7 @@ function projectChecks(cwd, opts) {
57
57
  ? ok('Git hooks active')
58
58
  : fail('Git hooks not active on this clone', 'run: git config core.hooksPath .githooks (your package manager\'s install does this too)'));
59
59
  } else if (manager.manual) {
60
- out.push(warn(`Git hooks run from ${manager.name}, without the kit's checks`, 'add "sh .githooks/pre-commit" and "sh .githooks/pre-push" to those hooks'));
60
+ out.push(warn(`Git hooks run from ${manager.name}, without the kit's checks`, `add "${kitRun('pre-commit')}" and "${kitRun('pre-push')}" to those hooks`));
61
61
  } else if (!hooksWired(cwd, manager)) {
62
62
  out.push(fail(`The kit's checks aren't in your ${manager.name} hooks`, 'run: npx agentic-mobile-kit sync'));
63
63
  } else {
@@ -68,6 +68,10 @@ function projectChecks(cwd, opts) {
68
68
  : fail(`${manager.name} isn't set up on this clone, so no git hooks run`, 'run your package manager\'s install'));
69
69
  }
70
70
 
71
+ // a team may keep .githooks out of git, so a fresh clone has none until it runs sync, and no kit checks run till then
72
+ const noHooks = ['pre-commit', 'pre-push'].filter(h => !fs.existsSync(path.join(cwd, '.githooks', h)));
73
+ if (noHooks.length) out.push(fail(`This clone has no ${noHooks.map(h => `.githooks/${h}`).join(' or ')}, so the kit's checks don't run`, 'run: npx agentic-mobile-kit sync'));
74
+
71
75
  if (fs.existsSync(path.join(cwd, 'scripts/amk/case-check.js'))) {
72
76
  const r = spawnSync(process.execPath, ['scripts/amk/case-check.js'], { cwd, encoding: 'utf8' });
73
77
  const lines = (r.stderr || '').trim().split('\n');
package/lib/init.js CHANGED
@@ -12,8 +12,8 @@ const TEMPLATE = path.join(__dirname, '..', 'stacks', 'react-native', 'template'
12
12
  const screens = require(path.join(TEMPLATE, 'scripts', 'amk', 'screens.js'));
13
13
  const RULESYNC = 'rulesync@27.0.0';
14
14
  const MARKERS = /<!-- KIT:START[\s\S]*?<!-- KIT:END[^>]*-->\n?/;
15
- // files with {{PLACEHOLDERS}} filled in from the project
16
- const FILLED = ['AGENTS.md', 'codemagic.yaml'];
15
+ // files with {{PLACEHOLDERS}} filled in from the project (the last three say what the CI chosen does, or that none does)
16
+ const FILLED = ['AGENTS.md', 'codemagic.yaml', 'scripts/amk/set-version.sh', 'docs/amk/team-process.md', '.githooks/pre-commit'];
17
17
  // docs each team rewrites for its app: sync replaces them only while they're untouched, and never merges into them
18
18
  const PROJECT_DOCS = ['product', 'tech', 'structure', 'conventions'].map(n => `docs/amk/${n}.md`);
19
19
  const HOOKS_CMD = 'git config core.hooksPath .githooks || true';
@@ -49,6 +49,8 @@ class InitError extends Error {}
49
49
  function git(cwd, ...args) {
50
50
  return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
51
51
  }
52
+ // whether .gitignore keeps a path out of git (a team may keep .githooks out), so git add refuses it
53
+ const ignoredByGit = (cwd, rel) => { try { git(cwd, 'check-ignore', '-q', '--', rel); return true; } catch { return false; } };
52
54
 
53
55
  function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); }
54
56
  // Windows line endings (git's autocrlf) read as plain newlines, so a Windows clone compares equal to the kit's files
@@ -301,6 +303,14 @@ function architecture(cwd, rnVersion) {
301
303
  // TypeScript files, not just the typescript package: the React Native template installs it in JavaScript apps too
302
304
  const usesTs = cwd => git(cwd, 'ls-files', '*.ts', '*.tsx').split('\n').some(f => f && !f.endsWith('.d.ts'));
303
305
 
306
+ // what the kit's texts say about CI: what the chosen CI does, or that nothing does
307
+ const ciTexts = ci => ({
308
+ BUILD_NUMBERS: ci.includes('codemagic') ? 'Build numbers are left alone (codemagic.yaml sets them at build time).'
309
+ : 'Build numbers are left alone, and no CI here sets them: raise them for each store upload (Android versionCode, iOS build number).',
310
+ PR_SIZE_LIMIT: ci.includes('github') ? 'CI enforces it; the `large-pr` label overrides' : 'nothing enforces it: the app has no CI check for it',
311
+ PR_SIZE_HOOK: ci.includes('github') ? 'the PR size check in CI is the hard limit' : 'there\'s no PR size check in CI here',
312
+ });
313
+
304
314
  function projectValues(cwd, pkg, deps, pm, ci, stack) {
305
315
  const rn = installedVersion(cwd, 'react-native', deps['react-native']);
306
316
  const ts = usesTs(cwd);
@@ -323,6 +333,7 @@ function projectValues(cwd, pkg, deps, pm, ci, stack) {
323
333
  PM: pm.name,
324
334
  PM_RUN: pm.run,
325
335
  SCREENS: screens.describe(screens.screens(cwd)),
336
+ ...ciTexts(ci),
326
337
  IOS_BUNDLE_ID: stack === 'expo' ? (expoConfig(cwd).ios || {}).bundleIdentifier || 'com.example.app' : iosBundleId(cwd),
327
338
  };
328
339
  }
@@ -330,7 +341,7 @@ function projectValues(cwd, pkg, deps, pm, ci, stack) {
330
341
  // a template file's text as the kit writes it into this project
331
342
  function kitText(src, rel, values, targets) {
332
343
  const text = fs.readFileSync(src, 'utf8');
333
- if (FILLED.includes(rel)) return fillPlaceholders(text, values);
344
+ if (FILLED.includes(renamedPath(rel))) return fillPlaceholders(text, values);
334
345
  if (rel === 'rulesync.jsonc') return setTargets(text, targets);
335
346
  return text;
336
347
  }
@@ -419,7 +430,18 @@ function merge3(current, base, kitNew, from) {
419
430
  // two tools setting it undo each other on every install (husky's prepare script runs after the kit's postinstall).
420
431
  const KIT_HOOKS = ['pre-commit', 'pre-push'];
421
432
  const MARK = 'agentic-mobile-kit';
422
- const hookCall = h => `sh .githooks/${h}${h === 'pre-push' ? ' "$@"' : ''} || exit 1 # ${MARK}`;
433
+ // the kit's command in a hook manager. A team may keep .githooks out of git, so a fresh clone has none until it runs
434
+ // sync: run-hook.sh then skips the hook with a hint, where a plain `sh .githooks/<hook>` failed every commit and push
435
+ const kitRun = h => `sh scripts/amk/run-hook.sh .githooks/${h}`;
436
+ // that plain command, which kits up to 0.7.12 added: sync upgrades it
437
+ const oldRun = h => new RegExp(`(^|[\\s"'])sh \\.githooks/${h}(?=$|[\\s"'])`, 'gm');
438
+ const hookCall = h => `${kitRun(h)}${h === 'pre-push' ? ' "$@"' : ''} || exit 1 # ${MARK}`;
439
+ // git's other client-side hooks. One another tool installed into .git/hooks (a time tracker's post-commit, say) stops
440
+ // running once core.hooksPath points at .githooks, so a .githooks file passes it on, in every clone that has one
441
+ const OTHER_HOOKS = ['applypatch-msg', 'pre-applypatch', 'post-applypatch', 'pre-merge-commit', 'prepare-commit-msg', 'commit-msg',
442
+ 'post-commit', 'pre-rebase', 'post-checkout', 'post-merge', 'pre-auto-gc', 'post-rewrite', 'reference-transaction', 'post-index-change'];
443
+ const FORWARD = `# ${MARK}: runs this clone's own`;
444
+ const forwarder = h => `#!/bin/sh\n${FORWARD} .git/hooks/${h}, which core.hooksPath (.githooks) would switch off\nhook="$(git rev-parse --git-common-dir)/hooks/${h}"\n[ ! -x "$hook" ] || exec "$hook" "$@"\n`;
423
445
  const localHooksPath = cwd => {
424
446
  let v = '';
425
447
  try { v = git(cwd, 'config', '--local', 'core.hooksPath'); } catch {}
@@ -444,7 +466,11 @@ function hookManager(cwd, pkg) {
444
466
  }
445
467
 
446
468
  const hookFile = (m, h) => (m.dir ? `${m.dir}/${h}` : m.yaml);
447
- const hooksWired = (cwd, m) => KIT_HOOKS.every(h => (m.json ? m.json[h] || '' : readIf(path.join(cwd, hookFile(m, h))) || '').includes(`.githooks/${h}`));
469
+ // the kit's command, or the team's own call to the hook; not an earlier kit's plain one, which sync upgrades
470
+ const hooksWired = (cwd, m) => KIT_HOOKS.every(h => {
471
+ const text = m.json ? m.json[h] || '' : readIf(path.join(cwd, hookFile(m, h))) || '';
472
+ return text.includes(`.githooks/${h}`) && !oldRun(h).test(text);
473
+ });
448
474
 
449
475
  // after the shebang, comments and husky's own setup line: a command after the team's `exit` would never run
450
476
  function insertCall(text, line) {
@@ -457,7 +483,7 @@ function insertCall(text, line) {
457
483
 
458
484
  // adds the kit's command to a lefthook hook (under its commands: or jobs:), or the hook itself; null if it can't tell where
459
485
  function lefthookAdd(text, h) {
460
- const run = `sh .githooks/${h}`;
486
+ const run = kitRun(h);
461
487
  const lines = text.replace(/\n+$/, '').split('\n');
462
488
  const start = lines.findIndex(l => new RegExp(`^["']?${h}["']?\\s*:`).test(l));
463
489
  if (start < 0) return `${lines.join('\n')}\n${h}: # ${MARK}\n commands: # ${MARK}\n ${MARK}:\n run: ${run}\n`;
@@ -483,24 +509,31 @@ function lefthookAdd(text, h) {
483
509
  // runs the kit's hooks from the project's hook manager; true if package.json changed
484
510
  function wireHooks(cwd, m, done) {
485
511
  if (m.manual) {
486
- done.warnings.push(`git hooks already run from ${m.name}, so the kit left core.hooksPath alone. To run the kit's checks too, add "sh .githooks/pre-commit" and "sh .githooks/pre-push" to those hooks.`);
512
+ done.warnings.push(`git hooks already run from ${m.name}, so the kit left core.hooksPath alone. To run the kit's checks too, add "${kitRun('pre-commit')}" and "${kitRun('pre-push')}" to those hooks.`);
487
513
  return false;
488
514
  }
489
515
  let pkgChanged = false;
490
516
  for (const h of KIT_HOOKS) {
491
517
  if (m.json) {
492
- if ((m.json[h] || '').includes(`.githooks/${h}`)) continue;
493
- m.json[h] = m.json[h] ? `sh .githooks/${h} && ${m.json[h]}` : `sh .githooks/${h}`;
518
+ const v = m.json[h] || '';
519
+ if (oldRun(h).test(v)) m.json[h] = v.replace(oldRun(h), `$1${kitRun(h)}`);
520
+ else if (v.includes(`.githooks/${h}`)) continue;
521
+ else m.json[h] = v ? `${kitRun(h)} && ${v}` : kitRun(h);
494
522
  pkgChanged = true;
495
523
  continue;
496
524
  }
497
525
  const rel = hookFile(m, h);
498
526
  const file = path.join(cwd, rel);
499
527
  const text = readIf(file);
528
+ if (text !== null && oldRun(h).test(text)) {
529
+ fs.writeFileSync(file, text.replace(oldRun(h), `$1${kitRun(h)}`));
530
+ if (!done.merged.includes(rel)) done.merged.push(rel);
531
+ continue;
532
+ }
500
533
  if ((text || '').includes(`.githooks/${h}`)) continue;
501
534
  if (m.yaml) {
502
535
  const next = lefthookAdd(text, h);
503
- if (next === null) { done.warnings.push(`couldn't add the kit's ${h} check to ${rel}: add a command there that runs "sh .githooks/${h}"`); continue; }
536
+ if (next === null) { done.warnings.push(`couldn't add the kit's ${h} check to ${rel}: add a command there that runs "${kitRun(h)}"`); continue; }
504
537
  fs.writeFileSync(file, next);
505
538
  if (!done.merged.includes(rel)) done.merged.push(rel);
506
539
  continue;
@@ -509,7 +542,7 @@ function wireHooks(cwd, m, done) {
509
542
  fs.writeFileSync(file, text === null ? `#!/usr/bin/env sh\n${hookCall(h)}\n` : insertCall(text, hookCall(h)));
510
543
  // husky 5 to 8 and plain hook folders run the file itself
511
544
  fs.chmodSync(file, 0o755);
512
- if (WIN) git(cwd, 'add', '--chmod=+x', '--', rel);
545
+ if (WIN && !ignoredByGit(cwd, rel)) git(cwd, 'add', '--chmod=+x', '--', rel);
513
546
  (text === null ? done.created : done.merged).push(rel);
514
547
  }
515
548
  if (pkgChanged && m.name === 'simple-git-hooks') done.warnings.push('run "npx simple-git-hooks" once, so it installs the hooks with the kit\'s checks in them');
@@ -522,8 +555,8 @@ function unwireHooks(cwd, m, report) {
522
555
  for (const h of KIT_HOOKS) {
523
556
  if (m.json) {
524
557
  const before = m.json[h];
525
- if (before === `sh .githooks/${h}`) delete m.json[h];
526
- else if (before) m.json[h] = before.replace(`sh .githooks/${h} && `, '');
558
+ if (before === kitRun(h) || before === `sh .githooks/${h}`) delete m.json[h];
559
+ else if (before) m.json[h] = before.replace(`${kitRun(h)} && `, '').replace(`sh .githooks/${h} && `, '');
527
560
  if (m.json[h] !== before) { pkgChanged = true; report.removed.push(`package.json ${m.name} ${h} (the kit's command)`); }
528
561
  continue;
529
562
  }
@@ -624,6 +657,9 @@ function finish(cwd, { pkg, deps, tools, files, stack, skipGenerate }) {
624
657
  // the project's hook manager runs the kit's hooks; drop the postinstall earlier kit versions added, which fought it
625
658
  if (dropHooksCmd(scripts)) pkgChanged = true;
626
659
  if (wireHooks(cwd, manager, done)) pkgChanged = true;
660
+ if (!manager.manual && ignoredByGit(cwd, '.githooks/pre-commit')) {
661
+ done.warnings.push(`.githooks is kept out of git here, so a fresh clone has none until it runs npx agentic-mobile-kit sync. Until then, ${manager.name} skips the kit's checks and says so`);
662
+ }
627
663
  } else if (!(scripts.postinstall || '').includes('core.hooksPath')) {
628
664
  // parentheses keep the existing script's failure behavior: `a && b || true` would hide a failing `a`
629
665
  scripts.postinstall = scripts.postinstall ? `${scripts.postinstall} && (${HOOKS_CMD})` : HOOKS_CMD;
@@ -639,14 +675,38 @@ function finish(cwd, { pkg, deps, tools, files, stack, skipGenerate }) {
639
675
  if (husky) git(cwd, 'config', 'core.hooksPath', husky.endsWith('/h') ? '.husky/_' : '.husky');
640
676
  else git(cwd, 'config', '--unset', 'core.hooksPath');
641
677
  }
678
+ let gitHooks = '';
679
+ try { gitHooks = path.resolve(cwd, git(cwd, 'rev-parse', '--git-common-dir'), 'hooks'); } catch {}
680
+ const forwarded = manager || !gitHooks ? []
681
+ : OTHER_HOOKS.filter(h => fs.existsSync(path.join(gitHooks, h)) && !fs.existsSync(path.join(cwd, '.githooks', h)));
682
+ for (const h of forwarded) {
683
+ // a team may keep .githooks out of git, so a fresh clone has none yet
684
+ fs.mkdirSync(path.join(cwd, '.githooks'), { recursive: true });
685
+ fs.writeFileSync(path.join(cwd, '.githooks', h), forwarder(h), { mode: 0o755 });
686
+ done.created.push(`.githooks/${h}`);
687
+ }
688
+ if (forwarded.length) {
689
+ const ignored = ignoredByGit(cwd, `.githooks/${forwarded[0]}`);
690
+ const files = forwarded.map(h => `.githooks/${h}`).join(', ');
691
+ done.warnings.push(`.git/hooks has ${forwarded.join(', ')} from another tool, which core.hooksPath would switch off: ${files} now run${forwarded.length > 1 ? '' : 's'} it. ${ignored
692
+ ? '.githooks is kept out of git here, so each clone gets that when it runs sync'
693
+ : `Commit ${forwarded.length > 1 ? 'them' : 'it'} with the kit, so it runs in every clone that has one`}`);
694
+ }
642
695
  // Windows files have no executable bit, and git skips non-executable hooks on Mac and Linux clones:
643
- // stage the hooks as executable so the commit carries it
644
- const hooks = ['.githooks/pre-commit', '.githooks/pre-push'].filter(h => fs.existsSync(path.join(cwd, h)));
645
- if (WIN && hooks.length) git(cwd, 'add', '--chmod=+x', '--', ...hooks);
696
+ // stage the hooks as executable so the commit carries it (not where the team keeps them out of git)
697
+ const hooks = ['.githooks/pre-commit', '.githooks/pre-push', ...forwarded.map(h => `.githooks/${h}`)]
698
+ .filter(h => WIN && fs.existsSync(path.join(cwd, h)) && !ignoredByGit(cwd, h));
699
+ if (hooks.length) git(cwd, 'add', '--chmod=+x', '--', ...hooks);
646
700
 
647
- // 6. tool configs for the chosen tools (permissions, hooks, subagents)
701
+ // 6. tool configs for the chosen tools (permissions, hooks, subagents), from rulesync.jsonc, which a team that keeps
702
+ // it out of git doesn't have in a fresh clone
648
703
  const rsFile = path.join(cwd, 'rulesync.jsonc');
649
- fs.writeFileSync(rsFile, setTargets(fs.readFileSync(rsFile, 'utf8'), tools.flatMap(t => TOOLS[t])));
704
+ const rs = readIf(rsFile);
705
+ if (rs === null) {
706
+ done.warnings.push('rulesync.jsonc isn\'t here (deleted, or kept out of git), so the AI tools\' settings, hooks and subagents weren\'t generated. npx agentic-mobile-kit init puts it back');
707
+ return { done, generated: true, generateError: '' };
708
+ }
709
+ fs.writeFileSync(rsFile, setTargets(rs, tools.flatMap(t => TOOLS[t])));
650
710
  let generated = true;
651
711
  let generateError = '';
652
712
  if (!skipGenerate) {
@@ -704,6 +764,8 @@ function sync(cwd, opts = {}) {
704
764
  const hadCi = installedCi(cwd, agents);
705
765
  const wasInstalled = rel => !ciGroup(rel) || hadCi.includes(ciGroup(rel));
706
766
  const values = projectValues(cwd, pkg, deps, detectPm(cwd, opts.pm), ci, stack);
767
+ // the kit's files as installed: their texts about CI said what the CI chosen then does
768
+ const oldValues = { ...values, ...ciTexts(hadCi) };
707
769
  const tools = installedTools(cwd);
708
770
  const targets = tools.flatMap(t => TOOLS[t]);
709
771
  const report = { moved: [], updated: [], added: [], merged: [], conflicts: [], removed: [], kept: [] };
@@ -730,7 +792,7 @@ function sync(cwd, opts = {}) {
730
792
  for (const [rel, src] of newFiles) {
731
793
  if (ciGroup(rel) && !ci.includes(ciGroup(rel))) continue;
732
794
  const kitNew = kitText(src, rel, values, targets);
733
- const kitOld = oldFiles.has(rel) && wasInstalled(rel) ? kitText(oldFiles.get(rel), rel, values, targets) : null;
795
+ const kitOld = oldFiles.has(rel) && wasInstalled(rel) ? kitText(oldFiles.get(rel), rel, oldValues, targets) : null;
734
796
  const current = projectText(cwd, rel, targets);
735
797
  if (rel === 'AGENTS.md' || rel === 'CLAUDE.md') {
736
798
  const next = current === null ? kitNew : rel === 'AGENTS.md' ? mergeAgents(current, kitNew) : mergeClaude(current);
@@ -738,7 +800,9 @@ function sync(cwd, opts = {}) {
738
800
  continue;
739
801
  }
740
802
  if (current === null) {
741
- if (kitOld === null) { writeKitFile(cwd, rel, kitNew); report.added.push(rel); } else report.kept.push(`${rel} (you deleted it)`);
803
+ // new in the kit, or kept out of git, so this clone doesn't have it yet (a team may keep .githooks out of git).
804
+ // Not rulesync.jsonc: it holds the team's choice of tools, which the kit's own copy doesn't know
805
+ if (kitOld === null || rel !== 'rulesync.jsonc' && ignoredByGit(cwd, rel)) { writeKitFile(cwd, rel, kitNew); report.added.push(rel); } else report.kept.push(`${rel} (you deleted it)`);
742
806
  continue;
743
807
  }
744
808
  if (current === kitNew) continue;
@@ -823,6 +887,7 @@ function uninstall(cwd, opts = {}) {
823
887
  if (isLink(q) && linkTarget(q) === `../../.agents/skills/${name}`) { fs.unlinkSync(q); report.removed.push(`${link}/${name}`); }
824
888
  }
825
889
  }
890
+ for (const h of OTHER_HOOKS) if ((readIf(path.join(cwd, '.githooks', h)) || '').includes(FORWARD)) remove(`.githooks/${h}`);
826
891
  // folders left empty (rmdir refuses non-empty ones)
827
892
  const dirs = [...new Set(report.removed.map(r => path.dirname(r.split(' (')[0])))].sort((a, b) => b.length - a.length);
828
893
  for (let d of dirs) {
@@ -895,5 +960,5 @@ function printUninstall({ report }, log = console.log) {
895
960
 
896
961
  module.exports = {
897
962
  init, sync, uninstall, printSummary, printSync, printUninstall, InitError, TOOLS, TESTED, CI, KIT_VERSION, tool, cleanEnv,
898
- hookManager, hooksWired, checkProject, recorded, installedCi, emptyFolder, createApp,
963
+ hookManager, hooksWired, kitRun, checkProject, recorded, installedCi, emptyFolder, createApp,
899
964
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-mobile-kit",
3
- "version": "0.7.11",
3
+ "version": "0.7.13",
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",
@@ -42,7 +42,7 @@ Never say a check passed unless you ran it in this session.
42
42
  - Ask before adding or upgrading dependencies, and before editing `package.json`, lockfiles, `app.json`, `app.config.*`, `eas.json` or `.github/workflows/`.
43
43
  - Never edit `ios/` or `android/`: the next prebuild overwrites them. Native settings go in `app.json` or `app.config.*`, through config plugins; native code goes in an Expo module (`expo-module` skill). Ask before adding a config plugin.
44
44
  - Never run `eas build`, `eas submit` or `eas update`: they build, ship or publish with the team's accounts, so a person runs them.
45
- - Never read, print or commit `.env` files, keystores or signing files. Secrets don't belong in this repo.
45
+ - Never read, print or commit `.env` files, keystores, signing files or the files `.amk-secrets` lists. Secrets don't belong in this repo.
46
46
  - Never use `git commit --no-verify`, `git push --force`, `git reset --hard` or `rm -rf`.
47
47
  - After 2 failed attempts at the same fix, stop and report what you found.
48
48
  - Chat is not memory: write decisions into the spec or `docs/amk/decisions.md` straight away.
@@ -12,7 +12,7 @@ If your tool has subagents, hand the review to the `m-reviewer` subagent, so it
12
12
 
13
13
  ## Reviewing
14
14
 
15
- 1. Get the changes: `git diff main...HEAD` and `git log main..HEAD --oneline`. If there's a spec, read its `requirements.md`.
15
+ 1. Get the changes since the base branch the kit's checks use: `node scripts/amk/baseline.js base` prints it, then `git diff <base>...HEAD` and `git log <base>..HEAD --oneline`. If there's a spec, read its `requirements.md`.
16
16
  2. Check, in order:
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).
@@ -30,12 +30,17 @@ 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 (the kit's own scripts aren't the app's code)
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
+ # Errors a file had before this commit don't block it, as verify.sh doesn't block them: only new ones do
34
35
  files=$(echo "$staged" | grep -E '\.(js|jsx|ts|tsx)$' | grep -v '^scripts/amk/' || true)
35
36
  if [ -n "$files" ]; then
36
37
  if [ -x node_modules/.bin/eslint ]; then
37
38
  # ponytail: file names with spaces aren't supported here; split on newlines if that ever matters
38
- node_modules/.bin/eslint $files || fail "fix the ESLint errors above"
39
+ r=0
40
+ node scripts/amk/baseline.js staged $files || r=$?
41
+ # 3: it couldn't compare with HEAD, so every error blocks, as before
42
+ [ "$r" != 3 ] || { r=0; node_modules/.bin/eslint $files || r=$?; }
43
+ [ "$r" = 0 ] || fail "fix the ESLint errors listed above"
39
44
  else
40
45
  echo "pre-commit: ESLint isn't installed, so staged files weren't linted (Expo: run 'npx expo lint' once)" >&2
41
46
  fi
@@ -52,7 +57,7 @@ if [ -f scripts/amk/case-check.js ]; then
52
57
  node scripts/amk/case-check.js || fail "rename them through git as shown above"
53
58
  fi
54
59
 
55
- # 7. warn about large commits (the PR size check in CI is the hard limit)
60
+ # 7. warn about large commits ({{PR_SIZE_HOOK}})
56
61
  lines=$(git diff --cached --numstat -- . ':(exclude)*.lock' ':(exclude)package-lock.json' ':(exclude)pnpm-lock.yaml' ':(exclude)*.snap' |
57
62
  awk '{ s += $1 + $2 } END { print s + 0 }')
58
63
  [ "$lines" -le 400 ] || echo "pre-commit: warning: $lines changed lines; consider smaller commits" >&2
@@ -6,9 +6,9 @@ claudecode:
6
6
  tools: ["Read", "Grep", "Glob", "Bash"]
7
7
  ---
8
8
 
9
- You review code changes with fresh eyes. You never edit files. Use the shell only for read-only commands such as `git diff`, `git log` and `git show`.
9
+ You review code changes with fresh eyes. You never edit files. Use the shell only for read-only commands such as `git diff`, `git log`, `git show` and `node scripts/amk/baseline.js base`.
10
10
 
11
- 1. Get the changes: `git diff main...HEAD`. If a spec exists in `specs/<id>/`, read its `requirements.md`.
11
+ 1. Get the changes since the base branch the kit's checks use: `node scripts/amk/baseline.js base` prints it, then `git diff <base>...HEAD`. If a spec exists in `specs/<id>/`, read its `requirements.md`.
12
12
  2. Check scope, tests (added, deleted, weakened), iOS vs Android differences, screens (the keyboard covering a field or button, content under the system bars, lists that don't scroll, text cut off at large sizes), tablets and landscape for the screens AGENTS.md lists (layouts that adapt to the window width, turned screens that scroll), accessibility (labels and roles, messages announced to screen readers), TypeScript (new `any` or `@ts-ignore`, a loosened tsconfig), error and empty states, secrets, native file changes, and performance.
13
13
  3. Confirm each finding in the code before reporting it.
14
14
  4. Report each finding as: severity (blocker or should fix), file:line, the problem, and a suggested fix. No style nits.
@@ -41,7 +41,7 @@ Never say a check passed unless you ran it in this session.
41
41
  - Stay inside the task. Ask before touching unrelated files.
42
42
  - Ask before adding or upgrading dependencies, and before editing `package.json`, lockfiles, `Podfile`, `build.gradle`, `Info.plist`, `AndroidManifest.xml` or `.github/workflows/`.
43
43
  - Don't hand-edit `ios/*.xcodeproj/project.pbxproj`. If a native file must be added to the Xcode project, stop and ask.
44
- - Never read, print or commit `.env` files, keystores or signing files. Secrets don't belong in this repo.
44
+ - Never read, print or commit `.env` files, keystores, signing files or the files `.amk-secrets` lists. Secrets don't belong in this repo.
45
45
  - Never use `git commit --no-verify`, `git push --force`, `git reset --hard` or `rm -rf`.
46
46
  - After 2 failed attempts at the same fix, stop and report what you found.
47
47
  - Chat is not memory: write decisions into the spec or `docs/amk/decisions.md` straight away.
@@ -2,7 +2,7 @@
2
2
 
3
3
  - The person who opens a PR owns it and must be able to explain every change without AI.
4
4
  - A commit made for a spec ends with `Spec: specs/<id>`.
5
- - Keep PRs under 600 changed lines (CI enforces it; the `large-pr` label overrides).
5
+ - Keep PRs under 600 changed lines ({{PR_SIZE_LIMIT}}).
6
6
  - Run at most 2 or 3 agents in parallel per person.
7
7
  - Don't use "skip permissions", "YOLO" or auto-run modes in any tool.
8
8
  - Keep secrets out of the repo folder; inject them at run time.
@@ -5,9 +5,13 @@
5
5
  // lint ESLint errors in the files changed since the base, compared with those files at the base
6
6
  // typecheck TypeScript errors (file, code, message), compared with a type check of the base
7
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/amk/baseline.js lint|typecheck|test
8
+ // The base: AMK_BASE, else the first of the remote's default branch, origin/main, origin/master, main and master
9
+ // whose merge base with HEAD has a package.json (a default branch left at an old first commit isn't the app's base).
10
+ // Its merge base is checked out once into a temporary git worktree that shares node_modules, and its results are kept
11
+ // for the next run.
12
+ // `base` prints the base, for reviews of a branch's changes. `staged <files>` is the pre-commit hook's lint: it passes
13
+ // when the files have no ESLint error they didn't have at HEAD, and exits with 3 when it can't find ESLint's CLI.
14
+ // Usage: node scripts/amk/baseline.js lint|typecheck|test|base|staged <files>
11
15
  'use strict';
12
16
  const fs = require('fs');
13
17
  const os = require('os');
@@ -16,8 +20,8 @@ const crypto = require('crypto');
16
20
  const { spawnSync, execFileSync } = require('child_process');
17
21
 
18
22
  const check = process.argv[2];
19
- if (!['lint', 'typecheck', 'test'].includes(check)) {
20
- console.error('usage: node scripts/amk/baseline.js lint|typecheck|test');
23
+ if (!['lint', 'typecheck', 'test', 'base', 'staged'].includes(check)) {
24
+ console.error('usage: node scripts/amk/baseline.js lint|typecheck|test|base|staged <files>');
21
25
  process.exit(2);
22
26
  }
23
27
  const root = process.cwd();
@@ -76,10 +80,16 @@ function failingTests(r) {
76
80
  });
77
81
  }
78
82
 
83
+ const hasApp = sha => Boolean(sha && git('rev-parse', '--verify', '--quiet', `${sha}:package.json`));
84
+ // { ref, note }: the note says when the remote's default branch was passed over
79
85
  function baseRef() {
80
- if (process.env.AMK_BASE) return process.env.AMK_BASE;
86
+ if (process.env.AMK_BASE) return { ref: process.env.AMK_BASE, note: '' };
81
87
  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}`));
88
+ const refs = [...new Set([remoteDefault, 'origin/main', 'origin/master', 'main', 'master'])]
89
+ .filter(r => r && git('rev-parse', '--verify', '--quiet', `${r}^{commit}`));
90
+ const ref = refs.find(r => hasApp(git('merge-base', 'HEAD', r))) || refs[0];
91
+ if (!ref) return null;
92
+ return { ref, note: ref === refs[0] ? '' : `comparing with ${ref}, as ${refs[0]} has no package.json where it meets this branch (AMK_BASE sets the base)` };
83
93
  }
84
94
 
85
95
  // the base commit, checked out once into a temporary worktree that shares the app's node_modules
@@ -114,25 +124,26 @@ function baseProblems(sha, extract) {
114
124
  return problems;
115
125
  }
116
126
 
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/amk/) don't change how the app's code is checked
123
- // (scripts/ai/ until 0.7.0)
127
+ // the ESLint setup files among changed that differ from sha's: with them, any error could be new. The kit's own
128
+ // .eslintignore lines (for scripts/amk/, scripts/ai/ until 0.7.0) don't change how the app's code is checked
129
+ function eslintSetupChanges(changed, sha) {
124
130
  const withoutKit = t => t.split('\n').filter(l => !/^scripts\/(amk|ai)\/$/.test(l.trim()) && !l.startsWith('# agentic-mobile-kit')).join('\n').trim();
125
- const setup = changed.filter(f => /(^|\/)(\.eslintrc(\.\w+)?|eslint\.config\.\w+|\.eslintignore)$/.test(f))
131
+ return changed.filter(f => /(^|\/)(\.eslintrc(\.\w+)?|eslint\.config\.\w+|\.eslintignore)$/.test(f))
126
132
  .filter(f => path.basename(f) !== '.eslintignore' || withoutKit(git('show', `${sha}:${f}`)) !== withoutKit(fs.readFileSync(path.join(root, f), 'utf8')));
127
- if (setup.length) return { reason: `the change edits the ESLint setup (${setup.join(', ')}), so any error could be new` };
128
- // ESLint 8 and 9 export only package.json, so find the CLI next to it
129
- let eslint;
133
+ }
134
+
135
+ // ESLint 8 and 9 export only package.json, so find the CLI next to it
136
+ function eslintCli() {
130
137
  try {
131
- eslint = path.join(path.dirname(require.resolve('eslint/package.json', { paths: [root] })), 'bin', 'eslint.js');
132
- if (!fs.existsSync(eslint)) throw new Error('no CLI');
138
+ const cli = path.join(path.dirname(require.resolve('eslint/package.json', { paths: [root] })), 'bin', 'eslint.js');
139
+ return fs.existsSync(cli) ? cli : null;
133
140
  } catch {
134
- return { reason: 'ESLint isn\'t installed' };
141
+ return null;
135
142
  }
143
+ }
144
+
145
+ // ESLint errors in files that they didn't have at sha (null without ESLint's report)
146
+ function lintErrorsNotAt(sha, files, eslint) {
136
147
  const lint = (args, input) => {
137
148
  const r = spawnSync(process.execPath, [eslint, '--format', 'json', ...args], { cwd: root, input, encoding: 'utf8', maxBuffer: 2 ** 28 });
138
149
  try {
@@ -142,9 +153,8 @@ function newLintErrors(sha) {
142
153
  }
143
154
  };
144
155
  const errors = results => (results || []).flatMap(f => f.messages.filter(m => m.severity === 2).map(m => `${m.ruleId || 'parsing'}: ${m.message}`));
145
- const files = changed.filter(f => /\.(js|jsx|ts|tsx)$/.test(f) && !f.startsWith('scripts/amk/') && fs.existsSync(path.join(root, f)));
146
156
  const results = files.length ? lint(files) : [];
147
- if (!results) return { reason: 'ESLint gave no report' };
157
+ if (!results) return null;
148
158
  const fresh = [];
149
159
  for (const result of results) {
150
160
  const file = slash(path.relative(root, result.filePath));
@@ -157,20 +167,77 @@ function newLintErrors(sha) {
157
167
  }
158
168
  fresh.push(...minus(now, before).map(p => `${file}: ${p}`));
159
169
  }
160
- return { fresh, files: files.length };
170
+ return fresh;
171
+ }
172
+
173
+ // ESLint errors in the files changed since the base, minus the errors those files had at the base. Errors in
174
+ // files the change didn't touch were there before, unless the change edits the ESLint setup itself.
175
+ function newLintErrors(sha) {
176
+ const changed = [...new Set([...git('diff', '--name-only', '--diff-filter=ACMR', sha).split('\n'),
177
+ ...git('ls-files', '--others', '--exclude-standard').split('\n')])].filter(Boolean);
178
+ const setup = eslintSetupChanges(changed, sha);
179
+ if (setup.length) return { reason: `the change edits the ESLint setup (${setup.join(', ')}), so any error could be new` };
180
+ const eslint = eslintCli();
181
+ if (!eslint) return { reason: 'ESLint isn\'t installed' };
182
+ const files = changed.filter(f => /\.(js|jsx|ts|tsx)$/.test(f) && !f.startsWith('scripts/amk/') && fs.existsSync(path.join(root, f)));
183
+ const fresh = lintErrorsNotAt(sha, files, eslint);
184
+ return fresh ? { fresh, files: files.length } : { reason: 'ESLint gave no report' };
185
+ }
186
+
187
+ if (check === 'base') {
188
+ const found = baseRef();
189
+ if (!found) {
190
+ console.error('no base branch found: set AMK_BASE to the branch this work is based on');
191
+ process.exit(1);
192
+ }
193
+ if (found.note) console.error(found.note);
194
+ console.log(found.ref);
195
+ process.exit(0);
196
+ }
197
+
198
+ if (check === 'staged') {
199
+ // ESLint's own report on the files first, then whether any error in them is new since HEAD: a commit that touches
200
+ // a file with errors from before isn't blocked by them, as verify.sh isn't
201
+ const files = process.argv.slice(3);
202
+ if (!files.length) process.exit(0);
203
+ const eslint = eslintCli();
204
+ if (!eslint) process.exit(3); // can't compare: the hook lints the files as they are
205
+
206
+ if (spawnSync(process.execPath, [eslint, ...files], { cwd: root, stdio: 'inherit' }).status === 0) process.exit(0);
207
+ if (!git('rev-parse', '--verify', '--quiet', 'HEAD')) process.exit(1); // the first commit: nothing to compare with
208
+ const setup = eslintSetupChanges(git('diff', '--cached', '--name-only', '--diff-filter=ACMR').split('\n').filter(Boolean), 'HEAD');
209
+ if (setup.length) {
210
+ console.log(`lint: the commit edits the ESLint setup (${setup.join(', ')}), so any of these errors could be new`);
211
+ process.exit(1);
212
+ }
213
+ const fresh = lintErrorsNotAt('HEAD', files, eslint);
214
+ if (!fresh) process.exit(1);
215
+ if (!fresh.length) {
216
+ console.log('lint: the files had all of these errors before this commit, so none is new');
217
+ process.exit(0);
218
+ }
219
+ console.log(`lint: ${fresh.length} new compared with HEAD:`);
220
+ for (const p of fresh.slice(0, 30)) console.log(` ${p}`);
221
+ if (fresh.length > 30) console.log(` … and ${fresh.length - 30} more`);
222
+ process.exit(1);
161
223
  }
162
224
 
163
225
  const now = runScript(root);
164
226
  process.stdout.write(now.out);
165
227
  if (now.code === 0) process.exit(0);
166
228
 
167
- const base = baseRef();
168
- const sha = base && git('merge-base', 'HEAD', base);
229
+ const found = baseRef();
230
+ const sha = found && git('merge-base', 'HEAD', found.ref);
169
231
  if (!sha) {
170
232
  console.log(`${check}: failed, and there's no base branch to compare with (set AMK_BASE)`);
171
233
  process.exit(1);
172
234
  }
173
- const label = `${base} (${sha.slice(0, 7)})`;
235
+ const label = `${found.ref} (${sha.slice(0, 7)})`;
236
+ if (found.note) console.log(`${check}: ${found.note}`);
237
+ if (!hasApp(sha)) {
238
+ console.log(`${check}: failed, and it can't be compared with ${label}, which has no package.json: set AMK_BASE to the branch this work is based on`);
239
+ process.exit(1);
240
+ }
174
241
  let fresh;
175
242
  let summary;
176
243
  if (check === 'lint') {
@@ -21,16 +21,23 @@ const paths = [];
21
21
  }
22
22
  })(payload, '');
23
23
 
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/;
24
+ // rm with a recursive flag and a force flag anywhere before the next ; & | (-rf, -Rf, -r -f, --recursive --force);
25
+ // a push with --force, -f or a +refspec
26
+ const destructive = /\brm(?=[^;&|\n]*\s(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b)(?=[^;&|\n]*\s(-[a-zA-Z]*f[a-zA-Z]*|--force)\b)|git\s+reset\s+--hard|git\s+push\s+(.*\s)?((--force|-f)\b|\+\S)|git\s+clean\s+-[a-z]*f|--no-verify|xcrun\s+simctl\s+erase/;
25
27
  // example files (.env.example, .env.local.example, .env.sample, .env.template) aren't secrets
26
28
  const secretFile = /(^|[\s/'"=])\.env(?![\w.-]*\.(?:example|sample|template)(?=$|[\s'";|&)]))(\.[\w.-]+)?(?=$|[\s'";|&)])|\.(keystore|jks|p8|p12|mobileprovision)\b/;
29
+ // the project's own secret files: .amk-secrets lists them, one path from the project root per line (a folder ends in /)
30
+ let listed = [];
31
+ try { listed = fs.readFileSync('.amk-secrets', 'utf8').split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')); } catch {}
32
+ const secret = s => secretFile.test(s) || listed.some(p => s.includes(p));
27
33
 
28
34
  const block = reason => { process.stderr.write(`Blocked by scripts/amk/guard.js: ${reason}\n`); process.exit(2); };
29
35
  for (const c of commands) {
30
- if (destructive.test(c)) block(`destructive command: ${c}`);
31
- if (secretFile.test(c)) block(`shell access to a secret file: ${c}`);
36
+ // a command that only mentions one, in a commit message, is blocked too: the message can come from a file instead
37
+ if (destructive.test(c)) block(`destructive command: ${c}${/git\s+commit\b/.test(c) ? '\n(Only in the commit message? Write it to a file and use git commit -F <file>.)' : ''}`);
38
+ if (secret(c)) block(`shell access to a secret file: ${c}`);
32
39
  }
33
40
  for (const p of paths) {
34
- if (secretFile.test(p)) block(`access to a secret file: ${p}`);
41
+ if (secret(p)) block(`access to a secret file: ${p}`);
35
42
  }
36
43
  process.exit(0);
@@ -18,10 +18,14 @@ if [ "$config" = Release ]; then
18
18
  [ -n "$config" ] || config=Release
19
19
  fi
20
20
 
21
+ # A check build isn't a release: with no dSYMs, and dSYMs looked for in a folder that never exists, the app's
22
+ # crash-reporter build phases (Crashlytics, PostHog, Sentry, …) find nothing to upload under the real app's version
23
+ check_build() { xcodebuild "$@" DEBUG_INFORMATION_FORMAT=dwarf DWARF_DSYM_FOLDER_PATH="$(pwd)/ios/DerivedData/no-dsyms" SENTRY_DISABLE_AUTO_UPLOAD=true; }
24
+
21
25
  if [ "${1:-}" = device ]; then
22
26
  [ -n "${AMK_IOS_TEAM:-}" ] || { echo "Set AMK_IOS_TEAM to the Apple team to sign with (Xcode > Settings > Accounts lists them)."; exit 1; }
23
27
  # signed for development whatever the project signs its releases with (a distribution profile doesn't install)
24
- xcodebuild -workspace "$workspace" -scheme "$scheme" -configuration "$config" -destination "id=$2" \
28
+ check_build -workspace "$workspace" -scheme "$scheme" -configuration "$config" -destination "id=$2" \
25
29
  -derivedDataPath ios/DerivedData -allowProvisioningUpdates -allowProvisioningDeviceRegistration \
26
30
  DEVELOPMENT_TEAM="$AMK_IOS_TEAM" CODE_SIGN_STYLE=Automatic CODE_SIGN_IDENTITY="Apple Development" \
27
31
  PROVISIONING_PROFILE_SPECIFIER= -quiet build
@@ -37,7 +41,7 @@ arch=x86_64
37
41
  set -- ARCHS="$arch"
38
42
  ! grep -rqsE "EXCLUDED_ARCHS\[sdk=iphonesimulator\*\]\"? = [^;]*$arch" ios/*.xcodeproj/project.pbxproj "ios/Pods/Target Support Files" || set --
39
43
 
40
- xcodebuild -workspace "$workspace" -scheme "$scheme" -configuration "$config" \
44
+ check_build -workspace "$workspace" -scheme "$scheme" -configuration "$config" \
41
45
  -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' \
42
46
  -derivedDataPath ios/DerivedData "$@" CODE_SIGNING_ALLOWED=NO -quiet build
43
47
  echo "iOS simulator build OK ($scheme, $config)"
@@ -0,0 +1,12 @@
1
+ // Gradle init script for verify.sh's Android check builds, which aren't releases: it turns off the tasks that send a
2
+ // build's mapping files, debug symbols or source maps somewhere (Crashlytics, PostHog, Sentry, Bugsnag, Datadog, …),
3
+ // which would file them under the real app's version. They're named for it: upload…, …Upload…, bugsnagRelease….
4
+ // Usage: ./gradlew --init-script scripts/amk/no-symbol-upload.gradle assembleRelease
5
+ allprojects {
6
+ tasks.configureEach { task ->
7
+ if (task.name.startsWith('upload') || task.name.contains('Upload') || task.name.startsWith('bugsnagRelease')) {
8
+ task.enabled = false
9
+ println "agentic-mobile-kit: a check build, so ${task.path} doesn't run"
10
+ }
11
+ }
12
+ }
@@ -0,0 +1,9 @@
1
+ #!/bin/sh
2
+ # Runs one of the kit's git hooks from the project's hook manager (husky, lefthook, simple-git-hooks).
3
+ # Usage: sh scripts/amk/run-hook.sh .githooks/<hook> [args…]
4
+ # A team may keep .githooks out of git, so a fresh clone has none until it runs sync: then this says so and lets the
5
+ # commit or push go on, as failing every one of them would leave only git commit --no-verify
6
+ set -eu
7
+ hook=$1; shift
8
+ if [ -f "$hook" ]; then exec sh "$hook" "$@"; fi
9
+ echo "agentic-mobile-kit: this clone has no $hook yet, so the kit's checks were skipped: run npx agentic-mobile-kit sync" >&2
@@ -1,7 +1,7 @@
1
1
  #!/bin/sh
2
2
  # Sets the version users see on both platforms: iOS MARKETING_VERSION and Android versionName, or in Expo
3
3
  # apps without native folders, expo.version in app.json.
4
- # Build numbers are left alone (codemagic.yaml sets them at build time).
4
+ # {{BUILD_NUMBERS}}
5
5
  # Usage: sh scripts/amk/set-version.sh 1.4.0
6
6
  set -eu
7
7
  v=${1:-}
@@ -11,14 +11,16 @@
11
11
  # build the release builds only, iOS and Android at the same time, for --no-build checks after it
12
12
  # plan whether this machine can check the devices at the same time, and the commands to run
13
13
  # --spec <id> run .maestro/<id>*.yaml and save evidence in .amk/evidence/<id>/
14
- # --label <n> evidence folder name (default: the spec id, or a timestamp)
14
+ # --label <n> evidence folder name (default: the spec id, or no-spec)
15
15
  # --flavor <name> Android product flavor to check (default: the first one in build.gradle)
16
16
  # --scheme <name> iOS scheme to check (default: the one named like the workspace)
17
17
  # --screens <l> only these of the screens the app supports, comma-separated: phone, tablet, portrait,
18
18
  # landscape, or one such as tablet-landscape
19
19
  # --no-build check the last build instead of building again (after `build`)
20
20
  # (no flows found: a smoke check that launches the app and takes a screenshot)
21
- # Evidence per screen: ios/ and android/ (phone, portrait), then -landscape/, -tablet/ and -tablet-landscape/
21
+ # Evidence per screen: ios/ and android/ (phone, portrait), then -landscape/, -tablet/ and -tablet-landscape/, each
22
+ # with its latest run only (the device's own log only for a flow that failed); the newest 5 evidence folders stay,
23
+ # and every prototype's
22
24
  # Env: AMK_ANDROID_FLAVOR, AMK_IOS_SCHEME, AMK_SCREENS (defaults for the options), AMK_IOS_DEVICE (simulator name
23
25
  # or UDID, or a connected iPhone's or iPad's: the only way to check on one, whose app data the flows clear),
24
26
  # AMK_ANDROID_DEVICE (adb serial: the only way to check on a phone, whose app data the flows clear),
@@ -26,7 +28,8 @@
26
28
  # AMK_IOS_TABLET (iPad simulator, or a connected iPad: name or UDID), AMK_ANDROID_TABLET_AVD (tablet emulator),
27
29
  # AMK_ANDROID_TABLET (serial), AMK_IOS_TEAM (the Apple team ID that signs builds for real iPhones and iPads;
28
30
  # default: the project's), AMK_PARALLEL (1 or 0: overrides plan's choice), AMK_DEVICE_WAIT (minutes to wait for a
29
- # device in use, 30), AMK_LOCK_DIR (where runs on this machine claim devices; /tmp/agentic-mobile-kit-<user id>)
31
+ # device in use, 30), AMK_LOCK_DIR (where runs on this machine claim devices; /tmp/agentic-mobile-kit-<user id>),
32
+ # AMK_EVIDENCE_KEEP (how many evidence folders stay, newest first: 5; 0 keeps them all)
30
33
  # A device in use by another run (any project on this machine) is skipped for a free one of the same kind, or waited
31
34
  # for when it was named or none is free.
32
35
  # Real iPhones and iPads (iOS 17 or later): Maestro doesn't run on them, so their flows run through maestro-runner, with
@@ -59,8 +62,21 @@ done
59
62
 
60
63
  root=$(pwd)
61
64
  . scripts/amk/maestro-env.sh
62
- evidence="$root/.amk/evidence/${label:-${spec:-$(date +%Y%m%d-%H%M%S)}}"
65
+ # runs without a spec or a label (verify.sh quick, mostly) share one folder, so they don't push out a feature's
66
+ evidence="$root/.amk/evidence/${label:-${spec:-no-spec}}"
63
67
  mkdir -p "$evidence"
68
+ # Evidence stays on this machine (.amk/ is out of git): the newest AMK_EVIDENCE_KEEP folders stay, this one among
69
+ # them, and older ones go (5; 0 keeps them all). A prototype's folder (<id>-prototype, material for a demo) always
70
+ # stays and isn't counted
71
+ touch "$evidence"
72
+ keep=${AMK_EVIDENCE_KEEP:-5}
73
+ if [ "$keep" -gt 0 ] 2> /dev/null; then
74
+ old=$(ls -dt "$root"/.amk/evidence/*/ 2> /dev/null | grep -v -- '-prototype/$' | tail -n +$((keep + 1)))
75
+ if [ -n "$old" ]; then
76
+ echo "$old" | while IFS= read -r d; do rm -r "${d:?}" || true; done
77
+ echo "evidence: removed $(echo "$old" | wc -l | tr -d ' ') older folders from .amk/evidence, keeping the newest $keep (AMK_EVIDENCE_KEEP sets how many; 0 keeps them all)"
78
+ fi
79
+ fi
64
80
  status=0
65
81
 
66
82
  flow_files() {
@@ -133,12 +149,11 @@ claim_wait() {
133
149
  }
134
150
 
135
151
  run_flow() { # screen device app_id file name orientation
136
- # Maestro's own log, which has errors its output leaves out; it adds to the file, so one run's log at a time
152
+ # Maestro's own logs, which have errors its output leaves out: of this flow's latest run only (each run adds a folder
153
+ # of its own), as an earlier run's screenshots aren't this run's evidence
137
154
  debug="$evidence/maestro-logs/$1-$5"
155
+ [ ! -d "$debug" ] || rm -r "$debug"
138
156
  mkdir -p "$debug" "$out/screenshots"
139
- rm -f "$debug/maestro.log"
140
- # an earlier run's screenshots, which aren't this run's evidence
141
- find "$debug" \( -path '*/takeScreenshot/*.png' -o -path '*/assets/*.png' \) -exec rm -f {} +
142
157
  target=$4
143
158
  # Maestro reads the path in the flows below itself, so it's a native path (a Windows path in Git Bash)
144
159
  native=$(cd "$(dirname "$4")" && { pwd -W 2> /dev/null || pwd; })/$(basename "$4")
@@ -187,6 +202,8 @@ run_flow() { # screen device app_id file name orientation
187
202
 
188
203
  run_flows() { # screen device app_id orientation (PORTRAIT, or LANDSCAPE_LEFT to turn it) [again]
189
204
  out="$evidence/$1"
205
+ # the screen's latest run only: an earlier run's screenshots aren't this run's evidence
206
+ [ -n "${5:-}" ] || [ ! -d "$out" ] || rm -r "$out"
190
207
  mkdir -p "$out"
191
208
  # this run's screenshots are the ones newer than this; the status before it, for running the screen again
192
209
  : > "$out/.started"
@@ -226,6 +243,8 @@ run_flows() { # screen device app_id orientation (PORTRAIT, or LANDSCAPE_LEFT to
226
243
  fi
227
244
  if [ "$ok" = 0 ]; then
228
245
  passed=$((passed + 1))
246
+ # the device's own log (the simulator's or the emulator's, up to 25 MB a run) helps only with a failure
247
+ find "$debug" -path '*/logs/device-*' -type f -exec rm -f {} +
229
248
  elif is_real "$2"; then
230
249
  echo " $1: flow $name failed, see ${out#"$root"/}/$name.log and maestro-runner's own log ${debug#"$root"/}/maestro-runner.log"
231
250
  status=1
@@ -343,7 +362,9 @@ ios() {
343
362
  fi
344
363
  # pod install also generates React Native codegen files into ios/build/generated; a newer Podfile needs it again
345
364
  if [ ! -d ios/Pods ] || [ ! -d ios/build/generated ] || [ ios/Podfile -nt ios/Pods/Manifest.lock ]; then
346
- sh scripts/amk/pod-install.sh > "$evidence/pod-install.log" 2>&1
365
+ if ! sh scripts/amk/pod-install.sh > "$evidence/pod-install.log" 2>&1; then
366
+ echo "ios: pod install FAILED, see ${evidence#"$root"/}/pod-install.log"; status=1; return
367
+ fi
347
368
  fi
348
369
  fi
349
370
  # the simulators first, so they boot while Xcode builds. A real iPhone or iPad only when named, as the flows clear
@@ -685,7 +706,9 @@ android() {
685
706
  set -- "$@" -Pandroid.injected.signing.store.file="$keystore" -Pandroid.injected.signing.store.password=android \
686
707
  -Pandroid.injected.signing.key.alias=androiddebugkey -Pandroid.injected.signing.key.password=android
687
708
  fi
688
- if ! (cd android && ./gradlew "assemble${variant}Release" --no-daemon -q "$@") > "$evidence/android-build.log" 2>&1; then
709
+ # a check build isn't a release: its mapping files and debug symbols stay off the crash reporters
710
+ set -- "$@" --init-script "$(cd scripts/amk && { pwd -W 2> /dev/null || pwd; })/no-symbol-upload.gradle"
711
+ if ! (cd android && SENTRY_DISABLE_AUTO_UPLOAD=true ./gradlew "assemble${variant}Release" --no-daemon -q "$@") > "$evidence/android-build.log" 2>&1; then
689
712
  echo "android: release build FAILED, see ${evidence#"$root"/}/android-build.log"; status=1; return
690
713
  fi
691
714
  fi