diff --git a/CHANGELOG.md b/CHANGELOG.md index e67b80f7..e30b7676 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,13 +23,14 @@ tag in lockstep. Tag releases as `vMAJOR.MINOR.PATCH`. ## [Unreleased] ### Added +- Plan approval is a gate (ROADMAP M0.9): `gate-dispatch` starts no execution role (RED, SCAFFOLD, GREEN, structural review, final gate) of a sprint until the human approved that sprint's plan as it is now. `events authority --sprint N` exits 3 with the line to type, `approve SN ` (reviewed, the code naming the sha256 of the sprint's plan files) or `autonomous SN ` (autonomy for that sprint, re-plans included, the code naming the authority record); the task contract's `STORY_DIR` and task must be a live story and task of that plan's frozen `ids.json`; the line must be among the human's captured prompts and typed after the sprint's last decision (M9.17's mechanism). A changed plan, a re-plan in reviewed mode, a roll-back to an old line, another sprint's line, a negated line and a hand-edited or emitted record all block (`plan.approved` and `human.approval` cannot be `events emit`ted); an approved autonomous mission grants its own sprints autonomy with no line. `events approval SPRINT|TASK_ID` is the check. Codex's `spawn_agent` (`agent_type`, `message`) and OpenCode's `task` now reach `gate-dispatch` too, and `claude -p`, `codex exec` and `opencode run` from a tool call are blocked in every aloop project, not only where a mission is set. `e2e-live.sh` pre-approves with an `autonomous S1 ` line in its prompt. Reason: the north star allows no human help beyond approval, and the approval was a playbook rule a supervisor could skip. A 4-lens adversarial review found 9 defects: 7 fixed with a check red on the first head (cross-sprint or unplanned `STORY_DIR`, a retyped line kept stale, mission autonomy over a non-mission sprint, `transcripts prune` dropping the prompts grants cite, `codex plugin add` refused, a code past column 200, a crash on a malformed run-log line), 2 in the playbook (intake reuses a mission's handed-off intent; a reviewed re-plan waits for the human's new line). `transcripts prune` now keeps the human's prompts. Test: `plan-approval.test.py` (20 checks, red on master), plus the host suites. - Core agent principles and the one-way / two-way door rule (ROADMAP §4.12, M9.30): seven core principles from Amazon's Leadership Principles, the door rule first, go to every aloop agent at session start (`aloop mission principles show --core`). A two-way door (a branch, a local edit, a test, a draft PR) is decided, not asked. A one-way door (`aloop mission doors list`: a push or merge to the default branch, a force-push, a release, a deploy, a message sent outside, a secret, dropped data, …) is stopped by a PreToolUse gate with `ASK[door] ` until the human records an authorization in their own terminal (`aloop mission doors authorize ID --by NAME --reason TEXT [--until DATE] [--once DIGEST]`, a hash-chained ledger row); a wall (switching a gate off, forging a human record) is never crossed. While a run is live, a question to the human must name a door the gate stopped and nobody authorized. Reason: Adeel's request that agents decide two-way doors themselves and ask only at a one-way door not already authorized. Test: `mission-doors.test.py`. Hardened by an adversarial review (15 findings, each a test): the gate reads Bash as the shell does (comments, line continuations, heredoc bodies, `xargs`, `find -exec`, `echo … | sh`), a branch condition reads the directory the command acts on (`git -C`, `cd`), settings are guarded wherever they live, dry runs and `command -v` are two-way, the newest decision by time counts and a revoke holds on every branch, a once-grant is crossed once under a lock, a broken ledger is named, and `doors authorize` refuses an agent's shell. - DeepSeek Harness (dsh) host (ROADMAP §4.9): `aloop install dsh` (alias `deepseek`; `--project P` or `--global`) renders a `dsh --profile aloop` profile in `$DSH_HOME` and installs the skills. Its native plugin (`plugin/hosts/dsh/aloop.mjs`) runs the same gates as Claude Code on dsh's own events: a deny before a tool runs, a block after an invalid artifact write, and a stop gate that steers a role back up to 3 times before the supervisor is told it is BLOCKED (or STUCK, released unverified). Roles are agent presets on two subagent tools, one per model route (`deepseek-v4-pro` for planning, `deepseek-flash` for work by default; `MODEL_PLANNING_DSH` / `MODEL_WORKER_DSH` override). A writer's `aloop bind` moves its working directory into its worktree, and `host-adapter` confines its commands, edits and `working_directory` there. Usage is recorded Claude-shaped per role, so budgets, the ledger and `run-summary` work unchanged. `make e2e-live HOST=dsh` drives it live and exits 2 with the fix when no `DEEPSEEK_API_KEY` is set. Reason: DeepSeek's own harness is the cheapest route to a strong model. The profile records the project it serves (or `--global`), so another project's `aloop-init` never re-renders it, and gates get the worker shell's environment (no API key). The mission layer's six roles run on dsh too: presets on their route group's subagent tool, `gate-mission-scope` on every write and command, and `gate-mission-artifact` at each role's start and stop; the mission skill installs as `aloop-mission`. A second review (3 lenses; 11 confirmed findings, each fixed with a test) closed: a working directory that vanished (dsh's tools move it back to the main tree, so the plugin judges `ensure()`'s directory and `host-adapter` refuses to run from a missing one), gate switches from the project's `.env` (dsh loads it; `SKIP_HOOKS`, `GATE_RUN_TESTS`, `REPO_DIR`, `AGENTIC_*` from it never reach a gate), an interrupted Stop that dropped the sprint-close notice, and the shared profile: its owner is the main tree, an older unrecorded profile is claimed only by the project that installed it, and a project it does not serve is told so by `install status`, `aloop-init` and the session itself. Tests: `dsh-plugin.test.mjs` (40 checks, emulated), `dsh-runtime.test.mjs` (32 checks on the real pinned dsh 0.2.1-rc.2 with a scripted model; the CI hosts job installs it) and `dsh-install.test.py` (9). - Brand kit and repo front page: `docs/brand/` holds the mark (an **a** whose bowl is a red-to-green loop passing a gold gate, with a 16 px cut), lockups, light and dark README banners, favicons, app icons, the site's OG card and the GitHub social preview, all generated by `docs/brand/gen_brand.py` from one palette with WCAG checks (rules in `docs/brand/README.md`). The README leads with the mission layer, the agent principles and the door rule, the supported hosts and the measured demo runs; the site carries the favicon and Open Graph/Twitter card metadata; `SECURITY.md` and bug/feature issue forms are new. - A mission's gap lists count only as `mission evaluate` computed them (ROADMAP §4.12, M9.27): `evaluate` records `eval.completed` in the committed ledger, and `mission tick`, `evaluate check` and `goal` take the newest eval whose content that record covers, with a matching seal, in the ledger's order. An eval file written by hand, or edited (or re-stamped) after it was recorded, no longer sends the loop to `RESEARCH` as "goal met" or makes `goal derive` refuse what tick handed out, a clock that is behind no longer reorders them, and a fresh checkout derives and closes goals from the evals it committed. An eval or state named as journey or baseline evidence needs its record too. Tests: `mission-tick` check 32, `mission-journeys`. - A mission's stop at a spend cap holds on a fresh checkout (ROADMAP §4.12, M9.24): the first `STOP_BUDGET` tick records a `mission.budget_exhausted` ledger row for the mission's content (once per content), and `mission tick` stops on it whatever the checkout's token ledger says, until a raised cap changes the content. - Lifting a mission block is the human's own words (ROADMAP §4.12, M9.51): `aloop mission tick --force --by` now asks (exit 3) for the human's typed `lift ` line, the code bound to this occurrence of that block, and records a `mission.lifted` ledger row, so `--by` alone, a lift only the run log has (or a replayed one), an old line or a line typed for an earlier block lift nothing, a lift of 3 failed goals reaches only those goals whatever `--now` says, and a fresh checkout keeps a lifted block lifted. `/aloop:mission` counts a lift among the typed grants it relays. A lift recorded before this (run data only) no longer counts. -- The mission layer's six fixed roles (ROADMAP §4.12, M9.9): `market-researcher`, `product-tester`, `state-assessor`, `evaluator`, `mission-planner` and `ethics-reviewer`, each a persona with a four-case eval suite, a model route (the four that judge on the planning route, the two that measure on the worker route), hook matchers on Claude Code, Codex, OpenCode and dsh, and Codex/OpenCode agents and dsh presets from `aloop install` (which also renders the mission skill for OpenCode as `aloop-mission` once it ships). `plugin/mission/roles.json` names the paths each role writes. `gate-mission-scope` (PreToolUse) is the role path guard: a mission role never writes source, mission.json or another role's dir, never commits and never runs a human's approval; a builder never writes `docs/agents/mission/` or runs a writing `mission` command; the supervisor never hand-writes a role's artifact. No one hand-writes `docs/agents/mission/ledger.jsonl` or the captured prompts a grant reads (`/transcripts/`), runs a hook's `transcripts prompt|record|…`, or starts a host session (`claude -p`, `codex exec`, `opencode run`, `dsh `) from a tool call where a mission is set (its prompt would count as the human's words, M9.17), and no dispatched agent runs `mission baseline restore`, `events authority` or an `events emit` of a human event. `gate-mission-artifact` records what exists when a role starts and, at its stop, requires an artifact in its own paths that passes the core contract and its area's check, refuses a deleted artifact, a change to another role's or a ledger that no longer verifies, and records `artifact.created|updated` as provenance. A mission write never arms the sprint lock. The scope gate reads a Bash command as the shell would (`_shellread.py`: quotes, comments, line continuations, heredocs, wrappers such as `timeout` and `env`, `bash -c`, `eval`, a script run by an interpreter, variables and `$(mktemp)`). Each area's check runs once per artifact with its id or subject, an ethics hard line is the reviewer's finding, not a defect, and a derived goal whose only blocks are its pending ethics review waits on the Ethics Reviewer, not on the planner. Test: `mission-roles.test.py` (33 checks, with each role run through the real journeys, baseline, assess, evaluate and ethics, goal, research and judge areas), `mission-scope-bash.test.py` (225 commands), `opencode-plugin.test.mjs`. +- The mission layer's six fixed roles (ROADMAP §4.12, M9.9): `market-researcher`, `product-tester`, `state-assessor`, `evaluator`, `mission-planner` and `ethics-reviewer`, each a persona with a four-case eval suite, a model route (the four that judge on the planning route, the two that measure on the worker route), hook matchers on Claude Code, Codex, OpenCode and dsh, and Codex/OpenCode agents and dsh presets from `aloop install` (which also renders the mission skill for OpenCode as `aloop-mission` once it ships). `plugin/mission/roles.json` names the paths each role writes. `gate-mission-scope` (PreToolUse) is the role path guard: a mission role never writes source, mission.json or another role's dir, never commits and never runs a human's approval; a builder never writes `docs/agents/mission/` or runs a writing `mission` command; the supervisor never hand-writes a role's artifact. No one hand-writes `docs/agents/mission/ledger.jsonl` or the captured prompts a grant reads (`/transcripts/`), runs a hook's `transcripts prompt|record|…`, or starts a host session (`claude -p`, `codex exec`, `opencode run`, `dsh `) from a tool call (in every aloop project since M0.9; its prompt would count as the human's words, M9.17), and no dispatched agent runs `mission baseline restore`, `events authority` or an `events emit` of a human event. `gate-mission-artifact` records what exists when a role starts and, at its stop, requires an artifact in its own paths that passes the core contract and its area's check, refuses a deleted artifact, a change to another role's or a ledger that no longer verifies, and records `artifact.created|updated` as provenance. A mission write never arms the sprint lock. The scope gate reads a Bash command as the shell would (`_shellread.py`: quotes, comments, line continuations, heredocs, wrappers such as `timeout` and `env`, `bash -c`, `eval`, a script run by an interpreter, variables and `$(mktemp)`). Each area's check runs once per artifact with its id or subject, an ethics hard line is the reviewer's finding, not a defect, and a derived goal whose only blocks are its pending ethics review waits on the Ethics Reviewer, not on the planner. Test: `mission-roles.test.py` (33 checks, with each role run through the real journeys, baseline, assess, evaluate and ethics, goal, research and judge areas), `mission-scope-bash.test.py` (225 commands), `opencode-plugin.test.mjs`. - The mission loop end to end, offline (ROADMAP §4.12, M9.13): `mission-e2e.test.py` drives `mission tick` from a new mission through research, a journey, a confirmed baseline, a gap list, a goal, its intents and one Aladdin sprint per intent to GOAL MET and the next raise of the bar, with zero tokens and each step done through the CLI the way its role or the human does it. A fresh clone hands out the same action. Ethics reviews and hard lines are now ledger rows (M9.24), so a clone no longer asks for every review again or forgets a hard line; the ledger row wins over its run-log copy, and a broken ledger makes every ethics verdict `broken`. Tests: `mission-e2e.test.py`, `mission-ethics.test.py`. - A mission baseline binds the mission's direction (ROADMAP §4.12, M9.25): `direction_sha256` covers the mission id, statement, mode and constraints, so raising a budget cap or changing the cadence (and approving it) keeps the confirmed baseline, while a new direction still asks for a new version. Reason: M9.8's budget test, a raised cap asked for a new baseline though "best" had not changed. Test: `mission-baseline.test.py`. - Mission approvals are the human's own words (ROADMAP §4.12, M9.17): `mission approve`, `baseline confirm|restore`, `journeys approve`, `mission ethics consent` and `mission telemetry consent` record only when a prompt the `UserPromptSubmit` hook captured has a line such as `approve msn_… 3f2a9c1b` (the verb and the first 8 hex of the content's sha256); until then they ask (exit 3) with that line. `--by` alone, a negated line, another code, a line older than a later decision about the subject (for a baseline, any version's confirmation) and a hand-appended ledger row without such a line grant nothing. Reason: an approval was only as strong as `--by`, so a role could approve its own mission change. Tests: `mission-core.test.py`, `mission-baseline.test.py`. diff --git a/Makefile b/Makefile index 64cc6636..de9ae194 100644 --- a/Makefile +++ b/Makefile @@ -74,7 +74,7 @@ shellcheck: ## Lint gate scripts (skipped with a warning if shellcheck is absent pycheck: ## Byte-compile the Python hook scripts @python3 -m py_compile plugin/bin/budget plugin/bin/stats plugin/bin/aloop-init plugin/bin/gate-commit-author plugin/bin/_paths.py \ plugin/bin/_usage.py plugin/bin/_events.py plugin/bin/events plugin/bin/intent plugin/bin/lessons plugin/bin/ids plugin/bin/targets plugin/bin/impact plugin/bin/timebox plugin/bin/sweep plugin/bin/capabilities plugin/bin/models plugin/bin/_routes.py plugin/bin/host plugin/bin/_host.py plugin/bin/config plugin/bin/_config.py plugin/bin/layout plugin/bin/_lsp.py scripts/test/fixtures/fake-lsp.py plugin/bin/_timebox.py plugin/bin/host-adapter plugin/bin/install \ - plugin/bin/mission plugin/bin/_mission.py plugin/bin/_mission_roles.py plugin/bin/_shellread.py plugin/bin/gate-mission-scope plugin/bin/gate-mission-artifact $$(ls plugin/mission/*.py 2>/dev/null) \ + plugin/bin/_approval.py plugin/bin/mission plugin/bin/_mission.py plugin/bin/_mission_roles.py plugin/bin/_shellread.py plugin/bin/gate-mission-scope plugin/bin/gate-mission-artifact $$(ls plugin/mission/*.py 2>/dev/null) \ && rm -rf plugin/bin/__pycache__ plugin/mission/__pycache__ && echo "python ok" .PHONY: test-hosts @@ -124,6 +124,7 @@ test-hosts: ## Budget/worktree regression + Codex hooks emulation + OpenCode and python3 scripts/test/planner-stuck.test.py python3 scripts/test/hook-matchers.test.py python3 scripts/test/dispatch.test.py + python3 scripts/test/plan-approval.test.py python3 scripts/test/log-execution.test.py python3 scripts/test/ensure-tools.test.py python3 scripts/test/fail-closed.test.py diff --git a/README.md b/README.md index 6af7a9c3..4dd5c6ec 100644 --- a/README.md +++ b/README.md @@ -133,8 +133,9 @@ its tests and the resolved change targets (`targets context`), never the whole r Determinism is structural, not vibes. Hooks enforce what the model cannot talk its way past: - the supervisor cannot write production source (`gate-supervisor-scope`), commit on main during a - sprint, or dispatch with its backends missing (`gate-tooling`) or on a model the project did not - pick (`gate-dispatch`); + sprint, or dispatch with its backends missing (`gate-tooling`), on a model the project did not + pick, or before the human approved the sprint's plan, or granted it autonomy, in a line they typed + (`gate-dispatch`); - a worker cannot leave its worktree, touch files outside its task, or pass a stop whose gate failed; - a gate that crashes **blocks** (`_failclosed.sh`), never a silent pass, and never a false block when a backend is absent (it degrades to a flagged, weaker check); @@ -330,7 +331,7 @@ structural, not luck: blocking it from doing the context-heavy work itself. Live runs: `make smoke-live YES=1` (hook wiring, ~$0.004) and `make e2e-live YES=1` (the whole -loop, ~$1; each run writes `summary.json` and a row for [docs/evidence/](docs/evidence/README.md)). Offline: `make ci`, which runs Rust fmt/clippy/tests, shellcheck, 54 Python/Node suites plus every `mission-*.test.py`, +loop, ~$1; each run writes `summary.json` and a row for [docs/evidence/](docs/evidence/README.md)). Offline: `make ci`, which runs Rust fmt/clippy/tests, shellcheck, 55 Python/Node suites plus every `mission-*.test.py`, the gate conformance fixtures (`make conformance`) and eval-suite validation. Every ROADMAP requirement is tracked with its test in [docs/TRACKING.md](docs/TRACKING.md). diff --git a/docs/OVERVIEW.md b/docs/OVERVIEW.md index a9721655..d728226c 100644 --- a/docs/OVERVIEW.md +++ b/docs/OVERVIEW.md @@ -47,7 +47,10 @@ The model can ignore a skill; it cannot ignore an exit code. - `standards` produces a cited coding standard; - `planner` writes the sprint contract and, per story, the semantic plan `targets.json` (tasks, tests, change targets) from which `tasks.md` / `validate.md` / `plan.md` are rendered. - The supervisor then **stops for approval**. + The supervisor then **stops for approval**, and that stop is a gate: `gate-dispatch` starts no + worker until the human types the `approve SN ` line naming this exact plan, and a changed plan + needs a new line; or they grant the sprint autonomy (`autonomous SN `, or an approved + autonomous mission), which covers its re-plans (M0.9). 3. **Execution** — human absent. For each task, a worker runs in its own git worktree: - **RED** writes tests that must fail *by assertion* and touch no production code; - **SCAFFOLD** creates each planned symbol exactly once, as a stub; diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index f539e5d4..0d72ac53 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -17,6 +17,7 @@ original plan. |---|---|---|---| | **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 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). A second, parallel run 19 (the other thread's, on #29's run-18 fixes): **13/13, 15m24s, $1.01, 1 wake**, 0 plugin-source reads (first counted as 5: the planner's `md-db describe --schema "$SCH"` on the plugin's schemas, a legitimate use the counter now recognises), 3 host-run blocks: run 18's two classes (unbound worker, bare `output.md`) did not recur; the scaffolder wrote its `### Scaffold` report shape (`+ create fn crate::count_words @ src/lib.rs`) into `.aladdin/scaffold-symbols` and the gate read `create` as a symbol twice (fixed, conformance cases: markers, verbs, keywords and crate paths are skipped, the block names the file's shape); the structural reviewer was dispatched without a worktree and its self-check found no contract in the main tree (fixed, test-first: `budget hook` copies the contract into the main tree for an observed role and removes it at stop). The planner's `targets render` diff and `targets check` self-checks (7, fixed on retry) are its own loop. Run 20 (planner stuck release + RED rule): 12/12, **10m47s, 1 block, 0 re-plans, 0 stuck** (the planner's 5 stop verdicts are now in `gates.jsonl`), 36 supervisor turns, 2 plugin-source reads — but **$2.79**: the supervisor dispatched the planning roles on opus and the workers on sonnet although defaults.md said haiku for both and its own `aloop models resolve` call had printed `haiku` (opus $1.11 + sonnet $1.68; run 19 on haiku workers: $0.99). Fixed, test-first: `gate-dispatch` refuses a dispatch whose `model` is not the role's resolved one, or that passes none (reason: a per-dispatch model choice is a project setting the supervisor had no business re-deciding; the cheapest deterministic fix). Run 21 (model gate): 12/12, **8m17s, $0.66** (from $2.79; run 19: $0.99), 29 supervisor turns, 1 wake, 0 plugin-source reads, 3 blocks (two planner self-checks fixed on retry, one structural-review finding fixed on retry), 0 stuck: every dispatch went on haiku (haiku $0.10 + supervisor sonnet $0.56). The cost is now where the model table puts it; the next lever is the supervisor's own context (sonnet $0.56 of $0.66). Run 22 (wordfreq on master before the model gate, 361f8d7): **13/13, 16m18s, $1.14, 2 wakes, 0 plugin-source reads**, 3 logged blocks (all the planner's own stop-gate self-checks, fixed on retry), 0 re-plans, 0 stuck. One loop the gate log does not show: the final-gate persona grepped its own suppression list, failed the sprint on RED's `#![allow(dead_code)]` in `tests/common/mod.rs` (a shared test-helper module, the Rust idiom; the deterministic gate accepts it) and cost a second GREEN dispatch and a final-gate retry. Fixed: the persona names exactly `assert_no_suppression`'s patterns and defers to `selfcheck final-gate` (reason: models explore, gates decide; test: `suppression-contract.test.py`, eval case final-gate #4). Run 23 (model gate, second intent `wordfreq`): **13/13, 10m58s, $0.76, 0 blocks**, 24 supervisor turns, 4 wakes, 1 plugin-source read: both dependent stories planned, built and merged with no gate block for the first time (run 22 on the same intent without the gate: $1.14, 16m18s, 3 blocks). Run 24 (experiment: the same intent with a **haiku supervisor**, `e2e-live.sh --model haiku`): 10/13, 19m09s, $0.66, 51 supervisor turns (from 24), 6 blocks — no cheaper than sonnet (the turns doubled), and the supervisor put the whole sprint under `.aladdin/sprint1/`, the git-ignored run-data dir, so the three planning checks found no sprint; every gate passed it. Fixed, test-first: `gate-stage2-complete` and `gate-dispatch` refuse a sprint or `STORY_DIR` inside `.aladdin/`/`.agentic/` and name `docs/agents/sprintN/` (reason: the plan is the audit trail and must be where the layout commits it; tests: `planner-stuck.test.py`, `dispatch.test.py`). The supervisor stays on the strong route. Run 25 (wordfreq under the model gate, #40's head, a second sample of run 23's setup): **13/13, 16m13s, $0.98** (from $1.14; haiku $0.19 + supervisor sonnet $0.79), 3 wakes, 0 plugin-source reads, 5 blocks, 0 re-plans, and the final gate passed first time (the persona fix held). 4 of the 5 blocks were one GREEN worker: it tried the Write tool on the main tree's `output.md`, worktree isolation refused it, and the gate's "latest block is not from 'green-worker'" named no way out, so it stopped three times, hit the stuck release and needed a supervisor wake to append with `cat >>`. Fixed: that block now carries the same shell-heredoc instruction as the missing-block one (conformance case). Run 26 (the supervisor's playbook trimmed: the Codex/OpenCode notes, the budget re-plan route, review blind spots, the script list, transcripts and worktree hygiene moved to an on-demand `skills/aloop/reference.md`, SKILL.md 58k → 49k chars): 13/13, 16m01s, $0.95, 36 supervisor turns, 2 wakes, 1 plugin-source read, 7 blocks. The playbook load fell from 25.0k to 18.8k tokens, about 6k fewer tokens re-read on every supervisor turn, and the supervisor never needed the reference file; the run's cost was set by a RED loop instead (5 of 7 blocks): the supervisor's mandate allowed a `src/` skeleton, the gate made RED revert it, and the tests then called a symbol that no longer existed; the block said only "add mod-common shims", so the worker stopped three times and hit the stuck release. Fixed: the compile block names each missing symbol and its shim, e.g. `pub fn count_words(…) -> … { todo!() }` in `tests/common/mod.rs`, called through `mod common;` (conformance case). Run 27 (master with the trimmed playbook and the named-symbol RED block, wordfreq): **13/13, 9m54s, $0.70, 1 wake**, 33 supervisor turns, 1 plugin-source read, 3 blocks (the planner's own self-check, and two scaffolders self-checking before they committed, each fixed on retry), 0 stuck, 0 re-plans: the fastest and cheapest two-story run so far (haiku $0.12 + supervisor sonnet $0.59). All 3 of those blocks were the workers' own `selfcheck` catches, with 0 blocks at stop. `run-summary` now counts them as `selfcheck_blocks`, and the worker prompts give the finish order as block, commit, selfcheck. Run 28 (master after #47, wordfreq): 13/13, 13m14s, $1.15, 3 wakes, 4 blocks (2 self-check catches). The supervisor took the manual task-worktree route without copying the contract into the worktree, so RED's `aloop bind` failed and its stop blocked twice in the shared tree. Fixed: `gate-dispatch` copies and refreshes the contract in a task worktree on every dispatch (test: `dispatch.test.py`). Run 29 (master after #49, with `aloop budget contract`, wordfreq): 13/13, 12m55s, $0.91 (haiku $0.15 + supervisor sonnet $0.76), 1 wake, 0 plugin-source reads, **0 gate blocks**, 38 supervisor turns. The supervisor wrote every contract with `budget contract` (no heredocs), but spent 5 turns polling for the planners' files with `sleep` loops after dispatching intake and standards in the background, and the final gate's sign-off never reached the main tree: its Write was refused, it wrote a worktree copy the host discarded, its stop passed because `gate-final` never checked comms, and the supervisor wrote the final-gate block itself. Fixed: `gate-final` runs `validate_comms` for a final-gate worker under a contract (conformance cases), the persona says how to append, and SKILL.md runs planning roles in the foreground (two in one message) and forbids writing an agent's block. Run 30 (master after #50, wordfreq): 13/13, 11m27s, **$0.70** (haiku $0.15 + supervisor sonnet $0.54), **23 supervisor turns** (from 38), 2 wakes, 0 plugin-source reads, 4 blocks, all caught by the workers' own self-checks (0 at stop). Every planning role ran in the foreground with no polling, and the final gate appended its own sign-off block (its first self-check caught it missing; the new comms check working as meant). The never-write-an-agent's-block rule is now a gate too (`gate-supervisor-scope`, test: `supervisor-scope.test.py`; reason: run 29 broke the prose rule once). Run 31 (semver on master after #52): 12/12, 10m24s, $0.91 (haiku $0.12 + supervisor sonnet $0.79), 27 supervisor turns, 2 wakes, 1 plugin-source read, 5 blocks; the supervisor-scope gate never fired. 4 of the 5 blocks were one loop: T2's tests called only T1's finished `parse`, the scaffolder listed it, and the gate demanded a TODO panic in a body it had not touched, so it hit the stuck release and needed a second dispatch. Fixed: a listed symbol that existed at `BASE_REF` in an unchanged file needs no stub (conformance cases). Run 32 (semver on master after #53): 12/12, $0.90, 0 scaffold blocks (2 blocks, both self-check catches), but 23m30s wall for 11m of work: the supervisor set a 1200s `ScheduleWakeup` "heartbeat" when the host moved the planner to the background, and the headless session waited for it 12 minutes after the final gate. It also ran `task-worktree add --help`, which made a worktree named `--help`. Fixed: `gate-supervisor-scope` blocks the supervisor's `ScheduleWakeup` while a sprint is live, and `task-worktree` prints usage for `--help` and refuses a dash-led TASK_ID (tests). Run 33 (wordfreq on master after #54): 13/13, 12m20s, $0.84, 27 supervisor turns, 2 wakes, 0 plugin-source reads, 5 blocks (all self-check catches), no wakeup. Runs 31-33 each improvised the same RED-to-SCAFFOLD handoff on Claude Code (`task-worktree --help`, inspect the host worktree, `task-worktree add` on RED's branch, then SCAFFOLD/GREEN bound to it); SKILL.md Part B now states it (skill-layout test). Run 34 (semver on master after #55): 12/12, 10m23s, $0.74, 21 supervisor turns (27 in run 31), 2 wakes, 1 block (a self-check catch); the supervisor went straight from RED to `task-worktree add` on RED's branch for both tasks, with no `--help` or inspection turns. Runs 32-34 also inherited the launching agent session (its session id and its team memory, recalled at start); `e2e-live.sh` now unsets those before the run (e2e-live-hosts test), so earlier runs from an agent session carry that caveat. Run 35 (wordfreq, the first with a clean env): 13/13, 12m59s, $0.91, 31 supervisor turns, 2 wakes, 0 plugin-source reads, 2 blocks (self-check catches), no memory recall and its own session id; within the range of runs 27-33, so the inherited memory had not been carrying the earlier results. Next: the Codex/OpenCode public runs (need a machine with those CLIs) | +| **M0.9 — Plan approval is a gate** | v0.13 | `gate-dispatch` admits no execution role (RED, SCAFFOLD, GREEN, the structural reviewer, the final gate) of a sprint until the human approved that sprint's plan as it is now. `events authority --sprint N` asks for a typed line, `approve SN ` (reviewed, the code naming the sha256 of the plan files: `stories.md`, `plan.md`, `ids.json`, each story's `tasks.md`, `validate.md`, `plan.md`, `targets.json`) or `autonomous SN ` (autonomy for that sprint, re-plans included, the code naming the authority record); the task contract's `STORY_DIR` and the task must be that plan's own (a live story and task in its frozen `ids.json`), and RED/SCAFFOLD/GREEN need a task id; the line must be among the human's captured prompts (M9.17's mechanism), typed after the sprint's last decision. A changed plan, a re-plan, a roll-back, another sprint's line, a hand-edited or emitted record and a negated line all block; an approved autonomous mission grants autonomy with no line. Covers Claude Code (`Task`), Codex (`spawn_agent`), OpenCode (`task`) and dsh; `claude -p`, `codex exec` and `opencode run` from a tool call are blocked in every aloop project (the prompt log is the approval's evidence). Reason: the north star says *no human help beyond approval*, but the approval was a prose rule: `events authority` trusted `--initiated-by` and nothing stopped a dispatch before it, so a supervisor could build an unapproved plan | done: `scripts/test/plan-approval.test.py` (20 checks, fails on master at check 1: an unapproved dispatch was admitted). A 4-lens adversarial review (each finding re-verified) found 9 real defects. Seven are fixed with a check that is red on the first head: another sprint's or an unplanned `STORY_DIR` passed under an approval, a line typed again after a later decision stayed stale, an approved mission's autonomy swallowed a non-mission sprint's typed line, `transcripts prune` dropped the prompts grants cite, `codex plugin add` was refused, a code past column 200 recorded a grant the gate refused, and a malformed run-log line crashed `events authority`. Two are playbook fixes: intake reuses the intent `mission goal next` handed off (a fresh `intent new` made the plan serve no mission intent), and a reviewed re-plan waits for the human's new line. Three test gaps (forged autonomy grants, a replayed approval, one sprint's autonomy over another) are covered; mutation results are in #99. every dispatching suite now approves first (`fixtures/plan_fixture.py`, `plan-fixture.mjs`); `e2e-live.sh` pre-approves with a typed `autonomous S1 ` line in the prompt. Open: the run log is not hash-chained, so deleting a later decision line restores an older approval (a roll-back by edit, not by re-typing); a program's write to the prompt log (`python -c`) is invisible to the scope gate, as in M9.17; the mission loop's `APPROVE_PLAN` step counts any `plan.approved` and should ask `events approval` (M9.23 owner); the door gate's `live_run` (M9.30) reads `plan.approved` or `AGENTIC_AUTONOMY_MODE`, so a sprint granted autonomy by the human's `autonomous SN ` line is not yet a live run for it: it should ask `events approval` too (M9.30 owner); M10.2's dependency check (`deps unplanned`) reads the story's plan files as they are at GREEN's stop, so a plan edited after approval can name a dependency: it should also require `events approval` to hold (next, this thread) | | **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` | @@ -197,7 +198,7 @@ These parts already exist but their semantics must change: ### 4.7 Provenance and lineage -- ✅ *Done (Unreleased): envelope + `bin/events` (emit/query/lineage); emitted by budget, gates, worktrees. Test: `scripts/test/events.test.py`. Decision rationale (`events decide`) and the authority record (`events authority`) are done too. Intent, plan (`ids freeze` → plan.created/revised; `events authority` → plan.approved) and commit (`task-worktree remove` → commit.created) emitters are done, and `events trace SHA` walks commit → intent → approver (test: `scripts/test/commit-trace.test.py`). `events commit-msg` and `events graph` close the last two items.* +- ✅ *Done (Unreleased): envelope + `bin/events` (emit/query/lineage); emitted by budget, gates, worktrees. Test: `scripts/test/events.test.py`. Decision rationale (`events decide`) and the authority record (`events authority`) are done too. Intent, plan (`ids freeze` → plan.created/revised; `events authority` → plan.approved) and commit (`task-worktree remove` → commit.created) emitters are done, and `events trace SHA` walks commit → intent → approver (test: `scripts/test/commit-trace.test.py`). `events commit-msg` and `events graph` close the last two items. Since M0.9 a `plan.approved` is emitted only for the human's typed approval of that sprint's plan (`events authority --sprint N`), `plan.approved` and `human.approval` cannot be `events emit`ted, and `events approval SN|TASK_ID` is the check `gate-dispatch` runs.* - **A normalized event stream** (`aladdin.event/1`) for the events listed in the table below. Its envelope carries IDs, `parent_event_id` / `caused_by`, role, host, model, authority, decision, and artifact and evidence refs. It references transcripts and never copies them. - **Structured decision rationale** at durable boundaries (plan, split, target, implementation, replan, acceptance). Each record gives a one-line reason, evidence refs and an authority ref. There is no chain-of-thought capture. - **An authority record per run:** `initiated_by`, policy profile, `autonomy_mode`, approved scope, overrides. @@ -443,7 +444,7 @@ Each task flips only its own row here and in TRACKING.md. | M9.6 | Telemetry (GA4): opt-in consent, Admin API setup, Measurement Protocol debug hit, fixed Data API reports (+ realtime), minimum-sample rule, static emit check; network faked in tests | M9.0 | `plugin/mission/telemetry.py`, `schemas/telemetry.json`, `scripts/test/mission-telemetry.test.py`, `scripts/test/fixtures/fake-ga.py` | yes | done: `mission-telemetry.test.py` (15 checks, fake GA); consent and revoke are human rows in the ledger, the newest by time decides (a union merge keeps order-free), a ledger failing its check decides nothing, and a fresh checkout keeps them (their provenance rides M9.17); the journeys it binds are what the records pin (frozen or a recorded replacement, not retired, unchanged); `verify` is the live round-trip (MP hit → realtime report), and the probe's client is never a counted user | | M9.7 | Principles in two variants with tension pairs; `principles show --mode`, hashed and injected into goals | M9.0 | `plugin/mission/principles.{md,py}`, `scripts/test/mission-principles.test.py` | yes | done: `mission principles show / hash / check`, `stamp()` / `verify()` / `stale()` for goals; `mission-principles.test.py` (7 checks). Calls: a goal keeps the stamp it was derived under (an older block is stale, not invalid: re-stamping would void its ethics review and approval); the Amazon tension pairs map onto our principle ids; the standing set and the four pairs are required, more may be added; a variant is at most 280 characters (the block rides on every goal) | | M9.8 | Loop: `tick` (the state machine above), `due` (zero-token cadence check), `cron` (host routine or crontab line), budget caps from the token ledger | M9.0 | `plugin/mission/{tick,due,cron}.py`, `scripts/test/mission-tick.test.py` | yes | done: `mission-tick.test.py` (32 checks, on baselines proposed, measured and confirmed through `aloop mission`; on a fresh checkout the human decisions, the baseline, state reports and gap lists decide the same). Review (13 findings, each a test that failed before its fix): a restore is never undone; an unmeasurable or vetoed proposal names what the gates accept; distinct block keys; the ledger folds by time; a committed hard review fails closed; a state needs its `state.assessed` record; only the 3-failed-goals grant resets that count; the facts fingerprint covers spend, reviews, intents, plans, the lock and grants | -| M9.9 | Roles and wiring: the six personas, hook matchers, model routes, host install, eval suites, role counts in docs; `gate-mission-scope` (role path guards) and `gate-mission-artifact` (a role's artifact passes its check at stop) | M9.0 | `plugin/agents/` (6 new files), `plugin/mission/roles.json` (the role table), `plugin/bin/_mission_roles.py`, `plugin/hooks/hooks.json`, `plugin/hosts/`, `plugin/evals/`, `plugin/bin/gate-mission-*`, the role lists in `_routes` / `install` / `gate-dispatch` / `selfcheck` / `budget`, role counts in README / OVERVIEW / plugin docs | yes (the only track touching shared lists) | done: `mission-roles.test.py` (33 checks, two of them runs of each role through master's real research, judge, journeys, baseline, assess, evaluate, ethics and goal areas), `mission-scope-bash.test.py` (225 Bash commands from two adversarial reviews and the M9.2/M9.3/M9.8/M9.17 asks), 6 OpenCode and 3 dsh end-to-end checks. Calls: judges (researcher, evaluator, planner, ethics) take the planning route, the two measuring roles the worker route; every mission role is read-only on source and writes only its own dirs (the planner also `docs/agents/intents/`, where only its `source: mission` intents are its work) and never the event log or the gates' state; the supervisor never hand-writes a role's artifact (mission.json stays the human's) and no one hand-writes `ledger.jsonl` (an edit made inside a role's run blocks its stop) or the captured prompts a grant reads (`/transcripts/`), runs a hook's `transcripts prompt|record|…`, or, where a mission is set, starts a host session from a tool call (`claude -p`, `codex exec`, `opencode run`, `dsh ` fire UserPromptSubmit: M9.17); no dispatched agent runs a human's step (`approve`, `confirm`, `veto`, `restore`…, `tick --force`, `events authority`, an `events emit|decide` with role `human`) or hand-emits a mission-layer event; a mission write never arms the sprint lock; an area's check runs once per artifact with its id or subject (`area_checks` in roles.json), and an ethics hard line is the reviewer's finding, not a defect, and a goal check that waits only on the goal's ethics review is the reviewer's step, not the planner's defect; a status change an event of the run explains (a human's step, or the role's own command: `baseline apply` freezing journeys, a hard line blocking its goal) is not another role's write; at stop a role must have written an artifact, and a content or status change to another role's artifact blocks unless a run of that role overlapped or the human approved it; a human event during a role's run is named, not blocked (the gate cannot tell who ran it: M9.17); the scope gate reads Bash with its own shell reader (`_shellread.py`), and what only running a command would tell is judged by its known directory or not at all | +| M9.9 | Roles and wiring: the six personas, hook matchers, model routes, host install, eval suites, role counts in docs; `gate-mission-scope` (role path guards) and `gate-mission-artifact` (a role's artifact passes its check at stop) | M9.0 | `plugin/agents/` (6 new files), `plugin/mission/roles.json` (the role table), `plugin/bin/_mission_roles.py`, `plugin/hooks/hooks.json`, `plugin/hosts/`, `plugin/evals/`, `plugin/bin/gate-mission-*`, the role lists in `_routes` / `install` / `gate-dispatch` / `selfcheck` / `budget`, role counts in README / OVERVIEW / plugin docs | yes (the only track touching shared lists) | done: `mission-roles.test.py` (33 checks, two of them runs of each role through master's real research, judge, journeys, baseline, assess, evaluate, ethics and goal areas), `mission-scope-bash.test.py` (225 Bash commands from two adversarial reviews and the M9.2/M9.3/M9.8/M9.17 asks), 6 OpenCode and 3 dsh end-to-end checks. Calls: judges (researcher, evaluator, planner, ethics) take the planning route, the two measuring roles the worker route; every mission role is read-only on source and writes only its own dirs (the planner also `docs/agents/intents/`, where only its `source: mission` intents are its work) and never the event log or the gates' state; the supervisor never hand-writes a role's artifact (mission.json stays the human's) and no one hand-writes `ledger.jsonl` (an edit made inside a role's run blocks its stop) or the captured prompts a grant reads (`/transcripts/`), runs a hook's `transcripts prompt|record|…`, or starts a host session from a tool call (in every aloop project since M0.9, which reads the same prompts) (`claude -p`, `codex exec`, `opencode run`, `dsh ` fire UserPromptSubmit: M9.17); no dispatched agent runs a human's step (`approve`, `confirm`, `veto`, `restore`…, `tick --force`, `events authority`, an `events emit|decide` with role `human`) or hand-emits a mission-layer event; a mission write never arms the sprint lock; an area's check runs once per artifact with its id or subject (`area_checks` in roles.json), and an ethics hard line is the reviewer's finding, not a defect, and a goal check that waits only on the goal's ethics review is the reviewer's step, not the planner's defect; a status change an event of the run explains (a human's step, or the role's own command: `baseline apply` freezing journeys, a hard line blocking its goal) is not another role's write; at stop a role must have written an artifact, and a content or status change to another role's artifact blocks unless a run of that role overlapped or the human approved it; a human event during a role's run is named, not blocked (the gate cannot tell who ran it: M9.17); the scope gate reads Bash with its own shell reader (`_shellread.py`), and what only running a command would tell is judged by its known directory or not at all | | M9.10 | Assess and evaluate: the State Assessor's report (numbers only, from pinned scripts) and the Evaluator's gap list against the baseline and rivals, with `goal_met` | M9.2, M9.3, M9.5 | `plugin/mission/{assess,evaluate}.py`, `schemas/{state,eval}.json`, `scripts/test/mission-evaluate.test.py` | after its needs | done: `mission-evaluate.test.py` (8 checks); judged metrics come from `judge.verdict(cwd, rubric, journey_id, rubric_sha256=…)` (M9.5) for the rubric content the journey pinned and stay pending until a pass or fail verdict; every input is the content its record covers (state `state.assessed`, baseline confirmation, frozen journeys, goal `goal.derived`/`goal.approved`). Open: rival values keyed per benchmark in the baseline, so the gap list compares against rivals (review finding) | | M9.11 | Goals and the Aladdin handoff: top gaps → a goal → intents (`intent` source `mission`), ethics and principles applied, mode → autonomy; `events trace` reaches goal → mission | M9.4, M9.7, M9.10 | `plugin/mission/goal.py`, `schemas/goal.json`, `plugin/bin/intent` (source list), `plugin/bin/events` (trace) | after its needs | done: `mission goal options / derive / check / approve / intents / next / close / show`, `intent new --source mission --goal --gap`, `events trace` adds goal → eval → ethics → mission; `mission-goal.test.py` (13 checks, on the real journeys → baseline → assess → evaluate pipeline; every new gate mutation-tested: deleting it fails a check). Calls: a goal takes M9.10's gaps in its own order (regressions, then closest to target) and names them as `targets` [{journey_id, criterion_id}], which `mission evaluate` narrows to while the goal is active; autonomous takes the top 3 by default, spoon-fed the human's `--pick` (the pick is `goal.approved`); a goal comes only from the latest eval of the whole mission (not an older one, whose gaps may be closed, nor one narrowed to an active goal) whose gap list `evaluate check` confirms, whose content its `eval.completed` recorded, and whose state a `state.assessed` recorded (a hand-written state that `mission evaluate` accepted is still refused); `goal check`, `intents`, `next` and `close` hold a goal to the content its `goal.derived` recorded, so a crafted or edited-and-resealed goal file is never handed off or closed; a goal is stale once the mission's content changes; intents are filled from the gap and the journey without a model (zero tokens), one per gap, normalized one at a time by `next`, which first makes that intent the newest file (gate-intake re-checks the newest, so the sprint's plan links the right gap); `intent new --source mission` needs `--gap` and a goal that passes `goal check` and lists that gap, and `intent check` holds a mission intent to its own `intent.received` record (goal and gap) and to the goal's autonomy (a reviewed goal's intent is not checked as autonomous); the handoff counts only intents whose first `intent.received` names the goal; `intents` and `close` change only the status, never the goal's hashed content (its ethics review, consent and approval stay valid); a goal is met by a newer evaluation of that goal that says `goal_met`, only while it is active (a derived, blocked or retired goal never closes; closing a met goal again is a no-op); `events emit` refuses `goal.derived`, `goal.met`, `state.assessed`, `eval.completed` and `intent.received`, so the lineage `trace` reads and the records a goal is derived and closed from are written only by their commands (edits outside its files: `assess` and `evaluate` add the content's `sha256` to their events, one field each). A gap a hard line fixed is held, by its id and by its summary: listed apart by `options`, never taken by `derive`, so the autonomous loop moves on instead of re-deriving it (`ethics.blocked` names the gaps); a gap's summary is the journey's title, criterion and target (stable across evals); a goal keeps the principles stamp it was derived under (stale after an upgrade, not invalid, since re-stamping would void its ethics review and approval) | | M9.12 | The `/aloop:mission` skill: the supervisor's playbook for the tick loop | M9.8, M9.9 | `plugin/skills/mission/` | after its needs | done: `mission-skill.test.py` (9 checks); a live run needs M9.9's roles | @@ -575,6 +576,7 @@ New with this roadmap: - Semantic targets never modify the accepted tree. - Deep failure evidence is on demand, not injected. - External evidence is source-referenced and never treated as an invariant. +- Execution starts only on the human's own word: no execution role of a sprint is dispatched before the human approved that sprint's plan as it is now (their typed `approve SN `), or granted that sprint autonomy (their typed `autonomous SN `, or an approved autonomous mission for its own sprints), and only on that plan's own stories and tasks (M0.9). - A one-way door is crossed only under the human's recorded authorization, and a wall never; a two-way door is decided, not asked (M9.30). ## 8. Tracking diff --git a/docs/TRACKING.md b/docs/TRACKING.md index 08a86400..fc379b01 100644 --- a/docs/TRACKING.md +++ b/docs/TRACKING.md @@ -57,6 +57,7 @@ Status of every requirement in [ROADMAP.md](ROADMAP.md), in the four states §8 | 4.10 | The supervisor's playbook draws the enforced layout (sprint under `docs/agents/`) and stays within a byte budget | IMPLEMENTED_TESTED | `scripts/test/skill-layout.test.py` | | 7 | The final-gate persona's suppression check is the gate's (`assert_no_suppression`), never its own list | IMPLEMENTED_TESTED | `scripts/test/suppression-contract.test.py` | | 4.11 | The north-star run reproducible on every host (`e2e-live.sh --host codex|opencode`: host install + headless CLI, same checks) | IMPLEMENTED_TESTED | `scripts/test/e2e-live-hosts.test.py` (measured Codex/OpenCode rows still pending: no CLIs here) | +| M0.9 | Plan approval is a gate: no execution role of a sprint is dispatched until the human approved that sprint's plan, as it is now, in their own typed line (`approve SN `, or `autonomous SN ` / an approved autonomous mission); Claude Code, Codex, OpenCode, dsh | IMPLEMENTED_TESTED | `scripts/test/plan-approval.test.py`, `scripts/test/dsh-plugin.test.mjs`, `scripts/test/opencode-plugin.test.mjs` | | M0.6 | Gates behave the same on stock macOS bash 3.2 (no bash-4+ construct; the standards.md matrix is the one that runs) | IMPLEMENTED_TESTED | `scripts/test/bash-portable.test.py` | | 6.3 | RED fails by assertion on any language: a non-cargo repo runs the standards.md matrix's test command (pytest exit codes, `go test` build failures) | IMPLEMENTED_TESTED | `scripts/test/any-language.test.py` | | 7 | The sprint and every STORY_DIR live in `docs/agents/sprintN/`, never in the git-ignored run-data dir (`gate-stage2-complete`, `gate-dispatch`) | IMPLEMENTED_TESTED | `scripts/test/planner-stuck.test.py`, `scripts/test/dispatch.test.py` | diff --git a/docs/evidence/README.md b/docs/evidence/README.md index 5b6c9e21..1e117edf 100644 --- a/docs/evidence/README.md +++ b/docs/evidence/README.md @@ -57,6 +57,7 @@ the cost cell reads — and the intent cell names the host. What each run found | run 47 | cli (Rust binary), on #81 | v0.12.0 + #81 (a653fd4) | 13/13 | 15m19s | $1.04 | 2 | 1 | 2 | `make e2e-live YES=1 INTENT=cli` | | run 48 | cli (Rust binary), on the task-merge rule | v0.12.0 + #90 (a60cd04) | 13/13 | 14m13s | $0.76 | 2 | 0 | 5 | `make e2e-live YES=1 INTENT=cli` | | run 49 | cli (Rust binary), on #95 and #102 | v0.12.0 + #102 (f8bcbc0) | 13/13 | 13m50s | $0.87 | 1 | 0 | 3 | `make e2e-live YES=1 INTENT=cli` | +| run 50 | cli (Rust binary), under the plan approval gate | v0.12.0 + #99 (575d95a) | 13/13 | 10m17s | $0.84 | 2 | 0 | 1 | `make e2e-live YES=1 INTENT=cli` | Columns: *checks* are the e2e script's own assertions (12 for `semver`, 13 for `wordfreq` since the commit-trace check); *wakes* are supervisor turns that ended and resumed (each re-reads @@ -101,3 +102,8 @@ tasks, one per story, with no merge refusal: the rule's persona line was enough. Run 49 (on #95, which stops the Rust suppression grep matching an iterator's `.skip(1)`, and #102) had 3 gate blocks, from 5, with no suppression or `targets` "neither in the tree nor planned" refusal. It planned 2 tasks again, for $0.87 in 13m50s. +Run 50 (on #99, M0.9) is the first run under the plan approval gate. The prompt carried the human's +typed `autonomous S1 ` line; the supervisor recorded the grant with it before its first dispatch +(a `human.approval` of kind autonomy that cites the captured line), and `gate-dispatch` then admitted +every dispatch of the sprint (S1-01-T1, S1-01-T2, S1-SR-W2, S1-FG) with no dispatch block. 2 tasks, +25 supervisor turns, $0.84 and 10m17s (run 49: $0.87, 13m50s); its 1 block was a worker's self-check. diff --git a/plugin/agents/intake.md b/plugin/agents/intake.md index d228c009..83d3a978 100644 --- a/plugin/agents/intake.md +++ b/plugin/agents/intake.md @@ -27,6 +27,10 @@ planning start on an ambiguous scope. security-sensitive or changes the intent → ask the human, record the `answer`), `spike` (unknown but testable → name the `spike_task`). Then `intent check `; `intent summary ` gives the lines for the approval summary. + A mission sprint already has its contract: when `aloop mission goal next` handed one off (the + newest `docs/agents/intents/int_*.json` has `"source": "mission"` and no plan yet), review that file + and `intent check` it; never `intent new` over it, or the plan no longer serves the mission's + intent and its autonomy does not cover the sprint (ROADMAP M0.9). ## Tools Everything is on PATH — never search for it: `selfcheck`, `md-db`, `ctx-symbols`, diff --git a/plugin/bin/README.md b/plugin/bin/README.md index 44eea554..2c779793 100644 --- a/plugin/bin/README.md +++ b/plugin/bin/README.md @@ -26,7 +26,7 @@ ctx-symbols) → WARN + grep fallback; never a silent pass. | script | event · matcher | checks | exit 2 when | |--------|-----------------|--------|-------------| | gate-supervisor-scope | PreToolUse · Write\|Edit\|MultiEdit\|Bash | MAIN agent (no `agent_type`) may not write production source mid-sprint, nor hand-author planning artifacts (stories/tasks/validate/plan/intake/standards.md — dispatch the activity), nor `git commit` on main (commits on main arrive through `task-worktree merge`); sub-agents (`agent_type` present) exempt | supervisor writes source / hand-writes a planner-owned artifact / commits on main | -| gate-dispatch | PreToolUse · Agent\|Task | the MAIN agent's dispatch of any aloop role passes the project's confirmed model (`aloop models resolve `, matched by family; no model or another model is refused), and a dispatch of an execution role opens with `TASK_ID: ` and that task's contract `/state/tasks/.env` exists (repos with a run-data dir only) | no TASK_ID line / contract not written yet | +| gate-dispatch | PreToolUse · Agent\|Task (Codex `spawn_agent`, OpenCode `task`, dsh `subagent`) | the MAIN agent's dispatch of any aloop role passes the project's confirmed model (`aloop models resolve `, matched by family; no model or another model is refused; Codex and OpenCode calls that name none use the agent file's pinned one), and a dispatch of an execution role opens with `TASK_ID: `, that task's contract `/state/tasks/.env` exists, and the human approved the sprint's plan as it is now, with STORY_DIR and the task that plan's own (`events approval`, M0.9) (repos with a run-data dir only) | no TASK_ID line / contract not written yet / plan not approved, or changed since | | gate-tooling | SubagentStart · exec roles + supervisor self-check | md-db + ctx-symbols installed (execution may not run grep-degraded); runs `ensure-tools --sync` first | a backend is missing and can't be built | | gate-validate-artifact | PostToolUse · Write | md-db-validate the written artifact | artifact malformed | | gate-red-verify | SubagentStop · red-worker | worktree-isolated; appended output.md block (validate_comms); every new test FAILS BY ASSERTION; no regression; diff = tests+shims | no/stale output.md block / shared-tree run / a new test passes / prod code / regression | @@ -64,7 +64,7 @@ ctx-symbols) → WARN + grep fallback; never a silent pass. | `gate-commit-author` | PreToolUse · Bash — a `git commit` must use the configured author: denies `--author`/`-c user.*`/`GIT_AUTHOR_*` overrides, a mismatched repo identity, and Claude co-author/attribution trailers (unless `CLAUDE_COAUTHOR=yes`) | | `stats` | `hook` (Stop + SubagentStop): rewrites `.agentic/ledger/.jsonl` from the transcripts (tokens per API call, main + sub-agents) and, once after a sprint closed, shows the totals + tells the supervisor to ask for `/clear`. `sprint-close` (run by gate-final on pass): `sprintN/stats.md` + `NEXT.md`. `show`: session / sprint / project totals | | `budget` | per-attempt time box for red/scaffolder/green workers. `hook pre\|post\|stop` (PreToolUse/PostToolUse `*`, SubagentStop): soft time limit → warning in the worker's tool result; soft token limit → telemetry only (`task.token_soft_limit` in `.agentic/logs/events.jsonl`, surfaced in stats.md/NEXT.md, worker not told); hard limit → PostToolUse `continue: false` stops the worker on that call, later calls refused; the harness (not the worker) appends the `status: re-plan` output.md block and records `task.token_hard_limit`/`task.time_hard_timeout` (+ the worktree's `.aladdin/budget-exceeded`, so its gate releases the stop unverified). `resolve` · `watch` (supervisor sleep; exits with STOPPED / KILL / STUCK lines) · `status` · `mark-killed` · `replans` (split cap) | -| `events` | the `aladdin.event/1` stream in `.agentic/logs/events.jsonl` (`_events.py`): `emit EVENT --task … --parent …` · `query --task/--event/--sprint` · `lineage TASK_ID` (worktree → limits → gates → decisions → merged/discarded, from refs, never transcripts) · `trace SHA` (commit → task → gates → plan → intent → approver) · `commit-msg TASK` (title + decisions + ids) · `graph [--format json|dot]` (downstream export). Written by `budget`, every gate verdict (`_gatelib.sh`) and `task-worktree`. | +| `events` | the `aladdin.event/1` stream in `.agentic/logs/events.jsonl` (`_events.py`): `emit EVENT --task … --parent …` · `query --task/--event/--sprint` · `lineage TASK_ID` (worktree → limits → gates → decisions → merged/discarded, from refs, never transcripts) · `trace SHA` (commit → task → gates → plan → intent → approver) · `commit-msg TASK` (title + decisions + ids) · `graph [--format json|dot]` (downstream export) · `authority … --sprint N` (the human's grant: exits 3 with the `approve SN ` / `autonomous SN ` line to type, M0.9) · `approval SPRINT|TASK_ID [--story-dir D] [--role R]` (exit 0 approved, 2 not; `gate-dispatch` runs it). `plan.approved` and `human.approval` cannot be emitted. Written by `budget`, every gate verdict (`_gatelib.sh`) and `task-worktree`. | | `intent` | the internal Intent Contract (ROADMAP §4.1): `new` issues the canonical `intent_id` + skeleton under `docs/agents/intents/`; `check FILE [--mode reviewed\|autonomous]` validates fields and the clarification policy (exit 2 invalid, 3 an `ask` needs the human); `summary FILE` lists defaults/assumptions/spikes for approval. Run by `gate-intake`. | | `ids` | canonical identity + referential integrity (ROADMAP §4.5): `freeze SPRINT_DIR` checks the structured references (story frontmatter ↔ dir, dirs ↔ stories.md, validate.md ↔ tasks.md headings, `split_from` → a retired task) and issues frozen UUIDv7 ids in `sprintN/ids.json`; a retired alias is never reused · `check` · `resolve ALIAS`. Run by `gate-stage2-complete`; events then carry `story_uid`/`task_uid`. | | `deps` | supply chain (ROADMAP M10.2): `added --base REF` lists the dependencies a change adds to Cargo.toml, package.json, requirements*.txt, pyproject.toml or go.mod · `unplanned --base REF --story DIR` the ones the story's plan does not name (exit 2); gate-green-verify blocks on them. No third-party parser. | @@ -92,7 +92,7 @@ done) AND a `SubagentStop` hook backstop running the same gate: | archivist | `gate-memory` (valid + never relaxes an invariant) | SubagentStop · `archivist` | | red/scaffold/green/structural/final | as above | SubagentStop · role | | the six mission roles (`plugin/mission/roles.json`) | `gate-mission-artifact`: the run wrote an artifact in its own paths, each passes the core contract and its area's check, nothing deleted, no other role's artifact changed (content or status) unless a run of its owner overlapped; the ledger still verifies if it changed; a run with no start record is blocked; a pass records `artifact.created` (provenance) and any human event during the run | SubagentStart (`start`: what exists) · SubagentStop · role | -| every agent and the supervisor | `gate-mission-scope`: a mission role writes only its own paths (never source, the event log or the gates' state); any other agent never writes `docs/agents/mission/` or runs a writing `mission` command; the supervisor never hand-writes a role's artifact; no one hand-writes `ledger.jsonl` or the captured prompts, runs a hook's `transcripts` command or (where a mission is set) starts a host session from a tool call; no dispatched agent runs `events authority` or emits a human or mission-layer event. Bash is read as the shell reads it (`_shellread.py`: quotes, comments, continuations, wrappers, `bash -c`, interpreters, variables) | PreToolUse · Write/Edit/MultiEdit/NotebookEdit/Bash | +| every agent and the supervisor | `gate-mission-scope`: a mission role writes only its own paths (never source, the event log or the gates' state); any other agent never writes `docs/agents/mission/` or runs a writing `mission` command; the supervisor never hand-writes a role's artifact; no one hand-writes `ledger.jsonl` or the captured prompts, runs a hook's `transcripts` command or starts a host session from a tool call (its prompt would read as the human's: M9.17, M0.9); no dispatched agent runs `events authority` or emits a human or mission-layer event. Bash is read as the shell reads it (`_shellread.py`: quotes, comments, continuations, wrappers, `bash -c`, interpreters, variables) | PreToolUse · Write/Edit/MultiEdit/NotebookEdit/Bash | `bin/selfcheck [role]` resolves the role from `$AGENT_ROLE` (task.env) and runs that gate; exit `0` PASS · `2` FAIL · `64` unknown role. A PASS here means the hook passes. diff --git a/plugin/bin/_approval.py b/plugin/bin/_approval.py new file mode 100644 index 00000000..1fe4cb6e --- /dev/null +++ b/plugin/bin/_approval.py @@ -0,0 +1,322 @@ +"""_approval.py — a sprint runs only on the human's own word (ROADMAP M0.9). + +"A human approves the plan" was a playbook rule: nothing checked it, so a supervisor could dispatch +workers before the human said go. Now the grant is a record, and gate-dispatch reads it: + + - reviewed (the default): `events authority --mode reviewed [--sprint N]` records the human's approval + of exactly the plan they saw. It counts only when a prompt the UserPromptSubmit hook captured has + the line `approve SN ` (M9.17's mechanism: the code is the first 8 hex of the grant's digest, + which covers every plan file of the sprint), and until then it asks (exit 3) with that line; + - autonomous: `events authority --mode autonomous --sprint N` grants sprint N autonomy (re-plans + included). It asks for `autonomous SN ` (the code names the authority record), unless the + project's mission is approved in autonomous mode: that approval is already the human's word, and it + covers the sprints that serve the mission's own intents. + +gate-dispatch admits an execution role of sprint N only while the sprint's newest grant holds: its +cited line is still in the captured prompts and grants exactly that content, the plan is still the one +approved (reviewed), and the mission still grants autonomy (mission-backed). An unverifiable newest +grant blocks: a hand-written record can only take a grant away, never add one. A line captured before +a later decision about the same sprint is stale, so an old approval never re-grants a replaced plan. +""" +import glob +import hashlib +import json +import os +import re + +import _events +import _mission as M +import _paths + +# the plan of a sprint: what the planner writes and the human approves. Comms (init.md, output.md), +# plan-ready.md ticks, logs and stats change during execution and are not the plan. +SPRINT_FILES = ("stories.md", "plan.md", "ids.json") +STORY_FILES = ("tasks.md", "validate.md", "plan.md", "targets.json") +STORY_DIR = re.compile(r"^s(\d+)-(\d+)-") +TASK = re.compile(r"^S(\d+)-(\d+)-T\d+$", re.I) +TASK_ROLES = ("red-worker", "scaffolder", "green-worker") # one task each; a review or the final gate may span the sprint +VERBS = {"plan": "approve", "autonomy": "autonomous"} +AUTH_FIELDS = ("initiated_by", "autonomy_mode", "scope", "policy", "overrides", "sprint") + + +def sprint_of(s): + """"S1" from 1, "1", "S1", "s1", "sprint1" or a task id (S1-01-T1, S1-SR-W1); "" otherwise.""" + m = re.match(r"^\s*(?:sprint|s)?(\d+)(?:-[A-Za-z0-9._-]*)?\s*$", str(s if s is not None else ""), re.I) + return "S%d" % int(m.group(1)) if m and int(m.group(1)) > 0 else "" + + +def sprint_dir(cwd, sp): + return os.path.join(_paths.docs(cwd), "sprint" + sp[1:]) + + +def plan_files(cwd, sp): + """(project-relative path, absolute path) of every plan file of the sprint, in a fixed order.""" + sdir = sprint_dir(cwd, sp) + out = [os.path.join(sdir, n) for n in SPRINT_FILES] + for d in sorted(glob.glob(os.path.join(sdir, "s*-*"))): + if os.path.isdir(d) and STORY_DIR.match(os.path.basename(d)): + out += [os.path.join(d, n) for n in STORY_FILES] + return [(M.rel(cwd, p), p) for p in out if os.path.isfile(p)] + + +def plan_digest(cwd, sp): + """The sha256 of the sprint's plan as it is now (None when the sprint has no dir).""" + if not os.path.isdir(sprint_dir(cwd, sp)): + return None + files = {} + for rel, p in plan_files(cwd, sp): + with open(p, "rb") as f: + files[rel] = hashlib.sha256(f.read()).hexdigest() + return hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest() + + +def content(auth): + return {k: auth.get(k) for k in AUTH_FIELDS} + + +def grant_sha(auth, plan_sha=None): + """What the human's code names: the plan (with the sprint and any override) for an approval, the + whole authority record for autonomy.""" + if auth.get("autonomy_mode") == "autonomous": + return M.digest(content(auth), drop=()) + return M.digest({"sprint": auth.get("sprint"), "plan": plan_sha, "overrides": auth.get("overrides") or {}}, drop=()) + + +def data(e): + """An event's data, {} when a hand-written line has none or another shape.""" + d = e.get("data") + return d if isinstance(d, dict) else {} + + +def plans(cwd, sp=None): + return [e for e in _events.read(cwd) if e.get("event") in ("plan.created", "plan.revised") + and (sp is None or data(e).get("sprint") == sp)] + + +def grants(cwd, sp): + """The human's grants about sprint sp (authority records that name it), oldest first.""" + out = [] + for e in _events.read(cwd): + a = e.get("authority") + if e.get("event") == "human.approval" and isinstance(a, dict) and a.get("sprint") == sp \ + and isinstance(a.get("grant"), dict): + out.append(e) + return out + + +def stale_floor(qs, decisions, sha): + """How many captured prompts are too old to grant `sha`: every one captured before a decision about the + same sprint that granted other content (as M9.17's stale_before, over the run log's grants).""" + clock, floor = M.prompt_clock(qs), 0 + for e in decisions: + g = e["authority"]["grant"] + if g.get("sha256") == sha: + continue # this very content again undoes nothing + seen = g.get("prompt_log") if isinstance(g.get("prompt_log"), dict) else {} + if clock["id"] and seen.get("id") == clock["id"] and isinstance(seen.get("seen"), int): + floor = max(floor, seen["seen"]) + else: # another prompt log: a prompt from that second or before is older + floor = max(floor, sum(1 for q in qs if q["ts"] <= str(e.get("ts") or ""))) + return floor + + +def ask(verb, sp, sha, what): + return M.NeedsHuman("%s is the human's own decision: they reply %s %s %s (the code names exactly %s), " + "then run this again" % (what, verb, sp, M.code(sha), "this plan" if verb == "approve" else + "this authority record")) + + +def provenance(cwd, sp, verb, sha, what): + """The newest captured prompt line that grants `sha` (not stale), as the record's `prompt`; raises + NeedsHuman with the line to reply when there is none.""" + qs = M.prompts(cwd) + for q in reversed(qs[stale_floor(qs, grants(cwd, sp), sha):]): + for line in q["text"].splitlines(): + line = line.strip()[:200] # what the record keeps is what the gate re-reads + if M.grants(line, verb, sha): + return {"ts": q["ts"], "sha256": q["sha256"], "session": q["session"], "line": line} + raise ask(verb, sp, sha, what) + + +def mission_autonomy(cwd): + """The approved mission's grant of autonomy, or None: mission.json approved as it is now (the human's + typed line, M9.17), in autonomous mode, on a ledger that verifies.""" + path = M.path_of(cwd, "mission") + doc, _ = M.load(path) + if not isinstance(doc, dict) or doc.get("mode") != "autonomous" or M.ledger_problems(cwd): + return None + try: + sha = M.digest(doc) + except (TypeError, ValueError): + return None + rec = M.approved(cwd, "mission.approved", M.rel(cwd, path), sha) + if not rec or not M.cites(rec): + return None + return {"ref": M.rel(cwd, path), "mission_id": doc.get("mission_id"), "sha256": sha, "event_id": rec.get("event_id"), + "by": rec["data"].get("by")} + + +def grant_for(cwd, initiated_by, mode, scope, sprint="", policy="default", overrides=None): + """(sprint, grant) for a new authority record: the grant cites the human's typed line (or, for + autonomy, the approved autonomous mission). Raises NeedsHuman until the human has typed it, + ValueError on a bad request. A reviewed record with no sprint and no frozen plan grants nothing.""" + sp = sprint_of(sprint) if sprint not in (None, "") else "" + if sprint not in (None, "") and not sp: + raise ValueError("--sprint names a sprint: N, SN or sprintN (got %r)" % sprint) + if mode == "autonomous" and not sp: + raise ValueError("autonomy is granted per sprint: name it with --sprint N (one sprint per autonomous run)") + if mode == "reviewed" and not sp: + latest = plans(cwd) + sp = data(latest[-1]).get("sprint", "") if latest else "" + if not sp: + return "", None # nothing planned yet: the record says who started the run + if mode == "reviewed" and not plans(cwd, sp): + raise ValueError("the plan of %s is not frozen: run gate-stage2-complete %s (its `ids freeze` records the " + "plan), then show it to the human" % (sp, M.rel(cwd, sprint_dir(cwd, sp)))) + auth = {"initiated_by": initiated_by, "autonomy_mode": mode, "scope": scope, "policy": policy, + "overrides": overrides or {}, "sprint": sp} + if mode == "reviewed": + plan_sha = plan_digest(cwd, sp) + sha = grant_sha(auth, plan_sha) + grant = {"kind": "plan", "sha256": sha, "plan_sha256": plan_sha, "files": [r for r, _ in plan_files(cwd, sp)], + "prompt": provenance(cwd, sp, VERBS["plan"], sha, "The approval of %s's plan" % sp)} + else: + sha = grant_sha(auth) + # the mission's autonomy covers only its own sprints: one planned from another intent asks the human + mission = mission_autonomy(cwd) if mission_intent(cwd, sp) or not plans(cwd, sp) else None + grant = {"kind": "autonomy", "sha256": sha} + if mission: + grant["mission"] = mission + else: + grant["prompt"] = provenance(cwd, sp, VERBS["autonomy"], sha, "Autonomy for %s" % sp) + grant["prompt_log"] = M.prompt_clock(M.prompts(cwd)) + return sp, grant + + +def cited(cwd, prompt, verb, sha, floor_decisions): + """Problems with a grant's cited line: it must be a line of a captured prompt (not a stale one) that + grants exactly `sha`.""" + if not isinstance(prompt, dict) or not isinstance(prompt.get("line"), str): + return ["it cites no line the human typed"] + if not M.grants(prompt["line"], verb, sha): + return ["its cited line %r does not %s this content (code %s)" % (prompt["line"], verb, M.code(sha))] + qs = M.prompts(cwd) + floor = stale_floor(qs, floor_decisions, sha) + seen = [i for i, q in enumerate(qs) if q["sha256"] == prompt.get("sha256") + and any(ln.strip()[:200] == prompt["line"] for ln in q["text"].splitlines())] + if any(i >= floor for i in seen): # the same words typed again after a later decision count again + return [] + if seen: + return ["its cited line %r was typed before a later decision about this sprint" % prompt["line"]] + return ["its cited line %r is not among the human's captured prompts in this checkout" % prompt["line"]] + + +def mission_intent(cwd, sp): + """The intent the sprint's newest plan serves, when it is a mission intent (intent.received with + source mission, written only by `intent new`), else None.""" + ps = plans(cwd, sp) + iid = data(ps[-1]).get("intent_id") if ps else None + if not iid: + return None + for e in _events.read(cwd): + d = data(e) + if e.get("event") == "intent.received" and d.get("intent_id") == iid and d.get("source") == "mission": + return iid + return None + + +def placement(cwd, sp, tid, story_dir="", role=""): + """Problems with what the dispatch works on: the approval of sp covers only sp's own plan, so the task + contract's STORY_DIR must be sp's dir or one of its stories (sN-NN-/ with N = sp, live in the frozen + ids.json the approval digests), a task id must be a live task there, and a RED/SCAFFOLD/GREEN worker works + on a task.""" + m = TASK.match(tid) + if role in TASK_ROLES and not m: + return ["a %s works on one task of the plan: its TASK_ID is SN-NN-Tk (got %s)" % (role, tid)] + sdir = os.path.realpath(sprint_dir(cwd, sp)) + try: + with open(os.path.join(sdir, "ids.json")) as f: + frozen = json.load(f).get("ids") + except (OSError, ValueError, AttributeError): + frozen = None # no frozen map: the approved digest pins that there is none + frozen = frozen if isinstance(frozen, dict) else None + + def live(alias, path=None): + e = frozen.get(alias) if frozen is not None else {} + return frozen is None or (isinstance(e, dict) and not e.get("retired") and (path is None or e.get("path") == path)) + if story_dir: + rp = os.path.realpath(story_dir) + sm = STORY_DIR.match(os.path.basename(rp)) + if rp != sdir: + if os.path.dirname(rp) != sdir or not sm or int(sm.group(1)) != int(sp[1:]): + return ["STORY_DIR %s is not in %s's plan: the human's approval of %s covers %s and its story dirs" + " (s%s-NN-/) only" % (M.rel(cwd, rp), sp, sp, M.rel(cwd, sdir), sp[1:])] + if not live("S%s-%s" % sm.groups(), os.path.basename(rp)): + return ["STORY_DIR %s is no live story of %s's frozen plan (%s/ids.json): plan it first" + % (M.rel(cwd, rp), sp, M.rel(cwd, sdir))] + if m and int(m.group(2)) != int(sm.group(2)): + return ["TASK_ID %s is not a task of the story dir %s" % (tid, M.rel(cwd, rp))] + if m and not live(tid): + return ["%s is not a live task of %s's frozen plan (%s/ids.json): plan it first" % (tid, sp, M.rel(cwd, sdir))] + return [] + + +def check(cwd, task_or_sprint, story_dir="", role=""): + """(True, why) when an execution role of this sprint may be dispatched now, else (False, problems). + `story_dir` (the task contract's STORY_DIR) and `role` tie the dispatch to the approved plan.""" + sp = sprint_of(task_or_sprint) + if not sp: + return False, ["TASK_ID %s names no sprint: a task id is SN-NN-Tk (SN-SR-Wk for a wave review), so the gate" + " knows whose plan approval it needs" % task_or_sprint] + plan_sha = plan_digest(cwd, sp) + if plan_sha is None: + return False, ["%s has no plan (%s does not exist)" % (sp, M.rel(cwd, sprint_dir(cwd, sp)))] + good, why = holds(cwd, sp, plan_sha) + if not good: + return good, why + bad = placement(cwd, sp, str(task_or_sprint), story_dir, role) + return (False, bad) if bad else (True, why) + + +def holds(cwd, sp, plan_sha): + """(True, why) when the sprint's newest grant holds for its plan as it is now, else (False, problems).""" + how = ("show the human the plan of %s; on their go run `aloop events authority --initiated-by \"\"" + " --mode reviewed --scope \"%s as approved\" --sprint %s`: it asks for their typed line `approve %s `" + " (an autonomous run: `--mode autonomous`, their line `autonomous %s `)" % (sp, sp, sp[1:], sp, sp)) + gs = grants(cwd, sp) + if not gs: + return False, ["the human has not approved the plan of %s: nothing of it is dispatched before they do." % sp, + " To get it: " + how] + e = gs[-1] + auth, g = e["authority"], e["authority"]["grant"] + who = "%s (%s)" % (auth.get("initiated_by"), auth.get("autonomy_mode")) + if g.get("kind") == "plan" and auth.get("autonomy_mode") == "reviewed": + if g.get("plan_sha256") != plan_sha: + return False, ["the plan of %s changed after the human approved it (approved %s, now %s): a changed plan is" + " a new decision." % (sp, M.code(g.get("plan_sha256") or ""), M.code(plan_sha)), + " Show them what changed (`git diff` of %s); then: %s" % (M.rel(cwd, sprint_dir(cwd, sp)), how)] + if g.get("sha256") != grant_sha(auth, plan_sha): + return False, ["the newest approval of %s does not match its own record (a hand-edited record); %s" % (sp, how)] + bad = cited(cwd, g.get("prompt"), VERBS["plan"], g["sha256"], gs[:-1]) + if bad: + return False, ["the newest approval of %s is not the human's own words: %s." % (sp, bad[0]), " " + how] + return True, "%s approved by %s, code %s" % (sp, who, M.code(g["sha256"])) + if g.get("kind") == "autonomy" and auth.get("autonomy_mode") == "autonomous": + if g.get("sha256") != grant_sha(auth): + return False, ["the newest autonomy grant of %s does not match its own record (a hand-edited record); %s" + % (sp, how)] + if isinstance(g.get("mission"), dict): + if not mission_autonomy(cwd): + return False, ["%s's autonomy came from the mission, which is no longer approved in autonomous mode" + " (aloop mission check); %s" % (sp, how)] + if not mission_intent(cwd, sp): + return False, ["%s's plan serves no mission intent: the mission's autonomy covers only the sprints of its" + " own goals (`aloop mission goal next`); %s" % (sp, how)] + return True, "%s autonomous under mission %s (approved by %s)" % (sp, g["mission"].get("mission_id"), + g["mission"].get("by")) + bad = cited(cwd, g.get("prompt"), VERBS["autonomy"], g["sha256"], gs[:-1]) + if bad: + return False, ["the newest autonomy grant of %s is not the human's own words: %s." % (sp, bad[0]), " " + how] + return True, "%s autonomous, granted by %s, code %s" % (sp, who, M.code(g["sha256"])) + return False, ["the newest grant of %s is neither a plan approval nor an autonomy grant (a hand-written record);" + " %s" % (sp, how)] diff --git a/plugin/bin/_events.py b/plugin/bin/_events.py index 41471439..a1131e9f 100644 --- a/plugin/bin/_events.py +++ b/plugin/bin/_events.py @@ -102,27 +102,32 @@ def authority_file(cwd=None): return os.path.join(_paths.home(cwd, "state"), "authority.json") -def record_authority(cwd, initiated_by, autonomy_mode, scope, policy="default", overrides=None): +def record_authority(cwd, initiated_by, autonomy_mode, scope, policy="default", overrides=None, sprint="", grant=None): """The run's authority record (who started it, under which policy and approval mode, for which scope, with which overrides). Stored in .agentic/state/authority.json and - emitted as human.approval; decisions point at it.""" + emitted as human.approval; decisions point at it. `sprint` and `grant` are the human's + grant about that sprint (_approval.grant_for, ROADMAP M0.9): a plan grant also emits + plan.approved for the sprint's latest frozen plan.""" if autonomy_mode not in AUTONOMY: raise ValueError("autonomy_mode must be one of %s" % ", ".join(AUTONOMY)) if not initiated_by or not scope: raise ValueError("an authority record needs initiated_by and scope") auth = {"initiated_by": initiated_by, "policy": policy, "autonomy_mode": autonomy_mode, "scope": scope, "overrides": overrides or {}} + if sprint: + auth.update(sprint=sprint, grant=grant) eid = emit(cwd, "human.approval", role="human", authority=auth, refs={"authority": authority_file(cwd)}) auth["event_id"] = eid with open(authority_file(cwd), "w") as f: json.dump(auth, f, indent=1) plan = None for ev in read(cwd): - if ev.get("event") in ("plan.created", "plan.revised"): + if ev.get("event") in ("plan.created", "plan.revised") and isinstance(ev.get("data"), dict) \ + and ev["data"].get("sprint") == sprint: plan = ev - if plan: # the approval covers the latest frozen plan + if plan and (grant or {}).get("kind") == "plan": # the approval covers the sprint's latest frozen plan emit(cwd, "plan.approved", role="human", parent_event_id=eid, caused_by=plan.get("event_id"), - authority=auth, refs=plan.get("refs"), sprint=(plan.get("data") or {}).get("sprint", "")) + authority=auth, refs=plan.get("refs"), sprint=sprint, plan_sha256=grant.get("plan_sha256")) return eid diff --git a/plugin/bin/events b/plugin/bin/events index 269d6f58..ea82022b 100755 --- a/plugin/bin/events +++ b/plugin/bin/events @@ -16,15 +16,25 @@ Usage: its recorded decisions and the intent, never model prose events graph [--format json|dot] the stream as a graph (events, tasks, commits, intents; parent / caused_by / about edges); rebuildable, downstream - events authority --initiated-by WHO --mode reviewed|autonomous --scope "..." + events authority --initiated-by WHO --mode reviewed|autonomous --scope "..." [--sprint N] [--policy P] [--override key=value ...] the run's authority record (human.approval); - decisions default to it + decisions default to it. With a sprint (reviewed: the + latest frozen plan's by default) it is the human's grant + and counts only in their own typed line: until a captured + prompt says `approve SN ` (autonomous: `autonomous + SN `) it asks with that line (exit 3). An approved + autonomous mission is that word for its own sprints + events approval SPRINT|TASK_ID [--story-dir DIR] [--role ROLE] + may an execution role of that sprint be dispatched now, on + that STORY_DIR? (gate-dispatch asks): exit 0 yes, 2 no and why + (ROADMAP M0.9) events decide KIND --reason "one line" [--task T] [--evidence ref ...] [--authority EVENT_ID] structured rationale (plan|split|target| implementation|replan|acceptance) Emitting never fails a hook: an unknown event type is the only error (exit 64), besides the -human approvals, ethics verdicts and goal lineage of the mission layer, which only their own commands write. +human approvals (the authority record and plan.approved included), ethics verdicts and goal lineage of the +mission layer, which only their own commands write. """ import glob import json @@ -33,6 +43,7 @@ import re import sys sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) +import _approval # noqa: E402 import _events # noqa: E402 import _mission # noqa: E402 import _paths # noqa: E402 @@ -43,6 +54,8 @@ GATE_OWNED = set(_mission.HUMAN_EVENTS) | {"ethics.reviewed", "ethics.blocked", "door.denied", "door.crossed", # the door gate's own records (M9.30) "state.assessed", "eval.completed", # what goals are derived and closed from "intent.received"} # an intent's lineage (`intent new`) +# the human's grant of a sprint (ROADMAP M0.9): only `events authority` writes it, from their typed line +GATE_OWNED |= {"human.approval", "plan.approved"} def parse(argv): @@ -110,7 +123,13 @@ def trace(cwd, sha): a = appr[-1].get("authority") or {} print("approved %s (%s) scope=%r" % (a.get("initiated_by"), a.get("autonomy_mode"), a.get("scope"))) else: - print("approved (missing: no plan.approved for this plan)") + auto = [e for e in evs if e.get("event") == "human.approval" and (e.get("authority") or {}).get("sprint") == sprint + and (e.get("authority") or {}).get("autonomy_mode") == "autonomous" and e.get("ts", "") <= commit.get("ts", "")] + if auto: + a = auto[-1]["authority"] + print("approved %s (autonomous) scope=%r" % (a.get("initiated_by"), a.get("scope"))) + else: + print("approved (missing: no plan.approved for this plan)") return 0 @@ -241,9 +260,22 @@ def main(argv): if cmd in ("authority", "decide"): try: if cmd == "authority": - eid = _events.record_authority(cwd, opts.get("initiated_by", ""), opts.get("mode", ""), opts.get("scope", ""), - policy=opts.get("policy", "default"), - overrides=dict(o.split("=", 1) for o in opts["override"] if "=" in o)) + who, mode, scope = opts.get("initiated_by", ""), opts.get("mode", ""), opts.get("scope", "") + if mode not in _events.AUTONOMY or not who or not scope: + raise ValueError("need --initiated-by WHO --mode %s --scope \"...\"" % "|".join(_events.AUTONOMY)) + policy = opts.get("policy", "default") + overrides = dict(o.split("=", 1) for o in opts["override"] if "=" in o) + try: + sprint, grant = _approval.grant_for(cwd, who, mode, scope, opts.get("sprint", ""), policy, overrides) + except _mission.NeedsHuman as e: + print("ASK[events]: %s" % e, file=sys.stderr) + return 3 + eid = _events.record_authority(cwd, who, mode, scope, policy=policy, overrides=overrides, + sprint=sprint, grant=grant) + if grant: + print("[events] %s: the human's %s recorded (code %s)" % ( + sprint, "plan approval" if grant["kind"] == "plan" else "grant of autonomy", _mission.code(grant["sha256"])), + file=sys.stderr) else: eid = _events.record_decision(cwd, pos[0] if pos else "", opts.get("reason", ""), task=opts.get("task", ""), evidence=opts["evidence"], authority_ref=opts.get("authority"), @@ -253,6 +285,16 @@ def main(argv): return 64 print(eid) return 0 + if cmd == "approval": + if not pos: + print("events approval: need a SPRINT or TASK_ID", file=sys.stderr) + return 64 + good, why = _approval.check(cwd, pos[0], opts.get("story_dir", ""), opts.get("role", "")) + if good: + print(why) + return 0 + print("\n".join(why), file=sys.stderr) + return 2 if cmd == "query": for ev in _events.read(cwd): ids = ev.get("ids") or {} diff --git a/plugin/bin/gate-dispatch b/plugin/bin/gate-dispatch index 165d0a44..d0a69111 100755 --- a/plugin/bin/gate-dispatch +++ b/plugin/bin/gate-dispatch @@ -6,8 +6,13 @@ # worker's SubagentStop gate cannot find STORY_DIR and blocks on every stop — a block the worker # cannot fix (live e2e run 6: 25 blocks). So the dispatch itself is refused until it is right. # +# Nor is anything of a sprint dispatched before the human approved its plan (ROADMAP M0.9): the +# sprint's newest grant (`events authority`, the human's typed line) must still cover the plan as it is. +# # Only aloop execution roles, only from the main session (a sub-agent's own Agent calls carry -# agent_type), only in a repo with aloop state (.agentic/). Exit: 0 allow · 2 deny. SKIP_HOOKS=1. +# agent_type), only in a repo with aloop state (.agentic/). Every host: Claude Code's Agent/Task +# (subagent_type, prompt), Codex's spawn_agent (agent_type, message), OpenCode's task and dsh's +# subagent (both through their plugins). Exit: 0 allow · 2 deny. SKIP_HOOKS=1. set -uo pipefail GATE_NAME=dispatch [ "${SKIP_HOOKS:-}" = "1" ] && exit 0 @@ -15,16 +20,19 @@ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" payload="$(cat 2>/dev/null || true)" command -v python3 >/dev/null 2>&1 || exit 0 -read -r role tid model < <(printf '%s' "$payload" | python3 -c ' +read -r role tid model tool < <(printf '%s' "$payload" | python3 -c ' import json, re, sys p = json.load(sys.stdin) if p.get("agent_type"): - print("- - -"); sys.exit() + print("- - - -"); sys.exit() ti = p.get("tool_input") or {} -role = (ti.get("subagent_type") or "").split(":")[-1] -m = re.match(r"\s*TASK_ID:\s*([A-Za-z0-9._-]+)", ti.get("prompt") or "") +role = str(ti.get("subagent_type") or ti.get("agent_type") or "").split(":")[-1] # Codex: agent_type +text = ti.get("prompt") or ti.get("message") or "" # Codex: message (or items) +if not text and isinstance(ti.get("items"), list): + text = "\n".join(str(i.get("text") or "") for i in ti["items"] if isinstance(i, dict)) +m = re.match(r"\s*TASK_ID:\s*([A-Za-z0-9._-]+)", text if isinstance(text, str) else "") model = re.sub(r"\s+", "", str(ti.get("model") or "")) or "-" -print(role or "-", m.group(1) if m else "-", model)' 2>/dev/null) || exit 0 +print(re.sub(r"\s+", "", role) or "-", m.group(1) if m else "-", model, re.sub(r"\s+", "", str(p.get("tool_name") or "")) or "-")' 2>/dev/null) || exit 0 case "$role" in red-worker|scaffolder|green-worker|structural-reviewer|final-gate|planner|intake|standards|archivist) ;; market-researcher|product-tester|state-assessor|evaluator|mission-planner|ethics-reviewer) ;; # mission roles (§4.12) @@ -40,7 +48,11 @@ case "$role" in red-worker|scaffolder|green-worker|structural-reviewer|final-gat # `claude-haiku-5-5` are the same answer; an absent model would fall back to the agent file's # default (opus for the planning roles), so it is refused too. An empty resolution (Codex: the # session's own model) checks nothing. -want="$("$HERE/models" resolve "$role" 2>/dev/null)" || want="" +# Codex's spawn_agent and OpenCode's task name no model per call: the role's agent file `aloop install` +# wrote from the same routes pins it, so there only a model the call does name is checked. +host="${AGENTIC_HOST:-}"; [ -z "$host" ] && [ "$tool" = spawn_agent ] && host=codex +want="$("$HERE/models" resolve "$role" ${host:+--host "$host"} 2>/dev/null)" || want="" +case "$host:$model" in codex:-|opencode:-) want="" ;; esac if [ -n "$want" ]; then fam() { case "$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" in *haiku*) echo haiku ;; *sonnet*) echo sonnet ;; *opus*) echo opus ;; *) echo "" ;; esac; } bad=0 @@ -88,6 +100,15 @@ if [ -z "$sd" ] || [ ! -d "$sd" ]; then [ "$role" = structural-reviewer ] && echo " A structural review of a whole wave has no single story: use the sprint dir, docs/agents/sprintN/, and append its dispatch block to that dir's init.md." >&2 exit 2 fi +# The plan is the human's (ROADMAP M0.9): the sprint's newest grant must hold now: their approval of +# exactly this plan (the typed line `approve SN `), or autonomy they granted the sprint (their +# `autonomous SN `, or an approved autonomous mission for its own sprints), and STORY_DIR and the task +# are of that plan (another sprint's story or an unplanned task is not covered). Before this it was a +# playbook rule, so a supervisor could dispatch workers before the human said go (2026-10-20 fact check). +if ! why="$("$HERE/events" approval "$tid" --story-dir "$sd" --role "$role" 2>&1 >/dev/null)"; then + printf 'BLOCK[%s]: dispatch %s of %s: %s\n' "$GATE_NAME" "$role" "$tid" "${why:-the plan approval check failed}" >&2 + exit 2 +fi # A manual task worktree (`aloop task-worktree add`, the sanctioned equivalent of isolation: # "worktree" and the Codex/OpenCode route) carries a copy of the contract: `aloop bind` checks it # and the host binding needs it. Refreshed on every dispatch, since one task's contract changes role diff --git a/plugin/bin/gate-mission-scope b/plugin/bin/gate-mission-scope index 786dfe87..f3f930ae 100755 --- a/plugin/bin/gate-mission-scope +++ b/plugin/bin/gate-mission-scope @@ -16,9 +16,9 @@ A builder never grades its own work, and a grader never builds: docs/agents/mission/ but mission.json (the human's, sealed by `mission approve`) is dispatched; - NO ONE hand-writes docs/agents/mission/ledger.jsonl (only the mission CLI appends to it) or the captured prompts (/transcripts/, the UserPromptSubmit hook's), runs a hook's `transcripts prompt|record|…`, - or, where a mission is set, starts a host session from a tool call (`claude -p`, `codex exec`, - `opencode run`, `dsh `: its prompt would be captured as the human's words, which a grant - reads, M9.17). + or starts a host session from a tool call (`claude -p`, `codex exec`, `opencode run`, `dsh `: + its prompt would be captured as the human's words, which a mission grant (M9.17) and a sprint's plan + approval (M0.9) read). Write/Edit/patch paths are exact. A Bash command is read as the shell would read it (_shellread.py: quotes, escapes, line continuations, comments, heredoc bodies as data, reserved words, subshells, @@ -62,7 +62,7 @@ TRANSCRIPT_HOOKS = {"prompt", "record", "snapshot", "stop", "stage-in"} # the hosts, and their subcommands that start no session (any other word is a prompt or a session) HOSTS = {"claude": {"plugin", "plugins", "mcp", "config", "doctor", "update", "install", "migrate-installer", "setup-token"}, - "codex": {"login", "logout", "mcp", "completion", "debug", "apply", "a", "help", "features"}, + "codex": {"login", "logout", "mcp", "completion", "debug", "apply", "a", "help", "features", "plugin"}, "opencode": {"auth", "models", "upgrade", "mcp", "agent", "github", "stats", "export", "import", "uninstall", "debug", "help"}, "dsh": {"plugin"}} # dsh's first word is a profile to boot (aloop, headless…) @@ -270,9 +270,8 @@ class Scope: def host(self, name, args): """A host session started from a tool call (`claude -p`, `codex exec`, `opencode run`, `dsh`) fires its own - UserPromptSubmit hook, so its prompt would be captured as the human's words (M9.17).""" - if self.role not in self.R.ROLES and not os.path.isdir(os.path.join(self.main, self.R.MISSION)): - return # no mission here: no grant to forge + UserPromptSubmit hook, so its prompt would be captured as the human's words (M9.17). Every aloop project + has a grant to forge: a sprint's plan approval reads the same prompts (M0.9).""" ts = [text(a) for a in args] if ts and all(t in ("--version", "-v", "-V", "--help", "-h") for t in ts): return @@ -280,9 +279,9 @@ class Scope: if pos and pos[0] in HOSTS[name]: return # a tool of the host (plugin validate, mcp list), no session raise Block("%s starts a %s session from a tool call: its prompt fires the UserPromptSubmit hook and would be" - " captured as the human's own words, which a mission grant reads (M9.17).\n A role never starts" - " another agent; a session the human wants runs from their own terminal or the mission's cron line." - % (self.who or "the supervisor", name)) + " captured as the human's own words, which a mission grant (M9.17) and a plan approval (M0.9) read." + "\n A role never starts another agent; a session the human wants runs from their own terminal or the" + " mission's cron line." % (self.who or "the supervisor", name)) def git(self, args, base): """Judge a git command: a mission role never writes the project's repo.""" diff --git a/plugin/bin/transcripts b/plugin/bin/transcripts index 8dbf2585..1e365ba5 100755 --- a/plugin/bin/transcripts +++ b/plugin/bin/transcripts @@ -20,7 +20,7 @@ # transcripts snapshot copy the full session transcript (stdin JSON) [Stop] # transcripts stop snapshot + remove ./.transcripts + stop marker [SubagentStop *] # transcripts view --all|--task ID read the store (supervisor) -# transcripts prune manual: keep last N events/task (AGENTIC_TRANSCRIPTS_KEEP, default all) +# transcripts prune manual: keep last N tool records/task and every prompt (AGENTIC_TRANSCRIPTS_KEEP) # # Per-worktree contract: the supervisor writes ./.aladdin/task.env (./.agentic/ in a legacy project) at dispatch with # TASK_ID, ATTEMPT, AGENT_ROLE (real env overrides it). The store path is fixed (_paths.sh). @@ -138,12 +138,15 @@ case "$cmd" in prune) ensure; N="${AGENTIC_TRANSCRIPTS_KEEP:-}" [ -n "$N" ] || { echo "set AGENTIC_TRANSCRIPTS_KEEP= to prune (default keeps everything)"; exit 0; } + # The human's prompts stay: a grant (M9.17, a sprint's plan approval M0.9) cites one, so pruning it + # would revoke the grant. Only tool-call records are compacted. for d in "$STORE"/*/; do f="${d}events.jsonl"; [ -f "$f" ] || continue - n="$(wc -l < "$f" 2>/dev/null || echo 0)" + n="$(grep -cv '"kind": *"prompt"' "$f" 2>/dev/null || true)" if [ "${n:-0}" -gt "$N" ]; then - head -n "$((n-N))" "$f" >> "$STORE/compacted/$(basename "$d").jsonl" 2>/dev/null || true - tail -n "$N" "$f" > "$f.tmp" 2>/dev/null && mv "$f.tmp" "$f" 2>/dev/null || true + : > "$f.tmp" && awk -v drop="$((n-N))" -v out="$STORE/compacted/$(basename "$d").jsonl" -v tmp="$f.tmp" ' + !/"kind": *"prompt"/ && ++k <= drop { print >> out; next } { print > tmp }' "$f" 2>/dev/null \ + && mv "$f.tmp" "$f" 2>/dev/null || true fi done echo "pruned (keep $N/task)";; diff --git a/plugin/hosts/opencode/aloop.js b/plugin/hosts/opencode/aloop.js index 2c3aa58e..6be10b33 100644 --- a/plugin/hosts/opencode/aloop.js +++ b/plugin/hosts/opencode/aloop.js @@ -10,7 +10,7 @@ // UserPromptSubmit chat.message on a root session → transcripts prompt, intent-trigger // (its context goes into the next turn's system prompt) // PreToolUse tool.execute.before → host-adapter, gate-supervisor-scope, -// gate-commit-author, budget pre; a deny THROWS (the tool call fails +// gate-commit-author, gate-dispatch (task), budget pre; a deny THROWS (the tool call fails // with the reason). Bound workers' commands/edits are REWRITTEN into // their worktree (bash workdir, file paths, patch headers). // PostToolUse tool.execute.after → transcripts record, budget post; context is @@ -208,6 +208,7 @@ export const AgenticAgile = async ({ client, directory, worktree }) => { if (EDITS.has(input.tool)) checks.push(["gate-supervisor-scope", []]) if (EDITS.has(input.tool) || input.tool === "bash") checks.push(["gate-mission-scope", []]) // role path guards if (input.tool === "bash") checks.push(["gate-commit-author", []]) + if (input.tool === "task") checks.push(["gate-dispatch", []]) // the task contract and the plan approval (M0.9) checks.push(["budget", ["hook", "pre"]]) for (const [script, a] of checks) { const why = denyOf(run(script, a, p)) diff --git a/plugin/mission/README.md b/plugin/mission/README.md index 00b18aa5..c121b675 100644 --- a/plugin/mission/README.md +++ b/plugin/mission/README.md @@ -140,8 +140,8 @@ A gate checks structure and evidence, never whether a judgment is right. - **M9.11 goals.** Add `mission` to the `intent` SOURCES. `gate-intake` checks the newest `int_*.json` by mtime and `ids freeze` links a plan to the last `intent.normalized` anywhere, so queued mission intents need an explicit link (built: `goal next` makes the intent it hands off the - newest file before normalizing it). `record_authority` also approves the latest plan: - record a goal's authority only after its sprint's `ids freeze`. `aladdin ""` refuses a + newest file before normalizing it). `events authority --sprint N` approves the sprint's latest + plan (M0.9): record it only after the sprint's `ids freeze` (reviewed mode refuses a sprint with no frozen plan). `aladdin ""` refuses a bare intent containing `/`; use `aladdin run`. - **M9.30 doors.** `doors.json` is the catalogue (anything unlisted is two-way; `{DEF}` is the default branch, `{DRY}` "not a dry run or a help page"); `doors.py` reads Bash as the shell does (with @@ -159,7 +159,8 @@ A gate checks structure and evidence, never whether a judgment is right. `UserPromptSubmit` too. M9.9 denies roles writes under `.aladdin/transcripts/` and `docs/agents/mission/ledger.jsonl`, running `transcripts prompt`, and a Bash command that starts a host session with a grant line. - `events authority` (the sprint's `human.approval`) still trusts `--initiated-by`. + `events authority` no longer trusts `--initiated-by` alone (M0.9): a sprint's grant cites the human's typed + `approve SN ` / `autonomous SN ` line, or the approved autonomous mission, and `gate-dispatch` checks it. - **Rivals (M9.1 → M9.10).** A baseline's `rivals` are claim refs today; the Product Tester's values per benchmark and metric belong in a keyed object so `evaluate` can compare against them. - **M9.6 telemetry.** `journeys.GA4_RESERVED_NAMES` is the one reserved-name list (the union of both diff --git a/plugin/skills/aloop/SKILL.md b/plugin/skills/aloop/SKILL.md index 6d48a1ba..1eae66ab 100644 --- a/plugin/skills/aloop/SKILL.md +++ b/plugin/skills/aloop/SKILL.md @@ -110,7 +110,8 @@ If a backend reports "not installed", run `ensure-tools --sync` once (needs carg current one) and run intake → planner before any RED. Silently switching into ad-hoc implementation is the bypass this skill exists to prevent. "Improve X" and "fix the broken Y" are sprint triggers, not invitations to edit files directly. -- The human is absent from execution. Never block waiting for human input mid-run. +- The human is absent from execution: never wait for them mid-run, except a reviewed + re-plan changes the plan they approved, so it waits for their line. - **You own all planning artifacts.** Sub-agents NEVER edit `stories.md`, `tasks.md`, `validate.md`, `plan.md`, `plan-ready.md`, or `sprintN/plan.md`. - **You NEVER write production source — in any phase.** Every line of code (tests, @@ -271,17 +272,18 @@ sprint at a time: dispatch the planner, review its output, present it for the hu approval, then — only on "go" — start that sprint's execution. Do NOT batch-write every future sprint's Stage-2 and chain straight into execution. -**Autonomous mode** is explicit, never inferred: the human chooses it at run start -(`events authority --mode autonomous`, and `AGENTIC_AUTONOMY_MODE=autonomous` for the -gates). Then the generated plan goes through the deterministic planning checks -(gate-intake incl. `intent check`, gate-stage2-complete) and straight into execution, -with no approval step, unless an escalation class is hit: an unanswered `ask` question -(`intent check` exit 3), a scope change, or the re-plan cap. Reviewed mode stays the default. - -**Provenance (on "go", and at every durable boundary).** Record who approved what, once -per sprint, before the first dispatch: -`events authority --initiated-by --mode reviewed|autonomous --scope "sprint N as approved"` -(plus `--override KEY=VALUE` for any limit the human changed). At each split, re-plan, +**Autonomous mode** is explicit, never inferred, and per sprint: the human grants it with +the line `events authority --mode autonomous --sprint N` asks for (or by approving an +autonomous mission), plus `AGENTIC_AUTONOMY_MODE=autonomous` for the gates. Then the plan +and its re-plans go through the deterministic planning checks (gate-intake incl. `intent +check`, gate-stage2-complete) and straight into execution, unless an escalation class is +hit: an unanswered `ask` question (`intent check` exit 3), a scope change, or the re-plan cap. + +**Approval is a gate.** `gate-dispatch` starts no execution role of a sprint until the +human approved its plan as it is now: +`events authority --initiated-by --mode reviewed|autonomous --scope "sprint N as approved" --sprint N` +(`--override KEY=VALUE` too) exits 3 with a line like `approve S1 1a2b3c4d`: relay it, the +human types it, run it again. Never type it yourself. At each split, re-plan, target or acceptance decision, record ONE line of rationale with its evidence: `events decide split|replan|acceptance|… --task SN-NN-Tk --reason "" --evidence `. No chain-of-thought — a reason, refs and the authority (`events lineage ` shows it). @@ -665,8 +667,7 @@ escalation is what happens when revision is exhausted. - PLANNING is a normal interactive session — the human is in the loop; the clarify/conflict/re-plan loops are human-bounded. -- EXECUTION is an autonomous run ("run until the sprint gate is green") and takes - no mid-run human input by design. +- EXECUTION is an autonomous run ("run until the sprint gate is green"). - **ONE sprint per autonomous run.** Execution is scoped to a single sprint — its FINAL-GATE is the finish line. When it passes, STOP and report; the human decides whether to start the next sprint, which RE-ENTERS interactive planning (dispatch the diff --git a/plugin/skills/aloop/reference.md b/plugin/skills/aloop/reference.md index aebdb2cb..ff3dfd29 100644 --- a/plugin/skills/aloop/reference.md +++ b/plugin/skills/aloop/reference.md @@ -51,6 +51,10 @@ again. Instead: 4. **Re-validate:** `gate-stage2-complete docs/agents/sprintN` must pass again. Log `replan SN-NN complete Tn`. 5. **Resume** the sprint: dispatch the new tasks (from RED) and continue the loop. + Reviewed mode: the re-plan changed the plan, so `gate-dispatch` blocks every dispatch of the + sprint until the human approves the new plan: run `events authority … --sprint N` again and + relay the `approve SN ` line it asks for (ROADMAP M0.9). An autonomous grant for the + sprint covers its re-plans. ### Breach classes (classify before you split) @@ -131,7 +135,8 @@ All of these are on PATH — call them by bare name. - Real isolation = the global store is never staged into the worktree. The read-only chmod is the softer "not yours to write" signal (defeatable, but it errors loudly). - Retention: everything is kept (no auto-compaction). `transcripts prune` is a manual, - opt-in cap (`AGENTIC_TRANSCRIPTS_KEEP=`) if disk gets tight. + opt-in cap (`AGENTIC_TRANSCRIPTS_KEEP=`) if disk gets tight; it keeps the human's prompts, + which their grants cite. ## Worktree hygiene (bin/worktree-hygiene) - SubagentStart (exec roles) sparse-checkout-excludes `docs/agents/` from the new diff --git a/plugin/skills/mission/SKILL.md b/plugin/skills/mission/SKILL.md index f39daa2f..5b65be31 100644 --- a/plugin/skills/mission/SKILL.md +++ b/plugin/skills/mission/SKILL.md @@ -79,8 +79,8 @@ paste artifacts into it. A role writes its artifact only through `aloop mission | `CONFIRM_BASELINE` | human | In plain words: the journeys, where we are, where the rivals are. Relay the `confirm ` line tick names; once they have typed it, `aloop mission baseline confirm --by`; a no is `veto --by --reason`. | a confirmed or vetoed version | | `OFFER_OPTIONS` | `mission-planner`, then human | Spoon-fed: show the eval's ranked gaps (`aloop mission goal options`), one line each, recommended first; their pick derives the goal (`aloop mission goal derive --pick GAP_ID --by ""`). | a goal with `goal.approved` | | `PLAN_INTENTS` | `mission-planner` | Turn the goal's gaps into Aladdin intents, source `mission` (`aloop mission goal intents `). | the goal is active | -| `SPRINT` | supervisor | `aloop mission goal next ` makes the next intent current; load the aloop skill and run one sprint on it. Autonomous: `aloop events authority --initiated-by "" --mode autonomous --scope "mission , goal "`; spoon-fed: reviewed mode, one intent at a time. | Aladdin's final gate closes the sprint | -| `APPROVE_PLAN` | human | Spoon-fed: show the sprint's plan in one screen. On their go, `aloop events authority --initiated-by "" --mode reviewed --scope "mission , goal "` (it records `plan.approved`). | the plan is approved | +| `SPRINT` | supervisor | `aloop mission goal next ` makes the next intent current; load the aloop skill and run one sprint on it (that intent is the sprint's contract: no `intent new`). Autonomous: `aloop events authority --initiated-by "" --mode autonomous --scope "mission , goal " --sprint N` (the approved autonomous mission is the grant: no line to type); spoon-fed: reviewed mode, one intent at a time. | Aladdin's final gate closes the sprint | +| `APPROVE_PLAN` | human | Spoon-fed: show the sprint's plan in one screen. Then `aloop events authority --initiated-by "" --mode reviewed --scope "mission , goal " --sprint N`: it exits 3 with the line `approve SN `; they type it, run it again (it records `plan.approved`; no dispatch before it). | the plan is approved | | `ASSESS` | `state-assessor` | Measure the product with the pinned scripts; numbers only, no opinions (`aloop mission assess`). | a new state report | | `EVALUATE` | `evaluator` | Compare the state with the baseline and the rivals: the gap list and `goal_met` (`aloop mission evaluate`); it never builds. A goal met in its eval: `aloop mission goal close --eval `. | a new eval, or a closed goal | | `DERIVE_GOAL` | `mission-planner` | The eval's top gaps become one goal, with the standing principles for the mode (`aloop mission goal derive`). | a derived goal | diff --git a/scripts/smoke/e2e-live.sh b/scripts/smoke/e2e-live.sh index 18638233..ae82afa8 100755 --- a/scripts/smoke/e2e-live.sh +++ b/scripts/smoke/e2e-live.sh @@ -172,8 +172,16 @@ ALOOP_NO_HOST_RERENDER=1 "$PLUGIN/bin/aloop-init" --apply MODEL_PLANNING="${WORK [ "$HOST" = claude ] || "$PLUGIN/bin/install" "$HOST" --project . >/dev/null git add -A && git commit -qm "aloop init" >/dev/null 2>&1 || true +# The approval given up front is the human's own typed line (ROADMAP M0.9): gate-dispatch admits no +# worker before it. The run is autonomous for sprint 1, so the line names that authority record, +# whose code is known before the plan exists; the prompt carries it as the human's words. +AUTH=(--initiated-by "e2e human" --mode autonomous --scope "the e2e run" --sprint 1) +GRANT="$("$PLUGIN/bin/events" authority "${AUTH[@]}" 2>&1 >/dev/null | sed -n 's/.*they reply \(autonomous S1 [0-9a-f]\{8\}\) .*/\1/p')" +[ -n "$GRANT" ] || { echo "e2e: no autonomy line from aloop events authority" >&2; exit 1; } PROMPT="Use the aloop skill. Intent: $INTENT -I am the human. I approve in advance: accept your recommended answer to every question, approve the plan as you propose it, and do not wait for me. Run the whole loop without stopping: retrospective (none yet), intake, standards, planner, then execution (RED, SCAFFOLD, GREEN per task, structural review, final gate), merging each passed task into main. Finish with the final gate green. Then print one line: E2E-DONE." +I am the human. I approve in advance: accept your recommended answer to every question, approve the plan as you propose it, and do not wait for me. Sprint 1 runs autonomously: before the first dispatch, record my grant with exactly \`aloop events authority --initiated-by \"e2e human\" --mode autonomous --scope \"the e2e run\" --sprint 1\`. My line for it: +$GRANT +Run the whole loop without stopping: retrospective (none yet), intake, standards, planner, then execution (RED, SCAFFOLD, GREEN per task, structural review, final gate), merging each passed task into main. Finish with the final gate green. Then print one line: E2E-DONE." case "$HOST" in claude) CMD=(claude -p --plugin-dir "$PLUGIN" --model "$SUP_MODEL" --output-format stream-json --verbose --max-turns 400 diff --git a/scripts/test/budget-contract.test.py b/scripts/test/budget-contract.test.py index fd70320d..8c3b0785 100644 --- a/scripts/test/budget-contract.test.py +++ b/scripts/test/budget-contract.test.py @@ -13,8 +13,12 @@ import os import shutil import subprocess +import sys import tempfile +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")) +from plan_fixture import approve_plan # noqa: E402 + BIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "plugin", "bin") T = tempfile.mkdtemp(prefix="aloop-contract-") atexit.register(shutil.rmtree, T, ignore_errors=True) @@ -91,6 +95,7 @@ def kv(task): assert budget("S1-01-T1", "--role", "red-worker", "--story", story).returncode == 0 and ini(story) == kept ok("init.md gets its 'type: init' frontmatter: created, or put on top of a file without one; never rewritten") +approve_plan(T, ENV, 1) # the human's go on sprint 1 (M0.9) gate = subprocess.run([os.path.join(BIN, "gate-dispatch")], cwd=T, env=ENV, capture_output=True, text=True, input=json.dumps( {"session_id": "s", "cwd": T, "tool_name": "Agent", "tool_input": { "subagent_type": "aloop:red-worker", "prompt": "TASK_ID: S1-01-T2\nDo RED.", "isolation": "worktree", "model": "haiku"}})) diff --git a/scripts/test/codex-hooks.test.py b/scripts/test/codex-hooks.test.py index 31df8252..b028b7ee 100644 --- a/scripts/test/codex-hooks.test.py +++ b/scripts/test/codex-hooks.test.py @@ -17,6 +17,9 @@ import sys import tempfile +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")) +from plan_fixture import approve_plan # noqa: E402 + ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "plugin")) BIN = os.path.join(ROOT, "bin") HOOKS = json.load(open(os.path.join(ROOT, "hooks", "hooks.json")))["hooks"] @@ -123,6 +126,20 @@ def rollout(thread, rows): why = denied(fire("PreToolUse", dict(base, tool_name="Bash", tool_input={"command": "git commit -m 'x\n\nCo-Authored-By: Claude '"}))) assert why and "co-author" in why.lower(); ok("commit-author blocks a Claude trailer") +# dispatch: Codex's spawn_agent ({agent_type, message}) runs gate-dispatch through the `Agent` matcher: the +# TASK_ID line, the task contract, then the human's plan approval (ROADMAP M0.9); no model per call is fine +spawn = lambda msg: dict(base, tool_name="spawn_agent", tool_input={"agent_type": "green-worker", "message": msg}) # noqa: E731 +why = denied(fire("PreToolUse", spawn("go green"))) +assert why and "TASK_ID: " in why, why +os.makedirs(os.path.join(T, ".aladdin/state/tasks"), exist_ok=True) +open(os.path.join(T, ".aladdin/state/tasks/S1-01-T9.env"), "w").write( + "TASK_ID=S1-01-T9\nATTEMPT=1\nAGENT_ROLE=green-worker\nSTORY_DIR=%s\n" % os.path.join(T, "docs/agents/sprint1/s1-01-x")) +why = denied(fire("PreToolUse", spawn("TASK_ID: S1-01-T9\nGREEN"))) +assert why and "has not approved the plan of S1" in why, why +approve_plan(T, ENV) +assert not denied(fire("PreToolUse", spawn("TASK_ID: S1-01-T9\nGREEN"))) +ok("spawn_agent is gated: its TASK_ID line, its contract and the human's approval of the sprint's plan") + # worker: SubagentStart registers; unbound writes refused; bind; confinement worker = dict(base, agent_id="th-red", agent_type="red-worker") fire("SubagentStart", worker) diff --git a/scripts/test/commit-trace.test.py b/scripts/test/commit-trace.test.py index de0b638c..3343449d 100644 --- a/scripts/test/commit-trace.test.py +++ b/scripts/test/commit-trace.test.py @@ -8,8 +8,12 @@ import json import os import subprocess +import sys import tempfile +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")) +from mission_fixture import as_human # noqa: E402 + ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "plugin")) BIN = os.path.join(ROOT, "bin") T = tempfile.mkdtemp(prefix="agentic-trace-") @@ -64,8 +68,12 @@ def events(): assert len([e for e in events() if e["event"] in ("plan.created", "plan.revised")]) == 1 ok("gate-stage2-complete emits plan.created once, caused by intent.normalized (unchanged re-run is silent)") -# approval → plan.approved for that plan -sh(os.path.join(BIN, "events"), "authority", "--initiated-by", "adeel", "--mode", "reviewed", "--scope", "sprint 1 as approved") +# approval → plan.approved for that plan, once the human typed the line it asks for (M0.9) +AUTH = (os.path.join(BIN, "events"), "authority", "--initiated-by", "adeel", "--mode", "reviewed", "--scope", "sprint 1 as approved") +r = sh(*AUTH, check=False) +assert r.returncode == 3 and "they reply approve S1 " in r.stderr and not [e for e in events() if e["event"] == "plan.approved"], r +r = as_human(lambda: sh(*AUTH, check=False), T, ENV) +assert r.returncode == 0, r.stderr appr = [e for e in events() if e["event"] == "plan.approved"] assert len(appr) == 1 and appr[0]["caused_by"] == plan[0]["event_id"] and appr[0]["authority"]["initiated_by"] == "adeel" ok("events authority emits plan.approved linked to the latest plan") diff --git a/scripts/test/dispatch.test.py b/scripts/test/dispatch.test.py index ea6c41ac..82b1b619 100644 --- a/scripts/test/dispatch.test.py +++ b/scripts/test/dispatch.test.py @@ -10,12 +10,16 @@ import os import shutil import subprocess +import sys import tempfile +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")) +from plan_fixture import approve_plan # noqa: E402 + GATE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "plugin", "bin", "gate-dispatch") T = tempfile.mkdtemp(prefix="aloop-dispatch-") atexit.register(shutil.rmtree, T, ignore_errors=True) -ENV = {k: v for k, v in os.environ.items() if k != "SKIP_HOOKS"} +ENV = {k: v for k, v in os.environ.items() if k not in ("SKIP_HOOKS", "AGENTIC_HOST")} n = 0 @@ -40,6 +44,7 @@ def run(subagent_type, prompt, agent_type=None, model="haiku"): os.makedirs(os.path.join(T, "docs", "agents")) open(os.path.join(T, "docs", "agents", "defaults.md"), "w").write( "---\ntype: agentic-defaults\n---\n```conf\nAGENTIC_MODEL_PLANNING=haiku\nAGENTIC_MODEL_WORKER=haiku\n```\n") +approve_plan(T, ENV, 1) # the human approved sprint 1's plan (M0.9; plan-approval.test.py checks that gate) r = run("aloop:green-worker", "TASK_ID: S1-01-T1\nDo GREEN.") assert r.returncode == 2 and "S1-01-T1.env" in r.stderr, r diff --git a/scripts/test/dsh-plugin.test.mjs b/scripts/test/dsh-plugin.test.mjs index d3d55026..b462e0a1 100644 --- a/scripts/test/dsh-plugin.test.mjs +++ b/scripts/test/dsh-plugin.test.mjs @@ -9,6 +9,7 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { fileURLToPath } from "node:url" import assert from "node:assert/strict" +import { approvePlan } from "./fixtures/plan-fixture.mjs" const ROOT = join(fileURLToPath(import.meta.url), "..", "..", "..", "plugin") const BIN = join(ROOT, "bin") @@ -120,9 +121,11 @@ assert.ok(denied(await pre(h, root, "subagent", red), /write the task contract/) mkdirSync(join(T, ".aladdin/state/tasks"), { recursive: true }) writeFileSync(join(T, ".aladdin/state/tasks/S1-01-T1.env"), `TASK_ID=S1-01-T1\nATTEMPT=1\nAGENT_ROLE=red-worker\nSTORY_DIR=${story}\n`) const wt = sh(join(BIN, "task-worktree"), ["add", "S1-01-T1"]).trim() +assert.ok(denied(await pre(h, root, "subagent", { ...red, cwd: wt }), /has not approved the plan of S1/)) +approvePlan(T, BIN) // the human's go on sprint 1 (M0.9) assert.ok(allowed(await pre(h, root, "subagent", { ...red, cwd: wt }))) assert.ok(readFileSync(join(wt, ".aladdin/task.env"), "utf8").includes("STORY_DIR="), "gate-dispatch copies the contract into the worktree") -ok("dispatch: no role, no TASK_ID line or no task contract is refused; a complete one is admitted") +ok("dispatch: no role, no TASK_ID line, no task contract or no plan approval is refused; a complete, approved one is admitted") const stale = host({ root: ROOT, models: { subagent: "deepseek-v4-pro" } }) // rendered before MODEL_WORKER changed plugin.apply(stale.ctx, stale.config) await stale.on["agent/created"]({ agent: agentOf("root"), source: "startup" }) diff --git a/scripts/test/dsh-runtime.test.mjs b/scripts/test/dsh-runtime.test.mjs index 2569e3d3..e7d3d7df 100644 --- a/scripts/test/dsh-runtime.test.mjs +++ b/scripts/test/dsh-runtime.test.mjs @@ -15,6 +15,7 @@ import { tmpdir } from "node:os" import { delimiter, join, relative } from "node:path" import { fileURLToPath } from "node:url" import assert from "node:assert/strict" +import { approvePlan } from "./fixtures/plan-fixture.mjs" const HERE = join(fileURLToPath(import.meta.url), "..") const ROOT = join(HERE, "..", "..", "plugin") @@ -59,6 +60,7 @@ assert.ok(existsSync(join(env.DSH_HOME, "profiles/aloop/cordis.patch.yml")) && e mkdirSync(join(P, ".aladdin/state/tasks"), { recursive: true }) writeFileSync(join(P, ".aladdin/state/tasks/S1-01-T1.env"), `TASK_ID=S1-01-T1\nATTEMPT=1\nAGENT_ROLE=red-worker\nSTORY_DIR=${story}\n`) const wt = sh(join(BIN, "task-worktree"), ["add", "S1-01-T1"]).trim() +approvePlan(P, BIN, 1, env) // the human's go on sprint 1 (M0.9): gate-dispatch admits nothing before it const red = "TASK_ID: S1-01-T1\nYour worktree: " + wt + ". First command: `aloop bind " + wt + "`." const script = { diff --git a/scripts/test/e2e-live-hosts.test.py b/scripts/test/e2e-live-hosts.test.py index aca86f99..7bcbae3e 100755 --- a/scripts/test/e2e-live-hosts.test.py +++ b/scripts/test/e2e-live-hosts.test.py @@ -117,6 +117,22 @@ def run(*args, env=ENV): assert "E2E-DONE" not in cmd and "prompt: stdin" in r.stdout, cmd ok("default host is claude: claude -p --plugin-dir … with the prompt on stdin (no host install)") +# 3b) the approval given up front is the human's typed line (ROADMAP M0.9): the prompt carries the line that +# grants sprint 1 autonomy, and that line, captured as the human's words, is what the recorded grant cites +r, d = run("--host", "opencode") +grant = re.search(r"^autonomous S1 [0-9a-f]{8}$", r.stdout, re.M) +assert grant and "--mode autonomous" in r.stdout and "--sprint 1" in r.stdout, r.stdout +repo = os.path.join(d, "repo") +AUTH = [os.path.join(BIN, "events"), "authority", "--initiated-by", "e2e human", "--mode", "autonomous", "--scope", "the e2e run", + "--sprint", "1"] +assert subprocess.run(AUTH, cwd=repo, env=ENV, capture_output=True, text=True).returncode == 3 # not before the human's words +subprocess.run([os.path.join(BIN, "transcripts"), "prompt"], cwd=repo, env=ENV, check=True, capture_output=True, text=True, + input=json.dumps({"hook_event_name": "UserPromptSubmit", "session_id": "e2e", "prompt": "Use the aloop skill.\n" + + grant.group(0) + "\nRun the whole loop."})) +r = subprocess.run(AUTH, cwd=repo, env=ENV, capture_output=True, text=True) +assert r.returncode == 0, r.stderr +ok("the e2e prompt carries the human's line granting sprint 1 autonomy; captured, it records that grant") + # 4) an unknown host or a missing CLI is a usage error before anything is seeded or spent r, _ = run("--host", "cursor") assert r.returncode == 2 and "cursor" in r.stdout + r.stderr, (r.returncode, r.stdout, r.stderr) diff --git a/scripts/test/events.test.py b/scripts/test/events.test.py index 7d36c7e5..1c71fcd8 100644 --- a/scripts/test/events.test.py +++ b/scripts/test/events.test.py @@ -8,8 +8,12 @@ import json import os import subprocess +import sys import tempfile +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")) +from mission_fixture import as_human # noqa: E402 + ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "plugin")) BIN = os.path.join(ROOT, "bin") T = tempfile.mkdtemp(prefix="agentic-events-") @@ -97,8 +101,14 @@ def events(): # 6) authority + decisions: a decision without an authority is refused; with one it links r = run(EV, "decide", "split", "--task", "S1-02-T3", "--reason", "too large") assert r.returncode == 64 and "no authority" in r.stderr, r.stderr -auth = sh(EV, "authority", "--initiated-by", "adeel", "--mode", "autonomous", "--scope", "sprint 1 as approved", - "--override", "TOKENS_HARD=300000") +AUTH = (EV, "authority", "--initiated-by", "adeel", "--mode", "autonomous", "--scope", "sprint 1 as approved", + "--override", "TOKENS_HARD=300000") +assert run(*AUTH).returncode == 64 # autonomy names its sprint (M0.9) +assert run(*AUTH, "--sprint", "1").returncode == 3 # and is the human's typed line +os.makedirs(os.path.join(T, "docs", "agents"), exist_ok=True) # an aloop project: its hook captures the human's prompts +r = as_human(lambda: run(*AUTH, "--sprint", "1"), T, ENV) +assert r.returncode == 0, r.stderr +auth = r.stdout.strip() assert run(EV, "authority", "--initiated-by", "x", "--mode", "yolo", "--scope", "s").returncode == 64 a = json.load(open(os.path.join(T, ".aladdin", "state", "authority.json"))) assert a["event_id"] == auth and a["autonomy_mode"] == "autonomous" and a["overrides"] == {"TOKENS_HARD": "300000"} diff --git a/scripts/test/fixtures/plan-fixture.mjs b/scripts/test/fixtures/plan-fixture.mjs new file mode 100644 index 00000000..4df7445a --- /dev/null +++ b/scripts/test/fixtures/plan-fixture.mjs @@ -0,0 +1,29 @@ +// plan-fixture.mjs — the human's approval of a sprint's plan in a test project (ROADMAP M0.9), for +// the host tests that dispatch an execution role: gate-dispatch admits none before it. +// import { approvePlan } from "./fixtures/plan-fixture.mjs" +// approvePlan(projectDir, binDir) // sprint 1: a plan record when none, then the human types the line asked for +import { spawnSync } from "node:child_process" +import { existsSync, mkdirSync, readFileSync } from "node:fs" +import { join } from "node:path" + +export function approvePlan(cwd, bin, sprint = 1, env = process.env) { + const run = (cmd, args, input) => spawnSync(join(bin, cmd), args, { cwd, env, input, encoding: "utf8" }) + mkdirSync(join(cwd, "docs/agents", `sprint${sprint}`), { recursive: true }) + const log = join(cwd, ".aladdin/logs/events.jsonl") + const planned = existsSync(log) && readFileSync(log, "utf8").split("\n").filter(Boolean).some((l) => { + try { const e = JSON.parse(l); return /^plan\.(created|revised)$/.test(e.event) && e.data?.sprint === `S${sprint}` } catch { return false } + }) + if (!planned) { // what `ids freeze` records when gate-stage2-complete passes + const r = run("events", ["emit", "plan.created", "--role", "planner", "--data", `sprint=S${sprint}`]) + if (r.status !== 0) throw new Error(`plan.created: ${r.stderr}`) + } + const args = ["authority", "--initiated-by", "tester", "--mode", "reviewed", "--scope", `sprint ${sprint} as approved`, "--sprint", String(sprint)] + let r = run("events", args) + const m = r.status === 3 && /they reply {2}(.+?) {2}\(the code/.exec(r.stderr) + if (m) { // the human types the line; the UserPromptSubmit hook captures it + run("transcripts", ["prompt"], JSON.stringify({ hook_event_name: "UserPromptSubmit", session_id: "s-human", prompt: m[1] })) + r = run("events", args) + } + if (r.status !== 0) throw new Error(`events authority: ${r.status} ${r.stderr}`) + return r.stdout.trim() +} diff --git a/scripts/test/fixtures/plan_fixture.py b/scripts/test/fixtures/plan_fixture.py new file mode 100644 index 00000000..4d071cac --- /dev/null +++ b/scripts/test/fixtures/plan_fixture.py @@ -0,0 +1,33 @@ +"""plan_fixture.py — the human's approval of a sprint's plan in a test project (ROADMAP M0.9). + + from plan_fixture import approve_plan + approve_plan(cwd, env) # sprint 1: a plan record when none, then the human types the line it asks for + +gate-dispatch admits no execution role of a sprint before this, so every test that dispatches one +approves its sprint first, the way the human does: `events authority` asks (exit 3) for +`approve SN `, the human types it (the UserPromptSubmit hook captures it), and it runs again. +""" +import json +import os +import subprocess + +from mission_fixture import BIN, as_human + +EV = os.path.join(BIN, "events") + + +def approve_plan(cwd, env, sprint=1, by="tester", mode="reviewed"): + """Approve sprint N's plan as it is now (mode autonomous: grant it autonomy); returns the grant's event id.""" + os.makedirs(os.path.join(cwd, "docs", "agents", "sprint%d" % sprint), exist_ok=True) + log = os.path.join(cwd, ".aladdin", "logs", "events.jsonl") + seen = [json.loads(ln) for ln in open(log)] if os.path.exists(log) else [] + if not any(e.get("event") in ("plan.created", "plan.revised") and (e.get("data") or {}).get("sprint") == "S%d" % sprint + for e in seen): # what `ids freeze` records when gate-stage2-complete passes + r = subprocess.run([EV, "emit", "plan.created", "--role", "planner", "--data", "sprint=S%d" % sprint], + cwd=cwd, env=env, capture_output=True, text=True) + assert r.returncode == 0, r.stderr + args = [EV, "authority", "--initiated-by", by, "--mode", mode, "--scope", "sprint %d as approved" % sprint, + "--sprint", str(sprint)] + r = as_human(lambda: subprocess.run(args, cwd=cwd, env=env, capture_output=True, text=True), cwd, env) + assert r.returncode == 0, r.stderr + return r.stdout.strip() diff --git a/scripts/test/layout.test.py b/scripts/test/layout.test.py index a9ce7c85..1263aa3a 100755 --- a/scripts/test/layout.test.py +++ b/scripts/test/layout.test.py @@ -9,8 +9,12 @@ import json import os import subprocess +import sys import tempfile +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures")) +from plan_fixture import approve_plan # noqa: E402 + ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "plugin")) BIN = os.path.join(ROOT, "bin") PASS = [0] @@ -107,22 +111,23 @@ def sh_home(t, **env): sd = os.path.join(C, "docs", "agents", "sprint1", "s1-01-x") os.makedirs(sd) os.makedirs(os.path.join(C, ".agentic", "state", "tasks")) -open(os.path.join(C, ".agentic", "state", "tasks", "T1.env"), "w").write("TASK_ID=T1\nATTEMPT=1\nAGENT_ROLE=green\nSTORY_DIR=%s\n" % sd) +open(os.path.join(C, ".agentic", "state", "tasks", "S1-01-T1.env"), "w").write("TASK_ID=S1-01-T1\nATTEMPT=1\nAGENT_ROLE=green\nSTORY_DIR=%s\n" % sd) assert sh_home(C) == os.path.join(C, ".aladdin"), "the one stray contract must not flip the live dir" -out = run(C, "bash", "-c", '. "%s/_paths.sh"; agentic_contract_path T1; agentic_contract_path nope; echo "rc=$?"' % BIN).stdout -assert out.splitlines()[0] == os.path.join(C, ".agentic", "state", "tasks", "T1.env") and out.splitlines()[-1] == "rc=1", out -assert run(C, "python3", "-c", 'import sys; sys.path.insert(0, "%s"); import _paths; print(_paths.contract_path("%s", "T1"))' % (BIN, C)).stdout.strip() == os.path.join(C, ".agentic", "state", "tasks", "T1.env") +out = run(C, "bash", "-c", '. "%s/_paths.sh"; agentic_contract_path S1-01-T1; agentic_contract_path nope; echo "rc=$?"' % BIN).stdout +assert out.splitlines()[0] == os.path.join(C, ".agentic", "state", "tasks", "S1-01-T1.env") and out.splitlines()[-1] == "rc=1", out +assert run(C, "python3", "-c", 'import sys; sys.path.insert(0, "%s"); import _paths; print(_paths.contract_path("%s", "S1-01-T1"))' % (BIN, C)).stdout.strip() == os.path.join(C, ".agentic", "state", "tasks", "S1-01-T1.env") +approve_plan(C, dict(os.environ, HOME=os.path.join(C, "home"), AGENTIC_NO_AUTOINSTALL="1"), 1) # M0.9 payload = json.dumps({"hook_event_name": "PreToolUse", "tool_name": "Agent", "cwd": C, - "tool_input": {"subagent_type": "aloop:green-worker", "prompt": "TASK_ID: T1\ndo it", "model": "sonnet"}}) + "tool_input": {"subagent_type": "aloop:green-worker", "prompt": "TASK_ID: S1-01-T1\ndo it", "model": "sonnet"}}) r = run(C, os.path.join(BIN, "gate-dispatch"), input=payload) if False else subprocess.run( [os.path.join(BIN, "gate-dispatch")], cwd=C, input=payload, capture_output=True, text=True, env=dict(os.environ, HOME=os.path.join(C, "home"), AGENTIC_NO_AUTOINSTALL="1")) assert r.returncode == 0, (r.returncode, r.stderr) payload2 = json.dumps({"hook_event_name": "PreToolUse", "tool_name": "Agent", "cwd": C, - "tool_input": {"subagent_type": "aloop:green-worker", "prompt": "TASK_ID: T9\ndo it", "model": "sonnet"}}) + "tool_input": {"subagent_type": "aloop:green-worker", "prompt": "TASK_ID: S1-01-T9\ndo it", "model": "sonnet"}}) r = subprocess.run([os.path.join(BIN, "gate-dispatch")], cwd=C, input=payload2, capture_output=True, text=True, env=dict(os.environ, HOME=os.path.join(C, "home"), AGENTIC_NO_AUTOINSTALL="1")) -assert r.returncode == 2 and ".aladdin/state/tasks/T9.env" in r.stderr, (r.returncode, r.stderr) +assert r.returncode == 2 and ".aladdin/state/tasks/S1-01-T9.env" in r.stderr, (r.returncode, r.stderr) ok("the task contract is found in .aladdin/ or .agentic/ (bash, python, gate-dispatch); a missing one is named at the live dir") # 7) worktree-local markers: written to the worktree's .aladdin/ (guarded) in a fresh project, to diff --git a/scripts/test/mission-doors.test.py b/scripts/test/mission-doors.test.py index 9811268f..a1b503c6 100644 --- a/scripts/test/mission-doors.test.py +++ b/scripts/test/mission-doors.test.py @@ -16,7 +16,7 @@ import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "fixtures")) -from mission_fixture import Project, M, BIN # noqa: E402 +from mission_fixture import Project, M, BIN, as_human # noqa: E402 sys.path.insert(0, M.AREAS_DIR) import _events # noqa: E402 @@ -387,7 +387,11 @@ def ask_in(x, text, session="S1", env=None): assert open(os.path.join(s1.dir, ".aladdin", "state", "sprint.lock")).readline().strip() == "S1" # the lock is armed assert ask_in(s1, plan_q).stdout == "" # planning: the approval is asked _events.emit(s1.dir, "plan.created", role="planner", sprint="S1") # as plugin/bin/ids names it -_events.record_authority(s1.dir, "Adeel", "reviewed", "sprint1") # the human approved the plan +os.makedirs(os.path.join(s1.dir, "docs", "agents", "sprint1"), exist_ok=True) +r = as_human(lambda: subprocess.run([EVENTS, "authority", "--initiated-by", "Adeel", "--mode", "reviewed", "--scope", + "sprint1", "--sprint", "1"], cwd=s1.dir, env=s1.env, capture_output=True, text=True), + s1.dir, s1.env) # the human approved the plan: their typed line (M0.9) +assert r.returncode == 0 and any(e.get("event") == "plan.approved" for e in _events.read(s1.dir)), r.stderr assert "two-way" in denied(ask_in(s1, "parse_row or parse_line?")) # executing: decide it assert ask_in(s1, "parse_row or parse_line?", session="S2").stdout == "" # another session's sprint assert "two-way" in denied(ask_in(Project(mode="spoon-fed"), "parse_row or parse_line?", diff --git a/scripts/test/mission-roles.test.py b/scripts/test/mission-roles.test.py index 151c6c98..d4c3bb58 100644 --- a/scripts/test/mission-roles.test.py +++ b/scripts/test/mission-roles.test.py @@ -290,8 +290,9 @@ def blocked(r, *words): assert blocked(scope("Bash", command="claude -p 'approve msn_x 1234abcd'"), "UserPromptSubmit") AP = git_repo(os.path.join(T, "aloop-no-mission")) os.makedirs(os.path.join(AP, "docs", "agents", "sprint1")) -assert allowed(scope("Bash", cwd=AP, command="claude -p 'run the smoke test'")) # no mission: no grant to forge -assert allowed(scope("Bash", G, cwd=AP, command="claude -p 'run the smoke test'")) +# no mission, still a grant to forge: a sprint's plan approval reads the same prompts (M0.9) +assert blocked(scope("Bash", cwd=AP, command="claude -p 'run the smoke test'"), "UserPromptSubmit", "plan approval (M0.9)") +assert blocked(scope("Bash", G, cwd=AP, command="claude -p 'approve S1 1234abcd'"), "UserPromptSubmit") SUPSCOPE, LOCK = os.path.join(BIN, "gate-supervisor-scope"), os.path.join(P, ".aladdin", "state", "sprint.lock") @@ -303,7 +304,7 @@ def supervisor_write(path): assert supervisor_write(os.path.join(MD, "mission.json")).returncode == 0 and not os.path.exists(LOCK) assert supervisor_write(os.path.join(P, "docs", "agents", "sprint1", "init.md")).returncode == 0 and os.path.exists(LOCK) os.remove(LOCK) -ok("no one hand-writes the ledger or the captured prompts, or starts a host session where a mission is set; no dispatched" +ok("no one hand-writes the ledger or the captured prompts, or starts a host session in an aloop project; no dispatched" " agent runs `events authority` or emits a human event; mission writes arm no sprint lock") S = "aloop:state-assessor" diff --git a/scripts/test/opencode-plugin.test.mjs b/scripts/test/opencode-plugin.test.mjs index d4576f54..b15e2700 100644 --- a/scripts/test/opencode-plugin.test.mjs +++ b/scripts/test/opencode-plugin.test.mjs @@ -7,6 +7,7 @@ import { tmpdir } from "node:os" import { join } from "node:path" import { fileURLToPath, pathToFileURL } from "node:url" import assert from "node:assert/strict" +import { approvePlan } from "./fixtures/plan-fixture.mjs" const ROOT = join(fileURLToPath(import.meta.url), "..", "..", "..", "plugin") const BIN = join(ROOT, "bin") @@ -163,6 +164,18 @@ await hooks["tool.execute.after"]({ tool: "task", sessionID: "root", callID: "m4 assert.ok(/BLOCKED after 3 fix rounds/.test(msnOut.output) && /BLOCK\[mission-artifact\]/.test(msnOut.output), msnOut.output) ok("gate-mission-artifact runs at the evaluator's stop and blocks a run that wrote no artifact") +// dispatch (the task tool) runs gate-dispatch: the TASK_ID line, the task contract, then the human's plan +// approval (ROADMAP M0.9); OpenCode names no model per call (the agent file pins it) +const task = (id, prompt, sessionID = "root") => hooks["tool.execute.before"]({ tool: "task", sessionID, callID: id }, + { args: { subagent_type: "green-worker", description: "GREEN", prompt } }) +await throws(() => task("d1", "go green"), /BLOCK\[dispatch\].*TASK_ID: /s, "OpenCode task: a worker dispatch without its TASK_ID line is refused") +mkdirSync(join(T, ".aladdin/state/tasks"), { recursive: true }) +writeFileSync(join(T, ".aladdin/state/tasks/S1-01-T2.env"), `TASK_ID=S1-01-T2\nATTEMPT=1\nAGENT_ROLE=green-worker\nSTORY_DIR=${join(T, "docs/agents/sprint1/s1-01-x")}\n`) +await throws(() => task("d2", "TASK_ID: S1-01-T2\nGREEN"), /has not approved the plan of S1/, "OpenCode task: no worker is dispatched before the human approves the sprint's plan") +approvePlan(T, BIN) +await task("d3", "TASK_ID: S1-01-T2\nGREEN"); ok("OpenCode task: after the human's typed approval the dispatch is admitted") +await task("d4", "TASK_ID: S2-01-T1\nGREEN", "child"); ok("OpenCode task: a sub-agent's own task call is not gate-dispatch's") + // Stop: a closed sprint is announced once (toast + prompt back into the session) mkdirSync(join(T, ".aladdin/state"), { recursive: true }) writeFileSync(join(T, ".aladdin/state/pending-close"), "Sprint 1 closed. Tokens — sprint: 1k\n") diff --git a/scripts/test/plan-approval.test.py b/scripts/test/plan-approval.test.py new file mode 100644 index 00000000..5c9fa244 --- /dev/null +++ b/scripts/test/plan-approval.test.py @@ -0,0 +1,469 @@ +#!/usr/bin/env python3 +"""The plan approval is a gate (ROADMAP M0.9): gate-dispatch admits no execution role of a sprint +until the human approved exactly its plan in their own typed line (`approve SN `, M9.17's +mechanism), or granted the sprint autonomy (`autonomous SN `, or an approved autonomous +mission for its own sprints). Regression: the 2026-10-20 fact check found "a human approves the +plan" was a playbook rule only, so workers could be dispatched before the human said go. + + python3 scripts/test/plan-approval.test.py +""" +import atexit +import json +import os +import shutil +import subprocess +import sys +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "fixtures")) +from mission_fixture import Project, as_human, say # noqa: E402 + +BIN = os.path.realpath(os.path.join(HERE, "..", "..", "plugin", "bin")) +GATE, EV, IDS, SCOPE = (os.path.join(BIN, n) for n in ("gate-dispatch", "events", "ids", "gate-mission-scope")) +T = tempfile.mkdtemp(prefix="aloop-plan-approval-") +atexit.register(shutil.rmtree, T, ignore_errors=True) +ENV = {k: v for k, v in os.environ.items() if k not in ("SKIP_HOOKS", "AGENTIC_HOST")} +ENV["HOME"] = os.path.join(T, "home") +n = [0] + + +def ok(msg): + n[0] += 1 + print("ok - " + msg) + + +def run(args, cwd=None, inp=None, env=None): + return subprocess.run(args, cwd=cwd or P, env=env or ENV, capture_output=True, text=True, input=inp) + + +def dispatch(tid, role="green-worker", model="haiku", cwd=None, codex=False, env=None): + ti = {"agent_type": role, "message": "TASK_ID: %s\nDo it." % tid} if codex else \ + {"subagent_type": "aloop:" + role, "prompt": "TASK_ID: %s\nDo it." % tid, "isolation": "worktree"} + if model: + ti["model"] = model + p = {"session_id": "s", "cwd": cwd or P, "tool_name": "spawn_agent" if codex else "Agent", "tool_input": ti} + return run([GATE], cwd=cwd, inp=json.dumps(p), env=env) + + +def authority(*extra, cwd=None, mode="reviewed", human=False, env=None): + args = [EV, "authority", "--initiated-by", "Adeel", "--mode", mode, "--scope", "the sprint as approved"] + list(extra) + go = lambda: run(args, cwd=cwd, env=env) # noqa: E731 + return as_human(go, cwd or P, env or ENV) if human else go() + + +def asked(r): + """The line a grant asks the human to type (exit 3), or None.""" + m = r.returncode == 3 and "they reply " in r.stderr and r.stderr.split("they reply ", 1)[1].split(" (", 1)[0] + return m or None + + +def events(cwd=None): + p = os.path.join(cwd or P, ".aladdin", "logs", "events.jsonl") + return [json.loads(ln) for ln in open(p)] if os.path.exists(p) else [] + + +def write(rel, text, cwd=None): + p = os.path.join(cwd or P, rel) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "w") as f: + f.write(text) + return p + + +def sprint(num, cwd=None, story="x"): + """A frozen sprint plan with one story (stories.md, plan.md, the story's three files) and a task contract.""" + root = cwd or P + sd = "docs/agents/sprint%d" % num + sid = "s%d-01-%s" % (num, story) + write(sd + "/stories.md", "---\ntype: stories\nsprint: %d\n---\n# Sprint %d\n\n- S%d-01 (%s)\n" % (num, num, num, sid), root) + write(sd + "/plan.md", "---\ntype: sprint-plan\nsprint: %d\nstage: \"2\"\n---\n# Waves\n" % num, root) + for f in ("tasks.md", "validate.md", "plan.md"): + write("%s/%s/%s" % (sd, sid, f), "---\nstory: S%d-01\n---\n## T1 — the task\n" % num, root) + r = run([IDS, "freeze", sd], cwd=root) + assert r.returncode == 0, r.stderr + tid = "S%d-01-T1" % num + write(".aladdin/state/tasks/%s.env" % tid, "TASK_ID=%s\nAGENT_ROLE=green-worker\nSTORY_DIR=%s\n" + % (tid, os.path.join(root, sd, sid)), root) + return os.path.join(root, sd, sid) + + +def project(name): + d = os.path.join(T, name) + os.makedirs(d) + subprocess.run(["git", "init", "-q"], cwd=d, check=True) + write("docs/agents/defaults.md", "---\ntype: agentic-defaults\n---\n```conf\nAGENTIC_MODEL_PLANNING=haiku\n" + "AGENTIC_MODEL_WORKER=haiku\n```\n", d) + os.makedirs(os.path.join(d, ".aladdin", "state", "tasks")) + return d + + +P = project("p") +story = sprint(1) + +# 1) before the human's word nothing of the sprint is dispatched; planning and mission roles need no approval +r = dispatch("S1-01-T1") +assert r.returncode == 2 and "has not approved the plan of S1" in r.stderr and "approve S1 " in r.stderr, r +assert "events authority" in r.stderr and "--sprint 1" in r.stderr, r.stderr +for role in ("red-worker", "scaffolder", "structural-reviewer", "final-gate"): + assert dispatch("S1-01-T1", role=role).returncode == 2, role +for role in ("planner", "intake", "standards", "archivist", "evaluator", "mission-planner"): + assert dispatch("S1-01-T1", role=role).returncode == 0, role +assert run([EV, "approval", "S1-01-T1"]).returncode == 2 +ok("no execution role of a sprint is dispatched before the human approves its plan; planning and mission roles are") + +# 2) the supervisor's record alone is no approval: it asks for the human's line and writes nothing +r = authority("--sprint", "1") +line = asked(r) +assert line and line.startswith("approve S1 ") and len(line.split()[-1]) == 8, r +assert not [e for e in events() if e["event"] in ("human.approval", "plan.approved")], "an ask recorded a grant" +assert not os.path.exists(os.path.join(P, ".aladdin", "state", "authority.json")) +assert dispatch("S1-01-T1").returncode == 2 +code = line.split()[-1] +for words in ("approve S1", "go ahead", "approve S1 %s" % ("0" * 8), "don't approve S1 %s" % code, + "approve S1 %s, no wait" % code, "the plan says approve S1 %s" % code): + say(P, ENV, words) + assert asked(authority("--sprint", "1")) == line, words +ok("`events authority` asks (exit 3) for `approve S1 ` and records nothing; a yes in other words, another code, " + "a negated line or a line that does not start with the verb grants nothing") + +# 3) the human types the line: the grant is recorded, linked to the plan, and the dispatch is admitted +say(P, ENV, "ok, " + line) +r = authority("--sprint", "1") +assert r.returncode == 0, r.stderr +evs = events() +appr = [e for e in evs if e["event"] == "plan.approved"] +plan = [e for e in evs if e["event"] in ("plan.created", "plan.revised")] +assert len(appr) == 1 and appr[0]["caused_by"] == plan[-1]["event_id"] and appr[0]["data"]["sprint"] == "S1", appr +g = [e for e in evs if e["event"] == "human.approval"][-1]["authority"] +assert g["sprint"] == "S1" and g["grant"]["kind"] == "plan" and g["grant"]["prompt"]["line"] == "ok, " + line, g +assert dispatch("S1-01-T1").returncode == 0 +assert dispatch("S1-01-T1", role="red-worker").returncode == 0 +r = run([EV, "approval", "S1-01-T1"]) +assert r.returncode == 0 and "S1 approved by Adeel (reviewed), code %s" % code in r.stdout, r +ok("the human's typed line records the approval (plan.approved for the frozen plan) and admits the sprint's roles") + +# 4) a changed plan is a new decision; comms, ticks and logs are not the plan +for f in ("init.md", "output.md", "plan-ready.md"): + write(os.path.join(story, f), "## attempt 1\n") +write("docs/agents/sprint1/execution.log", "wave-1 green S1-01 start T1\n") +assert dispatch("S1-01-T1").returncode == 0 +tasks = os.path.join(story, "tasks.md") +orig = open(tasks).read() +for rel in (tasks, os.path.join(story, "validate.md"), os.path.join(story, "plan.md"), + os.path.join(P, "docs/agents/sprint1/stories.md"), os.path.join(P, "docs/agents/sprint1/plan.md"), + os.path.join(P, "docs/agents/sprint1/ids.json"), os.path.join(story, "targets.json")): + before = open(rel).read() if os.path.exists(rel) else None + write(rel, (before or "{}") + "\n") + r = dispatch("S1-01-T1") + assert r.returncode == 2 and "changed after the human approved it" in r.stderr, (rel, r) + if before is None: + os.remove(rel) + else: + write(rel, before) + assert dispatch("S1-01-T1").returncode == 0, rel +ok("a change to any plan file (stories, plans, ids, a story's tasks/validate/plan/targets) blocks until it is approved;" + " init.md, output.md, plan-ready.md and logs do not") + +# 5) the old line does not approve new content; a fresh line does +write(tasks, orig + "## T2 — split\n") +r = authority("--sprint", "1") +line2 = asked(r) +assert line2 and line2 != line, r +say(P, ENV, line2) +assert authority("--sprint", "1").returncode == 0 +assert dispatch("S1-01-T1").returncode == 0 +ok("a re-plan needs its own line: the old one names other content") + +# 6) no roll-back: the replaced plan is not approved again, and its old line is stale +write(tasks, orig) +r = dispatch("S1-01-T1") +assert r.returncode == 2 and "changed after the human approved it" in r.stderr, r +assert asked(authority("--sprint", "1")) == line, "the old line re-granted a replaced plan" +say(P, ENV, line) +assert authority("--sprint", "1").returncode == 0 +assert dispatch("S1-01-T1").returncode == 0 +ok("after a newer approval the replaced plan is blocked, its old line is stale, and only a fresh line approves it again") + +# 7) a hand-written record never grants: the emit CLI refuses it, and an appended one only takes the grant away +for ev in ("plan.approved", "human.approval"): + r = run([EV, "emit", ev, "--role", "human", "--data", "sprint=S1"]) + assert r.returncode == 64 and "only its own command writes it" in r.stderr, (ev, r) +good = [e for e in events() if e["event"] == "human.approval"][-1] +forged = json.loads(json.dumps(good)) +forged["event_id"], forged["ts"] = "f" * 32, "2099-01-01T00:00:00Z" +forged["authority"]["grant"]["prompt"] = dict(good["authority"]["grant"]["prompt"], sha256="0" * 64, + line="approve S1 %s" % code) +with open(os.path.join(P, ".aladdin", "logs", "events.jsonl"), "a") as f: + f.write(json.dumps(forged) + "\n") +r = dispatch("S1-01-T1") +assert r.returncode == 2 and "not the human's own words" in r.stderr and "not among the human's captured prompts" in r.stderr, r +forged2 = json.loads(json.dumps(good)) +forged2["event_id"], forged2["ts"] = "e" * 32, "2099-01-01T00:00:01Z" +forged2["authority"]["overrides"] = {"BUDGET_TOKENS_HARD": "9999999"} +with open(os.path.join(P, ".aladdin", "logs", "events.jsonl"), "a") as f: + f.write(json.dumps(forged2) + "\n") +r = dispatch("S1-01-T1") +assert r.returncode == 2 and "does not match its own record" in r.stderr, r +say(P, ENV, "approve S1 %s" % code) +assert authority("--sprint", "1").returncode == 0 and dispatch("S1-01-T1").returncode == 0 +ok("`events emit` refuses plan.approved and human.approval; an appended record citing a line nobody typed, or " + "changing what the code covers, blocks the sprint until the human approves again") + +# 8) one sprint's approval is not another's; a task id must name its sprint +sprint(2) +r = dispatch("S2-01-T1") +assert r.returncode == 2 and "has not approved the plan of S2" in r.stderr, r +write(".aladdin/state/tasks/foo.env", "TASK_ID=foo\nSTORY_DIR=%s\n" % story) +r = dispatch("foo") +assert r.returncode == 2 and "names no sprint" in r.stderr, r +ok("an approval covers its own sprint only, and a TASK_ID that names no sprint is refused") + +# 9) autonomy is the human's word too, per sprint, and it covers that sprint's re-plans +r = authority(mode="autonomous") +assert r.returncode == 64 and "--sprint N" in r.stderr, r +r = authority("--sprint", "2", mode="autonomous") +aline = asked(r) +assert aline and aline.startswith("autonomous S2 "), r +assert dispatch("S2-01-T1").returncode == 2 +say(P, ENV, line) # S1's line is not S2's autonomy +assert asked(authority("--sprint", "2", mode="autonomous")) == aline +say(P, ENV, aline) +assert authority("--sprint", "2", mode="autonomous").returncode == 0 +assert dispatch("S2-01-T1").returncode == 0 +s2 = os.path.join(P, "docs/agents/sprint2/s2-01-x/tasks.md") +write(s2, open(s2).read() + "## T2 — split from T1\n") +assert dispatch("S2-01-T1").returncode == 0 +r = run([EV, "approval", "S2"]) +assert r.returncode == 0 and "S2 autonomous, granted by Adeel" in r.stdout, r +assert dispatch("S1-01-T1").returncode == 0 # S1 keeps its own approval +sprint(3) +r = dispatch("S3-01-T1") +assert r.returncode == 2 and "has not approved the plan of S3" in r.stderr, r # S2's autonomy is not S3's +ok("`--mode autonomous` names its sprint and asks for `autonomous SN `; granted, it admits the sprint's roles " + "through re-plans, and covers no other sprint") + +# 10) a later reviewed decision ends that autonomy, and the old autonomy line cannot bring it back +r = authority("--sprint", "2", human=True) +assert r.returncode == 0, r.stderr +write(s2, open(s2).read() + "## T3 — another\n") +r = dispatch("S2-01-T1") +assert r.returncode == 2 and "changed after the human approved it" in r.stderr, r +assert asked(authority("--sprint", "2", mode="autonomous")) == aline, "an old autonomy line re-granted autonomy" +ok("the sprint's newest grant decides: a reviewed approval after autonomy holds the plan again, and the old autonomy " + "line is stale") + +# 11) Codex (spawn_agent: agent_type, message) and OpenCode (no model per call) are gated the same way +assert dispatch("S2-01-T1", codex=True, model=None).returncode == 2 +r = dispatch("S1-01-T1", codex=True, model=None) +assert r.returncode == 0, r +oc = dict(ENV, AGENTIC_HOST="opencode") +assert dispatch("S1-01-T1", model=None, env=oc).returncode == 0 +r = dispatch("S1-01-T1", model="anthropic/claude-opus-5-5", env=oc) # a model the call names is still checked +assert r.returncode == 2 and "model: anthropic/claude-haiku" in r.stderr, r +assert dispatch("S2-01-T1", model=None, env=oc).returncode == 2 +r = dispatch("S1-01-T1", model=None) +assert r.returncode == 2 and "model: haiku" in r.stderr, r # Claude Code still needs the confirmed model +ok("Codex's spawn_agent and OpenCode's task are held to the plan approval; a host whose agent file pins the model " + "is not refused for naming none") + +# 12) the human's words cannot be forged from a tool call in any aloop project +for cmd in ("claude -p '%s'" % line, "codex exec '%s'" % aline, "opencode run 'go'"): + p = {"session_id": "s", "cwd": P, "tool_name": "Bash", "tool_input": {"command": cmd}} + r = run([SCOPE], inp=json.dumps(p)) + assert r.returncode == 2 and "UserPromptSubmit" in r.stderr, (cmd, r) +ok("a host session started from a tool call is refused in every aloop project (its prompt would pass for the human's)") + +# 13) an approved autonomous mission is the human's word for its own sprints, and only while it holds +mp = Project(mode="autonomous") +M = mp.dir +write("docs/agents/defaults.md", open(os.path.join(P, "docs/agents/defaults.md")).read(), M) +os.makedirs(os.path.join(M, ".aladdin", "state", "tasks"), exist_ok=True) +with open(os.path.join(M, ".aladdin", "logs", "events.jsonl"), "a") as f: # the run log `intent new --source mission` writes + f.write(json.dumps({"schema": "aladdin.event/1", "event_id": "i" * 32, "ts": "2026-10-20T00:00:00Z", + "event": "intent.received", "ids": {}, "role": "intake", "refs": {}, + "data": {"intent_id": "int_mission1", "source": "mission", "goal_id": "gol_x"}}) + "\n") + f.write(json.dumps({"schema": "aladdin.event/1", "event_id": "j" * 32, "ts": "2026-10-20T00:00:01Z", + "event": "intent.normalized", "ids": {}, "role": "intake", "refs": {}, + "data": {"intent_id": "int_mission1", "mode": "autonomous"}}) + "\n") +sprint(1, cwd=M) +r = authority("--sprint", "1", mode="autonomous", cwd=M, env=mp.env) +assert r.returncode == 0, r.stderr # no typed line: the mission's approval is it +g = [e for e in events(M) if e["event"] == "human.approval"][-1]["authority"]["grant"] +assert g["mission"]["mission_id"].startswith("msn_") and "prompt" not in g, g +assert dispatch("S1-01-T1", cwd=M, env=mp.env).returncode == 0 +with open(os.path.join(M, ".aladdin", "logs", "events.jsonl"), "a") as f: + f.write(json.dumps({"schema": "aladdin.event/1", "event_id": "k" * 32, "ts": "2026-10-20T00:00:02Z", + "event": "intent.normalized", "ids": {}, "role": "intake", "refs": {}, + "data": {"intent_id": "int_human1", "mode": "autonomous"}}) + "\n") +sprint(2, cwd=M) # a sprint for a human's own intent +assert asked(authority("--sprint", "2", mode="autonomous", cwd=M, env=mp.env)).startswith("autonomous S2 ") +assert dispatch("S2-01-T1", cwd=M, env=mp.env).returncode == 2 +assert authority("--sprint", "2", mode="autonomous", cwd=M, env=mp.env, human=True).returncode == 0 +assert dispatch("S2-01-T1", cwd=M, env=mp.env).returncode == 0 # the human's own line grants it +assert authority("--sprint", "3", mode="autonomous", cwd=M, env=mp.env).returncode == 0 # before its plan: the mission's +sprint(3, cwd=M) # ...but it was planned from the human's intent +r = dispatch("S3-01-T1", cwd=M, env=mp.env) +assert r.returncode == 2 and "serves no mission intent" in r.stderr, r +assert asked(authority("--sprint", "3", mode="autonomous", cwd=M, env=mp.env)).startswith("autonomous S3 ") +mj = os.path.join(M, "docs/agents/mission/mission.json") +doc = json.load(open(mj)) +doc["statement"] += " (edited)" +json.dump(doc, open(mj, "w")) +r = dispatch("S1-01-T1", cwd=M, env=mp.env) +assert r.returncode == 2 and "no longer approved in autonomous mode" in r.stderr, r +sp = Project(mode="spoon-fed") +sprint(1, cwd=sp.dir) +write("docs/agents/defaults.md", open(os.path.join(P, "docs/agents/defaults.md")).read(), sp.dir) +assert asked(authority("--sprint", "1", mode="autonomous", cwd=sp.dir, env=sp.env)).startswith("autonomous S1 ") +ok("an approved autonomous mission grants its own sprints autonomy without a typed line; a sprint for another intent " + "(planned before or after the grant), a mission changed since its approval or a spoon-fed mission needs the " + "human's line, and that line grants it") + +# 14) an approval covers its own plan only: the contract's STORY_DIR and the task must be of that plan +Q = project("q") +qs1 = sprint(1, cwd=Q) +qs2 = sprint(2, cwd=Q) # planned, never approved +assert authority("--sprint", "1", cwd=Q, human=True).returncode == 0 +assert dispatch("S1-01-T1", cwd=Q).returncode == 0 + + +def contract(tid, sd, role="green-worker"): + write(".aladdin/state/tasks/%s.env" % tid, "TASK_ID=%s\nAGENT_ROLE=%s\nSTORY_DIR=%s\n" % (tid, role, sd), Q) + + +def refused(tid, why, role="green-worker"): + r = dispatch(tid, role=role, cwd=Q) + assert r.returncode == 2 and why in r.stderr, (tid, role, r.stderr) + + +contract("S1-01-T1", qs2) # sprint 2's story under sprint 1's approval +for role in ("red-worker", "scaffolder", "green-worker", "structural-reviewer", "final-gate"): + refused("S1-01-T1", "is not in S1's plan", role) +contract("S1-01-T1", os.path.join(T, "elsewhere")) +os.makedirs(os.path.join(T, "elsewhere"), exist_ok=True) +refused("S1-01-T1", "is not in S1's plan") +contract("S1-01-T1", qs1) +assert dispatch("S1-01-T1", cwd=Q).returncode == 0 +unplanned = write("docs/agents/sprint1/s1-09-unplanned/init.md", "---\ntype: init\n---\n", Q) # comms only: no digest change +contract("S1-09-T1", os.path.dirname(unplanned)) +refused("S1-09-T1", "no live story of S1's frozen plan") +shutil.rmtree(os.path.dirname(unplanned)) +contract("S1-07-T1", qs1) +refused("S1-07-T1", "is not a task of the story dir") +contract("S1-01-T9", qs1) +refused("S1-01-T9", "is not a live task of S1's frozen plan") +contract("S1-X", qs1, "red-worker") +refused("S1-X", "works on one task of the plan", "red-worker") +contract("S1-SR-W1", os.path.dirname(qs1), "structural-reviewer") +assert dispatch("S1-SR-W1", role="structural-reviewer", cwd=Q).returncode == 0 # a wave review spans the sprint +ok("an approval covers its own plan only: a STORY_DIR of another sprint or outside it, a comms-only story, a task " + "of another story or one the frozen plan lacks, and a worker without a task are refused for every role") + +# 15) the same words typed again after a later decision count again +qline = [e for e in events(Q) if e["event"] == "human.approval"][-1]["authority"]["grant"]["prompt"]["line"] +assert authority("--sprint", "1", cwd=Q, mode="autonomous", human=True).returncode == 0 # a later decision +r = authority("--sprint", "1", cwd=Q) +assert asked(r) == qline, (asked(r), qline) # the same plan again: the same line +say(Q, ENV, qline) # typed byte for byte as before +assert authority("--sprint", "1", cwd=Q).returncode == 0 +r = dispatch("S1-01-T1", cwd=Q) +assert r.returncode == 0, r.stderr +ok("a line typed again after a later decision grants again: the gate reads its newest capture, not its first") + +# 16) what the record keeps is what the gate re-reads: a code past column 200 grants nothing +write("docs/agents/sprint1/s1-01-x/tasks.md", "---\nstory: S1-01\n---\n## T1 — the task, revised\n", Q) +assert run([IDS, "freeze", "docs/agents/sprint1"], cwd=Q).returncode == 0 +want = asked(authority("--sprint", "1", cwd=Q)) +say(Q, ENV, "approve S1 " + "I read every story, task and test of it and it is what I want, " * 4 + want.split()[-1]) +r = authority("--sprint", "1", cwd=Q) +assert asked(r) == want, r.stderr # asked again, nothing recorded +assert dispatch("S1-01-T1", cwd=Q).returncode == 2 +ok("a line whose code lies past what the record keeps is no grant: `events authority` asks again instead of " + "recording one the gate refuses") + +# 17) a hand-written run-log line of another shape never crashes the grant +with open(os.path.join(Q, ".aladdin", "logs", "events.jsonl"), "a") as f: + f.write(json.dumps({"event": "plan.revised", "data": "S1"}) + "\n") + f.write(json.dumps({"event": "intent.received", "data": ["x"]}) + "\n") +for extra in (("--sprint", "1"), ()): + r = authority(*extra, cwd=Q) + assert r.returncode in (0, 3) and "Traceback" not in r.stderr, r.stderr +r = run([EV, "approval", "S1-01-T1"], cwd=Q) +assert r.returncode in (0, 2) and "Traceback" not in r.stderr, r.stderr +ok("a run-log line whose data is not a record is skipped: no traceback from `events authority` or `events approval`") +qlog = os.path.join(Q, ".aladdin", "logs", "events.jsonl") +kept = [ln for ln in open(qlog) if isinstance(json.loads(ln).get("data"), dict)] +open(qlog, "w").writelines(kept) # the later checks run `ids freeze`, which reads it too + +# 18) pruning the transcripts keeps the human's prompts, so it never revokes a grant +assert authority("--sprint", "1", cwd=Q, human=True).returncode == 0 +assert dispatch("S1-01-T1", cwd=Q).returncode == 0 +TR = os.path.join(BIN, "transcripts") +for i in range(30): + run([TR, "record"], cwd=Q, inp=json.dumps({"tool_name": "Bash", "tool_input": {"command": "true %d" % i}})) +store = os.path.join(Q, ".aladdin", "transcripts") +before = sum(1 for ln in open(os.path.join(store, "session", "events.jsonl")) if '"kind": "prompt"' in ln) +r = run([TR, "prune"], cwd=Q, env=dict(ENV, AGENTIC_TRANSCRIPTS_KEEP="5")) +assert r.returncode == 0, r.stderr +lines = open(os.path.join(store, "session", "events.jsonl")).read().splitlines() +assert sum(1 for ln in lines if '"kind": "prompt"' in ln) == before and len(lines) == before + 5, (before, len(lines)) +assert os.path.getsize(os.path.join(store, "compacted", "session.jsonl")) > 0 +assert dispatch("S1-01-T1", cwd=Q).returncode == 0 +ok("`transcripts prune` compacts tool records only: the human's prompts stay, so every grant still holds") + +# 19) a host's own tools are not sessions: installing the Codex plugin is not refused +for cmd, code in (("codex plugin marketplace add /x", 0), ("codex plugin add aloop@aloop-marketplace", 0), + ("codex exec 'go'", 2)): + p = {"session_id": "s", "cwd": Q, "tool_name": "Bash", "tool_input": {"command": cmd}} + r = run([SCOPE], cwd=Q, inp=json.dumps(p)) + assert r.returncode == code, (cmd, r.returncode, r.stderr) +ok("`codex plugin …` (the documented install) runs in an aloop project; `codex exec` still does not") + +# 20) at every dispatch the newest record is re-proven: a forged autonomy grant or a replayed approval blocks +sys.path.insert(0, BIN) +import _approval # noqa: E402 +LOG = os.path.join(Q, ".aladdin", "logs", "events.jsonl") + + +def append(rec, i): + rec = json.loads(json.dumps(rec)) + rec["event_id"], rec["ts"] = ("%x" % i) * 32, "2000-01-01T00:00:%02dZ" % i # stamped in the past: it stales no new line + with open(LOG, "a") as f: + f.write(json.dumps(rec) + "\n") + + +qs3 = sprint(3, cwd=Q) +auth = {"initiated_by": "Adeel", "autonomy_mode": "autonomous", "scope": "s", "policy": "default", "overrides": {}, + "sprint": "S3"} +base = {"schema": "aladdin.event/1", "event": "human.approval", "ids": {}, "role": "human", "refs": {}, "data": {}} +qp = _approval.M.prompts(Q)[-1] # a prompt the human really typed +for i, (grant, extra, why) in enumerate(( + ({"kind": "autonomy"}, {}, "not the human's own words"), + ({"kind": "autonomy", "prompt": {"line": "autonomous S3 %s" % _approval.M.code(_approval.grant_sha(auth)), + "sha256": "0" * 64}}, {}, "not among the human's captured prompts"), + ({"kind": "autonomy"}, {"overrides": {"BUDGET_TOKENS_HARD": "9"}}, "does not match its own record"), + ({"kind": "autonomy", "prompt": {"line": qp["text"].splitlines()[0].strip()[:200], "sha256": qp["sha256"]}}, {}, + "does not autonomous this content")), start=1): + a = dict(auth, **extra) + g = dict(grant, sha256=_approval.grant_sha(auth)) + append(dict(base, authority=dict(a, grant=g)), i) + r = dispatch("S3-01-T1", cwd=Q) + assert r.returncode == 2 and why in r.stderr, (i, why, r.stderr) +r = authority("--sprint", "3", cwd=Q, human=True) +assert r.returncode == 0, r.stderr # plan A, the human's line +first = [e for e in events(Q) if e["event"] == "human.approval"][-1] +w3 = os.path.join(os.path.dirname(qs3), "plan.md") +orig3 = open(w3).read() +write(w3, orig3 + "Wave 1: S3-01\n") +assert authority("--sprint", "3", cwd=Q, human=True).returncode == 0 # plan B, a later decision +write(w3, orig3) # back to plan A's files +append(first, 9) # ...and plan A's old record replayed +r = dispatch("S3-01-T1", cwd=Q) +assert r.returncode == 2 and "typed before a later decision" in r.stderr, r.stderr +ok("each dispatch re-proves the newest record: an autonomy grant with no line, an unknown prompt, edited overrides " + "or another verb's line, and a replayed copy of an older approval, all block") + +shutil.rmtree(mp.dir, ignore_errors=True) +shutil.rmtree(sp.dir, ignore_errors=True) +print("%d checks passed" % n[0])