agentic-mobile-kit 0.14.2 → 0.15.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/lib/init.js CHANGED
@@ -722,10 +722,10 @@ function finish(cwd, { pkg, deps, tools, files, stack, skipGenerate }) {
722
722
  // .maestro/.amk-*: the copies of flows with view-tree steps that verify.sh runs on Android, there only while they run
723
723
  // node_modules without the slash: a git worktree often links the project's node_modules, and node_modules/ matches
724
724
  // only a folder, so git add -A would commit the link
725
- const ignored = ['.env', '.env.*', '!.env*.example', '!.env*.sample', '!.env*.template', '.amk/', '.maestro/.amk-*', 'node_modules', ...(stack === 'expo' ? ['/ios', '/android'] : [])];
725
+ const ignored = ['.env', '.env.*', '!.env*.example', '!.env*.sample', '!.env*.template', '.amk/', '.maestro/.amk-*', 'node_modules', '.claude/worktrees/', ...(stack === 'expo' ? ['/ios', '/android'] : [])];
726
726
  const missing = ignored.filter(l => !giText.split('\n').includes(l));
727
727
  if (missing.length) {
728
- fs.writeFileSync(gi, `${giText.replace(/\n*$/, giText ? '\n' : '')}\n# agentic-mobile-kit: secrets stay out of git; .amk/ holds local evidence (screenshots, logs), .maestro/.amk-* the flows verify.sh is running; node_modules also as a link (a worktree's)${stack === 'expo' ? '; ios/ and android/ are generated' : ''}\n${missing.join('\n')}\n`);
728
+ fs.writeFileSync(gi, `${giText.replace(/\n*$/, giText ? '\n' : '')}\n# agentic-mobile-kit: secrets stay out of git; .amk/ holds local evidence (screenshots, logs), .maestro/.amk-* the flows verify.sh is running; node_modules also as a link (a worktree's); .claude/worktrees/ Claude Code's worktrees${stack === 'expo' ? '; ios/ and android/ are generated' : ''}\n${missing.join('\n')}\n`);
729
729
  done.merged.push('.gitignore');
730
730
  }
731
731
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-mobile-kit",
3
- "version": "0.14.2",
3
+ "version": "0.15.0",
4
4
  "description": "One setup for AI-assisted development of React Native apps, bare or Expo: shared rules and workflows for Claude Code, Codex and Antigravity, git hooks, device checks with screenshots, and release tooling for the App Store and Google Play.",
5
5
  "license": "MIT",
6
6
  "author": "prakashpro1",
@@ -21,7 +21,7 @@ Input: $ARGUMENTS (what's wrong, steps to reproduce, error text, screenshots, ta
21
21
  - Test them in that order, one change at a time. Tag every log you add while debugging with `[amk-debug]`, and remove them all before committing: `git grep amk-debug` finds them.
22
22
  - Fix the cause, not the symptom: no try/catch that hides the error, no special case for the failing input.
23
23
  4. **Make the smallest fix.** Don't refactor or touch unrelated code.
24
- 5. **Verify.** The check from step 2 passes now, and stays in the project so the bug can't come back unnoticed. Then follow `.agents/skills/m-test/SKILL.md` for the spec its flow is named after, so the area's other checks run too; without one, `sh scripts/amk/verify.sh quick` and, for a bug on the device, `sh scripts/amk/verify.sh ios --flow <path>` and `android`, looking at the screenshots (`--screens` limits it to the screens the bug is on, such as `--screens tablet-landscape`). Paste the output.
24
+ 5. **Verify.** The check from step 2 passes now, and stays in the project so the bug can't come back unnoticed. Then follow `.agents/skills/m-test/SKILL.md` for `<the spec its flow is named after> --changed`: the flows reaching what the fix changed; without a spec, `sh scripts/amk/verify.sh quick`, and for a bug on the device `sh scripts/amk/verify.sh ios --changed` and `android`, looking at the screenshots (`--screens tablet-landscape`, say, for the screens the bug is on). Paste the output.
25
25
  6. **Two attempts at most.** If two fixes didn't work, stop. Report what you tried, what you learned and what you suspect next.
26
26
  7. **Record it.** If this kind of error could come back, add an entry to `docs/amk/known-issues.md` (error, cause, fix, prevention). If the fix changes what the app is meant to do, not just makes it work as specified, update that requirement in `specs/current/<area>.md` in the same format, and run `node scripts/amk/specs.js check`. A case the spec didn't cover becomes a scenario of its requirement there, and the check from step 2 is named after it: the Jest test's title, or a `# Scenario: <name>` block in the bug's flow.
27
27
  8. **Commit** on a branch of its own (`fix/<issue number>`, else `fix/<slug>`), with a message naming the cause you confirmed, for whoever debugs it next. Ask before pushing, then open a PR with the evidence; for an issue, its description says `Fixes #<number>`.
@@ -38,7 +38,7 @@ If no requirement changes, as with a pure style change, skip the spec files (ste
38
38
  1. Pick an ID: the task's ID if it has one, otherwise `YYYYMMDD-<slug>`. Write `specs/<id>/requirements.md` with a title, a one-line goal and only the requirements that change, under `## MODIFIED Requirements: <area>` (or ADDED or REMOVED; the format is in `specs/current/README.md`). Run `node scripts/amk/specs.js check specs/<id>/requirements.md`.
39
39
  2. Change the code, and add or update a test where logic changed. A text it adds or changes, in an app with language files, goes into each language's file and `specs/<id>/translations.md`, as the React Native rules file `AGENTS.md` names says (Texts in several languages).
40
40
  3. Run `sh scripts/amk/verify.sh quick` and show its output.
41
- 4. For a visible change, write `.maestro/<id>.yaml` (`node scripts/amk/specs.js flow <id>` starts it from `specs/_templates/flow.yaml`): open the changed screen and take a screenshot. Then follow `.agents/skills/m-test/SKILL.md` for `<id>`, which checks it on the devices with the flows of the area it changes and writes the test report. Off a Mac it checks Android only: say that iOS still needs checking on a Mac.
41
+ 4. For a visible change, write `.maestro/<id>.yaml` (`node scripts/amk/specs.js flow <id>` starts it from `specs/_templates/flow.yaml`): open the changed screen and take a screenshot. Then follow `.agents/skills/m-test/SKILL.md` for `<id> --changed`, which checks it on the devices with the flows of the area it changes and writes the test report. Off a Mac it checks Android only: say that iOS still needs checking on a Mac.
42
42
  5. Run `node scripts/amk/specs.js merge <id>` to update the living spec, and change the doc lines from step 3.
43
43
  6. Copy `specs/_templates/progress.md` to `specs/<id>/progress.md`, set `Status: done`, and write down the checks and their results.
44
44
 
@@ -30,7 +30,7 @@ If the input describes a bug rather than new behavior, suggest `m-bugfix` and st
30
30
 
31
31
  ## 2. Requirements (then stop for approval)
32
32
 
33
- 1. Pick an ID: the task's ID if it has one, otherwise `YYYYMMDD-<slug>`. Copy `requirements.md`, `design.md`, `tasks.md` and `progress.md` from `specs/_templates/` to `specs/<id>/`. If `specs/<id>/` already has a draft from `m-explore` or `m-prototype`, keep it and copy only the missing files.
33
+ 1. Pick an ID: the task's ID if it has one, otherwise `YYYYMMDD-<slug>`. Run `node scripts/amk/specs.js branch <id>`: it makes the feature's branch, on a feature branch not merged yet when there is one (this one builds on it), else on main, and says which. Copy `requirements.md`, `design.md`, `tasks.md` and `progress.md` from `specs/_templates/` to `specs/<id>/`. If `specs/<id>/` already has a draft from `m-explore` or `m-prototype`, keep it and copy only the missing files.
34
34
  2. Read `specs/current/<area>.md` for each area this touches: it says what the app does now. In an area with no living spec yet, read the code that implements it.
35
35
  3. **One intent.** The feature should be one thing you can say in a sentence. If it needs "and also", suggest splitting it into separate features, and ask.
36
36
  4. Fill `requirements.md`: the goal; the user stories (who it's for and why, each naming its requirements) and use cases (the journey and what can go differently, each alternative flow and exception naming the scenario that tests it); the requirements under `## ADDED`, `## MODIFIED` and `## REMOVED Requirements: <area>` (the format is in `specs/current/README.md`), with one SHALL per requirement and scenarios for the cases that matter; every edge-case line (or "n/a"); out of scope; open questions. Use the app's words from `docs/amk/glossary.md`; a new word, or one used two ways, gets settled with the user and added there. Then run `node scripts/amk/specs.js check specs/<id>/requirements.md`.
@@ -47,7 +47,7 @@ If the input describes a bug rather than new behavior, suggest `m-bugfix` and st
47
47
  1. **Ask for the UI/UX level first, when the feature has screens**, in one round with any other open design question: which level its screens should have (a single choice, with a preview of each where your tool shows one): Simple (clean, minimal and functional), Mixed (simple, with modern touches) or Premium (polished, following current design trends; it takes longer). `specs/_templates/design.md` describes each. Offer as the default the level a prototype settled (under `## Decisions` in `requirements.md`), otherwise the one the app's other screens have (an earlier spec's `design.md`), otherwise Simple. Don't design until the user has answered. Write the answer and the date under "UI/UX level" in `design.md` (n/a for a feature without screens).
48
48
  2. **Search the codebase before designing.** List the components, hooks, API clients and helpers you'll reuse in `design.md` under "Existing code to reuse". Read `docs/amk/structure.md` and `docs/amk/conventions.md`.
49
49
  3. Fill `design.md`: approach, files to change, risks (native changes, pod install, migrations), and `## Tests`. For those, run `node scripts/amk/specs.js tests <id>`: give each scenario its check (a Jest test named after it, a flow block, or manual steps for what a flow can't do), say what happens to the tests of the requirements this modifies or removes, and take the regression command it prints, adding the flows no spec links to that this touches. Calls the backend doesn't have yet: `## API contract`.
50
- 4. Fill `tasks.md`: small tasks (about an hour, under ~300 changed lines each), each a thin slice through every layer it needs (screen, state, API call, test) that works and can be checked on its own, rather than one layer at a time. Changes that make the feature easy to add (moving or renaming code that's there) come first, as their own task. Each task names the requirement it serves, the tasks it waits on (`after:`) and how it's checked, and its tests are written in the same task, not left for the end. The last task writes `.maestro/<id>.yaml` (`node scripts/amk/specs.js flow <id>` starts it from `specs/_templates/flow.yaml`, a block for each scenario): a Maestro flow with a `# Scenario <n>: <name>` comment above each scenario's steps, an assertion for its THEN and a screenshot, tapping elements by `testID` and scrolling to the ones further down a screen first (`scrollUntilVisible`): turned screens are short. A screen that loads data gets a scenario and a screenshot for its empty and error states too, where a flow can reach them (cleared data, or an account without any, for empty; `setAirplaneMode: enabled` for no network). When the feature adds screens, the task for its main screen comes first among them and ends with a look check: the start of `.maestro/<id>.yaml` opens that screen and takes its screenshot, run with `sh scripts/amk/verify.sh ios --flow .maestro/<id>.yaml --screens phone` (or `android`).
50
+ 4. Fill `tasks.md`: small tasks (about an hour, under ~300 changed lines each), each a thin slice through every layer it needs (screen, state, API call, test) that works and can be checked on its own, rather than one layer at a time. Changes that make the feature easy to add (moving or renaming code that's there) come first, as their own task. Each task names the requirement it serves, the tasks it waits on (`after:`) and how it's checked, and its tests are written in the same task, not left for the end. The last task writes `.maestro/<id>.yaml`: `node scripts/amk/specs.js flow <id>` starts it from `specs/_templates/flow.yaml`, whose comments say how (a `# Scenario` block per scenario with its assertion and screenshot, `testID` taps, empty and error states, starting at the screen). When the feature adds screens, the task for its main screen comes first among them and ends with a look check: the start of `.maestro/<id>.yaml` opens that screen and takes its screenshot, run with `sh scripts/amk/verify.sh ios --flow .maestro/<id>.yaml --screens phone` (or `android`).
51
51
  5. Show design and tasks and **stop until the user approves them**: a question of its own, asked once no question is open. Ask them to check that every task serves an approved requirement and nothing goes beyond the agreed scope.
52
52
 
53
53
  From here the plan lives in files, so the building can also run in a fresh session or another tool with `m-continue <id>`.
@@ -79,6 +79,6 @@ Then update the `docs/amk/` files the feature made untrue: a new key journey in
79
79
  ## 7. Review and pull request
80
80
 
81
81
  1. Run `m-review` (or the `m-reviewer` subagent, if your tool has subagents). Fix real problems only; skip style nits.
82
- 2. Ask the user before pushing. Then push the feature branch (never `main`) and open a PR. Start the description with the requirements this adds, changes and removes, so reviewers read what should be true before the code. Then add the evidence: lint, typecheck and test output, and the screenshot for each scenario. Then the risk: whether it can be undone once a store build ships (native changes, data saved in a new format, and API changes that installed versions still rely on can't be; JavaScript can be fixed in the next release), and what else it could break. Use `.github/pull_request_template.md` if the repo has one.
82
+ 2. Ask the user before pushing. Then push the feature branch (never `main`) and open a PR against the branch it started from (`progress.md`'s start line); once that one merges, `node scripts/amk/pr.js forward` moves it to main. Start the description with the requirements this adds, changes and removes, so reviewers read what should be true before the code. Then add the evidence: lint, typecheck and test output, and the screenshot for each scenario. Then the risk: whether it can be undone once a store build ships (native changes, data saved in a new format, and API changes that installed versions still rely on can't be; JavaScript can be fixed in the next release), and what else it could break. Use `.github/pull_request_template.md` if the repo has one.
83
83
 
84
84
  Never claim a check passed without running it in this session.
@@ -8,17 +8,17 @@ disable-model-invocation: true
8
8
 
9
9
  The user chose this workflow, directly or through `m-feature`, `m-change`, `m-bugfix` or `m-release`: follow its steps, even where other workflow instructions in this project (Superpowers, BMAD, proAgents or similar) say otherwise.
10
10
 
11
- Input: $ARGUMENTS (a spec ID; or `release <version>`, with the flows `m-release` chose).
11
+ Input: $ARGUMENTS (a spec ID, with `--changed` from `m-change` and `m-bugfix`: only the flows that reach what the branch changed; or `release <version>`, with the flows `m-release` chose).
12
12
 
13
13
  1. **Scope.** The spec's test plan (`## Tests` in `design.md`), or its scenarios when it has none, and `node scripts/amk/specs.js tests <id>` (a release: `specs.js tests`): the flows to run, the tests to change or retire, and the scenarios nothing checks.
14
14
  2. **Code checks.** `sh scripts/amk/verify.sh quick --label <id>` (the whole test suite, compared with the base branch), and `node scripts/amk/coverage.js check` when the app has `.amk-coverage`. Their output stays in `.amk/evidence/<id>/`.
15
- 3. **Devices,** for the flows the scope lists: `sh scripts/amk/verify.sh plan` with the options of the test plan's regression command (`--spec <id>,<the specs of the areas it touches> --label <id>`), and `--mock` while a call in the design's `## API contract` isn't on the backend yet (its evidence is then in `.amk/evidence/<id>-mock/`). It says how many devices this machine's memory can check at the same time, and prints the commands.
15
+ 3. **Devices,** for the flows the scope lists: `sh scripts/amk/verify.sh plan` with the options of the test plan's regression command (`--spec <id>,<the specs of the areas it touches> --label <id>`; with `--changed`, `--changed --spec <id> --label <id>`), and `--mock` while a call in the design's `## API contract` isn't on the backend yet (its evidence is then in `.amk/evidence/<id>-mock/`). It says how many devices this machine's memory can check at the same time, and prints the commands.
16
16
  - **One command** (`verify.sh all` with those options): run it.
17
17
  - **A plan, and your tool has subagents:** run its `quick` and `build` commands as printed (nothing added: the plain commands are the ones people allow), then, round by round, start one `m-device-checker` subagent per device command of the round, all at once, and wait for their reports before the next round. When all are back, check them yourself: every screen has screenshots in its folder, or in each `part-k/` folder when its flows ran in parts. A report alone isn't evidence. Without subagents, run that `verify.sh all` command instead.
18
18
 
19
19
  `verify.sh` compares each screenshot with the approved one and lists those that changed: open every one it lists, and at least one per screen. Once the user accepts how they look, `sh scripts/amk/verify.sh approve --label <id>` makes them the approved ones. Off a Mac it checks Android only: iOS is blocked (no Mac) until a teammate runs it. Maestro can report a tap as passed when nothing happened, so the screenshots are the evidence, not the log.
20
20
  4. **The verdict.** Give the `m-tester` subagent the spec ID (or the release), the evidence folder and what didn't run and why; without subagents, follow `.rulesync/subagents/m-tester.md` yourself. It gives each scenario a status and ends with Ready or Not ready.
21
21
  5. **The report.** Write `specs/<id>/test-report.md` (a release: `release-notes/<version>/test-report.md`) from `specs/_templates/test-report.md`, and show the verdict.
22
- 6. **After a fix,** run the failed flows again with `--flow <file>`, then the whole set, and update the report. After two failed attempts at the same fix, stop and report.
22
+ 6. **After a fix,** run the failed flows again with `--flow <file> --screens phone-portrait` (one screen while fixing), then the whole set on every screen, and update the report. After two failed attempts at the same fix, stop and report.
23
23
 
24
24
  Never count a check as passed without this run's evidence.
@@ -7,6 +7,10 @@
7
7
  // so it also runs in PowerShell. No matcher: runs for every tool call; guard.js decides from the payload
8
8
  "preToolUse": [{ "command": "node -e \"require(require('child_process').execSync('git rev-parse --show-toplevel').toString().trim() + '/scripts/amk/guard.js')\"" }],
9
9
  "stop": [{ "command": "node -e \"require(require('child_process').execSync('git rev-parse --show-toplevel').toString().trim() + '/scripts/amk/handoff-check.js')\"" }],
10
+ // when the AI waits for you, a notification (scripts/amk/notify.js): Claude Code's permission prompts and replies it
11
+ // has waited a minute for, Codex's approvals. Every finished turn comes from the stop hook (handoff-check.js)
12
+ "notification": [{ "command": "node -e \"require(require('child_process').execSync('git rev-parse --show-toplevel').toString().trim() + '/scripts/amk/notify.js').hook()\"" }],
13
+ "permissionRequest": [{ "command": "node -e \"require(require('child_process').execSync('git rev-parse --show-toplevel').toString().trim() + '/scripts/amk/notify.js').hook()\"" }],
10
14
  // after a compaction (Claude Code, and Codex where it calls it), the spec's handoff, next task and definition of done
11
15
  "sessionStart": [{ "matcher": "compact", "command": "node -e \"require(require('child_process').execSync('git rev-parse --show-toplevel').toString().trim() + '/scripts/amk/handoff-check.js')\"" }]
12
16
  }
@@ -43,7 +43,10 @@ if (payload.hook_event_name === 'SessionStart') {
43
43
  process.exit(0);
44
44
  }
45
45
 
46
- if (payload.stop_hook_active && !unattended) process.exit(0); // already reminded once; don't loop
46
+ // the turn really ends here (nothing below asks to go on): tell the developer, who may be in another window
47
+ const ends = () => { try { require('./notify.js').notify({ ...payload, hook_event_name: 'Stop' }); } catch {} process.exit(0); };
48
+
49
+ if (payload.stop_hook_active && !unattended) ends(); // already reminded once; don't loop
47
50
 
48
51
  // unattended: the feature's state at this stop (its last commit, ticked tasks and next step)
49
52
  const progress = unattended && own ? read(`specs/${own}/progress.md`) || '' : null;
@@ -57,7 +60,8 @@ if ((working.length || progress !== null) && !payload.stop_hook_active) {
57
60
  const link = f => { try { return fs.lstatSync(path.join(root, f)).isSymbolicLink(); } catch { return false; } };
58
61
  const changed = sh('git status --porcelain --untracked-files=all')
59
62
  .split('\n').filter(Boolean).filter(l => !(l.startsWith('?? ') && link(l.slice(3)))).map(l => l.slice(3));
60
- const codeChanged = changed.some(f => !f.startsWith('specs/') && !f.startsWith('.amk/'));
63
+ // not the AI tool's worktrees inside the project (Claude Code's .claude/worktrees/): another session's work
64
+ const codeChanged = changed.some(f => !f.startsWith('specs/') && !f.startsWith('.amk/') && !f.startsWith('.claude/worktrees/'));
61
65
  const handoffUpdated = changed.some(f => /^specs\/[^/]+\/progress\.md$/.test(f));
62
66
  if (codeChanged && !handoffUpdated) {
63
67
  process.stderr.write('There are uncommitted code changes, but no specs/<id>/progress.md was updated. ' +
@@ -104,4 +108,4 @@ if (progress !== null && !fs.existsSync(path.join(root, '.amk', 'build', 'STOP')
104
108
  process.exit(2);
105
109
  }
106
110
  }
107
- process.exit(0);
111
+ ends();
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ // Tells you when the AI waits for you, so a session in another window doesn't sit there unanswered: a desktop
3
+ // notification (macOS, Linux with notify-send, Windows) and, with AMK_NOTIFY_URL set, a chat or phone webhook (Slack,
4
+ // Google Chat, Discord). Hooks of the AI tool start it:
5
+ // Notification (Claude Code) a permission prompt, or a reply it has waited a minute for
6
+ // PermissionRequest (Codex) an approval (Claude Code says those through Notification)
7
+ // Stop (every tool) every finished turn, from handoff-check.js once the turn really ends: what it asks
8
+ // AMK_NOTIFY=off turns it off; AMK_NOTIFY=ask keeps the approvals, the waiting and the turns that end with a question.
9
+ // An unattended build (autopilot.js) notifies by itself, so nothing comes from here then.
10
+ 'use strict';
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+ const { spawn, spawnSync } = require('child_process');
15
+ const { redact } = require('./redact.js');
16
+
17
+ const root = path.join(__dirname, '..', '..');
18
+
19
+ // what the AI said last: the payload's, or the last assistant text in its transcript (one JSON event a line)
20
+ function lastWords(p) {
21
+ if (typeof p.last_assistant_message === 'string') return p.last_assistant_message;
22
+ try {
23
+ for (const line of fs.readFileSync(p.transcript_path, 'utf8').trim().split('\n').reverse()) {
24
+ let e;
25
+ try { e = JSON.parse(line); } catch { continue; }
26
+ const c = e.type === 'assistant' && e.message && e.message.content;
27
+ const text = Array.isArray(c) ? c.filter(x => x && x.type === 'text').map(x => x.text).join('\n') : typeof c === 'string' ? c : '';
28
+ if (text.trim()) return text;
29
+ }
30
+ } catch {}
31
+ return '';
32
+ }
33
+ const toolOf = (p, env) => (/[\\/]\.claude[\\/]/.test(p.transcript_path || '') || env.CLAUDECODE ? 'Claude Code'
34
+ : /[\\/]\.codex[\\/]/.test(p.transcript_path || '') ? 'Codex' : 'The AI');
35
+
36
+ // the notification for a hook's payload: { title, text }, or null
37
+ function message(p, env = process.env) {
38
+ const mode = String(env.AMK_NOTIFY || 'on').toLowerCase();
39
+ if (env.AMK_AUTOPILOT || ['off', '0', 'no', 'false'].includes(mode)) return null;
40
+ const project = path.basename(root);
41
+ const tool = toolOf(p, env);
42
+ const event = p.hook_event_name || '';
43
+ if (event === 'Notification') return { title: `${project}: ${tool} is waiting for you`, text: p.message || 'It needs your answer or approval.' };
44
+ if (event === 'PermissionRequest') {
45
+ if (tool === 'Claude Code') return null;
46
+ const input = p.tool_input || {};
47
+ return { title: `${project}: ${tool} needs your approval`, text: String(input.command || input.file_path || p.tool_name || 'a command') };
48
+ }
49
+ if (event !== 'Stop') return null;
50
+ const lines = lastWords(p).split('\n').map(l => l.replace(/[*_`#>]/g, '').trim()).filter(Boolean);
51
+ const question = lines.filter(l => /\?$/.test(l)).pop() || lines.find(l => /\bapprov/i.test(l));
52
+ if (mode === 'ask' && !question) return null;
53
+ return { title: `${project}: ${tool} ${question ? 'asks you' : 'finished'}`, text: question || lines[0] || 'Its turn is over.' };
54
+ }
55
+
56
+ // the desktop notification now, the webhook in a process of its own: a hook returns at once. Those processes start in
57
+ // the temp folder: on Windows a process holds the folder it runs in, and the project's would be locked meanwhile
58
+ function send(n, env = process.env) {
59
+ const text = redact(n.text).replace(/[\u0000-\u001f\u2028\u2029]+/g, ' ').slice(0, 300);
60
+ const title = n.title.slice(0, 120);
61
+ try {
62
+ if (process.platform === 'darwin') spawnSync('osascript', ['-e', `display notification ${JSON.stringify(text)} with title ${JSON.stringify(title)}`], { stdio: 'ignore', timeout: 10000 });
63
+ else if (process.platform === 'linux') spawnSync('notify-send', [title, text], { stdio: 'ignore', timeout: 10000 });
64
+ else if (process.platform === 'win32') {
65
+ const q = s => `'${s.replace(/'/g, "''")}'`;
66
+ spawn('powershell', ['-NoProfile', '-Command', `Add-Type -AssemblyName System.Windows.Forms; $n = New-Object System.Windows.Forms.NotifyIcon; $n.Icon = [System.Drawing.SystemIcons]::Information; $n.Visible = $true; $n.ShowBalloonTip(10000, ${q(title)}, ${q(text)}, 'Info'); Start-Sleep 10; $n.Dispose()`],
67
+ { detached: true, stdio: 'ignore', windowsHide: true, cwd: os.tmpdir() }).on('error', () => {}).unref();
68
+ }
69
+ } catch {}
70
+ if (!env.AMK_NOTIFY_URL) return;
71
+ // Slack and Google Chat read text, Discord content
72
+ const body = JSON.stringify({ text: `${title}: ${text}`, content: `${title}: ${text}` });
73
+ spawn(process.execPath, ['-e', 'fetch(process.argv[1], { method: "POST", headers: { "content-type": "application/json" }, body: process.argv[2], signal: AbortSignal.timeout(10000) }).catch(() => {})',
74
+ env.AMK_NOTIFY_URL, body], { detached: true, stdio: 'ignore', env, cwd: os.tmpdir() }).on('error', () => {}).unref();
75
+ }
76
+
77
+ const notify = (p, env = process.env) => { const n = message(p, env); if (n) send(n, env); return n; };
78
+ // a hook's own start: its payload on stdin
79
+ function hook() {
80
+ let p = {};
81
+ try { p = JSON.parse(fs.readFileSync(0, 'utf8')); } catch {}
82
+ notify(p);
83
+ }
84
+
85
+ module.exports = { message, send, notify, hook, lastWords };
@@ -167,15 +167,17 @@ function forward(main, { check = true } = {}, cfg = settings(), io = IO) {
167
167
  specs.fetchOrigin();
168
168
  const ref = specs.planRef();
169
169
  const plan = ref && specs.show(ref, 'specs/plan.md');
170
- if (!plan) return 0;
170
+ // the plan's features, and those built feature by feature on a branch of their own (specs.js branch)
171
+ const local = (git('for-each-ref', '--format=%(refname:short)', 'refs/heads/feature/') || '').split('\n').filter(Boolean).map(b => b.slice(8));
172
+ const ids = [...new Set([...(plan ? specs.planFeatures(plan).rows.map(r => r.id) : []), ...local])];
171
173
  const built = specs.builtOn(main);
172
174
  const was = branchNow();
173
175
  let code = 0;
174
- for (const r of specs.planFeatures(plan).rows) {
175
- const b = `feature/${r.id}`;
176
- if (built.has(r.id) || git('rev-parse', '--verify', '--quiet', `refs/heads/${b}`) === null) continue;
176
+ for (const id of ids) {
177
+ const b = `feature/${id}`;
178
+ if (built.has(id) || git('rev-parse', '--verify', '--quiet', `refs/heads/${b}`) === null) continue;
177
179
  // its pull request's base, from the start line specs.js start wrote: a stacked branch's parent
178
- const parent = (/its PR goes to ([^)\s]+)\)/.exec(git('show', `${b}:specs/${r.id}/progress.md`) || '') || [])[1];
180
+ const parent = (/its PR goes to ([^)\s]+)\)/.exec(git('show', `${b}:specs/${id}/progress.md`) || '') || [])[1];
179
181
  const parentId = parent && (/^feature\/(.+)$/.exec(parent) || [])[1];
180
182
  if (!parentId || !built.has(parentId)) continue;
181
183
  if (git('merge-base', '--is-ancestor', main, b) === null) {
@@ -183,7 +185,7 @@ function forward(main, { check = true } = {}, cfg = settings(), io = IO) {
183
185
  const before = git('rev-parse', 'HEAD');
184
186
  let s = { rest: [] };
185
187
  if (git('merge', '--no-edit', '--quiet', main) === null) {
186
- s = settle(r.id);
188
+ s = settle(id);
187
189
  if (s.rest.length || git('commit', '--no-edit', '--quiet') === null) {
188
190
  git('merge', '--abort');
189
191
  io.log(`${b}: main can't be merged in without a person: ${s.rest.length ? `conflicts in ${s.rest.join(', ')}` : 'the merge commit was refused (see the hook\'s message)'}. Merge main into it by hand, then push.`);
@@ -195,9 +197,9 @@ function forward(main, { check = true } = {}, cfg = settings(), io = IO) {
195
197
  if (s.lock || changed.some(f => LOCKS.test(f))) sh('sh', ['scripts/amk/install-deps.sh'], { stdio: 'ignore' });
196
198
  if ((s.pods || changed.includes('ios/Podfile.lock')) && process.platform === 'darwin') sh('sh', ['scripts/amk/pod-install.sh'], { stdio: 'ignore' });
197
199
  if (s.spec) {
198
- sh(process.execPath, ['scripts/amk/specs.js', 'merge', r.id], { stdio: 'ignore' });
200
+ sh(process.execPath, ['scripts/amk/specs.js', 'merge', id], { stdio: 'ignore' });
199
201
  git('add', '--', 'specs/current/');
200
- git('commit', '--quiet', '-m', `docs(spec): ${r.id} merged into the living spec again, after main\n\nSpec: specs/${r.id}`);
202
+ git('commit', '--quiet', '-m', `docs(spec): ${id} merged into the living spec again, after main\n\nSpec: specs/${id}`);
201
203
  }
202
204
  if (check && sh('sh', ['scripts/amk/verify.sh', 'quick'], { stdio: 'ignore' }).status !== 0) {
203
205
  git('reset', '--quiet', '--keep', before);
@@ -18,6 +18,12 @@
18
18
  // dependencies built or on the build's stack), or <id>. Makes feature/<id>
19
19
  // from main or the top of the stack, with the spec as of its approval commit.
20
20
  // Exits 3 when none is ready, 4 when the living spec changed under it
21
+ // node scripts/amk/specs.js changed-flows the flows that reach what this branch changed since main: those using a
22
+ // testID a changed file sets (or running a subflow that does), and the flows
23
+ // changed themselves; verify.sh --changed runs them
24
+ // node scripts/amk/specs.js branch <id> a feature built feature by feature: makes feature/<id>, on a feature branch
25
+ // not merged into main yet when there is one (the one you're on, else the
26
+ // newest: part 1 of a feature split in parts), so it has that code; else main
21
27
  // node scripts/amk/specs.js import <file> a CSV export (a spreadsheet saved as CSV) or a Trello board's JSON export,
22
28
  // a line per row or open card, as outside text to plan from
23
29
  // A requirement is "### Requirement: <name>", a sentence with SHALL or MUST, and at least one
@@ -748,6 +754,58 @@ function fetchOrigin() {
748
754
  try { execFileSync('git', ['fetch', '--quiet', 'origin'], { stdio: 'ignore', timeout: 60000, env }); } catch {}
749
755
  }
750
756
 
757
+ // the flows that reach what this branch changed since main, for a small change's device check: those that use a testID
758
+ // a changed file sets (testID="…", testID: '…'), or run a subflow that does, and the flows changed themselves
759
+ function changedFlows() {
760
+ const main = mainRef();
761
+ // without a main branch to compare with, what's changed and not committed yet
762
+ const base = (main && git('merge-base', 'HEAD', main)) || 'HEAD';
763
+ const files = [...new Set([...(git('diff', '--name-only', base) || '').split('\n'),
764
+ ...(git('ls-files', '--others', '--exclude-standard') || '').split('\n')])].filter(Boolean);
765
+ const ids = new Set();
766
+ for (const f of files.filter(x => /\.(jsx?|tsx?)$/.test(x) && !x.startsWith('scripts/amk/'))) {
767
+ for (const m of (read(f) || '').matchAll(/testID\s*[=:]\s*\{?\s*(["'`])([^"'`$]+)\1/g)) ids.add(m[2]);
768
+ }
769
+ const uses = text => [...stripYamlComments(text || '').matchAll(/\bid:\s*["']?([^"'\s,}]+)/g)].some(m => ids.has(m[1]));
770
+ const subs = allFlows('.maestro/subflows').map(f => `subflows/${f}`).filter(f => files.includes(`.maestro/${f}`) || uses(read(`.maestro/${f}`)));
771
+ return allFlows().filter(f => {
772
+ const text = read(`.maestro/${f}`) || '';
773
+ return files.includes(`.maestro/${f}`) || uses(text) || subs.some(sf => text.includes(sf));
774
+ }).map(f => path.resolve('.maestro', f));
775
+ }
776
+
777
+ // the start line in a feature's progress.md: where it started, and where its PR goes (pr.js forward reads it)
778
+ function logStart(id, line) {
779
+ const progress = `specs/${id}/progress.md`;
780
+ const p = read(progress) || read('specs/_templates/progress.md') || '## Log\n';
781
+ fs.mkdirSync(path.dirname(progress), { recursive: true });
782
+ fs.writeFileSync(progress, /^## Log\s*$/m.test(p) ? p.replace(/^## Log\s*\n(\s*<!--[\s\S]*?-->\s*\n)?/m, m => `${m.replace(/\n*$/, '\n')}\n${line}\n`) : `${p.replace(/\n*$/, '\n')}\n## Log\n\n${line}\n`);
783
+ }
784
+ // feature by feature: the branch a feature is built on. A feature branch not merged into main yet (part 1 of a feature
785
+ // split in parts, its PR still open) is where the next one starts, so the next one has its code: the one you're on,
786
+ // else the newest. Its PR then goes there, and pr.js forward moves it into main once that one merges
787
+ function branchFeature(id) {
788
+ const name = `feature/${id}`;
789
+ if (branch() === name) { console.log(`On ${name} already.`); return 0; }
790
+ if (exists(name)) {
791
+ if (git('switch', '--quiet', name) === null) { console.error(`git switch ${name} failed: commit or stash what's changed here first.`); return 1; }
792
+ console.log(`Switched to ${name}, where ${id} is built.`);
793
+ return 0;
794
+ }
795
+ fetchOrigin();
796
+ const main = mainRef();
797
+ if (!main) { console.error('No main branch found: set AMK_BASE to the branch features start from.'); return 1; }
798
+ const built = builtOn(main);
799
+ const open = (git('for-each-ref', '--sort=-committerdate', '--format=%(refname:short)', 'refs/heads/feature/') || '').split('\n').filter(Boolean)
800
+ .filter(b => !isAncestor(b, main) && !built.has(b.slice(8)) && show(b, `specs/${b.slice(8)}/progress.md`) !== null);
801
+ const from = open.includes(branch()) ? branch() : open[0] || main;
802
+ if (git('switch', '--quiet', '--no-track', '-c', name, from) === null) { console.error(`git switch -c ${name} ${from} failed.`); return 1; }
803
+ logStart(id, `- ${new Date().toISOString().slice(0, 16).replace('T', ' ')}: started from ${from} (its PR goes to ${from.replace(/^origin\//, '')})`);
804
+ console.log(from === main ? `Started ${name} from ${main}.`
805
+ : `Started ${name} from ${from}, which isn't merged into ${main.replace(/^origin\//, '')} yet: ${id} builds on it, and its PR goes there (pr.js forward moves it into ${main.replace(/^origin\//, '')} once ${from} merges).`);
806
+ return 0;
807
+ }
808
+
751
809
  function start(want) {
752
810
  if (branch() === 'plan') { console.error('This folder is on the plan branch: build in a folder on main or a feature branch.'); return 1; }
753
811
  if (git('status', '--porcelain', '--untracked-files=no')) { console.error('Commit the changes here first (git status): a feature starts from a clean folder.'); return 1; }
@@ -796,10 +854,7 @@ function start(want) {
796
854
  for (const a of [['switch', '--quiet', '--no-track', '-c', name, from], ['checkout', approved, '--', `specs/${pick.id}/`]]) {
797
855
  try { execFileSync('git', a, { stdio: ['ignore', 'ignore', 'pipe'] }); } catch (e) { console.error(`git ${a.join(' ')}: ${String(e.stderr || e.message).trim()}`); return 1; }
798
856
  }
799
- const progress = `specs/${pick.id}/progress.md`;
800
- const log = `- ${new Date().toISOString().slice(0, 16).replace('T', ' ')}: started from ${from} (its PR goes to ${from.replace(/^origin\//, '')}), with the spec as approved in ${short} on ${ref}`;
801
- const p = read(progress) || read('specs/_templates/progress.md') || '## Log\n';
802
- fs.writeFileSync(progress, /^## Log\s*$/m.test(p) ? p.replace(/^## Log\s*\n(\s*<!--[\s\S]*?-->\s*\n)?/m, m => `${m.replace(/\n*$/, '\n')}\n${log}\n`) : `${p.replace(/\n*$/, '\n')}\n## Log\n\n${log}\n`);
857
+ logStart(pick.id, `- ${new Date().toISOString().slice(0, 16).replace('T', ' ')}: started from ${from} (its PR goes to ${from.replace(/^origin\//, '')}), with the spec as approved in ${short} on ${ref}`);
803
858
  try {
804
859
  execFileSync('git', ['add', '--', `specs/${pick.id}/`], { stdio: 'ignore' });
805
860
  execFileSync('git', ['commit', '--quiet', '-m', `docs(spec): ${pick.id} from the plan, as approved in ${short}\n\nSpec: specs/${pick.id}`], { stdio: ['ignore', 'ignore', 'pipe'] });
@@ -889,6 +944,10 @@ if (require.main === module) {
889
944
  process.exitCode = status();
890
945
  } else if (cmd === 'start') {
891
946
  process.exitCode = start(args[0]);
947
+ } else if (cmd === 'changed-flows') {
948
+ for (const f of changedFlows()) console.log(f);
949
+ } else if (cmd === 'branch' && args[0]) {
950
+ process.exitCode = branchFeature(args[0]);
892
951
  } else if (cmd === 'plan-folder') {
893
952
  process.exitCode = planFolder();
894
953
  } else if (cmd === 'import' && args[0]) {
@@ -20,6 +20,8 @@
20
20
  # flows of each (a flow's name prefix works too: offline-sync runs offline-sync-1.yaml) and need --label
21
21
  # --flow <file> run only this flow: a path in the project, or anywhere (an absolute path)
22
22
  # --tags <list> only the flows with one of these tags in their header (tags: [smoke]), comma-separated
23
+ # --changed only the flows that reach what this branch changed: they use a testID a changed file sets, or
24
+ # are changed themselves (specs.js changed-flows); with --spec, its flows too
23
25
  # --label <n> evidence folder name (default: the spec id, or no-spec)
24
26
  # --flavor <name> Android product flavor to check (default: the first one in build.gradle)
25
27
  # --scheme <name> iOS scheme to check (default: the one named like the workspace)
@@ -72,6 +74,7 @@ only=${AMK_SCREENS:-}
72
74
  no_build=0
73
75
  mock=0
74
76
  related=0
77
+ changed=0
75
78
  build_only=0
76
79
  part=""
77
80
  while [ $# -gt 0 ]; do
@@ -86,6 +89,7 @@ while [ $# -gt 0 ]; do
86
89
  --no-build) no_build=1; shift ;;
87
90
  --mock) mock=1; shift ;;
88
91
  --related) related=1; shift ;;
92
+ --changed) changed=1; shift ;;
89
93
  --part) part=$2; shift 2 ;;
90
94
  *) echo "verify: unknown option $1"; exit 2 ;;
91
95
  esac
@@ -167,8 +171,11 @@ built_api() { echo "$api" > "$root/.amk/last-build-$1"; }
167
171
  flow_files() {
168
172
  {
169
173
  if [ -n "$flow" ]; then echo "$flow"
170
- elif [ -n "$spec" ]; then
171
- for s in $(echo "$spec" | tr ',' ' '); do find "$root/.maestro" -maxdepth 1 -iname "$s*.yaml" ! -name '.amk-*' 2>/dev/null; done | sort -u
174
+ elif [ -n "$spec" ] || [ "$changed" = 1 ]; then
175
+ {
176
+ [ "$changed" = 0 ] || node scripts/amk/specs.js changed-flows
177
+ for s in $(echo "$spec" | tr ',' ' '); do find "$root/.maestro" -maxdepth 1 -iname "$s*.yaml" ! -name '.amk-*' 2>/dev/null; done
178
+ } | sort -u
172
179
  else find "$root/.maestro" -maxdepth 1 -name '*.yaml' ! -name '.amk-*' 2>/dev/null | sort
173
180
  fi
174
181
  } | with_tags | awk -v k="$part_k" -v n="$part_n" '(NR - 1) % n == k - 1'
@@ -419,6 +426,7 @@ run_flows() { # screen device app_id orientation (PORTRAIT, or LANDSCAPE_LEFT to
419
426
  files=$(flow_files)
420
427
  if [ -z "$files" ]; then
421
428
  [ -z "$tags" ] || echo " $1: no flow has the tag $tags, so this is a check that the app opens"
429
+ [ "$changed" = 0 ] || [ -n "$spec" ] || echo " $1: no flow reaches what this branch changed, so this is a check that the app opens"
422
430
  # launchApp returns before the app has drawn, and a splash screen stays up until the JavaScript has loaded:
423
431
  # a fixed wait (for text that never appears), then for the screen to settle, so the screenshot shows the app
424
432
  printf 'appId: %s\n---\n- launchApp\n- extendedWaitUntil:\n visible: "agentic-mobile-kit: waiting for the app to draw"\n timeout: 5000\n optional: true\n- waitForAnimationToEnd\n- takeScreenshot: smoke-launch\n' "$3" > "$out/smoke.yaml"
@@ -19,8 +19,15 @@
19
19
  appId: ${APP_ID} # set by verify.sh
20
20
  # tags: [smoke] # optional: verify.sh --tags smoke checks only the flows with one of the tags
21
21
  ---
22
- - launchApp:
23
- clearState: true
22
+ # Start at the screen the scenarios are on: a flow that walks from the first screen through every one before it is
23
+ # slow, and fails for screens it only passes through.
24
+ # - The app keeps its data between flows (logged in, say): clear it (launchApp: { clearState: true }) only for a
25
+ # scenario that needs a fresh install: onboarding, an empty state, a first permission prompt.
26
+ # - Log in with the subflow only when the login screen shows:
27
+ # - runFlow: { file: subflows/login.yaml, when: { visible: { id: "login-email" } } }
28
+ # - Where the app opens screens from a link (React Navigation's linking, Expo Router's routes), open this one with it
29
+ # rather than tapping through: - openLink: <the app's scheme>://<the screen's path>
30
+ - launchApp
24
31
  # After every launchApp: a splash screen can still cover the app while assertions already pass (the app's views
25
32
  # exist under it), so wait a moment (for text that never appears), then for the screen to settle.
26
33
  - extendedWaitUntil:
@@ -1,7 +1,8 @@
1
1
  # Copy to .maestro/subflows/<name>.yaml for steps several flows share: logging in, skipping onboarding, answering a
2
2
  # permission prompt. A flow runs it with "- runFlow: subflows/<name>.yaml". verify.sh runs only the flows directly in
3
3
  # .maestro/, not the subflows below it. This one logs in with the test account from .maestro/.env.local (MAESTRO_EMAIL,
4
- # MAESTRO_PASSWORD), which isn't committed.
4
+ # MAESTRO_PASSWORD), which isn't committed. Run it only when the login screen shows, so a flow on an app that's still
5
+ # logged in goes straight on: - runFlow: { file: subflows/login.yaml, when: { visible: { id: "login-email" } } }
5
6
  appId: ${APP_ID}
6
7
  ---
7
8
  - tapOn: