diff --git a/CHANGELOG.md b/CHANGELOG.md index 76172173..0a21e4e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,13 @@ tag in lockstep. Tag releases as `vMAJOR.MINOR.PATCH`. ## [Unreleased] +### Added +- The planner's stop gate (`gate-stage2-complete` on SubagentStop) now logs its verdicts to `gates.jsonl` and the event stream like every other gate, and the stuck release covers the planner: the same block three times in a row releases its stop unverified with a `state/stuck/plan-sprintN.` marker the supervisor acts on (a re-dispatch is a new agent id and starts over). A direct call (the supervisor's own check, `selfcheck`) is logged as a self-check and never releases. Reason: live e2e run 19's re-planning planner was blocked 9 times on one unchanged reason, none counted. Test: `scripts/test/planner-stuck.test.py`. + +### Fixed +- Planner persona: a later task's RED tests must fail against what the earlier tasks leave on main, not only the empty tree (live run 19: three of T2's tests passed against T1's placeholder, costing a re-plan). +- `targets check` no longer rejects a `create` change whose file already exists **and defines its planned symbol**: that change has shipped. A mid-sprint re-plan re-runs the planner's stop gate over the whole plan, and live e2e run 19 blocked the planner 9 times on T1's merged `create tests/parse.rs` while its brief said not to touch T1. `target` now resolves such a change to `file:line`. Test: `scripts/test/semantic-targets.test.py`. + ### Added - `gate-supervisor-scope` now also enforces **the supervisor never commits on main**: a `git commit` from the main agent in the main tree while a sprint is live is blocked (a commit inside a task worktree, the initial commit of an unborn repo, `task-worktree merge` and a stale lock pass). Reason: live e2e run 16's `Track Cargo.lock` commit on main traced to nothing; the rule was prose in SKILL.md only. Test: `scripts/test/supervisor-scope.test.py`. diff --git a/Makefile b/Makefile index a5c322fb..76753074 100644 --- a/Makefile +++ b/Makefile @@ -116,6 +116,7 @@ test-hosts: ## Budget/worktree regression + Codex hooks emulation + OpenCode plu python3 scripts/test/codex-hooks.test.py python3 scripts/test/rename-compat.test.py python3 scripts/test/supervisor-scope.test.py + python3 scripts/test/planner-stuck.test.py python3 scripts/test/hook-matchers.test.py python3 scripts/test/dispatch.test.py python3 scripts/test/log-execution.test.py diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 4d91dd4a..c460833d 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -16,7 +16,7 @@ original plan. | Milestone | Target | Contents | Status | |---|---|---|---| | **M0 — Hygiene** | v0.10.x | Mark `DESIGN` / `ARCHITECTURE` / `KICKSTART` historical; fix stale counts (8 → 9 roles) and the README CI section; add the `CONTRIBUTING.md` the README badge links to; one live-session smoke test of the hook wiring (open since `DEVLOG` v0.1) | done: live smoke test `make smoke-live YES=1` (6 checks, ~$0.004 on haiku); its first run found the Linux fail-open in `gate-supervisor-scope` (fixed, regression test added) | -| **M0.8 — North-star run** | v0.11.x | `make e2e-live YES=1`: a one-line intent (semver parser) goes through retrospective, intake, standards, planner, RED/SCAFFOLD/GREEN per task, structural review and the final gate to merged, tested code in a real Claude Code session, with the approval given up front. Reason: nothing had ever run the whole loop live; the first run found that no role gate fired on plugin installs | run 1: done end to end, 19 min, $1.15 (sonnet supervisor, haiku workers), 22 tests on main, 9/11 checks; found and fixed the `aloop:` matcher bug, a selfcheck crash and copy-merging. Run 2: **11/11**, 12m46s, $0.92, host gates on every role, worktree branches merged with `--no-ff`; found gates looping on the supervisor's contract slips (fixed). Run 3: 11/11, 12m00s, **$0.79**; found GREEN looping on RED's unformatted tests (fixed: RED/SCAFFOLD run the format check) and selfcheck missing the contract in Claude Code worktrees (fixed: the contract is copied in). Run 4 (all fixes): 11/11, 17m56s, $1.10, 12 gate blocks and no loops (28 → 17 → 12). Cost varies $0.79–1.15 per run; next: cut it (scaffold symbol parsing slips such as `(enum,`, supervisor turns), then a second intent beyond the semver fixture. Run 5: 11/11 but 29 min, $1.83, 44 blocks (the planner made 5 tasks; 27 false isolation blocks after workers `cd`'d to the main tree, fixed; subagents also read the plugin's own source, which costs tokens). Run 6: 11/11, **11m10s, $0.65**, plugin-source reads 30 → 2 after the agent prompts said not to; found a dispatch-before-contract loop (25 blocks, fixed by `gate-dispatch`) and annotated scaffold-symbol lines (fixed). Run 7 (after #9): 11/11, 13m46s, $0.98, 20 blocks, no dispatch loop; found RED blocked for listing an earlier task's passing tests, scaffold-symbols tables with a header row and trait-impl lines, and a guessed memory.md frontmatter (all fixed; `aloop init` now seeds memory.md). The re-plan coverage loss is now caught by `gate-final` (every planned test must be on main). Run 8, **second intent** (`INTENT=wordfreq`, two dependent stories): 12/12, 18m05s, $1.53, 54 blocks; found scope globs expanded against the worktree (29 GREEN blocks) and `mod common;` across test crates reported as a HIGH duplicate (57 review halts), both fixed. Run 9 (wordfreq again): 12/12, 19m42s, $1.56, 29 blocks; the ctx-symbols fix had not reached the run (`ensure-tools` rebuilt only on a version bump, fixed) and the planner named story dirs `S1-01/` (block message now names `s1-01-/`). Run 10 (rebuilt tools): 12/12, $1.20, but 44m48s and 45 blocks: the duplicate false positive is gone (0 HIGH); a RED worker's Write/Edit to the story's output.md was refused by Claude Code's worktree isolation and it stopped 29 times without trying a shell append (fixed: the block and the personas say how), plus 3 stale-`ATTEMPT` tamper blocks (fixed). Fixed after run 10: a worker that repeats an identical block 3 times is released unverified with a `STUCK` marker the supervisor acts on (reason: 29 minutes lost in run 10). Run 11 (all run-10 fixes): 12/12, **12m56s, $0.86, 6 blocks** (from 44m48s, $1.20, 45): no repeated block, one RED report-append block fixed on the first retry, one scaffold fmt block, two structural-reviewer comms blocks (STORY_DIR unset for a sprint-wide review, then a stale block) and 12 `gate-validate-artifact` write blocks on the planner's artifacts. Fixed after run 11: the artifact-write block carries md-db's diagnostics (the planner guessed twice per artifact: 12 of 25 verdicts), `gate-dispatch` requires an existing `STORY_DIR` and names the sprint dir for a whole-wave structural review (2 blocks), and OpenCode reports a stuck release as unverified. Run 12 (those fixes): 12/12, 15m22s, $1.10, 21 blocks: the planner fixed each artifact on the first retry (8 write blocks, from 12) and the reviewer's contract had `STORY_DIR`, but a stale worktree checkout under `.claude/worktrees/` made `ctx-symbols conflicts` report every symbol of main as a duplicate and the reviewer was blocked 10 times on a HIGH finding it could not fix (fixed: the walk skips host checkouts, `.agentic/`, `.transcripts/`). The stuck release now covers the structural reviewer and the final gate too (reason: 10 identical blocks, run 12). Gap: `targets check` blocked the planner twice because a context target named a planned symbol not yet in `src/lib.rs` (reason: planned symbols do not exist before SCAFFOLD; §4.6 owner to decide). Run 13 (those fixes): 12/12, 16m31s, $1.33, 16 blocks; the first build of the walk exclusion also excluded a worktree that IS a host checkout, so the scaffold gate counted every symbol 0 times (9 blocks; the worker was then released by the stuck release and the run still finished); fixed before the run ended (the exclusion applies below the walk root) and covered by a conformance case. Open: `targets check` blocks on the planner's first `targets.json` (2 per run, fixed on retry; §4.6 owner), and sub-agents reading the plugin's own source rose to 17 (from 2–10). Run 14 (all fixes): 12/12, **13m47s, $0.88, 11 blocks**, one host-run block in all (RED touched `src/lib.rs`, fixed on retry), no stuck worker; the rest are planning write blocks fixed on the first retry and workers' own self-checks. The supervisor's GREEN mandates in runs 11–14 named one symbol and `src/lib.rs only`, and the diff scope (from `tasks.md` or `targets scope`) bounds them anyway, so the "GREEN instructions overreaching" item is closed as not reproduced. The planner persona now carries the schema's artifact shapes and the `targets check` rules (to measure). Run 15 (planner shapes + rules, `task-worktree merge`): **13/13**, 13m13s, $1.42, 6 blocks: **0 planning write blocks** (from 8–12: every artifact and `targets.json` passed first time), no host-run block, and §4.7 is live on Claude Code for the first time: 8 commits, 8 `commit.created`, 6 `worktree.merged`, every merged commit answers `events trace` (new e2e check). Plugin-source reads, counted precisely (tool calls naming a plugin path; `--schema` uses excluded): 9, 8, 6 in runs 13–15, all by the supervisor reading `init.template.md` and `log-execution` to learn shapes SKILL.md now states (`log-execution --help` added). Run 15 cost more than run 14 ($1.42 vs $0.88) because the supervisor dispatched every single-task wave in the background and woke 16 times (run 14: 2), each wake re-reading its context: 5.5M cached Sonnet tokens vs 2.8M. SKILL.md now runs a one-task wave in the foreground. Run 16 (that rule): 12/13, **13m04s, $0.79** (from $1.42), **4 wakes** (from 16), 2.3M cached Sonnet tokens (from 5.5M), 9 blocks, 4 plugin-source reads (from 6); the one failed check was the trace: the supervisor committed `Track Cargo.lock` on main itself (the fixture left the lockfile untracked), a commit no task owns. SKILL.md: the supervisor never commits on main; the fixture seeds the lockfile. Of run 16's 9 blocks, 4 were workers self-checking before appending their report block (the personas said "run selfcheck, append your report"; fixed: report first, then selfcheck), 2 were scaffold fmt/uncommitted work and 1 RED touching `src/lib.rs`. Run 17 (report-first personas, never-commit-on-main, seeded lockfile): **13/13, 12m58s, $0.95, 2 wakes, 0 plugin-source reads**, 6 blocks: 3 were the structural reviewer's own `selfcheck` finding no contract (only workers got the worktree copy; fixed in `budget hook`, test-first), 2 RED self-checks before the report (the persona fix landed after this run started), 1 RED touching `src/lib.rs`. Run 18 (reviewer contract copy, v0.12.0): 13/13, 21m21s, $1.03, 6 wakes, 2 plugin-source reads, 6 blocks: the first RED self-check found no contract because Claude Code now prepends a session-context line to the sub-agent transcript and `budget` read only the first `user` line for `TASK_ID` (fixed, test-first: it reads on to the first line naming one); a RED worker's `cat >>` created a story's `output.md` without its frontmatter and self-checked twice against it (fixed: `budget hook pre` seeds `output.md` with `type: output` before the worker's first call); the planner's `targets check` and `TBW` self-checks (3, fixed on retry, by design); one RED touched `src/lib.rs` because the supervisor's mandate told it to shim there (SKILL.md: the mandate names `tests/common/mod.rs`); one scaffold symbol slip. Wall time was runner contention, not more turns. The never-commit-on-main rule is now a gate (`gate-supervisor-scope` blocks the supervisor's `git commit` in the main tree while the sprint is live; reason: a prose rule that one run already broke is cheaper to enforce than to re-find). Next: measure blocks ≤3 with these fixes | +| **M0.8 — North-star run** | v0.11.x | `make e2e-live YES=1`: a one-line intent (semver parser) goes through retrospective, intake, standards, planner, RED/SCAFFOLD/GREEN per task, structural review and the final gate to merged, tested code in a real Claude Code session, with the approval given up front. Reason: nothing had ever run the whole loop live; the first run found that no role gate fired on plugin installs | run 1: done end to end, 19 min, $1.15 (sonnet supervisor, haiku workers), 22 tests on main, 9/11 checks; found and fixed the `aloop:` matcher bug, a selfcheck crash and copy-merging. Run 2: **11/11**, 12m46s, $0.92, host gates on every role, worktree branches merged with `--no-ff`; found gates looping on the supervisor's contract slips (fixed). Run 3: 11/11, 12m00s, **$0.79**; found GREEN looping on RED's unformatted tests (fixed: RED/SCAFFOLD run the format check) and selfcheck missing the contract in Claude Code worktrees (fixed: the contract is copied in). Run 4 (all fixes): 11/11, 17m56s, $1.10, 12 gate blocks and no loops (28 → 17 → 12). Cost varies $0.79–1.15 per run; next: cut it (scaffold symbol parsing slips such as `(enum,`, supervisor turns), then a second intent beyond the semver fixture. Run 5: 11/11 but 29 min, $1.83, 44 blocks (the planner made 5 tasks; 27 false isolation blocks after workers `cd`'d to the main tree, fixed; subagents also read the plugin's own source, which costs tokens). Run 6: 11/11, **11m10s, $0.65**, plugin-source reads 30 → 2 after the agent prompts said not to; found a dispatch-before-contract loop (25 blocks, fixed by `gate-dispatch`) and annotated scaffold-symbol lines (fixed). Run 7 (after #9): 11/11, 13m46s, $0.98, 20 blocks, no dispatch loop; found RED blocked for listing an earlier task's passing tests, scaffold-symbols tables with a header row and trait-impl lines, and a guessed memory.md frontmatter (all fixed; `aloop init` now seeds memory.md). The re-plan coverage loss is now caught by `gate-final` (every planned test must be on main). Run 8, **second intent** (`INTENT=wordfreq`, two dependent stories): 12/12, 18m05s, $1.53, 54 blocks; found scope globs expanded against the worktree (29 GREEN blocks) and `mod common;` across test crates reported as a HIGH duplicate (57 review halts), both fixed. Run 9 (wordfreq again): 12/12, 19m42s, $1.56, 29 blocks; the ctx-symbols fix had not reached the run (`ensure-tools` rebuilt only on a version bump, fixed) and the planner named story dirs `S1-01/` (block message now names `s1-01-/`). Run 10 (rebuilt tools): 12/12, $1.20, but 44m48s and 45 blocks: the duplicate false positive is gone (0 HIGH); a RED worker's Write/Edit to the story's output.md was refused by Claude Code's worktree isolation and it stopped 29 times without trying a shell append (fixed: the block and the personas say how), plus 3 stale-`ATTEMPT` tamper blocks (fixed). Fixed after run 10: a worker that repeats an identical block 3 times is released unverified with a `STUCK` marker the supervisor acts on (reason: 29 minutes lost in run 10). Run 11 (all run-10 fixes): 12/12, **12m56s, $0.86, 6 blocks** (from 44m48s, $1.20, 45): no repeated block, one RED report-append block fixed on the first retry, one scaffold fmt block, two structural-reviewer comms blocks (STORY_DIR unset for a sprint-wide review, then a stale block) and 12 `gate-validate-artifact` write blocks on the planner's artifacts. Fixed after run 11: the artifact-write block carries md-db's diagnostics (the planner guessed twice per artifact: 12 of 25 verdicts), `gate-dispatch` requires an existing `STORY_DIR` and names the sprint dir for a whole-wave structural review (2 blocks), and OpenCode reports a stuck release as unverified. Run 12 (those fixes): 12/12, 15m22s, $1.10, 21 blocks: the planner fixed each artifact on the first retry (8 write blocks, from 12) and the reviewer's contract had `STORY_DIR`, but a stale worktree checkout under `.claude/worktrees/` made `ctx-symbols conflicts` report every symbol of main as a duplicate and the reviewer was blocked 10 times on a HIGH finding it could not fix (fixed: the walk skips host checkouts, `.agentic/`, `.transcripts/`). The stuck release now covers the structural reviewer and the final gate too (reason: 10 identical blocks, run 12). Gap: `targets check` blocked the planner twice because a context target named a planned symbol not yet in `src/lib.rs` (reason: planned symbols do not exist before SCAFFOLD; §4.6 owner to decide). Run 13 (those fixes): 12/12, 16m31s, $1.33, 16 blocks; the first build of the walk exclusion also excluded a worktree that IS a host checkout, so the scaffold gate counted every symbol 0 times (9 blocks; the worker was then released by the stuck release and the run still finished); fixed before the run ended (the exclusion applies below the walk root) and covered by a conformance case. Open: `targets check` blocks on the planner's first `targets.json` (2 per run, fixed on retry; §4.6 owner), and sub-agents reading the plugin's own source rose to 17 (from 2–10). Run 14 (all fixes): 12/12, **13m47s, $0.88, 11 blocks**, one host-run block in all (RED touched `src/lib.rs`, fixed on retry), no stuck worker; the rest are planning write blocks fixed on the first retry and workers' own self-checks. The supervisor's GREEN mandates in runs 11–14 named one symbol and `src/lib.rs only`, and the diff scope (from `tasks.md` or `targets scope`) bounds them anyway, so the "GREEN instructions overreaching" item is closed as not reproduced. The planner persona now carries the schema's artifact shapes and the `targets check` rules (to measure). Run 15 (planner shapes + rules, `task-worktree merge`): **13/13**, 13m13s, $1.42, 6 blocks: **0 planning write blocks** (from 8–12: every artifact and `targets.json` passed first time), no host-run block, and §4.7 is live on Claude Code for the first time: 8 commits, 8 `commit.created`, 6 `worktree.merged`, every merged commit answers `events trace` (new e2e check). Plugin-source reads, counted precisely (tool calls naming a plugin path; `--schema` uses excluded): 9, 8, 6 in runs 13–15, all by the supervisor reading `init.template.md` and `log-execution` to learn shapes SKILL.md now states (`log-execution --help` added). Run 15 cost more than run 14 ($1.42 vs $0.88) because the supervisor dispatched every single-task wave in the background and woke 16 times (run 14: 2), each wake re-reading its context: 5.5M cached Sonnet tokens vs 2.8M. SKILL.md now runs a one-task wave in the foreground. Run 16 (that rule): 12/13, **13m04s, $0.79** (from $1.42), **4 wakes** (from 16), 2.3M cached Sonnet tokens (from 5.5M), 9 blocks, 4 plugin-source reads (from 6); the one failed check was the trace: the supervisor committed `Track Cargo.lock` on main itself (the fixture left the lockfile untracked), a commit no task owns. SKILL.md: the supervisor never commits on main; the fixture seeds the lockfile. Of run 16's 9 blocks, 4 were workers self-checking before appending their report block (the personas said "run selfcheck, append your report"; fixed: report first, then selfcheck), 2 were scaffold fmt/uncommitted work and 1 RED touching `src/lib.rs`. Run 17 (report-first personas, never-commit-on-main, seeded lockfile): **13/13, 12m58s, $0.95, 2 wakes, 0 plugin-source reads**, 6 blocks: 3 were the structural reviewer's own `selfcheck` finding no contract (only workers got the worktree copy; fixed in `budget hook`, test-first), 2 RED self-checks before the report (the persona fix landed after this run started), 1 RED touching `src/lib.rs`. Run 18 (reviewer contract copy, v0.12.0): 13/13, 21m21s, $1.03, 6 wakes, 2 plugin-source reads, 6 blocks: the first RED self-check found no contract because Claude Code now prepends a session-context line to the sub-agent transcript and `budget` read only the first `user` line for `TASK_ID` (fixed, test-first: it reads on to the first line naming one); a RED worker's `cat >>` created a story's `output.md` without its frontmatter and self-checked twice against it (fixed: `budget hook pre` seeds `output.md` with `type: output` before the worker's first call); the planner's `targets check` and `TBW` self-checks (3, fixed on retry, by design); one RED touched `src/lib.rs` because the supervisor's mandate told it to shim there (SKILL.md: the mandate names `tests/common/mod.rs`); one scaffold symbol slip. Wall time was runner contention, not more turns. The never-commit-on-main rule is now a gate (`gate-supervisor-scope` blocks the supervisor's `git commit` in the main tree while the sprint is live; reason: a prose rule that one run already broke is cheaper to enforce than to re-find). Next: measure blocks ≤3 with these fixes Run 19 (never-commit-on-main gate): 12/12, 15m47s, $0.99, 39 supervisor turns, 2 plugin-source reads, **2 logged blocks** (one RED whose T2 tests already passed against T1's placeholder, one scaffold) — but 9 unlogged ones: the mid-sprint re-plan of T2 ran the planner's stop gate again, and `targets check` blocked its stop 9 times with "create targets tests/parse.rs, which already exists" for T1's merged change, which the brief had told it not to touch; it stopped only once it rewrote C1/C2 to `modify` and the supervisor dispatched it a second time. Fixed: a `create` whose file now exists and defines its planned_symbol is realized, not a defect (`targets check` passes; `target` resolves it to file:line; test: `semantic-targets.test.py`, reproduced on run 19's plan). Fixed after run 19: the planner's stop-gate verdicts are logged in `gates.jsonl` and the stuck release covers the planner (reason: 9 identical blocks in run 19 went uncounted and nothing ended the loop; test: `planner-stuck.test.py`). The planner persona now plans a later task's RED tests against what the earlier tasks leave on main (reason: run 19's T2 re-plan; to measure in run 20). Next: run 20 with 0 re-plans and ≤3 blocks | | **M0.6 — Gates fail closed** | v0.11.x | A gate that crashes (exit 1, e.g. an unbound variable) is a non-blocking hook error on Claude Code, so the action goes through. Make every gate trap unexpected errors into exit 2 with the reason, and add a conformance case per gate. Reason: the smoke run showed one real instance | done: `_failclosed.sh` on all 10 sub-agent gates + supervisor-scope inside a sprint; `scripts/test/fail-closed.test.py` (5 checks). Left fail-open on purpose: `gate-commit-author` and `gate-validate-artifact` outside a sprint, which see every session on the machine | | **M0.7 — Supervisor-owned task contract** | v0.11.x | The contract lives in the main tree, `.agentic/state/tasks/.env`, and the dispatch prompt's first line names the task; gates and the time box find it from the host's transcript, a worktree `task.env` that disagrees blocks, and sub-agents may not Write/Edit `.agentic/state/` or `task.env`. Settled by a live probe: Claude Code's `isolation: "worktree"` makes `.claude/worktrees/agent-` at dispatch, so a pre-written in-worktree contract was impossible there. Bash writes are guarded too (a command naming the contract with a write verb is blocked; a heuristic, so an obfuscated write still gets through). On hosts with no sub-agent transcript the worktree's `TASK_ID` (or its `.agentic/worktrees/` path) picks the contract | done: `make conformance` (58 today) + `scripts/test/{budget-worktree,supervisor-scope}.test.py` | | **M0.5 — Rename to aloop** | v0.11.0 | Plugin, marketplace, skill, CLI (`aloop`, `aloop init`), OpenCode plugin file and docs renamed; `agentic`, `agentic init`, `agentic-init` and `agentic bind` kept as aliases; OpenCode/Codex installs clean up pre-rename files. Data layout and settings keys unchanged (moved to M1). GitHub repo rename is the owner's call | done: `scripts/test/rename-compat.test.py` | diff --git a/docs/TRACKING.md b/docs/TRACKING.md index e56187e2..551f08bb 100644 --- a/docs/TRACKING.md +++ b/docs/TRACKING.md @@ -31,6 +31,7 @@ Status of every requirement in [ROADMAP.md](ROADMAP.md), in the four states §8 | 4.7 | Decision rationale + authority record | IMPLEMENTED_TESTED | `scripts/test/events.test.py` | | 4.7 | Lineage: commit → intent → approver | IMPLEMENTED_TESTED | `scripts/test/commit-trace.test.py` | | 4.7 | Every commit on main is a task's: the supervisor's own `git commit` on main is blocked mid-sprint | IMPLEMENTED_TESTED | `scripts/test/supervisor-scope.test.py` | +| 6.9 | Stuck release covers the planner; its stop verdicts are logged like every gate | IMPLEMENTED_TESTED | `scripts/test/planner-stuck.test.py` | | 4.7 | Commit messages from rationale; graph export | IMPLEMENTED_TESTED | `scripts/test/commit-trace.test.py` | | 4.8 | Cross-project impact provider seam | IMPLEMENTED_TESTED | `scripts/test/impact-provider.test.py` | | 4.9 | Usage reporting: classes apart, exact or marked, unreported classes named | IMPLEMENTED_TESTED | `scripts/test/budget-meter.test.py` | diff --git a/plugin/agents/planner.md b/plugin/agents/planner.md index 0d74f887..18bed01a 100644 --- a/plugin/agents/planner.md +++ b/plugin/agents/planner.md @@ -49,6 +49,14 @@ hard; 150k / 20 min soft — see `docs/agents/defaults.md`). A worker still runn the hard limit is STOPPED by the hook and the task comes back to you to split — never retried. So size each task so one worker can do its RED or its GREEN well inside the soft limit: a handful of tests, one or two files, one behaviour. When in doubt, split. +A later task's RED tests must fail against what the EARLIER tasks leave on main, not only +against the empty tree: `gate-red-verify` requires every new test to fail by assertion, so +a task whose planned tests already pass against the previous task's skeleton (a placeholder +that maps every non-success to one error variant, a default where a `todo!()` was) cannot be +RED and costs a mid-sprint re-plan (live run 19: three of T2's tests passed against T1's +placeholder). Plan each later task's tests around behaviour the earlier task's contract does +not provide, and state in the earlier task's summary what its skeleton returns for inputs +outside its scope, so the later tests can assert something it gets wrong. If defaults.md sets `AGENTIC_TIME_MODE=auto`, propose ONE stable task duration for the project (with a min and a max) to the supervisor, who records it with `timebox propose`; ask for a revision only with evidence (a stats.md, an event id). diff --git a/plugin/bin/README.md b/plugin/bin/README.md index cb5d1233..064b8403 100644 --- a/plugin/bin/README.md +++ b/plugin/bin/README.md @@ -34,7 +34,7 @@ ctx-symbols) → WARN + grep fallback; never a silent pass. | gate-structural-integrity | SubagentStop · structural-reviewer | appended output.md block; orphan/parallel/duplicate via ctx-symbols | no/stale output.md block / foundation-poisoning finding | | gate-final | SubagentStop · final-gate | full matrix; zero suppressions; all plan-ready ticked | matrix red / suppression / unticked | | gate-standards-cited | SubagentStop · standards | standards.md citations resolve | dangling citation | -| gate-stage2-complete | supervisor self-check + SubagentStop · planner | every story Stage-2 valid; no TBW; sprint self-contained (no later-sprint story IDs, no work deferred to a later sprint) | incomplete or spilling planning | +| gate-stage2-complete | supervisor self-check + SubagentStop · planner | every story Stage-2 valid; no TBW; sprint self-contained (no later-sprint story IDs, no work deferred to a later sprint); verdicts logged like every gate, and the stuck release covers the planner (3 identical blocks → stop released unverified, marker `state/stuck/plan-sprintN.`) | incomplete or spilling planning | | gate-plan-shape | called by gates | each plan checkbox carries `path::fn` | malformed plan | | gate-ledger-format | called by gates | execution.log line shape | malformed ledger | diff --git a/plugin/bin/_gatelib.sh b/plugin/bin/_gatelib.sh index 7425a1ac..ea51ab17 100755 --- a/plugin/bin/_gatelib.sh +++ b/plugin/bin/_gatelib.sh @@ -76,7 +76,9 @@ _gate_stuck() { [ "$self" = false ] && [ -n "${TASK_ID:-}" ] && [ -n "${ATTEMPT:-}" ] || return 1 # The build roles, plus the two read-only roles whose blocks can name a defect only the # supervisor can act on (live e2e run 12: a HIGH structural finding blocked the reviewer 10x). - case "${AGENT_ROLE:-}" in red-worker|scaffolder|green-worker|structural-reviewer|final-gate) ;; *) return 1 ;; esac + # And the planner (live e2e run 19: 9 identical blocks on a re-plan); its key is the sprint + # + the host's agent id (gate-stage2-complete), so a re-dispatch starts over. + case "${AGENT_ROLE:-}" in red-worker|scaffolder|green-worker|structural-reviewer|final-gate|planner) ;; *) return 1 ;; esac [ "$n" -ge 2 ] 2>/dev/null && [ -f "$log" ] || return 1 prior="$(grep -F "\"gate\":\"${GATE_NAME:-?}\"" "$log" | grep -F "\"task\":\"$TASK_ID\",\"attempt\":\"$ATTEMPT\"" \ | grep -F "\"wt\":\"$(repo_dir)\"" | grep -F '"selfcheck":false' | tail -n $((n - 1)) | grep -c -F "\"exit\":2,\"selfcheck\":false,\"reason\":\"$rh\"}")" @@ -85,8 +87,14 @@ _gate_stuck() { printf 'role=%s gate=%s task=%s attempt=%s blocks=%s\n%s\n' "${AGENT_ROLE:-}" "${GATE_NAME:-?}" "$TASK_ID" "$ATTEMPT" "$n" \ "$GATE_BLOCK_REASON" > "$AGENTIC_STATE/stuck/$TASK_ID.$ATTEMPT" 2>/dev/null echo "[${GATE_NAME:-gate}] STUCK — the same block $n times in a row; stop released, NOT verified." >&2 - echo " This attempt is not a pass. Supervisor: do not merge; discard the worktree and re-dispatch" >&2 - echo " $TASK_ID with a Feedback block that addresses the reason (.agentic/state/stuck/$TASK_ID.$ATTEMPT), or re-plan." >&2 + if [ "${AGENT_ROLE:-}" = planner ]; then + echo " The plan is not approved. Supervisor: read the reason ($AGENTIC_STATE/stuck/$TASK_ID.$ATTEMPT), then" >&2 + echo " re-dispatch the planner with a Feedback block that addresses it (fix the plan defect it names, or" >&2 + echo " say which changes already shipped), or fix the artifact out of band and run gate-stage2-complete." >&2 + else + echo " This attempt is not a pass. Supervisor: do not merge; discard the worktree and re-dispatch" >&2 + echo " $TASK_ID with a Feedback block that addresses the reason ($AGENTIC_STATE/stuck/$TASK_ID.$ATTEMPT), or re-plan." >&2 + fi return 0 } diff --git a/plugin/bin/gate-stage2-complete b/plugin/bin/gate-stage2-complete index f70594f1..f118d0d3 100755 --- a/plugin/bin/gate-stage2-complete +++ b/plugin/bin/gate-stage2-complete @@ -5,10 +5,14 @@ set -uo pipefail BIN_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; export PATH="$BIN_DIR:$PATH" # md-db shim -> real binary GATE_NAME="gate-stage2-complete" +# A direct call (the supervisor's own check, bin/selfcheck) is logged as a self-check; only a +# host SubagentStop payload makes a verdict. Decided before _gatelib.sh reads the payload. +[ -t 0 ] && export AGENTIC_SELFCHECK=1 # shellcheck source=/dev/null -. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/_failclosed.sh" # a crash blocks, never allows +. "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/_gatelib.sh" # fail-closed + verdict log + stuck release HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" : "${CLAUDE_PLUGIN_ROOT:=$(cd "$HERE/.." && pwd)}" +[ -n "$GATE_PAYLOAD" ] || export AGENTIC_SELFCHECK=1 sprint_dir="${1:-${SPRINT_DIR:-}}" if [ -z "$sprint_dir" ]; then @@ -17,11 +21,19 @@ fi if [ -z "$sprint_dir" ] || [ ! -d "$sprint_dir" ]; then echo "WARN[$GATE_NAME]: no sprint dir found; stage-2 check skipped (weaker)" >&2; exit 0 fi +# The planner has no task contract: its stuck key is the sprint it plans and the host's agent +# id (live e2e run 19: one planner was blocked 9 times on one unchanged reason, uncounted). +# A re-dispatch is a new agent id, so it starts the count over. +if [ -z "${TASK_ID:-}" ] && [ -n "$GATE_PAYLOAD" ]; then + _aid="$(printf '%s' "$GATE_PAYLOAD" | sed -nE 's/.*"agent_id"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' | head -1)" + if [ -n "$_aid" ]; then + export TASK_ID="plan-$(basename "$sprint_dir")" ATTEMPT="${ATTEMPT:-$(printf '%s' "$_aid" | tr -c 'A-Za-z0-9_-' '_')}" + fi +fi # 1) No TBW placeholders anywhere. if grep -rl 'TBW' "$sprint_dir" >/dev/null 2>&1; then - echo "BLOCK[$GATE_NAME]: TBW remains in $sprint_dir (partial Stage-2 forbidden)" >&2 - exit 2 + fail "TBW remains in $sprint_dir (partial Stage-2 forbidden)" fi # 2) Every SN-NN story in stories.md has a dir with tasks.md + validate.md + plan.md. @@ -33,13 +45,12 @@ if [ -f "$stories" ]; then lc="$(echo "$id" | tr 'A-Z' 'a-z')" # s1-01 dir="$(find "$sprint_dir" -maxdepth 1 -type d -name "${lc}-*" | head -1)" if [ -z "$dir" ]; then - echo "BLOCK[$GATE_NAME]: no story dir for $id: expected $sprint_dir/${lc}-/ (lowercase, e.g. ${lc}-count-words/) holding tasks.md, validate.md and plan.md" >&2 other="$(find "$sprint_dir" -maxdepth 1 -type d -iname "${lc}*" | head -1)" - [ -n "$other" ] && echo " found $other: rename it, e.g. git mv '$other' '$sprint_dir/${lc}-'" >&2 - exit 2 + fail "no story dir for $id: expected $sprint_dir/${lc}-/ (lowercase, e.g. ${lc}-count-words/) holding tasks.md, validate.md and plan.md${other:+ + found $other: rename it, e.g. git mv '$other' '$sprint_dir/${lc}-'}" fi for f in tasks.md validate.md plan.md; do - [ -f "$dir/$f" ] || { echo "BLOCK[$GATE_NAME]: $id missing $f" >&2; exit 2; } + [ -f "$dir/$f" ] || fail "$id missing $f" done done else @@ -56,32 +67,26 @@ if [ -n "$this_n" ]; then -exec grep -hoE '\bS[0-9]+-[0-9]+\b' {} + 2>/dev/null \ | sed -E 's/^S([0-9]+)-.*/\1/' | sort -un | awk -v n="$this_n" '$1>n' | head -1)" if [ -n "$later" ]; then - echo "BLOCK[$GATE_NAME]: sprint $this_n references story IDs from later sprint $later —" \ - "a sprint must be self-contained (context is cleared between sprints). Cut the" \ - "dependency or move the story into this sprint." >&2 - exit 2 + fail "sprint $this_n references story IDs from later sprint $later — a sprint must be self-contained (context is cleared between sprints). Cut the dependency or move the story into this sprint." fi spill="$(find "$sprint_dir" -name '*.md' ! -name stories.md ! -name init.md ! -name output.md \ -exec grep -lEi '(continue|continued|finish|finished|complete|completed|defer|deferred|carry|carried|spill|pick(ed)? up)[a-z]* (it |this |the rest )?(in|into|to|over to|during) (the )?(next|later|following|future|subsequent) sprint|sprint ?(n ?\+ ?1|'"$((this_n+1))"')\b' {} + 2>/dev/null | head -1)" if [ -n "$spill" ]; then - echo "BLOCK[$GATE_NAME]: $spill defers work into a later sprint — every task must" \ - "finish inside sprint $this_n. Cut the story smaller; list the remainder under" \ - "stories.md 'Out of scope'." >&2 - exit 2 + fail "$spill defers work into a later sprint — every task must finish inside sprint $this_n. Cut the story smaller; list the remainder under stories.md 'Out of scope'." fi fi # 4) Identity + referential integrity (ROADMAP §4.5): issue canonical ids for every story # and task alias, check the structured references between artifacts, freeze the map. "$BIN_DIR/ids" freeze "$sprint_dir" \ - || { echo "BLOCK[$GATE_NAME]: broken cross-artifact reference in $sprint_dir (see above)" >&2; exit 2; } + || fail "broken cross-artifact reference in $sprint_dir (see above)" # 5) Semantic change targets (ROADMAP §4.6), where the planner wrote them: each target's # task, operation, path and symbol must hold against tasks.md and the real tree. for t in "$sprint_dir"/s*-*-*/targets.json; do [ -f "$t" ] || continue "$BIN_DIR/targets" check "$(dirname "$t")" \ - || { echo "BLOCK[$GATE_NAME]: invalid change targets in $t (see above)" >&2; exit 2; } + || fail "invalid change targets in $t (see above)" done # 6) Structural validation via md-db (fallback to frontmatter check). @@ -91,7 +96,7 @@ if "$BIN_DIR/ensure-tools" --resolve md-db >/dev/null 2>&1; then find "$sprint_dir" -type f \( -name stories.md -o -name tasks.md -o -name validate.md \ -o -name plan.md -o -name plan-ready.md \) \ | md-db validate --stdin-list --schema "${CLAUDE_PLUGIN_ROOT}/schemas/planning-artifacts.kdl" \ - || { echo "BLOCK[$GATE_NAME]: md-db rejected $sprint_dir" >&2; exit 2; } + || fail "md-db rejected $sprint_dir" else echo "WARN[$GATE_NAME]: md-db absent; structural validation limited to dir/frontmatter checks" >&2 fi diff --git a/plugin/bin/targets b/plugin/bin/targets index 0e6ac165..007e1ce1 100755 --- a/plugin/bin/targets +++ b/plugin/bin/targets @@ -245,7 +245,10 @@ def problems(sdir, targets, root, doc=None): p.append("%s: create needs planned_symbol" % where) if t.get("symbol"): p.append("%s: create names a planned_symbol, not an existing symbol" % where) - if exists: + # A create whose file now exists AND defines its planned_symbol is realized (its task + # merged; a mid-sprint re-plan re-checks the whole plan), not a defect. + if exists and (not t.get("planned_symbol") + or locate(root, path, t["planned_symbol"])[0] is None): p.append("%s: create targets %s, which already exists (use modify/extend)" % (where, path)) elif not exists and path not in planned: p.append("%s: %s targets %s, which is neither in the tree nor planned" % (where, op, path)) @@ -259,6 +262,11 @@ def problems(sdir, targets, root, doc=None): def resolve(t, root): + if t.get("operation") == "create" and t.get("planned_symbol") and os.path.exists(os.path.join(root, t["path"])): + line, be = locate(root, t["path"], t["planned_symbol"]) + if line is not None: # realized create: the planned file and symbol exist now + return "%s %s %s:%s %s [%s] — %s" % (t["change_ref"], t["operation"], t["path"], line, + t["planned_symbol"], be, t.get("reason", "")) if t.get("operation") == "create" or not os.path.exists(os.path.join(root, t["path"])): return "%s %s %s %s (planned, shadow) — %s" % (t["change_ref"], t["operation"], t["path"], t.get("planned_symbol", ""), t.get("reason", "")) diff --git a/plugin/pipeline/planning/02-planner/persona.md b/plugin/pipeline/planning/02-planner/persona.md index c746e445..80977af5 100644 --- a/plugin/pipeline/planning/02-planner/persona.md +++ b/plugin/pipeline/planning/02-planner/persona.md @@ -49,6 +49,14 @@ hard; 150k / 20 min soft — see `docs/agents/defaults.md`). A worker still runn the hard limit is STOPPED by the hook and the task comes back to you to split — never retried. So size each task so one worker can do its RED or its GREEN well inside the soft limit: a handful of tests, one or two files, one behaviour. When in doubt, split. +A later task's RED tests must fail against what the EARLIER tasks leave on main, not only +against the empty tree: `gate-red-verify` requires every new test to fail by assertion, so +a task whose planned tests already pass against the previous task's skeleton (a placeholder +that maps every non-success to one error variant, a default where a `todo!()` was) cannot be +RED and costs a mid-sprint re-plan (live run 19: three of T2's tests passed against T1's +placeholder). Plan each later task's tests around behaviour the earlier task's contract does +not provide, and state in the earlier task's summary what its skeleton returns for inputs +outside its scope, so the later tests can assert something it gets wrong. If defaults.md sets `AGENTIC_TIME_MODE=auto`, propose ONE stable task duration for the project (with a min and a max) to the supervisor, who records it with `timebox propose`; ask for a revision only with evidence (a stats.md, an event id). diff --git a/plugin/skills/aloop/SKILL.md b/plugin/skills/aloop/SKILL.md index 23b9b4db..0b4ab8a2 100644 --- a/plugin/skills/aloop/SKILL.md +++ b/plugin/skills/aloop/SKILL.md @@ -397,7 +397,7 @@ in a legacy project — the gates read either): .aladdin/task.env optional copy of the contract (Codex/OpenCode, older sprints); it must match the contract when both exist .aladdin/budget-exceeded marker the time-box hook writes at a HARD limit -main tree: .aladdin/state/stuck/. a gate released a worker that repeated +main tree: .aladdin/state/stuck/. a gate released a worker (or, as plan-sprintN., a planner) that repeated one block 3 times (unverified; `budget watch` reports it once) STORY_DIR is the ABSOLUTE path to sN-NN-/ (the comms dir). .aladdin/scaffold-symbols scaffolder-written production-symbol list (scaffold gate) diff --git a/scripts/test/planner-stuck.test.py b/scripts/test/planner-stuck.test.py new file mode 100644 index 00000000..9fb3f8f4 --- /dev/null +++ b/scripts/test/planner-stuck.test.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""The planner's stop gate (gate-stage2-complete on SubagentStop) logs its verdicts to +gates.jsonl like every other gate, and the stuck release covers it: the same block three +times in a row releases the planner's stop UNVERIFIED with a stuck marker the supervisor +acts on. Live e2e run 19: a re-planning planner was blocked 9 times on one unchanged reason, +none of them counted, and only a second dispatch ended it. + + python3 scripts/test/planner-stuck.test.py +""" +import json +import os +import subprocess +import tempfile + +BIN = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "plugin", "bin")) +GATE = os.path.join(BIN, "gate-stage2-complete") +T = tempfile.mkdtemp(prefix="aloop-planner-stuck-") +ENV = {k: v for k, v in os.environ.items() if k not in ("SKIP_HOOKS", "AGENTIC_SELFCHECK", "AGENTIC_STUCK_BLOCKS")} +ENV["HOME"] = os.path.join(T, "home") +ENV["PATH"] = "/usr/bin:/bin" # no md-db: the structural step falls back (fixture is minimal) +ENV.pop("CLAUDE_PLUGIN_DATA", None) +SP = os.path.join(T, "docs", "agents", "sprint1") +LOG = os.path.join(T, ".aladdin", "logs", "gates.jsonl") +EVENTS = os.path.join(T, ".aladdin", "logs", "events.jsonl") +n = 0 + + +def ok(msg): + global n + n += 1 + print("ok - " + msg) + + +def write(rel, text): + p = os.path.join(T, rel) + os.makedirs(os.path.dirname(p), exist_ok=True) + open(p, "w").write(text) + + +def hook(agent_id="a1", **env): + p = {"session_id": "s1", "cwd": T, "agent_id": agent_id, "agent_type": "aloop:planner", "hook_event_name": "SubagentStop"} + return subprocess.run([GATE, SP], input=json.dumps(p), cwd=T, env=dict(ENV, **env), capture_output=True, text=True) + + +def rows(): + return [json.loads(l) for l in open(LOG)] if os.path.exists(LOG) else [] + + +subprocess.run(["git", "init", "-q"], cwd=T, check=True) +# a plan defect the planner keeps not fixing: stories.md names S1-01 but there is no story dir +write("docs/agents/sprint1/stories.md", "---\ntype: stories\nsprint: 1\n---\n- S1-01 export\n") + +rcs = [hook().returncode for _ in range(2)] +assert rcs == [2, 2], rcs +r = hook() +assert r.returncode == 0 and "STUCK" in r.stderr and "NOT verified" in r.stderr, r +marker_dir = os.path.join(T, ".aladdin", "state", "stuck") +markers = os.listdir(marker_dir) +assert len(markers) == 1 and markers[0].endswith(".a1"), markers +assert "no story dir" in open(os.path.join(marker_dir, markers[0])).read() +ok("the third identical planner block releases its stop unverified, with a stuck marker") + +got = [x for x in rows() if x["gate"] == "gate-stage2-complete"] +assert [x["exit"] for x in got] == [2, 2, 0] and all(x["role"] == "planner" for x in got), got +assert got[2].get("released") == "stuck" and got[0]["reason"] == got[1]["reason"] != "", got +ev = [json.loads(l) for l in open(EVENTS)] +assert [e["event"] for e in ev if e["event"].startswith("gate.")] == ["gate.failed"] * 3, [e["event"] for e in ev] +ok("every planner verdict is in gates.jsonl (role planner, same reason hash) and the event stream") + +r = hook(agent_id="a2") +assert r.returncode == 2 and "STUCK" not in r.stderr, r +ok("a re-dispatched planner (new agent id) starts the count over") + +# the supervisor's self-check (bin/selfcheck) and a direct call never release, and a direct +# call is logged as a self-check, not a verdict +for _ in range(3): + r = hook(agent_id="a3", AGENTIC_SELFCHECK="1") + assert r.returncode == 2 and "STUCK" not in r.stderr, r +r = subprocess.run([GATE, SP], cwd=T, env=ENV, capture_output=True, text=True, stdin=subprocess.DEVNULL) +assert r.returncode == 2 and "STUCK" not in r.stderr, r +last = rows()[-1] +assert last["selfcheck"] is True and last["role"] == "", last +assert len([e for e in [json.loads(l) for l in open(EVENTS)] if e["event"].startswith("gate.")]) == 4, "a self-check is not an event" +ok("a self-check never releases and is logged as such; a direct call emits no gate event") + +# a sound plan passes and is logged as a pass +write("docs/agents/sprint1/s1-01-export/tasks.md", "---\ntype: tasks\nstory: S1-01\n---\n## T1 — a\n") +write("docs/agents/sprint1/s1-01-export/validate.md", "---\ntype: validate\nstory: S1-01\n---\n## T1\n") +write("docs/agents/sprint1/s1-01-export/plan.md", "---\ntype: plan\nstory: S1-01\nscope: tests only\n---\n") +r = hook(agent_id="a4") +assert r.returncode == 0 and "Stage-2 complete" in r.stderr, r +assert rows()[-1]["exit"] == 0 and rows()[-1]["selfcheck"] is False +ok("a complete plan passes and is logged as a pass") + +print("\n%d checks passed" % n) diff --git a/scripts/test/semantic-targets.test.py b/scripts/test/semantic-targets.test.py index 3458f8ec..a976cdee 100644 --- a/scripts/test/semantic-targets.test.py +++ b/scripts/test/semantic-targets.test.py @@ -108,4 +108,20 @@ def targets(*ts): assert r.returncode == 0, r.stderr ok("unknown symbol/task, create-over-existing, ghost path, bad op, escaping path, duplicate ref → blocked; gate runs it") +# 6) a mid-sprint re-plan re-checks changes that already shipped (live e2e run 19: T1's +# `create tests/parse.rs` merged, then the T2 re-plan's planner was blocked 9 times with +# "already exists" for a change it was told not to touch). A create whose file now exists +# AND defines its planned_symbol is realized, not wrong; one whose file exists without the +# symbol is still a plan defect. +targets(C1, C2) +write("src/export/csv_writer.py", "import csv\n\n\ndef write_csv(rows):\n return rows\n") +r = run(TG, "check", SD) +assert r.returncode == 0, r.stderr +assert "src/export/csv_writer.py:4 write_csv" in run(TG, "target", "T1", SD).stdout +write("src/export/csv_writer.py", "import csv\n\n\ndef other():\n return 1\n") +r = run(TG, "check", SD) +assert r.returncode == 2 and "already exists" in r.stderr, r.stderr +os.remove(os.path.join(T, "src", "export", "csv_writer.py")) +ok("a create whose file already defines its planned_symbol is realized (passes); without the symbol it is still blocked") + print("\n%d checks passed" % PASS[0])