agentic-mobile-kit 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,15 +21,31 @@ npx agentic-mobile-kit doctor
21
21
 
22
22
  `init` never overwrites your files. It adds its section to an existing `AGENTS.md` between `KIT` markers, and it's safe to run again. Undo it with git.
23
23
 
24
+ ## Update or remove it
25
+
26
+ ```sh
27
+ npx agentic-mobile-kit@latest sync # update the kit's files; your own changes to them are merged in
28
+ npx agentic-mobile-kit uninstall # remove the kit; files you changed are kept and listed
29
+ ```
30
+
31
+ Both need a clean working tree, and both leave the result for you to review with `git diff`.
32
+
33
+ `sync` reports what it updated, added, removed and merged. If you and the kit changed the same lines, the file gets `<<<<<<<` conflict markers to resolve. The docs your team filled in (`docs/ai/product.md`, `tech.md`, `structure.md`, `conventions.md`) are never changed.
34
+
35
+ Installs older than 0.4.0 don't record which kit version made them, so their first `sync` or `uninstall` needs `--from <version>`, for example `--from 0.3.0`. That version can only be a guess, so `sync` doesn't merge on top of it: every file that matches neither version gets conflict markers instead.
36
+
24
37
  ## What it adds
25
38
 
26
39
  - **Context for every AI tool:** `AGENTS.md` (plus a one-line `CLAUDE.md`), `docs/ai/` (product, tech, structure, conventions, decisions, known issues, React Native rules) and spec templates in `specs/_templates/`.
27
- - **Workflows:** the skills `m-feature`, `m-bugfix`, `m-continue`, `m-pause` and `m-review`. Invoke them with `/m-feature` in Claude Code and Antigravity, or `$m-feature` in Codex. Also Callstack's React Native skills.
40
+ - **Workflows:** the skills `m-feature`, `m-bugfix`, `m-continue`, `m-pause`, `m-review`, `m-release` and `m-learn`. Invoke them with `/m-feature` in Claude Code and Antigravity, or `$m-feature` in Codex. Also Callstack's React Native skills.
28
41
  - **Guardrails in each tool:** a guard hook that blocks destructive commands and secret files, a stop hook that asks for a handoff update, permission rules and a read-only `m-reviewer` subagent, generated with rulesync.
42
+ - **Releases:** `m-release` writes `CHANGELOG.md` from real commits with git-cliff, plus store and client notes, then runs `scripts/ai/release-check.js`, which catches what store review would reject. A version tag starts signed builds on Codemagic (`codemagic.yaml`, one-time setup in `docs/ai/codemagic.md`).
29
43
  - **Checks no tool can skip:** git hooks (secrets, signing files, broken Xcode project files, lint, typecheck, tests) and GitHub Actions CI (lint, typecheck, tests, secret scan, PR size, Android and iOS builds).
30
44
 
31
45
  Work continues across tools and machines through `specs/<id>/progress.md`: run `m-pause` in one tool, then `m-continue` in another.
32
46
 
47
+ For the day-to-day workflow, what's enforced, and a 1-hour training plan, see the [team guide](docs/team-guide.md).
48
+
33
49
  ## License
34
50
 
35
51
  MIT
package/bin/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  const { version } = require('../package.json');
3
- const { init, printSummary, InitError, TOOLS } = require('../lib/init');
3
+ const { init, sync, uninstall, printSummary, printSync, printUninstall, InitError, TOOLS } = require('../lib/init');
4
4
  const { doctor, printDoctor } = require('../lib/doctor');
5
5
 
6
6
  const [cmd, ...rest] = process.argv.slice(2);
