agentic-mobile-kit 0.7.16 → 0.7.17

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
@@ -173,7 +173,7 @@ function createApp(cwd, kind, { run = tool, log = console.log, pods = process.pl
173
173
  // the tools commit only in a repository they create; init needs everything committed
174
174
  commit(own ? 'Initial commit' : 'Add the files that were already in the folder');
175
175
  newAppDefaults(cwd, kind, { run, log });
176
- commit('Support tablets and landscape; stricter TypeScript with @/ imports');
176
+ commit('Support tablets and landscape; stricter TypeScript with @/ imports; an error boundary');
177
177
  // the first pod install changes the Xcode project and Info.plist: a commit of its own keeps that out of the first feature
178
178
  if (kind === 'bare' && pods) {
179
179
  log('Installing the iOS pods\n');
@@ -186,8 +186,9 @@ function createApp(cwd, kind, { run = tool, log = console.log, pods = process.pl
186
186
  }
187
187
 
188
188
  // What a new app starts with beyond the tool's template: iPad and every orientation (the React Native template locks
189
- // iPhones to portrait; Expo's locks everything to portrait and leaves iPad out), and stricter TypeScript with "@/"
190
- // imports for src/. Expo's template has the "@/" paths already, and Metro reads them; bare apps need a Babel plugin.
189
+ // iPhones to portrait; Expo's locks everything to portrait and leaves iPad out), stricter TypeScript with "@/"
190
+ // imports for src/, and an error boundary around the app (neither template has one, so a render error leaves a blank
191
+ // screen). Expo's template has the "@/" paths already, and Metro reads them; bare apps need a Babel plugin.
191
192
  const STRICTER = { noUncheckedIndexedAccess: true, noImplicitOverride: true, noImplicitReturns: true, noFallthroughCasesInSwitch: true };
192
193
  const ALIAS_PLUGIN = 'babel-plugin-module-resolver@5';
193
194
  const ADD_DEV = { npm: ['npm', 'install', '--save-dev'], Yarn: ['yarn', 'add', '--dev'], pnpm: ['pnpm', 'add', '--save-dev'], Bun: ['bun', 'add', '--dev'] };
@@ -197,6 +198,7 @@ function newAppDefaults(cwd, kind, { run, log }) {
197
198
  const next = text === null ? null : change(text);
198
199
  if (next !== null && next !== text) fs.writeFileSync(path.join(cwd, rel), next);
199
200
  };
201
+ errorBoundary(cwd, kind, edit, log);
200
202
  const json = text => { try { return JSON.parse(text); } catch { return null; } };
201
203
  // short lists stay on one line, as the templates write them
202
204
  const format = j => `${JSON.stringify(j, null, 2).replace(/\[\n\s*([^[\]{}]*?)\n\s*\]/g, (m, items) => `[${items.split(/,\n\s*/).join(', ')}]`)}\n`;
@@ -245,6 +247,45 @@ function newAppDefaults(cwd, kind, { run, log }) {
245
247
  edit('tsconfig.json', stricter(alias));
246
248
  }
247
249
 
250
+ // the error boundary: the component next to the app's others, used by the root layout (Expo Router shows an
251
+ // ErrorBoundary that a route exports) or around the root component index.js registers. Relative imports, which work
252
+ // whether or not the "@/" alias is set up
253
+ const NEW_APP_FILES = path.join(TEMPLATE, '..', 'new-app');
254
+ function errorBoundary(cwd, kind, edit, log) {
255
+ const place = (rel, source) => {
256
+ if (fs.existsSync(path.join(cwd, rel))) return false;
257
+ fs.mkdirSync(path.dirname(path.join(cwd, rel)), { recursive: true });
258
+ fs.copyFileSync(path.join(NEW_APP_FILES, source), path.join(cwd, rel));
259
+ return true;
260
+ };
261
+ const from = (file, target) => { const r = path.relative(path.dirname(file), target).split(path.sep).join('/'); return r.startsWith('.') ? r : `./${r}`; };
262
+ if (kind === 'expo') {
263
+ const layout = ['src/app/_layout.tsx', 'app/_layout.tsx'].find(f => fs.existsSync(path.join(cwd, f)));
264
+ if (!layout) { log('! No app/_layout.tsx or src/app/_layout.tsx, so no error boundary was added: export an ErrorBoundary from the root layout'); return; }
265
+ if (/\bErrorBoundary\b/.test(readIf(path.join(cwd, layout)))) return;
266
+ const component = `${layout.startsWith('src/') || fs.existsSync(path.join(cwd, 'src')) ? 'src/' : ''}components/error-boundary.tsx`;
267
+ if (!place(component, 'error-boundary.tsx')) { log(`! ${component} is already there, so no error boundary was added`); return; }
268
+ const line = `export { ErrorBoundary } from '${from(layout, component.replace(/\.tsx$/, ''))}';`;
269
+ // after the last import, which may span lines
270
+ edit(layout, text => {
271
+ const imports = [...text.matchAll(/^import\b[^;]*?(?:from\s*)?['"][^'"]+['"];?[ \t]*$/gm)];
272
+ const at = imports.length ? imports[imports.length - 1].index + imports[imports.length - 1][0].length : 0;
273
+ return at ? `${text.slice(0, at)}\n${line}${text.slice(at)}` : `${line}\n${text}`;
274
+ });
275
+ return;
276
+ }
277
+ const index = readIf(path.join(cwd, 'index.js'));
278
+ const register = /AppRegistry\.registerComponent\(\s*appName\s*,\s*\(\)\s*=>\s*App\s*\)/;
279
+ if (!index || !register.test(index) || !/^import App from '\.\/App';$/m.test(index)) {
280
+ log('! index.js doesn\'t register App the usual way, so no error boundary was added: wrap the app in one');
281
+ return;
282
+ }
283
+ if (!place('src/components/ErrorBoundary.tsx', 'ErrorBoundary.tsx')) { log('! src/components/ErrorBoundary.tsx is already there, so no error boundary was added'); return; }
284
+ edit('index.js', text => text
285
+ .replace(/^import App from '\.\/App';$/m, "import App from './App';\nimport { withErrorBoundary } from './src/components/ErrorBoundary';")
286
+ .replace(register, 'AppRegistry.registerComponent(appName, () => withErrorBoundary(App))'));
287
+ }
288
+
248
289
  // Expo apps whose ios/ and android/ come from `expo prebuild` (Continuous Native Generation, not in git) get the
249
290
  // Expo overlay. Expo apps that keep the native folders in git are set up like bare apps.
250
291
  function detectStack(cwd, deps) {
@@ -252,11 +293,14 @@ function detectStack(cwd, deps) {
252
293
  }
253
294
 
254
295
  // a stack's files, rel -> source: the template, and for Expo the overlay next to it, which replaces or adds files
296
+ // deps, when given, are the app's: an app on Expo Router doesn't get the react-navigation skill, as from SDK 56 it imports
297
+ // navigation from expo-router, which its own skill teaches (one on React Navigation itself still needs it)
255
298
  const EXPO_LEAVES_OUT = ['docs/amk/react-native.md', '.agents/skills/upgrading-react-native/'];
256
- function stackFiles(template, stack) {
299
+ function stackFiles(template, stack, deps = {}) {
257
300
  const files = new Map(templateFiles(template).map(rel => [rel, path.join(template, rel)]));
258
301
  if (stack !== 'expo') return files;
259
- for (const rel of files.keys()) if (EXPO_LEAVES_OUT.some(f => (f.endsWith('/') ? rel.startsWith(f) : rel === f))) files.delete(rel);
302
+ const out = [...EXPO_LEAVES_OUT, ...(deps['expo-router'] ? ['.agents/skills/react-navigation/'] : [])];
303
+ for (const rel of files.keys()) if (out.some(f => (f.endsWith('/') ? rel.startsWith(f) : rel === f))) files.delete(rel);
260
304
  const overlay = path.join(template, '..', 'expo');
261
305
  if (fs.existsSync(overlay)) for (const rel of templateFiles(overlay)) files.set(rel, path.join(overlay, rel));
262
306
  return files;
@@ -747,7 +791,7 @@ function init(cwd, opts = {}) {
747
791
  const pm = detectPm(cwd, opts.pm);
748
792
  const tools = opts.tools || TESTED;
749
793
  for (const t of tools) if (!TOOLS[t]) throw new InitError(`Unknown tool "${t}". Choose from: ${Object.keys(TOOLS).join(', ')}.`);
750
- const files = stackFiles(opts.template || TEMPLATE, stack);
794
+ const files = stackFiles(opts.template || TEMPLATE, stack, deps);
751
795
  const ci = chooseCi(cwd, readIf(path.join(cwd, 'AGENTS.md')), opts.ci);
752
796
  const values = projectValues(cwd, pkg, deps, pm, ci, stack);
753
797
  const targets = tools.flatMap(t => TOOLS[t]);
@@ -791,9 +835,10 @@ function sync(cwd, opts = {}) {
791
835
  const tools = installedTools(cwd);
792
836
  const targets = tools.flatMap(t => TOOLS[t]);
793
837
  const report = { moved: [], updated: [], added: [], merged: [], conflicts: [], removed: [], kept: [] };
794
- const newFiles = stackFiles(opts.template || TEMPLATE, stack);
838
+ const newFiles = stackFiles(opts.template || TEMPLATE, stack, deps);
795
839
  // an install from before 0.7.0: the kit's files move to the new folders first, so the team's edits come along.
796
840
  // Other files in the old folders may be the app's own, so they stay where they are.
841
+ // all the old version installed, whatever the app uses now: what this one leaves out goes
797
842
  const oldKit = stackFiles(oldDir, stack);
798
843
  const moved = [...oldKit.keys()].filter(rel => renamedPath(rel) !== rel
799
844
  && fs.existsSync(path.join(cwd, rel)) && !fs.existsSync(path.join(cwd, renamedPath(rel))));
@@ -844,6 +889,7 @@ function sync(cwd, opts = {}) {
844
889
  if (current === null) continue;
845
890
  if (current === kitText(src, rel, values, targets)) { fs.unlinkSync(path.join(cwd, rel)); report.removed.push(rel); } else report.kept.push(`${rel} (the kit dropped it; you changed it)`);
846
891
  }
892
+ removeEmptyFolders(cwd, report.removed);
847
893
 
848
894
  const { done, generated, generateError } = finish(cwd, { pkg, deps, tools, files: newFiles, stack, skipGenerate: opts.skipGenerate });
849
895
  report.added.push(...done.created);
@@ -870,6 +916,14 @@ function generatedFiles(cwd) {
870
916
  return out;
871
917
  }
872
918
 
919
+ // the folders that removed files (paths from cwd, maybe followed by " (why)") left empty; rmdir refuses non-empty ones
920
+ function removeEmptyFolders(cwd, removed) {
921
+ const dirs = [...new Set(removed.map(r => path.dirname(r.split(' (')[0])))].sort((a, b) => b.length - a.length);
922
+ for (let d of dirs) {
923
+ for (; d && d !== '.'; d = path.dirname(d)) { try { fs.rmdirSync(path.join(cwd, d)); } catch { break; } }
924
+ }
925
+ }
926
+
873
927
  function uninstall(cwd, opts = {}) {
874
928
  const { pkg, deps, stack: detected } = checkProject(cwd);
875
929
  const agents = readIf(path.join(cwd, 'AGENTS.md'));
@@ -910,11 +964,7 @@ function uninstall(cwd, opts = {}) {
910
964
  }
911
965
  }
912
966
  for (const h of OTHER_HOOKS) if ((readIf(path.join(cwd, '.githooks', h)) || '').includes(FORWARD)) remove(`.githooks/${h}`);
913
- // folders left empty (rmdir refuses non-empty ones)
914
- const dirs = [...new Set(report.removed.map(r => path.dirname(r.split(' (')[0])))].sort((a, b) => b.length - a.length);
915
- for (let d of dirs) {
916
- for (; d && d !== '.'; d = path.dirname(d)) { try { fs.rmdirSync(path.join(cwd, d)); } catch { break; } }
917
- }
967
+ removeEmptyFolders(cwd, report.removed);
918
968
 
919
969
  // git hooks: the kit's postinstall, or its lines in the project's hook manager (which would fail once .githooks is gone)
920
970
  const scripts = pkg.scripts || {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-mobile-kit",
3
- "version": "0.7.16",
3
+ "version": "0.7.17",
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",
@@ -6,6 +6,6 @@
6
6
  | expo-upgrade | same | same | MIT | Image files left out |
7
7
  | expo-module | same | same | MIT | Image files left out |
8
8
  | react-native-best-practices | https://github.com/callstackincubator/agent-skills | 61e6e7dfdf3a8ee862254c200d751fcb1fb863dc | MIT (`LICENSE-callstack`) | Image files left out |
9
- | react-navigation | same | same | MIT | Image files left out |
9
+ | react-navigation | same | same | MIT | Image files left out; not in apps on Expo Router |
10
10
 
11
11
  Updated with `scripts/vendor-skills.sh` in the agentic-mobile-kit repo.
@@ -22,8 +22,9 @@ This project may also use other AI workflow frameworks (for example Superpowers,
22
22
  | Check dependency versions and the app config | `npx expo install --check`, `npx expo-doctor` |
23
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 devices at the same time | `sh scripts/amk/verify.sh plan --spec <id>` says how many this machine's memory fits, and prints the commands: one per device (in rounds when they don't all fit; a device's flows in parts when there's room), each for an `m-device-checker` subagent |
25
+ | React Native mistakes in this branch's changed lines (`verify.sh quick` runs it) | `node scripts/amk/rn-check.js` |
25
26
  | 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
- | Check a release before tagging it (versions, permission texts, debug leftovers) | `node scripts/amk/release-check.js` |
27
+ | Check a release before tagging it (versions, permission texts, store review rules, debug leftovers) | `node scripts/amk/release-check.js` |
27
28
  | Signed release builds (a person runs them: they use the signing keys) | `sh scripts/amk/release-build.sh android`, `sh scripts/amk/release-build.sh ios` |
28
29
 
29
30
  ## Definition of done
@@ -44,11 +45,12 @@ Never say a check passed unless you ran it in this session.
44
45
  - 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
46
  - Never read, print or commit `.env` files, keystores, signing files or the files `.amk-secrets` lists. Secrets don't belong in this repo.
46
47
  - Never use `git commit --no-verify`, `git push --force`, `git reset --hard` or `rm -rf`.
48
+ - When `rn-check` (in `verify.sh quick`) reports a problem (✗), show it to the user and let them choose, for each one: fix it, or keep the line with `// amk-ok <today's date>: <their reason>`. Never add an `amk-ok` on your own. One kept over two weeks ago comes back when its file changes again: ask again. Fix the warnings (!) in code the task changed, or tell the user why one stays.
47
49
  - After 2 failed attempts at the same fix, stop and report what you found.
48
50
  - Chat is not memory: write decisions into the spec or `docs/amk/decisions.md` straight away.
49
51
  - Follow `docs/amk/expo.md`. Before fixing a build error, check `docs/amk/known-issues.md`.
50
52
 
51
53
  ## Skills
52
54
 
53
- `expo-router`, `expo-upgrade`, `expo-module` (from Expo), `react-native-best-practices`, `react-navigation` (from Callstack), in `.agents/skills/`.
55
+ `expo-router`, `expo-upgrade`, `expo-module` (from Expo), `react-native-best-practices`, and in an app on React Navigation without Expo Router, `react-navigation` (from Callstack), in `.agents/skills/`.
54
56
  <!-- KIT:END agentic-mobile-kit -->
@@ -1,6 +1,6 @@
1
1
  # Expo rules
2
2
 
3
- Rules for things AI agents commonly get wrong in Expo apps. Each one comes from a documented platform change, or from a bug agents keep making on screens.
3
+ Rules for things AI agents commonly get wrong in Expo apps. Each one comes from a documented platform change, or from a bug agents keep making on screens. `node scripts/amk/rn-check.js`, which `verify.sh quick` runs, checks the lines a branch changes for some of them.
4
4
 
5
5
  ## Expo changes with every SDK
6
6
 
@@ -14,7 +14,8 @@ Rules for things AI agents commonly get wrong in Expo apps. Each one comes from
14
14
  - `ios/` and `android/` are generated by `npx expo prebuild` and aren't in git. Never edit them: the next prebuild overwrites the change.
15
15
  - Native settings (permissions and their texts, bundle ID, entitlements) go in `app.json` or `app.config.*`. Libraries with native setup bring a config plugin; add it to `plugins`.
16
16
  - Native code of the app's own goes in an Expo module (`expo-module` skill), not into the generated folders.
17
- - A library with native code needs a new native build: Expo Go doesn't include it. `sh scripts/amk/verify.sh` makes release builds with the current native code.
17
+ - Run the app in a development build, not Expo Go: Expo Go can't load native code the app adds, and the store version runs only one SDK. `sh scripts/amk/verify.sh` makes release builds with the current native code.
18
+ - Android release builds shrink the code with R8 (on by default from SDK 58). A crash only in release builds usually means a missing keep rule: add the rule; don't turn R8 off.
18
19
 
19
20
  ## Architecture
20
21
 
@@ -29,7 +30,7 @@ Rules for things AI agents commonly get wrong in Expo apps. Each one comes from
29
30
  - With the keyboard open, the field being typed in and the button that submits the form stay visible and tappable, on both platforms.
30
31
  - Lists that grow with the user's data scroll (`FlatList`, or the list component the app already uses), and so does any screen taller than a small phone.
31
32
  - At the largest system text size, text wraps instead of being cut off: no fixed heights on views that hold text. Don't turn off font scaling (`allowFontScaling={false}`) to make a layout fit.
32
- - Messages that appear after an action, such as a form error, are read out by screen readers: announce them with `AccessibilityInfo.announceForAccessibility`.
33
+ - Messages that appear after an action, such as a form error, are read out by screen readers. On Android, show the message in a view with `accessibilityLiveRegion="polite"`: Android 16 deprecated announcements. On iOS, announce it with `AccessibilityInfo.announceForAccessibility`.
33
34
  - Check every UI change on both iOS and Android; behavior differs (keyboard, insets, fonts, permissions).
34
35
  - Give every interactive element a `testID` (kebab-case, for example `dark-mode-switch`). End-to-end tools tap by `testID`. On iOS, React Native exposes a label and its control as duplicate accessibility elements, so tapping by text can hit the label: nothing happens, yet the tool reports success.
35
36
  - Give every interactive element an `accessibilityLabel` that says what it does and an `accessibilityRole` (`button`, `link`, `switch`, …), so screen readers can use it. Icon-only buttons need it most; screen readers don't read `testID`.
@@ -43,9 +44,64 @@ Rules for things AI agents commonly get wrong in Expo apps. Each one comes from
43
44
  - Lay out by window width: under 600 points (dp on Android), the phone layout; from 600, the tablet layout, with more columns, and a list beside its detail where that helps. Text-heavy content and forms keep a readable width (about 600 to 700 points) instead of stretching edge to edge.
44
45
  - Sizes: when the app already has a way to size things (a scaling helper, or sizes in its theme), use it everywhere and don't mix in another. A new app takes sizes from its theme: spacing and a few text sizes step up from 600 points, and text follows the system font size. Judge the tablet and landscape screenshots like the phone's: each should look made for that screen, not stretched or tiny.
45
46
  - Landscape leaves little height: screens scroll, the keyboard covers more, and the safe-area insets include the left and right edges (the notch or Dynamic Island side).
46
- - Apps targeting Android 16 (API 36) can't lock the orientation or size on tablets and foldables (600 dp wide and up): the system ignores the lock there. So on Android tablets every screen has to work turned, whatever the app's settings say.
47
+ - Android ignores orientation and size locks on tablets and foldables (600 dp wide and up) for apps targeting Android 16 (API 36), and from Android 17 (API 37) apps can't opt out. Apple deprecated `UIRequiresFullScreen` with iPadOS 26, so iPad windows resize too, and on iOS 27 `ScreenOrientation.lockAsync` may do nothing. Every screen has to work at any window size and turned, whatever the app's settings say.
47
48
  - Don't lock the orientation in code to avoid layout work. Which orientations the app supports is a product decision, set in `app.json`: `orientation` (`default` turns, `portrait` or `landscape` locks) and `ios.supportsTablet` for the iPad app.
48
49
 
50
+ ## Current Expo, React Native and React
51
+
52
+ These changed after most AI training data was written: check them instead of writing from memory.
53
+
54
+ - Navigation (SDK 56 and later): import from Expo Router's own entry points, such as `expo-router/react-navigation`, never from `@react-navigation/*`, which no longer works alongside it (`expo-router` skill; the `expo-upgrade` skill's codemod moves old imports).
55
+ - `expo-av` isn't maintained any more: use `expo-audio` and `expo-video`. `@expo/vector-icons` is deprecated from SDK 56: use `@react-native-vector-icons/*`. In `expo-file-system`, `File` and `Directory`'s `copy` and `move` (SDK 56) and `File.write` (SDK 58) are async; the `…Sync` versions aren't.
56
+ - iOS: from SDK 58, prebuild generates `SceneDelegate.swift`, as apps built with Xcode 27 don't launch without the UIScene life cycle. Config plugins that change the app delegate's window or URL handling have to change the scene delegate instead.
57
+ - Removed from React Native: `InteractionManager` (0.87; use `requestIdleCallback`), the `StatusBar` props `backgroundColor` and `translucent` (0.87), `Modal`'s `animated` (0.87; `animationType`), a boolean `keyboardShouldPersistTaps` (0.87; `"handled"`) and `StyleSheet.absoluteFillObject` (0.85; `StyleSheet.absoluteFill`).
58
+ - Deprecated, so not in new code: `ImageBackground` (a `View` with an absolutely positioned image), `InputAccessoryView` (`KeyboardStickyView` from `react-native-keyboard-controller`) and `AccessibilityInfo.setAccessibilityFocus` (`sendAccessibilityEvent`).
59
+ - Import from `react-native` itself. `react-native/Libraries/…` is private, and a type error from React Native 0.87; don't add the `react-native-legacy-deep-imports` opt-out to hide it.
60
+ - React 19: pass `ref` as a prop instead of `forwardRef`, render `<SomeContext value={…}>` instead of `<SomeContext.Provider>`, and use `useEffectEvent` (19.2) instead of turning off `react-hooks/exhaustive-deps`.
61
+ - With the React Compiler on (`experiments.reactCompiler` in `app.json`), it memoizes: don't add `memo`, `useMemo` or `useCallback` to new code, and don't remove the ones there as a side task.
62
+ - Android: Google Play takes only apps targeting Android 16 (API 36) or higher (from 31 August 2026). Don't lower the target SDK to get out of edge to edge, back handling or orientation changes.
63
+
64
+ ## Errors, storage and effects
65
+
66
+ - Wrap the app in an error boundary, so a render error shows a screen to recover from instead of a blank or closed app: export an `ErrorBoundary` from the root layout (Expo Router), or use the crash reporter's.
67
+ - Every failure reaches the user or the crash reporter: no empty `catch`, and an action started from a button catches its error and shows it, with a way to retry, so a spinner never stays up.
68
+ - Tokens, passwords and keys go in `expo-secure-store`, never in AsyncStorage or other plain storage. Anything in the JavaScript bundle, `EXPO_PUBLIC_` variables included, can be read by anyone who has the app: no secret keys there.
69
+ - Session replay and analytics mask what users type, and logs leave out tokens and personal data.
70
+ - Effects clean up what they start: timers (`clearTimeout`, `clearInterval`), listeners and subscriptions (return their `remove`), and async work that can finish after the screen closes (an `AbortController`, or a flag the cleanup sets).
71
+ - List keys come from the item's ID, not its index: index keys mix up rows when items are added, removed or reordered.
72
+ - Images go in asset files, never in code as base64 strings: they bloat the bundle, and all of it loads with the JavaScript.
73
+ - Component tests use React Native Testing Library (`@testing-library/react-native`) and find elements as users and screen readers do, by role, label or text (`getByRole('button', { name: 'Save' })`), rather than relying on snapshots.
74
+
75
+ ## Platform guidelines and accessibility
76
+
77
+ From Apple's Human Interface Guidelines, Android's design and app quality guidelines, and WCAG 2.2.
78
+
79
+ - Touch targets: every button, link and control is at least 44×44 points on iOS and 48×48 dp on Android (`minWidth`/`minHeight: 48` covers both): pad a small icon instead of sizing the button to it. `hitSlop` doesn't reach past the parent's bounds, so use it only where the layout can't grow.
80
+ - Text: no `fontSize` under 11, and don't cap scaling below 2× (`maxFontSizeMultiplier`, or `Text.defaultProps`).
81
+ - Contrast, in both light and dark: text 4.5:1 against its background (3:1 from 18 points, or 14 bold), and input borders, focus rings and icons that carry meaning 3:1. Colors come from the theme, whose pairs are checked once; a grey like `#999` on white is only 2.8:1.
82
+ - Screen readers: controls show their state in `accessibilityState` (`checked`, `selected`, `expanded`, `disabled`), and screen and section titles have `accessibilityRole="header"`. A label names the action ("Delete photo"), without the role ("button") the reader already says. Put `accessible` on a row that reads as one item, never on one that holds its own buttons. Meaningful images get a label; decorative ones need nothing.
83
+ - Every swipe, drag or long-press action also has a visible button or menu item, and is in `accessibilityActions`. Color is never the only signal: an error shows text, and a state adds an icon or a word.
84
+ - Back: keep swipe back on iOS and the system back on Android. To ask before leaving unsaved changes, use `usePreventRemove` (from `expo-router/react-navigation`), not `gestureEnabled: false`. A `hardwareBackPress` listener returns `true` only while it closes something on screen; apps don't quit themselves (`BackHandler.exitApp`). Every `Modal` has `onRequestClose`, which Android's back button calls; forms open as sheets (a route with `presentation: 'formSheet'`, or `presentationStyle="pageSheet"`).
85
+ - Permissions: ask when the user starts the feature that needs it, never at launch or when a screen opens; first say in the app why. When it's denied, say what's unavailable and keep the rest working. When the system won't ask again (`canAskAgain` is false), the feature's button explains that and offers `Linking.openSettings()`. Ask for notifications after an action they serve, not on launch; on Android 13 and later, `expo-notifications` shows the prompt only once a notification channel exists, so create it first.
86
+ - Use the native controls (`@react-native-community/datetimepicker`, `Alert.alert` with verb buttons and `style: 'destructive'` and `'cancel'`, `Switch`); a custom one gets the same role, state and size.
87
+ - Dark mode: `userInterfaceStyle: "automatic"` in `app.json` (Android also needs `expo-system-ui`), and colors from the theme's light and dark values (`useColorScheme()`), not hex values in components; don't lock the app to light.
88
+ - Data screens have loading, empty (why, and what to do next), error (what failed, with Retry) and content states. A message the user has to read doesn't vanish on a timer, and screen readers announce it.
89
+ - Reduce Motion: with it on, nothing loops or moves for decoration. Don't pass `ReduceMotion.Never` to Reanimated for decoration; with `Animated` or Lottie, read `AccessibilityInfo.isReduceMotionEnabled()` and the `reduceMotionChanged` event, and fade or stop instead.
90
+ - iOS 26: use native headers and tab bars (Expo Router's `Stack` and native tabs), which iOS draws in its current style; don't draw imitation glass behind content, or opt out with `UIDesignRequiresCompatibility` (builds with the iOS 27 SDK ignore it). Nothing the user needs sits under a floating tab bar, button or footer: scroll content gets bottom padding for it.
91
+ - Haptics only for success, error or a selection, never as the only feedback, with `expo-haptics`; not `Vibration.vibrate`.
92
+
93
+ ## Store review
94
+
95
+ What App Store review and Google Play reject. `node scripts/amk/release-check.js` checks the app config for some of it.
96
+
97
+ - Apps where people can create an account let them start deleting it in the app: a full deletion, not deactivation; a direct link to a web page that finishes it is fine (Apple 5.1.1(v)). Google Play also needs that web link in the Data safety form.
98
+ - A third-party or social login (Google, Facebook) as the main sign-in also needs an equivalent private one, usually Sign in with Apple (`expo-apple-authentication`, 4.8); an app that signs in only with the company's own accounts doesn't.
99
+ - Digital content and subscriptions are sold with in-app purchase (3.1.1); physical goods and services aren't. Links to buy elsewhere follow the storefront's current rules.
100
+ - Permission texts (in each library's plugin options, or `ios.infoPlist`) say what the app does with the data and why, for each use; ask only for what the app uses.
101
+ - The privacy manifest (`ios.privacyManifests` in `app.json`) and App Store Connect's privacy details list the data the app and its SDKs collect (analytics, crash reporting, session replay). Tracking needs the App Tracking Transparency prompt first (`expo-tracking-transparency`).
102
+ - Google Play restricts these permissions to apps whose core feature needs them, with a declaration in Play Console: photos and videos (`READ_MEDIA_IMAGES`, `READ_MEDIA_VIDEO`: others use the Android photo picker), `QUERY_ALL_PACKAGES`, `MANAGE_EXTERNAL_STORAGE`, SMS and call log, `USE_EXACT_ALARM`, and background location (also a video and an in-app disclosure first). A library can add one: list it in `android.blockedPermissions` when the app doesn't need it.
103
+ - Android foreground services declare their type and its `FOREGROUND_SERVICE_<TYPE>` permission (the library's config plugin usually does), and each type is declared in Play Console.
104
+
49
105
  ## TypeScript
50
106
 
51
107
  - Keep the checks `tsconfig.json` has. Don't loosen them, or get past one with `any`, `@ts-ignore` or a non-null `!`.
@@ -0,0 +1,61 @@
1
+ // The app's error boundary. index.js registers withErrorBoundary(App), so a render error anywhere in the app shows this
2
+ // screen, with a way to try again, instead of a blank screen or a closed app. Once the app has a crash reporter, report
3
+ // the error in componentDidCatch (or use the reporter's own boundary).
4
+ import React from 'react';
5
+ import { Pressable, StyleSheet, Text, useColorScheme, View } from 'react-native';
6
+
7
+ type Props = { children: React.ReactNode };
8
+ type State = { error: Error | null };
9
+
10
+ export class ErrorBoundary extends React.Component<Props, State> {
11
+ override state: State = { error: null };
12
+
13
+ static getDerivedStateFromError(error: Error): State {
14
+ return { error };
15
+ }
16
+
17
+ override componentDidCatch(error: Error, info: React.ErrorInfo) {
18
+ console.error(error, info.componentStack);
19
+ }
20
+
21
+ override render() {
22
+ if (!this.state.error) return this.props.children;
23
+ return <Fallback error={this.state.error} retry={() => this.setState({ error: null })} />;
24
+ }
25
+ }
26
+
27
+ function Fallback({ error, retry }: { error: Error; retry: () => void }) {
28
+ const dark = useColorScheme() === 'dark';
29
+ return (
30
+ <View style={[styles.screen, dark && styles.screenDark]} accessibilityLiveRegion="assertive">
31
+ <Text style={[styles.title, dark && styles.textDark]} accessibilityRole="header">
32
+ Something went wrong
33
+ </Text>
34
+ {__DEV__ ? <Text style={[styles.detail, dark && styles.textDark]}>{error.message}</Text> : null}
35
+ <Pressable onPress={retry} style={styles.button} accessibilityRole="button" accessibilityLabel="Try again" testID="error-try-again">
36
+ <Text style={styles.buttonText}>Try again</Text>
37
+ </Pressable>
38
+ </View>
39
+ );
40
+ }
41
+
42
+ // the app's root component inside the boundary
43
+ export function withErrorBoundary<P extends object>(Component: React.ComponentType<P>) {
44
+ return function WithErrorBoundary(props: P) {
45
+ return (
46
+ <ErrorBoundary>
47
+ <Component {...props} />
48
+ </ErrorBoundary>
49
+ );
50
+ };
51
+ }
52
+
53
+ const styles = StyleSheet.create({
54
+ screen: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 24, gap: 16, backgroundColor: '#fff' },
55
+ screenDark: { backgroundColor: '#000' },
56
+ title: { fontSize: 20, fontWeight: '600', textAlign: 'center', color: '#000' },
57
+ detail: { fontSize: 14, textAlign: 'center', color: '#000' },
58
+ textDark: { color: '#fff' },
59
+ button: { paddingVertical: 12, paddingHorizontal: 24, borderRadius: 8, backgroundColor: '#007AFF' },
60
+ buttonText: { fontSize: 16, fontWeight: '600', color: '#fff' },
61
+ });
@@ -0,0 +1,30 @@
1
+ // The app's error boundary. The root layout exports it, so Expo Router shows it, with a way to try again, when a screen
2
+ // throws while rendering, instead of a blank screen or a closed app. A route can export its own ErrorBoundary for its
3
+ // screens. Once the app has a crash reporter, report the error here.
4
+ import { type ErrorBoundaryProps } from 'expo-router';
5
+ import { Pressable, StyleSheet, Text, useColorScheme, View } from 'react-native';
6
+
7
+ export function ErrorBoundary({ error, retry }: ErrorBoundaryProps) {
8
+ const dark = useColorScheme() === 'dark';
9
+ return (
10
+ <View style={[styles.screen, dark && styles.screenDark]} accessibilityLiveRegion="assertive">
11
+ <Text style={[styles.title, dark && styles.textDark]} accessibilityRole="header">
12
+ Something went wrong
13
+ </Text>
14
+ {__DEV__ ? <Text style={[styles.detail, dark && styles.textDark]}>{error.message}</Text> : null}
15
+ <Pressable onPress={retry} style={styles.button} accessibilityRole="button" accessibilityLabel="Try again" testID="error-try-again">
16
+ <Text style={styles.buttonText}>Try again</Text>
17
+ </Pressable>
18
+ </View>
19
+ );
20
+ }
21
+
22
+ const styles = StyleSheet.create({
23
+ screen: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 24, gap: 16, backgroundColor: '#fff' },
24
+ screenDark: { backgroundColor: '#000' },
25
+ title: { fontSize: 20, fontWeight: '600', textAlign: 'center', color: '#000' },
26
+ detail: { fontSize: 14, textAlign: 'center', color: '#000' },
27
+ textDark: { color: '#fff' },
28
+ button: { paddingVertical: 12, paddingHorizontal: 24, borderRadius: 8, backgroundColor: '#007AFF' },
29
+ buttonText: { fontSize: 16, fontWeight: '600', color: '#fff' },
30
+ });
@@ -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 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`.
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`. Run `node scripts/amk/rn-check.js`: what it reports in the changed lines is a finding, and each `// amk-ok: <reason>` it lists needs a reason that holds.
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).
@@ -24,11 +24,15 @@ If your tool has subagents, hand the review to the `m-reviewer` subagent, so it
24
24
  - **Both platforms:** anything iOS-only or Android-only (insets, back button, permissions, keyboard)?
25
25
  - **Screens:** with the keyboard open, do the field and its button stay visible? Does anything sit under the status bar, home indicator or gesture bar? Do lists that grow with the user's data scroll? Does text wrap at the largest text size?
26
26
  - **Tablets and landscape** (the screens `AGENTS.md` lists): does each layout adapt to the window width (`useWindowDimensions`), rather than stretching or centering the phone layout? Do turned screens scroll, with the left and right insets handled? Are sizes done the app's existing way?
27
- - **Accessibility:** does every new button or other touchable have an `accessibilityLabel` and an `accessibilityRole`? Are messages that appear after an action, such as form errors, announced to screen readers?
28
- - **Errors and states:** offline, server errors, empty and loading states.
29
- - **Security:** secrets, tokens, `.env` contents, logging of personal data.
27
+ - **Accessibility:** does every new button or other touchable have an `accessibilityLabel` and an `accessibilityRole`, and checkboxes, switches and tabs their `accessibilityState`? Are messages that appear after an action, such as form errors, announced to screen readers? Text contrast 4.5:1 in both themes, nothing under 11 points, swipe and long-press actions reachable another way?
28
+ - **Platform guidelines:** tap areas of at least 44×44 pt (48×48 dp on Android); swipe back and the Android back button still work, and every `Modal` closes with back; permissions asked when the user starts the feature, with a way to Settings once blocked; native controls; dark mode from the theme; Reduce Motion respected.
29
+ - **Store review:** a new sign-up path needs account deletion in the app; a new social login needs Sign in with Apple; digital goods use in-app purchase; a new permission has a text that says why, and Google Play's restricted ones (photos, all packages, exact alarms, background location) a reason the feature can't do without. `node scripts/amk/release-check.js` finds some of these.
30
+ - **Current APIs:** nothing React Native removed or deprecated, no `react-native/Libraries/…` imports, and React 19's ways (`ref` as a prop, `<Context value>`), as the React Native rules list them.
31
+ - **Errors and states:** offline, server errors, empty and loading states; an error boundary around the app; no empty `catch`; an action that fails shows it and can be retried.
32
+ - **Effects:** timers, listeners and subscriptions are cleaned up, and async work that ends after the screen closes doesn't update it.
33
+ - **Security:** secrets, tokens in plain storage instead of the Keychain/Keystore (or `expo-secure-store`), secret keys in the JavaScript bundle, `.env` contents, logging of personal data, session replay that records typed text.
30
34
  - **Native:** `project.pbxproj`, `Podfile`, Gradle or manifest changes, and whether pods and builds were re-run.
31
- - **Performance:** heavy work in render, list keys, needless re-renders.
35
+ - **Performance:** heavy work in render, list keys (from IDs, not the index), needless re-renders, base64 images in code.
32
36
  3. For each finding, check it in the code before reporting it. Report: severity (**blocker**, **should fix**), file and line, the problem, and a suggested fix. Leave out style nits; lint handles those.
33
37
  4. End with: "Ready for PR" or "Not ready: N blockers".
34
38
 
@@ -6,10 +6,10 @@ 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`, `git show` and `node scripts/amk/baseline.js base`.
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`, `node scripts/amk/baseline.js base` and `node scripts/amk/rn-check.js`.
10
10
 
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
- 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.
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`. Run `node scripts/amk/rn-check.js`: what it reports is a finding, and each `// amk-ok: <reason>` it lists needs a reason that holds.
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, state on checkboxes, switches and tabs, contrast, text sizes, messages announced to screen readers), platform guidelines (44/48 tap areas, back gestures and the back button, permissions asked in context, native controls, dark mode, Reduce Motion), store review (account deletion, Sign in with Apple next to a social login, in-app purchase for digital goods, permission texts, restricted Android permissions), TypeScript (new `any` or `@ts-ignore`, a loosened tsconfig), removed or deprecated React Native APIs, errors (an error boundary, no empty `catch`, failed actions shown), error and empty states, effects that don't clean up, secrets and tokens in plain storage, 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.
15
15
  5. End with "Ready for PR" or "Not ready: N blockers".
@@ -22,8 +22,9 @@ This project may also use other AI workflow frameworks (for example Superpowers,
22
22
  | Android build | `cd android && ./gradlew assembleDebug` |
23
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 devices at the same time | `sh scripts/amk/verify.sh plan --spec <id>` says how many this machine's memory fits, and prints the commands: one per device (in rounds when they don't all fit; a device's flows in parts when there's room), each for an `m-device-checker` subagent |
25
+ | React Native mistakes in this branch's changed lines (`verify.sh quick` runs it) | `node scripts/amk/rn-check.js` |
25
26
  | 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
- | Check a release before tagging it (versions, permission texts, debug leftovers) | `node scripts/amk/release-check.js` |
27
+ | Check a release before tagging it (versions, permission texts, store review rules, debug leftovers) | `node scripts/amk/release-check.js` |
27
28
  | Signed release builds (a person runs them: they use the signing keys) | `sh scripts/amk/release-build.sh android [flavor]`, `sh scripts/amk/release-build.sh ios [scheme]` |
28
29
 
29
30
  ## Definition of done
@@ -43,6 +44,7 @@ Never say a check passed unless you ran it in this session.
43
44
  - Don't hand-edit `ios/*.xcodeproj/project.pbxproj`. If a native file must be added to the Xcode project, stop and ask.
44
45
  - Never read, print or commit `.env` files, keystores, signing files or the files `.amk-secrets` lists. Secrets don't belong in this repo.
45
46
  - Never use `git commit --no-verify`, `git push --force`, `git reset --hard` or `rm -rf`.
47
+ - When `rn-check` (in `verify.sh quick`) reports a problem (✗), show it to the user and let them choose, for each one: fix it, or keep the line with `// amk-ok <today's date>: <their reason>`. Never add an `amk-ok` on your own. One kept over two weeks ago comes back when its file changes again: ask again. Fix the warnings (!) in code the task changed, or tell the user why one stays.
46
48
  - After 2 failed attempts at the same fix, stop and report what you found.
47
49
  - Chat is not memory: write decisions into the spec or `docs/amk/decisions.md` straight away.
48
50
  - Follow `docs/amk/react-native.md`. Before fixing a build error, check `docs/amk/known-issues.md`.
@@ -1,6 +1,6 @@
1
1
  # React Native rules (bare)
2
2
 
3
- Rules for things AI agents commonly get wrong in current React Native. Each one comes from a documented platform change, or from a bug agents keep making on screens.
3
+ Rules for things AI agents commonly get wrong in current React Native. Each one comes from a documented platform change, or from a bug agents keep making on screens. `node scripts/amk/rn-check.js`, which `verify.sh quick` runs, checks the lines a branch changes for some of them.
4
4
 
5
5
  ## Architecture
6
6
 
@@ -16,7 +16,7 @@ Rules for things AI agents commonly get wrong in current React Native. Each one
16
16
  - With the keyboard open, the field being typed in and the button that submits the form stay visible and tappable, on both platforms.
17
17
  - Lists that grow with the user's data scroll (`FlatList`, or the list component the app already uses), and so does any screen taller than a small phone.
18
18
  - At the largest system text size, text wraps instead of being cut off: no fixed heights on views that hold text. Don't turn off font scaling (`allowFontScaling={false}`) to make a layout fit.
19
- - Messages that appear after an action, such as a form error, are read out by screen readers: announce them with `AccessibilityInfo.announceForAccessibility`.
19
+ - Messages that appear after an action, such as a form error, are read out by screen readers. On Android, show the message in a view with `accessibilityLiveRegion="polite"`: Android 16 deprecated announcements. On iOS, announce it with `AccessibilityInfo.announceForAccessibility`.
20
20
  - Check every UI change on both iOS and Android; behavior differs (keyboard, insets, fonts, permissions).
21
21
  - Give every interactive element a `testID` (kebab-case, for example `dark-mode-switch`). End-to-end tools tap by `testID`. On iOS, React Native exposes a label and its control as duplicate accessibility elements, so tapping by text can hit the label: nothing happens, yet the tool reports success.
22
22
  - Give every interactive element an `accessibilityLabel` that says what it does and an `accessibilityRole` (`button`, `link`, `switch`, …), so screen readers can use it. Icon-only buttons need it most; screen readers don't read `testID`.
@@ -30,9 +30,64 @@ Rules for things AI agents commonly get wrong in current React Native. Each one
30
30
  - Lay out by window width: under 600 points (dp on Android), the phone layout; from 600, the tablet layout, with more columns, and a list beside its detail where that helps. Text-heavy content and forms keep a readable width (about 600 to 700 points) instead of stretching edge to edge.
31
31
  - Sizes: when the app already has a way to size things (a scaling helper, or sizes in its theme), use it everywhere and don't mix in another. A new app takes sizes from its theme: spacing and a few text sizes step up from 600 points, and text follows the system font size. Judge the tablet and landscape screenshots like the phone's: each should look made for that screen, not stretched or tiny.
32
32
  - Landscape leaves little height: screens scroll, the keyboard covers more, and the safe-area insets include the left and right edges (the notch or Dynamic Island side).
33
- - Apps targeting Android 16 (API 36) can't lock the orientation or size on tablets and foldables (600 dp wide and up): the system ignores the lock there. So on Android tablets every screen has to work turned, whatever the app's settings say.
33
+ - Android ignores orientation and size locks on tablets and foldables (600 dp wide and up) for apps targeting Android 16 (API 36), and from Android 17 (API 37) apps can't opt out. Apple deprecated `UIRequiresFullScreen` with iPadOS 26, so iPad windows resize too. Every screen has to work at any window size and turned, whatever the app's settings say.
34
34
  - Don't lock the orientation in code to avoid layout work. Which orientations the app supports is a product decision, set in `Info.plist` (`UISupportedInterfaceOrientations`, and `~ipad` for iPads) and the Android manifest (`android:screenOrientation`); the iPad app itself is the Xcode target's device family.
35
35
 
36
+ ## Current React Native and React
37
+
38
+ These changed after most AI training data was written: check them instead of writing from memory.
39
+
40
+ - Removed: `InteractionManager` (0.87; use `requestIdleCallback`), the `StatusBar` props `backgroundColor` and `translucent` (0.87; edge to edge, they did nothing), `Modal`'s `animated` (0.87; `animationType`), a boolean `keyboardShouldPersistTaps` (0.87; `"handled"`) and `StyleSheet.absoluteFillObject` (0.85; `StyleSheet.absoluteFill`).
41
+ - Deprecated, so not in new code: `ImageBackground` (a `View` with an absolutely positioned `Image`), `InputAccessoryView` (`KeyboardStickyView` from `react-native-keyboard-controller`), `DrawerLayoutAndroid` (`react-native-drawer-layout`) and `AccessibilityInfo.setAccessibilityFocus` (`sendAccessibilityEvent`).
42
+ - Import from `react-native` itself. `react-native/Libraries/…` is private, and a type error from 0.87; don't add the `react-native-legacy-deep-imports` opt-out to hide it (it goes after 0.88).
43
+ - Jest: from 0.85 the preset is its own package, `preset: '@react-native/jest-preset'`.
44
+ - React 19: pass `ref` as a prop instead of `forwardRef`, render `<SomeContext value={…}>` instead of `<SomeContext.Provider>`, and use `useEffectEvent` (19.2) instead of turning off `react-hooks/exhaustive-deps`.
45
+ - With the React Compiler on (`babel-plugin-react-compiler` in `babel.config.js`), it memoizes: don't add `memo`, `useMemo` or `useCallback` to new code, and don't remove the ones there as a side task.
46
+ - iOS: apps built with Xcode 27 (the iOS 27 SDK) don't launch without the UIScene life cycle, which React Native supports from 0.88. Below 0.88, build with Xcode 26: moving to 0.88 is a task of its own. From then on, URL and user-activity handling goes in `SceneDelegate`.
47
+ - Android: Google Play takes only apps targeting Android 16 (API 36) or higher (from 31 August 2026). Don't lower `targetSdkVersion` to get out of edge to edge, back handling or orientation changes.
48
+
49
+ ## Errors, storage and effects
50
+
51
+ - Wrap the app in an error boundary (the crash reporter's, or a component with `getDerivedStateFromError`), so a render error shows a screen to recover from instead of a blank or closed app.
52
+ - Every failure reaches the user or the crash reporter: no empty `catch`, and an action started from a button catches its error and shows it, with a way to retry, so a spinner never stays up.
53
+ - Tokens, passwords and keys go in the Keychain and Keystore (`react-native-keychain`), never in AsyncStorage or other plain storage. Anything in the JavaScript bundle can be read by anyone who has the app: no secret keys in code, or in `.env` values the bundle includes.
54
+ - Session replay and analytics mask what users type, and logs leave out tokens and personal data.
55
+ - Effects clean up what they start: timers (`clearTimeout`, `clearInterval`), listeners and subscriptions (return their `remove`), and async work that can finish after the screen closes (an `AbortController`, or a flag the cleanup sets).
56
+ - List keys come from the item's ID, not its index: index keys mix up rows when items are added, removed or reordered.
57
+ - Images go in asset files, never in code as base64 strings: they bloat the bundle, and all of it loads with the JavaScript.
58
+ - Component tests use React Native Testing Library (`@testing-library/react-native`) and find elements as users and screen readers do, by role, label or text (`getByRole('button', { name: 'Save' })`), rather than relying on snapshots.
59
+
60
+ ## Platform guidelines and accessibility
61
+
62
+ From Apple's Human Interface Guidelines, Android's design and app quality guidelines, and WCAG 2.2.
63
+
64
+ - Touch targets: every button, link and control is at least 44×44 points on iOS and 48×48 dp on Android (`minWidth`/`minHeight: 48` covers both): pad a small icon instead of sizing the button to it. `hitSlop` doesn't reach past the parent's bounds, so use it only where the layout can't grow.
65
+ - Text: no `fontSize` under 11, and don't cap scaling below 2× (`maxFontSizeMultiplier`), in `Text.defaultProps`, or in native code (a `fontScale` or content size override).
66
+ - Contrast, in both light and dark: text 4.5:1 against its background (3:1 from 18 points, or 14 bold), and input borders, focus rings and icons that carry meaning 3:1. Colors come from the theme, whose pairs are checked once; a grey like `#999` on white is only 2.8:1.
67
+ - Screen readers: controls show their state in `accessibilityState` (`checked`, `selected`, `expanded`, `disabled`), and screen and section titles have `accessibilityRole="header"`. A label names the action ("Delete photo"), without the role ("button") the reader already says. Put `accessible` on a row that reads as one item, never on one that holds its own buttons. Meaningful images get a label; decorative ones need nothing.
68
+ - Every swipe, drag or long-press action also has a visible button or menu item, and is in `accessibilityActions`. Color is never the only signal: an error shows text, and a state adds an icon or a word.
69
+ - Back: keep swipe back on iOS and the system back on Android. To ask before leaving unsaved changes, use React Navigation's `usePreventRemove`, not `gestureEnabled: false`. A `hardwareBackPress` listener returns `true` only while it closes something on screen; apps don't quit themselves (`BackHandler.exitApp`). Every `Modal` has `onRequestClose`, which Android's back button calls; forms open as sheets (`presentationStyle="pageSheet"`, or the navigator's sheet presentation).
70
+ - Permissions: ask when the user starts the feature that needs it, never at launch or when a screen opens; first say in the app why. When it's denied, say what's unavailable and keep the rest working. When the system won't ask again (`never_ask_again`, `blocked`), the feature's button explains that and offers `Linking.openSettings()`. Ask for notifications (Android 13 and later need `POST_NOTIFICATIONS`) after an action they serve, not on launch.
71
+ - Use the native controls (`@react-native-community/datetimepicker`, `Alert.alert` with verb buttons and `style: 'destructive'` and `'cancel'`, `ActionSheetIOS`, `Switch`); a custom one gets the same role, state and size.
72
+ - Dark mode: colors come from the theme's light and dark values (`useColorScheme()`), not hex values in components; don't lock the app to light.
73
+ - Data screens have loading, empty (why, and what to do next), error (what failed, with Retry) and content states. A message the user has to read doesn't vanish on a timer, and screen readers announce it.
74
+ - Reduce Motion: with it on, nothing loops or moves for decoration. Don't pass `ReduceMotion.Never` to Reanimated for decoration; with `Animated` or Lottie, read `AccessibilityInfo.isReduceMotionEnabled()` and the `reduceMotionChanged` event, and fade or stop instead.
75
+ - iOS 26: use native headers and tab bars (React Navigation's native stack and native tabs), which iOS draws in its current style; don't draw imitation glass behind content, or opt out with `UIDesignRequiresCompatibility` (builds with the iOS 27 SDK ignore it). Nothing the user needs sits under a floating tab bar, button or footer: scroll content gets bottom padding for it.
76
+ - Haptics only for success, error or a selection, never as the only feedback, through the app's haptics library; not `Vibration.vibrate`.
77
+
78
+ ## Store review
79
+
80
+ What App Store review and Google Play reject. `node scripts/amk/release-check.js` checks the project for some of it.
81
+
82
+ - Apps where people can create an account let them start deleting it in the app: a full deletion, not deactivation; a direct link to a web page that finishes it is fine (Apple 5.1.1(v)). Google Play also needs that web link in the Data safety form.
83
+ - A third-party or social login (Google, Facebook) as the main sign-in also needs an equivalent private one, usually Sign in with Apple (4.8); an app that signs in only with the company's own accounts doesn't.
84
+ - Digital content and subscriptions are sold with in-app purchase (3.1.1); physical goods and services aren't. Links to buy elsewhere follow the storefront's current rules.
85
+ - Permission texts (`…UsageDescription`) say what the app does with the data and why, for each use; ask only for what the app uses.
86
+ - The privacy manifest and App Store Connect's privacy details list the data the app and its SDKs collect (analytics, crash reporting, session replay). Tracking needs the App Tracking Transparency prompt first.
87
+ - Google Play restricts these permissions to apps whose core feature needs them, with a declaration in Play Console: photos and videos (`READ_MEDIA_IMAGES`, `READ_MEDIA_VIDEO`: others use the Android photo picker), `QUERY_ALL_PACKAGES`, `MANAGE_EXTERNAL_STORAGE`, SMS and call log, `USE_EXACT_ALARM`, and background location (also a video and an in-app disclosure first). A library can add one: remove it in `AndroidManifest.xml` with `tools:node="remove"` when the app doesn't need it.
88
+ - Android foreground services declare their type (`android:foregroundServiceType`) and its `FOREGROUND_SERVICE_<TYPE>` permission, and each type is declared in Play Console.
89
+ - From 1 February 2027, Google Play takes updates to apps targeting Android 15 or later only with 16 KB page size support, which React Native has from 0.77.
90
+
36
91
  ## TypeScript
37
92
 
38
93
  - Keep the checks `tsconfig.json` has. Don't loosen them, or get past one with `any`, `@ts-ignore` or a non-null `!`.
@@ -161,6 +161,8 @@ const NEEDS = {
161
161
  'expo-location': ['NSLocationWhenInUseUsageDescription'],
162
162
  'expo-contacts': ['NSContactsUsageDescription'],
163
163
  'expo-local-authentication': ['NSFaceIDUsageDescription'],
164
+ 'react-native-tracking-transparency': ['NSUserTrackingUsageDescription'],
165
+ 'expo-tracking-transparency': ['NSUserTrackingUsageDescription'],
164
166
  };
165
167
  // the texts Expo's config plugins write when app.json gives none: too vague for App Review
166
168
  const EXPO_DEFAULT = /^Allow \$\(PRODUCT_NAME\) to /;
@@ -189,7 +191,10 @@ for (const plistPath of Object.keys(textsByPlist)) {
189
191
  }
190
192
  const vague = Object.entries(texts).filter(([, t]) => EXPO_DEFAULT.test(t)).map(([k]) => k);
191
193
  if (vague.length) warn(`${plistPath}: Expo's default text for ${vague.join(', ')}`, 'App Review asks why the app needs each permission: set the text in the library\'s plugin options or ios.infoPlist in app.json');
192
- if (!problems.length && !vague.length && !Object.values(texts).some(t => PLACEHOLDER.test(t))) ok(`${plistPath}: permission texts`, `${Object.keys(texts).length} present`);
194
+ // too short to say what the app does with the data and why ("Camera access")
195
+ const short = Object.entries(texts).filter(([, t]) => t.trim() && t.trim().length < 25 && !PLACEHOLDER.test(t) && !EXPO_DEFAULT.test(t));
196
+ for (const [key, text] of short) warn(`${plistPath}: ${key} is short ("${text.trim()}")`, 'say what the app does with it and why, for each use; App Review rejects vague texts (5.1.1)');
197
+ if (!problems.length && !vague.length && !short.length && !Object.values(texts).some(t => PLACEHOLDER.test(t))) ok(`${plistPath}: permission texts`, `${Object.keys(texts).length} present`);
193
198
  const arbitrary = expo ? (expoPlist.NSAppTransportSecurity || {}).NSAllowsArbitraryLoads === true
194
199
  : /<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(readNow(plistPath) || '');
195
200
  if (arbitrary) {
@@ -199,7 +204,9 @@ for (const plistPath of Object.keys(textsByPlist)) {
199
204
 
200
205
  // ---------- 4. Android permissions ----------
201
206
  const SENSITIVE = /\.(ACCESS_(FINE|COARSE|BACKGROUND)_LOCATION|CAMERA|RECORD_AUDIO|READ_CONTACTS|WRITE_CONTACTS|READ_EXTERNAL_STORAGE|WRITE_EXTERNAL_STORAGE|READ_MEDIA_\w+|BLUETOOTH_SCAN|BLUETOOTH_CONNECT|POST_NOTIFICATIONS|READ_PHONE_STATE|BODY_SENSORS|READ_CALENDAR|WRITE_CALENDAR|ACCESS_MEDIA_LOCATION)$/;
202
- const perms = t => all(/<uses-permission[^>]*android:name="([^"]+)"/g, t);
207
+ // what the manifest asks for: not the ones it removes (tools:node="remove", for a permission a library adds)
208
+ const perms = t => uniq([...(t || '').matchAll(/<uses-permission\b[^>]*>/g)].map(m => m[0]).filter(p => !/tools:node="remove"/.test(p))
209
+ .map(p => (/android:name="([^"]+)"/.exec(p) || [])[1]).filter(Boolean));
203
210
  // Expo: the manifest prebuild would write, as JSON
204
211
  const expoManifest = ((expoResults.android || {}).manifest || {}).manifest;
205
212
  const permsNow = expo ? uniq(((expoManifest || {})['uses-permission'] || []).map(p => p.$['android:name'])) : perms(readNow(manifestPath));
@@ -274,6 +281,146 @@ for (const f of noteFiles) {
274
281
  }
275
282
  if (!noteFiles.length) info('No store release notes yet', 'run the m-release skill to write them from the changelog');
276
283
 
284
+ // ---------- 8. store review rules ----------
285
+ // what App Store review and Google Play policy reject that the project shows. Most need a person to judge (an
286
+ // exception, an approved Play declaration), so they warn
287
+ const found = names => names.filter(n => deps[n]);
288
+ const sourceFiles = (git('ls-files', '--', '*.js', '*.jsx', '*.ts', '*.tsx') || '').split('\n')
289
+ .filter(f => f && !/(^|\/)(node_modules|scripts\/amk|__tests__|__mocks__|e2e|ios|android)\//.test(f) && !/\.(test|spec)\.\w+$/.test(f));
290
+ const source = sourceFiles.map(f => readNow(f) || '').join('\n');
291
+ // a sign-up in code (a call, a screen, an API path), not the words in a comment or in text ("No account, no sign-up")
292
+ const SIGN_UP = /\b(signUp|signup|createAccount|createUserWithEmailAndPassword|registerUser|registerAccount)\s*\(|\b(name|screen)\s*[:=]\s*\{?\s*['"](SignUp|Signup|Register|Registration|CreateAccount)['"]|navigate\(\s*['"](SignUp|Signup|Register|Registration|CreateAccount)['"]|['"`][^'"`\s]*\/(sign-?up|register|registration|create-?account)\b/i;
293
+ const rnVersion = (() => { try { return require(path.resolve('node_modules/react-native/package.json')).version; } catch { return (deps['react-native'] || '').replace(/^[^\d]*/, ''); } })();
294
+ const [rnMajor, rnMinor] = rnVersion.split('.').map(Number);
295
+ const rnBelow = minor => rnMajor === 0 && rnMinor < minor;
296
+ let storeFindings = 0;
297
+ const storeWarn = (label, fix) => { storeFindings++; warn(label, fix); };
298
+
299
+ // Apple
300
+ if (SIGN_UP.test(stripComments(source))
301
+ && !/delete[ _-]?(my[ _-]?)?account|account[ _-]?deletion|deleteUser|close[ _-]?account|remove[ _-]?account/i.test(source)) {
302
+ storeWarn('The app has a sign-up, but no account deletion was found in its code', 'people who can create an account must be able to start deleting it in the app (Apple 5.1.1(v)); Google Play also needs a web link to it in the Data safety form');
303
+ }
304
+ const social = [...found(['@react-native-google-signin/google-signin', 'react-native-fbsdk-next']),
305
+ ...(/expo-auth-session\/providers\/(google|facebook)/.test(source) ? ['expo-auth-session'] : [])];
306
+ const entitlements = fs.existsSync('ios') ? fs.readdirSync('ios', { withFileTypes: true }).filter(e => e.isDirectory())
307
+ .flatMap(e => fs.readdirSync(`ios/${e.name}`).filter(f => f.endsWith('.entitlements')).map(f => readNow(`ios/${e.name}/${f}`) || '')) : [];
308
+ const appleSignIn = found(['expo-apple-authentication', '@invertase/react-native-apple-authentication']).length
309
+ || entitlements.some(e => e.includes('com.apple.developer.applesignin')) || ((expo || {}).ios || {}).usesAppleSignIn;
310
+ if (social.length && !appleSignIn) {
311
+ storeWarn(`A social login (${social.join(', ')}) without Sign in with Apple`, 'App Review needs an equivalent private login next to it, usually Sign in with Apple (4.8); fine if the app signs in only with the company\'s own accounts');
312
+ }
313
+ const trackers = found(['react-native-fbsdk-next', 'react-native-appsflyer', 'react-native-adjust', 'react-native-google-mobile-ads']);
314
+ const allTexts = Object.values(textsByPlist).flatMap(Object.keys);
315
+ if (trackers.length && !found(['react-native-tracking-transparency', 'expo-tracking-transparency']).length && !allTexts.includes('NSUserTrackingUsageDescription')) {
316
+ storeWarn(`${trackers.join(', ')} can track people across apps, and the app has no App Tracking Transparency prompt`, 'ask with the ATT prompt first (react-native-tracking-transparency or expo-tracking-transparency) and set NSUserTrackingUsageDescription (5.1.2)');
317
+ }
318
+ const privacy = expo ? [['app config (ios.privacyManifests)', (expo.ios || {}).privacyManifests || {}]]
319
+ : (fs.existsSync('ios') ? fs.readdirSync('ios', { withFileTypes: true }) : []).filter(e => e.isDirectory() && fs.existsSync(`ios/${e.name}/PrivacyInfo.xcprivacy`))
320
+ .map(e => [`ios/${e.name}/PrivacyInfo.xcprivacy`, readNow(`ios/${e.name}/PrivacyInfo.xcprivacy`) || '']);
321
+ const collectors = found(['@react-native-firebase/analytics', '@react-native-firebase/crashlytics', '@sentry/react-native', '@amplitude/analytics-react-native',
322
+ '@segment/analytics-react-native', 'posthog-react-native', 'mixpanel-react-native', '@microsoft/react-native-clarity', '@datadog/mobile-react-native',
323
+ '@bugsnag/react-native', '@intercom/intercom-react-native', 'react-native-appsflyer', 'react-native-fbsdk-next']);
324
+ for (const [where, m] of privacy) {
325
+ const xml = typeof m === 'string';
326
+ const tracking = xml ? /<key>NSPrivacyTracking<\/key>\s*<true\s*\/>/.test(m) : m.NSPrivacyTracking === true;
327
+ const domains = xml ? /<key>NSPrivacyTrackingDomains<\/key>\s*<array>\s*<string>/.test(m) : (m.NSPrivacyTrackingDomains || []).length > 0;
328
+ const collected = xml ? /<key>NSPrivacyCollectedDataTypes<\/key>\s*<array>\s*<dict>/.test(m) : (m.NSPrivacyCollectedDataTypes || []).length > 0;
329
+ if (tracking && !domains) fail(`${where}: NSPrivacyTracking is true but lists no NSPrivacyTrackingDomains`, 'list the domains the app tracks with; Apple needs them when tracking is on');
330
+ if (!collected && collectors.length) storeWarn(`${where} lists no collected data, and ${collectors.join(', ')} collect some`, 'make sure App Store Connect\'s privacy details (and this manifest, where the SDK\'s own doesn\'t) list it: names, emails, usage data, crash data, recordings');
331
+ }
332
+ const plistFlags = expo ? [['app config (ios.infoPlist)', expoPlist]] : plists.map(p => [p, readNow(p) || '']);
333
+ for (const [where, p] of plistFlags) {
334
+ const on = key => (typeof p === 'string' ? new RegExp(`<key>${key}</key>\\s*<true\\s*/>`).test(p) : p[key] === true);
335
+ if (on('UIDesignRequiresCompatibility')) storeWarn(`${where}: UIDesignRequiresCompatibility opts out of iOS 26's design`, 'builds with the iOS 27 SDK ignore it: make the app work with the current design');
336
+ if (on('UIRequiresFullScreen')) storeWarn(`${where}: UIRequiresFullScreen is deprecated (iPadOS 26)`, 'iPad windows resize anyway: make every screen adapt to the window');
337
+ }
338
+ const nativeCaps = [...(git('grep', '-l', '-E', 'override +var +preferredContentSizeCategory|\\(UIContentSizeCategory\\) *preferredContentSizeCategory', '--', 'ios/*.swift', 'ios/*.m', 'ios/*.mm') || '').split('\n'),
339
+ ...(git('grep', '-l', '-E', 'fontScale *= *[^= ]', '--', 'android/*.kt', 'android/*.java') || '').split('\n')].filter(f => f && !f.includes('/Pods/'));
340
+ if (nativeCaps.length) storeWarn(`Native code caps the user's text size: ${nativeCaps.join(', ')}`, 'people who pick a large text size get a smaller one; let text scale, and make layouts wrap');
341
+ if (rnVersion && rnBelow(88)) info(`React Native ${rnVersion}: apps built with Xcode 27 (the iOS 27 SDK) don't launch below 0.88`, 'App Store uploads move to each new Xcode from a date Apple announces: upgrade React Native before then');
342
+ const payments = found(['@stripe/stripe-react-native', 'react-native-razorpay', 'react-native-paypal', 'react-native-braintree-dropin-ui']);
343
+ if (payments.length && !found(['react-native-iap', 'react-native-purchases', 'expo-iap', 'expo-in-app-purchases']).length) {
344
+ info(`${payments.join(', ')} without in-app purchase`, 'fine for physical goods and services; digital content and subscriptions need in-app purchase (3.1.1)');
345
+ }
346
+
347
+ // Google: every permission the release build gets: the app's manifests and its libraries' (Gradle merges them), less
348
+ // what the app removes. A release build's merged manifest already is that, when it's newer than what it was built from
349
+ function walk(dir, keep, depth = 0) {
350
+ if (depth > 6 || !fs.existsSync(dir)) return [];
351
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => (e.isDirectory() ? walk(`${dir}/${e.name}`, keep, depth + 1) : keep(`${dir}/${e.name}`) ? [`${dir}/${e.name}`] : []));
352
+ }
353
+ const tags = (t, name) => [...(t || '').matchAll(new RegExp(`<${name}\\b[^>]*>`, 'g'))].map(m => m[0]);
354
+ const attr = (tag, a) => (new RegExp(`${a}="([^"]+)"`).exec(tag) || [])[1];
355
+ const mtime = f => { try { return fs.statSync(f).mtimeMs; } catch { return 0; } };
356
+ const ownManifests = expo ? [] : (fs.existsSync('android/app/src') ? fs.readdirSync('android/app/src') : [])
357
+ .map(d => `android/app/src/${d}/AndroidManifest.xml`).filter(f => fs.existsSync(f));
358
+ const intermediates = 'android/app/build/intermediates';
359
+ const built = expo || !fs.existsSync(intermediates) ? [] : fs.readdirSync(intermediates).filter(d => /^merged_manifests?$/.test(d))
360
+ .flatMap(d => walk(`${intermediates}/${d}`, f => /release/i.test(f) && f.endsWith('AndroidManifest.xml')));
361
+ const sourcesTime = Math.max(...[...ownManifests, 'package.json', gradlePath].filter(Boolean).map(mtime));
362
+ const merged = built.filter(f => mtime(f) >= sourcesTime);
363
+ const appManifests = merged.length ? merged : ownManifests;
364
+ const libManifests = merged.length ? [] : Object.keys(deps).map(d => [d, readNow(`node_modules/${d}/android/src/main/AndroidManifest.xml`)]).filter(([, t]) => t);
365
+ const removed = new Set([...ownManifests.flatMap(f => tags(readNow(f), 'uses-permission').filter(p => /tools:node="remove"/.test(p)).map(p => attr(p, 'android:name'))),
366
+ ...(expo ? ((expoManifest || {})['uses-permission'] || []).filter(p => p.$['tools:node'] === 'remove').map(p => p.$['android:name']) : []),
367
+ ...(((expo || {}).android || {}).blockedPermissions || [])]);
368
+ const granted = new Map();
369
+ const grant = (name, from) => { if (name && !removed.has(name)) granted.set(name, [...new Set([...(granted.get(name) || []), from])]); };
370
+ if (expo) for (const p of (expoManifest || {})['uses-permission'] || []) { if (p.$['tools:node'] !== 'remove') grant(p.$['android:name'], 'the app config'); }
371
+ for (const f of appManifests) for (const p of tags(readNow(f), 'uses-permission').filter(x => !/tools:node="remove"/.test(x))) grant(attr(p, 'android:name'), merged.length ? 'the merged release manifest' : f);
372
+ for (const [lib, t] of libManifests) for (const p of tags(t, 'uses-permission')) grant(attr(p, 'android:name'), lib);
373
+ const permName = n => n.replace(/^android\.permission\./, '');
374
+ const RESTRICTED = {
375
+ READ_MEDIA_IMAGES: 'only for apps built around broad access to photos; others use the Android photo picker, which needs no permission',
376
+ READ_MEDIA_VIDEO: 'only for apps built around broad access to videos; others use the Android photo picker, which needs no permission',
377
+ QUERY_ALL_PACKAGES: 'list the apps it needs to see in <queries> instead',
378
+ MANAGE_EXTERNAL_STORAGE: 'picking files or media isn\'t an allowed use: use the system pickers',
379
+ READ_SMS: 'only for the default SMS app: one-time codes use the SMS Retriever API', RECEIVE_SMS: 'only for the default SMS app: one-time codes use the SMS Retriever API',
380
+ SEND_SMS: 'only for the default SMS app', RECEIVE_MMS: 'only for the default SMS app', RECEIVE_WAP_PUSH: 'only for the default SMS app', WRITE_SMS: 'only for the default SMS app',
381
+ READ_CALL_LOG: 'only for the default phone app', WRITE_CALL_LOG: 'only for the default phone app', PROCESS_OUTGOING_CALLS: 'only for the default phone app',
382
+ USE_EXACT_ALARM: 'only for alarm, timer and calendar apps: others use SCHEDULE_EXACT_ALARM, and check canScheduleExactAlarms',
383
+ ACCESS_BACKGROUND_LOCATION: 'needs a Play Console declaration for one feature, a short video, and a prominent disclosure in the app before asking',
384
+ REQUEST_INSTALL_PACKAGES: 'needs a Play Console declaration', USE_FULL_SCREEN_INTENT: 'only for calls and alarms',
385
+ };
386
+ const remove = expo ? 'list it in android.blockedPermissions' : 'remove it (tools:node="remove" for one a library adds)';
387
+ for (const [name, from] of granted) {
388
+ const why = RESTRICTED[permName(name)];
389
+ if (why) storeWarn(`Google Play restricts ${permName(name)} (from ${from.join(', ')})`, `${why}; keep it only with an approved Play Console declaration, otherwise ${remove}`);
390
+ }
391
+ // foreground services: each declares its type, and each FOREGROUND_SERVICE_<TYPE> permission has a service of that type
392
+ // the app's own services (a merged manifest also has every library's, which declare their own types)
393
+ const services = [...ownManifests.flatMap(f => tags(readNow(f), 'service').map(s => [s, f])),
394
+ ...(expo ? ((((expoManifest || {}).application || [])[0] || {}).service || []).map(s => [`<service ${Object.entries(s.$ || {}).map(([k, v]) => `${k}="${v}"`).join(' ')}>`, 'the app config']) : [])];
395
+ const typeName = v => v.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase();
396
+ const allServices = [...services, ...merged.flatMap(f => tags(readNow(f), 'service').map(s => [s, f])), ...libManifests.flatMap(([lib, t]) => tags(t, 'service').map(s => [s, lib]))];
397
+ const types = new Set(allServices.flatMap(([s]) => (attr(s, 'android:foregroundServiceType') || '').split('|').filter(Boolean).map(typeName)));
398
+ if ([...granted.keys()].some(n => permName(n).startsWith('FOREGROUND_SERVICE'))) {
399
+ // once per service, wherever it's declared (the main manifest and a flavor's, say)
400
+ const untyped = new Map();
401
+ for (const [s, from] of services.filter(([s]) => !attr(s, 'android:foregroundServiceType'))) {
402
+ const name = attr(s, 'android:name') || 'a service';
403
+ untyped.set(name, [...(untyped.get(name) || []), from]);
404
+ }
405
+ for (const [name, from] of untyped) {
406
+ storeWarn(`${name} has no android:foregroundServiceType (${from.join(', ')})`, 'if it runs in the foreground, declare its type and the matching FOREGROUND_SERVICE_<TYPE> permission: from Android 14, starting it without one crashes');
407
+ }
408
+ for (const n of [...granted.keys()].map(permName).filter(n => /^FOREGROUND_SERVICE_./.test(n))) {
409
+ if (!types.has(n.replace('FOREGROUND_SERVICE_', ''))) storeWarn(`${n} is declared, but no service has that type`, 'give the service that does this work the matching android:foregroundServiceType, or remove the permission');
410
+ }
411
+ if (types.size) info(`Foreground service types to declare in Play Console: ${[...types].join(', ')}`);
412
+ }
413
+ if (rnVersion && rnBelow(77)) {
414
+ const due = Date.now() >= Date.parse('2027-02-01');
415
+ (due ? fail : warn)(`React Native ${rnVersion} has no 16 KB page size support (from 0.77)`, 'from 1 February 2027 Google Play takes updates to apps targeting Android 15 or later only with it: upgrade React Native');
416
+ if (!due) storeFindings++;
417
+ }
418
+ const notifiers = found(['@react-native-firebase/messaging', '@notifee/react-native', 'react-native-push-notification', 'expo-notifications', 'react-native-onesignal', 'react-native-notifications']);
419
+ if (notifiers.length && !/requestPermission|requestPermissionsAsync|requestNotifications|POST_NOTIFICATIONS|requestUserPermission/.test(source)) {
420
+ storeWarn(`${notifiers.join(', ')}, but the code never asks for permission to notify`, 'Android 13 and later show notifications only once the user allows them: ask after an action they serve');
421
+ }
422
+ if (!storeFindings) ok('Store review rules', 'nothing found');
423
+
277
424
  // ---------- report ----------
278
425
  const icon = { ok: '✓', info: '·', warn: '!', fail: '✗' };
279
426
  console.log(`Release check${since ? ` (compared with ${since})` : ''}`);
@@ -0,0 +1,306 @@
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. Problems (✗) fail it, and so verify.sh quick; warnings (!) don't. Only changed lines: code already
4
+ // on the base branch is never reported. A line that's right as it is carries `// amk-ok <date>: <reason>`, on it or on
5
+ // 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
6
+ // 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
7
+ // from git when the comment has none).
8
+ // The base is the one baseline.js uses (AMK_BASE sets it). Usage: node scripts/amk/rn-check.js
9
+ 'use strict';
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { execFileSync, spawnSync } = require('child_process');
13
+
14
+ const root = process.cwd();
15
+ const git = (...args) => {
16
+ try {
17
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 2 ** 28 });
18
+ } catch {
19
+ return null;
20
+ }
21
+ };
22
+ if (git('rev-parse', '--git-dir') === null) {
23
+ console.log('rn-check: skipped (not a git repository)');
24
+ process.exit(0);
25
+ }
26
+
27
+ // ---------- the changed lines ----------
28
+ const found = spawnSync(process.execPath, [path.join(__dirname, 'baseline.js'), 'base'], { cwd: root, encoding: 'utf8' });
29
+ const baseRef = found.status === 0 ? found.stdout.trim() : '';
30
+ const sha = (baseRef && git('merge-base', 'HEAD', baseRef) || git('rev-parse', '--verify', '--quiet', 'HEAD') || '').trim();
31
+ const since = baseRef || 'the last commit';
32
+ const source = f => /\.(js|jsx|ts|tsx|mjs|cjs)$/.test(f) && !f.endsWith('.d.ts')
33
+ && !/(^|\/)(node_modules|scripts\/amk|__tests__|__mocks__|e2e)\//.test(f)
34
+ && !/\.(test|spec)\.\w+$|(^|\/)(jest[.-]setup|setup-?tests)[^/]*$/i.test(f);
35
+ const changed = new Map(); // file -> Set of line numbers, or 'all'
36
+ if (sha) {
37
+ let file = null;
38
+ for (const line of (git('diff', '-U0', '--no-color', '--no-ext-diff', '--relative', '-M', '--diff-filter=ACMR', sha) || '').split('\n')) {
39
+ if (line.startsWith('+++ ')) { file = line === '+++ /dev/null' ? null : line.slice(6); continue; }
40
+ const h = /^@@ -\S+ \+(\d+)(?:,(\d+))? @@/.exec(line);
41
+ if (!h || !file || !source(file)) continue;
42
+ if (!changed.has(file)) changed.set(file, new Set());
43
+ for (let n = Number(h[1]), end = n + Number(h[2] ?? 1); n < end; n++) changed.get(file).add(n);
44
+ }
45
+ }
46
+ for (const f of (git('ls-files', '--others', '--exclude-standard') || '').split('\n')) if (f && source(f)) changed.set(f, 'all');
47
+
48
+ // ---------- what the app uses ----------
49
+ let pkg = {};
50
+ try { pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); } catch {}
51
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
52
+ const major = name => Number((/\d+/.exec(deps[name] || '') || [0])[0]);
53
+ const expoSdk = deps.expo ? major('expo') : 0;
54
+
55
+ // the code without its comments (each comment character a space, so positions and lines stay). A quote opened in
56
+ // JSX text (Don't) ends with its line, so it can't hide the rest of the file; a template string can span lines
57
+ function stripComments(text) {
58
+ const out = text.split('');
59
+ let block = false;
60
+ let quote = null;
61
+ for (let i = 0; i < text.length; i++) {
62
+ const c = text[i];
63
+ const n = text[i + 1];
64
+ if (c === '\n') { if (quote !== '`') quote = null; continue; }
65
+ if (block) {
66
+ if (c === '*' && n === '/') { out[i] = out[i + 1] = ' '; i++; block = false; } else out[i] = ' ';
67
+ continue;
68
+ }
69
+ if (quote) { if (c === '\\') i++; else if (c === quote) quote = null; continue; }
70
+ if (c === '"' || c === "'" || c === '`') { quote = c; continue; }
71
+ if (c === '/' && n === '*') { block = true; out[i] = out[i + 1] = ' '; i++; continue; }
72
+ // not a URL's // (https://) or one in a regular expression (\/\/)
73
+ if (c === '/' && n === '/' && !/[:\w\\]/.test(text[i - 1] || '')) {
74
+ while (i < text.length && text[i] !== '\n') out[i++] = ' ';
75
+ i--;
76
+ }
77
+ }
78
+ return out.join('');
79
+ }
80
+
81
+ // from an opening bracket or a tag's <, the index of its end: the matching bracket, or the tag's closing >
82
+ function endOf(code, start) {
83
+ const open = { '(': ')', '[': ']', '{': '}' };
84
+ const stack = [];
85
+ let quote = null;
86
+ for (let i = start; i < code.length; i++) {
87
+ const c = code[i];
88
+ if (quote) { if (c === '\\') i++; else if (c === quote || (c === '\n' && quote !== '`')) quote = null; continue; }
89
+ if (c === '"' || c === "'" || c === '`') quote = c;
90
+ else if (open[c]) stack.push(open[c]);
91
+ else if (c === stack[stack.length - 1]) { stack.pop(); if (!stack.length && code[start] !== '<') return i; }
92
+ else if (c === '>' && code[start] === '<' && !stack.length && code[i - 1] !== '=') return i;
93
+ }
94
+ return code.length - 1;
95
+ }
96
+
97
+ // ---------- the checks ----------
98
+ const findings = [];
99
+ const kept = [];
100
+ const DAY = 24 * 3600 * 1000;
101
+ // a day as the user's calendar has it
102
+ const localDay = ms => new Date(ms - new Date(ms).getTimezoneOffset() * 60000).toISOString().slice(0, 10);
103
+ const today = localDay(Date.now());
104
+ // when the amk-ok on line n of file was given: its date, else the day git has for the line (today when uncommitted)
105
+ function okSince(file, n, date) {
106
+ if (date) return date;
107
+ const t = /^committer-time (\d+)$/m.exec(git('blame', '--porcelain', '-L', `${n},${n}`, '--', file) || '');
108
+ return t ? localDay(Number(t[1]) * 1000) : today;
109
+ }
110
+ const importsFrom = (code, from) => [...code.matchAll(new RegExp(`import\\s+[^;'"]*?\\{([^}]*)\\}\\s*from\\s*['"]${from}['"]`, 'g'))];
111
+ const timers = /\bset(Timeout|Interval)\s*\(/;
112
+ // a permission prompt (not App Tracking Transparency's, which apps show early on purpose)
113
+ const ASK = /\b(PermissionsAndroid\.request(?:Multiple)?|request\(\s*PERMISSIONS\.|requestMultiple|request(?:Foreground|Background)?PermissionsAsync|requestNotifications|requestPermission|Geolocation\.requestAuthorization)\s*\(?/;
114
+ const TOUCHABLE = /^(Pressable|TouchableOpacity|TouchableHighlight|TouchableWithoutFeedback|TouchableNativeFeedback)$/;
115
+ const listeners = /\.(addEventListener|addListener|subscribe)\s*\(/;
116
+ const reduceMotion = /isReduceMotionEnabled|reduceMotionChanged|useReducedMotion|ReduceMotion\b/;
117
+
118
+ function check(file, text) {
119
+ const code = stripComments(text);
120
+ const ts = /\.tsx?$/.test(file);
121
+ const out = [];
122
+ const add = (level, at, end, message, line) => out.push({ level, at, end: end ?? at, message, line });
123
+ const each = (re, fn, src = code) => { for (const m of src.matchAll(re)) fn(m); };
124
+
125
+ // problems: removed or private APIs, secrets and tokens in the open, images in code
126
+ each(/\bInteractionManager\b/g, m => add('✗', m.index, null, 'InteractionManager was removed in React Native 0.87: use requestIdleCallback'));
127
+ each(/\babsoluteFillObject\b/g, m => add('✗', m.index, null, 'StyleSheet.absoluteFillObject was removed in React Native 0.85: use StyleSheet.absoluteFill'));
128
+ 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)`));
129
+ each(/<\s*(StatusBar|Modal|ScrollView|FlatList|SectionList|KeyboardAwareScrollView)\b/g, m => {
130
+ const end = endOf(code, m.index);
131
+ const tag = code.slice(m.index, end + 1);
132
+ const prop = m[1] === 'StatusBar' ? /\s(backgroundColor|translucent)\b/.exec(tag)
133
+ : m[1] === 'Modal' ? /\s(animated)\b(?!Type)/.exec(tag)
134
+ : /\s(keyboardShouldPersistTaps)(\s*=\s*\{\s*(true|false)\s*\}|(?=[\s/>]))/.exec(tag);
135
+ if (!prop) return;
136
+ const instead = { backgroundColor: 'edge to edge, it did nothing', translucent: 'edge to edge, it did nothing', animated: 'use animationType', keyboardShouldPersistTaps: 'use "handled"' }[prop[1]];
137
+ 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}`);
138
+ });
139
+ 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'`));
140
+ // at the name itself: a branch that adds another name to an old import statement didn't add this one
141
+ for (const m of importsFrom(code, 'react-native')) {
142
+ const name = n => { const i = m[0].search(new RegExp(`\\b${n}\\b`)); return i < 0 ? null : m.index + i; };
143
+ if (name('SafeAreaView') !== null) add('✗', name('SafeAreaView'), null, "SafeAreaView from 'react-native' is deprecated and iOS-only: use react-native-safe-area-context");
144
+ for (const n of ['ImageBackground', 'InputAccessoryView', 'DrawerLayoutAndroid']) {
145
+ if (name(n) !== null) add('!', name(n), null, `${n} is deprecated in React Native: see the React Native rules for its replacement`);
146
+ }
147
+ for (const n of ['NativeModules', 'requireNativeComponent']) {
148
+ if (name(n) !== null) add('!', name(n), null, `${n} is the old architecture: write a Turbo Module or a Fabric component`);
149
+ }
150
+ }
151
+ each(/\bAsyncStorage\s*\.\s*(setItem|multiSet|mergeItem)\s*\(/g, m => {
152
+ const open = m.index + m[0].length - 1;
153
+ if (/token|password|passwd|secret|credential|api[_-]?key/i.test(code.slice(open, endOf(code, open)))) {
154
+ 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)'}`);
155
+ }
156
+ });
157
+ // secrets are reported without their value; comments too, as they ship in the repository
158
+ const secrets = [
159
+ [/\bgh[pousr]_[A-Za-z0-9]{36,}/g, 'a GitHub token'], [/\bgithub_pat_[A-Za-z0-9_]{40,}/g, 'a GitHub token'],
160
+ [/\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'],
161
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----/g, 'a private key'], [/\bxox[baprs]-[A-Za-z0-9-]{10,}/g, 'a Slack token'],
162
+ [/\bsk-(proj-|ant-)?[A-Za-z0-9_-]{32,}/g, 'an AI service API key'],
163
+ ];
164
+ 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);
165
+ 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);
166
+ each(/data:image\/[a-z+]+;base64,[A-Za-z0-9+/=]{8000,}/g, m => add('✗', m.index, m.index + m[0].length, `a ${Math.round(m[0].length * 0.75 / 1024)} KB base64 image in code: put it in an asset file`), text);
167
+ if (expoSdk >= 56 && deps['expo-router']) {
168
+ 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)`));
169
+ }
170
+
171
+ // warnings: likely mistakes, which an app's own components can make right
172
+ each(/<\s*(Pressable|TouchableOpacity|TouchableHighlight|TouchableWithoutFeedback|TouchableNativeFeedback)\b/g, m => {
173
+ const end = endOf(code, m.index);
174
+ const tag = code.slice(m.index, end + 1);
175
+ if (/\{\s*\.\.\./.test(tag) || /\baccessible\s*=\s*\{\s*false\s*\}/.test(tag) || /onPress\s*=\s*\{\s*Keyboard\.dismiss\s*\}/.test(tag)) return;
176
+ const missing = [!/\b(accessibilityLabel|aria-label|accessibilityLabelledBy)\b/.test(tag) && 'accessibilityLabel', !/\b(accessibilityRole|role)\s*=/.test(tag) && 'accessibilityRole'].filter(Boolean);
177
+ if (missing.length) add('!', m.index, end, `<${m[1]}> without ${missing.join(' and ')}: screen readers can't tell what it does`);
178
+ });
179
+ each(/\bDimensions\s*\.\s*get\s*\(/g, m => add('!', m.index, null, "Dimensions.get doesn't update on rotation or resizing: use useWindowDimensions()"));
180
+ 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'));
181
+ 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'));
182
+ 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'));
183
+ each(/\bcatch\s*(\([^)]*\))?\s*\{|\.catch\(\s*(\(\s*\w*\s*\)|\w+)\s*=>\s*\{/g, m => {
184
+ const open = m.index + m[0].length - 1;
185
+ const close = endOf(code, open);
186
+ 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');
187
+ });
188
+ each(/\buse(Layout)?Effect\s*\(/g, m => {
189
+ const open = m.index + m[0].length - 1;
190
+ const close = endOf(code, open);
191
+ const body = code.slice(open, close);
192
+ const t = timers.exec(body);
193
+ 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));
194
+ const p = ASK.exec(body);
195
+ 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));
196
+ const l = listeners.exec(body);
197
+ 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));
198
+ });
199
+ each(/\bconsole\s*\.\s*log\s*\(/g, m => add('!', m.index, null, 'console.log left in: remove it, or use the app\'s logger'));
200
+ 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'));
201
+ each(/\bAccessibilityInfo\s*\.\s*setAccessibilityFocus\s*\(/g, m => add('!', m.index, null, 'AccessibilityInfo.setAccessibilityFocus is deprecated: use sendAccessibilityEvent'));
202
+ // platform guidelines: text, back, screen readers, tap areas, permissions, motion
203
+ 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`); });
204
+ 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`); });
205
+ 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'));
206
+ 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'));
207
+ 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'));
208
+ 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'));
209
+ each(/\bReduceMotion\s*\.\s*Never\b/g, m => add('!', m.index, null, 'ReduceMotion.Never ignores the user\'s Reduce Motion setting: let decoration stop'));
210
+ 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`); });
211
+ each(/<\s*([A-Z][\w.]*)\b/g, m => {
212
+ const end = endOf(code, m.index);
213
+ const tag = code.slice(m.index, end + 1);
214
+ const at = re => m.index + Math.max(tag.search(re), 0);
215
+ const role = /\b(?:accessibilityRole|role)\s*=\s*\{?\s*["'](switch|checkbox|radio|tab|togglebutton)["']/.exec(tag);
216
+ 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`);
217
+ if (m[1] === 'Modal' && !/\bonRequestClose\b/.test(tag)) add('!', m.index, null, 'a Modal without onRequestClose: Android\'s back button can\'t close it');
218
+ 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');
219
+ 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');
220
+ const style = TOUCHABLE.test(m[1]) && !/\b(hitSlop|minWidth|minHeight)\b/.test(tag) && /\bstyle\s*=\s*\{\{([^{}]*)\}\}/.exec(tag);
221
+ const sizes = style ? [...style[1].matchAll(/\b(?:width|height)\s*:\s*(\d+(?:\.\d+)?)(?![\w.%])/g)].map(s => Number(s[1])) : [];
222
+ 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`);
223
+ });
224
+ 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'));
225
+ // a file that asks for a permission but never handles one the system won't ask for again
226
+ const ask = ASK.exec(code);
227
+ 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()');
228
+ if (major('react') >= 19) {
229
+ each(/\bforwardRef\s*[<(]/g, m => add('!', m.index, null, 'forwardRef isn\'t needed in React 19: take ref as a prop'));
230
+ each(/<\s*[\w.]+\.Provider\b/g, m => add('!', m.index, null, 'React 19 renders a context directly: <SomeContext value={…}> instead of .Provider'));
231
+ }
232
+ 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'));
233
+ 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/*'));
234
+ if (ts) {
235
+ each(/@ts-ignore\b/g, m => add('!', m.index, null, '@ts-ignore hides a type error: fix the type instead'), text);
236
+ // in a type, not in JSX text ("Note: any change")
237
+ 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'));
238
+ }
239
+ return out;
240
+ }
241
+
242
+ // the 1-based line of index i
243
+ function lineAt(code, i) {
244
+ let n = 1;
245
+ for (let j = code.indexOf('\n'); j !== -1 && j < i; j = code.indexOf('\n', j + 1)) n++;
246
+ return n;
247
+ }
248
+
249
+ for (const [file, lines] of changed) {
250
+ let text;
251
+ try { text = fs.readFileSync(path.join(root, file), 'utf8'); } catch { continue; }
252
+ const rows = text.split('\n');
253
+ const starts = [0];
254
+ for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) starts.push(i + 1);
255
+ 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; };
256
+ for (const f of check(file, text)) {
257
+ const from = line(f.at);
258
+ const to = line(f.end);
259
+ const touched = lines === 'all' || [...Array(to - from + 1).keys()].some(k => lines.has(from + k));
260
+ const at = f.line || from;
261
+ // on the line, or in a comment on the line above
262
+ const above = /^\s*(\/\/|\/\*|\{\s*\/\*)/.test(rows[at - 2] || '') ? at - 1 : 0;
263
+ const okAt = [at, above].find(n => n && /amk-ok\b/.test(rows[n - 1]));
264
+ const ok = okAt && /amk-ok(?:\s+(\d{4}-\d{2}-\d{2}))?\s*:\s*(\S.*?)\s*(\*\/\s*\}?)?\s*$/.exec(rows[okAt - 1]);
265
+ let message = f.message;
266
+ if (ok) {
267
+ const since = okSince(file, okAt, ok[1]);
268
+ // kept: listed when its own lines changed; over two weeks old, asked again whenever its file changes
269
+ if (Date.parse(today) - Date.parse(since) <= 14 * DAY) { if (touched) kept.push(`${file}:${at}: ${ok[2]} (${since})`); continue; }
270
+ message = `kept with amk-ok since ${since}, over two weeks, and its file changed again: ${f.message}. The user's reason then: ${ok[2]}`;
271
+ } else if (!touched) continue;
272
+ if (!findings.some(x => x.where === `${file}:${at}` && x.message === message)) findings.push({ ...f, message, where: `${file}:${at}` });
273
+ }
274
+ }
275
+
276
+ // ---------- once for the app: an error boundary somewhere ----------
277
+ let boundary = true;
278
+ if (changed.size) {
279
+ boundary = false;
280
+ const files = [...(git('ls-files') || '').split('\n'), ...changed.keys()].filter(f => f && source(f));
281
+ for (const f of new Set(files)) {
282
+ try {
283
+ if (/componentDidCatch|getDerivedStateFromError|ErrorBoundary|Sentry\s*\.\s*wrap\b/.test(fs.readFileSync(path.join(root, f), 'utf8'))) { boundary = true; break; }
284
+ } catch {}
285
+ }
286
+ }
287
+
288
+ // ---------- report ----------
289
+ // by file, then line
290
+ const order = w => { const [, file, n] = /^(.*):(\d+)$/.exec(w); return [file, Number(n)]; };
291
+ 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; });
292
+ const problems = findings.filter(f => f.level === '✗');
293
+ const warnings = findings.filter(f => f.level === '!');
294
+ const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
295
+ if (!changed.size) console.log(`rn-check: no changed source files since ${since}`);
296
+ else if (!findings.length) console.log(`rn-check: nothing to report in the lines changed since ${since}`);
297
+ else console.log(`rn-check: ${plural(problems.length, 'problem')}, ${plural(warnings.length, 'warning')} in the lines changed since ${since}`);
298
+ for (const f of [...problems, ...warnings]) console.log(` ${f.level} ${f.where} ${f.message}`);
299
+ 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`);
300
+ if (kept.length) console.log(` kept with amk-ok: ${[...new Set(kept)].join('; ')}`);
301
+ if (problems.length) {
302
+ 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.`);
303
+ 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.');
304
+ }
305
+ if (warnings.length || !boundary) console.log(' Fix each ! in the code this task changed, or tell the user why it stays.');
306
+ process.exit(problems.length ? 1 : 0);
@@ -416,6 +416,11 @@ quick() {
416
416
  cat "$evidence/lint.log" "$evidence/typecheck.log" "$evidence/test.log" 2> /dev/null | sed -n -E '/^(lint|typecheck|test): /,/^[^ ]/p' | head -n 20
417
417
  status=1
418
418
  fi
419
+ # React Native mistakes in the lines this branch changed (the app's rules list them): its problems fail quick, its
420
+ # warnings don't
421
+ node scripts/amk/rn-check.js > "$evidence/rn-check.log" 2>&1 || status=1
422
+ head -n 40 "$evidence/rn-check.log"
423
+ [ "$(wc -l < "$evidence/rn-check.log")" -le 40 ] || echo " … all of it in ${evidence#"$root"/}/rn-check.log"
419
424
  }
420
425
 
421
426
  ios() {