agentic-mobile-kit 0.14.2 → 0.16.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
@@ -36,6 +36,7 @@ Each choice prints the command it runs, for scripts and CI: `init` (with `--ci g
36
36
  | Build the planned features overnight | `node scripts/amk/autopilot.js` | First the review comments nobody answered on its pull requests, and the bugs labelled `amk-fix`, each to a pull request. Then a fresh session of the AI tool for each feature, with only the build's commands allowed and only the variables a build needs. A stalled session starts again from its handoff; a full disk, an expired sign-in or a usage limit ends the build with the command to go on. Notes and a stop file steer it, and you're notified of each block |
37
37
  | Make a small change | `m-change` | Checks it's small, then shows the code, living-spec and docs changes for one approval, makes them together and runs the checks |
38
38
  | Fix a bug | `m-bugfix` | From a description, an issue or a Sentry or Crashlytics report: makes the bug fail on demand (a test, or a Maestro flow on the device), lists the likely causes, finds the root cause, then makes the smallest fix |
39
+ | See what the AI is doing, and how far a check is | Claude Code: under the prompt; any tool: `node scripts/amk/status.js --watch` | Whether it works, waits for something it started (and goes on by itself) or waits for you, the feature's tasks done, and the checks as they run: a device check's flow k of n, the quick check's stage, CI's checks, an unattended build's feature |
39
40
  | Stop, or switch tool or machine | `m-pause` | Writes a handoff in the spec, commits and pushes |
40
41
  | Carry on anywhere | `m-continue` | Reads the spec and handoff, then picks up at the next step |
41
42
  | Test a change or a release | `m-test` | Runs the checks and the device flows of the change and the areas it touches; a read-only tester gives each scenario a status, and the report says Ready or Not ready |
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.16.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",
@@ -1,9 +1,9 @@
1
1
  <!-- KIT:START agentic-mobile-kit {{KIT_VERSION}} ci={{KIT_CI}} stack={{KIT_STACK}} (edit outside these markers; the kit updates what's inside) -->
2
2
  # {{APP_NAME}}: instructions for AI agents
3
3
 
4
- Read by Claude Code (through CLAUDE.md), Codex, Cursor, OpenCode, Kiro and Antigravity; details live in `docs/amk/`.
4
+ Read by every AI tool here (Claude Code through CLAUDE.md); details live in `docs/amk/`.
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.
6
+ Other AI workflow frameworks in this project (Superpowers, BMAD, proAgents, …) 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
7
 
8
8
  ## Project
9
9
 
@@ -26,7 +26,7 @@ This project may also use other AI workflow frameworks (for example Superpowers,
26
26
  | Check devices at the same time | `sh scripts/amk/verify.sh plan --spec <id>` prints a command per device, each for an `m-device-checker` subagent |
27
27
  | After each task: lint, typecheck and the tests of the changed files | `sh scripts/amk/verify.sh quick --related` |
28
28
  | React Native mistakes, flow problems and oversized files or functions in this branch's changes (`verify.sh quick` runs it) | `node scripts/amk/rn-check.js` |
29
- | Specs and the plan: progress, checks, the tests of the areas a spec touches, flows, the living spec, planning | `node scripts/amk/specs.js status` (or `check`, `tests <id>`, `flow <id>`, `merge <id>`, `check --plan`, `plan-folder`, `import <file>`, `start [<id>]`) |
29
+ | Specs and the plan: progress, checks, a spec's tests and flows, the living spec, planning | `node scripts/amk/specs.js status` (or `check`, `tests <id>`, `flow <id>`, `merge <id>`, `check --plan`, `plan-folder`, `import <file>`, `start [<id>]`) |
30
30
  | Unattended (a person starts it; never skipping permission prompts): its PRs' review fixes, `amk-fix` bugs, then approved features | `node scripts/amk/autopilot.js [--reviews \| --bugs \| --features]`; first `node scripts/amk/autopilot.js check` |
31
31
  | A feature's PR: checks (with a failure's log), review comments, auto-merge, main merged into stacked branches | `node scripts/amk/pr.js checks` (or `comments`, `automerge`, `forward`) |
32
32
  | Check a release before tagging it (versions, store review rules, debug leftovers) | `node scripts/amk/release-check.js` |
@@ -53,9 +53,10 @@ Never say a check passed unless you ran it in this session.
53
53
  - Never run `eas build`, `eas submit` or `eas update`: they use the team's accounts, so a person runs them.
54
54
  - Never read, print or commit `.env` files, keystores, signing files or the files `.amk-secrets` lists. Secrets don't belong in this repo.
55
55
  - Never use `git commit --no-verify`, `git push --force`, `git reset --hard` or `rm -rf`, and never throw away work that can't be brought back (uncommitted changes with `git checkout .` or `git restore .`, stashes with `git stash drop` or `clear`, unmerged commits with `git branch -D`): ask first. To undo your own edit to a file, `git checkout -- <that file>`.
56
- - When `rn-check` (in `verify.sh quick`) reports a problem (✗), show it to the user and let them choose, for each one: fix it, or keep the line with `// amk-ok <today's date>: <their reason>`. Never add an `amk-ok`, or a cap in `.amk-size-caps`, on your own. One kept over two weeks ago comes back when its file changes: ask again. Fix the warnings (!) in code the task changed, or tell the user why one stays.
56
+ - When `rn-check` (in `verify.sh quick`) reports a problem (✗), show it to the user and let them choose, for each one: fix it, or keep the line with `// amk-ok <today's date>: <their reason>`. Never add an `amk-ok`, or a cap in `.amk-size-caps`, on your own. Fix the warnings (!) in code the task changed, or tell the user why one stays.
57
57
  - Run shell commands one at a time, as the skills write them, not joined with `&&` or `;`: a tool asks about a joined line, or refuses it, as a whole. When one is refused, run its parts on their own before deciding anything is blocked.
58
58
  - After 2 failed attempts at the same fix, stop and report what you found.
59
+ - Ending your turn while something you started still runs (a background command, a subagent, CI)? Say what you wait for, and whether you go on by yourself.
59
60
  - Chat is not memory: write decisions into the spec or `docs/amk/decisions.md` straight away.
60
61
  - Follow `docs/amk/expo.md`. Before fixing a build error, check `docs/amk/known-issues.md`.
61
62
 
@@ -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
  }
