agentic-mobile-kit 0.3.0 → 0.5.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
@@ -11,6 +11,7 @@ Run in the app's root, on a clean git working tree:
11
11
  ```sh
12
12
  npx agentic-mobile-kit init
13
13
  npx agentic-mobile-kit init --tools claude,codex,antigravity # choose your AI tools
14
+ npx agentic-mobile-kit init --ci github,codemagic # only if the app uses that CI
14
15
  ```
15
16
 
16
17
  Then check the project and your machine, with a fix for each problem:
@@ -21,13 +22,26 @@ npx agentic-mobile-kit doctor
21
22
 
22
23
  `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
24
 
25
+ ## Update or remove it
26
+
27
+ ```sh
28
+ npx agentic-mobile-kit@latest sync # update the kit's files; your own changes to them are merged in
29
+ npx agentic-mobile-kit uninstall # remove the kit; files you changed are kept and listed
30
+ ```
31
+
32
+ Both need a clean working tree, and both leave the result for you to review with `git diff`.
33
+
34
+ `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.
35
+
36
+ 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.
37
+
24
38
  ## What it adds
25
39
 
26
40
  - **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
41
  - **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
42
  - **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.
29
- - **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`).
30
- - **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).
43
+ - **Releases:** `m-release` writes each release's changelog from real commits with git-cliff, plus store and client notes, all in `release-notes/<version>/`. It then runs `scripts/ai/release-check.js`, which catches what store review would reject. Signed builds come from `scripts/ai/release-build.sh` on a Mac: an app bundle signed with your upload key, and an `.ipa` signed through Xcode's account. With `--ci codemagic`, a version tag starts them on Codemagic instead (`codemagic.yaml`, one-time setup in `docs/ai/codemagic.md`).
44
+ - **Checks no tool can skip:** git hooks (secrets, signing files, broken Xcode project files, lint, typecheck, tests) and, with `--ci github`, GitHub Actions CI (lint, typecheck, tests, secret scan, PR size, Android and iOS builds, nightly Android end-to-end tests).
31
45
 
32
46
  Work continues across tools and machines through `specs/<id>/progress.md`: run `m-pause` in one tool, then `m-continue` in another.
33
47
 
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, CI } = require('../lib/init');
4
4
  const { doctor, printDoctor } = require('../lib/doctor');
5
5
 
6
6
  const [cmd, ...rest] = process.argv.slice(2);
@@ -8,32 +8,47 @@ const flag = name => {
8
8
  const i = rest.indexOf(`--${name}`);
9
9
  return i >= 0 ? rest[i + 1] : undefined;
10
10
  };
11
+ const list = name => (flag(name) ? flag(name).split(',').map(s => s.trim()).filter(Boolean) : undefined);
11
12
 
12
13
  const help = `agentic-mobile-kit ${version}
13
14
 
14
15
  Usage:
15
- npx agentic-mobile-kit init [--tools claude,codex,antigravity] [--pm yarn|npm|pnpm|bun]
16
+ npx agentic-mobile-kit init [--tools claude,codex,antigravity] [--ci github,codemagic] [--pm yarn|npm|pnpm|bun]
17
+ npx agentic-mobile-kit sync [--ci github,codemagic] [--from <version>]
18
+ npx agentic-mobile-kit uninstall [--from <version>]
16
19
  npx agentic-mobile-kit doctor
17
20
 
18
21
  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.