@@ -13,27 +13,41 @@ const help = `agentic-mobile-kit ${version}
13
13
 
14
14
  Usage:
15
15
  npx agentic-mobile-kit init [--tools claude,codex,antigravity] [--pm yarn|npm|pnpm|bun]
16
+ npx agentic-mobile-kit sync [--from <version>]
17
+ npx agentic-mobile-kit uninstall [--from <version>]
16
18
  npx agentic-mobile-kit doctor
17
19
 
18
20
  Commands:
19
- init Install the kit into a bare React Native project (run in the app's root).
20
- doctor Check the project and this machine, with a fix for each problem.
21
+ init Install the kit into a bare React Native project (run in the app's root).
22
+ sync Update the kit's files to this version. Your own changes to them are merged in, not lost.
23
+ uninstall Remove the kit's files and sections. Files you changed are kept and listed.
24
+ doctor Check the project and this machine, with a fix for each problem.
21
25
 
22
26
  Options:
23
27
  --tools AI tools your team uses: ${Object.keys(TOOLS).join(', ')} (default: claude,codex,antigravity)
24
- --pm Package manager, if it can't be detected from the lockfile`;
28
+ --pm Package manager, if it can't be detected from the lockfile
29
+ --from The kit version that installed the project; needed only for installs made before 0.4.0`;
30
+
31
+ // init, sync and uninstall stop with a plain message when the project isn't ready for them
32
+ function run(name, fn) {
33
+ try { fn(); } catch (e) {
34
+ if (!(e instanceof InitError)) throw e;
35
+ console.error(`${name} stopped: ${e.message}`);
36
+ process.exitCode = 1;
37
+ }
38
+ }
25
39
 
26
40
  if (cmd === '--version' || cmd === '-v') {
27
41
  console.log(version);
28
42
  } else if (cmd === 'init') {
29
- try {
43
+ run('init', () => {
30
44
  const tools = flag('tools') ? flag('tools').split(',').map(s => s.trim()).filter(Boolean) : undefined;
31
45
  printSummary(init(process.cwd(), { tools, pm: flag('pm') }));
32
- } catch (e) {
33
- if (!(e instanceof InitError)) throw e;
34
- console.error(`init stopped: ${e.message}`);
35
- process.exitCode = 1;
36
- }
46
+ });
47
+ } else if (cmd === 'sync') {
48
+ run('sync', () => printSync(sync(process.cwd(), { from: flag('from'), pm: flag('pm') })));
49
+ } else if (cmd === 'uninstall') {
50
+ run('uninstall', () => printUninstall(uninstall(process.cwd(), { from: flag('from'), pm: flag('pm') })));
37
51
  } else if (cmd === 'doctor') {
38
52
  if (printDoctor(doctor(process.cwd())) > 0) process.exitCode = 1;
39
53
  } else {
package/lib/init.js CHANGED
@@ -1,13 +1,21 @@
1
1
  'use strict';
2
2
  // `agentic-mobile-kit init`: installs the kit into a bare React Native project.
3
- // Never overwrites existing files; merges AGENTS.md / CLAUDE.md; git is the backup (clean tree required).
3
+ // `sync` updates an installed project to this kit version; `uninstall` removes the kit.
4
+ // All three need a clean working tree, so git is the backup for everything they touch.
4
5
  const fs = require('fs');
6
+ const os = require('os');
5
7
  const path = require('path');
6
8
  const { execFileSync, spawnSync } = require('child_process');
7
9
 
10
+ const KIT_VERSION = require('../package.json').version;
8
11
  const TEMPLATE = path.join(__dirname, '..', 'stacks', 'react-native', 'template');
9
12
  const RULESYNC = 'rulesync@27.0.0';
10
13
  const MARKERS = /<!-- KIT:START[\s\S]*?<!-- KIT:END[^>]*-->\n?/;
14
+ // files with {{PLACEHOLDERS}} filled in from the project
15
+ const FILLED = ['AGENTS.md', 'codemagic.yaml'];
16
+ // docs each team rewrites for its app: sync replaces them only while they're untouched, and never merges into them
17
+ const PROJECT_DOCS = ['product', 'tech', 'structure', 'conventions'].map(n => `docs/ai/${n}.md`);
18
+ const HOOKS_CMD = 'git config core.hooksPath .githooks || true';
11
19
 
12
20
  // tool name -> rulesync targets
13
21
  const TOOLS = {
@@ -27,6 +35,11 @@ function git(cwd, ...args) {
27
35
  }
28
36
 
29
37
  function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); }
38
+ const readIf = file => { try { return fs.readFileSync(file, 'utf8'); } catch { return null; } };
39
+ function isLink(p) { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } }
40
+
41
+ // when the kit runs under npx, npm_config_* variables (e.g. the outer --package) would leak into the npx/npm it starts
42
+ const cleanEnv = () => Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^npm_(config|package|lifecycle)_/i.test(k)));
30
43
 
31
44
  function installedVersion(cwd, pkg, declared) {
32
45
  try { return readJson(path.join(cwd, 'node_modules', pkg, 'package.json')).version; } catch {}
@@ -55,10 +68,10 @@ function checkProject(cwd) {
55
68
  throw new InitError('This folder is not a git repository. Run "git init" and commit first; git is how init can be undone.');
56
69
  }
57
70
  if (git(cwd, 'status', '--porcelain')) {
58
- throw new InitError('You have uncommitted changes. Commit or stash them first, so init can be undone with git.');
71
+ throw new InitError('You have uncommitted changes. Commit or stash them first, so this can be undone with git.');
59
72
  }
60
73
  const pkgFile = path.join(cwd, 'package.json');
61
- if (!fs.existsSync(pkgFile)) throw new InitError('No package.json here. Run init in the root of your React Native app.');
74
+ if (!fs.existsSync(pkgFile)) throw new InitError('No package.json here. Run this in the root of your React Native app.');
62
75
  const pkg = readJson(pkgFile);
63
76
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
64
77
  if (!deps['react-native']) throw new InitError('This is not a React Native project (no "react-native" dependency).');
@@ -68,7 +81,7 @@ function checkProject(cwd) {
68
81
  return { pkg, deps };
69
82
  }
70
83
 
71
- // all template files, relative paths, including dotfiles
84
+ // all files under dir, as relative paths, including dotfiles
72
85
  function templateFiles(dir = TEMPLATE, base = '') {
73
86
  return fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => {
74
87
  const rel = path.join(base, e.name);
@@ -76,17 +89,23 @@ function templateFiles(dir = TEMPLATE, base = '') {
76
89
  });
77
90
  }
78
91
 
92
+ // the app's bundle ID, for Codemagic signing; React Native's template derives it from the product name
93
+ function iosBundleId(cwd) {
94
+ const proj = fs.readdirSync(path.join(cwd, 'ios')).find(f => f.endsWith('.xcodeproj')) || '';
95
+ let pbx = '';
96
+ try { pbx = fs.readFileSync(path.join(cwd, 'ios', proj, 'project.pbxproj'), 'utf8'); } catch {}
97
+ const ids = [...pbx.matchAll(/PRODUCT_BUNDLE_IDENTIFIER = "?([^";]+)"?;/g)].map(m => m[1]).filter(id => !/Tests$/.test(id));
98
+ const id = ids.find(i => !i.includes('$(')) || ids[0] || 'com.example.app';
99
+ return id.replace(/\$\(PRODUCT_NAME(:rfc1034identifier)?\)/, proj.replace(/\.xcodeproj$/, '').replace(/[^A-Za-z0-9.-]/g, '-'));
100
+ }
101
+
79
102
  function fillPlaceholders(text, values) {
80
103
  return text.replace(/\{\{(\w+)\}\}/g, (m, k) => (k in values ? values[k] : m));
81
104
  }
82
105
 
83
- function init(cwd, opts = {}) {
84
- const { pkg, deps } = checkProject(cwd);
85
- const pm = detectPm(cwd, opts.pm);
86
- const tools = opts.tools || TESTED;
87
- for (const t of tools) if (!TOOLS[t]) throw new InitError(`Unknown tool "${t}". Choose from: ${Object.keys(TOOLS).join(', ')}.`);
88
-
89
- const values = {
106
+ function projectValues(cwd, pkg, deps, pm) {
107
+ return {
108
+ KIT_VERSION,
90
109
  APP_NAME: pkg.name || path.basename(cwd),
91
110
  RN_VERSION: installedVersion(cwd, 'react-native', deps['react-native']),
92
111
  REACT_VERSION: installedVersion(cwd, 'react', deps.react),
@@ -94,96 +113,275 @@ function init(cwd, opts = {}) {
94
113
  NODE_VERSION: (pkg.engines && pkg.engines.node) || `${process.versions.node.split('.')[0]}`,
95
114
  PM: pm.name,
96
115
  PM_RUN: pm.run,
116
+ IOS_BUNDLE_ID: iosBundleId(cwd),
97
117
  };
98
- const report = { created: [], merged: [], skipped: [] };
118
+ }
99
119
 
100
- // 1. template files (never overwrite)
101
- for (const rel of templateFiles()) {
102
- const src = path.join(TEMPLATE, rel);
103
- const dest = path.join(cwd, rel);
104
- const kitText = () => fillPlaceholders(fs.readFileSync(src, 'utf8'), values);
120
+ // a template file's text as the kit writes it into this project
121
+ function kitText(templateDir, rel, values, targets) {
122
+ const text = fs.readFileSync(path.join(templateDir, rel), 'utf8');
123
+ if (FILLED.includes(rel)) return fillPlaceholders(text, values);
124
+ if (rel === 'rulesync.jsonc') return setTargets(text, targets);
125
+ return text;
126
+ }
105
127
 
106
- if (rel === 'AGENTS.md' && fs.existsSync(dest)) {
107
- const current = fs.readFileSync(dest, 'utf8');
108
- const section = kitText();
109
- const next = MARKERS.test(current) ? current.replace(MARKERS, section) : `${current.replace(/\n*$/, '\n\n')}${section}`;
110
- if (next !== current) { fs.writeFileSync(dest, next); report.merged.push(rel); } else report.skipped.push(rel);
111
- continue;
112
- }
113
- if (rel === 'CLAUDE.md' && fs.existsSync(dest)) {
114
- const current = fs.readFileSync(dest, 'utf8');
115
- if (/^@AGENTS\.md\s*$/m.test(current)) report.skipped.push(rel);
116
- else { fs.writeFileSync(dest, `${current.replace(/\n*$/, '\n\n')}@AGENTS.md\n`); report.merged.push(rel); }
117
- continue;
118
- }
119
- if (fs.existsSync(dest)) { report.skipped.push(rel); continue; }
128
+ const setTargets = (text, targets) => text.replace(/"targets":\s*\[[^\]]*\]/, () => `"targets": ${JSON.stringify(targets)}`);
129
+ // a project file's text for comparing with the kit's: the targets line is the project's own (init rewrites it)
130
+ const projectText = (cwd, rel, targets) => {
131
+ const text = readIf(path.join(cwd, rel));
132
+ return text !== null && rel === 'rulesync.jsonc' ? setTargets(text, targets) : text;
133
+ };
134
+ // a function replacement, so "$" in the kit's text is never read as a replacement pattern
135
+ const mergeAgents = (current, section) => (MARKERS.test(current) ? current.replace(MARKERS, () => section) : `${current.replace(/\n*$/, '\n\n')}${section}`);
136
+ const mergeClaude = current => (/^@AGENTS\.md\s*$/m.test(current) ? current : `${current.replace(/\n*$/, '\n\n')}@AGENTS.md\n`);
120
137
 
121
- fs.mkdirSync(path.dirname(dest), { recursive: true });
122
- if (rel === 'AGENTS.md') fs.writeFileSync(dest, kitText());
123
- else fs.copyFileSync(src, dest);
124
- // npm doesn't always keep the executable bit, and git silently skips non-executable hooks
125
- const executable = rel.startsWith(`.githooks${path.sep}`) || /\.(sh|js)$/.test(rel) && rel.startsWith(`scripts${path.sep}`);
126
- fs.chmodSync(dest, executable ? 0o755 : 0o644);
127
- report.created.push(rel);
138
+ function writeKitFile(cwd, rel, text) {
139
+ const dest = path.join(cwd, rel);
140
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
141
+ fs.writeFileSync(dest, text);
142
+ // npm doesn't always keep the executable bit, and git silently skips non-executable hooks
143
+ const executable = rel.startsWith(`.githooks${path.sep}`) || /\.(sh|js)$/.test(rel) && rel.startsWith(`scripts${path.sep}`);
144
+ fs.chmodSync(dest, executable ? 0o755 : 0o644);
145
+ }
146
+
147
+ // the tools a project was set up for, read back from its rulesync targets
148
+ function installedTools(cwd) {
149
+ const m = (readIf(path.join(cwd, 'rulesync.jsonc')) || '').match(/"targets":\s*\[([^\]]*)\]/);
150
+ let targets = [];
151
+ try { targets = JSON.parse(`[${m ? m[1] : ''}]`); } catch {}
152
+ const tools = Object.keys(TOOLS).filter(t => TOOLS[t].every(x => targets.includes(x)));
153
+ return tools.length ? tools : TESTED;
154
+ }
155
+
156
+ // the kit version that installed the project: recorded in AGENTS.md since 0.4.0, or given with --from.
157
+ // A --from version is a guess (installs may predate it), so it isn't trusted as a merge base.
158
+ function oldTemplate(agents, opts) {
159
+ if (opts.fromDir) return { from: opts.from || 'old', dir: opts.fromDir, exact: !opts.from };
160
+ const from = opts.from || (agents.match(/KIT:START agentic-mobile-kit (\d[^\s>]*)/) || [])[1];
161
+ if (!from) {
162
+ throw new InitError('This project doesn\'t record which kit version installed it (versions before 0.4.0 didn\'t). '
163
+ + 'Pass it with --from, for example --from 0.3.0; the commit that added or last updated the kit usually says.');
128
164
  }
165
+ const [a, b] = [from, KIT_VERSION].map(v => v.split('.').map(n => parseInt(n, 10) || 0));
166
+ const newer = a.findIndex((n, i) => n !== b[i]);
167
+ if (newer >= 0 && a[newer] > b[newer]) throw new InitError(`This project uses kit ${from}, which is newer than this one (${KIT_VERSION}). Use the latest: npx agentic-mobile-kit@latest`);
168
+ return { from, dir: from === KIT_VERSION ? TEMPLATE : fetchTemplate(from), exact: !opts.from };
169
+ }
170
+
171
+ function fetchTemplate(version) {
172
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'amk-kit-'));
173
+ const r = spawnSync('npm', ['pack', `agentic-mobile-kit@${version}`, '--pack-destination', dir, '--silent'], { cwd: dir, env: cleanEnv(), encoding: 'utf8' });
174
+ if (r.status !== 0) throw new InitError(`Couldn't download agentic-mobile-kit@${version} from npm: ${(r.stderr || '').trim().split('\n').pop()}`);
175
+ execFileSync('tar', ['-xzf', path.join(dir, r.stdout.trim().split('\n').pop()), '-C', dir]);
176
+ return path.join(dir, 'package', 'stacks', 'react-native', 'template');
177
+ }
178
+
179
+ // three-way merge: your changes and the kit's changes since the old version, both kept
180
+ function merge3(current, base, kitNew, from) {
181
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'amk-merge-'));
182
+ const files = [current, base, kitNew].map((text, i) => { const f = path.join(dir, String(i)); fs.writeFileSync(f, text); return f; });
183
+ const r = spawnSync('git', ['merge-file', '-p', '-L', 'your version', '-L', `kit ${from}`, '-L', `kit ${KIT_VERSION}`, ...files], { encoding: 'utf8' });
184
+ fs.rmSync(dir, { recursive: true, force: true });
185
+ if (r.status === null || r.status < 0 || r.status > 127) throw new Error(`git merge-file failed: ${r.stderr}`);
186
+ return { text: r.stdout, conflicts: r.status };
187
+ }
188
+
189
+ // steps 2–6, shared by init and sync
190
+ function finish(cwd, { pkg, deps, tools, skipGenerate }) {
191
+ const done = { created: [], merged: [], skipped: [] };
129
192
 
130
193
  // 2. skills folder links for tools that don't read .agents/skills
131
- const links = [['.claude/skills', 'claude'], ['.kiro/skills', 'kiro']];
132
- for (const [link, tool] of links) {
194
+ for (const [link, tool] of [['.claude/skills', 'claude'], ['.kiro/skills', 'kiro']]) {
133
195
  if (!tools.includes(tool)) continue;
134
196
  const dest = path.join(cwd, link);
135
- if (fs.existsSync(dest) || isLink(dest)) { report.skipped.push(link); continue; }
197
+ if (fs.existsSync(dest) || isLink(dest)) { done.skipped.push(link); continue; }
136
198
  fs.mkdirSync(path.dirname(dest), { recursive: true });
137
199
  fs.symlinkSync('../.agents/skills', dest);
138
- report.created.push(`${link} -> .agents/skills`);
200
+ done.created.push(`${link} -> .agents/skills`);
139
201
  }
140
202
 
141
203
  // 3. .gitignore: keep secrets out of git
142
204
  const gi = path.join(cwd, '.gitignore');
143
- const giText = fs.existsSync(gi) ? fs.readFileSync(gi, 'utf8') : '';
205
+ const giText = readIf(gi) || '';
144
206
  const missing = ['.env', '.env.*', '!.env.example', '.ai/'].filter(l => !giText.split('\n').includes(l));
145
207
  if (missing.length) {
146
208
  fs.writeFileSync(gi, `${giText.replace(/\n*$/, giText ? '\n' : '')}\n# agentic-mobile-kit: secrets stay out of git; .ai/ holds local evidence (screenshots, logs)\n${missing.join('\n')}\n`);
147
- report.merged.push('.gitignore');
209
+ done.merged.push('.gitignore');
148
210
  }
149
211
 
150
212
  // 4. package.json scripts: typecheck, and hooks path on install (never overwrite existing scripts)
151
- const pkgFile = path.join(cwd, 'package.json');
152
213
  const scripts = (pkg.scripts = pkg.scripts || {});
153
214
  let pkgChanged = false;
154
215
  // only TypeScript projects get typecheck: tsc fails ("no inputs") in JavaScript apps that merely have typescript installed
155
216
  const hasTs = git(cwd, 'ls-files', '*.ts', '*.tsx').split('\n').some(f => f && !f.endsWith('.d.ts'));
156
217
  if (!scripts.typecheck && deps.typescript && hasTs) { scripts.typecheck = 'tsc --noEmit'; pkgChanged = true; }
157
- const hooksCmd = 'git config core.hooksPath .githooks || true';
158
218
  if (!(scripts.postinstall || '').includes('core.hooksPath')) {
159
219
  // parentheses keep the existing script's failure behavior: `a && b || true` would hide a failing `a`
160
- scripts.postinstall = scripts.postinstall ? `${scripts.postinstall} && (${hooksCmd})` : hooksCmd;
220
+ scripts.postinstall = scripts.postinstall ? `${scripts.postinstall} && (${HOOKS_CMD})` : HOOKS_CMD;
161
221
  pkgChanged = true;
162
222
  }
163
- if (pkgChanged) { fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`); report.merged.push('package.json (scripts)'); }
223
+ if (pkgChanged) { fs.writeFileSync(path.join(cwd, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`); done.merged.push('package.json (scripts)'); }
164
224
 
165
225
  // 5. activate the git hooks now
166
226
  git(cwd, 'config', 'core.hooksPath', '.githooks');
167
227
 
168
228
  // 6. tool configs for the chosen tools (permissions, hooks, subagents)
169
229
  const rsFile = path.join(cwd, 'rulesync.jsonc');
170
- const rs = fs.readFileSync(rsFile, 'utf8');
171
- const targets = tools.flatMap(t => TOOLS[t]);
172
- fs.writeFileSync(rsFile, rs.replace(/"targets":\s*\[[^\]]*\]/, `"targets": ${JSON.stringify(targets)}`));
230
+ fs.writeFileSync(rsFile, setTargets(fs.readFileSync(rsFile, 'utf8'), tools.flatMap(t => TOOLS[t])));
173
231
  let generated = true;