@@ -1,9 +1,9 @@
1
1
  <!-- KIT:START agentic-mobile-kit {{KIT_VERSION}} ci={{KIT_CI}} stack={{KIT_STACK}} (edit outside these markers; the kit updates what's inside) -->
2
2
  # {{APP_NAME}}: instructions for AI agents
3
3
 
4
- Read by Claude Code (through CLAUDE.md), Codex, Cursor, OpenCode, Kiro and Antigravity; details live in `docs/amk/`.
4
+ Read by every AI tool here (Claude Code through CLAUDE.md); details live in `docs/amk/`.
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.
6
+ Other AI workflow frameworks in this project (Superpowers, BMAD, proAgents, …) 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
7
 
8
8
  ## Project
9
9
 
@@ -26,7 +26,7 @@ This project may also use other AI workflow frameworks (for example Superpowers,
26
26
  | Check devices at the same time | `sh scripts/amk/verify.sh plan --spec <id>` prints a command per device, each for an `m-device-checker` subagent |
27
27
  | After each task: lint, typecheck and the tests of the changed files | `sh scripts/amk/verify.sh quick --related` |
28
28
  | React Native mistakes, flow problems and oversized files or functions in this branch's changes (`verify.sh quick` runs it) | `node scripts/amk/rn-check.js` |
29
- | Specs and the plan: progress, checks, the tests of the areas a spec touches, flows, the living spec, planning | `node scripts/amk/specs.js status` (or `check`, `tests <id>`, `flow <id>`, `merge <id>`, `check --plan`, `plan-folder`, `import <file>`, `start [<id>]`) |
29
+ | Specs and the plan: progress, checks, a spec's tests and flows, the living spec, planning | `node scripts/amk/specs.js status` (or `check`, `tests <id>`, `flow <id>`, `merge <id>`, `check --plan`, `plan-folder`, `import <file>`, `start [<id>]`) |
30
30
  | Unattended (a person starts it; never skipping permission prompts): its PRs' review fixes, `amk-fix` bugs, then approved features | `node scripts/amk/autopilot.js [--reviews \| --bugs \| --features]`; first `node scripts/amk/autopilot.js check` |
31
31
  | A feature's PR: checks (with a failure's log), review comments, auto-merge, main merged into stacked branches | `node scripts/amk/pr.js checks` (or `comments`, `automerge`, `forward`) |
32
32
  | Check a release before tagging it (versions, store review rules, debug leftovers) | `node scripts/amk/release-check.js` |
@@ -52,9 +52,10 @@ Never say a check passed unless you ran it in this session.
52
52
  - Don't hand-edit `ios/*.xcodeproj/project.pbxproj`. If a native file must be added to the Xcode project, stop and ask.
53
53
  - Never read, print or commit `.env` files, keystores, signing files or the files `.amk-secrets` lists. Secrets don't belong in this repo.
54
54
  - Never use `git commit --no-verify`, `git push --force`, `git reset --hard` or `rm -rf`, and never throw away work that can't be brought back (uncommitted changes with `git checkout .` or `git restore .`, stashes with `git stash drop` or `clear`, unmerged commits with `git branch -D`): ask first. To undo your own edit to a file, `git checkout -- <that file>`.
55
- - When `rn-check` (in `verify.sh quick`) reports a problem (✗), show it to the user and let them choose, for each one: fix it, or keep the line with `// amk-ok <today's date>: <their reason>`. Never add an `amk-ok`, or a cap in `.amk-size-caps`, on your own. One kept over two weeks ago comes back when its file changes: ask again. Fix the warnings (!) in code the task changed, or tell the user why one stays.
55
+ - When `rn-check` (in `verify.sh quick`) reports a problem (✗), show it to the user and let them choose, for each one: fix it, or keep the line with `// amk-ok <today's date>: <their reason>`. Never add an `amk-ok`, or a cap in `.amk-size-caps`, on your own. Fix the warnings (!) in code the task changed, or tell the user why one stays.
56
56
  - Run shell commands one at a time, as the skills write them, not joined with `&&` or `;`: a tool asks about a joined line, or refuses it, as a whole. When one is refused, run its parts on their own before deciding anything is blocked.
57
57
  - After 2 failed attempts at the same fix, stop and report what you found.
58
+ - Ending your turn while something you started still runs (a background command, a subagent, CI)? Say what you wait for, and whether you go on by yourself.
58
59
  - Chat is not memory: write decisions into the spec or `docs/amk/decisions.md` straight away.
59
60
  - Follow `docs/amk/react-native.md`. Before fixing a build error, check `docs/amk/known-issues.md`.
60
61
 
@@ -33,6 +33,7 @@ const path = require('path');
33
33
  const { spawn, spawnSync } = require('child_process');
34
34
  const { redact, untrusted } = require('./redact.js');
35
35
  const specs = require('./specs.js');
36
+ const progress = require('./progress.js');
36
37
 
37
38
  const ROOT = fs.realpathSync(path.join(__dirname, '..', '..'));
38
39
  const BUILD = path.join(ROOT, '.amk', 'build');
@@ -513,6 +514,15 @@ function reviewQueue(ids = new Set(), ghx = gh) {
513
514
  }
514
515
  // the plan's features, by id
515
516
  const planIds = () => { const ref = specs.planRef(); const plan = ref && specs.show(ref, 'specs/plan.md'); return new Set(plan ? specs.planFeatures(plan).rows.map(r => r.id) : []); };
517
+ // the plan's features, and how many of them are built: on main, or done on their branch
518
+ function planCount() {
519
+ try {
520
+ const ids = [...planIds()];
521
+ const main = specs.mainRef();
522
+ const built = main ? specs.builtOn(main) : new Set();
523
+ return { total: ids.length, done: ids.filter(id => built.has(id) || isDone(git('show', `feature/${id}:specs/${id}/progress.md`))).length };
524
+ } catch { return {}; }
525
+ }
516
526
  // open issues labelled amk-fix, oldest first: labelled by someone who can label them, or by Sentry's integration with
517
527
  // "Sentry adds amk-fix: on"; without amk-needs-info, and without an open pull request from fix/<n> yet
518
528
  function bugQueue(cfg, ghx = gh) {
@@ -572,7 +582,9 @@ async function build(o, d = {}) {
572
582
  // main merged into the build's stacked branches whose parent has merged (pr.js forward), at the start of each round
573
583
  forward: log => { const pr = require('./pr.js'); return pr.forward(specs.mainRef(), {}, pr.settings(), { ...pr.IO, log }); },
574
584
  reviews: () => reviewQueue(planIds()), bugs: () => bugQueue(cfg), prFor, needsInfo: (n, t) => needsInfo(n, t),
575
- unanswered: n => { const me = (gh(['api', 'user']) || {}).login; const repo = repoName(); return Boolean(me && repo) && unanswered(repo, n, me); }, ...d };
585
+ unanswered: n => { const me = (gh(['api', 'user']) || {}).login; const repo = repoName(); return Boolean(me && repo) && unanswered(repo, n, me); },
586
+ // where the build stands, for the status line and status.js --watch: null when it ends
587
+ progress: at => (at ? progress.set('autopilot', { title: 'Unattended build', pid: process.pid, ...at }) : progress.end('autopilot')), ...d };
576
588
  const cfg = settings();
577
589
  const env = cleanEnv(process.env, cfg);
578
590
  const built = [];
@@ -627,14 +639,18 @@ async function build(o, d = {}) {
627
639
  await io.notify('Build: stopped on one', `${id}: ${reason}`);
628
640
  return null;
629
641
  };
630
- for (const p of kinds.includes('reviews') ? io.reviews() : []) {
642
+ const reviews = kinds.includes('reviews') ? io.reviews() : [];
643
+ for (const [i, p] of reviews.entries()) {
644
+ io.progress({ stage: 'review comments', done: i, total: reviews.length, label: `#${p.number}` });
631
645
  end = await other({ id: `review-${p.number}`, branch: () => toBranch(p.headRefName), prompt: `m-review the review comments on pull request #${p.number}`,
632
646
  note: x => unattendedReview(p.number, p.headRefName, x), what: `review comments on pull request #${p.number}`,
633
647
  after: () => (io.unanswered(p.number) ? null : `review-${p.number}: answered`) });
634
648
  if (end) break;
635
649
  }
636
- for (const i of !end && kinds.includes('bugs') ? io.bugs() : []) {
650
+ const bugs = !end && kinds.includes('bugs') ? io.bugs() : [];
651
+ for (const [k, i] of bugs.entries()) {
637
652
  const n = i.number;
653
+ io.progress({ stage: 'bugs', done: k, total: bugs.length, label: `#${n}` });
638
654
  end = await other({ id: `bug-${n}`, branch: () => toBranch(`fix/${n}`, true), prompt: `m-bugfix #${n}`, note: x => unattendedBug(n, x), what: `issue #${n}`,
639
655
  after: () => {
640
656
  const url = io.prFor(`fix/${n}`);
@@ -678,6 +694,7 @@ async function build(o, d = {}) {
678
694
  fs.mkdirSync(path.dirname(log), { recursive: true });
679
695
  fs.appendFileSync(log, `\n=== ${stamp()}: session ${t.sessions} of ${id} (${o.tool}${notes ? ', with notes.md' : ''})\n`);
680
696
  io.log(`${stamp()} ${id}: session ${t.sessions} (${o.tool}), logged in .amk/build/${id}/build.log`);
697
+ io.progress({ stage: 'features', ...planCount(), label: `${id}${t.sessions > 1 ? ` (session ${t.sessions})` : ''}` });
681
698
  const { cmd, args } = TOOLS[o.tool](`m-continue ${id}`, unattended(id, notes), o);
682
699
  const s = await io.session({ id, cmd, args, env, log, stallMs: o.stall * 60e3 });
683
700
  commitHandoff(id);
@@ -718,6 +735,7 @@ async function build(o, d = {}) {
718
735
  fs.mkdirSync(BUILD, { recursive: true });
719
736
  fs.writeFileSync(path.join(BUILD, 'report.md'), `# Build of ${stamp()}\n\n${redact(report)}\n`);
720
737
  io.log(`\n${report}`);
738
+ io.progress(null);
721
739
  await io.notify('Build ended', `${end.reason}. Built: ${built.length}${done.length ? `, reviews and bugs: ${done.length}` : ''}, blocked: ${blocked.length}`);
722
740
  return { end, built, blocked, done };
723
741
  }
@@ -43,7 +43,15 @@ 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): the status line hears of it, and the developer, who may be in
47
+ // another window, is told
48
+ const ends = () => {
49
+ try { require('./status.js').mark(payload, { ended: Date.now() }); } catch {}
50
+ try { require('./notify.js').notify({ ...payload, hook_event_name: 'Stop' }); } catch {}
51
+ process.exit(0);
52
+ };
53
+
54
+ if (payload.stop_hook_active && !unattended) ends(); // already reminded once; don't loop
47
55
 
48
56
  // unattended: the feature's state at this stop (its last commit, ticked tasks and next step)
49
57
  const progress = unattended && own ? read(`specs/${own}/progress.md`) || '' : null;
@@ -57,7 +65,8 @@ if ((working.length || progress !== null) && !payload.stop_hook_active) {
57
65
  const link = f => { try { return fs.lstatSync(path.join(root, f)).isSymbolicLink(); } catch { return false; } };
58
66
  const changed = sh('git status --porcelain --untracked-files=all')
59
67
  .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/'));
68
+ // not the AI tool's worktrees inside the project (Claude Code's .claude/worktrees/): another session's work
69
+ const codeChanged = changed.some(f => !f.startsWith('specs/') && !f.startsWith('.amk/') && !f.startsWith('.claude/worktrees/'));
61
70
  const handoffUpdated = changed.some(f => /^specs\/[^/]+\/progress\.md$/.test(f));
62
71
  if (codeChanged && !handoffUpdated) {
63
72
  process.stderr.write('There are uncommitted code changes, but no specs/<id>/progress.md was updated. ' +
@@ -104,4 +113,4 @@ if (progress !== null && !fs.existsSync(path.join(root, '.amk', 'build', 'STOP')
104
113
  process.exit(2);
105
114
  }
106
115
  }
107
- process.exit(0);
116
+ ends();
@@ -0,0 +1,98 @@
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, or
8
+ // (Claude Code) what it waits for, when it ends the turn while something it started runs
9
+ // AMK_NOTIFY=off turns it off; AMK_NOTIFY=ask keeps the approvals, the waiting and the turns that end with a question.
10
+ // The hook also tells the status line (status.js) that the agent waits for you, whether or not it notifies.
11
+ // An unattended build (autopilot.js) notifies by itself, so nothing comes from here then.
12
+ 'use strict';
13
+ const fs = require('fs');
14
+ const os = require('os');
15
+ const path = require('path');
16
+ const { spawn, spawnSync } = require('child_process');
17
+ const { redact } = require('./redact.js');
18
+
19
+ const root = path.join(__dirname, '..', '..');
20
+
21
+ // what the AI said last: the payload's, or the last assistant text in its transcript (one JSON event a line)
22
+ function lastWords(p) {
23
+ if (typeof p.last_assistant_message === 'string') return p.last_assistant_message;
24
+ try {
25
+ for (const line of fs.readFileSync(p.transcript_path, 'utf8').trim().split('\n').reverse()) {
26
+ let e;
27
+ try { e = JSON.parse(line); } catch { continue; }
28
+ const c = e.type === 'assistant' && e.message && e.message.content;
29
+ const text = Array.isArray(c) ? c.filter(x => x && x.type === 'text').map(x => x.text).join('\n') : typeof c === 'string' ? c : '';
30
+ if (text.trim()) return text;
31
+ }
32
+ } catch {}
33
+ return '';
34
+ }
35
+ const waiting = (p, words) => { try { const a = require('./status.js').stateOf(p, words); return a && a.state === 'waiting' ? a : null; } catch { return null; } };
36
+ const toolOf = (p, env) => (/[\\/]\.claude[\\/]/.test(p.transcript_path || '') || env.CLAUDECODE ? 'Claude Code'
37
+ : /[\\/]\.codex[\\/]/.test(p.transcript_path || '') ? 'Codex' : 'The AI');
38
+
39
+ // the notification for a hook's payload: { title, text }, or null
40
+ function message(p, env = process.env) {
41
+ const mode = String(env.AMK_NOTIFY || 'on').toLowerCase();
42
+ if (env.AMK_AUTOPILOT || ['off', '0', 'no', 'false'].includes(mode)) return null;
43
+ const project = path.basename(root);
44
+ const tool = toolOf(p, env);
45
+ const event = p.hook_event_name || '';
46
+ if (event === 'Notification') return { title: `${project}: ${tool} is waiting for you`, text: p.message || 'It needs your answer or approval.' };
47
+ if (event === 'PermissionRequest') {
48
+ if (tool === 'Claude Code') return null;
49
+ const input = p.tool_input || {};
50
+ return { title: `${project}: ${tool} needs your approval`, text: String(input.command || input.file_path || p.tool_name || 'a command') };
51
+ }
52
+ if (event !== 'Stop') return null;
53
+ const words = lastWords(p);
54
+ // a turn that ends while what it started still runs (a command in the background, a subagent): Claude Code goes on
55
+ // by itself when that ends, as its log says
56
+ const a = tool === 'Claude Code' ? waiting(p, words) : null;
57
+ if (a) return mode === 'ask' ? null : { title: `${project}: ${tool} is waiting for ${a.pending[0].what}`, text: 'It goes on by itself when that ends: nothing is needed from you now.' };
58
+ const lines = words.split('\n').map(l => l.replace(/[*_`#>]/g, '').trim()).filter(Boolean);
59
+ const question = lines.filter(l => /\?$/.test(l)).pop() || lines.find(l => /\bapprov/i.test(l));
60
+ if (mode === 'ask' && !question) return null;
61
+ return { title: `${project}: ${tool} ${question ? 'asks you' : 'finished'}`, text: question || lines[0] || 'Its turn is over.' };
62
+ }
63
+
64
+ // the desktop notification now, the webhook in a process of its own: a hook returns at once. Those processes start in
65
+ // the temp folder: on Windows a process holds the folder it runs in, and the project's would be locked meanwhile
66
+ function send(n, env = process.env) {
67
+ const text = redact(n.text).replace(/[\u0000-\u001f\u2028\u2029]+/g, ' ').slice(0, 300);
68
+ const title = n.title.slice(0, 120);
69
+ try {
70
+ if (process.platform === 'darwin') spawnSync('osascript', ['-e', `display notification ${JSON.stringify(text)} with title ${JSON.stringify(title)}`], { stdio: 'ignore', timeout: 10000 });
71
+ else if (process.platform === 'linux') spawnSync('notify-send', [title, text], { stdio: 'ignore', timeout: 10000 });
72
+ else if (process.platform === 'win32') {
73
+ const q = s => `'${s.replace(/'/g, "''")}'`;
74
+ 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()`],
75
+ { detached: true, stdio: 'ignore', windowsHide: true, cwd: os.tmpdir() }).on('error', () => {}).unref();
76
+ }
77
+ } catch {}
78
+ if (!env.AMK_NOTIFY_URL) return;
79
+ // Slack and Google Chat read text, Discord content
80
+ const body = JSON.stringify({ text: `${title}: ${text}`, content: `${title}: ${text}` });
81
+ spawn(process.execPath, ['-e', 'fetch(process.argv[1], { method: "POST", headers: { "content-type": "application/json" }, body: process.argv[2], signal: AbortSignal.timeout(10000) }).catch(() => {})',
82
+ env.AMK_NOTIFY_URL, body], { detached: true, stdio: 'ignore', env, cwd: os.tmpdir() }).on('error', () => {}).unref();
83
+ }
84
+
85
+ const notify = (p, env = process.env) => { const n = message(p, env); if (n) send(n, env); return n; };
86
+ // a hook's own start: its payload on stdin. The status line hears of it too: a reply Claude Code has waited a minute
87
+ // for means the turn is over; anything else (a permission prompt, Codex's approvals) waits for you until the next step
88
+ function hook() {
89
+ let p = {};
90
+ try { p = JSON.parse(fs.readFileSync(0, 'utf8')); } catch {}
91
+ try {
92
+ const idle = p.notification_type === 'idle_prompt' || /waiting for your input/i.test(p.message || '');
93
+ require('./status.js').mark(p, idle ? { ended: Date.now() } : { attention: { at: Date.now(), text: String(p.message || (p.tool_input || {}).command || 'your approval').slice(0, 200) } });
94
+ } catch {}
95
+ notify(p);
96
+ }
97
+
98
+ module.exports = { message, send, notify, hook, lastWords };
@@ -20,6 +20,7 @@ const path = require('path');
20
20
  const { spawnSync } = require('child_process');
21
21
  const { untrusted } = require('./redact.js');
22
22
  const specs = require('./specs.js');
23
+ const progress = require('./progress.js');
23
24
 
24
25
  const ROOT = path.join(__dirname, '..', '..');
25
26
  const read = f => { try { return fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n'); } catch { return null; } };
@@ -36,8 +37,12 @@ const IO = {
36
37
  ghText: args => { const r = sh('gh', args, { timeout: 120000 }); return r.status === 0 ? r.stdout : null; },
37
38
  ghRun: args => sh('gh', args, { timeout: 120000 }),
38
39
  sleep: ms => new Promise(r => setTimeout(r, ms)),
39
- // where a wait stands, under .amk/: autopilot.js's stall watchdog counts a change there as activity
40
- note: t => { try { fs.mkdirSync(path.join(ROOT, '.amk'), { recursive: true }); fs.writeFileSync(path.join(ROOT, '.amk/pr-checks.txt'), `${new Date().toISOString()} ${t}\n`); } catch {} },
40
+ // where a wait stands, under .amk/: autopilot.js's stall watchdog counts a change there as activity, and the status
41
+ // line shows how many checks are done (progress.js)
42
+ note: (t, at) => {
43
+ try { fs.mkdirSync(path.join(ROOT, '.amk'), { recursive: true }); fs.writeFileSync(path.join(ROOT, '.amk/pr-checks.txt'), `${new Date().toISOString()} ${t}\n`); } catch {}
44
+ if (at) progress.set('pr-checks', { title: 'CI', pid: process.pid, ...at });
45
+ },
41
46
  now: Date.now,
42
47
  log: t => console.log(t),
43
48
  };
@@ -77,7 +82,8 @@ async function checks(branch, { waitMs = 30 * 60e3, pollMs = 30e3, firstMs = 3 *
77
82
  for (;;) {
78
83
  list = checkList(pr, io);
79
84
  const pending = list.filter(c => c.bucket === 'pending');
80
- io.note(`${pr.url}: ${list.length ? `waiting for ${pending.map(c => c.name).join(', ')}` : 'no checks reported yet'}`);
85
+ io.note(`${pr.url}: ${list.length ? `waiting for ${pending.map(c => c.name).join(', ')}` : 'no checks reported yet'}`,
86
+ { stage: `PR #${pr.number}`, done: list.length - pending.length, total: list.length, label: pending.length ? `waiting for ${pending[0].name}${pending.length > 1 ? ` and ${pending.length - 1} more` : ''}` : 'no checks reported yet' });
81
87
  if (list.length && !pending.length) break;
82
88
  // a repository without CI never reports any: after a few minutes, there's nothing to wait for
83
89
  if (!list.length && io.now() - start >= firstMs) { io.log(`No checks reported on ${pr.url}: nothing to wait for.`); return 0; }
@@ -167,15 +173,17 @@ function forward(main, { check = true } = {}, cfg = settings(), io = IO) {
167
173
  specs.fetchOrigin();
168
174
  const ref = specs.planRef();
169
175
  const plan = ref && specs.show(ref, 'specs/plan.md');
170
- if (!plan) return 0;
176
+ // the plan's features, and those built feature by feature on a branch of their own (specs.js branch)
177
+ const local = (git('for-each-ref', '--format=%(refname:short)', 'refs/heads/feature/') || '').split('\n').filter(Boolean).map(b => b.slice(8));
178
+ const ids = [...new Set([...(plan ? specs.planFeatures(plan).rows.map(r => r.id) : []), ...local])];
171
179
  const built = specs.builtOn(main);
172
180
  const was = branchNow();
173
181
  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;
182
+ for (const id of ids) {
183
+ const b = `feature/${id}`;
184
+ if (built.has(id) || git('rev-parse', '--verify', '--quiet', `refs/heads/${b}`) === null) continue;
177
185
  // 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];
186
+ const parent = (/its PR goes to ([^)\s]+)\)/.exec(git('show', `${b}:specs/${id}/progress.md`) || '') || [])[1];
179
187
  const parentId = parent && (/^feature\/(.+)$/.exec(parent) || [])[1];
180
188
  if (!parentId || !built.has(parentId)) continue;
181
189
  if (git('merge-base', '--is-ancestor', main, b) === null) {
@@ -183,7 +191,7 @@ function forward(main, { check = true } = {}, cfg = settings(), io = IO) {
183
191
  const before = git('rev-parse', 'HEAD');
184
192
  let s = { rest: [] };
185
193
  if (git('merge', '--no-edit', '--quiet', main) === null) {
186
- s = settle(r.id);
194
+ s = settle(id);
187
195
  if (s.rest.length || git('commit', '--no-edit', '--quiet') === null) {
188
196
  git('merge', '--abort');
189
197
  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 +203,9 @@ function forward(main, { check = true } = {}, cfg = settings(), io = IO) {
195
203
  if (s.lock || changed.some(f => LOCKS.test(f))) sh('sh', ['scripts/amk/install-deps.sh'], { stdio: 'ignore' });
196
204
  if ((s.pods || changed.includes('ios/Podfile.lock')) && process.platform === 'darwin') sh('sh', ['scripts/amk/pod-install.sh'], { stdio: 'ignore' });
197
205
  if (s.spec) {
198
- sh(process.execPath, ['scripts/amk/specs.js', 'merge', r.id], { stdio: 'ignore' });
206
+ sh(process.execPath, ['scripts/amk/specs.js', 'merge', id], { stdio: 'ignore' });
199
207
  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}`);
208
+ git('commit', '--quiet', '-m', `docs(spec): ${id} merged into the living spec again, after main\n\nSpec: specs/${id}`);
201
209
  }
202
210
  if (check && sh('sh', ['scripts/amk/verify.sh', 'quick'], { stdio: 'ignore' }).status !== 0) {
203
211
  git('reset', '--quiet', '--keep', before);
@@ -231,7 +239,7 @@ if (require.main === module) {
231
239
  const branch = named || branchNow();
232
240
  const main = specs.mainRef();
233
241
  const done = c => { process.exitCode = c; };
234
- if (cmd === 'checks') checks(branch, { waitMs: (parseFloat(opt('--wait')) || 30) * 60e3 }).then(done);
242
+ if (cmd === 'checks') checks(branch, { waitMs: (parseFloat(opt('--wait')) || 30) * 60e3 }).then(c => { progress.end('pr-checks', c === 0 ? 'passed' : ''); done(c); });
235
243
  else if (cmd === 'automerge') done(automerge(branch, main));
236
244
  else if (cmd === 'comments') done(comments(branch));
237
245
  else if (cmd === 'forward') done(forward(main));
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ // Where the kit's long runs stand, for the status line and `node scripts/amk/status.js --watch`: a small JSON file per
3
+ // run in .amk/progress/ (what it is, its stage, how far: done of total, what it's on, since when), written as it goes,
4
+ // and the length of the last run of each kind that passed, as a guide to how long the next one takes.
5
+ // node scripts/amk/progress.js set <key> --pid <pid> --title <title> [--kind <k>] [--stage <s>] [--done <n>] [--total <n>] [--label <l>]
6
+ // node scripts/amk/progress.js end <key> [--result passed|failed] or, for every run of a process, end-pid <pid>
7
+ // A run whose process is gone (killed, crashed) is left out when it's read, and its file removed.
8
+ 'use strict';
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ const DIR = path.join(__dirname, '..', '..', '.amk', 'progress');
13
+ const HISTORY = path.join(DIR, 'history.json');
14
+ const file = key => path.join(DIR, `${String(key).replace(/[^A-Za-z0-9._-]/g, '_')}.json`);
15
+ const readJson = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
16
+ // written whole: a reader never sees half a file
17
+ function writeJson(f, value) {
18
+ fs.mkdirSync(path.dirname(f), { recursive: true });
19
+ const tmp = `${f}.${process.pid}.tmp`;
20
+ fs.writeFileSync(tmp, `${JSON.stringify(value)}\n`);
21
+ fs.renameSync(tmp, f);
22
+ }
23
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
24
+
25
+ // a run's record: kept from the last call, so a stage can change without repeating the title
26
+ function set(key, fields, now = Date.now()) {
27
+ const was = readJson(file(key)) || {};
28
+ // a new stage starts its own count
29
+ const fresh = fields.stage !== undefined && fields.stage !== was.stage;
30
+ const kept = fresh ? (({ done, total, label, ...rest }) => rest)(was) : was;
31
+ const next = { ...kept, ...fields, key, started: was.started || now, updated: now };
32
+ if (fresh) next.stageStarted = now;
33
+ if (!next.pid) next.pid = process.pid;
34
+ try { writeJson(file(key), next); } catch {}
35
+ return next;
36
+ }
37
+ // done: the record goes, and how long it took, when it passed, stays as the guide for its kind (one that failed or
38
+ // stopped part of the way says little about the next)
39
+ function end(key, result, now = Date.now()) {
40
+ const r = readJson(file(key));
41
+ try { fs.rmSync(file(key), { force: true }); } catch {}
42
+ if (!r || result !== 'passed') return r;
43
+ const history = readJson(HISTORY) || {};
44
+ history[r.kind || r.title] = { ms: now - r.started, at: now };
45
+ try { writeJson(HISTORY, history); } catch {}
46
+ return r;
47
+ }
48
+ const endPid = pid => runs({ all: true }).filter(r => String(r.pid) === String(pid)).map(r => end(r.key));
49
+
50
+ // the runs going on now, oldest first, each with its kind's last length; those whose process is gone are cleared away
51
+ function runs({ all = false } = {}) {
52
+ let names = [];
53
+ try { names = fs.readdirSync(DIR).filter(f => f.endsWith('.json') && f !== 'history.json'); } catch { return []; }
54
+ const history = readJson(HISTORY) || {};
55
+ return names.map(f => readJson(path.join(DIR, f))).filter(Boolean).filter(r => {
56
+ if (all || alive(r.pid)) return true;
57
+ try { fs.rmSync(file(r.key), { force: true }); } catch {}
58
+ return false;
59
+ }).map(r => ({ ...r, last: history[r.kind || r.title] || null })).sort((a, b) => a.started - b.started);
60
+ }
61
+
62
+ module.exports = { set, end, endPid, runs, writeJson, DIR };
63
+
64
+ if (require.main === module) {
65
+ const [cmd, key, ...rest] = process.argv.slice(2);
66
+ const opt = n => (rest.includes(`--${n}`) ? rest[rest.indexOf(`--${n}`) + 1] : undefined);
67
+ const num = n => (opt(n) === undefined ? undefined : Number(opt(n)));
68
+ if (cmd === 'set' && key) {
69
+ const fields = { title: opt('title'), kind: opt('kind'), stage: opt('stage'), label: opt('label'), done: num('done'), total: num('total'), pid: num('pid') };
70
+ set(key, Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined && !Number.isNaN(v))));
71
+ } else if (cmd === 'end' && key) end(key, opt('result'));
72
+ else if (cmd === 'end-pid' && key) endPid(key);
73
+ else { console.error('usage: progress.js set <key> --pid <pid> --title <title> [--kind k] [--stage s] [--done n] [--total n] [--label l] | end <key> [--result passed] | end-pid <pid>'); process.exitCode = 2; }
74
+ }
@@ -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]) {
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+ // What's going on in this project, at a glance: whether the AI agent is working, is waiting for something it started
3
+ // (a command in the background, a subagent: it goes on by itself when that ends), or is waiting for you; the feature's
4
+ // tasks (specs/<id>/tasks.md); and where the kit's long runs stand (scripts/amk/progress.js: device and quick checks, CI,
5
+ // an unattended build), with how long the last one of each took.
6
+ // Claude Code's status line runs it (statusLine in .claude/settings.json, every 2 seconds): a developer's own status
7
+ // line first, when they have one, then the kit's lines. AMK_STATUS=off leaves the kit's lines out.
8
+ // node scripts/amk/status.js the status, once
9
+ // node scripts/amk/status.js --watch every 2 seconds, in a terminal of its own: with any AI tool
10
+ // The agent's state comes from Claude Code's session log (for --watch, the newest of this project) and its hooks: other
11
+ // tools show the tasks and the runs.
12
+ 'use strict';
13
+ const fs = require('fs');
14
+ const os = require('os');
15
+ const path = require('path');
16
+ const { Buffer } = require('buffer');
17
+ const { execFileSync, spawnSync } = require('child_process');
18
+ const progress = require('./progress.js');
19
+
20
+ const root = path.join(__dirname, '..', '..');
21
+ const project = path.basename(root);
22
+ const STATE = path.join(root, '.amk', 'state');
23
+ const TAIL = 4 * 2 ** 20; // a session's first look reads at most this much of its end
24
+ const STALE = 6 * 3600e3; // something in the background not heard of for this long is taken as gone
25
+ const readJson = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
26
+ const save = (f, v) => { try { progress.writeJson(f, v); } catch {} };
27
+ const git = (...a) => { try { return execFileSync('git', a, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } catch { return ''; } };
28
+ const off = (env = process.env) => ['off', '0', 'no', 'false'].includes(String(env.AMK_STATUS || '').toLowerCase());
29
+ const idOf = (transcript, id) => String(id || path.basename(String(transcript || ''), '.jsonl')).replace(/[^A-Za-z0-9_-]/g, '_');
30
+
31
+ // ---------- the agent, from Claude Code's session log ----------
32
+ // the question a message ends with (its last line asking something), or an approval it asks for
33
+ function asks(text) {
34
+ const lines = String(text || '').split('\n').map(l => l.replace(/[*_`#>]/g, '').trim()).filter(Boolean);
35
+ return lines.filter(l => /\?$/.test(l)).pop() || lines.find(l => /\bapprov/i.test(l)) || '';
36
+ }
37
+ const what = p => { const i = p.input || {}; return String(i.description || i.command || i.prompt || p.name).split('\n')[0].slice(0, 80); };
38
+ // one record of the log: what the agent did last, and what it started in the background and hasn't heard back from
39
+ function take(s, line) {
40
+ let e;
41
+ try { e = JSON.parse(line); } catch { return; }
42
+ if (e.isSidechain) return; // a subagent's own records
43
+ const at = Date.parse(e.timestamp) || null;
44
+ const content = e.message && e.message.content;
45
+ // a background job's news: as a prompt of its own, or added to a turn under way. Its end has a status (completed,
46
+ // failed, stopped); a watcher's (Monitor's) events have none, and it goes on
47
+ const note = e.type === 'user' && typeof content === 'string' ? content
48
+ : e.type === 'attachment' && e.attachment && typeof e.attachment.prompt === 'string' ? e.attachment.prompt : '';
49
+ if (/^\s*<task-notification>/.test(note)) {
50
+ const id = (/<task-id>([^<]+)<\/task-id>/.exec(note) || [])[1];
51
+ if (id && /<status>(?!running)\w+<\/status>/.test(note)) delete s.pending[id];
52
+ }
53
+ if (e.type === 'assistant' && Array.isArray(content)) {
54
+ for (const p of content) {
55
+ if (p.type === 'tool_use') {
56
+ s.uses[p.id] = what(p);
57
+ const q = p.name === 'AskUserQuestion' && (((p.input || {}).questions || [])[0] || {}).question;
58
+ s.last = { kind: 'tool', name: p.name, at, ...(q ? { ask: String(q).slice(0, 200) } : {}) };
59
+ } else if (p.type === 'text' && String(p.text).trim()) s.last = { kind: 'text', text: String(p.text).slice(-2000), at };
60
+ }
61
+ } else if (e.type === 'user' && typeof content === 'string') s.last = { kind: 'prompt', at };
62
+ else if (e.type === 'user' && Array.isArray(content)) {
63
+ for (const p of content) {
64
+ if (p.type === 'tool_result') {
65
+ const r = e.toolUseResult || {};
66
+ const job = r.backgroundTaskId || (r.status === 'async_launched' && r.agentId) || r.taskId;
67
+ if (job) s.pending[job] = { what: String(r.description || s.uses[p.tool_use_id] || 'a command').slice(0, 80), at };
68
+ delete s.uses[p.tool_use_id];
69
+ s.last = { kind: 'result', at };
70
+ } else if (p.type === 'text') s.last = { kind: /^\[Request interrupted by user/.test(p.text || '') ? 'stopped' : 'prompt', at };
71
+ }
72
+ }
73
+ }
74
+ // the session as its log says now: read on from where the last look stopped (kept in .amk/state/), whole lines only
75
+ function session(transcript, id) {
76
+ let size;
77
+ try { size = fs.statSync(transcript).size; } catch { return null; }
78
+ const cache = path.join(STATE, `session-${idOf(transcript, id)}.json`);
79
+ let s = readJson(cache);
80
+ if (!s || s.path !== transcript || s.offset > size) s = { path: transcript, offset: Math.max(0, size - TAIL), pending: {}, uses: {}, last: null, cut: true };
81
+ if (size > s.offset) {
82
+ const buf = Buffer.alloc(size - s.offset);
83
+ const fd = fs.openSync(transcript, 'r');
84
+ try { fs.readSync(fd, buf, 0, buf.length, s.offset); } finally { fs.closeSync(fd); }
85
+ const end = buf.lastIndexOf(10);
86
+ if (end >= 0) {
87
+ let lines = buf.subarray(0, end + 1).toString('utf8').split('\n');
88
+ if (s.cut && s.offset > 0) lines = lines.slice(1); // the first look starts inside a line
89
+ for (const l of lines) if (l) take(s, l);
90
+ s.offset += end + 1;
91
+ s.cut = false;
92
+ const uses = Object.entries(s.uses);
93
+ if (uses.length > 50) s.uses = Object.fromEntries(uses.slice(-50));
94
+ save(cache, s);
95
+ }
96
+ }
97
+ return s;
98
+ }
99
+ // what the hooks saw that the log doesn't say: the turn ended (Stop), or Claude Code asks for a permission
100
+ const marksFile = (transcript, id) => path.join(STATE, `marks-${idOf(transcript, id)}.json`);
101
+ const marks = (transcript, id) => readJson(marksFile(transcript, id)) || {};
102
+ function mark(p, fields) {
103
+ if (!p.transcript_path && !p.session_id) return;
104
+ save(marksFile(p.transcript_path, p.session_id), { ...marks(p.transcript_path, p.session_id), ...fields });
105
+ }
106
+ // working, waiting (for what it started: it goes on by itself), asks (you), stopped (you stopped it), or done
107
+ function agentState(s, m = {}, now = Date.now(), lastWords = null) {
108
+ if (!s || !s.last) return null;
109
+ const pending = Object.values(s.pending || {}).filter(p => !p.at || now - p.at < STALE).sort((a, b) => (a.at || 0) - (b.at || 0));
110
+ const l = s.last;
111
+ const at = l.at || 0;
112
+ if (l.kind === 'tool' && l.name === 'AskUserQuestion') return { state: 'asks', text: l.ask || 'a question', pending, at };
113
+ if (m.attention && m.attention.at >= at) return { state: 'asks', text: m.attention.text, pending, at: m.attention.at };
114
+ const over = l.kind === 'stopped' || (m.ended && m.ended >= at) || lastWords !== null;
115
+ if (!over) return { state: 'working', pending, at };
116
+ if (pending.length) return { state: 'waiting', pending, at };
117
+ if (l.kind === 'stopped') return { state: 'stopped', pending, at };
118
+ const q = asks(lastWords !== null ? lastWords : l.kind === 'text' ? l.text : '');
119
+ return q ? { state: 'asks', text: q, pending, at } : { state: 'done', pending, at };
120
+ }
121
+ const stateOf = (p, lastWords = null) => agentState(session(p.transcript_path, p.session_id), marks(p.transcript_path, p.session_id), Date.now(), lastWords);
122
+ // the newest Claude Code session log of this project (Claude Code names its folder after the project's path)
123
+ function newestTranscript(dir = root, home = os.homedir()) {
124
+ try {
125
+ const base = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(home, '.claude'), 'projects', fs.realpathSync(dir).replace(/[^a-zA-Z0-9]/g, '-'));
126
+ return fs.readdirSync(base).filter(f => f.endsWith('.jsonl')).map(f => path.join(base, f))
127
+ .map(f => [f, fs.statSync(f).mtimeMs]).sort((a, b) => b[1] - a[1]).map(x => x[0])[0] || null;
128
+ } catch { return null; }
129
+ }
130
+
131
+ // ---------- the feature's tasks ----------
132
+ function readText(f) { try { return fs.readFileSync(f, 'utf8'); } catch { return ''; } }
133
+ // the feature of this branch (feature/<id>, fix/<id>), else the spec in progress updated last
134
+ function tasks() {
135
+ const specs = path.join(root, 'specs');
136
+ const id0 = (/^(?:feature|fix)\/(.+)$/.exec(git('symbolic-ref', '--quiet', '--short', 'HEAD')) || [])[1];
137
+ let id = id0 && fs.existsSync(path.join(specs, id0, 'tasks.md')) ? id0 : null;
138
+ if (!id) {
139
+ let dirs = [];
140
+ try { dirs = fs.readdirSync(specs).filter(d => d !== '_templates' && d !== 'current'); } catch {}
141
+ id = dirs.map(d => path.join(specs, d, 'progress.md')).filter(f => /^Status:\s*in progress/im.test(readText(f)))
142
+ .map(f => [f, fs.statSync(f).mtimeMs]).sort((a, b) => b[1] - a[1]).map(([f]) => path.basename(path.dirname(f)))[0] || null;
143
+ }
144
+ if (!id) return null;
145
+ const items = [...readText(path.join(specs, id, 'tasks.md')).matchAll(/^\s*- \[([ xX])\]\s*(.*)$/gm)]
146
+ .map(m => ({ done: m[1] !== ' ', title: m[2].replace(/^\d+[.)]\s*/, '').split(/\s+—\s+/)[0].trim() }));
147
+ if (!items.length) return null;
148
+ const done = items.filter(t => t.done).length;
149
+ return { id, done, total: items.length, current: (items.find(t => !t.done) || {}).title || '', items };
150
+ }
151
+
152
+ // ---------- the view ----------
153
+ const C = { dim: s => `\x1b[2m${s}\x1b[22m`, yellow: s => `\x1b[33m${s}\x1b[39m`, magenta: s => `\x1b[35m${s}\x1b[39m`, green: s => `\x1b[32m${s}\x1b[39m`, cyan: s => `\x1b[36m${s}\x1b[39m` };
154
+ const plain = s => s.replace(/\x1b\[[0-9;]*m/g, '');
155
+ // a line cut to the width, its colours kept
156
+ function fit(s, width) {
157
+ if (!width || [...plain(s)].length <= width) return s;
158
+ let out = '';
159
+ let n = 0;
160
+ for (const part of s.split(/(\x1b\[[0-9;]*m)/)) {
161
+ if (/^\x1b\[/.test(part)) { out += part; continue; }
162
+ const chars = [...part].slice(0, Math.max(0, width - 1 - n));
163
+ out += chars.join('');
164
+ n += chars.length;
165
+ }
166
+ return `${out}…\x1b[0m`;
167
+ }
168
+ const ago = (from, now = Date.now()) => {
169
+ const s = Math.max(0, Math.round((now - from) / 1000));
170
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`;
171
+ };
172
+ const bar = (done, total, w = 5) => { const n = Math.round((done / total) * w); return `${'▰'.repeat(n)}${'▱'.repeat(w - n)}`; };
173
+ // the agent's line; plain work isn't one under Claude Code's prompt, where its spinner says so
174
+ function agentLine(a, now = Date.now(), always = false) {
175
+ if (!a) return '';
176
+ const first = a.pending[0];
177
+ const more = a.pending.length > 1 ? ` and ${a.pending.length - 1} more` : '';
178
+ if (a.state === 'waiting') return `${C.yellow('⏳ Waiting')} for ${first.what}${first.at ? ` (${ago(first.at, now)})` : ''}${more} ${C.dim('· goes on by itself when that ends')}`;
179
+ if (a.state === 'asks') return `${C.magenta('❓ Needs you:')} ${a.text}`;
180
+ if (a.state === 'stopped') return `${C.cyan('⏸ Stopped')} ${C.dim('· your turn')}`;
181
+ if (a.state === 'done') return `${C.green('✓ Done')} ${C.dim('· your turn')}`;
182
+ if (first) return `${C.cyan('▶ Working')} ${C.dim(`· ${first.what} running in the background${more}`)}`;
183
+ return always ? C.cyan('▶ Working') : '';
184
+ }
185
+ const runLine = (r, now = Date.now()) => `${r.title}${r.stage ? `: ${r.stage}` : ''}${r.total ? ` ${r.done || 0}/${r.total}` : ''}${r.label ? ` ${r.label}` : ''} ${C.dim(`${ago(r.started, now)}${r.last ? ` (last ${ago(0, r.last.ms)})` : ''}`)}`;
186
+ const taskLine = t => `${t.id} ${bar(t.done, t.total)} ${t.done}/${t.total} tasks${t.current ? ` ${C.dim(`· ${t.current}`)}` : ''}`;
187
+
188
+ // the kit's lines under the prompt: the agent, then the feature's tasks and the runs
189
+ function lines({ transcript = null, sessionId = null, now = Date.now(), width = 0 } = {}) {
190
+ const a = transcript ? agentState(session(transcript, sessionId), marks(transcript, sessionId), now) : null;
191
+ const t = tasks();
192
+ const work = [t && taskLine(t), ...progress.runs().map(r => runLine(r, now))].filter(Boolean);
193
+ return [agentLine(a, now), work.join(C.dim(' · '))].filter(Boolean).map(l => fit(l, width));
194
+ }
195
+
196
+ // Claude Code's status line: the developer's own first (the project's setting replaces theirs), then the kit's
197
+ function ownStatusLine(input, env = process.env) {
198
+ const own = (readJson(path.join(env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'), 'settings.json')) || {}).statusLine;
199
+ if (!own || own.type !== 'command' || !own.command || /scripts\/amk\/status\.js/.test(own.command)) return '';
200
+ // ponytail: through the system shell; a Windows status line written for Git Bash doesn't run here
201
+ const r = spawnSync(own.command, { shell: true, input, encoding: 'utf8', timeout: 1500, env });
202
+ return (r.stdout || '').replace(/\r\n/g, '\n').replace(/\n+$/, ''); // a Windows command's lines end in \r\n
203
+ }
204
+ function statusLine() {
205
+ let input = '';
206
+ try { input = fs.readFileSync(0, 'utf8'); } catch {}
207
+ let p = {};
208
+ try { p = JSON.parse(input); } catch {}
209
+ const out = [ownStatusLine(input)];
210
+ if (!off()) out.push(...lines({ transcript: p.transcript_path, sessionId: p.session_id, width: Number(process.env.COLUMNS) || 0 }));
211
+ process.stdout.write(`${out.filter(Boolean).join('\n')}\n`);
212
+ }
213
+
214
+ // once, or every 2 seconds in a terminal of its own, with any AI tool
215
+ function full({ now = Date.now(), transcript = newestTranscript() } = {}) {
216
+ const a = transcript ? agentState(session(transcript), marks(transcript), now) : null;
217
+ const t = tasks();
218
+ const out = [`${project} ${C.dim(`· ${new Date(now).toLocaleTimeString()}`)}`, ''];
219
+ out.push(a ? `${agentLine(a, now, true)}${a.at ? C.dim(` · ${ago(a.at, now)} ago`) : ''}` : C.dim('The agent: shown for Claude Code sessions. Other tools: the tasks and the checks below.'));
220
+ if (a && a.pending.length > 1) for (const p of a.pending) out.push(C.dim(` ⏳ ${p.what}${p.at ? ` (${ago(p.at, now)})` : ''}`));
221
+ if (t) {
222
+ out.push('', `${t.id}: ${t.done} of ${t.total} tasks done ${bar(t.done, t.total, 10)}`);
223
+ const next = t.items.findIndex(x => !x.done);
224
+ t.items.forEach((x, i) => out.push(` ${x.done ? C.green('✓') : i === next ? C.cyan('▶') : C.dim('○')} ${x.done ? C.dim(x.title) : x.title}`));
225
+ }
226
+ const runs = progress.runs();
227
+ if (runs.length) out.push('', ...runs.map(r => `${runLine(r, now)}${r.total ? ` ${bar(r.done || 0, r.total, 10)}` : ''}`));
228
+ if (!t && !runs.length && !a) out.push(C.dim('Nothing in progress.'));
229
+ return out.join('\n');
230
+ }
231
+
232
+ module.exports = { asks, take, session, marks, mark, agentState, stateOf, newestTranscript, tasks, lines, statusLine, ownStatusLine, full, fit, ago };
233
+
234
+ if (require.main === module) {
235
+ if (process.argv.includes('--watch')) {
236
+ const draw = () => process.stdout.write(`\x1b[H\x1b[2J${full()}\n${C.dim('\nEvery 2 seconds. Ctrl+C to stop.')}\n`);
237
+ draw();
238
+ setInterval(draw, 2000);
239
+ } else console.log(full());
240
+ }
@@ -5,6 +5,10 @@
5
5
  // Antigravity rejects, dropping the whole hook set, the guard included
6
6
  // - Codex asks with options to pick from (request_user_input) in every mode, not only in plan mode: rulesync writes no
7
7
  // [features] table, and Codex reads it from the project's config once the folder is trusted
8
+ // - Codex shows its plan as a checklist while it works (update_plan, off since Codex 0.152), in step with the spec's tasks
9
+ // - Claude Code shows what's going on under the prompt (scripts/amk/status.js, every 2 seconds), the spec's tasks
10
+ // included. rulesync has no statusLine, and keeps it once it's there. A team's own status line in the project's
11
+ // settings stays
8
12
  // Usage: node scripts/amk/tool-configs.js (in the project's folder)
9
13
  'use strict';
10
14
  const fs = require('fs');
@@ -34,8 +38,27 @@ function codexQuestions(dir) {
34
38
  : `${text.replace(/\n*$/, '\n')}\n# agentic-mobile-kit: questions as options to pick from, in every mode\n[features]\n${on}\n`);
35
39
  }
36
40
 
37
- const afterGenerate = dir => { flattenAntigravityStop(dir); codexQuestions(dir); };
41
+ function codexPlan(dir) {
42
+ const file = path.join(dir, '.codex/config.toml');
43
+ const text = read(file);
44
+ if (text === null || /^[^#\n]*\bupdate_plan\b/m.test(text)) return;
45
+ fs.writeFileSync(file, `${text.replace(/\n*$/, '\n')}\n# agentic-mobile-kit: the plan as a checklist while it works, in step with the spec's tasks\n[tools.update_plan]\nenabled = true\n`);
46
+ }
47
+
48
+ // found from wherever Claude Code runs it, as the hooks are (.rulesync/hooks.jsonc)
49
+ const STATUS_LINE = { type: 'command', command: "node -e \"require(require('child_process').execSync('git rev-parse --show-toplevel').toString().trim() + '/scripts/amk/status.js').statusLine()\"", refreshInterval: 2 };
50
+ function claudeStatus(dir) {
51
+ const file = path.join(dir, '.claude/settings.json');
52
+ let settings;
53
+ try { settings = JSON.parse(read(file)); } catch { return; }
54
+ if (!settings || typeof settings !== 'object') return;
55
+ const before = JSON.stringify(settings);
56
+ if (!settings.statusLine || /scripts\/amk\/status\.js/.test(settings.statusLine.command || '')) settings.statusLine = STATUS_LINE;
57
+ if (JSON.stringify(settings) !== before) fs.writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
58
+ }
59
+
60
+ const afterGenerate = dir => { flattenAntigravityStop(dir); codexQuestions(dir); codexPlan(dir); claudeStatus(dir); };
38
61
 
39
- module.exports = { afterGenerate, flattenAntigravityStop, codexQuestions };
62
+ module.exports = { afterGenerate, flattenAntigravityStop, codexQuestions, codexPlan, claudeStatus, STATUS_LINE };
40
63
 
41
64
  if (require.main === module) afterGenerate(process.cwd());
@@ -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'
@@ -239,7 +246,28 @@ unclaim() { l=$(lock_path "$1"); rm -f "$l/owner"; rmdir "$l" 2> /dev/null || tr
239
246
  release() { for l in $held; do rm -f "$l/owner"; rmdir "$l" 2> /dev/null || true; done; held=""; }
240
247
  temps="" # the temporary devices this run made for a part of the flows (--part), deleted at its end
241
248
  tree_flow="" # the copy of a flow with view-tree steps (Android), next to it while it runs
242
- trap 'release; drop_temps; [ -z "$tree_flow" ] || rm -f "$tree_flow"' EXIT
249
+ # where this run stands, for the status line and node scripts/amk/status.js --watch: a record per check in
250
+ # .amk/progress/ (scripts/amk/progress.js), gone when the check ends. Git Bash's $$ isn't the process ID node sees
251
+ me=$$
252
+ [ ! -r "/proc/$$/winpid" ] || me=$(cat "/proc/$$/winpid")
253
+ step() { # quick, ios or android; its stage; for the flows: how many ran, of how many, and the one running
254
+ step_title="Quick check" step_kind=quick-$related
255
+ case $1 in
256
+ ios | android)
257
+ step_title=iOS
258
+ [ "$1" = ios ] || step_title=Android
259
+ if [ "$build_only" = 1 ]; then step_title="$step_title build"; else step_title="$step_title check${part:+ part $part}"; fi
260
+ step_kind=$1-$build_only$no_build${part:+-part} ;;
261
+ esac
262
+ if [ -n "${3:-}" ]; then
263
+ node "$root/scripts/amk/progress.js" set "verify-$1-$me" --pid "$me" --title "$step_title" --kind "$step_kind" --stage "$2" --done "$3" --total "$4" --label "$5"
264
+ else
265
+ node "$root/scripts/amk/progress.js" set "verify-$1-$me" --pid "$me" --title "$step_title" --kind "$step_kind" --stage "$2"
266
+ fi > /dev/null 2>&1 || true
267
+ }
268
+ # its length is kept as a guide for the next of its kind when it passed
269
+ finish() { node "$root/scripts/amk/progress.js" end "verify-$1-$me" --result "$([ "$status" = 0 ] && echo passed || echo failed)" > /dev/null 2>&1 || true; }
270
+ trap 'release; drop_temps; [ -z "$tree_flow" ] || rm -f "$tree_flow"; node "$root/scripts/amk/progress.js" end-pid "$me" > /dev/null 2>&1 || true' EXIT
243
271
  trap 'exit 130' INT TERM
244
272
  holder() {
245
273
  l=$(lock_path "$1")
@@ -419,6 +447,7 @@ run_flows() { # screen device app_id orientation (PORTRAIT, or LANDSCAPE_LEFT to
419
447
  files=$(flow_files)
420
448
  if [ -z "$files" ]; then
421
449
  [ -z "$tags" ] || echo " $1: no flow has the tag $tags, so this is a check that the app opens"
450
+ [ "$changed" = 0 ] || [ -n "$spec" ] || echo " $1: no flow reaches what this branch changed, so this is a check that the app opens"
422
451
  # launchApp returns before the app has drawn, and a splash screen stays up until the JavaScript has loaded:
423
452
  # a fixed wait (for text that never appears), then for the screen to settle, so the screenshot shows the app
424
453
  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"
@@ -427,9 +456,13 @@ run_flows() { # screen device app_id orientation (PORTRAIT, or LANDSCAPE_LEFT to
427
456
  passed=0
428
457
  total=0
429
458
  flakies=0
459
+ count=$(echo $files | wc -w | tr -d ' ')
460
+ view=${1#"${1%%-*}"}
461
+ case $view in '') view=phone ;; -landscape) view="phone landscape" ;; *) view=$(echo "${view#-}" | tr - ' ') ;; esac
430
462
  for f in $files; do
431
463
  total=$((total + 1))
432
464
  name=$(basename "$f" .yaml)
465
+ step "${1%%-*}" "$view" $((total - 1)) "$count" "$name"
433
466
  ok=0 why="" shot="" first=""
434
467
  # an earlier run's first try, when the flow was flaky then
435
468
  [ ! -d "$evidence/maestro-logs/$1-$name-first-try" ] || rm -r "$evidence/maestro-logs/$1-$name-first-try"
@@ -593,9 +626,9 @@ check_screens() { # platform phone tablet app_id screens…
593
626
 
594
627
  quick() {
595
628
  # each one passes when the app's script passes, or when all its failures were already on the base branch
596
- if node scripts/amk/baseline.js lint > "$evidence/lint.log" 2>&1 &&
597
- node scripts/amk/baseline.js typecheck > "$evidence/typecheck.log" 2>&1 &&
598
- node scripts/amk/baseline.js test $([ "$related" = 0 ] || echo --related) > "$evidence/test.log" 2>&1; then
629
+ if step quick lint && node scripts/amk/baseline.js lint > "$evidence/lint.log" 2>&1 &&
630
+ step quick typecheck && node scripts/amk/baseline.js typecheck > "$evidence/typecheck.log" 2>&1 &&
631
+ step quick tests && node scripts/amk/baseline.js test $([ "$related" = 0 ] || echo --related) > "$evidence/test.log" 2>&1; then
599
632
  if [ "$related" = 0 ]; then echo "quick: lint, typecheck and tests passed"; else echo "quick: lint, typecheck and the tests related to this branch's changes passed"; fi
600
633
  # what didn't run (no such script, or an Expo app without ESLint yet), and failures the base branch already had
601
634
  cat "$evidence/lint.log" "$evidence/typecheck.log" "$evidence/test.log" |
@@ -607,6 +640,7 @@ quick() {
607
640
  fi
608
641
  # React Native mistakes in the lines this branch changed (the app's rules list them): its problems fail quick, its
609
642
  # warnings don't
643
+ step quick "React Native check"
610
644
  node scripts/amk/rn-check.js > "$evidence/rn-check.log" 2>&1 || status=1
611
645
  head -n 40 "$evidence/rn-check.log"
612
646
  [ "$(wc -l < "$evidence/rn-check.log")" -le 40 ] || echo " … all of it in ${evidence#"$root"/}/rn-check.log"
@@ -621,6 +655,7 @@ ios() {
621
655
  fi
622
656
  [ "$build_only" = 1 ] || command -v maestro > /dev/null || { echo "ios: Maestro isn't installed (https://maestro.dev)"; status=1; return; }
623
657
  same_api ios || { status=1; return; }
658
+ step ios "$([ "$no_build" = 1 ] && echo devices || echo build)"
624
659
  if [ "$no_build" = 0 ]; then
625
660
  # Expo apps without native folders in git: generate ios/ first
626
661
  if ! sh scripts/amk/prebuild.sh ios > "$evidence/prebuild-ios.log" 2>&1; then
@@ -696,6 +731,7 @@ ios() {
696
731
  echo "ios: there's no build to check yet: run sh scripts/amk/verify.sh build first"; status=1; return
697
732
  fi
698
733
  app_id=$(/usr/libexec/PlistBuddy -c 'Print CFBundleIdentifier' "$a/Info.plist")
734
+ step ios installing
699
735
  for d in $device $tablet; do
700
736
  if is_real "$d"; then
701
737
  launch_check "$d" || { status=1; return; }
@@ -974,6 +1010,7 @@ android_ready() {
974
1010
  android() {
975
1011
  [ "$build_only" = 1 ] || command -v maestro > /dev/null || { echo "android: Maestro isn't installed (https://maestro.dev)"; status=1; return; }
976
1012
  same_api android || { status=1; return; }
1013
+ step android "$([ "$no_build" = 1 ] && echo devices || echo build)"
977
1014
  case $(uname -s) in # where Android Studio puts the SDK by default
978
1015
  Darwin) default_sdk=$HOME/Library/Android/sdk ;;
979
1016
  MINGW* | MSYS* | CYGWIN*) default_sdk=${LOCALAPPDATA:-$HOME/AppData/Local}/Android/Sdk ;;
@@ -1084,6 +1121,7 @@ android() {
1084
1121
  aapt2="$(ls -d "$sdk"/build-tools/*/ 2> /dev/null | sort -V | tail -n 1)aapt2"
1085
1122
  app_id=$("$aapt2" dump badging "$apk" 2> /dev/null | sed -n "s/^package: name='\([^']*\)'.*/\1/p")
1086
1123
  [ -n "$app_id" ] || app_id=$(sed -n 's/.*applicationId *=\{0,1\} *"\([^"]*\)".*/\1/p' android/app/build.gradle* | head -n 1)
1124
+ step android installing
1087
1125
  if [ -n "$device" ]; then
1088
1126
  android_ready "$device" || { echo "android: $device didn't finish starting (see: adb devices)"; status=1; return; }
1089
1127
  "$adb" -s "$device" install -r "$apk" > /dev/null
@@ -1108,10 +1146,10 @@ build() {
1108
1146
  build_only=1
1109
1147
  ios_pid=""
1110
1148
  if [ "$(uname -s)" = Darwin ]; then
1111
- (trap release EXIT; ios; exit $status) > "$evidence/build-ios.out" 2>&1 &
1149
+ (trap release EXIT; ios; finish ios; exit $status) > "$evidence/build-ios.out" 2>&1 &
1112
1150
  ios_pid=$!
1113
1151
  fi
1114
- (trap release EXIT; android; exit $status) > "$evidence/build-android.out" 2>&1 &
1152
+ (trap release EXIT; android; finish android; exit $status) > "$evidence/build-android.out" 2>&1 &
1115
1153
  android_pid=$!
1116
1154
  [ -z "$ios_pid" ] || wait "$ios_pid" || status=1
1117
1155
  wait "$android_pid" || status=1
@@ -1234,10 +1272,10 @@ case $mode in ios | android | all | build)
1234
1272
  esac
1235
1273
 
1236
1274
  case $mode in
1237
- quick) quick ;;
1238
- ios) ios ;;
1239
- android) android ;;
1240
- all) quick; ios; android ;;
1275
+ quick) quick; finish quick ;;
1276
+ ios) ios; finish ios ;;
1277
+ android) android; finish android ;;
1278
+ all) quick; finish quick; ios; finish ios; android; finish android ;;
1241
1279
  build) build ;;
1242
1280
  plan) plan; exit 0 ;;
1243
1281
  approve) node scripts/amk/shots.js approve "$evidence"; exit $? ;;
@@ -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:
@@ -1,6 +1,6 @@
1
1
  # <ID>: tasks
2
2
 
3
- Each task: about an hour of work, under ~300 changed lines, one commit. Each is a thin slice through every layer it needs (screen, state, API call, test) that works and can be checked on its own, not one layer at a time; moving or renaming code that's there, to make the feature easy to add, comes first. Each names the requirement it serves, the tasks it waits on, and how it's checked. Its tests are written in the same task, not in a catch-up task at the end.
3
+ Each task: about an hour of work, under ~300 changed lines, one commit. Each is a thin slice through every layer it needs (screen, state, API call, test) that works and can be checked on its own, not one layer at a time; moving or renaming code that's there, to make the feature easy to add, comes first. Each names the requirement it serves, the tasks it waits on, and how it's checked. Its tests are written in the same task, not in a catch-up task at the end. While building, your AI tool's task list, if it has one (Codex's plan), follows this one: the task you're on in progress, each done when it's ticked here.
4
4
 
5
5
  - [ ] 1. <task> — for: <requirement name> — after: <task numbers, or none> — files: <paths> — check: <test, command or screen>
6
6
  - [ ] 2.