agentic-mobile-kit 0.7.10 → 0.7.12

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/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
  }
@@ -420,6 +431,12 @@ function merge3(current, base, kitNew, from) {
420
431
  const KIT_HOOKS = ['pre-commit', 'pre-push'];
421
432
  const MARK = 'agentic-mobile-kit';
422
433
  const hookCall = h => `sh .githooks/${h}${h === 'pre-push' ? ' "$@"' : ''} || exit 1 # ${MARK}`;
434
+ // git's other client-side hooks. One another tool installed into .git/hooks (a time tracker's post-commit, say) stops
435
+ // running once core.hooksPath points at .githooks, so a .githooks file passes it on, in every clone that has one
436
+ const OTHER_HOOKS = ['applypatch-msg', 'pre-applypatch', 'post-applypatch', 'pre-merge-commit', 'prepare-commit-msg', 'commit-msg',
437
+ 'post-commit', 'pre-rebase', 'post-checkout', 'post-merge', 'pre-auto-gc', 'post-rewrite', 'reference-transaction', 'post-index-change'];
438
+ const FORWARD = `# ${MARK}: runs this clone's own`;
439
+ 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
440
  const localHooksPath = cwd => {
424
441
  let v = '';
425
442
  try { v = git(cwd, 'config', '--local', 'core.hooksPath'); } catch {}
@@ -509,7 +526,7 @@ function wireHooks(cwd, m, done) {
509
526
  fs.writeFileSync(file, text === null ? `#!/usr/bin/env sh\n${hookCall(h)}\n` : insertCall(text, hookCall(h)));
510
527
  // husky 5 to 8 and plain hook folders run the file itself
511
528
  fs.chmodSync(file, 0o755);
512
- if (WIN) git(cwd, 'add', '--chmod=+x', '--', rel);
529
+ if (WIN && !ignoredByGit(cwd, rel)) git(cwd, 'add', '--chmod=+x', '--', rel);
513
530
  (text === null ? done.created : done.merged).push(rel);
514
531
  }
515
532
  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');
@@ -639,14 +656,38 @@ function finish(cwd, { pkg, deps, tools, files, stack, skipGenerate }) {
639
656
  if (husky) git(cwd, 'config', 'core.hooksPath', husky.endsWith('/h') ? '.husky/_' : '.husky');
640
657
  else git(cwd, 'config', '--unset', 'core.hooksPath');
641
658
  }
659
+ let gitHooks = '';
660
+ try { gitHooks = path.resolve(cwd, git(cwd, 'rev-parse', '--git-common-dir'), 'hooks'); } catch {}
661
+ const forwarded = manager || !gitHooks ? []
662
+ : OTHER_HOOKS.filter(h => fs.existsSync(path.join(gitHooks, h)) && !fs.existsSync(path.join(cwd, '.githooks', h)));
663
+ for (const h of forwarded) {
664
+ // a team may keep .githooks out of git, so a fresh clone has none yet
665
+ fs.mkdirSync(path.join(cwd, '.githooks'), { recursive: true });
666
+ fs.writeFileSync(path.join(cwd, '.githooks', h), forwarder(h), { mode: 0o755 });
667
+ done.created.push(`.githooks/${h}`);
668
+ }
669
+ if (forwarded.length) {
670
+ const ignored = ignoredByGit(cwd, `.githooks/${forwarded[0]}`);
671
+ const files = forwarded.map(h => `.githooks/${h}`).join(', ');
672
+ 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
673
+ ? '.githooks is kept out of git here, so each clone gets that when it runs sync'
674
+ : `Commit ${forwarded.length > 1 ? 'them' : 'it'} with the kit, so it runs in every clone that has one`}`);
675
+ }
642
676
  // 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);
677
+ // stage the hooks as executable so the commit carries it (not where the team keeps them out of git)
678
+ const hooks = ['.githooks/pre-commit', '.githooks/pre-push', ...forwarded.map(h => `.githooks/${h}`)]
679
+ .filter(h => WIN && fs.existsSync(path.join(cwd, h)) && !ignoredByGit(cwd, h));
680
+ if (hooks.length) git(cwd, 'add', '--chmod=+x', '--', ...hooks);
646
681
 
647
- // 6. tool configs for the chosen tools (permissions, hooks, subagents)
682
+ // 6. tool configs for the chosen tools (permissions, hooks, subagents), from rulesync.jsonc, which a team that keeps
683
+ // it out of git doesn't have in a fresh clone
648
684
  const rsFile = path.join(cwd, 'rulesync.jsonc');
649
- fs.writeFileSync(rsFile, setTargets(fs.readFileSync(rsFile, 'utf8'), tools.flatMap(t => TOOLS[t])));
685
+ const rs = readIf(rsFile);
686
+ if (rs === null) {
687
+ 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');
688
+ return { done, generated: true, generateError: '' };
689
+ }
690
+ fs.writeFileSync(rsFile, setTargets(rs, tools.flatMap(t => TOOLS[t])));
650
691
  let generated = true;
651
692
  let generateError = '';
652
693
  if (!skipGenerate) {
@@ -704,6 +745,8 @@ function sync(cwd, opts = {}) {
704
745
  const hadCi = installedCi(cwd, agents);
705
746
  const wasInstalled = rel => !ciGroup(rel) || hadCi.includes(ciGroup(rel));
706
747
  const values = projectValues(cwd, pkg, deps, detectPm(cwd, opts.pm), ci, stack);
748
+ // the kit's files as installed: their texts about CI said what the CI chosen then does
749
+ const oldValues = { ...values, ...ciTexts(hadCi) };
707
750
  const tools = installedTools(cwd);
708
751
  const targets = tools.flatMap(t => TOOLS[t]);
709
752
  const report = { moved: [], updated: [], added: [], merged: [], conflicts: [], removed: [], kept: [] };
@@ -730,7 +773,7 @@ function sync(cwd, opts = {}) {
730
773
  for (const [rel, src] of newFiles) {
731
774
  if (ciGroup(rel) && !ci.includes(ciGroup(rel))) continue;
732
775
  const kitNew = kitText(src, rel, values, targets);
733
- const kitOld = oldFiles.has(rel) && wasInstalled(rel) ? kitText(oldFiles.get(rel), rel, values, targets) : null;
776
+ const kitOld = oldFiles.has(rel) && wasInstalled(rel) ? kitText(oldFiles.get(rel), rel, oldValues, targets) : null;
734
777
  const current = projectText(cwd, rel, targets);
735
778
  if (rel === 'AGENTS.md' || rel === 'CLAUDE.md') {
736
779
  const next = current === null ? kitNew : rel === 'AGENTS.md' ? mergeAgents(current, kitNew) : mergeClaude(current);
@@ -823,6 +866,7 @@ function uninstall(cwd, opts = {}) {
823
866
  if (isLink(q) && linkTarget(q) === `../../.agents/skills/${name}`) { fs.unlinkSync(q); report.removed.push(`${link}/${name}`); }
824
867
  }
825
868
  }
869
+ for (const h of OTHER_HOOKS) if ((readIf(path.join(cwd, '.githooks', h)) || '').includes(FORWARD)) remove(`.githooks/${h}`);
826
870
  // folders left empty (rmdir refuses non-empty ones)
827
871
  const dirs = [...new Set(report.removed.map(r => path.dirname(r.split(' (')[0])))].sort((a, b) => b.length - a.length);
828
872
  for (let d of dirs) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-mobile-kit",
3
- "version": "0.7.10",
3
+ "version": "0.7.12",
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,7 +20,7 @@ This project may also use other AI workflow frameworks (for example Superpowers,
20
20
  | Add a library (ask first) | `npx expo install <package>`: the version that matches the SDK |
21
21
  | Lint, typecheck, test (each skips what the app doesn't have yet) | `sh scripts/amk/pm-run.sh lint`, `sh scripts/amk/pm-run.sh typecheck`, `sh scripts/amk/pm-run.sh test` |
22
22
  | Check dependency versions and the app config | `npx expo install --check`, `npx expo-doctor` |
23
- | Check on devices (release builds, Maestro flows, screenshots) | `sh scripts/amk/verify.sh all --spec <id>`; another iOS scheme: `--scheme <name>`; only some screens: `--screens phone` (or `tablet`, `landscape`, …) |
23
+ | Check on devices (release builds, Maestro flows, screenshots) | `sh scripts/amk/verify.sh all --spec <id>`; another iOS scheme: `--scheme <name>`; only some screens: `--screens phone` (or `tablet`, `landscape`, …); on a real iPhone or iPad the user names: `AMK_IOS_DEVICE=<its UDID>` (the flows clear the app's data on it) |
24
24
  | Check every device at the same time, on a machine with room for it | `sh scripts/amk/verify.sh plan --spec <id>` says whether, and prints the commands: one per device, each for an `m-device-checker` subagent |
25
25
  | Specs: progress, format check, fold a finished feature into the living spec | `node scripts/amk/specs.js status`, `node scripts/amk/specs.js check`, `node scripts/amk/specs.js merge <id>` |
26
26
  | Check a release before tagging it (versions, permission texts, debug leftovers) | `node scripts/amk/release-check.js` |
@@ -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.
@@ -20,7 +20,7 @@ This project may also use other AI workflow frameworks (for example Superpowers,
20
20
  | iOS pods (after native dependency changes) | `sh scripts/amk/pod-install.sh` |
21
21
  | iOS build (simulator, no signing) | `sh scripts/amk/ios-build.sh` |
22
22
  | Android build | `cd android && ./gradlew assembleDebug` |
23
- | Check on devices (release builds, Maestro flows, screenshots) | `sh scripts/amk/verify.sh all --spec <id>`; with product flavors it checks the first unless `--flavor <name>`; another iOS scheme: `--scheme <name>`; only some screens: `--screens phone` (or `tablet`, `landscape`, …) |
23
+ | Check on devices (release builds, Maestro flows, screenshots) | `sh scripts/amk/verify.sh all --spec <id>`; with product flavors it checks the first unless `--flavor <name>`; another iOS scheme: `--scheme <name>`; only some screens: `--screens phone` (or `tablet`, `landscape`, …); on a real iPhone or iPad the user names: `AMK_IOS_DEVICE=<its UDID>` (the flows clear the app's data on it) |
24
24
  | Check every device at the same time, on a machine with room for it | `sh scripts/amk/verify.sh plan --spec <id>` says whether, and prints the commands: one per device, each for an `m-device-checker` subagent |
25
25
  | Specs: progress, format check, fold a finished feature into the living spec | `node scripts/amk/specs.js status`, `node scripts/amk/specs.js check`, `node scripts/amk/specs.js merge <id>` |
26
26
  | Check a release before tagging it (versions, permission texts, debug leftovers) | `node scripts/amk/release-check.js` |
@@ -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);
@@ -4,6 +4,9 @@
4
4
  # archives with: apps with one per environment (for example "Release Staging") get theirs.
5
5
  # AMK_IOS_SCHEME picks the scheme (default: the one named like the workspace).
6
6
  # Output goes to ios/DerivedData: ios/build holds React Native codegen files from pod install.
7
+ # `ios-build.sh device <UDID>` builds for that iPhone or iPad instead, signed by Xcode's automatic signing for the team
8
+ # in AMK_IOS_TEAM, with the Apple account in Xcode: the first time, Xcode registers the device with the team and makes a
9
+ # development profile for it. The project's own signing settings stay as they are.
7
10
  set -eu
8
11
  config=${CONFIGURATION:-Debug}
9
12
  workspace=$(ls -d ios/*.xcworkspace 2>/dev/null | head -n 1)
@@ -15,6 +18,21 @@ if [ "$config" = Release ]; then
15
18
  [ -n "$config" ] || config=Release
16
19
  fi
17
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
+
25
+ if [ "${1:-}" = device ]; then
26
+ [ -n "${AMK_IOS_TEAM:-}" ] || { echo "Set AMK_IOS_TEAM to the Apple team to sign with (Xcode > Settings > Accounts lists them)."; exit 1; }
27
+ # signed for development whatever the project signs its releases with (a distribution profile doesn't install)
28
+ check_build -workspace "$workspace" -scheme "$scheme" -configuration "$config" -destination "id=$2" \
29
+ -derivedDataPath ios/DerivedData -allowProvisioningUpdates -allowProvisioningDeviceRegistration \
30
+ DEVELOPMENT_TEAM="$AMK_IOS_TEAM" CODE_SIGN_STYLE=Automatic CODE_SIGN_IDENTITY="Apple Development" \
31
+ PROVISIONING_PROFILE_SPECIFIER= -quiet build
32
+ echo "iOS device build OK ($scheme, $config, team $AMK_IOS_TEAM)"
33
+ exit 0
34
+ fi
35
+
18
36
  # only this Mac's simulator architecture: a Release build would otherwise compile Intel and Apple silicon both,
19
37
  # and fail to link libraries that ship without an Intel simulator slice. Not when the project or a pod excludes it
20
38
  # for the simulator (Google's ML Kit pods exclude arm64): then Xcode builds what the project allows.
@@ -23,7 +41,7 @@ arch=x86_64
23
41
  set -- ARCHS="$arch"
24
42
  ! grep -rqsE "EXCLUDED_ARCHS\[sdk=iphonesimulator\*\]\"? = [^;]*$arch" ios/*.xcodeproj/project.pbxproj "ios/Pods/Target Support Files" || set --
25
43
 
26
- xcodebuild -workspace "$workspace" -scheme "$scheme" -configuration "$config" \
44
+ check_build -workspace "$workspace" -scheme "$scheme" -configuration "$config" \
27
45
  -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' \
28
46
  -derivedDataPath ios/DerivedData "$@" CODE_SIGNING_ALLOWED=NO -quiet build
29
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
+ }
@@ -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,22 +11,29 @@
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
- # or UDID), AMK_ANDROID_DEVICE (adb serial: the only way to check on a phone, whose app data the flows clear),
25
+ # or UDID, or a connected iPhone's or iPad's: the only way to check on one, whose app data the flows clear),
26
+ # AMK_ANDROID_DEVICE (adb serial: the only way to check on a phone, whose app data the flows clear),
24
27
  # AMK_ANDROID_AVD (the emulator to use, started if it isn't running; other devices are left alone),
25
- # AMK_IOS_TABLET (iPad simulator name or UDID), AMK_ANDROID_TABLET_AVD (tablet emulator), AMK_ANDROID_TABLET (serial),
26
- # AMK_PARALLEL (1 or 0: overrides plan's choice), AMK_DEVICE_WAIT (minutes to wait for a device in use, 30),
27
- # AMK_LOCK_DIR (where runs on this machine claim devices; /tmp/agentic-mobile-kit-<user id>)
28
+ # AMK_IOS_TABLET (iPad simulator, or a connected iPad: name or UDID), AMK_ANDROID_TABLET_AVD (tablet emulator),
29
+ # AMK_ANDROID_TABLET (serial), AMK_IOS_TEAM (the Apple team ID that signs builds for real iPhones and iPads;
30
+ # default: the project's), AMK_PARALLEL (1 or 0: overrides plan's choice), AMK_DEVICE_WAIT (minutes to wait for a
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)
28
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
29
34
  # for when it was named or none is free.
35
+ # Real iPhones and iPads (iOS 17 or later): Maestro doesn't run on them, so their flows run through maestro-runner, with
36
+ # WebDriverAgent signed by the same team. The app is opened once first, and crash reports it leaves join the evidence.
30
37
  # Flows that log in read ${MAESTRO_EMAIL} and the like from a local, gitignored .maestro/.env.local (never committed).
31
38
  set -eu
32
39
 
@@ -55,8 +62,21 @@ done
55
62
 
56
63
  root=$(pwd)
57
64
  . scripts/amk/maestro-env.sh
58
- 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}}"
59
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
60
80
  status=0
61
81
 
62
82
  flow_files() {
@@ -129,22 +149,51 @@ claim_wait() {
129
149
  }
130
150
 
131
151
  run_flow() { # screen device app_id file name orientation
132
- # 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
133
154
  debug="$evidence/maestro-logs/$1-$5"
155
+ [ ! -d "$debug" ] || rm -r "$debug"
134
156
  mkdir -p "$debug" "$out/screenshots"
135
- rm -f "$debug/maestro.log"
136
- find "$debug" -path '*/takeScreenshot/*.png' -exec rm -f {} + # an earlier run's, which aren't this run's evidence
137
157
  target=$4
138
- if [ "$6" != PORTRAIT ]; then
139
- # a turned screen: the flow runs inside one that turns the device first and back to portrait after. Maestro
140
- # reads the path in it itself, so it's a native path (a Windows path in Git Bash)
141
- native=$(cd "$(dirname "$4")" && { pwd -W 2> /dev/null || pwd; })/$(basename "$4")
158
+ # Maestro reads the path in the flows below itself, so it's a native path (a Windows path in Git Bash)
159
+ native=$(cd "$(dirname "$4")" && { pwd -W 2> /dev/null || pwd; })/$(basename "$4")
160
+ if is_real "$2"; then
161
+ # on a real device every flow runs inside one, first: the first launchApp maestro-runner finds in a flow decides
162
+ # whether it answers alerts itself, and for most it does (for permission prompts, which it can't allow ahead),
163
+ # pressing the last button of the app's own alerts too, such as a Delete. Maestro never answers an app's alerts.
164
+ # So one that says to leave permissions alone comes first, where it never runs (on Android only)
165
+ on_complete="" turn=""
166
+ if [ "$6" != PORTRAIT ]; then
167
+ # WebDriverAgent turns the device, then fails the step unless the app in front turned too: here the home
168
+ # screen, which most iPhones never turn. Whether the app turned shows in its screenshots. It knows
169
+ # LANDSCAPE_LEFT only as "landscape"
170
+ on_complete='onFlowComplete:\n - setOrientation:\n orientation: PORTRAIT\n optional: true\n'
171
+ turn='- setOrientation:\n orientation: landscape\n optional: true\n'
172
+ fi
173
+ printf "appId: %s\n${on_complete}---\n- runFlow:\n when:\n platform: Android\n commands:\n - launchApp:\n permissions:\n all: unset\n${turn}- runFlow: '%s'\n" "$3" "$native" > "$debug/screen.yaml"
174
+ target=$debug/screen.yaml
175
+ elif [ "$6" != PORTRAIT ]; then
176
+ # a turned screen: the flow runs inside one that turns the device first and back to portrait after
142
177
  printf "appId: %s\nonFlowComplete:\n - setOrientation: PORTRAIT\n---\n- setOrientation: %s\n- runFlow: '%s'\n" "$3" "$6" "$native" > "$debug/screen.yaml"
143
178
  target=$debug/screen.yaml
144
179
  fi
180
+ rc=0
181
+ if is_real "$2"; then
182
+ # it also saves each named screenshot next to its flow file: the ones it makes there move to its log folder, so
183
+ # the project stays as it was (they're in its report too)
184
+ pngs() { find "$(dirname "$4")" \( -path "$root/.amk" -o -name node_modules \) -prune -o -name '*.png' -print | sort; }
185
+ pngs "$@" > "$debug/.pngs"
186
+ # with the app's build: on a real device, clearState installs the app again
187
+ MAESTRO_RUNNER_NO_TELEMETRY=1 DO_NOT_TRACK=1 npx -y "$runner" --platform ios --driver wda --device "$2" \
188
+ --team-id "$team" --wda-bundle-id "$3.wda" --app-file "$device_app" test -e APP_ID="$3" --output "$debug" \
189
+ --flatten "$target" > "$out/$5.log" 2>&1 || rc=$?
190
+ pngs "$@" | comm -13 "$debug/.pngs" - | while IFS= read -r f; do mv "$f" "$debug/"; done
191
+ # its takeScreenshot files, not the ones of a step that failed (<step>-after.png)
192
+ find "$debug" -path '*/assets/*.png' ! -name '*-[0-9][0-9][0-9]-after.png' -exec cp {} "$out/screenshots/" \;
193
+ return $rc
194
+ fi
145
195
  # screenshots use relative names: older Maestro saves them in the current folder, then in --test-output-dir, and
146
196
  # from 2.7 in the debug output under <flow>/takeScreenshot/, from where they join the screen's evidence
147
- rc=0
148
197
  (cd "$out" && maestro --device "$2" test --test-output-dir "$out" --debug-output "$debug" --flatten-debug-output \
149
198
  -e APP_ID="$3" "$target" > "$out/$5.log" 2>&1) || rc=$?
150
199
  find "$debug" -path '*/takeScreenshot/*.png' -exec cp {} "$out/screenshots/" \;
@@ -153,6 +202,8 @@ run_flow() { # screen device app_id file name orientation
153
202
 
154
203
  run_flows() { # screen device app_id orientation (PORTRAIT, or LANDSCAPE_LEFT to turn it) [again]
155
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"
156
207
  mkdir -p "$out"
157
208
  # this run's screenshots are the ones newer than this; the status before it, for running the screen again
158
209
  : > "$out/.started"
@@ -183,9 +234,20 @@ run_flows() { # screen device app_id orientation (PORTRAIT, or LANDSCAPE_LEFT to
183
234
  android_ready "$2" || true
184
235
  ok=0
185
236
  run_flow "$1" "$2" "$3" "$f" "$name" "$4" || ok=$?
237
+ elif [ "$ok" != 0 ] && is_real "$2" && grep -qs 'explicitly trusted' "$out/$name.log"; then
238
+ # as launch_check found it does: here after clearState installed the app again, which it opened a moment later
239
+ echo " $1: the device didn't open the app it had just installed again; running flow $name once more"
240
+ sleep 15
241
+ ok=0
242
+ run_flow "$1" "$2" "$3" "$f" "$name" "$4" || ok=$?
186
243
  fi
187
244
  if [ "$ok" = 0 ]; then
188
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 {} +
248
+ elif is_real "$2"; then
249
+ echo " $1: flow $name failed, see ${out#"$root"/}/$name.log and maestro-runner's own log ${debug#"$root"/}/maestro-runner.log"
250
+ status=1
189
251
  else
190
252
  echo " $1: flow $name failed, see ${out#"$root"/}/$name.log and Maestro's own log ${debug#"$root"/}/maestro.log"
191
253
  status=1
@@ -225,6 +287,14 @@ run_flows() { # screen device app_id orientation (PORTRAIT, or LANDSCAPE_LEFT to
225
287
  elif [ "$wrong" != 0 ]; then
226
288
  echo " $1: $wrong screenshots show the screen $was: the device or the app didn't turn, so this screen isn't checked; treating this as a failure"
227
289
  status=1
290
+ # an app that sets its orientation in code (an orientation library, or native code) can keep it although its native
291
+ # settings allow turning: where it does, so the team can say which is right
292
+ set_in=$(git grep -l -E 'lockTo(Portrait|Landscape)|OrientationLock\.|lockPlatformAsync|setRequestedOrientation|supportedInterfaceOrientationsFor' \
293
+ -- ':!scripts/amk' ':!*.md' 2> /dev/null | head -n 3 | tr '\n' ' ')
294
+ if [ -n "$set_in" ]; then
295
+ case $was in upright) other=landscape ;; *) other=portrait ;; esac
296
+ echo " $1: the app sets its orientation in its code (${set_in% }), which can keep it $was. If it's meant to stay $was, take $other out of its native settings (UISupportedInterfaceOrientations in Info.plist, screenOrientation in AndroidManifest.xml) and this screen isn't checked any more; otherwise change that code"
297
+ fi
228
298
  fi
229
299
  }
230
300
 
@@ -249,10 +319,10 @@ check_screens() { # platform phone tablet app_id screens…
249
319
  upright=LANDSCAPE_LEFT turned=PORTRAIT
250
320
  fi
251
321
  case $screen in *-landscape) turn=$turned where=$where-landscape ;; *) turn=$upright ;; esac
252
- # Maestro turns devices from 2.0 on, and taps the right place on a turned iPad from 2.3
322
+ # Maestro turns devices from 2.0 on, and taps the right place on a turned iPad from 2.3 (real ones: maestro-runner)
253
323
  need=2.0.0
254
324
  case $where in ios-tablet*) need=2.3.0 ;; esac
255
- if [ "$turn" != PORTRAIT ] && ! maestro_at_least $need; then
325
+ if [ "$turn" != PORTRAIT ] && ! is_real "$on" && ! maestro_at_least $need; then
256
326
  echo "$where: not checked: turning the device needs Maestro ${need%.0} or later (this is $(maestro_version))"
257
327
  continue
258
328
  fi
@@ -292,10 +362,13 @@ ios() {
292
362
  fi
293
363
  # pod install also generates React Native codegen files into ios/build/generated; a newer Podfile needs it again
294
364
  if [ ! -d ios/Pods ] || [ ! -d ios/build/generated ] || [ ios/Podfile -nt ios/Pods/Manifest.lock ]; then
295
- 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
296
368
  fi
297
369
  fi
298
- # the simulators first, so they boot while Xcode builds
370
+ # the simulators first, so they boot while Xcode builds. A real iPhone or iPad only when named, as the flows clear
371
+ # the app's data on it
299
372
  device="" tablet=""
300
373
  if [ "$build_only" = 0 ]; then
301
374
  screens=$(screens_for ios)
@@ -304,36 +377,67 @@ ios() {
304
377
  take_simulator iPhone "${AMK_IOS_DEVICE:-}" || { status=1; return; }
305
378
  device=$taken
306
379
  if [ -z "$device" ]; then
307
- if [ -n "${AMK_IOS_DEVICE:-}" ]; then echo "ios: no simulator has the name or UDID \"$AMK_IOS_DEVICE\""; else echo "ios: no iPhone simulator found (set AMK_IOS_DEVICE)"; fi
380
+ if [ -n "${AMK_IOS_DEVICE:-}" ]; then echo "ios: no simulator or connected iPhone or iPad has the name or UDID \"$AMK_IOS_DEVICE\""; else echo "ios: no iPhone simulator found (set AMK_IOS_DEVICE)"; fi
308
381
  status=1; return
309
382
  fi
310
383
  fi
311
384
  if echo "$screens" | grep -q '^tablet-'; then
312
385
  take_simulator iPad "${AMK_IOS_TABLET:-}" || { status=1; return; }
313
386
  tablet=$taken
314
- if [ -z "$tablet" ] && [ -n "${AMK_IOS_TABLET:-}" ]; then echo "ios: no simulator has the name or UDID \"$AMK_IOS_TABLET\""; status=1; return; fi
387
+ if [ -z "$tablet" ] && [ -n "${AMK_IOS_TABLET:-}" ]; then echo "ios: no simulator or connected iPad has the name or UDID \"$AMK_IOS_TABLET\""; status=1; return; fi
315
388
  [ -n "$tablet" ] || echo "ios: the app runs on iPad, but there's no iPad simulator, so iPads aren't checked (add one in Xcode, or set AMK_IOS_TABLET)"
316
389
  fi
317
- for d in $device $tablet; do xcrun simctl boot "$d" 2> /dev/null || true; done
390
+ [ -n "$device$tablet" ] || return
391
+ for d in $device $tablet; do
392
+ if is_real "$d"; then echo "ios: checking on $d, a real device; the flows clear the app's data on it"
393
+ else xcrun simctl boot "$d" 2> /dev/null || true; fi
394
+ done
395
+ else
396
+ # the plan's build step: a build for each real device named too
397
+ for n in "${AMK_IOS_DEVICE:-}" "${AMK_IOS_TABLET:-}"; do
398
+ [ -z "$n" ] || [ -n "$(simulators iPhone "$n")" ] || { r=$(real_ios "$n"); [ -z "$r" ] || reals="$reals $r"; }
399
+ done
318
400
  fi
401
+ team=$(ios_team)
402
+ if [ -n "$reals" ] && [ -z "$team" ]; then
403
+ echo "ios: a real device runs only apps signed by an Apple team: set AMK_IOS_TEAM to your team ID (Xcode > Settings > Accounts lists them)"
404
+ status=1; return
405
+ fi
406
+ sims=$build_only # whether to build for simulators: the plan's build step always does
407
+ for d in $device $tablet; do is_real "$d" || sims=1; done
319
408
  # one build of this project at a time; a check without its own build waits for one that's under way
320
409
  claim_wait "build-ios-$project" "" "the iOS build of this project" || { status=1; return; }
321
410
  if [ "$no_build" = 0 ]; then
322
- if ! CONFIGURATION=Release sh scripts/amk/ios-build.sh > "$evidence/ios-build.log" 2>&1; then
411
+ if [ "$sims" = 1 ] && ! CONFIGURATION=Release sh scripts/amk/ios-build.sh > "$evidence/ios-build.log" 2>&1; then
323
412
  echo "ios: release build FAILED, see ${evidence#"$root"/}/ios-build.log"; status=1; return
324
413
  fi
414
+ for d in $reals; do
415
+ if ! CONFIGURATION=Release AMK_IOS_TEAM=$team sh scripts/amk/ios-build.sh device "$d" > "$evidence/ios-device-build.log" 2>&1; then
416
+ echo "ios: release build for $d FAILED, see ${evidence#"$root"/}/ios-device-build.log"; status=1; return
417
+ fi
418
+ done
325
419
  fi
326
420
  unclaim "build-ios-$project"
327
421
  [ "$build_only" = 0 ] || { echo "ios: release build done"; return; }
328
422
  # the newest app: the scheme just built (another scheme's app may still be there from an earlier build)
329
423
  app=$(ls -dt ios/DerivedData/Build/Products/*-iphonesimulator/*.app 2> /dev/null | head -n 1)
330
- [ -n "$app" ] || { echo "ios: there's no build to check yet: run sh scripts/amk/verify.sh build first"; status=1; return; }
331
- app_id=$(/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' "$app/Info.plist")
424
+ device_app=$(ls -dt "$root"/ios/DerivedData/Build/Products/*-iphoneos/*.app 2> /dev/null | head -n 1)
425
+ a=$app
426
+ [ "$sims" = 1 ] || a=$device_app
427
+ if [ -z "$a" ] || { [ -n "$reals" ] && [ -z "$device_app" ]; }; then
428
+ echo "ios: there's no build to check yet: run sh scripts/amk/verify.sh build first"; status=1; return
429
+ fi
430
+ app_id=$(/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' "$a/Info.plist")
332
431
  for d in $device $tablet; do
333
- xcrun simctl bootstatus "$d" -b > /dev/null
334
- xcrun simctl install "$d" "$app"
432
+ if is_real "$d"; then
433
+ launch_check "$d" || { status=1; return; }
434
+ else
435
+ xcrun simctl bootstatus "$d" -b > /dev/null
436
+ xcrun simctl install "$d" "$app"
437
+ fi
335
438
  done
336
439
  check_screens ios "$device" "$tablet" "$app_id" $screens
440
+ for d in $reals; do crash_reports "$d"; done
337
441
  }
338
442
 
339
443
  # the simulators for $1 (iPhone or iPad), best first: the one named in $2 (name or UDID); else the booted ones,
@@ -351,17 +455,87 @@ simulators() {
351
455
  console.log(list.map(d => d.udid).join("\n"));'
352
456
  }
353
457
  # a simulator for $1 (iPhone or iPad) that this run holds, in $taken: the one named in $2, once it's free; else the
354
- # first free one; else the best one, once it's free. Empty when there's none
458
+ # first free one; else the best one, once it's free. Empty when there's none. A name no simulator has can be a real
459
+ # device's
355
460
  take_simulator() {
356
461
  taken=""
357
462
  candidates=$(simulators "$1" "$2")
463
+ if [ -z "$candidates" ] && [ -n "$2" ]; then
464
+ candidates=$(real_ios "$2")
465
+ [ -z "$candidates" ] || reals="$reals $candidates"
466
+ fi
358
467
  [ -n "$candidates" ] || return 0
359
468
  first=$(echo "$candidates" | head -n 1)
360
469
  if [ -z "$2" ]; then
361
470
  for u in $candidates; do claim "ios-$u" "$u" && { taken=$u; break; }; done
362
471
  [ -z "$taken" ] || [ "$taken" = "$first" ] || echo "ios: $first is in use by $(holder "ios-$first"), so checking on $taken"
363
472
  fi
364
- [ -n "$taken" ] || { claim_wait "ios-$first" "$first" "the $1 simulator $first" || return 1; taken=$first; }
473
+ [ -n "$taken" ] || { claim_wait "ios-$first" "$first" "the $1 $first" || return 1; taken=$first; }
474
+ }
475
+
476
+ # Real iPhones and iPads, through Xcode's devicectl (iOS 17 or later). Maestro doesn't run on them, so their flows run
477
+ # through maestro-runner: pinned, as a newer one may behave differently, and without its usage data
478
+ runner=maestro-runner@1.1.29
479
+ reals="" # the real devices this run checks on
480
+ is_real() { case " $reals " in *" $1 "*) ;; *) return 1 ;; esac; }
481
+ # the UDID of the connected iPhone or iPad with the name or UDID $1
482
+ real_ios() {
483
+ xcrun devicectl list devices --json-output "$evidence/.devices.json" > /dev/null 2>&1 || return 0
484
+ WANT=$1 node -e 'const want = process.env.WANT;
485
+ const d = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")).result.devices.find(d => d.hardwareProperties?.reality === "physical" &&
486
+ [d.identifier, d.deviceProperties?.name, d.hardwareProperties.udid].includes(want));
487
+ if (d) console.log(d.hardwareProperties.udid);' "$evidence/.devices.json"
488
+ }
489
+ # the Apple team that signs the app and WebDriverAgent for real devices: AMK_IOS_TEAM, else the project's
490
+ ios_team() { echo "${AMK_IOS_TEAM:-$(sed -n 's/.*DEVELOPMENT_TEAM = "\{0,1\}\([A-Z0-9]\{10\}\)"\{0,1\};.*/\1/p' ios/*.xcodeproj/project.pbxproj 2> /dev/null | head -n 1)}"; }
491
+ # installs the app on the real device $1 and opens it, so what the device needs (trusting the team, unlocking) shows
492
+ # before the flows, and an app that closes at once is caught with its crash report. Notes the crash reports already there
493
+ launch_check() {
494
+ exe=$(/usr/libexec/PlistBuddy -c 'Print CFBundleExecutable' "$device_app/Info.plist")
495
+ crashes "$1" > "$evidence/.crashes-$1"
496
+ log=$evidence/launch-$1.log
497
+ if ! xcrun devicectl device install app --device "$1" "$device_app" > "$log" 2>&1; then
498
+ echo "ios: the app didn't install on $1 (is it unlocked, with Developer Mode on?), see ${log#"$root"/}"
499
+ return 1
500
+ fi
501
+ # a device now and then refuses an app it has just installed for a moment, as if it didn't trust the team
502
+ tries=0
503
+ until said=$(xcrun devicectl device process launch --device "$1" --terminate-existing "$app_id" 2>&1); do
504
+ echo "$said" >> "$log"
505
+ tries=$((tries + 1))
506
+ case $said in
507
+ *'explicitly trusted'*) [ "$tries" -lt 3 ] || {
508
+ echo "ios: $1 doesn't open apps from this team yet: on it, Settings > General > VPN & Device Management > Developer App > Trust, then run this again"
509
+ return 1; } ;;
510
+ *) echo "ios: the app didn't open on $1 (is it unlocked?), see ${log#"$root"/}"; return 1 ;;
511
+ esac
512
+ sleep 10
513
+ done
514
+ echo "$said" >> "$log"
515
+ sleep 10
516
+ xcrun devicectl device info processes --device "$1" --json-output "$evidence/.processes.json" > /dev/null 2>&1 || true
517
+ if ! grep -qs "/$(basename "$device_app")/" "$evidence/.processes.json"; then
518
+ echo "ios: the app closed within 10 seconds of opening on $1"
519
+ crash_reports "$1"
520
+ return 1
521
+ fi
522
+ }
523
+ # the app's crash reports on the real device $1
524
+ crashes() {
525
+ xcrun devicectl device info files --device "$1" --domain-type systemCrashLogs --json-output "$evidence/.files.json" > /dev/null 2>&1 || return 0
526
+ EXE=$exe node -e 'for (const f of JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")).result.files || [])
527
+ if (f.relativePath.startsWith(process.env.EXE + "-") && f.relativePath.endsWith(".ips")) console.log(f.relativePath)' "$evidence/.files.json"
528
+ }
529
+ # the ones that weren't there before launch_check join the evidence: the app crashed during the checks
530
+ crash_reports() {
531
+ new=$(crashes "$1" | grep -v -x -F -f "$evidence/.crashes-$1" || true)
532
+ [ -n "$new" ] || return 0
533
+ mkdir -p "$evidence/crashes"
534
+ for c in $new; do
535
+ xcrun devicectl device copy from --device "$1" --domain-type systemCrashLogs --source "$c" --destination "$evidence/crashes/$c" > /dev/null 2>&1 || true
536
+ done
537
+ echo "ios: the app crashed on $1 during the checks: $(echo "$new" | wc -l | tr -d ' ') crash reports in ${evidence#"$root"/}/crashes"
538
+ status=1
365
539
  }
366
540
 
367
541
  # a running emulator's adb serial: of the AVD named in $1 if one is, else of the kind in $2 (phone or tablet) if given
@@ -532,7 +706,9 @@ android() {
532
706
  set -- "$@" -Pandroid.injected.signing.store.file="$keystore" -Pandroid.injected.signing.store.password=android \
533
707
  -Pandroid.injected.signing.key.alias=androiddebugkey -Pandroid.injected.signing.key.password=android
534
708
  fi
535
- 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
536
712
  echo "android: release build FAILED, see ${evidence#"$root"/}/android-build.log"; status=1; return
537
713
  fi
538
714
  fi