174
232
  let generateError = '';
175
- if (!opts.skipGenerate) {
176
- // when init itself runs under npx, npm_config_* variables (e.g. the outer --package) would leak into this npx
177
- const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^npm_(config|package|lifecycle)_/i.test(k)));
178
- const r = spawnSync('npx', ['-y', RULESYNC, 'generate'], { cwd, env, encoding: 'utf8' });
233
+ if (!skipGenerate) {
234
+ const r = spawnSync('npx', ['-y', RULESYNC, 'generate'], { cwd, env: cleanEnv(), encoding: 'utf8' });
179
235
  generated = r.status === 0;
180
236
  if (!generated) generateError = `${r.stderr || ''}${r.stdout || ''}`.trim().split('\n').slice(-5).join('\n');
181
237
  }
238
+ return { done, generated, generateError };
239
+ }
240
+
241
+ function init(cwd, opts = {}) {
242
+ const { pkg, deps } = checkProject(cwd);
243
+ const pm = detectPm(cwd, opts.pm);
244
+ const tools = opts.tools || TESTED;
245
+ for (const t of tools) if (!TOOLS[t]) throw new InitError(`Unknown tool "${t}". Choose from: ${Object.keys(TOOLS).join(', ')}.`);
246
+ const template = opts.template || TEMPLATE;
247
+ const values = projectValues(cwd, pkg, deps, pm);
248
+ const targets = tools.flatMap(t => TOOLS[t]);
249
+ const report = { created: [], merged: [], skipped: [] };
250
+
251
+ // 1. template files (never overwrite)
252
+ for (const rel of templateFiles(template)) {
253
+ const dest = path.join(cwd, rel);
254
+ const text = kitText(template, rel, values, targets);
255
+ const current = readIf(dest);
256
+ if (current !== null && (rel === 'AGENTS.md' || rel === 'CLAUDE.md')) {
257
+ const next = rel === 'AGENTS.md' ? mergeAgents(current, text) : mergeClaude(current);
258
+ if (next !== current) { fs.writeFileSync(dest, next); report.merged.push(rel); } else report.skipped.push(rel);
259
+ continue;
260
+ }
261
+ if (fs.existsSync(dest)) { report.skipped.push(rel); continue; }
262
+ writeKitFile(cwd, rel, text);
263
+ report.created.push(rel);
264
+ }
182
265
 
266
+ const { done, generated, generateError } = finish(cwd, { pkg, deps, tools, skipGenerate: opts.skipGenerate });
267
+ for (const k of Object.keys(report)) report[k].push(...done[k]);
183
268
  return { report, values, tools, generated, generateError };
184
269
  }
185
270
 
