agentic-mobile-kit 0.7.16 → 0.7.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. package/bin/cli.js +1 -1
  2. package/lib/init.js +122 -20
  3. package/package.json +1 -1
  4. package/stacks/react-native/expo/.agents/skills/THIRD_PARTY.md +1 -1
  5. package/stacks/react-native/expo/AGENTS.md +6 -3
  6. package/stacks/react-native/expo/docs/amk/expo.md +60 -4
  7. package/stacks/react-native/new-app/ErrorBoundary.tsx +61 -0
  8. package/stacks/react-native/new-app/error-boundary.tsx +30 -0
  9. package/stacks/react-native/template/.agents/skills/m-feature/SKILL.md +6 -5
  10. package/stacks/react-native/template/.agents/skills/m-prototype/SKILL.md +4 -3
  11. package/stacks/react-native/template/.agents/skills/m-review/SKILL.md +10 -6
  12. package/stacks/react-native/template/.github/workflows/e2e.yml +3 -0
  13. package/stacks/react-native/template/.rulesync/subagents/m-device-checker.md +2 -2
  14. package/stacks/react-native/template/.rulesync/subagents/m-reviewer.md +3 -3
  15. package/stacks/react-native/template/AGENTS.md +5 -2
  16. package/stacks/react-native/template/docs/amk/react-native.md +58 -3
  17. package/stacks/react-native/template/scripts/amk/a11y.js +78 -0
  18. package/stacks/react-native/template/scripts/amk/release-check.js +149 -2
  19. package/stacks/react-native/template/scripts/amk/report.js +78 -0
  20. package/stacks/react-native/template/scripts/amk/rn-check.js +435 -0
  21. package/stacks/react-native/template/scripts/amk/verify.sh +139 -15
  22. package/stacks/react-native/template/specs/_templates/design.md +16 -0
  23. package/stacks/react-native/template/specs/_templates/flow.yaml +8 -0
  24. package/stacks/react-native/template/specs/_templates/subflow.yaml +36 -0