22
+ init Install the kit into a bare React Native project (run in the app's root).
23
+ sync Update the kit's files to this version. Your own changes to them are merged in, not lost.
24
+ uninstall Remove the kit's files and sections. Files you changed are kept and listed.
25
+ doctor Check the project and this machine, with a fix for each problem.
21
26
 
22
27
  Options:
23
28
  --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`;
29
+ --ci CI to set up, only if the app uses it: ${Object.keys(CI).join(', ')} (GitHub Actions checks, Codemagic signed builds; default: none)
30
+ --pm Package manager, if it can't be detected from the lockfile
31
+ --from The kit version that installed the project; needed only for installs made before 0.4.0`;
25
32
 
26
- if (cmd === '--version' || cmd === '-v') {
27
- console.log(version);
28
- } else if (cmd === 'init') {
29
- try {
30
- const tools = flag('tools') ? flag('tools').split(',').map(s => s.trim()).filter(Boolean) : undefined;
31
- printSummary(init(process.cwd(), { tools, pm: flag('pm') }));
32
- } catch (e) {
33
+ // init, sync and uninstall stop with a plain message when the project isn't ready for them
34
+ function run(name, fn) {
35
+ try { fn(); } catch (e) {
33
36
  if (!(e instanceof InitError)) throw e;
34
- console.error(`init stopped: ${e.message}`);
37
+ console.error(`${name} stopped: ${e.message}`);
35
38
  process.exitCode = 1;
36
39
  }
40
+ }
41
+
42
+ if (cmd === '--version' || cmd === '-v') {
43
+ console.log(version);
44
+ } else if (cmd === 'init') {
45
+ run('init', () => {
46
+ printSummary(init(process.cwd(), { tools: list('tools'), ci: list('ci'), pm: flag('pm') }));
47
+ });
48
+ } else if (cmd === 'sync') {
49
+ run('sync', () => printSync(sync(process.cwd(), { from: flag('from'), ci: list('ci'), pm: flag('pm') })));
50
+ } else if (cmd === 'uninstall') {
51
+ run('uninstall', () => printUninstall(uninstall(process.cwd(), { from: flag('from'), pm: flag('pm') })));
37
52
  } else if (cmd === 'doctor') {
38
53
  if (printDoctor(doctor(process.cwd())) > 0) process.exitCode = 1;
39
54
  } else {
package/lib/init.js CHANGED
@@ -1,13 +1,27 @@
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';
19
+ // optional parts, installed only when a project chooses them with --ci: not every app uses CI
20
+ const CI = {
21
+ github: rel => rel.startsWith(`.github${path.sep}`),
22
+ codemagic: rel => rel === 'codemagic.yaml' || rel === path.join('docs', 'ai', 'codemagic.md'),
23
+ };
24
+ const ciGroup = rel => Object.keys(CI).find(g => CI[g](rel));
11
25
 
12
26
  // tool name -> rulesync targets
13
27
  const TOOLS = {
@@ -27,6 +41,11 @@ function git(cwd, ...args) {
27
41
  }
28
42
 
29
43
  function readJson(file) { return JSON.parse(fs.readFileSync(file, 'utf8')); }
44
+ const readIf = file => { try { return fs.readFileSync(file, 'utf8'); } catch { return null; } };
45
+ function isLink(p) { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } }
46
+
47
+ // when the kit runs under npx, npm_config_* variables (e.g. the outer --package) would leak into the npx/npm it starts
48
+ const cleanEnv = () => Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^npm_(config|package|lifecycle)_/i.test(k)));
30
49
 
31
50
  function installedVersion(cwd, pkg, declared) {
32
51
  try { return readJson(path.join(cwd, 'node_modules', pkg, 'package.json')).version; } catch {}
@@ -55,10 +74,10 @@ function checkProject(cwd) {
55
74
  throw new InitError('This folder is not a git repository. Run "git init" and commit first; git is how init can be undone.');
56
75
  }
57
76
  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.');
77
+ throw new InitError('You have uncommitted changes. Commit or stash them first, so this can be undone with git.');
59
78
  }
60
79
  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.');
80
+ if (!fs.existsSync(pkgFile)) throw new InitError('No package.json here. Run this in the root of your React Native app.');
62
81
  const pkg = readJson(pkgFile);
63
82
  const deps = { ...pkg.dependencies, ...pkg.devDependencies };
64
83
  if (!deps['react-native']) throw new InitError('This is not a React Native project (no "react-native" dependency).');
@@ -68,7 +87,7 @@ function checkProject(cwd) {
68
87
  return { pkg, deps };
69
88
  }
70
89
 
71
- // all template files, relative paths, including dotfiles
90
+ // all files under dir, as relative paths, including dotfiles
72
91
  function templateFiles(dir = TEMPLATE, base = '') {
73
92
  return fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => {
74
93
  const rel = path.join(base, e.name);
@@ -90,13 +109,10 @@ function fillPlaceholders(text, values) {
90
109
  return text.replace(/\{\{(\w+)\}\}/g, (m, k) => (k in values ? values[k] : m));
91
110
  }
92
111
 
93
- function init(cwd, opts = {}) {
94
- const { pkg, deps } = checkProject(cwd);
95
- const pm = detectPm(cwd, opts.pm);
96
- const tools = opts.tools || TESTED;
97
- for (const t of tools) if (!TOOLS[t]) throw new InitError(`Unknown tool "${t}". Choose from: ${Object.keys(TOOLS).join(', ')}.`);
98
-
99
- const values = {
112
+ function projectValues(cwd, pkg, deps, pm, ci) {
113
+ return {
114
+ KIT_VERSION,
115
+ KIT_CI: ci.join(',') || 'none',
100
116
  APP_NAME: pkg.name || path.basename(cwd),
101
117
  RN_VERSION: installedVersion(cwd, 'react-native', deps['react-native']),
102
118
  REACT_VERSION: installedVersion(cwd, 'react', deps.react),
@@ -106,99 +122,324 @@ function init(cwd, opts = {}) {
106
122
  PM_RUN: pm.run,
107
123
  IOS_BUNDLE_ID: iosBundleId(cwd),
108
124
  };
109
- const report = { created: [], merged: [], skipped: [] };
125
+ }
110
126
 
111
- // 1. template files (never overwrite)
112
- for (const rel of templateFiles()) {
113
- const src = path.join(TEMPLATE, rel);
114
- const dest = path.join(cwd, rel);
115
- const kitText = () => fillPlaceholders(fs.readFileSync(src, 'utf8'), values);
127
+ // a template file's text as the kit writes it into this project
128
+ function kitText(templateDir, rel, values, targets) {
129
+ const text = fs.readFileSync(path.join(templateDir, rel), 'utf8');
130
+ if (FILLED.includes(rel)) return fillPlaceholders(text, values);
131
+ if (rel === 'rulesync.jsonc') return setTargets(text, targets);
132
+ return text;
133
+ }
116
134
 
117
- if (rel === 'AGENTS.md' && fs.existsSync(dest)) {
118
- const current = fs.readFileSync(dest, 'utf8');
119
- const section = kitText();
120
- const next = MARKERS.test(current) ? current.replace(MARKERS, section) : `${current.replace(/\n*$/, '\n\n')}${section}`;
121
- if (next !== current) { fs.writeFileSync(dest, next); report.merged.push(rel); } else report.skipped.push(rel);
122
- continue;
123
- }
124
- if (rel === 'CLAUDE.md' && fs.existsSync(dest)) {
125
- const current = fs.readFileSync(dest, 'utf8');
126
- if (/^@AGENTS\.md\s*$/m.test(current)) report.skipped.push(rel);
127
- else { fs.writeFileSync(dest, `${current.replace(/\n*$/, '\n\n')}@AGENTS.md\n`); report.merged.push(rel); }
128
- continue;
129
- }
130
- if (fs.existsSync(dest)) { report.skipped.push(rel); continue; }
135
+ const setTargets = (text, targets) => text.replace(/"targets":\s*\[[^\]]*\]/, () => `"targets": ${JSON.stringify(targets)}`);
136
+ // a project file's text for comparing with the kit's: the targets line is the project's own (init rewrites it)
137
+ const projectText = (cwd, rel, targets) => {
138
+ const text = readIf(path.join(cwd, rel));
139
+ return text !== null && rel === 'rulesync.jsonc' ? setTargets(text, targets) : text;
140
+ };
141
+ // a function replacement, so "$" in the kit's text is never read as a replacement pattern
142
+ const mergeAgents = (current, section) => (MARKERS.test(current) ? current.replace(MARKERS, () => section) : `${current.replace(/\n*$/, '\n\n')}${section}`);
143
+ const mergeClaude = current => (/^@AGENTS\.md\s*$/m.test(current) ? current : `${current.replace(/\n*$/, '\n\n')}@AGENTS.md\n`);
131
144
 
132
- fs.mkdirSync(path.dirname(dest), { recursive: true });
133
- if (rel === 'AGENTS.md' || rel === 'codemagic.yaml') fs.writeFileSync(dest, kitText());
134
- else fs.copyFileSync(src, dest);
135
- // npm doesn't always keep the executable bit, and git silently skips non-executable hooks
136
- const executable = rel.startsWith(`.githooks${path.sep}`) || /\.(sh|js)$/.test(rel) && rel.startsWith(`scripts${path.sep}`);
137
- fs.chmodSync(dest, executable ? 0o755 : 0o644);
138
- report.created.push(rel);
145
+ function writeKitFile(cwd, rel, text) {
146
+ const dest = path.join(cwd, rel);
147
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
148
+ fs.writeFileSync(dest, text);
149
+ // npm doesn't always keep the executable bit, and git silently skips non-executable hooks
150
+ const executable = rel.startsWith(`.githooks${path.sep}`) || /\.(sh|js)$/.test(rel) && rel.startsWith(`scripts${path.sep}`);
151
+ fs.chmodSync(dest, executable ? 0o755 : 0o644);
152
+ }
153
+
154
+ // the tools a project was set up for, read back from its rulesync targets
155
+ function installedTools(cwd) {
156
+ const m = (readIf(path.join(cwd, 'rulesync.jsonc')) || '').match(/"targets":\s*\[([^\]]*)\]/);
157
+ let targets = [];
158
+ try { targets = JSON.parse(`[${m ? m[1] : ''}]`); } catch {}
159
+ const tools = Object.keys(TOOLS).filter(t => TOOLS[t].every(x => targets.includes(x)));
160
+ return tools.length ? tools : TESTED;
161
+ }
162
+
163
+ // what the kit marker in AGENTS.md records: the kit version since 0.4.0, the CI choice since 0.5.0
164
+ function recorded(agents) {
165
+ const m = (agents || '').match(/KIT:START agentic-mobile-kit (\d[^\s>]*)(?: ci=([\w,]+))?/);
166
+ return { version: m ? m[1] : null, ci: m && m[2] ? m[2].split(',').filter(g => CI[g]) : null };
167
+ }
168
+
169
+ // the CI parts a project has: as recorded, or (installs before 0.5.0 got them by default) recognized by the kit's own files
170
+ function installedCi(cwd, agents) {
171
+ return recorded(agents).ci || Object.keys(CI).filter(g => (g === 'github'
172
+ ? /agentic-mobile-kit/.test(readIf(path.join(cwd, '.github', 'workflows', 'ci.yml')) || '')
173
+ : fs.existsSync(path.join(cwd, 'docs', 'ai', 'codemagic.md'))));
174
+ }
175
+
176
+ function chooseCi(cwd, agents, wanted = []) {
177
+ for (const g of wanted) if (!CI[g]) throw new InitError(`Unknown CI "${g}". Choose from: ${Object.keys(CI).join(', ')}.`);
178
+ return Object.keys(CI).filter(g => wanted.includes(g) || installedCi(cwd, agents).includes(g));
179
+ }
180
+
181
+ // the kit version that installed the project: recorded in AGENTS.md since 0.4.0, or given with --from.
182
+ // A --from version is a guess (installs may predate it), so it isn't trusted as a merge base.
183
+ function oldTemplate(agents, opts) {
184
+ if (opts.fromDir) return { from: opts.from || 'old', dir: opts.fromDir, exact: !opts.from };
185
+ const from = opts.from || recorded(agents).version;
186
+ if (!from) {
187
+ throw new InitError('This project doesn\'t record which kit version installed it (versions before 0.4.0 didn\'t). '
188
+ + 'Pass it with --from, for example --from 0.3.0; the commit that added or last updated the kit usually says.');
139
189
  }
190
+ const [a, b] = [from, KIT_VERSION].map(v => v.split('.').map(n => parseInt(n, 10) || 0));
191
+ const newer = a.findIndex((n, i) => n !== b[i]);
192
+ 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`);
193
+ return { from, dir: from === KIT_VERSION ? TEMPLATE : fetchTemplate(from), exact: !opts.from };
194
+ }
195
+
196
+ function fetchTemplate(version) {
197
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'amk-kit-'));
198
+ const r = spawnSync('npm', ['pack', `agentic-mobile-kit@${version}`, '--pack-destination', dir, '--silent'], { cwd: dir, env: cleanEnv(), encoding: 'utf8' });
199
+ if (r.status !== 0) throw new InitError(`Couldn't download agentic-mobile-kit@${version} from npm: ${(r.stderr || '').trim().split('\n').pop()}`);
200
+ execFileSync('tar', ['-xzf', path.join(dir, r.stdout.trim().split('\n').pop()), '-C', dir]);
201
+ return path.join(dir, 'package', 'stacks', 'react-native', 'template');
202
+ }
203
+
204
+ // three-way merge: your changes and the kit's changes since the old version, both kept
205
+ function merge3(current, base, kitNew, from) {
206
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'amk-merge-'));
207
+ const files = [current, base, kitNew].map((text, i) => { const f = path.join(dir, String(i)); fs.writeFileSync(f, text); return f; });
208
+ const r = spawnSync('git', ['merge-file', '-p', '-L', 'your version', '-L', `kit ${from}`, '-L', `kit ${KIT_VERSION}`, ...files], { encoding: 'utf8' });
209
+ fs.rmSync(dir, { recursive: true, force: true });
210
+ if (r.status === null || r.status < 0 || r.status > 127) throw new Error(`git merge-file failed: ${r.stderr}`);
211
+ return { text: r.stdout, conflicts: r.status };
212
+ }
213
+
214
+ const SKILL_LINKS = [['.claude/skills', 'claude'], ['.kiro/skills', 'kiro']];
215
+ const kitSkills = template => fs.readdirSync(path.join(template, '.agents', 'skills'), { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name);
216
+
217
+ // steps 2–6, shared by init and sync
218
+ function finish(cwd, { pkg, deps, tools, template, skipGenerate }) {
219
+ const done = { created: [], merged: [], skipped: [] };
140
220
 
141
- // 2. skills folder links for tools that don't read .agents/skills
142
- const links = [['.claude/skills', 'claude'], ['.kiro/skills', 'kiro']];
143
- for (const [link, tool] of links) {
221
+ // 2. skills links for tools that don't read .agents/skills
222
+ for (const [link, tool] of SKILL_LINKS) {
144
223
  if (!tools.includes(tool)) continue;
145
224
  const dest = path.join(cwd, link);
146
- if (fs.existsSync(dest) || isLink(dest)) { report.skipped.push(link); continue; }
147
- fs.mkdirSync(path.dirname(dest), { recursive: true });
148
- fs.symlinkSync('../.agents/skills', dest);
149
- report.created.push(`${link} -> .agents/skills`);
225
+ if (!fs.existsSync(dest) && !isLink(dest)) {
226
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
227
+ fs.symlinkSync('../.agents/skills', dest);
228
+ done.created.push(`${link} -> .agents/skills`);
229
+ continue;
230
+ }
231
+ if (isLink(dest) || !fs.statSync(dest).isDirectory()) { done.skipped.push(link); continue; }
232
+ // the folder already holds another framework's skills: link each kit skill into it
233
+ for (const name of kitSkills(template)) {
234
+ const p = path.join(dest, name);
235
+ const target = `../../.agents/skills/${name}`;
236
+ if (isLink(p) && fs.readlinkSync(p) === target) continue;
237
+ if (fs.existsSync(p) || isLink(p)) { done.skipped.push(`${link}/${name} (another skill has this name)`); continue; }
238
+ fs.symlinkSync(target, p);
239
+ done.created.push(`${link}/${name} -> .agents/skills/${name}`);
240
+ }
150
241
  }
151
242
 
152
243
  // 3. .gitignore: keep secrets out of git
153
244
  const gi = path.join(cwd, '.gitignore');
154
- const giText = fs.existsSync(gi) ? fs.readFileSync(gi, 'utf8') : '';
245
+ const giText = readIf(gi) || '';
155
246
  const missing = ['.env', '.env.*', '!.env.example', '.ai/'].filter(l => !giText.split('\n').includes(l));
156
247
  if (missing.length) {
157
248
  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`);
158
- report.merged.push('.gitignore');
249
+ done.merged.push('.gitignore');
159
250
  }
160
251
 
161
252
  // 4. package.json scripts: typecheck, and hooks path on install (never overwrite existing scripts)
162
- const pkgFile = path.join(cwd, 'package.json');
163
253
  const scripts = (pkg.scripts = pkg.scripts || {});
164
254
  let pkgChanged = false;
165
255
  // only TypeScript projects get typecheck: tsc fails ("no inputs") in JavaScript apps that merely have typescript installed
166
256
  const hasTs = git(cwd, 'ls-files', '*.ts', '*.tsx').split('\n').some(f => f && !f.endsWith('.d.ts'));
167
257
  if (!scripts.typecheck && deps.typescript && hasTs) { scripts.typecheck = 'tsc --noEmit'; pkgChanged = true; }
168
- const hooksCmd = 'git config core.hooksPath .githooks || true';
169
258
  if (!(scripts.postinstall || '').includes('core.hooksPath')) {
170
259
  // parentheses keep the existing script's failure behavior: `a && b || true` would hide a failing `a`
171
- scripts.postinstall = scripts.postinstall ? `${scripts.postinstall} && (${hooksCmd})` : hooksCmd;
260
+ scripts.postinstall = scripts.postinstall ? `${scripts.postinstall} && (${HOOKS_CMD})` : HOOKS_CMD;
172
261
  pkgChanged = true;
173
262
  }
174
- if (pkgChanged) { fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`); report.merged.push('package.json (scripts)'); }
263
+ if (pkgChanged) { fs.writeFileSync(path.join(cwd, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`); done.merged.push('package.json (scripts)'); }
175
264
 
176
265
  // 5. activate the git hooks now
177
266
  git(cwd, 'config', 'core.hooksPath', '.githooks');
178
267
 
179
268
  // 6. tool configs for the chosen tools (permissions, hooks, subagents)
180
269
  const rsFile = path.join(cwd, 'rulesync.jsonc');
181
- const rs = fs.readFileSync(rsFile, 'utf8');
182
- const targets = tools.flatMap(t => TOOLS[t]);
183
- fs.writeFileSync(rsFile, rs.replace(/"targets":\s*\[[^\]]*\]/, `"targets": ${JSON.stringify(targets)}`));
270
+ fs.writeFileSync(rsFile, setTargets(fs.readFileSync(rsFile, 'utf8'), tools.flatMap(t => TOOLS[t])));
184
271
  let generated = true;
185
272
  let generateError = '';
186
- if (!opts.skipGenerate) {
187
- // when init itself runs under npx, npm_config_* variables (e.g. the outer --package) would leak into this npx
188
- const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !/^npm_(config|package|lifecycle)_/i.test(k)));
189
- const r = spawnSync('npx', ['-y', RULESYNC, 'generate'], { cwd, env, encoding: 'utf8' });
273
+ if (!skipGenerate) {
274
+ const r = spawnSync('npx', ['-y', RULESYNC, 'generate'], { cwd, env: cleanEnv(), encoding: 'utf8' });
190
275
  generated = r.status === 0;
191
276
  if (!generated) generateError = `${r.stderr || ''}${r.stdout || ''}`.trim().split('\n').slice(-5).join('\n');
192
277
  }
278
+ return { done, generated, generateError };
279
+ }
193
280
 
194
- return { report, values, tools, generated, generateError };
281
+ function init(cwd, opts = {}) {
282
+ const { pkg, deps } = checkProject(cwd);
283
+ const pm = detectPm(cwd, opts.pm);
284
+ const tools = opts.tools || TESTED;
285
+ for (const t of tools) if (!TOOLS[t]) throw new InitError(`Unknown tool "${t}". Choose from: ${Object.keys(TOOLS).join(', ')}.`);
286
+ const template = opts.template || TEMPLATE;
287
+ const ci = chooseCi(cwd, readIf(path.join(cwd, 'AGENTS.md')), opts.ci);
288
+ const values = projectValues(cwd, pkg, deps, pm, ci);
289
+ const targets = tools.flatMap(t => TOOLS[t]);
290
+ const report = { created: [], merged: [], skipped: [] };
291
+
292
+ // 1. template files (never overwrite)
293
+ for (const rel of templateFiles(template)) {
294
+ if (ciGroup(rel) && !ci.includes(ciGroup(rel))) continue;
295
+ const dest = path.join(cwd, rel);
296
+ const text = kitText(template, rel, values, targets);
297
+ const current = readIf(dest);
298
+ if (current !== null && (rel === 'AGENTS.md' || rel === 'CLAUDE.md')) {
299
+ const next = rel === 'AGENTS.md' ? mergeAgents(current, text) : mergeClaude(current);
300
+ if (next !== current) { fs.writeFileSync(dest, next); report.merged.push(rel); } else report.skipped.push(rel);
301
+ continue;
302
+ }
303
+ if (fs.existsSync(dest)) { report.skipped.push(rel); continue; }
304
+ writeKitFile(cwd, rel, text);
305
+ report.created.push(rel);
306
+ }
307
+
308
+ const { done, generated, generateError } = finish(cwd, { pkg, deps, tools, template, skipGenerate: opts.skipGenerate });
309
+ for (const k of Object.keys(report)) report[k].push(...done[k]);
310
+ return { report, values, tools, ci, generated, generateError };
195
311
  }
196
312
 
197
- function isLink(p) { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } }
313
+ function sync(cwd, opts = {}) {
314
+ const { pkg, deps } = checkProject(cwd);
315
+ const agents = readIf(path.join(cwd, 'AGENTS.md'));
316
+ if (!agents || !MARKERS.test(agents)) throw new InitError('The kit isn\'t installed here (AGENTS.md has no KIT section). Run init instead.');
317
+ const { from, dir: oldDir, exact } = oldTemplate(agents, opts);
318
+ const template = opts.template || TEMPLATE;
319
+ const ci = chooseCi(cwd, agents, opts.ci);
320
+ // a CI part chosen just now was never installed, so its files are new rather than deleted by the team
321
+ const hadCi = installedCi(cwd, agents);
322
+ const wasInstalled = rel => !ciGroup(rel) || hadCi.includes(ciGroup(rel));
323
+ const values = projectValues(cwd, pkg, deps, detectPm(cwd, opts.pm), ci);
324
+ const tools = installedTools(cwd);
325
+ const targets = tools.flatMap(t => TOOLS[t]);
326
+ const report = { updated: [], added: [], merged: [], conflicts: [], removed: [], kept: [] };
327
+ const newFiles = templateFiles(template);
328
+ const oldFiles = new Set(templateFiles(oldDir));
329
+
330
+ for (const rel of newFiles) {
331
+ if (ciGroup(rel) && !ci.includes(ciGroup(rel))) continue;
332
+ const kitNew = kitText(template, rel, values, targets);
333
+ const kitOld = oldFiles.has(rel) && wasInstalled(rel) ? kitText(oldDir, rel, values, targets) : null;
334
+ const current = projectText(cwd, rel, targets);
335
+ if (rel === 'AGENTS.md' || rel === 'CLAUDE.md') {
336
+ const next = current === null ? kitNew : rel === 'AGENTS.md' ? mergeAgents(current, kitNew) : mergeClaude(current);
337
+ if (next !== current) { fs.writeFileSync(path.join(cwd, rel), next); report.updated.push(rel); }
338
+ continue;
339
+ }
340
+ if (current === null) {
341
+ if (kitOld === null) { writeKitFile(cwd, rel, kitNew); report.added.push(rel); } else report.kept.push(`${rel} (you deleted it)`);
342
+ continue;
343
+ }
344
+ if (current === kitNew) continue;
345
+ if (kitOld === null) { report.kept.push(`${rel} (your own file; the kit now has one with this name)`); continue; }
346
+ if (current === kitOld) { writeKitFile(cwd, rel, kitNew); report.updated.push(rel); continue; }
347
+ if (PROJECT_DOCS.includes(rel)) continue;
348
+ // without an exact base, an old unchanged file would look like your edit and be kept: show every difference instead
349
+ const { text, conflicts } = merge3(current, exact ? kitOld : '', kitNew, from);
350
+ writeKitFile(cwd, rel, text);
351
+ (conflicts ? report.conflicts : report.merged).push(rel);
352
+ }
353
+ // files the kit no longer ships
354
+ for (const rel of oldFiles) {
355
+ if (newFiles.includes(rel) || !wasInstalled(rel)) continue;
356
+ const current = projectText(cwd, rel, targets);
357
+ if (current === null) continue;
358
+ 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)`);
359
+ }
198
360
 
199
- function printSummary({ report, values, tools, generated, generateError }, log = console.log) {
361
+ const { done, generated, generateError } = finish(cwd, { pkg, deps, tools, template, skipGenerate: opts.skipGenerate });
362
+ report.added.push(...done.created);
363
+ report.updated.push(...done.merged);
364
+ return { report, from, to: KIT_VERSION, tools, generated, generateError };
365
+ }
366
+
367
+ // what rulesync generates from the project's kit sources, regenerated in an empty folder: [[path, text]]
368
+ function generatedFiles(cwd) {
369
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'amk-gen-'));
370
+ fs.cpSync(path.join(cwd, '.rulesync'), path.join(dir, '.rulesync'), { recursive: true });
371
+ fs.copyFileSync(path.join(cwd, 'rulesync.jsonc'), path.join(dir, 'rulesync.jsonc'));
372
+ const r = spawnSync('npx', ['-y', RULESYNC, 'generate'], { cwd: dir, env: cleanEnv(), encoding: 'utf8' });
373
+ if (r.status !== 0) throw new InitError(`Couldn't work out which tool configs rulesync generated: ${`${r.stderr}${r.stdout}`.trim().split('\n').pop()}`);
374
+ const files = templateFiles(dir).filter(f => !f.startsWith(`.rulesync${path.sep}`) && !['rulesync.jsonc', '.gitignore'].includes(f));
375
+ const out = files.map(f => [f, fs.readFileSync(path.join(dir, f), 'utf8')]);
376
+ fs.rmSync(dir, { recursive: true, force: true });
377
+ return out;
378
+ }
379
+
380
+ function uninstall(cwd, opts = {}) {
381
+ const { pkg, deps } = checkProject(cwd);
382
+ const agents = readIf(path.join(cwd, 'AGENTS.md'));
383
+ if (!agents || !MARKERS.test(agents)) throw new InitError('The kit isn\'t installed here (AGENTS.md has no KIT section).');
384
+ const { from, dir: template } = oldTemplate(agents, opts);
385
+ const values = projectValues(cwd, pkg, deps, detectPm(cwd, opts.pm), installedCi(cwd, agents));
386
+ const targets = installedTools(cwd).flatMap(t => TOOLS[t]);
387
+ const report = { removed: [], kept: [], left: [] };
388
+ const remove = rel => { fs.unlinkSync(path.join(cwd, rel)); report.removed.push(rel); };
389
+ // listed before their sources are removed
390
+ const generated = opts.skipGenerate ? [] : generatedFiles(cwd);
391
+
392
+ for (const rel of templateFiles(template)) {
393
+ const current = projectText(cwd, rel, targets);
394
+ if (current === null) continue;
395
+ if (rel === 'AGENTS.md' || rel === 'CLAUDE.md') {
396
+ const rest = rel === 'AGENTS.md' ? current.replace(MARKERS, () => '') : current.replace(/^@AGENTS\.md[ \t]*\n?/m, '');
397
+ if (!rest.trim()) remove(rel);
398
+ else if (rest !== current) { fs.writeFileSync(path.join(cwd, rel), rest.replace(/\n+$/, '\n')); report.removed.push(`${rel} (the kit's part)`); }
399
+ continue;
400
+ }
401
+ if (current === kitText(template, rel, values, targets)) remove(rel); else report.kept.push(rel);
402
+ }
403
+ for (const [rel, text] of generated) {
404
+ const current = readIf(path.join(cwd, rel));
405
+ if (current === null) continue;
406
+ if (current === text) remove(rel); else report.kept.push(`${rel} (also has your own settings; remove the kit's entries by hand)`);
407
+ }
408
+ for (const [link] of SKILL_LINKS) {
409
+ const p = path.join(cwd, link);
410
+ if (isLink(p) && fs.readlinkSync(p) === '../.agents/skills') { fs.unlinkSync(p); report.removed.push(link); continue; }
411
+ // per-skill links inside another framework's skills folder
412
+ if (!fs.existsSync(p) || isLink(p)) continue;
413
+ for (const name of fs.readdirSync(p)) {
414
+ const q = path.join(p, name);
415
+ if (isLink(q) && fs.readlinkSync(q) === `../../.agents/skills/${name}`) { fs.unlinkSync(q); report.removed.push(path.join(link, name)); }
416
+ }
417
+ }
418
+ // folders left empty (rmdir refuses non-empty ones)
419
+ const dirs = [...new Set(report.removed.map(r => path.dirname(r.split(' (')[0])))].sort((a, b) => b.length - a.length);
420
+ for (let d of dirs) {
421
+ for (; d && d !== '.'; d = path.dirname(d)) { try { fs.rmdirSync(path.join(cwd, d)); } catch { break; } }
422
+ }
423
+
424
+ // git hooks
425
+ const scripts = pkg.scripts || {};
426
+ const postinstall = scripts.postinstall === HOOKS_CMD ? undefined : (scripts.postinstall || '').replace(` && (${HOOKS_CMD})`, '') || undefined;
427
+ if (postinstall !== scripts.postinstall) {
428
+ if (postinstall) scripts.postinstall = postinstall; else delete scripts.postinstall;
429
+ fs.writeFileSync(path.join(cwd, 'package.json'), `${JSON.stringify(pkg, null, 2)}\n`);
430
+ report.removed.push('package.json postinstall (git hooks)');
431
+ }
432
+ try { if (git(cwd, 'config', 'core.hooksPath') === '.githooks') git(cwd, 'config', '--unset', 'core.hooksPath'); } catch {}
433
+
434
+ report.left.push('.gitignore lines for .env files and .ai/ (they keep secrets and local evidence out of git)');
435
+ if (scripts.typecheck === 'tsc --noEmit') report.left.push('the "typecheck" script in package.json');
436
+ return { report, from };
437
+ }
438
+
439
+ function printSummary({ report, values, tools, ci, generated, generateError }, log = console.log) {
200
440
  log(`agentic-mobile-kit installed for ${values.APP_NAME} (React Native ${values.RN_VERSION}, ${values.PM}).`);
201
441
  log(`Tools: ${tools.join(', ')}${tools.some(t => !TESTED.includes(t)) ? ' (cursor, opencode and kiro are not tested yet)' : ''}`);
442
+ log(`CI: ${ci.length ? ci.join(', ') : 'none (add it any time with --ci github,codemagic)'}`);
202
443
  log(` created: ${report.created.length} files`);
203
444
  if (report.merged.length) log(` merged: ${report.merged.join(', ')}`);
204
445
  if (report.skipped.length) log(` kept as they were (already existed): ${report.skipped.join(', ')}`);
@@ -206,9 +447,31 @@ function printSummary({ report, values, tools, generated, generateError }, log =
206
447
  log('\nNext steps:');
207
448
  log(' 1. Fill in docs/ai/product.md, tech.md, structure.md and conventions.md for this app.');
208
449
  log(' 2. Commit on a branch and open a PR. Add the "large-pr" label (the vendored skills are large).');
209
- log(' 3. Turn on branch protection for main: see docs/branch-protection.md in the kit repo.');
210
- log(' 4. Signed store builds on Codemagic: one-time setup in docs/ai/codemagic.md.');
211
- if (tools.includes('codex')) log(' 5. Codex users: open the project in Codex once and approve its hooks (they stay off until approved).');
450
+ const more = [
451
+ ci.includes('github') && 'Turn on branch protection for main: see docs/branch-protection.md in the kit repo.',
452
+ ci.includes('codemagic') && 'Signed store builds on Codemagic: one-time setup in docs/ai/codemagic.md.',
453
+ tools.includes('codex') && 'Codex users: open the project in Codex once and approve its hooks (they stay off until approved).',
454
+ ].filter(Boolean);
455
+ more.forEach((m, i) => log(` ${i + 3}. ${m}`));
456
+ }
457
+
458
+ function printSync({ report, from, to, generated, generateError }, log = console.log) {
459
+ log(`agentic-mobile-kit updated from ${from} to ${to}.`);
460
+ const lines = [
461
+ ['updated', report.updated], ['added', report.added], ['removed', report.removed],
462
+ ['merged with your changes', report.merged], ['CONFLICTS, resolve the <<<<<<< markers', report.conflicts], ['left alone', report.kept],
463
+ ];
464
+ for (const [label, files] of lines) if (files.length) log(` ${label}: ${files.join(', ')}`);
465
+ if (!Object.values(report).some(a => a.length)) log(' Nothing to change.');
466
+ if (!generated) log(` ! could not generate tool configs; run: npx -y ${RULESYNC} generate\n${generateError.replace(/^/gm, ' ')}`);
467
+ log('\nReview it with "git diff", run the checks, then commit on a branch and open a PR.');
468
+ }
469
+
470
+ function printUninstall({ report }, log = console.log) {
471
+ log(`agentic-mobile-kit removed: ${report.removed.length} files and sections.`);
472
+ if (report.kept.length) log(` kept because you changed them: ${report.kept.join(', ')}`);
473
+ for (const l of report.left) log(` left in place: ${l}`);
474
+ log('\nReview it with "git status" and "git diff", then commit. Undo it with git if you change your mind.');
212
475
  }
213
476
 
214
- module.exports = { init, printSummary, InitError, TOOLS };
477
+ module.exports = { init, sync, uninstall, printSummary, printSync, printUninstall, InitError, TOOLS, CI, KIT_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-mobile-kit",
3
- "version": "0.3.0",
3
+ "version": "0.5.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",
@@ -6,6 +6,8 @@ disable-model-invocation: true
6
6
 
7
7
  # m-bugfix
8
8
 
9
+ The user chose this workflow: follow its steps for this task, even where other workflow instructions in this project (Superpowers, BMAD, proAgents or similar) say otherwise.
10
+
9
11
  Input: $ARGUMENTS (what's wrong, steps to reproduce, error text, screenshots, task link).
10
12
 
11
13
  1. **Check `docs/ai/known-issues.md`** for a matching error. If there is one, apply its fix and verify.
@@ -6,6 +6,8 @@ disable-model-invocation: true
6
6
 
7
7
  # m-continue
8
8
 
9
+ The user chose this workflow: follow its steps for this task, even where other workflow instructions in this project (Superpowers, BMAD, proAgents or similar) say otherwise.
10
+
9
11
  Input: $ARGUMENTS (a spec ID, or empty).
10
12
 
11
13
  1. **Check git first.** Run `git fetch` and `git status`.
@@ -6,6 +6,8 @@ disable-model-invocation: true
6
6
 
7
7
  # m-feature
8
8
 
9
+ The user chose this workflow: follow its steps for this task, even where other workflow instructions in this project (Superpowers, BMAD, proAgents or similar) say otherwise.
10
+
9
11
  Input: $ARGUMENTS (the requirement text, a file path, or a task link plus pasted details).
10
12
 
11
13
  ## 1. Always use the full flow
@@ -6,6 +6,8 @@ disable-model-invocation: true
6
6
 
7
7
  # m-learn
8
8
 
9
+ The user chose this workflow: follow its steps for this task, even where other workflow instructions in this project (Superpowers, BMAD, proAgents or similar) say otherwise.
10
+
9
11
  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
12
 
11
13
  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.
@@ -6,6 +6,8 @@ disable-model-invocation: true
6
6
 
7
7
  # m-pause
8
8
 
9
+ The user chose this workflow: follow its steps for this task, even where other workflow instructions in this project (Superpowers, BMAD, proAgents or similar) say otherwise.
10
+
9
11
  1. **Update the handoff block** at the top of `specs/<id>/progress.md`: date and time, tool and model, branch, status (start the line with `not started`, `in progress — task N of M` or `done`, exactly), done, in progress (with file paths and what's half-done), the exact next step, decisions, open question, last check results, blockers, notes. Add a line to the log.
10
12
  2. **Move decisions out of the chat.** Anything decided in this conversation goes into `requirements.md`, `design.md` or `docs/ai/decisions.md` now. Chat history doesn't travel to other tools.
11
13
  3. **Commit the work in progress** on the feature branch (never `main`): message `wip: <id> <short summary>`, ending with `Assisted-by: <tool>/<model>` and `Spec: specs/<id>`.
@@ -1,23 +1,31 @@
1
1
  ---
2
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.
3
+ description: Prepare a store release - version, changelog and store notes from real commits, release check, release PR, then the tag and the signed builds. Run only when the user explicitly invokes m-release.
4
4
  disable-model-invocation: true
5
5
  ---
6
6
 
7
7
  # m-release
8
8
 
9
- Input: $ARGUMENTS (the new version such as 1.4.0, or patch, minor or major; anything the client should hear about).
9
+ The user chose this workflow: follow its steps for this task, even where other workflow instructions in this project (Superpowers, BMAD, proAgents or similar) say otherwise.
10
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.
11
+ Input: $ARGUMENTS (the new version such as 1.4.0, or patch, minor or major; which app, if the project ships several; anything the client should hear about).
12
+
13
+ 1. **Start clean:** `main`, pulled, with a clean working tree. Find the last release with `git describe --tags --abbrev=0 --match 'v*'`.
14
+ - No tag, but the app is already in the stores: ask the user which commit was the last store release (or its date and version), and tag it locally as `v<that version>`. The changelog then starts there instead of at the first commit.
15
+ - No tag and never released: this is the first release.
12
16
  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.
17
+ 3. **Changelog from real commits:** `npx -y git-cliff@2.14.2 --unreleased --tag v<version> -o release-notes/<version>/CHANGELOG.md`. If the repo tracks a root `CHANGELOG.md` (`git ls-files CHANGELOG.md`), also add the section there with `--prepend CHANGELOG.md`. Leave the root file alone if `.gitignore` ignores it, because another tool may own it. Don't add, merge or reword entries by hand. A misleading commit message gets fixed in the notes below, not in the changelog.
18
+ 4. **Store and client notes** go in `release-notes/<version>/` too. Write them only from that changelog, so every line traces back to an entry. Leave out internal changes (refactors, CI, dependency bumps) unless users notice them.
15
19
  - `play-store.txt`: plain text for users, at most 500 characters.
16
20
  - `app-store.txt`: plain text for users, at most 4000 characters, with no `<` or `>`.
17
21
  - `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
22
 
19
23
  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.
24
+ 5. **Version and build numbers:** `sh scripts/ai/set-version.sh <version>` sets the iOS and Android version names. If the script stops because the project ships several apps, ask the user which version each app gets, and set them after they confirm.
25
+ - When `codemagic.yaml` sets build numbers, leave them alone.
26
+ - Otherwise every store upload needs a higher build number. Ask before changing native files. Then raise Android's `versionCode` in `android/app/build.gradle`, and set iOS with `cd ios && agvtool new-version -all <number>`. Never edit `project.pbxproj` by hand. iOS may keep its build number when the version name changes, if that's how the team works.
21
27
  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.
28
+ 7. **Release PR:** commit as `chore(release): <version>` (so the next changelog leaves it out), with `Assisted-by: <tool>/<model>`. Ask before pushing. Open a PR titled `Release <version>` with the changelog and the release-check output.
29
+ 8. **Tag and build, 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>`.
30
+ - With Codemagic (`codemagic.yaml`; see `docs/ai/codemagic.md`), the tag starts the signed builds.
31
+ - Without CI, the user builds signed apps on their Mac, because signing keys stay with people. Tell them to run `sh scripts/ai/release-build.sh android [flavor]` and `sh scripts/ai/release-build.sh ios [scheme]`, and to upload the results from `.ai/release/` (Play Console, and Xcode's Organizer or Transporter). Never run these yourself or ask for the keys.
@@ -6,6 +6,8 @@ disable-model-invocation: true
6
6
 
7
7
  # m-review
8
8
 
9
+ The user chose this workflow: follow its steps for this task, even where other workflow instructions in this project (Superpowers, BMAD, proAgents or similar) say otherwise.
10
+
9
11
  If your tool has subagents, hand the review to the `m-reviewer` subagent, so it looks at the code with fresh eyes. Otherwise review it yourself, read-only.
10
12
 
11
13
  ## Reviewing
@@ -1,8 +1,10 @@
1
- <!-- KIT:START agentic-mobile-kit (edit outside these markers; the kit updates what's inside) -->
1
+ <!-- KIT:START agentic-mobile-kit {{KIT_VERSION}} ci={{KIT_CI}} (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/`.
5
5
 
6
+ This project may also use other AI workflow frameworks (for example Superpowers, BMAD or proAgents). They keep working for everything else. When the user starts a task with an `m-` skill (`/m-feature`, `$m-feature`, …), follow that skill's steps for the whole task; where another framework's instructions differ, the `m-` skill wins.
7
+
6
8
  ## Project
7
9
 
8
10
  - Bare React Native {{RN_VERSION}} (New Architecture), React {{REACT_VERSION}}, TypeScript {{TS_VERSION}}, Node {{NODE_VERSION}}. Package manager: {{PM}}.
@@ -19,6 +21,7 @@ Read by Claude Code (through CLAUDE.md), Codex, Cursor, OpenCode, Kiro and Antig
19
21
  | Android build | `cd android && ./gradlew assembleDebug` |
20
22
  | Check on devices (release builds, Maestro flows, screenshots) | `sh scripts/ai/verify.sh all --spec <id>` |
21
23
  | Check a release before tagging it (versions, permission texts, debug leftovers) | `node scripts/ai/release-check.js` |
24
+ | Signed release builds (a person runs them: they use the signing keys) | `sh scripts/ai/release-build.sh android [flavor]`, `sh scripts/ai/release-build.sh ios [scheme]` |
22
25
 
23
26
  ## Definition of done
24
27
 
@@ -0,0 +1,87 @@
1
+ #!/bin/sh
2
+ # Builds signed release apps on this Mac: for apps without CI, or to check a release by hand.
3
+ # A person runs it, because it uses the signing keys, which agents must never handle.
4
+ #
5
+ # sh scripts/ai/release-build.sh android [flavor] signed app bundle (.aab) for Google Play
6
+ # sh scripts/ai/release-build.sh ios [scheme] signed .ipa for App Store Connect (TestFlight)
7
+ #
8
+ # Android signs with your upload key. Set its path in your shell, never in the repo:
9
+ # export AMK_UPLOAD_KEYSTORE=~/keys/myapp-upload.jks AMK_UPLOAD_KEY_ALIAS=upload
10
+ # The passwords are asked for, unless AMK_UPLOAD_STORE_PASSWORD and AMK_UPLOAD_KEY_PASSWORD are set.
11
+ # Without AMK_UPLOAD_KEYSTORE it uses the app's own signing setup, and stops if that's the debug key.
12
+ # iOS signs with the Apple account in Xcode (Settings > Accounts) and automatic signing; Xcode may
13
+ # create a distribution certificate or profile in that team if one is missing.
14
+ # Version and build numbers come from the repo, so set them first (the m-release skill does).
15
+ # Output: .ai/release/
16
+ set -eu
17
+ platform=${1:-}
18
+ target=${2:-}
19
+ out=.ai/release
20
+ mkdir -p "$out"
21
+
22
+ # secret VAR "question": read it without echo, unless it's already set
23
+ secret() {
24
+ eval "[ -n \"\${$1:-}\" ]" && return 0
25
+ [ -t 0 ] || { echo "Set $1 in your shell, or run this in a terminal to be asked." >&2; exit 1; }
26
+ printf '%s: ' "$2" >&2; stty -echo; read -r value; stty echo; echo >&2
27
+ eval "$1=\$value"
28
+ }
29
+
30
+ case "$platform" in
31
+ android)
32
+ flavor=$(printf %s "$target" | awk '{ print toupper(substr($0, 1, 1)) substr($0, 2) }')
33
+ if [ -n "${AMK_UPLOAD_KEYSTORE:-}" ]; then
34
+ secret AMK_UPLOAD_STORE_PASSWORD 'Keystore password'
35
+ secret AMK_UPLOAD_KEY_PASSWORD 'Key password'
36
+ # injected signing (as Android Studio's "Generate Signed Bundle" does): build.gradle stays as it is
37
+ set -- -Pandroid.injected.signing.store.file="$AMK_UPLOAD_KEYSTORE" \
38
+ -Pandroid.injected.signing.store.password="$AMK_UPLOAD_STORE_PASSWORD" \
39
+ -Pandroid.injected.signing.key.alias="${AMK_UPLOAD_KEY_ALIAS:-upload}" \
40
+ -Pandroid.injected.signing.key.password="$AMK_UPLOAD_KEY_PASSWORD"
41
+ else
42
+ set --
43
+ fi
44
+ (cd android && ./gradlew "bundle${flavor}Release" "$@")
45
+ dir=android/app/build/outputs/bundle/${target:-release}${target:+Release}
46
+ for aab in "$dir"/*.aab; do
47
+ signer=$(keytool -printcert -jarfile "$aab" | sed -n 's/^Owner: //p' | head -n 1)
48
+ case "$signer" in
49
+ ''|*'Android Debug'*) echo "$aab is signed with the debug key. Set AMK_UPLOAD_KEYSTORE (see the top of this script)." >&2; exit 1 ;;
50
+ esac
51
+ cp "$aab" "$out/"
52
+ echo "Signed by: $signer"
53
+ echo "$out/$(basename "$aab")"
54
+ done
55
+ ;;
56
+ ios)
57
+ workspace=$(ls -d ios/*.xcworkspace | head -n 1)
58
+ scheme=${target:-$(basename "$workspace" .xcworkspace)}
59
+ [ -d ios/Pods ] || (cd ios && pod install)
60
+ log="$out/$scheme-ios.log"
61
+ echo "Archiving $scheme (several minutes; log: $log)"
62
+ xcodebuild -workspace "$workspace" -scheme "$scheme" -configuration Release -destination 'generic/platform=iOS' \
63
+ -archivePath "$out/$scheme.xcarchive" -allowProvisioningUpdates archive > "$log" 2>&1 \
64
+ || { grep -E 'error:|BUILD FAILED|ARCHIVE FAILED' "$log" | head -n 20; exit 1; }
65
+ cat > "$out/ExportOptions.plist" <<'PLIST'
66
+ <?xml version="1.0" encoding="UTF-8"?>
67
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
68
+ <plist version="1.0"><dict>
69
+ <key>method</key><string>app-store-connect</string>
70
+ <key>destination</key><string>export</string>
71
+ <key>signingStyle</key><string>automatic</string>
72
+ </dict></plist>
73
+ PLIST
74
+ xcodebuild -exportArchive -archivePath "$out/$scheme.xcarchive" -exportPath "$out/$scheme" \
75
+ -exportOptionsPlist "$out/ExportOptions.plist" -allowProvisioningUpdates >> "$log" 2>&1 \
76
+ || { grep -E 'error:|EXPORT FAILED' "$log" | head -n 20; exit 1; }
77
+ ipa=$(ls "$out/$scheme"/*.ipa | head -n 1)
78
+ # the export re-signs for distribution, so check the app inside the .ipa, not the archive
79
+ unzip -oq "$ipa" -d "$out/$scheme/unzipped"
80
+ echo "Signed by: $(codesign -dvv "$out/$scheme/unzipped"/Payload/*.app 2>&1 | sed -n 's/^Authority=//p' | head -n 1)"
81
+ echo "$ipa"
82
+ ;;
83
+ *)
84
+ sed -n '2,16p' "$0"
85
+ exit 1
86
+ ;;
87
+ esac
@@ -49,7 +49,7 @@ const iosBuilds = t => all(/CURRENT_PROJECT_VERSION = ([^;]+);/g, t);
49
49
  const androidVersions = t => all(/versionName\s*=?\s*"([^"]+)"/g, stripComments(t));
50
50
  const androidBuilds = t => all(/versionCode\s*=?\s*(\d+)/g, stripComments(t));
51
51
 
52
- function compare(platform, now, before, kind) {
52
+ function compare(platform, now, before, kind, versionChanged) {
53
53
  if (kind === 'build number' && ciBuildNumber[platform]) { info(`${platform} build number: set by Codemagic at build time`); return; }
54
54
  if (!now.length) { warn(`${platform} ${kind}: couldn't read it`, 'check it by hand before you ship'); return; }
55
55
  if (!before) { info(`${platform} ${kind}: ${now.join(', ')}`); return; }
@@ -57,6 +57,9 @@ function compare(platform, now, before, kind) {
57
57
  if (kind === 'build number' && before.length && maxNum(now) < maxNum(before)) {
58
58
  fail(`${platform} build number went down (${before.join(', ')} → ${now.join(', ')})`, 'stores reject a build number lower than the last upload');
59
59
  } else ok(`${platform} ${kind}`, `${before.join(', ') || '?'} → ${now.join(', ')}`);
60
+ } else if (kind === 'build number' && platform === 'iOS' && versionChanged) {
61
+ // the App Store needs a new build number only within a version, so 1 again for a new version is fine
62
+ ok(`${platform} build number (${now.join(', ')} again, for a new version)`);
60
63
  } else if (kind === 'build number') {
61
64
  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
65
  } else {
@@ -66,8 +69,9 @@ function compare(platform, now, before, kind) {
66
69
 
67
70
  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
71
  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');
72
+ const [now, before] = [iosVersions(pbx), since && iosVersions(readAt(since, pbxPath))];
73
+ compare('iOS', now, before, 'version');
74
+ compare('iOS', iosBuilds(pbx), since && iosBuilds(readAt(since, pbxPath)), 'build number', before && now.join() !== before.join());
71
75
  }
72
76
  if (gradle) {
73
77
  compare('Android', androidVersions(gradle), since && androidVersions(readAt(since, gradlePath)), 'version');
@@ -76,7 +80,7 @@ if (gradle) {
76
80
  if (pbx && gradle) {
77
81
  const a = iosVersions(pbx), b = androidVersions(gradle);
78
82
  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');
83
+ info(`iOS shows version ${a.join(', ')}, Android shows ${b.join(', ')}`, 'users and support see different numbers; fine if your team numbers the platforms separately');
80
84
  }
81
85
  }
82
86
 
@@ -168,7 +172,8 @@ const releaseBlock = block(block(gradle, 'buildTypes'), 'release');
168
172
  if (/debuggable\s*=?\s*true/.test(releaseBlock)) fail('Android release build is debuggable', 'remove "debuggable true" from buildTypes.release; Play rejects debuggable apps');
169
173
  if (/android\.injected\.signing/.test(codemagic)) ok('Android release signing', 'Codemagic signs with the upload key');
170
174
  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');
175
+ // the kit's release-build.sh (and Codemagic) sign with the upload key, and Play rejects debug-signed uploads anyway
176
+ info('build.gradle signs release builds with the debug key', 'build store releases with sh scripts/ai/release-build.sh android, which signs with your upload key');
172
177
  }
173
178
  if (/android:usesCleartextTraffic="true"/.test(readNow(manifestPath) || '')) {
174
179
  warn('Android allows cleartext (HTTP) traffic', 'allow only the domains that need it (network security config)');