186
- function isLink(p) { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } }
271
+ function sync(cwd, opts = {}) {
272
+ const { pkg, deps } = checkProject(cwd);
273
+ const agents = readIf(path.join(cwd, 'AGENTS.md'));
274
+ if (!agents || !MARKERS.test(agents)) throw new InitError('The kit isn\'t installed here (AGENTS.md has no KIT section). Run init instead.');
275
+ const { from, dir: oldDir, exact } = oldTemplate(agents, opts);
276
+ const template = opts.template || TEMPLATE;
277
+ const values = projectValues(cwd, pkg, deps, detectPm(cwd, opts.pm));
278
+ const tools = installedTools(cwd);
279
+ const targets = tools.flatMap(t => TOOLS[t]);
280
+ const report = { updated: [], added: [], merged: [], conflicts: [], removed: [], kept: [] };
281
+ const newFiles = templateFiles(template);
282
+ const oldFiles = new Set(templateFiles(oldDir));
283
+
284
+ for (const rel of newFiles) {
285
+ const kitNew = kitText(template, rel, values, targets);
286
+ const kitOld = oldFiles.has(rel) ? kitText(oldDir, rel, values, targets) : null;
287
+ const current = projectText(cwd, rel, targets);
288
+ if (rel === 'AGENTS.md' || rel === 'CLAUDE.md') {
289
+ const next = current === null ? kitNew : rel === 'AGENTS.md' ? mergeAgents(current, kitNew) : mergeClaude(current);
290
+ if (next !== current) { fs.writeFileSync(path.join(cwd, rel), next); report.updated.push(rel); }
291
+ continue;
292
+ }
293
+ if (current === null) {
294
+ if (kitOld === null) { writeKitFile(cwd, rel, kitNew); report.added.push(rel); } else report.kept.push(`${rel} (you deleted it)`);
295
+ continue;
296
+ }
297
+ if (current === kitNew) continue;
298
+ if (kitOld === null) { report.kept.push(`${rel} (your own file; the kit now has one with this name)`); continue; }
299
+ if (current === kitOld) { writeKitFile(cwd, rel, kitNew); report.updated.push(rel); continue; }
300
+ if (PROJECT_DOCS.includes(rel)) continue;
301
+ // without an exact base, an old unchanged file would look like your edit and be kept: show every difference instead
302
+ const { text, conflicts } = merge3(current, exact ? kitOld : '', kitNew, from);
303
+ writeKitFile(cwd, rel, text);
304
+ (conflicts ? report.conflicts : report.merged).push(rel);
305
+ }
306
+ // files the kit no longer ships
307
+ for (const rel of oldFiles) {
308
+ if (newFiles.includes(rel)) continue;
309
+ const current = projectText(cwd, rel, targets);
310
+ if (current === null) continue;
311
+ if (current === kitText(oldDir, 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)`);
312
+ }
313
+
314
+ const { done, generated, generateError } = finish(cwd, { pkg, deps, tools, skipGenerate: opts.skipGenerate });
315
+ report.added.push(...done.created);
316
+ report.updated.push(...done.merged);
317
+ return { report, from, to: KIT_VERSION, tools, generated, generateError };
318
+ }
319
+
320
+ // what rulesync generates from the project's kit sources, regenerated in an empty folder: [[path, text]]
321
+ function generatedFiles(cwd) {
322
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'amk-gen-'));
323
+ fs.cpSync(path.join(cwd, '.rulesync'), path.join(dir, '.rulesync'), { recursive: true });
324
+ fs.copyFileSync(path.join(cwd, 'rulesync.jsonc'), path.join(dir, 'rulesync.jsonc'));
325
+ const r = spawnSync('npx', ['-y', RULESYNC, 'generate'], { cwd: dir, env: cleanEnv(), encoding: 'utf8' });
326
+ if (r.status !== 0) throw new InitError(`Couldn't work out which tool configs rulesync generated: ${`${r.stderr}${r.stdout}`.trim().split('\n').pop()}`);
327
+ const files = templateFiles(dir).filter(f => !f.startsWith(`.rulesync${path.sep}`) && !['rulesync.jsonc', '.gitignore'].includes(f));
328
+ const out = files.map(f => [f, fs.readFileSync(path.join(dir, f), 'utf8')]);
329
+ fs.rmSync(dir, { recursive: true, force: true });
330
+ return out;
331
+ }
332
+
333
+ function uninstall(cwd, opts = {}) {
334
+ const { pkg, deps } = checkProject(cwd);
335
+ const agents = readIf(path.join(cwd, 'AGENTS.md'));
336
+ if (!agents || !MARKERS.test(agents)) throw new InitError('The kit isn\'t installed here (AGENTS.md has no KIT section).');
337
+ const { from, dir: template } = oldTemplate(agents, opts);
338
+ const values = projectValues(cwd, pkg, deps, detectPm(cwd, opts.pm));
339
+ const targets = installedTools(cwd).flatMap(t => TOOLS[t]);
340
+ const report = { removed: [], kept: [], left: [] };
341
+ const remove = rel => { fs.unlinkSync(path.join(cwd, rel)); report.removed.push(rel); };
342
+ // listed before their sources are removed
343
+ const generated = opts.skipGenerate ? [] : generatedFiles(cwd);
344
+
345
+ for (const rel of templateFiles(template)) {
346
+ const current = projectText(cwd, rel, targets);
347
+ if (current === null) continue;
348
+ if (rel === 'AGENTS.md' || rel === 'CLAUDE.md') {
349
+ const rest = rel === 'AGENTS.md' ? current.replace(MARKERS, () => '') : current.replace(/^@AGENTS\.md[ \t]*\n?/m, '');
350
+ if (!rest.trim()) remove(rel);
351
+ else if (rest !== current) { fs.writeFileSync(path.join(cwd, rel), rest.replace(/\n+$/, '\n')); report.removed.push(`${rel} (the kit's part)`); }
352
+ continue;
353
+ }
354
+ if (current === kitText(template, rel, values, targets)) remove(rel); else report.kept.push(rel);
355
+ }
356
+ for (const [rel, text] of generated) {
357
+ const current = readIf(path.join(cwd, rel));
358
+ if (current === null) continue;
359
+ if (current === text) remove(rel); else report.kept.push(`${rel} (also has your own settings; remove the kit's entries by hand)`);
360
+ }
361
+ for (const link of ['.claude/skills', '.kiro/skills']) {
362
+ const p = path.join(cwd, link);
363
+ if (isLink(p) && fs.readlinkSync(p) === '../.agents/skills') { fs.unlinkSync(p); report.removed.push(link); }
364
+ }
365
+ // folders left empty (rmdir refuses non-empty ones)
366
+ const dirs = [...new Set(report.removed.map(r => path.dirname(r.split(' (')[0])))].sort((a, b) => b.length - a.length);
367
+ for (let d of dirs) {
368
+ for (; d && d !== '.'; d = path.dirname(d)) { try { fs.rmdirSync(path.join(cwd, d)); } catch { break; } }
369
+ }
370
+
371
+ // git hooks
372
+ const scripts = pkg.scripts || {};
373
+ const postinstall = scripts.postinstall === HOOKS_CMD ? undefined : (scripts.postinstall || '').replace(` && (${HOOKS_CMD})`, '') || undefined;
374
+ if (postinstall !== scripts.postinstall) {
375
+ if (postinstall) scripts.postinstall = postinstall; else delete scripts.postinstall;
376
+ fs.writeFileSync(path.join(cwd, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`);
377
+ report.removed.push('package.json postinstall (git hooks)');
378
+ }
379
+ try { if (git(cwd, 'config', 'core.hooksPath') === '.githooks') git(cwd, 'config', '--unset', 'core.hooksPath'); } catch {}
380
+
381
+ report.left.push('.gitignore lines for .env files and .ai/ (they keep secrets and local evidence out of git)');
382
+ if (scripts.typecheck === 'tsc --noEmit') report.left.push('the "typecheck" script in package.json');
383
+ return { report, from };
384
+ }
187
385
 
188
386
  function printSummary({ report, values, tools, generated, generateError }, log = console.log) {
189
387
  log(`agentic-mobile-kit installed for ${values.APP_NAME} (React Native ${values.RN_VERSION}, ${values.PM}).`);
@@ -196,7 +394,27 @@ function printSummary({ report, values, tools, generated, generateError }, log =
196
394
  log(' 1. Fill in docs/ai/product.md, tech.md, structure.md and conventions.md for this app.');
197
395
  log(' 2. Commit on a branch and open a PR. Add the "large-pr" label (the vendored skills are large).');
198
396
  log(' 3. Turn on branch protection for main: see docs/branch-protection.md in the kit repo.');
199
- if (tools.includes('codex')) log(' 4. Codex users: open the project in Codex once and approve its hooks (they stay off until approved).');
397
+ log(' 4. Signed store builds on Codemagic: one-time setup in docs/ai/codemagic.md.');
398
+ if (tools.includes('codex')) log(' 5. Codex users: open the project in Codex once and approve its hooks (they stay off until approved).');
399
+ }
400
+
401
+ function printSync({ report, from, to, generated, generateError }, log = console.log) {
402
+ log(`agentic-mobile-kit updated from ${from} to ${to}.`);
403
+ const lines = [
404
+ ['updated', report.updated], ['added', report.added], ['removed', report.removed],
405
+ ['merged with your changes', report.merged], ['CONFLICTS, resolve the <<<<<<< markers', report.conflicts], ['left alone', report.kept],
406
+ ];
407
+ for (const [label, files] of lines) if (files.length) log(` ${label}: ${files.join(', ')}`);
408
+ if (!Object.values(report).some(a => a.length)) log(' Nothing to change.');
409
+ if (!generated) log(` ! could not generate tool configs; run: npx -y ${RULESYNC} generate\n${generateError.replace(/^/gm, ' ')}`);
410
+ log('\nReview it with "git diff", run the checks, then commit on a branch and open a PR.');
411
+ }
412
+
413
+ function printUninstall({ report }, log = console.log) {
414
+ log(`agentic-mobile-kit removed: ${report.removed.length} files and sections.`);
415
+ if (report.kept.length) log(` kept because you changed them: ${report.kept.join(', ')}`);
416
+ for (const l of report.left) log(` left in place: ${l}`);
417
+ log('\nReview it with "git status" and "git diff", then commit. Undo it with git if you change your mind.');
200
418
  }
201
419
 
202
- module.exports = { init, printSummary, InitError, TOOLS };
420
+ module.exports = { init, sync, uninstall, printSummary, printSync, printUninstall, InitError, TOOLS, KIT_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-mobile-kit",
3
- "version": "0.2.1",
3
+ "version": "0.4.0",
4
4
  "description": "One setup for AI-assisted mobile development that works the same in Claude Code, Codex, Cursor, OpenCode, Kiro and Antigravity. Early development.",
5
5
  "license": "MIT",
6
6
  "author": "prakashpro1",
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: m-learn
3
+ description: Turn a mistake or a correction into the smallest lasting fix (a check, a docs line or a skill step) so no tool repeats it, and remove guidance that is no longer true. Run only when the user explicitly invokes m-learn.
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ # m-learn
8
+
9
+ Input: $ARGUMENTS (what went wrong or what the user had to correct; the error text, PR comment or session transcript if there is one).
10
+
11
+ 1. **State the lesson in one sentence:** what happened, what should have happened, and why. The usual causes are missing context, an ignored rule, the wrong command, or a gap in the rules. Quote the evidence, and don't guess what an earlier session did. If the cause isn't clear, ask.
12
+ 2. **Check whether it's already covered.** Search `AGENTS.md`, `docs/ai/` and `.agents/skills/`. If a rule exists and was ignored, writing it again won't help; enforce it instead (step 3.1).
13
+ 3. **Pick the strongest small fix**, in this order:
14
+ 1. A check that runs without anyone remembering it: a lint rule, a test, a git hook, a CI step, a pattern in `scripts/ai/guard.js`, or a rule in `scripts/ai/release-check.js`.
15
+ 2. A known error: add the error text, cause, fix and prevention to `docs/ai/known-issues.md`.
16
+ 3. Project knowledge: one line in the right `docs/ai/` file. Use `conventions.md`, `react-native.md` or `tech.md`, or `decisions.md` with the date and the reason.
17
+ 4. A workflow step: edit the skill that should have caught it.
18
+ 5. `AGENTS.md`: only for a rule every task needs, and keep the file under 150 lines.
19
+
20
+ Make one fix in one place. Don't copy the same rule into several files.
21
+ 4. **Remove what's no longer true** in the file you touched: old versions, renamed scripts, bugs that are fixed. Check versions and paths against the repo before trusting a line.
22
+ 5. **Show that it works.**
23
+ - For a check: show it failing on the old mistake and passing on the fixed code.
24
+ - For docs or a skill: show the diff, and name the task that would have gone differently.
25
+ 6. **This project or every project?** If the lesson applies to any React Native app, say so and draft an issue for the agentic-mobile-kit repo, so every project gets the fix. Ask before opening it.
26
+ 7. **Commit** with a message that starts with `chore(learn):` and ends with `Assisted-by: <tool>/<model>`. That prefix keeps it out of the changelog and easy to find with `git log --grep 'chore(learn)'` in the monthly review. Ask before pushing.
@@ -0,0 +1,3 @@
1
+ # Codex: run this skill only when invoked explicitly ($m-learn), never automatically.
2
+ policy:
3
+ allow_implicit_invocation: false
@@ -0,0 +1,23 @@
1
+ ---
2
+ name: m-release
3
+ description: Prepare a store release - version, changelog and store notes from real commits, release check, release PR, then the tag that starts the signed builds. Run only when the user explicitly invokes m-release.
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ # m-release
8
+
9
+ Input: $ARGUMENTS (the new version such as 1.4.0, or patch, minor or major; anything the client should hear about).
10
+
11
+ 1. **Start clean:** `main`, pulled, with a clean working tree. Find the last release with `git describe --tags --abbrev=0 --match 'v*'`. If there's none, this is the first release.
12
+ 2. **Choose the version.** Show the commits since the last release (`git log --oneline <last tag>..HEAD`). Suggest minor if there's anything new for users, patch for fixes only, and major only if the user asks. Get the user's confirmation, then create the branch `release/v<version>`.
13
+ 3. **Changelog from real commits:** `npx -y git-cliff@2.14.2 --unreleased --tag v<version> --prepend CHANGELOG.md`. If `CHANGELOG.md` doesn't exist yet, use `-o CHANGELOG.md` instead of `--prepend CHANGELOG.md`. Don't add, merge or reword entries by hand. A misleading commit message gets fixed in the notes below, not in the changelog.
14
+ 4. **Store and client notes** go in `release-notes/<version>/`. Write them only from the new changelog section, so every line traces back to an entry. Leave out internal changes (refactors, CI, dependency bumps) unless users notice them.
15
+ - `play-store.txt`: plain text for users, at most 500 characters.
16
+ - `app-store.txt`: plain text for users, at most 4000 characters, with no `<` or `>`.
17
+ - `client.md`: for the client or product owner. Cover what's new, what's fixed, what they should test or do, and known issues.
18
+
19
+ Show all three files to the user and wait for their approval.
20
+ 5. **Version name:** `sh scripts/ai/set-version.sh <version>` sets the iOS and Android version names. Leave build numbers alone when `codemagic.yaml` sets them; otherwise ask whether to bump them. If the script stops because the project ships several apps, ask the user which version each app gets.
21
+ 6. **Release check:** `node scripts/ai/release-check.js`. Show the output. Fix each ✗, asking first when the fix touches native config. List each ! for the user to decide.
22
+ 7. **Release PR:** commit as `Release <version>` with `Assisted-by: <tool>/<model>`. Ask before pushing. Open a PR titled `Release <version>` with the new changelog section and the release-check output.
23
+ 8. **Tag after the merge.** Once the PR is merged, ask the user before tagging. Then run `git switch main && git pull && git tag v<version> && git push origin v<version>`. With Codemagic set up (`docs/ai/codemagic.md`), the tag starts the signed builds, which go to TestFlight and Play's internal track.
@@ -0,0 +1,3 @@
1
+ # Codex: run this skill only when invoked explicitly ($m-release), never automatically.
2
+ policy:
3
+ allow_implicit_invocation: false
@@ -1,5 +1,6 @@
1
1
  #!/bin/sh
2
2
  # agentic-mobile-kit pre-push: typecheck and tests before code leaves the machine.
3
3
  set -eu
4
+ [ -d node_modules ] || { echo "pre-push: dependencies aren't installed; run: sh scripts/ai/install-deps.sh" >&2; exit 1; }
4
5
  sh scripts/ai/pm-run.sh typecheck || { echo "pre-push: fix the type errors above" >&2; exit 1; }
5
6
  CI=true sh scripts/ai/pm-run.sh test || { echo "pre-push: fix the failing tests above" >&2; exit 1; }
@@ -1,4 +1,4 @@
1
- <!-- KIT:START agentic-mobile-kit (edit outside these markers; the kit updates what's inside) -->
1
+ <!-- KIT:START agentic-mobile-kit {{KIT_VERSION}} (edit outside these markers; the kit updates what's inside) -->
2
2
  # {{APP_NAME}}: instructions for AI agents
3
3
 
4
4
  Read by Claude Code (through CLAUDE.md), Codex, Cursor, OpenCode, Kiro and Antigravity. Keep it short; details live in `docs/ai/`.
@@ -18,6 +18,7 @@ Read by Claude Code (through CLAUDE.md), Codex, Cursor, OpenCode, Kiro and Antig
18
18
  | iOS build (simulator, no signing) | `sh scripts/ai/ios-build.sh` |
19
19
  | Android build | `cd android && ./gradlew assembleDebug` |
20
20
  | Check on devices (release builds, Maestro flows, screenshots) | `sh scripts/ai/verify.sh all --spec <id>` |
21
+ | Check a release before tagging it (versions, permission texts, debug leftovers) | `node scripts/ai/release-check.js` |
21
22
 
22
23
  ## Definition of done
23
24
 
@@ -0,0 +1,28 @@
1
+ # git-cliff config: CHANGELOG.md from commit messages (https://git-cliff.org). The m-release skill runs it.
2
+ # Conventional commits (feat:, fix:, perf:) get their own sections; other commit messages go under "Other".
3
+
4
+ [changelog]
5
+ header = "# Changelog\n"
6
+ body = """
7
+ {% if version %}## {{ version | trim_start_matches(pat="v") }} ({{ timestamp | date(format="%Y-%m-%d") }}){% else %}## Unreleased{% endif %}
8
+ {% for group, commits in commits | group_by(attribute="group") %}
9
+ ### {{ group | striptags | trim }}
10
+ {% for commit in commits %}
11
+ - {% if commit.scope %}{{ commit.scope }}: {% endif %}{{ commit.message | split(pat="\n") | first | trim }}{% if commit.breaking %} (breaking){% endif %}\
12
+ {% endfor %}
13
+ {% endfor %}
14
+ """
15
+ trim = false
16
+
17
+ [git]
18
+ conventional_commits = true
19
+ filter_unconventional = false
20
+ tag_pattern = "v[0-9].*"
21
+ commit_parsers = [
22
+ { message = "^feat", group = "<!-- 0 -->New" },
23
+ { message = "^fix", group = "<!-- 1 -->Fixed" },
24
+ { message = "^perf", group = "<!-- 2 -->Faster" },
25
+ { message = "^(chore|ci|build|test|style|docs|refactor)(\\(.*\\))?!?:", skip = true },
26
+ { message = "^(Merge|Revert \"Merge)", skip = true },
27
+ { message = ".*", group = "<!-- 3 -->Other" },
28
+ ]
@@ -0,0 +1,88 @@
1
+ # Signed release builds on Codemagic (codemagic.io). One-time setup for each app: docs/ai/codemagic.md
2
+ # Both workflows start when a version tag is pushed (git push origin v1.2.0); you can also start them in Codemagic.
3
+ # Build numbers are set on the build machine only (one more than the store's latest), so the repo never needs a bump for them.
4
+ workflows:
5
+ android-release:
6
+ name: Android release
7
+ instance_type: mac_mini_m2
8
+ max_build_duration: 60
9
+ triggering: &on_version_tag
10
+ events:
11
+ - tag
12
+ tag_patterns:
13
+ - pattern: 'v*'
14
+ environment:
15
+ android_signing:
16
+ - upload_keystore
17
+ groups:
18
+ - google_play
19
+ node: 24
20
+ java: 17
21
+ scripts:
22
+ - name: Release check
23
+ script: node scripts/ai/release-check.js
24
+ - name: Install dependencies
25
+ script: sh scripts/ai/install-deps.sh
26
+ - name: Store release notes
27
+ script: cp "release-notes/${CM_TAG#v}/play-store.txt" release_notes.txt 2>/dev/null || true
28
+ - name: Build the signed app bundle
29
+ script: |
30
+ echo "sdk.dir=$ANDROID_SDK_ROOT" > android/local.properties
31
+ package=$(sed -n -E 's/.*applicationId( =)? "([^"]+)".*/\2/p' android/app/build.gradle* | head -1)
32
+ if last=$(google-play get-latest-build-number --package-name "$package") && [ -n "$last" ]; then code=$((last + 1)); else code=$BUILD_NUMBER; fi
33
+ # AGP 9 ignores injected version codes, so the number is written into build.gradle on this machine only
34
+ sed -i '' -E "s/versionCode( =)? [0-9]+/versionCode\1 $code/" android/app/build.gradle*
35
+ grep -qE "versionCode( =)? $code" android/app/build.gradle* || { echo "No versionCode number in android/app/build.gradle to set"; exit 1; }
36
+ # the upload key from Codemagic; build.gradle keeps debug signing for local release builds
37
+ cd android && ./gradlew bundleRelease \
38
+ -Pandroid.injected.signing.store.file="$CM_KEYSTORE_PATH" \
39
+ -Pandroid.injected.signing.store.password="$CM_KEYSTORE_PASSWORD" \
40
+ -Pandroid.injected.signing.key.alias="$CM_KEY_ALIAS" \
41
+ -Pandroid.injected.signing.key.password="$CM_KEY_PASSWORD"
42
+ artifacts:
43
+ - android/app/build/outputs/bundle/release/*.aab
44
+ publishing:
45
+ google_play:
46
+ credentials: $GOOGLE_PLAY_SERVICE_ACCOUNT_CREDENTIALS
47
+ track: internal
48
+
49
+ ios-release:
50
+ name: iOS release
51
+ instance_type: mac_mini_m2
52
+ max_build_duration: 60
53
+ triggering: *on_version_tag
54
+ integrations:
55
+ app_store_connect: codemagic
56
+ environment:
57
+ ios_signing:
58
+ distribution_type: app_store
59
+ bundle_identifier: {{IOS_BUNDLE_ID}}
60
+ vars:
61
+ APP_STORE_APPLE_ID: 0 # App Store Connect > the app > App Information > Apple ID
62
+ node: 24
63
+ xcode: latest
64
+ cocoapods: default
65
+ scripts:
66
+ - name: Release check
67
+ script: node scripts/ai/release-check.js
68
+ - name: Install dependencies
69
+ script: sh scripts/ai/install-deps.sh && cd ios && pod install
70
+ - name: Store release notes
71
+ script: |
72
+ notes="release-notes/${CM_TAG#v}/app-store.txt"
73
+ [ ! -f "$notes" ] || node -e 'const fs = require("fs"); fs.writeFileSync("release_notes.json", JSON.stringify([{ language: "en-US", text: fs.readFileSync(process.argv[1], "utf8").trim() }]))' "$notes"
74
+ - name: Use the signing files
75
+ script: xcode-project use-profiles
76
+ - name: Build the signed ipa
77
+ script: |
78
+ if last=$(app-store-connect get-latest-build-number "$APP_STORE_APPLE_ID") && [ -n "$last" ]; then build=$((last + 1)); else build=$BUILD_NUMBER; fi
79
+ (cd ios && agvtool new-version -all "$build")
80
+ workspace=$(ls -d ios/*.xcworkspace | head -1)
81
+ xcode-project build-ipa --workspace "$workspace" --scheme "$(basename "$workspace" .xcworkspace)"
82
+ artifacts:
83
+ - build/ios/ipa/*.ipa
84
+ - /tmp/xcodebuild_logs/*.log
85
+ publishing:
86
+ app_store_connect:
87
+ auth: integration
88
+ submit_to_testflight: true
@@ -0,0 +1,39 @@
1
+ # Signed release builds on Codemagic
2
+
3
+ `codemagic.yaml` has two workflows. `android-release` builds a signed app bundle and uploads it to Google Play's internal track. `ios-release` builds a signed ipa and uploads it to TestFlight. Both start when a version tag is pushed (`git push origin v1.2.0`), and you can start either one by hand in Codemagic.
4
+
5
+ Each build:
6
+ 1. runs `node scripts/ai/release-check.js` and stops if it finds a problem;
7
+ 2. sets the build number on the build machine: one more than the latest in the store, or Codemagic's build counter for a new app. Nothing is committed, so the repo keeps only the version name (for example 1.2.0), which you bump in the release PR;
8
+ 3. uses `release-notes/<version>/play-store.txt` or `app-store.txt` as the store's "What's new" or TestFlight's "What to test", when the build comes from a tag;
9
+ 4. signs with keys that Codemagic stores. The repo never holds them, and local release builds (`verify.sh`, the e2e CI) stay signed with the debug key.
10
+
11
+ ## One-time setup for each app
12
+
13
+ You need admin rights in the Codemagic team (or your personal account). Menus are under **Team settings** for a team and under **Settings** for a personal account.
14
+
15
+ 1. **Add the app:** Applications → Add application → choose the repository, then pick `codemagic.yaml` as the configuration.
16
+ 2. **Android upload key:** codemagic.yaml settings → Code signing identities → Android keystores. Upload the app's upload keystore, enter its password, key alias and key password, and set the reference name to `upload_keystore`.
17
+ - A new app has no key yet. Create one with `keytool -genkeypair -keystore upload.jks -storetype PKCS12 -alias upload -keyalg RSA -keysize 2048 -validity 10000`, keep the file and password in your password manager, and turn on Play App Signing.
18
+ 3. **Google Play access:**
19
+ - In Google Cloud, create a service account and download its JSON key.
20
+ - In Play Console → Users and permissions, invite it with release rights for the app.
21
+ - In Codemagic, open the app → Environment variables. Add `GOOGLE_PLAY_SERVICE_ACCOUNT_CREDENTIALS` with the JSON as its value, in a group named `google_play`, marked Secret.
22
+ - Upload the first build of a new app by hand in Play Console. If the app has never been published, add `submit_as_draft: true` under `google_play` in `codemagic.yaml`.
23
+ 4. **App Store Connect API key:** in App Store Connect → Users and Access → Integrations → App Store Connect API, create a key with App Manager access. In Codemagic → Integrations → Developer Portal → Manage keys → Add key, name it `codemagic`, enter the Issuer ID and Key ID, and upload the `.p8` file.
24
+ 5. **iOS certificate and profile:** codemagic.yaml settings → Code signing identities:
25
+ - iOS certificates → Generate certificate → Apple Distribution. Apple allows three per team, so reuse one that Codemagic created before.
26
+ - iOS provisioning profiles → Fetch profiles → the App Store profile for the app's bundle ID.
27
+ 6. **Check `codemagic.yaml`:**
28
+ - `bundle_identifier` was filled in from the Xcode project.
29
+ - Set `APP_STORE_APPLE_ID` (App Store Connect → the app → App Information → Apple ID). Without it, the iOS build number falls back to Codemagic's build counter, which the store rejects if it's lower than an earlier upload.
30
+
31
+ Then start `android-release` by hand and check that the signed `.aab` appears in the build's artifacts. Do the same for `ios-release`.
32
+
33
+ ## Apps with more than one target
34
+
35
+ When one repo ships several apps (for example a main app and a kiosk app, or product flavors), copy the workflow once per app. In each copy, set the bundle ID, the scheme (iOS) and the Gradle task and package (Android).
36
+
37
+ ## Plan limits
38
+
39
+ The free personal plan includes 500 macOS minutes a month and runs one build at a time.
@@ -6,4 +6,4 @@
6
6
  - Run at most 2 or 3 agents in parallel per person.
7
7
  - Don't use "skip permissions", "YOLO" or auto-run modes in any tool.
8
8
  - Keep secrets out of the repo folder; inject them at run time.
9
- - Review the metrics and the `learn` changes once a month. Re-check `AGENTS.md` and `docs/ai/` after every React Native, Xcode or Android Gradle Plugin upgrade, and after switching AI models.
9
+ - Review the metrics and the `m-learn` changes (`git log --grep 'chore(learn)'`) once a month. Re-check `AGENTS.md` and `docs/ai/` after every React Native, Xcode or Android Gradle Plugin upgrade, and after switching AI models.
@@ -0,0 +1,202 @@
1
+ #!/usr/bin/env node
2
+ // Release check for a bare React Native app: what App Store review, Play review or your users would catch.
3
+ // Usage: node scripts/ai/release-check.js [--since <git ref>]
4
+ // --since the previous release to compare with (default: the latest git tag)
5
+ // Exits 1 when something would get the release rejected or broken; warnings don't fail it.
6
+ 'use strict';
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { execFileSync } = require('child_process');
10
+
11
+ const args = process.argv.slice(2);
12
+ const argSince = args.includes('--since') ? args[args.indexOf('--since') + 1] : null;
13
+
14
+ const results = [];
15
+ const ok = (label, detail) => results.push({ level: 'ok', label, detail });
16
+ const info = (label, detail) => results.push({ level: 'info', label, detail });
17
+ const warn = (label, fix) => results.push({ level: 'warn', label, fix });
18
+ const fail = (label, fix) => results.push({ level: 'fail', label, fix });
19
+
20
+ const git = (...a) => { try { return execFileSync('git', a, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return null; } };
21
+ const readNow = f => { try { return fs.readFileSync(f, 'utf8'); } catch { return null; } };
22
+ const readAt = (ref, f) => (ref ? git('show', `${ref}:${f}`) : null);
23
+ const stripComments = t => (t || '').replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');
24
+ const uniq = a => [...new Set(a)];
25
+ const all = (re, text) => uniq([...(text || '').matchAll(re)].map(m => m[1].replace(/^"|"$/g, '').trim()));
26
+ const maxNum = a => Math.max(...a.map(Number).filter(n => !Number.isNaN(n)));
27
+
28
+ // a clean checkout of a release tag is that release being built (e.g. in CI): compare with the tag before it
29
+ const atTag = git('tag', '--points-at', 'HEAD') && git('status', '--porcelain') === '';
30
+ const since = argSince || git('describe', '--tags', '--abbrev=0', ...(atTag ? ['HEAD^'] : []));
31
+
32
+ // ---------- files ----------
33
+ const xcodeproj = (fs.readdirSync('ios', { withFileTypes: true }).find(e => e.isDirectory() && e.name.endsWith('.xcodeproj')) || {}).name;
34
+ const pbxPath = xcodeproj ? `ios/${xcodeproj}/project.pbxproj` : null;
35
+ const pbx = pbxPath ? readNow(pbxPath) : null;
36
+ const plists = all(/INFOPLIST_FILE = ([^;]+);/g, pbx).map(p => `ios/${p}`).filter(p => fs.existsSync(p));
37
+ const gradlePath = ['android/app/build.gradle', 'android/app/build.gradle.kts'].find(f => fs.existsSync(f));
38
+ const gradle = stripComments(readNow(gradlePath));
39
+ const manifestPath = 'android/app/src/main/AndroidManifest.xml';
40
+ const pkg = JSON.parse(readNow('package.json') || '{}');
41
+ // this kit's codemagic.yaml sets build numbers and the Android upload key on the build machine
42
+ const codemagic = readNow('codemagic.yaml') || '';
43
+ const ciBuildNumber = { iOS: /agvtool new-version/.test(codemagic), Android: /versionCode[^\n]*\$code/.test(codemagic) };
44
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
45
+
46
+ // ---------- 1. versions ----------
47
+ const iosVersions = t => all(/MARKETING_VERSION = ([^;]+);/g, t);
48
+ const iosBuilds = t => all(/CURRENT_PROJECT_VERSION = ([^;]+);/g, t);
49
+ const androidVersions = t => all(/versionName\s*=?\s*"([^"]+)"/g, stripComments(t));
50
+ const androidBuilds = t => all(/versionCode\s*=?\s*(\d+)/g, stripComments(t));
51
+
52
+ function compare(platform, now, before, kind) {
53
+ if (kind === 'build number' && ciBuildNumber[platform]) { info(`${platform} build number: set by Codemagic at build time`); return; }
54
+ if (!now.length) { warn(`${platform} ${kind}: couldn't read it`, 'check it by hand before you ship'); return; }
55
+ if (!before) { info(`${platform} ${kind}: ${now.join(', ')}`); return; }
56
+ if (!before.length || now.join() !== before.join()) {
57
+ if (kind === 'build number' && before.length && maxNum(now) < maxNum(before)) {
58
+ fail(`${platform} build number went down (${before.join(', ')} → ${now.join(', ')})`, 'stores reject a build number lower than the last upload');
59
+ } else ok(`${platform} ${kind}`, `${before.join(', ') || '?'} → ${now.join(', ')}`);
60
+ } else if (kind === 'build number') {
61
+ warn(`${platform} build number unchanged since ${since} (${now.join(', ')})`, 'bump it, unless your CI sets it (for example Codemagic); stores reject a repeated build number');
62
+ } else {
63
+ warn(`${platform} version unchanged since ${since} (${now.join(', ')})`, 'fine for a re-upload of the same version; otherwise bump it');
64
+ }
65
+ }
66
+
67
+ if (!since) info('No previous release found (no git tag)', 'tag each release, e.g. v1.4.0, or pass --since <ref>, so the next check can compare');
68
+ if (pbx) {
69
+ compare('iOS', iosVersions(pbx), since && iosVersions(readAt(since, pbxPath)), 'version');
70
+ compare('iOS', iosBuilds(pbx), since && iosBuilds(readAt(since, pbxPath)), 'build number');
71
+ }
72
+ if (gradle) {
73
+ compare('Android', androidVersions(gradle), since && androidVersions(readAt(since, gradlePath)), 'version');
74
+ compare('Android', androidBuilds(gradle), since && androidBuilds(readAt(since, gradlePath)), 'build number');
75
+ }
76
+ if (pbx && gradle) {
77
+ const a = iosVersions(pbx), b = androidVersions(gradle);
78
+ if (a.length && b.length && !a.some(v => b.includes(v))) {
79
+ warn(`iOS shows version ${a.join(', ')}, Android shows ${b.join(', ')}`, 'users and support see different numbers; align them unless that\'s intended');
80
+ }
81
+ }
82
+
83
+ // ---------- 2. iOS privacy manifest ----------
84
+ if (pbx) {
85
+ const manifests = fs.readdirSync('ios', { withFileTypes: true })
86
+ .filter(e => e.isDirectory() && fs.existsSync(`ios/${e.name}/PrivacyInfo.xcprivacy`)).map(e => `ios/${e.name}/PrivacyInfo.xcprivacy`);
87
+ if (!manifests.length) fail('No PrivacyInfo.xcprivacy in the iOS app', 'Apple requires a privacy manifest; React Native\'s template ships one in ios/<App>/');
88
+ else if (!/PrivacyInfo\.xcprivacy/.test(pbx)) fail(`${manifests[0]} isn't in the Xcode project`, 'add it to the app target in Xcode so it ships in the build');
89
+ else ok('iOS privacy manifest', manifests.join(', '));
90
+ }
91
+
92
+ // ---------- 3. iOS permission texts ----------
93
+ // libraries that make iOS ask for a permission, and the Info.plist text each one needs
94
+ const NEEDS = {
95
+ 'react-native-vision-camera': ['NSCameraUsageDescription'],
96
+ 'react-native-image-picker': ['NSCameraUsageDescription', 'NSPhotoLibraryUsageDescription'],
97
+ 'react-native-image-crop-picker': ['NSCameraUsageDescription', 'NSPhotoLibraryUsageDescription'],
98
+ '@react-native-camera-roll/camera-roll': ['NSPhotoLibraryUsageDescription'],
99
+ 'react-native-geolocation-service': ['NSLocationWhenInUseUsageDescription'],
100
+ '@react-native-community/geolocation': ['NSLocationWhenInUseUsageDescription'],
101
+ 'react-native-location': ['NSLocationWhenInUseUsageDescription'],
102
+ 'react-native-contacts': ['NSContactsUsageDescription'],
103
+ 'react-native-ble-plx': ['NSBluetoothAlwaysUsageDescription'],
104
+ 'react-native-ble-manager': ['NSBluetoothAlwaysUsageDescription'],
105
+ 'react-native-kontaktio': ['NSBluetoothAlwaysUsageDescription', 'NSLocationWhenInUseUsageDescription'],
106
+ 'react-native-nfc-manager': ['NFCReaderUsageDescription'],
107
+ 'react-native-biometrics': ['NSFaceIDUsageDescription'],
108
+ 'react-native-touch-id': ['NSFaceIDUsageDescription'],
109
+ 'react-native-audio-recorder-player': ['NSMicrophoneUsageDescription'],
110
+ '@react-native-voice/voice': ['NSMicrophoneUsageDescription', 'NSSpeechRecognitionUsageDescription'],
111
+ };
112
+ const PLACEHOLDER = /^\s*$|\b(todo|tbd|lorem|placeholder|description here|your text)\b/i;
113
+ const usageTexts = f => Object.fromEntries([...(readNow(f) || '').matchAll(/<key>(\w+UsageDescription)<\/key>\s*<string>([^<]*)<\/string>/g)].map(m => [m[1], m[2]]));
114
+ const textsByPlist = Object.fromEntries(plists.map(f => [f, usageTexts(f)]));
115
+ const needed = Object.entries(NEEDS).filter(([lib]) => deps[lib]).flatMap(([lib, keys]) => keys.map(key => ({ lib, key })));
116
+ for (const plistPath of plists) {
117
+ const texts = textsByPlist[plistPath];
118
+ const problems = [];
119
+ for (const { lib, key } of needed) {
120
+ if (key in texts) continue;
121
+ // with several app targets (e.g. a kiosk app), one may legitimately not use a library
122
+ const elsewhere = plists.filter(p => p !== plistPath && key in textsByPlist[p]);
123
+ if (elsewhere.length) warn(`${plistPath}: no ${key}, which ${elsewhere[0]} has (${lib})`, `if this app uses ${lib}, add it; otherwise ignore`);
124
+ else problems.push(`${key} (${lib})`);
125
+ }
126
+ if (problems.length) fail(`${plistPath}: missing permission texts: ${uniq(problems).join(', ')}`, 'add each key with a sentence that says why the app needs it; without it iOS crashes on the permission request and review rejects the app (guideline 5.1.1)');
127
+ const neededKeys = needed.map(n => n.key);
128
+ for (const [key, text] of Object.entries(texts).filter(([, t]) => PLACEHOLDER.test(t))) {
129
+ if (neededKeys.includes(key)) fail(`${plistPath}: ${key} is ${text.trim() ? `a placeholder ("${text.trim()}")` : 'empty'}`, 'write a real reason users can understand');
130
+ else warn(`${plistPath}: ${key} is ${text.trim() ? 'a placeholder' : 'empty'}`, 'remove the key if the app doesn\'t use this permission; otherwise write a real reason');
131
+ }
132
+ if (!problems.length && !Object.values(texts).some(t => PLACEHOLDER.test(t))) ok(`${plistPath}: permission texts`, `${Object.keys(texts).length} present`);
133
+ const plist = readNow(plistPath);
134
+ if (/<key>NSAllowsArbitraryLoads<\/key>\s*<true\s*\/>/.test(plist)) {
135
+ warn(`${plistPath}: NSAllowsArbitraryLoads is true (any HTTP allowed)`, 'App Review may ask why; allow only the domains that need it (NSExceptionDomains)');
136
+ }
137
+ }
138
+
139
+ // ---------- 4. Android permissions ----------
140
+ 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)$/;
141
+ const perms = t => all(/<uses-permission[^>]*android:name="([^"]+)"/g, t);
142
+ const permsNow = perms(readNow(manifestPath));
143
+ if (since && readAt(since, manifestPath) !== null) {
144
+ const before = perms(readAt(since, manifestPath));
145
+ const added = permsNow.filter(p => !before.includes(p));
146
+ const removed = before.filter(p => !permsNow.includes(p));
147
+ if (added.some(p => SENSITIVE.test(p))) {
148
+ warn(`New Android permissions since ${since}: ${added.join(', ')}`, 'update the Play Console data safety form, and explain the permission in the app before asking');
149
+ } else if (added.length) info(`New Android permissions since ${since}: ${added.join(', ')}`);
150
+ else ok('No new Android permissions', removed.length ? `removed: ${removed.join(', ')}` : '');
151
+ } else if (permsNow.some(p => SENSITIVE.test(p))) {
152
+ info('Android permissions that the Play data safety form must cover', permsNow.filter(p => SENSITIVE.test(p)).map(p => p.split('.').pop()).join(', '));
153
+ }
154
+
155
+ // ---------- 5. debug leftovers ----------
156
+ // the body of `name { … }` inside text, found by matching braces (Gradle blocks nest)
157
+ function block(text, name) {
158
+ const m = new RegExp(`(^|\\W)${name}\\s*\\{`).exec(text || '');
159
+ if (!m) return '';
160
+ let depth = 0;
161
+ for (let i = m.index + m[0].length - 1; i < text.length; i++) {
162
+ if (text[i] === '{') depth++;
163
+ else if (text[i] === '}' && --depth === 0) return text.slice(m.index + m[0].length, i);
164
+ }
165
+ return '';
166
+ }
167
+ const releaseBlock = block(block(gradle, 'buildTypes'), 'release');
168
+ if (/debuggable\s*=?\s*true/.test(releaseBlock)) fail('Android release build is debuggable', 'remove "debuggable true" from buildTypes.release; Play rejects debuggable apps');
169
+ if (/android\.injected\.signing/.test(codemagic)) ok('Android release signing', 'Codemagic signs with the upload key');
170
+ else if (/signingConfig\s*=?\s*signingConfigs\.debug/.test(releaseBlock)) {
171
+ warn('Android release build is signed with the debug key', 'fine only if your release pipeline (for example Codemagic) re-signs it; Play rejects debug-signed uploads');
172
+ }
173
+ if (/android:usesCleartextTraffic="true"/.test(readNow(manifestPath) || '')) {
174
+ warn('Android allows cleartext (HTTP) traffic', 'allow only the domains that need it (network security config)');
175
+ }
176
+ const debuggers = (git('grep', '-n', '-E', '^[[:space:]]*debugger;?[[:space:]]*$', '--', '*.js', '*.jsx', '*.ts', '*.tsx') || '').split('\n').filter(Boolean);
177
+ if (debuggers.length) fail(`"debugger" statements left in code: ${debuggers.slice(0, 3).join(', ')}${debuggers.length > 3 ? ' …' : ''}`, 'remove them');
178
+ else ok('No "debugger" statements');
179
+
180
+ // ---------- 6. store notes ----------
181
+ const LIMITS = { 'play-store': 500, 'app-store': 4000 };
182
+ const noteFiles = fs.existsSync('release-notes') ? (git('ls-files', '--others', '--cached', '--exclude-standard', 'release-notes') || '').split('\n').filter(Boolean) : [];
183
+ for (const f of noteFiles) {
184
+ const kind = Object.keys(LIMITS).find(k => path.basename(f).startsWith(k));
185
+ if (!kind) continue;
186
+ const len = [...readNow(f).trim()].length;
187
+ if (len > LIMITS[kind]) fail(`${f} is ${len} characters (limit ${LIMITS[kind]})`, 'shorten it; the store rejects longer release notes');
188
+ else ok(`${f}`, `${len}/${LIMITS[kind]} characters`);
189
+ }
190
+ if (!noteFiles.length) info('No store release notes yet', 'run the m-release skill to write them from the changelog');
191
+
192
+ // ---------- report ----------
193
+ const icon = { ok: '✓', info: '·', warn: '!', fail: '✗' };
194
+ console.log(`Release check${since ? ` (compared with ${since})` : ''}`);
195
+ for (const r of results) {
196
+ console.log(` ${icon[r.level]} ${r.label}${r.detail ? ` (${r.detail})` : ''}`);
197
+ if (r.fix) console.log(` → ${r.fix}`);
198
+ }
199
+ const failures = results.filter(r => r.level === 'fail').length;
200
+ const warnings = results.filter(r => r.level === 'warn').length;
201
+ console.log(`\n${failures} problem(s), ${warnings} warning(s).`);
202
+ process.exitCode = failures ? 1 : 0;
@@ -0,0 +1,20 @@
1
+ #!/bin/sh
2
+ # Sets the version users see on both platforms: iOS MARKETING_VERSION and Android versionName.
3
+ # Build numbers are left alone (codemagic.yaml sets them at build time).
4
+ # Usage: sh scripts/ai/set-version.sh 1.4.0
5
+ set -eu
6
+ v=${1:-}
7
+ echo "$v" | grep -qE '^[0-9]+\.[0-9]+(\.[0-9]+)?$' || { echo "usage: sh scripts/ai/set-version.sh <version, e.g. 1.4.0>" >&2; exit 1; }
8
+ pbx=$(ls ios/*.xcodeproj/project.pbxproj | head -1)
9
+ gradle=$(ls android/app/build.gradle android/app/build.gradle.kts 2>/dev/null | head -1)
10
+
11
+ # several apps in one project (targets or flavors with their own versions): a person decides each one
12
+ [ -z "$(grep -oE 'MARKETING_VERSION = [^;]+' "$pbx" | sort -u | sed -n 2p)" ] || { echo "$pbx has several app versions; set each one in Xcode" >&2; exit 1; }
13
+ [ -z "$(grep -oE 'versionName( =)? "[^"]+"' "$gradle" | sort -u | sed -n 2p)" ] || { echo "$gradle has several versionName values; set each one by hand" >&2; exit 1; }
14
+
15
+ sed -i '' -E "s/MARKETING_VERSION = [^;]+;/MARKETING_VERSION = $v;/" "$pbx"
16
+ sed -i '' -E "s/versionName( =)? \"[^\"]+\"/versionName\1 \"$v\"/" "$gradle"
17
+ grep -q "MARKETING_VERSION = $v;" "$pbx" || { echo "No MARKETING_VERSION in $pbx; set the version in Xcode" >&2; exit 1; }
18
+ grep -qE "versionName( =)? \"$v\"" "$gradle" || { echo "No versionName in $gradle; set it by hand" >&2; exit 1; }
19
+ plutil -lint -s "$pbx"
20
+ echo "Version $v set in $pbx and $gradle."