@@ -0,0 +1,435 @@
1
+ #!/usr/bin/env node
2
+ // Checks the lines this branch adds or changes for React Native mistakes that the app's rules (docs/amk/react-native.md
3
+ // or expo.md) list, and its Maestro flows (.maestro/): Maestro's own syntax check, files they run that aren't there,
4
+ // taps by text, and each scenario of a spec the branch touched with its steps, an assertion and a screenshot.
5
+ // Problems (✗) fail it, and so verify.sh quick; warnings (!) don't. Only changed lines: code already
6
+ // on the base branch is never reported. A line that's right as it is carries `// amk-ok <date>: <reason>`, on it or on
7
+ // the line above, with the user's reason and the day they gave it; it's listed as kept, for review. When a branch changes
8
+ // a file again, a kept line in it that's over two weeks old is reported again, for the user to decide again (the date
9
+ // from git when the comment has none).
10
+ // The base is the one baseline.js uses (AMK_BASE sets it). Usage: node scripts/amk/rn-check.js
11
+ 'use strict';
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const { execFileSync, spawnSync } = require('child_process');
15
+
16
+ const root = process.cwd();
17
+ const git = (...args) => {
18
+ try {
19
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 2 ** 28 });
20
+ } catch {
21
+ return null;
22
+ }
23
+ };
24
+ if (git('rev-parse', '--git-dir') === null) {
25
+ console.log('rn-check: skipped (not a git repository)');
26
+ process.exit(0);
27
+ }
28
+
29
+ // ---------- the changed lines ----------
30
+ const found = spawnSync(process.execPath, [path.join(__dirname, 'baseline.js'), 'base'], { cwd: root, encoding: 'utf8' });
31
+ const baseRef = found.status === 0 ? found.stdout.trim() : '';
32
+ const sha = (baseRef && git('merge-base', 'HEAD', baseRef) || git('rev-parse', '--verify', '--quiet', 'HEAD') || '').trim();
33
+ const since = baseRef || 'the last commit';
34
+ const source = f => /\.(js|jsx|ts|tsx|mjs|cjs)$/.test(f) && !f.endsWith('.d.ts')
35
+ && !/(^|\/)(node_modules|scripts\/amk|__tests__|__mocks__|e2e)\//.test(f)
36
+ && !/\.(test|spec)\.\w+$|(^|\/)(jest[.-]setup|setup-?tests)[^/]*$/i.test(f);
37
+ // Maestro flows: the ones verify.sh runs (.maestro/*.yaml) and the subflows they run (in folders below)
38
+ // (not the copies with view-tree steps verify.sh runs for a moment on Android: .amk-<screen>-<flow>.yaml)
39
+ const flowFile = f => /^\.maestro\/.+\.ya?ml$/.test(f) && !/(^|\/)\.amk-/.test(f);
40
+ const changed = new Map(); // file -> Set of line numbers, or 'all'
41
+ if (sha) {
42
+ let file = null;
43
+ for (const line of (git('diff', '-U0', '--no-color', '--no-ext-diff', '--relative', '-M', '--diff-filter=ACMR', sha) || '').split('\n')) {
44
+ if (line.startsWith('+++ ')) { file = line === '+++ /dev/null' ? null : line.slice(6); continue; }
45
+ const h = /^@@ -\S+ \+(\d+)(?:,(\d+))? @@/.exec(line);
46
+ if (!h || !file || !(source(file) || flowFile(file))) continue;
47
+ if (!changed.has(file)) changed.set(file, new Set());
48
+ for (let n = Number(h[1]), end = n + Number(h[2] ?? 1); n < end; n++) changed.get(file).add(n);
49
+ }
50
+ }
51
+ for (const f of (git('ls-files', '--others', '--exclude-standard') || '').split('\n')) if (f && (source(f) || flowFile(f))) changed.set(f, 'all');
52
+
53
+ // ---------- what the app uses ----------
54
+ let pkg = {};
55
+ try { pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); } catch {}
56
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
57
+ const major = name => Number((/\d+/.exec(deps[name] || '') || [0])[0]);
58
+ const expoSdk = deps.expo ? major('expo') : 0;
59
+
60
+ // the code without its comments (each comment character a space, so positions and lines stay). A quote opened in
61
+ // JSX text (Don't) ends with its line, so it can't hide the rest of the file; a template string can span lines
62
+ function stripComments(text) {
63
+ const out = text.split('');
64
+ let block = false;
65
+ let quote = null;
66
+ for (let i = 0; i < text.length; i++) {
67
+ const c = text[i];
68
+ const n = text[i + 1];
69
+ if (c === '\n') { if (quote !== '`') quote = null; continue; }
70
+ if (block) {
71
+ if (c === '*' && n === '/') { out[i] = out[i + 1] = ' '; i++; block = false; } else out[i] = ' ';
72
+ continue;
73
+ }
74
+ if (quote) { if (c === '\\') i++; else if (c === quote) quote = null; continue; }
75
+ if (c === '"' || c === "'" || c === '`') { quote = c; continue; }
76
+ if (c === '/' && n === '*') { block = true; out[i] = out[i + 1] = ' '; i++; continue; }
77
+ // not a URL's // (https://) or one in a regular expression (\/\/)
78
+ if (c === '/' && n === '/' && !/[:\w\\]/.test(text[i - 1] || '')) {
79
+ while (i < text.length && text[i] !== '\n') out[i++] = ' ';
80
+ i--;
81
+ }
82
+ }
83
+ return out.join('');
84
+ }
85
+
86
+ // from an opening bracket or a tag's <, the index of its end: the matching bracket, or the tag's closing >
87
+ function endOf(code, start) {
88
+ const open = { '(': ')', '[': ']', '{': '}' };
89
+ const stack = [];
90
+ let quote = null;
91
+ for (let i = start; i < code.length; i++) {
92
+ const c = code[i];
93
+ if (quote) { if (c === '\\') i++; else if (c === quote || (c === '\n' && quote !== '`')) quote = null; continue; }
94
+ if (c === '"' || c === "'" || c === '`') quote = c;
95
+ else if (open[c]) stack.push(open[c]);
96
+ else if (c === stack[stack.length - 1]) { stack.pop(); if (!stack.length && code[start] !== '<') return i; }
97
+ else if (c === '>' && code[start] === '<' && !stack.length && code[i - 1] !== '=') return i;
98
+ }
99
+ return code.length - 1;
100
+ }
101
+
102
+ // ---------- the checks ----------
103
+ const findings = [];
104
+ const kept = [];
105
+ const DAY = 24 * 3600 * 1000;
106
+ // a day as the user's calendar has it
107
+ const localDay = ms => new Date(ms - new Date(ms).getTimezoneOffset() * 60000).toISOString().slice(0, 10);
108
+ const today = localDay(Date.now());
109
+ // when the amk-ok on line n of file was given: its date, else the day git has for the line (today when uncommitted)
110
+ function okSince(file, n, date) {
111
+ if (date) return date;
112
+ const t = /^committer-time (\d+)$/m.exec(git('blame', '--porcelain', '-L', `${n},${n}`, '--', file) || '');
113
+ return t ? localDay(Number(t[1]) * 1000) : today;
114
+ }
115
+ const BASE64 = new Set([...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='].map(c => c.charCodeAt(0)));
116
+ const SECRETS = [
117
+ [/\bgh[pousr]_[A-Za-z0-9]{36,}/g, 'a GitHub token'], [/\bgithub_pat_[A-Za-z0-9_]{40,}/g, 'a GitHub token'],
118
+ [/\b[sr]k_live_[A-Za-z0-9]{20,}/g, 'a Stripe secret key'], [/\bAKIA[0-9A-Z]{16}\b/g, 'an AWS access key'],
119
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----/g, 'a private key'], [/\bxox[baprs]-[A-Za-z0-9-]{10,}/g, 'a Slack token'],
120
+ [/\bsk-(proj-|ant-)?[A-Za-z0-9_-]{32,}/g, 'an AI service API key'],
121
+ ];
122
+ const importsFrom = (code, from) => [...code.matchAll(new RegExp(`import\\s+[^;'"]*?\\{([^}]*)\\}\\s*from\\s*['"]${from}['"]`, 'g'))];
123
+ const timers = /\bset(Timeout|Interval)\s*\(/;
124
+ // a permission prompt (not App Tracking Transparency's, which apps show early on purpose)
125
+ const ASK = /\b(PermissionsAndroid\.request(?:Multiple)?|request\(\s*PERMISSIONS\.|requestMultiple|request(?:Foreground|Background)?PermissionsAsync|requestNotifications|requestPermission|Geolocation\.requestAuthorization)\s*\(?/;
126
+ const TOUCHABLE = /^(Pressable|TouchableOpacity|TouchableHighlight|TouchableWithoutFeedback|TouchableNativeFeedback)$/;
127
+ const listeners = /\.(addEventListener|addListener|subscribe)\s*\(/;
128
+ const reduceMotion = /isReduceMotionEnabled|reduceMotionChanged|useReducedMotion|ReduceMotion\b/;
129
+
130
+ function check(file, text) {
131
+ const code = stripComments(text);
132
+ const ts = /\.tsx?$/.test(file);
133
+ const out = [];
134
+ const add = (level, at, end, message, line) => out.push({ level, at, end: end ?? at, message, line });
135
+ const each = (re, fn, src = code) => { for (const m of src.matchAll(re)) fn(m); };
136
+
137
+ // problems: removed or private APIs, secrets and tokens in the open, images in code
138
+ each(/\bInteractionManager\b/g, m => add('✗', m.index, null, 'InteractionManager was removed in React Native 0.87: use requestIdleCallback'));
139
+ each(/\babsoluteFillObject\b/g, m => add('✗', m.index, null, 'StyleSheet.absoluteFillObject was removed in React Native 0.85: use StyleSheet.absoluteFill'));
140
+ each(/\bStatusBar\s*\.\s*set(BackgroundColor|Translucent)\s*\(/g, m => add('✗', m.index, null, `StatusBar.set${m[1]} was removed in React Native 0.87 (edge to edge, it did nothing)`));
141
+ each(/<\s*(StatusBar|Modal|ScrollView|FlatList|SectionList|KeyboardAwareScrollView)\b/g, m => {
142
+ const end = endOf(code, m.index);
143
+ const tag = code.slice(m.index, end + 1);
144
+ const prop = m[1] === 'StatusBar' ? /\s(backgroundColor|translucent)\b/.exec(tag)
145
+ : m[1] === 'Modal' ? /\s(animated)\b(?!Type)/.exec(tag)
146
+ : /\s(keyboardShouldPersistTaps)(\s*=\s*\{\s*(true|false)\s*\}|(?=[\s/>]))/.exec(tag);
147
+ if (!prop) return;
148
+ const instead = { backgroundColor: 'edge to edge, it did nothing', translucent: 'edge to edge, it did nothing', animated: 'use animationType', keyboardShouldPersistTaps: 'use "handled"' }[prop[1]];
149
+ add('✗', m.index + prop.index + 1, null, `${m[1]}'s ${prop[1] === 'keyboardShouldPersistTaps' ? 'boolean keyboardShouldPersistTaps' : prop[1]} was removed in React Native 0.87: ${instead}`);
150
+ });
151
+ each(/(['"])react-native\/Libraries\/[^'"\n]*\1/g, m => add('✗', m.index, null, `${m[0]} is React Native's private code (a type error from 0.87): import from 'react-native'`));
152
+ // at the name itself: a branch that adds another name to an old import statement didn't add this one
153
+ for (const m of importsFrom(code, 'react-native')) {
154
+ const name = n => { const i = m[0].search(new RegExp(`\\b${n}\\b`)); return i < 0 ? null : m.index + i; };
155
+ if (name('SafeAreaView') !== null) add('✗', name('SafeAreaView'), null, "SafeAreaView from 'react-native' is deprecated and iOS-only: use react-native-safe-area-context");
156
+ for (const n of ['ImageBackground', 'InputAccessoryView', 'DrawerLayoutAndroid']) {
157
+ if (name(n) !== null) add('!', name(n), null, `${n} is deprecated in React Native: see the React Native rules for its replacement`);
158
+ }
159
+ for (const n of ['NativeModules', 'requireNativeComponent']) {
160
+ if (name(n) !== null) add('!', name(n), null, `${n} is the old architecture: write a Turbo Module or a Fabric component`);
161
+ }
162
+ }
163
+ each(/\bAsyncStorage\s*\.\s*(setItem|multiSet|mergeItem)\s*\(/g, m => {
164
+ const open = m.index + m[0].length - 1;
165
+ if (/token|password|passwd|secret|credential|api[_-]?key/i.test(code.slice(open, endOf(code, open)))) {
166
+ add('✗', m.index, null, `a token or password saved to AsyncStorage, which isn't encrypted: use ${expoSdk ? 'expo-secure-store' : 'the Keychain/Keystore (react-native-keychain)'}`);
167
+ }
168
+ });
169
+ // secrets are reported without their value; comments too, as they ship in the repository
170
+ for (const [re, what] of SECRETS) each(re, m => add('✗', m.index, null, `${what} in code: anyone with the repository or the app can read it. Revoke it and keep it on a server`), text);
171
+ each(/\bAIza[0-9A-Za-z_-]{35}\b/g, m => add('!', m.index, null, 'a Google API key in code: ship it only if it is restricted to this app (Google Cloud console)'), text);
172
+ // measured without a regular expression, whose repetition overflows the stack on an image of a few MB
173
+ for (let i = text.indexOf('data:image/'); i !== -1; i = text.indexOf('data:image/', i + 1)) {
174
+ const head = /^data:image\/[a-z+]+;base64,/.exec(text.slice(i, i + 40));
175
+ if (!head) continue;
176
+ let j = i + head[0].length;
177
+ while (j < text.length && BASE64.has(text.charCodeAt(j))) j++;
178
+ if (j - i >= 8000) add('✗', i, j, `a ${Math.round((j - i) * 0.75 / 1024)} KB base64 image in code: put it in an asset file`);
179
+ i = j;
180
+ }
181
+ if (expoSdk >= 56 && deps['expo-router']) {
182
+ each(/(['"])@react-navigation\/[^'"\n]+\1/g, m => add('✗', m.index, null, `${m[0]} doesn't work alongside Expo Router from SDK 56: import from expo-router (see the expo-router skill)`));
183
+ }
184
+
185
+ // warnings: likely mistakes, which an app's own components can make right
186
+ each(/<\s*(Pressable|TouchableOpacity|TouchableHighlight|TouchableWithoutFeedback|TouchableNativeFeedback)\b/g, m => {
187
+ const end = endOf(code, m.index);
188
+ const tag = code.slice(m.index, end + 1);
189
+ if (/\{\s*\.\.\./.test(tag) || /\baccessible\s*=\s*\{\s*false\s*\}/.test(tag) || /onPress\s*=\s*\{\s*Keyboard\.dismiss\s*\}/.test(tag)) return;
190
+ const missing = [!/\b(accessibilityLabel|aria-label|accessibilityLabelledBy)\b/.test(tag) && 'accessibilityLabel', !/\b(accessibilityRole|role)\s*=/.test(tag) && 'accessibilityRole'].filter(Boolean);
191
+ if (missing.length) add('!', m.index, end, `<${m[1]}> without ${missing.join(' and ')}: screen readers can't tell what it does`);
192
+ });
193
+ each(/\bDimensions\s*\.\s*get\s*\(/g, m => add('!', m.index, null, "Dimensions.get doesn't update on rotation or resizing: use useWindowDimensions()"));
194
+ each(/\ballowFontScaling\s*(=\s*\{\s*false\s*\}|:\s*false\b)/g, m => add('!', m.index, null, 'allowFontScaling false ignores the user\'s text size: make the layout wrap instead'));
195
+ each(/\bkey\s*=\s*\{\s*(index|idx|i)\s*\}/g, m => add('!', m.index, null, 'a list key from the index mixes up rows when items change: use the item\'s ID'));
196
+ each(/\bkeyExtractor\s*=\s*\{\s*\(\s*[^,()]*,\s*(\w+)\s*(?::\s*number\s*)?\)\s*=>\s*(String\(\s*\1\s*\)|\1\s*\.\s*toString\(\s*\)|`\$\{\s*\1\s*\}`|\1)\s*\}/g, m => add('!', m.index, null, 'a list key from the index mixes up rows when items change: use the item\'s ID'));
197
+ each(/\bcatch\s*(\([^)]*\))?\s*\{|\.catch\(\s*(\(\s*\w*\s*\)|\w+)\s*=>\s*\{/g, m => {
198
+ const open = m.index + m[0].length - 1;
199
+ const close = endOf(code, open);
200
+ if (!text.slice(open + 1, close).trim()) add('!', m.index, close, 'an empty catch: the error disappears. Show it, or report it to the crash reporter');
201
+ });
202
+ each(/\buse(Layout)?Effect\s*\(/g, m => {
203
+ const open = m.index + m[0].length - 1;
204
+ const close = endOf(code, open);
205
+ const body = code.slice(open, close);
206
+ const t = timers.exec(body);
207
+ if (t && !/\bclear(Timeout|Interval)\s*\(/.test(body)) add('!', m.index, close, `a set${t[1]} in an effect with nothing clearing it: clear it in the effect's cleanup`, lineAt(code, open + t.index));
208
+ const p = ASK.exec(body);
209
+ if (p) add('!', m.index, close, `${p[1]} in an effect asks when the screen opens: ask when the user starts the feature that needs it`, lineAt(code, open + p.index));
210
+ const l = listeners.exec(body);
211
+ if (l && !/\breturn\b/.test(body)) add('!', m.index, close, `${l[1]} in an effect that returns no cleanup: return a function that removes it`, lineAt(code, open + l.index));
212
+ });
213
+ each(/\bconsole\s*\.\s*log\s*\(/g, m => add('!', m.index, null, 'console.log left in: remove it, or use the app\'s logger'));
214
+ each(/\bmask(AllTextInputs|AllText|AllInputs|TextInputs)\s*:\s*false\b/g, m => add('!', m.index, null, 'session replay that records what users type: mask text inputs'));
215
+ each(/\bAccessibilityInfo\s*\.\s*setAccessibilityFocus\s*\(/g, m => add('!', m.index, null, 'AccessibilityInfo.setAccessibilityFocus is deprecated: use sendAccessibilityEvent'));
216
+ // platform guidelines: text, back, screen readers, tap areas, permissions, motion
217
+ each(/\bfontSize\s*:\s*(\d+(?:\.\d+)?)(?![\w.])/g, m => { if (Number(m[1]) >= 1 && Number(m[1]) < 11) add('!', m.index, null, `fontSize ${m[1]} is under 11, the smallest size Apple's guidelines allow for reading`); });
218
+ each(/\bmaxFontSizeMultiplier\s*[=:]\s*\{?\s*(\d+(?:\.\d+)?)/g, m => { if (Number(m[1]) >= 1 && Number(m[1]) < 2) add('!', m.index, null, `maxFontSizeMultiplier ${m[1]} caps the user's text size: allow at least 2`); });
219
+ each(/\bgestureEnabled\s*[:=]\s*\{?\s*false\b/g, m => add('!', m.index, null, 'gestureEnabled false turns off swipe back: keep it, and ask before leaving unsaved changes with usePreventRemove'));
220
+ each(/['"]hardwareBackPress['"]\s*,\s*\(\s*\)\s*=>\s*true\b/g, m => add('!', m.index, null, 'a back handler that always returns true traps Android\'s back button: return true only while it closes something'));
221
+ each(/\bBackHandler\s*\.\s*exitApp\s*\(/g, m => add('!', m.index, null, 'BackHandler.exitApp: Android apps don\'t quit themselves; leave back to the system'));
222
+ each(/\bVibration\s*\.\s*vibrate\s*\(/g, m => add('!', m.index, null, 'Vibration.vibrate buzzes: use the app\'s haptics library, for success, error or a selection only'));
223
+ each(/\bReduceMotion\s*\.\s*Never\b/g, m => add('!', m.index, null, 'ReduceMotion.Never ignores the user\'s Reduce Motion setting: let decoration stop'));
224
+ each(/\baccessibilityLabel\s*=\s*\{?\s*["']([^"'\n]*)["']/g, m => { if (/\b(button|icon|image|tap|click)\b/i.test(m[1])) add('!', m.index, null, `the label "${m[1]}" names the role or the gesture: screen readers say the role; name the action`); });
225
+ each(/<\s*([A-Z][\w.]*)\b/g, m => {
226
+ const end = endOf(code, m.index);
227
+ const tag = code.slice(m.index, end + 1);
228
+ const at = re => m.index + Math.max(tag.search(re), 0);
229
+ const role = /\b(?:accessibilityRole|role)\s*=\s*\{?\s*["'](switch|checkbox|radio|tab|togglebutton)["']/.exec(tag);
230
+ if (role && !/\b(accessibilityState|aria-checked|aria-selected)\b/.test(tag)) add('!', at(/\b(accessibilityRole|role)\s*=/), null, `a ${role[1]} without accessibilityState: screen readers can't tell whether it's on`);
231
+ if (m[1] === 'Modal' && !/\bonRequestClose\b/.test(tag)) add('!', m.index, null, 'a Modal without onRequestClose: Android\'s back button can\'t close it');
232
+ if (/\bonLongPress\s*=/.test(tag) && !/\baccessibilityActions\b/.test(tag)) add('!', at(/\bonLongPress\s*=/), null, 'a long-press action screen readers can\'t reach: add it to accessibilityActions, and show it another way too');
233
+ if ((m[1] === 'LottieView' || m[1] === 'Lottie') && /\sloop\b(?!\s*=\s*\{\s*false\s*\})/.test(tag) && !reduceMotion.test(code)) add('!', m.index, null, 'a looping animation that ignores Reduce Motion: read AccessibilityInfo.isReduceMotionEnabled() and stop it');
234
+ const style = TOUCHABLE.test(m[1]) && !/\b(hitSlop|minWidth|minHeight)\b/.test(tag) && /\bstyle\s*=\s*\{\{([^{}]*)\}\}/.exec(tag);
235
+ const sizes = style ? [...style[1].matchAll(/\b(?:width|height)\s*:\s*(\d+(?:\.\d+)?)(?![\w.%])/g)].map(s => Number(s[1])) : [];
236
+ if (sizes.some(n => n < 44)) add('!', m.index, null, `a <${m[1]}> ${Math.min(...sizes)} points wide or high: tap areas are at least 44×44 (48×48 dp on Android); pad it, or add hitSlop`);
237
+ });
238
+ if (!reduceMotion.test(code)) each(/\bAnimated\s*\.\s*loop\s*\(/g, m => add('!', m.index, null, 'a looping animation that ignores Reduce Motion: read AccessibilityInfo.isReduceMotionEnabled() and stop it'));
239
+ // a file that asks for a permission but never handles one the system won't ask for again
240
+ const ask = ASK.exec(code);
241
+ if (ask && !/canAskAgain|never_ask_again|NEVER_ASK_AGAIN|BLOCKED|\bblocked\b|openSettings/.test(code)) add('!', ask.index, null, 'a permission request with nothing for when it\'s blocked: then the button explains it and offers Linking.openSettings()');
242
+ if (major('react') >= 19) {
243
+ each(/\bforwardRef\s*[<(]/g, m => add('!', m.index, null, 'forwardRef isn\'t needed in React 19: take ref as a prop'));
244
+ each(/<\s*[\w.]+\.Provider\b/g, m => add('!', m.index, null, 'React 19 renders a context directly: <SomeContext value={…}> instead of .Provider'));
245
+ }
246
+ if (expoSdk) each(/(['"])expo-av\1/g, m => add('!', m.index, null, 'expo-av isn\'t maintained any more: use expo-audio and expo-video'));
247
+ if (expoSdk >= 56) each(/(['"])@expo\/vector-icons[^'"\n]*\1/g, m => add('!', m.index, null, '@expo/vector-icons is deprecated from SDK 56: use @react-native-vector-icons/*'));
248
+ if (ts) {
249
+ each(/@ts-ignore\b/g, m => add('!', m.index, null, '@ts-ignore hides a type error: fix the type instead'), text);
250
+ // in a type, not in JSX text ("Note: any change")
251
+ each(/\bas\s+any\b(?!\s+[a-z])|:\s*any(?=\s*[;,)=>\]|&}[\n])|<any>/g, m => add('!', m.index, null, 'any turns off type checking here: give it a type'));
252
+ }
253
+ return out;
254
+ }
255
+
256
+ // the 1-based line of index i
257
+ function lineAt(code, i) {
258
+ let n = 1;
259
+ for (let j = code.indexOf('\n'); j !== -1 && j < i; j = code.indexOf('\n', j + 1)) n++;
260
+ return n;
261
+ }
262
+
263
+ // ---------- Maestro flows ----------
264
+ // a flow without its comments (each comment character a space, so positions stay): # outside quotes starts one
265
+ function stripYamlComments(text) {
266
+ return text.split('\n').map(l => {
267
+ let quote = null;
268
+ for (let i = 0; i < l.length; i++) {
269
+ const c = l[i];
270
+ if (quote) { if (c === quote) quote = null; } else if (c === '"' || c === "'") quote = c;
271
+ else if (c === '#' && (i === 0 || /\s/.test(l[i - 1]))) return l.slice(0, i) + ' '.repeat(l.length - i);
272
+ }
273
+ return l;
274
+ }).join('\n');
275
+ }
276
+ const TAPS = /^(tapOn|doubleTapOn|longPressOn)$/;
277
+ const SELECTS = /^(tapOn|doubleTapOn|longPressOn|assertVisible|assertNotVisible|scrollUntilVisible|extendedWaitUntil|copyTextFrom)$/;
278
+ const ASSERTS = /^(assertVisible|assertNotVisible|assertTrue|assertWithAI|assertNoDefectsWithAI)$/;
279
+ // buttons of system dialogs (permission prompts, alerts), which have no testID
280
+ const SYSTEM_BUTTON = /^(allow|allow while using (the )?app|allow once|only this time|while using the app|ok|cancel|continue|don.t allow|not now|deny|close)$/i;
281
+ const unquote = v => { v = v.trim(); return /^'.*'$/.test(v) ? v.slice(1, -1).replace(/''/g, "'") : /^".*"$/.test(v) ? v.slice(1, -1) : v; };
282
+ let noMaestro = false;
283
+ function checkFlow(file, text) {
284
+ const out = [];
285
+ const add = (level, at, message, always) => out.push({ level, at, end: at, message, always });
286
+ const dir = path.dirname(file);
287
+ let offset = 0;
288
+ let cmd = null;
289
+ let optional = false;
290
+ let target = '';
291
+ let asserts = 0;
292
+ const done = () => { if (cmd === 'extendedWaitUntil' && !optional) asserts++; };
293
+ for (const l of stripYamlComments(text).split('\n')) {
294
+ const at = offset;
295
+ offset += l.length + 1;
296
+ const item = /^\s*-\s*([A-Za-z]+)\s*:?\s*(.*)$/.exec(l);
297
+ if (item) { done(); cmd = item[1]; optional = false; if (ASSERTS.test(cmd)) asserts++; }
298
+ if (/^\s*optional\s*:\s*true\b/.test(l)) optional = true;
299
+ const app = /^appId\s*:\s*(.+)$/.exec(l);
300
+ if (app && !/\$\{APP_ID\}/.test(app[1])) add('!', at, `appId ${app[1].trim()}: verify.sh sets APP_ID for the build it checks, which a flavor or scheme changes: use appId: \${APP_ID}`);
301
+ // what this line selects: the command's own value (tapOn: Save), keys of an inline map, or a key below the command
302
+ const sel = [];
303
+ if (item && SELECTS.test(cmd) && item[2].trim() && !/^[{[|>]/.test(item[2].trim())) sel.push(['text', unquote(item[2])]);
304
+ for (const m of (item && /^\{/.test(item[2].trim()) ? item[2] : !item ? l : '').matchAll(/\b(text|id|visible|notVisible)\s*:\s*("[^"]*"|'(?:[^']|'')*'|[^,}\n]+)/g)) {
305
+ if (SELECTS.test(cmd || '') && unquote(m[2])) sel.push([m[1] === 'id' ? 'id' : 'text', unquote(m[2])]);
306
+ }
307
+ for (const [kind, value] of sel) {
308
+ if (TAPS.test(cmd)) target = value;
309
+ if (kind === 'text' && TAPS.test(cmd) && !SYSTEM_BUTTON.test(value) && !value.includes('${')) {
310
+ add('!', at, `${cmd} "${value}" taps by text: on iOS a label and its control both match, and on a real iPhone a hidden one can; tap by testID (id:)`);
311
+ }
312
+ if (kind === 'text' && /['’]/.test(value)) add('!', at, `"${value}" has an apostrophe, which a real iPhone can't search for (maestro-runner): match a testID, or text without it`);
313
+ }
314
+ if (item && cmd === 'inputText' && item[2].trim() && !item[2].includes('${') && /pass(word|code)?\b|\bpin\b|otp|secret/i.test(target)) {
315
+ add('!', at, `a password typed into the flow: use \${MAESTRO_PASSWORD} (or another MAESTRO_ variable) from .maestro/.env.local, which isn't committed`);
316
+ }
317
+ // a subflow or script it runs: there, or the flow fails when it gets to it
318
+ const runs = (item && /^(runFlow|runScript)$/.test(cmd) && !/^[{[|>]/.test(item[2].trim()) && item[2].trim()) || (!item && /^(runFlow|runScript)$/.test(cmd || '') && (/^\s*file\s*:\s*(.+)$/.exec(l) || [])[1]);
319
+ if (runs && !runs.includes('${') && /\.(ya?ml|js)$/.test(unquote(runs)) && !fs.existsSync(path.join(root, dir, unquote(runs)))) {
320
+ add('✗', at, `${cmd} ${unquote(runs)}: no such file next to this flow (${dir}/)`, true);
321
+ }
322
+ }
323
+ done();
324
+ for (const [re, what] of SECRETS) for (const m of text.matchAll(re)) add('✗', m.index, `${what} in a flow: anyone with the repository can read it. Revoke it, and use a MAESTRO_ variable from .maestro/.env.local`);
325
+ // a flow verify.sh runs (not a subflow) that never checks anything passes whatever the app shows
326
+ if (/^\.maestro\/[^/]+$/.test(file) && !asserts) add('!', 0, 'this flow checks nothing: add an assertVisible for what each scenario\'s THEN expects', true);
327
+ // Maestro's own syntax check (seconds, no device): AMK_MAESTRO names another maestro
328
+ const r = noMaestro ? null : spawnSync(process.env.AMK_MAESTRO || 'maestro', ['check-syntax', file], { cwd: root, encoding: 'utf8' });
329
+ if (r && r.error) noMaestro = true;
330
+ else if (r && r.status !== 0) {
331
+ const said = `${r.stdout || ''}\n${r.stderr || ''}`.split('\n').map(s => s.trim()).find(s => s && s !== 'OK') || 'invalid flow';
332
+ const n = Number((/:(\d+):\d+/.exec(said) || [])[1]) || 1;
333
+ add('✗', text.split('\n').slice(0, n - 1).reduce((a, s) => a + s.length + 1, 0), `maestro check-syntax: ${said.replace(/\s+at \/syntax-checker:\d+:\d+/, '')}`, true);
334
+ }
335
+ return out;
336
+ }
337
+
338
+ for (const [file, lines] of changed) {
339
+ let text;
340
+ try { text = fs.readFileSync(path.join(root, file), 'utf8'); } catch { continue; }
341
+ const rows = text.split('\n');
342
+ const starts = [0];
343
+ for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) starts.push(i + 1);
344
+ const line = i => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= i) lo = mid; else hi = mid - 1; } return lo + 1; };
345
+ for (const f of flowFile(file) ? checkFlow(file, text) : check(file, text)) {
346
+ const from = line(f.at);
347
+ const to = line(f.end);
348
+ const touched = lines === 'all' || [...Array(to - from + 1).keys()].some(k => lines.has(from + k));
349
+ const at = f.line || from;
350
+ // on the line, or in a comment on the line above
351
+ const above = /^\s*(\/\/|\/\*|\{\s*\/\*|#)/.test(rows[at - 2] || '') ? at - 1 : 0;
352
+ const okAt = [at, above].find(n => n && /amk-ok\b/.test(rows[n - 1]));
353
+ const ok = okAt && /amk-ok(?:\s+(\d{4}-\d{2}-\d{2}))?\s*:\s*(\S.*?)\s*(\*\/\s*\}?)?\s*$/.exec(rows[okAt - 1]);
354
+ let message = f.message;
355
+ if (ok) {
356
+ const since = okSince(file, okAt, ok[1]);
357
+ // kept: listed when its own lines changed; over two weeks old, asked again whenever its file changes
358
+ if (Date.parse(today) - Date.parse(since) <= 14 * DAY) { if (touched) kept.push(`${file}:${at}: ${ok[2]} (${since})`); continue; }
359
+ message = `kept with amk-ok since ${since}, over two weeks, and its file changed again: ${f.message}. The user's reason then: ${ok[2]}`;
360
+ } else if (!touched && !f.always) continue;
361
+ if (!findings.some(x => x.where === `${file}:${at}` && x.message === message)) findings.push({ ...f, message, where: `${file}:${at}` });
362
+ }
363
+ }
364
+
365
+ // ---------- once for the app: an error boundary somewhere ----------
366
+ let boundary = true;
367
+ if ([...changed.keys()].some(source)) {
368
+ boundary = false;
369
+ const files = [...(git('ls-files') || '').split('\n'), ...changed.keys()].filter(f => f && source(f));
370
+ for (const f of new Set(files)) {
371
+ try {
372
+ if (/componentDidCatch|getDerivedStateFromError|ErrorBoundary|Sentry\s*\.\s*wrap\b/.test(fs.readFileSync(path.join(root, f), 'utf8'))) { boundary = true; break; }
373
+ } catch {}
374
+ }
375
+ }
376
+
377
+ // ---------- each scenario of a spec the branch touched has its steps in the spec's flows ----------
378
+ // specs/<id>/requirements.md lists them ("#### Scenario: <name>"); the flows are .maestro/<id>*.yaml, with a
379
+ // "# Scenario <n>: <name>" comment above each one's steps, as specs/_templates/flow.yaml shows
380
+ const touchedPaths = [...(sha ? (git('diff', '--name-only', '--relative', sha) || '').split('\n') : []),
381
+ ...(git('ls-files', '--others', '--exclude-standard') || '').split('\n')].filter(Boolean);
382
+ const norm = s => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
383
+ const specIds = fs.existsSync(path.join(root, 'specs')) ? fs.readdirSync(path.join(root, 'specs'), { withFileTypes: true })
384
+ .filter(e => e.isDirectory() && !/^(_|current$)/.test(e.name)).map(e => e.name) : [];
385
+ const flowsDir = fs.existsSync(path.join(root, '.maestro')) ? fs.readdirSync(path.join(root, '.maestro')).filter(f => /\.ya?ml$/.test(f)) : [];
386
+ for (const id of specIds) {
387
+ const req = `specs/${id}/requirements.md`;
388
+ let reqText;
389
+ try { reqText = fs.readFileSync(path.join(root, req), 'utf8'); } catch { continue; }
390
+ const flows = flowsDir.filter(f => f.toLowerCase().startsWith(id.toLowerCase())).map(f => `.maestro/${f}`);
391
+ if (!flows.length || !touchedPaths.some(p => p.startsWith(`specs/${id}/`) || flows.includes(p))) continue;
392
+ const blocks = flows.flatMap(f => {
393
+ const text = fs.readFileSync(path.join(root, f), 'utf8');
394
+ const code = stripYamlComments(text).split('\n');
395
+ const out = [];
396
+ text.split('\n').forEach((l, i) => {
397
+ const m = /^\s*#\s*Scenario\b\s*(\d+)?\s*[:.)-]?\s*(.*)$/i.exec(l);
398
+ if (m) out.push({ n: Number(m[1]) || 0, name: norm(m[2]), at: i });
399
+ else if (out.length) out[out.length - 1].code = `${out[out.length - 1].code || ''}${code[i]}\n`;
400
+ });
401
+ return out.map(b => ({ ...b, flow: f }));
402
+ });
403
+ [...reqText.matchAll(/^#### Scenario:\s*(.*)$/gm)].forEach((m, i) => {
404
+ const name = norm(m[1]);
405
+ const where = `${req}:${reqText.slice(0, m.index).split('\n').length}`;
406
+ const b = blocks.find(x => x.n === i + 1) || blocks.find(x => name && x.name && (x.name.includes(name) || name.includes(x.name)));
407
+ const say = message => findings.push({ level: '!', message, where });
408
+ if (!b) say(`scenario ${i + 1} "${m[1].trim()}" has no block in ${flows.join(', ')}: add "# Scenario ${i + 1}: ${m[1].trim()}" above its steps, with an assertion for its THEN and a screenshot`);
409
+ else {
410
+ if (!/-\s*(assertVisible|assertNotVisible|assertTrue|assertWithAI|extendedWaitUntil)\b/.test(b.code || '')) say(`scenario ${i + 1} "${m[1].trim()}" has no assertion in ${b.flow}: check what its THEN expects`);
411
+ if (!/-\s*takeScreenshot\b/.test(b.code || '')) say(`scenario ${i + 1} "${m[1].trim()}" has no screenshot in ${b.flow}, so it has no evidence`);
412
+ }
413
+ });
414
+ }
415
+
416
+ // ---------- report ----------
417
+ // by file, then line
418
+ const order = w => { const [, file, n] = /^(.*):(\d+)$/.exec(w); return [file, Number(n)]; };
419
+ findings.sort((a, b) => { const [fa, na] = order(a.where); const [fb, nb] = order(b.where); return fa === fb ? na - nb : fa < fb ? -1 : 1; });
420
+ const problems = findings.filter(f => f.level === '✗');
421
+ const warnings = findings.filter(f => f.level === '!');
422
+ const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
423
+ if (!changed.size && !findings.length) console.log(`rn-check: no changed code or flows since ${since}`);
424
+ else if (!findings.length) console.log(`rn-check: nothing to report in the lines changed since ${since}`);
425
+ else console.log(`rn-check: ${plural(problems.length, 'problem')}, ${plural(warnings.length, 'warning')} in the lines changed since ${since}`);
426
+ for (const f of [...problems, ...warnings]) console.log(` ${f.level} ${f.where} ${f.message}`);
427
+ if (noMaestro && [...changed.keys()].some(flowFile)) console.log(' flows not syntax-checked: Maestro isn\'t installed here');
428
+ if (!boundary) console.log(` ! the app has no error boundary: a render error shows a blank screen or closes the app. Wrap the app in one`);
429
+ if (kept.length) console.log(` kept with amk-ok: ${[...new Set(kept)].join('; ')}`);
430
+ if (problems.length) {
431
+ console.log(` Each ✗ fails verify.sh quick. Ask the user, for each one: fix it, or keep the line with \`// amk-ok ${today}: <their reason>\` on it (# in a flow).`);
432
+ console.log(' Never add an amk-ok without the user\'s reason. One kept over two weeks ago comes back when its file changes: ask again, and to keep it, write today\'s date.');
433
+ }
434
+ if (warnings.length || !boundary) console.log(' Fix each ! in the code this task changed, or tell the user why it stays.');
435
+ process.exit(problems.length ? 1 : 0);