From 6baab24efc007413dd401d5a0f64f1f135e17001 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 3 Dec 2026 17:15:11 +0100 Subject: [PATCH 01/15] Move item 579 to release 0.18.0 --- todo.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/todo.md b/todo.md index 22a8d6f5..ca4db86e 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 579 | 0.17.0 | | | **Make stability-reviewer trace every path, asynchronous ones included, to a callback that a change guards.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.7 | | 484 | 0.18.0 | | owner | **Keep project configs and this machine's rules in `~/.config/build-release/`, and transcripts and review reports in `~/.local/state/build-release/`, each under its `XDG_*` variable where set, read no old place, and have rule-hook guard the new ones.** | 3 | 2 | 4 | 7 | 6 | 2 by 4 | 0.4 | | 575 | 0.18.0 | 484 | owner | **Rename `do-epic` to `build-epic`, with no alias, and its config folder with it.** | 2 | 2 | 2 | 4 | 4 | 2 by 2, 6 by 1 | 0.6 | | 482 | 0.18.0 | | owner | **Run the setup from a clone of a release by the path of its `bin/`, with no install step, and replace `deploy-release` with a command that moves that clone to the newest tag.** | 3 | 2 | 3 | 6 | 7 | 2 by 6 | 0.4 | @@ -21,6 +20,7 @@ | 577 | 0.18.0 | 483, 486, 575 | owner | **Test in the gate that a container holding only a stock Claude Code runs a chunk from a clone, against a mock Messages API, and that the run leaves the container's own `~/.claude` as it was.** | 3 | 1 | 2 | 4 | 6 | 3 by 9, 2 by 5 | 5.2 | | 576 | 0.18.0 | 575 | owner | **Name the project `dev-factory` in the README, the prose and the tools, and say in the changelog that the repo moved.** | 2 | 2 | 2 | 4 | 4 | 2 by 1, 6 by 1 | 0.4 | | 578 | 0.18.0 | 576, 577 | owner | **Ship one chunk of this repo, to a merged pull request, from a clone of `main` that runs in the generated home, beside the untouched `~/.claude`.** | 1 | 2 | 1 | 2 | 1 | 2 by 4 | 1.2 | +| 579 | 0.18.0 | | | **Make stability-reviewer trace every path, asynchronous ones included, to a callback that a change guards.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.7 | | 487 | 0.20.0 | 483 | owner | **Run larv-review's passes from a program that picks them from the diff and the item, counts rounds against the cap and decides each rerun, with each reviewer returning its findings as JSON against a schema.** | 4 | 2 | 3 | 7 | 8 | 1.1 by 5, 1.4 by 5 | 0.4 | | 498 | 0.20.0 | 487 | owner | **Drive each chunk as a state machine in `build-release`, from preflight through implementing, review, the pull request and the merge to finishing its items, with the worker as one model step that ends in a result that code checks.** | 4 | 2 | 3 | 7 | 8 | 1.1 by 4, 1.4 by 4 | 0.3 | | 488 | 0.20.0 | 498 | owner | **Cut the larv-review skill, `CLAUDE.md` and rule-hook down to what `build-release` doesn't own: the judgement the model makes and the safety guards.** | 2 | 2 | 3 | 5 | 5 | 1.4 by 4, code health by 2 | 2.3 | @@ -106,15 +106,6 @@ ## Details -### 579. Make stability-reviewer trace every path, asynchronous ones included, to a callback that a change guards. - -A forge auto-reviewer found, on a library, a guard the stability pass had read as complete: the code kept a user callback from running before the constructor returned by leaving it out of one handler, while a background export of the same record still reached the callback through a global error handler. The stability reviewer checked the direct call and not the asynchronous one. - -Add to the concurrency section: where a change keeps a callback, handler or hook from running in some window, the reviewer lists every path that can reach it, including background goroutines, threads, queues and process-wide handlers, and reports each path the guard leaves open. - -Touches: -- `agents/stability-reviewer.md`: `### 6. Concurrency & State Management` (small) - ### 484. Keep project configs and this machine's rules in `~/.config/build-release/`, and transcripts and review reports in `~/.local/state/build-release/`, each under its `XDG_*` variable where set, read no old place, and have rule-hook guard the new ones. Part of the standalone-install plan lilleman approved on 2026-11-20, as reshaped on 2026-12-03 when 0.18.0 was planned. Today they live in `~/.claude-projects/`, `~/.claude/*-transcripts`, `~/.claude/loop-claude-models.json` and `~/.local/state/larv-review`. `rules/goals-and-audience.md` loads by the glob `**/.claude-projects/*/goals.md`, which moves with the folder. The release ships no migrate command and reads no old place: the only two machines move once, after the cut, by a throwaway script that is never committed. From the first release that reads project configs from `~/.config/build-release/`, rule-hook must read each `env-file` from those configs and refuse a read of it, as it does today from the old folder. @@ -421,6 +412,15 @@ Touches: - `README.md` +### 579. Make stability-reviewer trace every path, asynchronous ones included, to a callback that a change guards. + +A forge auto-reviewer found, on a library, a guard the stability pass had read as complete: the code kept a user callback from running before the constructor returned by leaving it out of one handler, while a background export of the same record still reached the callback through a global error handler. The stability reviewer checked the direct call and not the asynchronous one. + +Add to the concurrency section: where a change keeps a callback, handler or hook from running in some window, the reviewer lists every path that can reach it, including background goroutines, threads, queues and process-wide handlers, and reports each path the guard leaves open. + +Touches: +- `agents/stability-reviewer.md`: `### 6. Concurrency & State Management` (small) + ### 487. Run larv-review's passes from a program that picks them from the diff and the item, counts rounds against the cap and decides each rerun, with each reviewer returning its findings as JSON against a schema. Part of the standalone-install plan lilleman approved on 2026-11-20. It applies the decision `loop: a step whose result a program can check …` in `docs/decisions.md`. The reviewer briefs stay prose. Start here, since larv-review holds the most sequencing rules. -- 2.52.0 From 20c83f861f638230139fa1c534b2fcb06944ac1e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 3 Dec 2026 17:19:12 +0100 Subject: [PATCH 02/15] Re-score item 484's L to 4 --- todo.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index ca4db86e..b00b822f 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,7 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 484 | 0.18.0 | | owner | **Keep project configs and this machine's rules in `~/.config/build-release/`, and transcripts and review reports in `~/.local/state/build-release/`, each under its `XDG_*` variable where set, read no old place, and have rule-hook guard the new ones.** | 3 | 2 | 4 | 7 | 6 | 2 by 4 | 0.4 | +| 484 | 0.18.0 | | owner | **Keep project configs and this machine's rules in `~/.config/build-release/`, and transcripts and review reports in `~/.local/state/build-release/`, each under its `XDG_*` variable where set, read no old place, and have rule-hook guard the new ones.** | 4 | 2 | 4 | 8 | 6 | 2 by 4 | 0.4 | | 575 | 0.18.0 | 484 | owner | **Rename `do-epic` to `build-epic`, with no alias, and its config folder with it.** | 2 | 2 | 2 | 4 | 4 | 2 by 2, 6 by 1 | 0.6 | | 482 | 0.18.0 | | owner | **Run the setup from a clone of a release by the path of its `bin/`, with no install step, and replace `deploy-release` with a command that moves that clone to the newest tag.** | 3 | 2 | 3 | 6 | 7 | 2 by 6 | 0.4 | | 483 | 0.18.0 | 482, 484 | owner | **Run every claude the loop starts in a Claude home that the commands generate under `~/.local/share/build-release/` and refresh when the clone's tag changes, with the enabled plugins installed there and the person signed in by `/login` in that home.** | 4 | 2 | 3 | 7 | 7 | 2 by 8 | 0.5 | @@ -112,6 +112,8 @@ Part of the standalone-install plan lilleman approved on 2026-11-20, as reshaped Item 480 lands first and gathers these paths in one module, so how many of the call sites below still change here is not predictable; the list names each. Whether the other state the tools keep under `~/.local/state`, such as the chunk claims, do-epic's epic state and the project-record copies, moves too is not predictable either, so the list holds it. The trial records under `judge-field-trials/`, `reviewer-merge-trials/`, `stability-skip-count/` and `presentation/` name the old transcript folders, and the list leaves them out as history. +L is 4 since the change is S 6, spans some twenty packages under `bin/`, moves live config and state, and threads the `XDG_*` environment to call sites that today hold only `home`. + Touches: - `bin/loop_state/paths.py`: `Paths` (small), `paths_from` (small) -- 2.52.0 From 1ca2c8efe0964c30b3c4902e79c273157bfbb529 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 3 Dec 2026 18:56:28 +0100 Subject: [PATCH 03/15] Keep configs in ~/.config/build-release/ and tool state in ~/.local/state/build-release/, under XDG_* where set --- CLAUDE.md | 4 +- README.md | 29 ++- bin/adf_codec/test_adf_codec.py | 13 +- bin/agent_cycle/test_interrupt.py | 2 +- bin/agent_cycle/test_run.py | 2 +- bin/branch_chunks/read.py | 5 +- bin/branch_chunks/test_branch_chunks.py | 8 +- bin/build-release | 2 +- bin/build_release/loop/chunk_start.py | 4 +- bin/build_release/loop/chunk_windows.py | 22 +- bin/build_release/loop/main.py | 4 +- bin/build_release/loop/routing_check.py | 7 +- bin/build_release/loop/test_chunk_start.py | 18 +- bin/build_release/loop/test_chunk_windows.py | 24 ++- bin/build_release/loop/test_main.py | 18 +- bin/build_release/loop/test_routing_check.py | 2 +- bin/build_release/loop/usage.py | 17 +- bin/build_release/test_black_box.py | 29 +-- bin/chunk_driver/claims.py | 14 +- bin/chunk_driver/cycle_start.py | 2 +- bin/chunk_driver/doubles.py | 2 +- bin/chunk_driver/project/model_choice.py | 6 +- bin/chunk_driver/project/premises.py | 5 +- bin/chunk_driver/project/records.py | 5 +- bin/chunk_driver/project/test_model_choice.py | 18 +- bin/chunk_driver/project/test_records.py | 32 +-- bin/chunk_driver/test_cycle_start.py | 2 +- bin/chunk_pr/main.py | 2 +- bin/chunk_preflight/main.py | 5 +- bin/chunk_preflight/test_chunk_preflight.py | 8 +- bin/command_patterns/test_command_patterns.py | 2 +- bin/compress_archives/main.py | 8 +- .../test_compress_archives.py | 22 +- bin/deploy_release/main.py | 2 +- bin/deploy_release/test_deploy_release.py | 10 +- bin/do-epic | 2 +- bin/do_epic/backend/jira.py | 2 +- bin/do_epic/backend/test_jira.py | 4 +- bin/do_epic/config.py | 21 +- bin/do_epic/e2e/scenario.py | 6 +- bin/do_epic/e2e/test_scenario.py | 2 +- bin/do_epic/epic_run.py | 4 +- bin/do_epic/human_tasks.py | 9 +- bin/do_epic/main.py | 36 ++-- bin/do_epic/parking.py | 4 +- bin/do_epic/planning.py | 12 +- bin/do_epic/repos.py | 10 +- bin/do_epic/scheduler.py | 17 +- bin/do_epic/status.py | 6 +- bin/do_epic/test_do_epic.py | 54 ++--- bin/do_epic/test_findings.py | 8 +- bin/do_epic/test_finish.py | 18 +- bin/do_epic/test_human_tasks.py | 4 +- bin/do_epic/test_main.py | 68 +++--- bin/do_epic/test_planning.py | 36 ++-- bin/do_epic/test_repos.py | 6 +- bin/do_epic/test_scheduler.py | 30 +-- bin/judge_replay/main.py | 16 +- bin/judge_replay/test_judge_replay.py | 33 +-- bin/larv_review/history_changes.py | 5 +- bin/larv_review/history_commands.py | 48 ++--- bin/larv_review/main.py | 41 ++-- bin/larv_review/owed.py | 6 +- bin/larv_review/reviewer_header.py | 19 +- bin/larv_review/round_title.py | 7 +- bin/larv_review/scoring_due.py | 5 +- bin/larv_review/scoring_setup.py | 19 +- bin/larv_review/test_larv_review.py | 42 ++-- bin/larv_review/test_scoring_setup.py | 12 +- bin/loop_effects/effects.py | 2 +- bin/loop_state/paths.py | 42 +++- bin/loop_state/test_paths.py | 30 ++- bin/machine_load/test_machine_load.py | 4 +- bin/model_routing/ladder_file.py | 9 +- bin/model_routing/test_ladder_file.py | 20 +- bin/notifier/main.py | 4 +- bin/notifier/notify.py | 8 +- bin/notifier/test_notifier.py | 28 +-- bin/notify | 3 +- bin/plan/test_ranking.py | 6 +- bin/project_config/doubles.py | 4 +- bin/project_config/main.py | 21 +- bin/project_config/settings.py | 36 ++-- bin/project_config/test_project_config.py | 200 +++++++++--------- bin/project_record/main.py | 25 +-- bin/project_record/test_project_record.py | 40 ++-- bin/rank_todo.py | 8 +- bin/reading_cost/main.py | 2 +- bin/reading_cost/test_reading_cost.py | 8 +- bin/record_store/test_stores.py | 14 +- bin/repo_checks/test_gitignore.py | 2 - bin/repo_checks/test_paths_in_one_module.py | 4 +- bin/review_replay/main.py | 10 +- bin/review_replay/replay.py | 44 ++-- bin/review_replay/rounds.py | 4 +- bin/review_replay/test_review_replay.py | 43 ++-- bin/review_rules/review_folder.py | 24 ++- bin/review_rules/test_review_folder.py | 6 +- bin/routing_figures/archive.py | 14 +- bin/routing_figures/test_routing_figures.py | 26 +-- bin/rule_hook/env_file.py | 4 +- bin/rule_hook/main.py | 18 +- bin/rule_hook/reviewer_report.py | 10 +- bin/rule_hook/reviewer_rung.py | 4 +- bin/rule_hook/round_report.py | 5 +- bin/rule_hook/rules.py | 7 +- bin/rule_hook/test_rule_hook.py | 72 ++++--- bin/rule_hook/todo_check.py | 7 +- bin/run_heavy/main.py | 2 +- bin/run_heavy/test_run_heavy.py | 2 +- bin/rung_replay/command.py | 4 +- bin/score-outcomes | 3 +- bin/score_outcomes/main.py | 17 +- bin/score_outcomes/test_score_outcomes.py | 8 +- bin/subagent-rung | 3 +- bin/subagent_rung/main.py | 7 +- bin/subagent_rung/test_subagent_rung.py | 4 +- bin/task_bench/features/feature_tasks.py | 8 +- bin/task_bench/features/shipped_features.py | 6 +- bin/task_bench/features/test_feature_tasks.py | 6 +- .../features/test_shipped_features.py | 2 +- bin/task_bench/figures/gather.py | 10 +- bin/task_bench/figures/record_figures.py | 10 +- bin/task_bench/figures/test_gather.py | 10 +- bin/task_bench/figures/test_record_figures.py | 10 +- bin/task_bench/main.py | 20 +- bin/task_bench/test_task_bench.py | 20 +- bin/test_env.py | 2 +- bin/test_rank_todo.py | 4 +- bin/todo-item | 3 +- bin/todo_item/main.py | 4 +- bin/todo_item/test_todo_item.py | 12 +- .../test_touch_predictions.py | 2 +- bin/transcript_archive/__init__.py | 2 +- bin/transcript_archive/location.py | 4 +- .../test_transcript_archive.py | 2 +- docs/decisions.md | 28 +-- docs/reading-cost.md | 12 ++ reviewer-merge-trials/driver.py | 10 +- rules/goals-and-audience.md | 2 +- settings.json | 2 +- skills/larv-review/SKILL.md | 2 +- 142 files changed, 1095 insertions(+), 933 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 26f7f6d8..12033dfe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -89,7 +89,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, are th 4. A review rules the work below standard: systems-architect's BLOCK, a finding against the review standards' `quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up"). It doesn't fire where the fix changes only prose (`larv-review` §3 says what is prose): fix that on your own rung. When one fires, hand the hard part, edits included, to a subagent on the rung build-release's prompt names, one above yours. Open the subagent's prompt with the marker build-release's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung build-release's prompt names. Ask the human before going higher. Where build-release's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread. -- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`larv-review review-folder` prints it), and removes no image or file it did not create. +- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/build-release/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`larv-review review-folder` prints it), and removes no image or file it did not create. - Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer. - Where `rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest or a `docker run` line, pin a container image to its full patch version and a GitHub Action to a semver tag. @@ -105,7 +105,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, are th - PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title). - Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. - Branch for a plan item without a ticket: `item-`, in the worktree `-item-` beside the checkout, as `chunk-preflight` makes them. Under a `branch` template, `chunk-preflight` names both by the template. -- Where the project's config keeps a file in the config's folder, `~/.claude-projects//`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Two chunks may commit there at once, so commit only that file: `git commit -m -- <file>`, after `git add <file>` where it is new. Where git finds `index.lock` held, the other chunk is committing: try again. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title. +- Where the project's config keeps a file in the config's folder, `~/.config/build-release/<key>/`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Two chunks may commit there at once, so commit only that file: `git commit -m <title> -- <file>`, after `git add <file>` where it is new. Where git finds `index.lock` held, the other chunk is committing: try again. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title. - Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both. - On GitHub and Gitea, open a chunk's pull request as a draft, mark it ready and merge it with `chunk-pr`, which picks `gh` or `tea` from the remote; `chunk-pr --help` says how. Once it has merged, run `chunk-pr clean` in the chunk's worktree: it removes the worktree and the branch and fast-forwards the main checkout. diff --git a/README.md b/README.md index 46eeaa11..9d4351f0 100644 --- a/README.md +++ b/README.md @@ -83,29 +83,28 @@ Then pick a model with `/model`. Link `build-release` onto `PATH`: `ln -s ~/.claude/bin/build-release ~/.local/bin/build-release`. Every claude it starts, the interactive ones included, skips every permission prompt. build-release runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later. -Back up these four folders and one file: +The setup keeps what you write in the config folder, `~/.config/build-release/`, and what its tools write in the state folder, `~/.local/state/build-release/`. Where `XDG_CONFIG_HOME` or `XDG_STATE_HOME` is set, the folder is `build-release/` under the folder that variable names instead. Back up these four folders: -- `~/.claude-projects/`: each project's config, and a client project's plan and records. A project's `env-file`, if you keep it here as below, puts credentials in the backup, so keep the backup private. -- `~/.claude/loop-claude-models.json`: the model of each project, which build-release and do-epic write. -- `~/.claude/loop-claude-transcripts`: every transcript build-release keeps. Where you set `BUILD_RELEASE_TRANSCRIPTS`, back up the folder it names instead. -- `~/.claude/do-epic-transcripts`: the transcripts of do-epic's chunks. -- `~/.local/state/larv-review`: each chunk's review reports. +- `~/.config/build-release/`: each project's config, a client project's plan and records, and `models.json`, the model of each project, which build-release and do-epic write. A project's `env-file`, if you keep it here as below, puts credentials in the backup, so keep the backup private. +- `~/.local/state/build-release/transcripts`: every transcript build-release keeps. Where you set `BUILD_RELEASE_TRANSCRIPTS`, back up the folder it names instead. +- `~/.local/state/build-release/do-epic-transcripts`: the transcripts of do-epic's chunks. +- `~/.local/state/build-release/larv-review`: each chunk's review reports. Leave out Claude Code's memory files in `~/.claude/projects/<folder>/memory/`: Claude Code writes them, so they aren't part of this setup. To keep build-release's transcripts and the reports small, add a crontab line that gzips each transcript and review file 30 days after it last changed, and logs each run with its date: ```sh -17 4 * * * { date; $HOME/.claude/bin/compress-archives; } >> $HOME/.local/state/compress-archives.log 2>&1 +17 4 * * * { date; $HOME/.claude/bin/compress-archives; } >> $HOME/.local/state/build-release/compress-archives.log 2>&1 ``` Cron runs it with its own `PATH` and environment. Where the `python3` on cron's `PATH` is older than 3.14, or you set `BUILD_RELEASE_TRANSCRIPTS`, set `PATH` or that variable in the crontab too. -To get build-release's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes. +To get build-release's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.config/build-release/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.config/build-release/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes. ### Set up a project -Each project the loop runs in has a folder, `~/.claude-projects/<key>/`, where `<key>` is the project's name, and a config in it, `config.toml`. The folder is a git repo of its own, so the config has a history and a client's files never enter this repo. The loop commits each change it makes to a file there, such as the plan, in that repo, titled as its commits in the checkout. A project is a whole git checkout, never a subfolder of one. +Each project the loop runs in has a folder, `~/.config/build-release/<key>/`, where `<key>` is the project's name, and a config in it, `config.toml`. The folder is a git repo of its own, so the config has a history and a client's files never enter this repo. The loop commits each change it makes to a file there, such as the plan, in that repo, titled as its commits in the checkout. A project is a whole git checkout, never a subfolder of one. The config names the project's main checkout and the path of every file the loop keeps for it. No path setting has a default: `project-config` fails and names each setting a config leaves out. A path is `checkout:<path>` inside the checkout, `folder:<path>` inside the config's folder, or one that starts with `/` or `~/`. Every tool reads and writes each file at the path its setting gives, and `chunk-preflight` and `todo-item` print those paths for the agents. Five of the settings name the project's records: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`. Keep each file's name, such as `todo.md`: the rules for a file load by its name. A project of your own keeps every file but the principles and the review standards in its checkout: @@ -125,7 +124,7 @@ standards = "~/.claude/skills/larv-review/standards" `principles` and `standards` name the folders the reviewers hold the project to: the technical principles and the review standards. Both ship with this setup, at the paths above. A folder of your own replaces the shipped one. A standards folder must hold `quality.md`, `prose.md`, `comments.md` and `readme.md`, since the reviewers and the rules name those files. -A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it or searches a folder holding it with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path. +A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.config/build-release/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it or searches a folder holding it with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path. A project may also set `touch-predictions`, a path spelt as `changelog`'s is, such as `touch-predictions = "checkout:docs/touch-predictions.md"`. `touch-predictions record` appends each chunk's predicted files and parts there, beside those it touched. A project that leaves it out keeps no such record. @@ -167,7 +166,7 @@ A client that keeps its goals and audience in an epic's description names that e To name a chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`, set these three templates, with your Jira project's key in place of `ABC`: `branch = "ABC-{id}"`, `commit-title = "ABC-{id} - {summary}"` and `pull-request-title = "ABC-{id} - {summary}"`. `project-config --help` says how the templates work. ```sh -mkdir -p ~/.claude-projects/acme && cd ~/.claude-projects/acme +mkdir -p ~/.config/build-release/acme && cd ~/.config/build-release/acme git init $EDITOR config.toml git add config.toml && git commit -m "Add the config" @@ -176,9 +175,9 @@ cd ~/code/acme-billing && ~/.claude/bin/project-config The last line prints each setting's path once the config is complete. -`do-epic` keeps its settings per machine, not per project, in `~/.claude-projects/do-epic/`, two files for every epic: +`do-epic` keeps its settings per machine, not per project, in `~/.config/build-release/do-epic/`, two files for every epic: -- `config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.claude-projects`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that moves a finished chunk's issue, and closes a finished epic, and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic moves no issue to done and closes no epic, and a chunk that finishes stops with that reason. +- `config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.config/build-release`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that moves a finished chunk's issue, and closes a finished epic, and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic moves no issue to done and closes no epic, and a chunk that finishes stops with that reason. - `config.toml` fits do-epic to a team whose own automation moves issues, such as a CI job that moves an issue when its pull request merges. Two settings do: - `jira-unblocking-statuses` lists the statuses at which an issue's work has landed though Jira doesn't count it done yet, such as `["Release Ready"]`, in upper or lower case. An issue in one of them takes no chunk and no longer blocks the issues it blocks, and `--status` names the statuses beside each blocker. A status Jira counts as done always does both. The release reviews, which are the epic's last chunk, still wait until Jira counts every issue done: run `do-epic <EPIC-KEY>` then, to start them. - `jira-automation-moves-issues = true` keeps do-epic from moving the issue of a finished chunk in a repo: the automation moves it, and do-epic waits for that move before it starts what the issue blocks. An issue without a repo has no pull request, so do-epic still moves it, with `jira-finish-transition`. The setting needs `jira-unblocking-statuses`, which names the status the automation gives an issue whose pull request merged. @@ -194,7 +193,7 @@ An epic's description states the formula that puts its issues in order: once und Each repo an epic changes has a project config of its own, as in the rest of this section. `do-epic` fails and names each setting or file that is missing or invalid. -A project runs on the routing ladder this setup ships, `bin/model_routing/routing-ladder.json`: the rungs, least competent first, each a model at an effort, that build-release routes workers, subagents and reviews to. To run one project on other rungs, as when an outage or a client's account leaves it fewer models, copy that file to `~/.claude-projects/<key>/routing-ladder.json` and cut or change its rungs. Keep one model for each family, such as opus: Claude Code launches a subagent by its family's name. The project's file replaces the shipped ladder whole. build-release reads it as each cycle starts, and `subagent-rung` and rule-hook each time they run. The loop never commits it, so commit it in the folder's repo yourself only where it should last. Set the project's models to ones its ladder holds, for example with `BUILD_RELEASE_WORKER_MODEL` and `BUILD_RELEASE_JUDGE_MODEL`. A model off the ladder is not routed: every worker runs on that model, at the effort Claude Code's `settings.json` gives. Each cycle of a project on a ladder of its own says so on stderr, naming the file, and says where the worker's model is off it. `build-release --help` shows the file's shape. +A project runs on the routing ladder this setup ships, `bin/model_routing/routing-ladder.json`: the rungs, least competent first, each a model at an effort, that build-release routes workers, subagents and reviews to. To run one project on other rungs, as when an outage or a client's account leaves it fewer models, copy that file to `~/.config/build-release/<key>/routing-ladder.json` and cut or change its rungs. Keep one model for each family, such as opus: Claude Code launches a subagent by its family's name. The project's file replaces the shipped ladder whole. build-release reads it as each cycle starts, and `subagent-rung` and rule-hook each time they run. The loop never commits it, so commit it in the folder's repo yourself only where it should last. Set the project's models to ones its ladder holds, for example with `BUILD_RELEASE_WORKER_MODEL` and `BUILD_RELEASE_JUDGE_MODEL`. A model off the ladder is not routed: every worker runs on that model, at the effort Claude Code's `settings.json` gives. Each cycle of a project on a ladder of its own says so on stderr, naming the file, and says where the worker's model is off it. `build-release --help` shows the file's shape. ## Update @@ -216,7 +215,7 @@ Once the next release holds no item in `todo.md` and its release review has land bin/deploy-release --cut ``` -It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. A cut keeps each step it finished, with its time in UTC, in a file of its own under `~/.local/state/deploy-release/`. `deploy-release --help` lists the steps. Each other machine takes the release with Update. +It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. A cut keeps each step it finished, with its time in UTC, in a file of its own under `~/.local/state/build-release/deploy-release/`. `deploy-release --help` lists the steps. Each other machine takes the release with Update. A fix that must ship before `main`'s other unreleased work goes out as a patch release, such as 0.15.2 after v0.15.1. File its item under that release, merge its chunk, then cut it at once with the commits the chunk merged, as a range or one commit. A range leaves out its first commit, as git's `..` does, so start it at the commit before the chunk's first: diff --git a/bin/adf_codec/test_adf_codec.py b/bin/adf_codec/test_adf_codec.py index 464ec4e7..1fe9fffe 100644 --- a/bin/adf_codec/test_adf_codec.py +++ b/bin/adf_codec/test_adf_codec.py @@ -272,14 +272,14 @@ def not_slept(seconds): def test_a_heavy_slot_is_held_until_the_block_ends(tmp_path): with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, tmp_path, 1, not_said, not_slept, fcntl.flock) as held: assert held is None - assert slots.taken_slot(tmp_path / "run-heavy", 1, fcntl.flock) is None - slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1, fcntl.flock) + assert slots.taken_slot(tmp_path / "build-release" / "run-heavy", 1, fcntl.flock) is None + slot, fd = slots.taken_slot(tmp_path / "build-release" / "run-heavy", 1, fcntl.flock) os.close(fd) def test_a_process_under_run_heavy_takes_no_second_slot(tmp_path): - (tmp_path / "run-heavy").mkdir() - slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1, fcntl.flock) + (tmp_path / "build-release" / "run-heavy").mkdir(parents=True) + slot, fd = slots.taken_slot(tmp_path / "build-release" / "run-heavy", 1, fcntl.flock) try: with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path), slots.HELD: "0"}, tmp_path, 1, not_said, not_slept, fcntl.flock) as held: assert held is None @@ -288,9 +288,10 @@ def test_a_process_under_run_heavy_takes_no_second_slot(tmp_path): def test_a_heavy_slot_folder_that_cannot_be_made_yields_a_failure(tmp_path): - (tmp_path / "run-heavy").write_text("a file where the folder goes") + (tmp_path / "build-release").mkdir() + (tmp_path / "build-release" / "run-heavy").write_text("a file where the folder goes") with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, tmp_path, 1, not_said, not_slept, fcntl.flock) as held: - assert isinstance(held, Failure) and held.reason.startswith(f"cannot take a heavy slot in {tmp_path / 'run-heavy'}: ") + assert isinstance(held, Failure) and held.reason.startswith(f"cannot take a heavy slot in {tmp_path / 'build-release' / 'run-heavy'}: ") def test_container_run_runs_the_image_on_the_text(tmp_path): diff --git a/bin/agent_cycle/test_interrupt.py b/bin/agent_cycle/test_interrupt.py index 5c7393c9..e7e46c79 100644 --- a/bin/agent_cycle/test_interrupt.py +++ b/bin/agent_cycle/test_interrupt.py @@ -27,7 +27,7 @@ class Interrupts(unittest.TestCase): def setUp(self): self.home = pathlib.Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.home) - self.paths = paths.paths_from(self.home) + self.paths = paths.paths_from(self.home, {}) self.transcript = self.home / "t.jsonl" self.transcript.write_text(json.dumps(human("a")) + "\n") self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), Rung("m", "high"), str(self.transcript), {"BUILD_RELEASE_WORKER_RUNG": "m at high effort"}) diff --git a/bin/agent_cycle/test_run.py b/bin/agent_cycle/test_run.py index f16c578d..d1c89fee 100644 --- a/bin/agent_cycle/test_run.py +++ b/bin/agent_cycle/test_run.py @@ -64,7 +64,7 @@ class Cycles(unittest.TestCase): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) self.home = pathlib.Path(temp.name) - self.paths = paths.paths_from(self.home) + self.paths = paths.paths_from(self.home, {}) self.session = session.session_named("A proj a-driver", self.paths.claude_code_transcripts) self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {}) diff --git a/bin/branch_chunks/read.py b/bin/branch_chunks/read.py index bbac2f60..200d54e6 100644 --- a/bin/branch_chunks/read.py +++ b/bin/branch_chunks/read.py @@ -1,3 +1,4 @@ +from collections.abc import Mapping import pathlib from branch_chunks.fixes import blamed, fixing_changes, FixingChange, removed_work, Traced, with_fixes @@ -15,9 +16,9 @@ from project_config import templates READ_AT = {"plan": NOT_WORK[0], "comprehension-history": NOT_WORK[1], "reading-cost": NOT_WORK[2]} -def unsupported(checkout: str | None, home: pathlib.Path, run: Git = git) -> str | None: +def unsupported(checkout: str | None, home: pathlib.Path, env: Mapping[str, str], run: Git = git) -> str | None: """Why branch_chunks cannot tell what the chunks of checkout's project shipped, else the current directory's: its config under home puts the plan or a record where their commits are not read. None where it can, as for a checkout no config names.""" - config = located(checkout, home, run) + config = located(checkout, home, env, run) if isinstance(config, Failure): return None elsewhere = [label for name, path in READ_AT.items() for label, tracked in [held(config, name)] if tracked != path] diff --git a/bin/branch_chunks/test_branch_chunks.py b/bin/branch_chunks/test_branch_chunks.py index 333cfa4a..34de92e2 100644 --- a/bin/branch_chunks/test_branch_chunks.py +++ b/bin/branch_chunks/test_branch_chunks.py @@ -207,13 +207,13 @@ class Unsupported(unittest.TestCase): def test_says_which_files_the_config_puts_where_no_commits_are_read(self): checkout = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())).resolve() run = functools.partial(git, env=isolated_env()) - self.assertIsNone(unsupported(str(checkout), checkout, run), "no git checkout, so no config names it") + self.assertIsNone(unsupported(str(checkout), checkout, {}, run), "no git checkout, so no config names it") folder = configured(self, checkout) - home = folder.parents[1] - self.assertIsNone(unsupported(str(checkout), home, run)) + home = folder.parents[2] + self.assertIsNone(unsupported(str(checkout), home, {}, run)) config = folder / "config.toml" config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"').replace('"checkout:docs/reading-cost.md"', '"checkout:records/reading-cost.md"')) - self.assertEqual(unsupported(str(checkout), home, run), f"the project's config puts {folder}/todo.md, {checkout}/records/reading-cost.md elsewhere than todo.md, docs/comprehension-history.md, docs/reading-cost.md in the checkout, the only paths whose commits are read so far") + self.assertEqual(unsupported(str(checkout), home, {}, run), f"the project's config puts {folder}/todo.md, {checkout}/records/reading-cost.md elsewhere than todo.md, docs/comprehension-history.md, docs/reading-cost.md in the checkout, the only paths whose commits are read so far") class TracedTo(unittest.TestCase): diff --git a/bin/build-release b/bin/build-release index 7551c6b8..3028e9ea 100755 --- a/bin/build-release +++ b/bin/build-release @@ -10,4 +10,4 @@ from loop_effects import effects from build_release.loop import main from loop_state import paths -sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, pathlib.Path.cwd(), effects.system_effects(pathlib.Path.home(), os.environ))) +sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd(), effects.system_effects(pathlib.Path.home(), os.environ))) diff --git a/bin/build_release/loop/chunk_start.py b/bin/build_release/loop/chunk_start.py index a27ebff1..50baa539 100644 --- a/bin/build_release/loop/chunk_start.py +++ b/bin/build_release/loop/chunk_start.py @@ -37,13 +37,13 @@ def chunk_facts(loop: Loop) -> str: item = item_of(loop.window.name) done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root) facts = fresh_prompt.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else fresh_prompt.preflight_facts(done.stdout.strip()) - held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects) + held = held_beside(loop.window.name, loop.root, loop.paths, loop.env, loop.effects) return facts + (fresh_prompt.held_by_others(held) if held else "") def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure: """What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. Where announce is True, as when a chunk starts, it says UNSEEN_RELEASES for such a plan, so the human reads it once per chunk, not every cycle.""" - config = located(loop.root, loop.paths.home) + config = located(loop.root, loop.paths.home, loop.env) if isinstance(config, Failure): return config if announce and config.tracked("plan") is None: diff --git a/bin/build_release/loop/chunk_windows.py b/bin/build_release/loop/chunk_windows.py index dabcbabb..34659244 100644 --- a/bin/build_release/loop/chunk_windows.py +++ b/bin/build_release/loop/chunk_windows.py @@ -100,9 +100,9 @@ def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | No return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs)) -def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | NoItem | Failure: +def next_plan(root: str, home: pathlib.Path, env: typing.Mapping[str, str], effects: Effects) -> NextChunk | NoItem | Failure: """The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it.""" - config = located(root, home) + config = located(root, home, env) if isinstance(config, Failure): return config # A chunk that just merged left the plan on origin. A fetch that fails leaves the plan as last fetched, which chunk-preflight then reads too. @@ -116,18 +116,18 @@ def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | No def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | AwaitedMerges | Failure: """Starts a build-release in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started build-release. AwaitedMerges where chunks_to_start returns it. A Failure says why no chunk may start, or why one could not; those before it run.""" - config = located(loop_run.root, paths.home) + config = located(loop_run.root, paths.home, env) if isinstance(config, Failure): return config session = loop_session(loop_run.root, paths.home) handed = {name: value for name, value in env.items() if name.startswith(HANDED)} - with starting(project_lock(loop_run.root, paths.home)) as unlocked: + with starting(project_lock(loop_run.root, paths.home, env)) as unlocked: if unlocked: return unlocked windows = tmux.listed(session, effects.tmux) if refused := refusal(session, windows, loop_run.root, effects.tmux): return refused - chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, effects) + chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, env, effects) if isinstance(chunks, AwaitedMerges): return chunks for chunk in chunks: @@ -147,12 +147,12 @@ def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux) return None -def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, effects: Effects) -> list[str] | AwaitedMerges: +def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> list[str] | AwaitedMerges: """The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does. AwaitedMerges where no chunk runs or restarts and every item left awaits a person's merge.""" room = room_of(windows, loop_run.chunk, leaving, limit) if not room.left: return room.restart - plan = next_plan(loop_run.root, paths.home, effects) + plan = next_plan(loop_run.root, paths.home, env, effects) if isinstance(plan, Failure): # Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself. say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects) @@ -164,14 +164,14 @@ def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool return room.restart + [chunk for chunk in picked if chunk not in room.stopped] -def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]: +def held_beside(chunk: str, root: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> list[int]: """The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it.""" - wait_for_starts(root, paths.home) + wait_for_starts(root, paths.home, env) others = [window.name for window in tmux.listed(loop_session(root, paths.home), effects.tmux) if window.name != chunk] return sorted(held_items(others, project_key(root, paths.home), paths.claude_code_transcripts)) -def wait_for_starts(root: str, home: pathlib.Path) -> None: +def wait_for_starts(root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> None: """Returns once no loop of the project is starting windows: start_chunks holds the lock file `claims.LOCK` names while it starts them. Where the lock cannot be taken, it returns at once.""" - with starting(project_lock(root, home)): + with starting(project_lock(root, home, env)): pass diff --git a/bin/build_release/loop/main.py b/bin/build_release/loop/main.py index 5663ff31..26d0764e 100644 --- a/bin/build_release/loop/main.py +++ b/bin/build_release/loop/main.py @@ -133,10 +133,10 @@ def handed_on(loop_run: LoopRun, loop: Loop, start: StartChunks) -> Stop: def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop: """The cycle loop_run runs next, from the premises, the records, the project's models and its routing ladder read afresh, and the route the chunk runs on; the stop where one of them cannot be read.""" - premises = read_premises(loop.root, loop.paths.home) + premises = read_premises(loop.root, loop.paths.home, loop.env) if isinstance(premises, Failure): return Stop(1, premises.reason) - records = read_records(loop.root, loop.paths.home, loop.paths.claude_dir) + records = read_records(loop.root, loop.paths.home, loop.env, loop.paths.claude_dir) if isinstance(records, Failure): return Stop(1, records.reason) routing = project_routing(loop, fresh_prompt.DRIVER) diff --git a/bin/build_release/loop/routing_check.py b/bin/build_release/loop/routing_check.py index 1e4172e3..1f2e5672 100644 --- a/bin/build_release/loop/routing_check.py +++ b/bin/build_release/loop/routing_check.py @@ -1,4 +1,5 @@ """Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing: build-release measures review rounds…`.""" +from collections.abc import Mapping import pathlib from routing_figures import archive @@ -20,14 +21,14 @@ from text_files.utc_stamp import utc def check_routing(root: pathlib.Path, rung: Rung, loop: Loop) -> Stop | None: """Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. root is the archive's, and rung is the rung of the claude that puts the calls to the human.""" with archive.locked(root) as held: - new = new_calls(root, loop.paths, loop.effects) if held else [] + new = new_calls(root, loop.paths, loop.env, loop.effects) if held else [] if isinstance(new, Failure): say(f"routing figures: {new.reason}", loop.effects) return None return raise_calls(root, new, rung, loop) if new else None -def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] | Failure: +def new_calls(root: pathlib.Path, paths: Paths, env: Mapping[str, str], effects: Effects) -> list[Call] | Failure: """Once due, measures and keeps the figures, and returns their calls not raised since the latest reset; none while not due.""" cycle = archive.cycles(root) if isinstance(cycle, Failure): @@ -39,7 +40,7 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] if isinstance(raised, Failure): return raised say(f"\n=== cycle {cycle} across build-release's archive: measuring the routing figures ===", effects, stdout=True) - measured = archive.measure_archive(root, str(paths.home), raised.since, effects.git) + measured = archive.measure_archive(root, str(paths.home), env, raised.since, effects.git) if isinstance(measured, Failure): return measured # The shipped ladder, not the project's: the figures span every project. diff --git a/bin/build_release/loop/test_chunk_start.py b/bin/build_release/loop/test_chunk_start.py index 076331de..0789a6d5 100644 --- a/bin/build_release/loop/test_chunk_start.py +++ b/bin/build_release/loop/test_chunk_start.py @@ -50,7 +50,7 @@ class RouteSources(unittest.TestCase): unread = Failure("no git") fake = FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]) with contextlib.redirect_stderr(io.StringIO()) as stderr: - facts, held = chunk_start.chunk_start(a_loop(fake.effects(), root=root, session=opened, paths=paths.paths_from(folder.parents[1]))) + facts, held = chunk_start.chunk_start(a_loop(fake.effects(), root=root, session=opened, paths=paths.paths_from(folder.parents[2], {}))) self.assertEqual((facts, held.plan), ("", plan_of(TODO))) self.assertEqual([args for args in fake.made("git") if args[0] == "remote"], [["remote"]]) # An open session is no fresh chunk, so the human isn't told again of releases the plan cannot show. @@ -79,7 +79,7 @@ class RouteSources(unittest.TestCase): with tempfile.TemporaryDirectory() as root: folder = configured(self, pathlib.Path(root)) effects = dataclasses.replace(FakeEffects().effects(), git=git) - held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[1]))) + held = chunk_start.fetched_plan(a_loop(effects, root=root, paths=paths.paths_from(folder.parents[2], {}))) self.assertEqual(held.cut.changelog, "what origin/main:CHANGELOG.md holds\n") def test_passes_over_an_item_whose_pull_request_awaits_a_persons_merge_as_the_loops_forge_lists_them(self): @@ -96,33 +96,33 @@ class RouteSources(unittest.TestCase): folder = configured(self, pathlib.Path(root)) (folder / "config.toml").write_text((folder / "config.toml").read_text() + 'merge = "human"\n') fake = FakeEffects(forge=[f"12\thttps://github.com/o/r/pull/12\t{head}\tfalse\tfalse\n"] * 3) - held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[1]))) + held = chunk_start.fetched_plan(a_loop(dataclasses.replace(fake.effects(), git=git), root=root, paths=paths.paths_from(folder.parents[2], {}))) self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(7, ""), (3, "#12 https://github.com/o/r/pull/12"), (1, "")]) self.assertEqual(fake.made("forge")[0][:4], [root, "gh", "pr", "list"]) self.assertIsNone(chunk_start.plan_item(held, None, fake.effects()), "items 7 and 3 wait, so no item of the next release routes the chunk") - window = chunk_windows.next_plan(root, folder.parents[1], dataclasses.replace(fake.effects(), git=git)) + window = chunk_windows.next_plan(root, folder.parents[2], {}, dataclasses.replace(fake.effects(), git=git)) self.assertEqual((window.awaits_merge, fake.made("forge")[1][:4]), (True, [root, "gh", "pr", "list"]), "a window starts by the same pick") - stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[1]), dataclasses.replace(fake.effects(), git=git)) + stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[2], {}), {}, dataclasses.replace(fake.effects(), git=git)) self.assertEqual(stopped, chunk_windows.AwaitedMerges(window.why), "so the loop starts no chunk, and says which pull requests it waits on") def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self): with tempfile.TemporaryDirectory() as root: folder = configured(self, pathlib.Path(root)) - loop = a_loop(FakeEffects(git=[*ON_MAIN] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + loop = a_loop(FakeEffects(git=[*ON_MAIN] * 2).effects(), root=root, paths=paths.paths_from(folder.parents[2], {})) config = folder / "config.toml" - tracked = a_loop(FakeEffects(git=[*ON_MAIN, *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + tracked = a_loop(FakeEffects(git=[*ON_MAIN, *[Failure("no git")] * 4]).effects(), root=root, paths=paths.paths_from(folder.parents[2], {})) with contextlib.redirect_stderr(io.StringIO()) as stderr: chunk_start.fetched_plan(tracked) self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release") config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) (folder / "todo.md").write_text(TODO) unread = Failure("no git") - standing = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + standing = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[2], {})) with contextlib.redirect_stderr(io.StringIO()) as stderr: held = chunk_start.fetched_plan(standing) self.assertEqual((held.plan, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers") self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review build-release cannot call due is never skipped silently") - quiet = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1])) + quiet = a_loop(FakeEffects(git=[*ON_MAIN, unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[2], {})) with contextlib.redirect_stderr(io.StringIO()) as stderr: chunk_start.fetched_plan(quiet, announce=False) self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts") diff --git a/bin/build_release/loop/test_chunk_windows.py b/bin/build_release/loop/test_chunk_windows.py index 59b189f8..44d39e1d 100644 --- a/bin/build_release/loop/test_chunk_windows.py +++ b/bin/build_release/loop/test_chunk_windows.py @@ -99,14 +99,14 @@ class ChunkWindows(unittest.TestCase): def test_tells_a_chunk_the_items_the_projects_other_live_chunks_hold(self): with tempfile.TemporaryDirectory() as temp: home = pathlib.Path(temp) - held = paths.paths_from(home) + held = paths.paths_from(home, {}) folder = held.claude_code_transcripts / "-r" folder.mkdir(parents=True) lines = [assistant({"type": "text", "text": "Chunk items: 8 (L 1, E + I 2), 11 (L 2, E + I 3)"})] (folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines)) # Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item. fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n") - self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11]) + self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, {}, fake.effects()), [8, 9, 10, 11]) self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]]) @@ -118,13 +118,13 @@ class StartChunks(unittest.TestCase): made = tempfile.TemporaryDirectory() self.addCleanup(made.cleanup) self.root = pathlib.Path(made.name, "r") - self.home = configured(self, self.root).parents[1] + self.home = configured(self, self.root).parents[2] self.session = "loop-" + str(self.root).lstrip("/").replace("/", "-").replace(".", "-") # Items 1 and 2 overlap, so 2 waits; 3 runs beside 1. self.plan = plan_text("a.py", "a.py", "c.py") def limit(self, chunks): - config = self.home / ".claude-projects" / self.root.name / "config.toml" + config = self.home / ".config/build-release" / self.root.name / "config.toml" config.write_text(config.read_text() + f"parallel-chunks = {chunks}\n") def start(self, fake, chunk=None, leaving=False, plan=None, env=None, owner=None): @@ -134,7 +134,7 @@ class StartChunks(unittest.TestCase): ran = [] effects = dataclasses.replace(fake.effects(), git=self.git_reading(self.plan if plan is None else plan, ran)) with contextlib.redirect_stderr(io.StringIO()) as said: - started = chunk_windows.start_chunks(run, leaving, paths.paths_from(self.home), env or {}, self.LAUNCHER, effects) + started = chunk_windows.start_chunks(run, leaving, paths.paths_from(self.home, env or {}), env or {}, self.LAUNCHER, effects) self.said = said.getvalue() fetches = [args for args in ran if args[0] == "fetch"] self.planned = len(fetches) @@ -188,7 +188,7 @@ class StartChunks(unittest.TestCase): def test_leaves_out_the_items_a_running_chunk_names_on_its_chunk_items_line(self): self.limit(2) - transcripts = paths.paths_from(self.home).claude_code_transcripts + transcripts = paths.paths_from(self.home, {}).claude_code_transcripts folder = transcripts / "-r" folder.mkdir(parents=True) opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts) @@ -232,7 +232,7 @@ class StartChunks(unittest.TestCase): def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self): self.limit(2) - transcripts = paths.paths_from(self.home).claude_code_transcripts + transcripts = paths.paths_from(self.home, {}).claude_code_transcripts folder = transcripts / "-r" folder.mkdir(parents=True) opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts) @@ -256,10 +256,11 @@ class StartChunks(unittest.TestCase): def test_says_why_it_cannot_take_the_lock_on_starting_windows(self): (self.home / ".local" / "state").mkdir(parents=True) - (self.home / ".local" / "state" / "loop-claude").write_text("") + (self.home / ".local" / "state" / "build-release").mkdir(parents=True, exist_ok=True) + (self.home / ".local" / "state" / "build-release" / "claims").write_text("") started = self.start(FakeEffects()) self.assertIsInstance(started, Failure) - self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/loop-claude/"), started.reason) + self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/build-release/claims/"), started.reason) def test_an_error_raised_under_the_lock_is_not_reported_as_the_locks(self): with self.assertRaisesRegex(OSError, "the plan's disk is gone"): @@ -267,9 +268,10 @@ class StartChunks(unittest.TestCase): def test_a_chunk_reads_the_other_windows_where_it_cannot_take_the_lock(self): (self.home / ".local" / "state").mkdir(parents=True) - (self.home / ".local" / "state" / "loop-claude").write_text("") + (self.home / ".local" / "state" / "build-release").mkdir(parents=True, exist_ok=True) + (self.home / ".local" / "state" / "build-release" / "claims").write_text("") fake = FakeEffects(windows="item-7\t0\t@1\nitem-9\t1\t@3\n") - self.assertEqual(chunk_windows.held_beside("item-7", str(self.root), paths.paths_from(self.home), fake.effects()), [9]) + self.assertEqual(chunk_windows.held_beside("item-7", str(self.root), paths.paths_from(self.home, {}), {}, fake.effects()), [9]) def test_a_chunk_holds_its_own_item_and_those_on_its_latest_chunk_items_line(self): with tempfile.TemporaryDirectory() as temp: diff --git a/bin/build_release/loop/test_main.py b/bin/build_release/loop/test_main.py index c9fb2030..611c1fc8 100644 --- a/bin/build_release/loop/test_main.py +++ b/bin/build_release/loop/test_main.py @@ -129,7 +129,7 @@ class WindowStarts(unittest.TestCase): return list(started) if isinstance(started, tuple) else started with contextlib.redirect_stdout(io.StringIO()) as said: - stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME), pathlib.Path("/b/build-release"), CWD, fake.effects(), steps(start)) + stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME, env or {}), pathlib.Path("/b/build-release"), CWD, fake.effects(), steps(start)) return stop, said.getvalue() def test_refuses_to_start_anything_on_a_tmux_older_than_needed(self): @@ -156,8 +156,8 @@ class WindowStarts(unittest.TestCase): effects, env, launcher = fake.effects(), {"BUILD_RELEASE_X": "1"}, pathlib.Path("/b/build-release") asked = [] with contextlib.redirect_stdout(io.StringIO()): - main.run_loop(["do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects, steps(lambda *args: asked.append(args) or ["item-3"])) - self.assertEqual(asked, [(main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME), env, launcher, effects)]) + main.run_loop(["do it"], env, paths.paths_from(self.HOME, {}), launcher, CWD, effects, steps(lambda *args: asked.append(args) or ["item-3"])) + self.assertEqual(asked, [(main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME, {}), env, launcher, effects)]) def test_a_window_loop_runs_its_chunk_in_its_own_session_and_window_and_hands_on_once_it_finished(self): fake = FakeEffects(git=["/r\n"]) @@ -171,8 +171,8 @@ class WindowStarts(unittest.TestCase): taken = steps(lambda *args: started.append(args) or [], fingerprint=lambda launcher: "", exec_if_edited=lambda *args: None, next_cycle=lambda *args: cycles.append(args) or cycle, run_cycle=lambda cycle: concluded.pop(0), closed_cycle=lambda *args: closed.pop(0), check_routing=lambda *args: None) with contextlib.redirect_stdout(io.StringIO()): - stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects, taken) - loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=paths.paths_from(self.HOME), env=env, launcher=launcher, effects=effects) + stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME, {}), launcher, CWD, effects, taken) + loop = this_loop.Loop(root="/r", session=session.session_named("A r build-release item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=paths.paths_from(self.HOME, {}), env=env, launcher=launcher, effects=effects) self.assertEqual(stop, Stop(0, "")) self.assertEqual(cycles, [(main.LoopRun(1, "/r", "do it", "", chunk="item-3"), loop), (main.LoopRun(2, "/r", "do it", "", chunk="item-3"), loop)]) self.assertEqual(started, [(main.LoopRun(2, "/r", "do it", "", chunk="item-3"), True, loop.paths, env, launcher, effects)]) @@ -180,7 +180,7 @@ class WindowStarts(unittest.TestCase): def window_loop(self, cycles, env, **doubles): """run_loop's stop for item-3's window loop, and each step it took with what it handed that step. Each step answers as its double in `doubles` does, else as a cycle without a stop: next_cycle answers the next of `cycles`, run_cycle an unfinished verdict, and closed_cycle the run with one more unfinished verdict.""" fake, calls, cycles = FakeEffects(git=["/r\n"]), [], list(cycles) - effects, launcher, home = fake.effects(), pathlib.Path("/b/build-release"), paths.paths_from(self.HOME) + effects, launcher, home = fake.effects(), pathlib.Path("/b/build-release"), paths.paths_from(self.HOME, env or {}) self.unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished)) answers = {"fingerprint": lambda *args: "print-1", "exec_if_edited": lambda *args: None, "next_cycle": lambda *args: cycles.pop(0), "run_cycle": lambda *args: self.unfinished, "closed_cycle": lambda run, *args: dataclasses.replace(run, unfinished_run=run.unfinished_run + 1), "check_routing": lambda *args: None, **doubles} @@ -246,7 +246,7 @@ class WindowStarts(unittest.TestCase): fake = FakeEffects(git=["/r\n"]) effects = dataclasses.replace(fake.effects(), tmux_on_terminal=lambda args: 1) with contextlib.redirect_stdout(io.StringIO()): - stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME), pathlib.Path("/b/build-release"), CWD, effects, steps(lambda *args: ["item-3"])) + stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME, {}), pathlib.Path("/b/build-release"), CWD, effects, steps(lambda *args: ["item-3"])) self.assertEqual(stop, Stop(1, "`tmux attach-session -t =loop-r` failed; the chunks go on in the tmux session")) def test_a_window_loop_outside_tmux_stops(self): @@ -273,7 +273,7 @@ class WindowStarts(unittest.TestCase): class StopDms(unittest.TestCase): def run_main(self, argv, fake): with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()): - code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "build-release"), CWD, fake.effects()) + code = main.main(argv, {}, paths.paths_from(pathlib.Path(home), {}), pathlib.Path(home, "build-release"), CWD, fake.effects()) return code, said.getvalue() def exit_code(self, run, fake): @@ -325,7 +325,7 @@ class StopDms(unittest.TestCase): class OwnLadder(unittest.TestCase): def test_a_cycle_on_a_projects_own_ladder_names_its_file_and_says_where_the_workers_model_is_off_it(self): - file = pathlib.Path("/h/.claude-projects/acme/routing-ladder.json") + file = pathlib.Path("/h/.config/build-release/acme/routing-ladder.json") self.assertEqual(main.own_ladder(file, "claude-fable-5-2", False), f"routing on the project's own ladder, {file}.") self.assertEqual(main.own_ladder(file, "claude-opus-5-5", True), f"routing on the project's own ladder, {file}. claude-opus-5-5 is not on it, so the worker runs on claude-opus-5-5 unrouted; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run.") diff --git a/bin/build_release/loop/test_routing_check.py b/bin/build_release/loop/test_routing_check.py index f9ceb901..19da54c5 100644 --- a/bin/build_release/loop/test_routing_check.py +++ b/bin/build_release/loop/test_routing_check.py @@ -33,7 +33,7 @@ class RoutingCheck(unittest.TestCase): self.home = pathlib.Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.home) self.root = self.home / "archive" - self.paths = paths.paths_from(self.home) + self.paths = paths.paths_from(self.home, {}) self.session = session.session_named("A log build-release", self.paths.claude_code_transcripts) def loop(self, fake): diff --git a/bin/build_release/loop/usage.py b/bin/build_release/loop/usage.py index 62e0066b..7a86d33d 100644 --- a/bin/build_release/loop/usage.py +++ b/bin/build_release/loop/usage.py @@ -3,8 +3,9 @@ HELP = """Run a task as headless claude cycles; a judge interrupts only when a d usage: build-release <task> Run it anywhere inside a project checkout whose goals file has ## Goals and ## Audience, the -premises. The goals file is the one the project's config, ~/.claude-projects/<key>/config.toml, sets -as goals-and-audience: a file, or a Jira epic's description. `project-config goals-and-audience` +premises. The goals file is the one the project's config, ~/.config/build-release/<key>/config.toml, +sets as goals-and-audience: a file, or a Jira epic's description. `project-config +goals-and-audience` prints where it is. The task runs at the checkout root. Each cycle a worker runs the task. A chunk's first worker prompt also quotes the premises. They, with code health (the setup's CLAUDE.md → "Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the @@ -78,9 +79,9 @@ worker to find the facts itself. At every interrupt, and as every cycle ends, Ctrl-C and a failure included, the claude session's transcript is copied into a folder per chunk under $BUILD_RELEASE_TRANSCRIPTS/<key> (default root -~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task, -then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC -time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py. +~/.local/state/build-release/transcripts), named by its hash, with an outcomes file beside it: the +task, then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its +UTC time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py. A worker's claude can print its final result and then keep waiting on a background shell that never ends. Every 5 minutes without output from that claude after its final result, build-release @@ -110,7 +111,7 @@ characters to a file and see its path and the first 2,000 characters (BASH_MAX_O bin/claude_code/output_limits.py). Every claude build-release starts runs the project's model, saved per <key> in -~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker, +~/.config/build-release/models.json and read each cycle, unless routing, below, puts the worker, the session /talk opens and the judge on another rung, a model at an effort. A project without an entry, as on its first run, is asked for one on the terminal. BUILD_RELEASE_JUDGE_MODEL overrides the model for the judge, BUILD_RELEASE_WORKER_MODEL for the worker and the session /talk opens; with @@ -142,8 +143,8 @@ or max: It holds one model of each family, such as opus, since the Agent tool launches a subagent or a review by its family's name. This setup ships one, bin/model_routing/routing-ladder.json. A project -that keeps a routing-ladder.json in its config's folder, ~/.claude-projects/<key>/, runs on that -ladder instead, whole: write there every rung the project may run on. build-release reads the +that keeps a routing-ladder.json in its config's folder, ~/.config/build-release/<key>/, runs on +that ladder instead, whole: write there every rung the project may run on. build-release reads the project's ladder as each cycle starts, says on stderr where the project runs on its own, and never commits the file. subagent-rung and rule-hook read the same ladder; the routing figures, judge-replay and review-replay, which span every project, read the shipped one. diff --git a/bin/build_release/test_black_box.py b/bin/build_release/test_black_box.py index 39619b51..c24f3655 100644 --- a/bin/build_release/test_black_box.py +++ b/bin/build_release/test_black_box.py @@ -325,13 +325,13 @@ class Checkout: return self.home / ".claude.json" def models_file(self): - return self.home / ".claude" / "loop-claude-models.json" + return self.home / ".config/build-release" / "models.json" def transcripts(self): return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl")) def archive(self): - return pathlib.Path(self.env.get("BUILD_RELEASE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts")) + return pathlib.Path(self.env.get("BUILD_RELEASE_TRANSCRIPTS", self.home / ".local/state/build-release" / "transcripts")) def archived(self): """Each archived transcript's outcomes, with every UTC stamp replaced by <UTC> and every setup version by <config>, after checking the copy is named by its content hash.""" @@ -397,10 +397,10 @@ class Premises(unittest.TestCase): run = checkout.run([worker()]) self.assertEqual((run.code, run.calls), (1, [])) self.assertEqual(run.stderr.strip(), f"cannot read {checkout.root}/README.md: Is a directory - no premises.") - (checkout.home / ".claude-projects" / "proj" / "config.toml").unlink() + (checkout.home / ".config/build-release" / "proj" / "config.toml").unlink() run = checkout.run([worker()]) self.assertEqual((run.code, run.calls), (1, [])) - self.assertEqual(run.stderr.strip(), f"no config names the checkout {checkout.root}: write ~/.claude-projects/<key>/config.toml, as `project-config --help` shows - no premises.") + self.assertEqual(run.stderr.strip(), f"no config names the checkout {checkout.root}: write {checkout.home}/.config/build-release/<key>/config.toml, as `project-config --help` shows - no premises.") (checkout.temp / "fake-bin" / "git").unlink() run = checkout.run([worker()]) self.assertEqual((run.code, run.calls), (1, [])) @@ -512,7 +512,7 @@ class Cycles(unittest.TestCase): def test_routes_on_the_ladder_the_projects_config_folder_holds_in_place_of_the_shipped_one(self): checkout = Checkout(self) checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-fable-5-2" - ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json" + ladder = checkout.home / ".config/build-release" / "proj" / "routing-ladder.json" ladder.write_text('[{"model": "claude-fable-5-2", "effort": "low"}, {"model": "claude-fable-5-2", "effort": "max"}]') checkout.commit_plan(CHEAP) run = checkout.run([worker(), judge(), worker(), judge(), worker()]) @@ -524,7 +524,7 @@ class Cycles(unittest.TestCase): def test_says_where_the_projects_own_ladder_leaves_out_the_workers_model_and_says_nothing_on_the_shipped_one(self): checkout = Checkout(self) self.assertNotIn("own ladder", checkout.run([worker()]).stderr) - ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json" + ladder = checkout.home / ".config/build-release" / "proj" / "routing-ladder.json" ladder.write_text('[{"model": "claude-fable-5-2", "effort": "low"}]') run = checkout.run([worker()]) self.assertIn(f"routing on the project's own ladder, {ladder}. worker-model is not on it, so the worker runs on worker-model unrouted; BUILD_RELEASE_WORKER_MODEL and BUILD_RELEASE_JUDGE_MODEL name other models for a run.\n", run.stderr) @@ -533,7 +533,7 @@ class Cycles(unittest.TestCase): def test_reads_the_projects_ladder_afresh_each_cycle_and_exits_1_once_it_holds_a_fault(self): checkout = Checkout(self) checkout.env["BUILD_RELEASE_WORKER_MODEL"] = "claude-fable-5-2" - ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json" + ladder = checkout.home / ".config/build-release" / "proj" / "routing-ladder.json" ladder.write_text('[{"model": "claude-fable-5-2", "effort": "high"}]') checkout.env["FAKE_CLAUDE_EDIT"] = str(ladder.parent) run = checkout.run([worker(replace=["routing-ladder.json", '"high"}', '"high"},']), judge()]) @@ -672,7 +672,7 @@ class Cycles(unittest.TestCase): checkout.archive().write_text("in the way") run = checkout.run([worker(say="landed-it"), judge(finished=True, evidence="landed-it")]) self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) - self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript: .*/loop-claude-transcripts/proj: Not a directory$") + self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not archive the transcript: .*/build-release/transcripts/proj: Not a directory$") self.assertEqual(run.stderr.count("could not archive the transcript"), 1) session = argument(run.calls[0], "--session-id") checkout.archive().unlink() @@ -820,7 +820,7 @@ class Windows(unittest.TestCase): checkout = Checkout(self) checkout.commit_plan(BESIDE) if parallel: - config = checkout.home / ".claude-projects" / "proj" / "config.toml" + config = checkout.home / ".config/build-release" / "proj" / "config.toml" config.write_text(f"parallel-chunks = {parallel}\n" + config.read_text()) return checkout @@ -944,11 +944,11 @@ class Interrupt(unittest.TestCase): def test_sends_the_dm_through_the_notifier_and_env_file_the_config_names_and_no_credential_reaches_a_prompt_a_line_printed_or_a_file_written(self): checkout = Checkout(self) token = "tok-3f9a1c7e-sentinel" - env_file = checkout.home / ".claude-projects" / "proj.env" + env_file = checkout.home / ".config/build-release" / "proj.env" env_file.write_text(f"MATTERMOST_URL=https://127.0.0.1:1\nMATTERMOST_TOKEN={token}\nMATTERMOST_RECIPIENT=lilleman\n") env_file.chmod(0o600) - with (checkout.home / ".claude-projects" / "proj" / "config.toml").open("a") as config: - config.write('env-file = "~/.claude-projects/proj.env"\nnotifier = "mattermost"\n') + with (checkout.home / ".config/build-release" / "proj" / "config.toml").open("a") as config: + config.write('env-file = "~/.config/build-release/proj.env"\nnotifier = "mattermost"\n') run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertIn("could not DM you: cannot reach https://127.0.0.1:1", run.stderr) @@ -1054,7 +1054,7 @@ class Models(unittest.TestCase): def test_keeps_the_models_file_mode_and_other_projects_when_saving(self): checkout = Checkout(self) del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"] - checkout.models_file().parent.mkdir(parents=True) + checkout.models_file().parent.mkdir(parents=True, exist_ok=True) checkout.models_file().write_text(json.dumps({"other": "model-x"})) checkout.models_file().chmod(0o640) def saved_elsewhere(): @@ -1092,7 +1092,8 @@ class Models(unittest.TestCase): assert_not_root(self) checkout = Checkout(self) del checkout.env["BUILD_RELEASE_JUDGE_MODEL"], checkout.env["BUILD_RELEASE_WORKER_MODEL"] - checkout.models_file().parent.mkdir(parents=True, mode=0o500) + checkout.models_file().parent.mkdir(parents=True, exist_ok=True) + checkout.models_file().parent.chmod(0o500) self.addCleanup(checkout.models_file().parent.chmod, 0o700) run = checkout.run([worker()], terminal_input="custom-model\n") self.assertEqual((run.code, run.calls), (1, [])) diff --git a/bin/chunk_driver/claims.py b/bin/chunk_driver/claims.py index fb3ab695..1c925800 100644 --- a/bin/chunk_driver/claims.py +++ b/bin/chunk_driver/claims.py @@ -4,16 +4,15 @@ An entry point holds `starting` on `project_lock` while it lists the windows of """ import contextlib import fcntl +from collections.abc import Mapping import pathlib import typing from failure import Failure from transcript_archive.project_key import project_key -from loop_state.paths import STATE_FOLDER +from loop_state.paths import state_folder from agent_cycle import tmux -# Under the home folder, a folder per project key holds LOCK. -CLAIMS = f"{STATE_FOLDER}/loop-claude" # The file an entry point keeps locked with flock while it lists the windows of a project's chunks and starts new ones. Two loops whose chunks finish together then don't start a chunk twice, and do-epic, which holds the same lock, never starts a chunk in a checkout while build-release does. LOCK = "starting" # The flag that tells the entry point in a window its chunk, as `--chunk item-372` for build-release and `--chunk ABC-34 ABC-12` for do-epic. Nobody types it, so no panel picked it. @@ -47,9 +46,14 @@ def locked(file: pathlib.Path) -> typing.Iterator[Failure | None]: yield None -def project_lock(root: str, home: pathlib.Path) -> pathlib.Path: +def claims_folder(state: pathlib.Path) -> pathlib.Path: + """The folder, in the state folder, that holds a folder per project key for its LOCK.""" + return state / "claims" + + +def project_lock(root: str, home: pathlib.Path, env: Mapping[str, str]) -> pathlib.Path: """The folder of the LOCK that everything starting a chunk in the checkout root holds.""" - return home / CLAIMS / project_key(root, home) + return claims_folder(state_folder(env, home)) / project_key(root, home) def loop_session(root: str, home: pathlib.Path) -> str: diff --git a/bin/chunk_driver/cycle_start.py b/bin/chunk_driver/cycle_start.py index a5f2c716..ceb0aa0f 100644 --- a/bin/chunk_driver/cycle_start.py +++ b/bin/chunk_driver/cycle_start.py @@ -52,7 +52,7 @@ def project_routing(loop: Loop, driver: str) -> Routing | Stop: models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, driver, loop.effects) if isinstance(models, Stop): return models - ladder_file = project_ladder_file(loop.root, loop.paths.home) + ladder_file = project_ladder_file(loop.root, loop.paths.home, loop.env) return Stop(1, ladder_file.reason) if isinstance(ladder_file, Failure) else routing_on(models, ladder_file) diff --git a/bin/chunk_driver/doubles.py b/bin/chunk_driver/doubles.py index ef93b53b..80bdb9f6 100644 --- a/bin/chunk_driver/doubles.py +++ b/bin/chunk_driver/doubles.py @@ -12,5 +12,5 @@ from agent_cycle.doubles import WINDOW def a_loop(effects: Effects, **fields: typing.Any) -> Loop: """A loop in /r on effects, with fields in place of its defaults.""" home = pathlib.Path("/h") - defaults = {"root": "/r", "session": session.session_named("A proj a-driver", paths.paths_from(home).claude_code_transcripts), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/a-driver"), "window": WINDOW} + defaults = {"root": "/r", "session": session.session_named("A proj a-driver", paths.paths_from(home, {}).claude_code_transcripts), "paths": paths.paths_from(home, {}), "env": {}, "launcher": pathlib.Path("/b/a-driver"), "window": WINDOW} return Loop(**{**defaults, **fields}, effects=effects) diff --git a/bin/chunk_driver/project/model_choice.py b/bin/chunk_driver/project/model_choice.py index a30c62a4..0797cc23 100644 --- a/bin/chunk_driver/project/model_choice.py +++ b/bin/chunk_driver/project/model_choice.py @@ -5,7 +5,7 @@ import sys import typing from claude_code.model_catalog import catalog_models -from chunk_driver.claims import CLAIMS, locked +from chunk_driver.claims import claims_folder, locked from loop_effects.effects import Effects, say from failure import Failure from agent_cycle.stop import needs_human, needs_terminal, Stop @@ -21,7 +21,7 @@ class Models: # The environment variables that name the judge's and the worker's model for one run, over the model saved or configured. JUDGE_MODEL = "BUILD_RELEASE_JUDGE_MODEL" WORKER_MODEL = "BUILD_RELEASE_WORKER_MODEL" -# The file, in CLAIMS under the home folder, that save_model keeps locked with flock while it rereads and replaces the models file. The models file's own folder is a checkout of this setup, which takes no lock file. +# The file, in the claims folder, that save_model keeps locked with flock while it rereads and replaces the models file. The models file's own folder is the config folder, which a person backs up, so it takes no lock file. MODELS_LOCK = "models.lock" @@ -59,7 +59,7 @@ def get_or_ask_model(project_key: str, paths: Paths, driver: str, effects: Effec def save_model(project_key: str, chosen: str, paths: Paths, replace: typing.Callable[[pathlib.Path, bytes], Failure | None]) -> Failure | None: """Adds the project's model to the models file, whose only writer this is, through replace, which writes a file as replace_file does. It holds MODELS_LOCK from its read to its write, so two entry points that save at once both keep their pick.""" saved = paths.models_file - with locked(paths.home / CLAIMS / MODELS_LOCK) as unlocked: + with locked(claims_folder(paths.state_folder) / MODELS_LOCK) as unlocked: if unlocked: return Failure(f"could not save the model in {saved}: {unlocked.reason}") # Read under the lock: another entry point may have saved its project while this one waited on the human. diff --git a/bin/chunk_driver/project/premises.py b/bin/chunk_driver/project/premises.py index ab7154b4..391d9994 100644 --- a/bin/chunk_driver/project/premises.py +++ b/bin/chunk_driver/project/premises.py @@ -1,3 +1,4 @@ +from collections.abc import Mapping import pathlib from failure import Failure @@ -6,9 +7,9 @@ from project_config.main import located from plan.goals_file import section -def read_premises(root: str, home: pathlib.Path) -> str | Failure: +def read_premises(root: str, home: pathlib.Path, env: Mapping[str, str]) -> str | Failure: """Where the goals file is kept, then its ## Goals and ## Audience. The goals file is the one that the config of root's checkout, under home, names: a file or a Jira epic's description. A Failure where no config names the checkout, or the goals file cannot be read, is missing or empty, lacks a section, holds one twice or leaves one empty.""" - config = located(root, home) + config = located(root, home, env) if isinstance(config, Failure): return Failure(f"{config.reason} - no premises.") goals = goals_store(config) diff --git a/bin/chunk_driver/project/records.py b/bin/chunk_driver/project/records.py index b25b9bdc..bb6042fe 100644 --- a/bin/chunk_driver/project/records.py +++ b/bin/chunk_driver/project/records.py @@ -1,3 +1,4 @@ +from collections.abc import Mapping import pathlib from loop_state.paths import CLAUDE_HOME @@ -22,7 +23,7 @@ HUMAN_RULE_NAMES = (f"~/{CLAUDE_HOME}/{HUMAN_RULES_FILE}", f"~/{CLAUDE_HOME}/{HU CONSEQUENCE = "the judge cannot read the records" -def read_records(root: str | None, home: pathlib.Path, claude_dir: pathlib.Path, first: tuple[tuple[str, str], ...] = ()) -> str | Failure: +def read_records(root: str | None, home: pathlib.Path, env: Mapping[str, str], claude_dir: pathlib.Path, first: tuple[tuple[str, str], ...] = ()) -> str | Failure: """The project's `AGENTS.md` and decision log, then the human's rules, CLAUDE.md first, each headed by its name. One that does not exist, or is empty, is left out. A text that several of them hold appears once, headed by all their names. `AGENTS.md` is read where the config under home of root's project puts it, and the decision log from the store that config names. Each is headed by its name in RECORD_FILES wherever it is kept. @@ -31,7 +32,7 @@ def read_records(root: str | None, home: pathlib.Path, claude_dir: pathlib.Path, texts: list[tuple[str, str | Failure]] = list(first) rules = [claude_dir / HUMAN_RULES_FILE, *sorted((claude_dir / HUMAN_RULE_DIR).glob("*.md"))] if root is not None: - config = located(root, home) + config = located(root, home, env) if isinstance(config, Failure): return Failure(f"{config.reason} - {CONSEQUENCE}.") rules += sorted(config.paths["standards"].glob("*.md")) diff --git a/bin/chunk_driver/project/test_model_choice.py b/bin/chunk_driver/project/test_model_choice.py index 8113b06e..4608f4da 100644 --- a/bin/chunk_driver/project/test_model_choice.py +++ b/bin/chunk_driver/project/test_model_choice.py @@ -30,8 +30,8 @@ class ModelsOfARun(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) - self.paths = paths_from(pathlib.Path(temp.name)) - self.paths.models_file.parent.mkdir() + self.paths = paths_from(pathlib.Path(temp.name), {}) + self.paths.models_file.parent.mkdir(parents=True) def test_a_run_that_names_both_models_reads_no_models_file_and_asks_nothing(self): self.paths.models_file.write_text("not json") @@ -76,17 +76,17 @@ class SavingAModel(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) - self.paths = paths_from(pathlib.Path(temp.name)) - self.lock = self.paths.home / ".local/state/loop-claude/models.lock" + self.paths = paths_from(pathlib.Path(temp.name), {}) + self.lock = self.paths.home / ".local/state/build-release/claims/models.lock" def test_adds_the_projects_model_to_those_the_file_holds(self): - self.paths.models_file.parent.mkdir() + self.paths.models_file.parent.mkdir(parents=True) self.paths.models_file.write_text(json.dumps({"other": "model-x"})) self.assertIsNone(model_choice.save_model("proj", "model-b", self.paths, replace_file)) self.assertEqual(json.loads(self.paths.models_file.read_text()), {"other": "model-x", "proj": "model-b"}) def test_writes_the_file_for_a_human_to_merge_into_a_project_per_tab_indented_line_in_the_order_of_their_keys(self): - self.paths.models_file.parent.mkdir() + self.paths.models_file.parent.mkdir(parents=True) self.paths.models_file.write_text(json.dumps({"zebra": "model-z", "other": "model-x"})) self.assertIsNone(model_choice.save_model("proj", "model-b", self.paths, replace_file)) self.assertEqual(self.paths.models_file.read_text(), '{\n\t"other": "model-x",\n\t"proj": "model-b",\n\t"zebra": "model-z"\n}') @@ -100,7 +100,7 @@ class SavingAModel(unittest.TestCase): return False def test_holds_the_models_lock_from_its_read_to_its_write(self): - self.paths.models_file.parent.mkdir() + self.paths.models_file.parent.mkdir(parents=True) held = [] class Watched(pathlib.PosixPath): @@ -119,7 +119,7 @@ class SavingAModel(unittest.TestCase): self.assertFalse(self.lock_is_held()) def test_doesnt_save_anything_where_it_cannot_take_the_lock(self): - self.paths.models_file.parent.mkdir() + self.paths.models_file.parent.mkdir(parents=True) self.lock.parent.parent.mkdir(parents=True) self.lock.parent.write_text("") saved = model_choice.save_model("proj", "model-b", self.paths, replace_file) @@ -128,7 +128,7 @@ class SavingAModel(unittest.TestCase): self.assertFalse(self.paths.models_file.exists()) def test_a_pick_is_saved_through_save_model_alone(self): - self.paths.models_file.parent.mkdir() + self.paths.models_file.parent.mkdir(parents=True) fake, held = FakeEffects(inputs=["my-model"]), [] def replace(path: pathlib.Path, data: bytes) -> Failure: diff --git a/bin/chunk_driver/project/test_records.py b/bin/chunk_driver/project/test_records.py index 4766709f..252606ac 100644 --- a/bin/chunk_driver/project/test_records.py +++ b/bin/chunk_driver/project/test_records.py @@ -16,42 +16,42 @@ class Records(unittest.TestCase): with tempfile.TemporaryDirectory() as root: claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") config = configured(self, pathlib.Path(root), home=claude_md.parents[1]) / "config.toml" - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "") + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent), "") claude_md.parent.mkdir(parents=True) claude_md.write_text("# Global\n") - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "From ~/.claude/CLAUDE.md:\n# Global") + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent), "From ~/.claude/CLAUDE.md:\n# Global") pathlib.Path(root, "docs").mkdir() pathlib.Path(root, "docs", "decisions.md").write_text("# Decisions\n") pathlib.Path(root, "AGENTS.md").write_text("\n# Rules\n") - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global") + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent), "From AGENTS.md:\n# Rules\n\nFrom docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global") pathlib.Path(claude_md.parent, "rules").mkdir() pathlib.Path(claude_md.parent, "rules", "todo-items.md").write_text("# Todo\n") pathlib.Path(claude_md.parent, "rules", "goals-and-audience.md").write_text("# Goals\n") pathlib.Path(claude_md.parent, "rules", "notes.txt").write_text("not a rule\n") pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True) pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n") - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/goals-and-audience.md:\n# Goals\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments")) + self.assertTrue(records.read_records(root, claude_md.parents[1], {}, claude_md.parent).endswith("From ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/goals-and-audience.md:\n# Goals\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments")) config.write_text(config.read_text().replace('"~/.claude/skills/larv-review/standards"', '"~/review-standards"')) pathlib.Path(claude_md.parents[1], "review-standards").mkdir() pathlib.Path(claude_md.parents[1], "review-standards", "quality.md").write_text("# Ours\n") - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/review-standards/quality.md:\n# Ours"), "the config's standards folder replaces the default") + self.assertTrue(records.read_records(root, claude_md.parents[1], {}, claude_md.parent).endswith("From ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/review-standards/quality.md:\n# Ours"), "the config's standards folder replaces the default") config.write_text(config.read_text().replace('"~/review-standards"', f'"{root}/standards"')) pathlib.Path(root, "standards").mkdir() pathlib.Path(root, "standards", "quality.md").write_text("# Elsewhere\n") - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith(f"From {root}/standards/quality.md:\n# Elsewhere"), "a folder outside home is named in full") + self.assertTrue(records.read_records(root, claude_md.parents[1], {}, claude_md.parent).endswith(f"From {root}/standards/quality.md:\n# Elsewhere"), "a folder outside home is named in full") config.write_text(config.read_text().replace('"checkout:AGENTS.md"', '"checkout:docs/decisions.md"')) - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From AGENTS.md and docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global"), "a file the config names for two records appears once") + self.assertTrue(records.read_records(root, claude_md.parents[1], {}, claude_md.parent).startswith("From AGENTS.md and docs/decisions.md:\n# Decisions\n\nFrom ~/.claude/CLAUDE.md:\n# Global"), "a file the config names for two records appears once") config.write_text(config.read_text().replace('"checkout:docs/decisions.md"', '"checkout:AGENTS.md"', 1)) config.write_text(config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"').replace('"checkout:docs/decisions.md"', '"folder:log/decisions.md"')) - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From ~/.claude/CLAUDE.md:\n# Global"), "the checkout's AGENTS.md and docs/decisions.md are its owners'") + self.assertTrue(records.read_records(root, claude_md.parents[1], {}, claude_md.parent).startswith("From ~/.claude/CLAUDE.md:\n# Global"), "the checkout's AGENTS.md and docs/decisions.md are its owners'") pathlib.Path(config.parent, "log").mkdir() pathlib.Path(config.parent, "log", "decisions.md").write_text("# Ours\n") pathlib.Path(config.parent, "AGENTS.md").write_text("# Our rules\n") - self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From AGENTS.md:\n# Our rules\n\nFrom docs/decisions.md:\n# Ours\n\nFrom ~/.claude/CLAUDE.md:\n# Global")) + self.assertTrue(records.read_records(root, claude_md.parents[1], {}, claude_md.parent).startswith("From AGENTS.md:\n# Our rules\n\nFrom docs/decisions.md:\n# Ours\n\nFrom ~/.claude/CLAUDE.md:\n# Global")) config.unlink() - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"no config names the checkout {root}: write ~/.claude-projects/<key>/config.toml, as `project-config --help` shows - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent), Failure(f"no config names the checkout {root}: write {claude_md.parents[1]}/.config/build-release/<key>/config.toml, as `project-config --help` shows - the judge cannot read the records.")) def test_puts_the_records_handed_in_first_and_reads_only_the_humans_rules_without_a_checkout(self): with tempfile.TemporaryDirectory() as root: @@ -65,19 +65,19 @@ class Records(unittest.TestCase): pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n") pathlib.Path(root, "AGENTS.md").write_text("# Rules\n") first = (("the epic ABC-1's description, ## Decisions", "Squash.\n"), ("the epic ABC-1's description, ## Scoring", " \n")) - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent, first), "From the epic ABC-1's description, ## Decisions:\nSquash.\n\nFrom AGENTS.md:\n# Rules\n\nFrom ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments") - self.assertEqual(records.read_records(None, claude_md.parents[1], claude_md.parent, first), "From the epic ABC-1's description, ## Decisions:\nSquash.\n\nFrom ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo") + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent, first), "From the epic ABC-1's description, ## Decisions:\nSquash.\n\nFrom AGENTS.md:\n# Rules\n\nFrom ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments") + self.assertEqual(records.read_records(None, claude_md.parents[1], {}, claude_md.parent, first), "From the epic ABC-1's description, ## Decisions:\nSquash.\n\nFrom ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo") def test_stops_on_a_record_it_cannot_read(self): with tempfile.TemporaryDirectory() as root: claude_md = pathlib.Path(root, "home", ".claude", "CLAUDE.md") configured(self, pathlib.Path(root), home=claude_md.parents[1]) claude_md.mkdir(parents=True) - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent), Failure(f"CLAUDE.md in {claude_md.parent}: Is a directory - the judge cannot read the records.")) pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True) - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"cannot read {root}/docs/decisions.md: Is a directory - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent), Failure(f"cannot read {root}/docs/decisions.md: Is a directory - the judge cannot read the records.")) pathlib.Path(root, "AGENTS.md").write_bytes(b"# Rules\n\xff\n") - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent), Failure(f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the records.")) def test_stops_on_a_rule_it_cannot_read(self): @@ -87,7 +87,7 @@ class Records(unittest.TestCase): rules = pathlib.Path(claude_md.parent, "rules") rules.mkdir(parents=True) pathlib.Path(rules, "todo-items.md").write_bytes(b"\xff\n") - self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records.")) + self.assertEqual(records.read_records(root, claude_md.parents[1], {}, claude_md.parent), Failure(f"todo-items.md in {rules} is not UTF-8 on line 1 - the judge cannot read the records.")) class JudgeRules(unittest.TestCase): diff --git a/bin/chunk_driver/test_cycle_start.py b/bin/chunk_driver/test_cycle_start.py index f27b2a4f..8eb07e3d 100644 --- a/bin/chunk_driver/test_cycle_start.py +++ b/bin/chunk_driver/test_cycle_start.py @@ -62,7 +62,7 @@ class ProjectRouting(unittest.TestCase): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) self.home = pathlib.Path(temp.name) - self.paths = paths_from(self.home) + self.paths = paths_from(self.home, {}) self.checkout = self.home / "code" / "acme" self.checkout.mkdir(parents=True) self.config = configured(self, self.checkout, home=self.home) diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index eb99b051..026b07a7 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -159,7 +159,7 @@ def main(argv: list[str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 - done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home())), os.environ.get(PARKS) == "1", time.sleep) + done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home(), os.environ)), os.environ.get(PARKS) == "1", time.sleep) if isinstance(done, Failure): print(f"chunk-pr: {done.reason}", file=sys.stderr) return 1 diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index e5b798d1..3ad2abd1 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -92,6 +92,7 @@ Exit 1, saying why, on any argument other than --worktree, --item with an ID, -h CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds above 0, when git cannot start or finds no checkout or no default branch, or when no config names the checkout or its config cannot be read. """ +import os import pathlib import re import subprocess @@ -167,7 +168,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non if isinstance(default, Failure): return default ref, note = default - config = located(str(root), pathlib.Path.home()) + config = located(str(root), pathlib.Path.home(), os.environ) if isinstance(config, Failure): return config outside = None if config.tracked("plan") else config.plan_label @@ -178,7 +179,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non # The folder the chunk works in: the item's worktree where one was made or found, else the checkout. worktree = item.worktree.path if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else None # A `checkout:` path lands in the worktree the chunk works in. - made = located(str(worktree), pathlib.Path.home()) if worktree else config + made = located(str(worktree), pathlib.Path.home(), os.environ) if worktree else config places = (config if isinstance(made, Failure) else made).places left = left_worktrees(root, forge_run) if config.merge == "human" else () indentation = space_indented(worktree or root, timeout) diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index 8df35c79..6ce928cc 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -143,7 +143,7 @@ class Repo: class ChunkPreflightTool(unittest.TestCase): def test_passes_over_an_item_whose_pull_request_awaits_a_persons_merge_and_names_a_worktree_a_merged_one_left(self): repo = Repo(self, origin="github.com/o/r.git") - config = repo.temp / "home" / ".claude-projects" / "proj" / "config.toml" + config = repo.temp / "home" / ".config/build-release" / "proj" / "config.toml" config.write_text(config.read_text() + 'merge = "human"\n') repo.git(repo.root, "worktree", "add", "--quiet", "-b", "item-3", str(repo.temp / "proj-item-3"), "main") repo.write(repo.temp / "proj-item-3", "todo.md", TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "")) @@ -171,7 +171,7 @@ elif args[:6] == ["pr", "list", "--head", "item-2", "--state", "merged"]: def test_reads_a_plan_outside_the_checkout_as_it_stands_and_names_where_the_config_puts_each_file(self): repo = Repo(self) - folder = repo.temp / "home" / ".claude-projects" / "proj" + folder = repo.temp / "home" / ".config/build-release" / "proj" config = folder / "config.toml" config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) (folder / "todo.md").write_text(SHIPPED) @@ -192,7 +192,7 @@ elif args[:6] == ["pr", "list", "--head", "item-2", "--state", "merged"]: repo.push_from_elsewhere("todo.md", SHIPPED) plain = repo.preflight() self.assertIn("- The project's config sets: language English; commit-title {summary}; pull-request-title {summary}; branch item-{id}.\n", plain.stdout) - config = repo.temp / "home" / ".claude-projects" / "proj" / "config.toml" + config = repo.temp / "home" / ".config/build-release" / "proj" / "config.toml" config.write_text(config.read_text() + 'language = "Swedish"\ncommit-title = "PAY-{id} - {summary}"\nbranch = "feature/PAY-{id}"\n') done = repo.preflight("--worktree") self.assertEqual(done.returncode, 0, done.stderr) @@ -651,7 +651,7 @@ class EpicBranchWorktree(unittest.TestCase): self.assertFalse((self.repo.temp / "proj-item-3").exists()) def test_the_tool_makes_no_worktree_where_the_config_sets_an_epic_branch_and_keeps_its_plan_in_a_file(self): - config = self.repo.temp / "home" / ".claude-projects" / "proj" / "config.toml" + config = self.repo.temp / "home" / ".config/build-release" / "proj" / "config.toml" config.write_text(config.read_text() + 'epic-branch = "{epic}"\n') done = self.repo.preflight("--worktree") self.assertEqual(done.returncode, 0, done.stderr) diff --git a/bin/command_patterns/test_command_patterns.py b/bin/command_patterns/test_command_patterns.py index d4a83fd6..aa608588 100644 --- a/bin/command_patterns/test_command_patterns.py +++ b/bin/command_patterns/test_command_patterns.py @@ -87,7 +87,7 @@ class Main(unittest.TestCase): self.git("commit", "-q", "--allow-empty", "-m", "Start") self.tag("v0.1.0", "2026-11-01T00:00:00Z") self.tag("v0.2.0", "2026-11-05T00:00:00Z") - archive = self.home / ".claude" / "loop-claude-transcripts" / "project" + archive = self.home / ".local/state/build-release" / "transcripts" / "project" for name, finished, command in (("before", "2026-10-30T00:00:00Z", "make old"), ("between", "2026-11-03T00:00:00Z", "tea pr create"), ("after", "2026-11-07T00:00:00Z", "gh pr view")): folder = archive / name folder.mkdir(parents=True) diff --git a/bin/compress_archives/main.py b/bin/compress_archives/main.py index 8cdc6bdc..e80d59df 100644 --- a/bin/compress_archives/main.py +++ b/bin/compress_archives/main.py @@ -3,8 +3,8 @@ usage: compress-archives It gzips each file that last changed over 30 days ago: in build-release's archive, -$BUILD_RELEASE_TRANSCRIPTS (default ~/.claude/loop-claude-transcripts), each transcript, *.jsonl; -in the review folders, ~/.local/state/larv-review, every file but a lock, *.lock. A file's last change is the later +$BUILD_RELEASE_TRANSCRIPTS (default ~/.local/state/build-release/transcripts), each transcript, *.jsonl; +in the review folders, ~/.local/state/build-release/larv-review, every file but a lock, *.lock. A file's last change is the later of its mtime and ctime, so a copied or unpacked file counts from when it landed. The gzip lands beside the file as <name>.gz, with the same times. The file is removed only once @@ -21,7 +21,7 @@ import typing from transcript_archive.location import archive_root from failure import Failure -from review_rules.review_folder import REPORTS +from review_rules.review_folder import reports_folder from text_files.compressed import SUFFIX # Why 30 days: docs/decisions.md → `archives: gzip each transcript in build-release's archive and each file in the review folders 30 days after it last changed, keeping all of them`. @@ -37,7 +37,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, now return 1 cutoff = now() - AGE_DAYS * 24 * 60 * 60 count = 0 - for path in [*old_files(archive_root(home, env), "*.jsonl", cutoff), *old_files(home / REPORTS, "*", cutoff)]: + for path in [*old_files(archive_root(home, env), "*.jsonl", cutoff), *old_files(reports_folder(home, env), "*", cutoff)]: if failed := compress(path): print(failed.reason, file=sys.stderr) return 1 diff --git a/bin/compress_archives/test_compress_archives.py b/bin/compress_archives/test_compress_archives.py index 74f3e80e..4fde2ab2 100644 --- a/bin/compress_archives/test_compress_archives.py +++ b/bin/compress_archives/test_compress_archives.py @@ -27,8 +27,8 @@ class Main(unittest.TestCase): def setUp(self): self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) - self.archive = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" - self.reviews = self.home / ".local" / "state" / "larv-review" / "code" / "proj-item-1" + self.archive = self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1" + self.reviews = self.home / ".local" / "state" / "build-release" / "larv-review" / "code" / "proj-item-1" for folder in (self.archive / "session" / "s" / "subagents", self.reviews / "probe"): folder.mkdir(parents=True) self.write(self.archive / "a.jsonl", OLD) @@ -57,14 +57,14 @@ class Main(unittest.TestCase): code, out, err = self.run_main() self.assertEqual((code, err), (0, "")) self.assertEqual(self.kept(), [ - ".claude/loop-claude-transcripts/proj/c1/a.jsonl.gz", - ".claude/loop-claude-transcripts/proj/c1/a.outcomes.md", - ".claude/loop-claude-transcripts/proj/c1/b.jsonl", - ".claude/loop-claude-transcripts/proj/c1/session/s/subagents/agent-a.jsonl.gz", - ".claude/loop-claude-transcripts/proj/c1/session/s/subagents/agent-a.meta.json", - ".local/state/larv-review/code/proj-item-1/branch-1.diff", - ".local/state/larv-review/code/proj-item-1/probe/out.js.gz", - ".local/state/larv-review/code/proj-item-1/stability-round-1.md.gz", + ".local/state/build-release/larv-review/code/proj-item-1/branch-1.diff", + ".local/state/build-release/larv-review/code/proj-item-1/probe/out.js.gz", + ".local/state/build-release/larv-review/code/proj-item-1/stability-round-1.md.gz", + ".local/state/build-release/transcripts/proj/c1/a.jsonl.gz", + ".local/state/build-release/transcripts/proj/c1/a.outcomes.md", + ".local/state/build-release/transcripts/proj/c1/b.jsonl", + ".local/state/build-release/transcripts/proj/c1/session/s/subagents/agent-a.jsonl.gz", + ".local/state/build-release/transcripts/proj/c1/session/s/subagents/agent-a.meta.json", ]) self.assertEqual(gzip.decompress((self.archive / "a.jsonl.gz").read_bytes()), b"a.jsonl\n") self.assertEqual(out, "Compressed 4 files.\n") @@ -103,7 +103,7 @@ class Main(unittest.TestCase): def test_reads_the_archive_where_build_release_transcripts_puts_it(self): moved = self.home / "elsewhere" - (self.home / ".claude" / "loop-claude-transcripts").rename(moved) + (self.home / ".local/state/build-release" / "transcripts").rename(moved) code, _, err = self.run_main(env={"BUILD_RELEASE_TRANSCRIPTS": str(moved)}) self.assertEqual((code, err), (0, "")) self.assertTrue((moved / "proj" / "c1" / "a.jsonl.gz").is_file()) diff --git a/bin/deploy_release/main.py b/bin/deploy_release/main.py index d449c604..ff3d9060 100644 --- a/bin/deploy_release/main.py +++ b/bin/deploy_release/main.py @@ -34,7 +34,7 @@ with --cut-patch. It says on stderr as each step finishes, and ends stdout, after the changelog, with the line `Done: v<version> is cut and pushed, and <checkout> is on it.` It keeps each of those lines, with its time in UTC, in the run's trace: a file of its own under -$XDG_STATE_HOME/deploy-release (default ~/.local/state/deploy-release), named by when the run began. --cut-patch does too. +$XDG_STATE_HOME/build-release/deploy-release (default ~/.local/state/build-release/deploy-release), named by when the run began. --cut-patch does too. Where Ctrl-C or an unexpected fault ends the run, the trace ends with a line that starts `stopped:`. Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut diff --git a/bin/deploy_release/test_deploy_release.py b/bin/deploy_release/test_deploy_release.py index ef9b2140..7da40684 100644 --- a/bin/deploy_release/test_deploy_release.py +++ b/bin/deploy_release/test_deploy_release.py @@ -491,7 +491,7 @@ class Cut(unittest.TestCase): def traces(self) -> list[str]: """The text of each run's trace, oldest first.""" - return [file.read_text() for file in sorted((self.temp / "state" / "deploy-release").glob("*.log")) if not file.name.endswith("-ci.log")] + return [file.read_text() for file in sorted((self.temp / "state" / "build-release" / "deploy-release").glob("*.log")) if not file.name.endswith("-ci.log")] def test_keeps_each_step_of_a_cut_with_its_time_in_a_file_of_the_run(self): self.assert_cut(self.cut()) @@ -500,7 +500,7 @@ class Cut(unittest.TestCase): self.assertRegex(lines[0], rf"^[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}T[0-9:]{{8}}Z deploy-release --cut {self.target} in {self.clone}$") self.assertRegex(kept, r"(?m)^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:]{8}Z pushed the tag v0\.2\.0$") self.assertIn("Done: v0.2.0 is cut and pushed", lines[-1]) - [file] = (self.temp / "state" / "deploy-release").glob("*.log") + [file] = (self.temp / "state" / "build-release" / "deploy-release").glob("*.log") self.assertRegex(file.name, r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}Z-[0-9]+\.log$") def test_keeps_the_reason_a_cut_stopped_in_its_trace_and_a_rerun_writes_its_own(self): @@ -556,7 +556,7 @@ class Cut(unittest.TestCase): def test_says_where_ci_shs_output_goes_and_keeps_it_there(self): ran = self.cut_patch(self.plan_patch({"ci.sh": "echo the suite ran\nexit 0\n"})) self.assertEqual(ran.returncode, 0, ran.stderr) - [log] = (self.temp / "state" / "deploy-release").glob("*-ci.log") + [log] = (self.temp / "state" / "build-release" / "deploy-release").glob("*-ci.log") self.assertEqual(log.read_text(), "the suite ran\n") self.assertIn(f"ci.sh's output goes to {log}", ran.stderr) @@ -966,8 +966,8 @@ class Trace(unittest.TestCase): self.now = lambda: 1795771805.0 def test_keeps_traces_under_the_state_folder_xdg_names_else_under_homes(self): - self.assertEqual(trace.trace_folder({"XDG_STATE_HOME": "/x/state"}, pathlib.Path("/home/u")), pathlib.Path("/x/state/deploy-release")) - self.assertEqual(trace.trace_folder({}, pathlib.Path("/home/u")), pathlib.Path("/home/u/.local/state/deploy-release")) + self.assertEqual(trace.trace_folder({"XDG_STATE_HOME": "/x/state"}, pathlib.Path("/home/u")), pathlib.Path("/x/state/build-release/deploy-release")) + self.assertEqual(trace.trace_folder({}, pathlib.Path("/home/u")), pathlib.Path("/home/u/.local/state/build-release/deploy-release")) def test_names_a_run_by_its_start_and_its_process(self): self.assertEqual(trace.run_name(self.now(), 4711), "2026-11-27T09-30-05Z-4711") diff --git a/bin/do-epic b/bin/do-epic index 0e812de1..dca330f0 100755 --- a/bin/do-epic +++ b/bin/do-epic @@ -10,4 +10,4 @@ from loop_effects import effects from do_epic import main from loop_state import paths -sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, effects.system_effects(pathlib.Path.home(), os.environ))) +sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, effects.system_effects(pathlib.Path.home(), os.environ))) diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 948a16e5..67c59985 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -17,7 +17,7 @@ from do_epic.backend.jira_start import Start, started FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"] # How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes. PARENTS_PER_SEARCH = 50 -NO_FINISH = "do-epic's settings name no transition to {to} by: set `{transition}` and `{status}` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"" +NO_FINISH = "do-epic's settings name no transition to {to} by: set `{transition}` and `{status}` in ~/.config/build-release/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"" @dataclasses.dataclass(frozen=True) diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index f46fed52..48f66c83 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -228,7 +228,7 @@ class Jira(Case): no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) unconverted = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it"), Finish("Mark as done", "Done")) for store, reason in ( - (unnamed, "do-epic's settings name no transition to close an epic by: set `jira-finish-transition` and `jira-finish-status` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\""), + (unnamed, "do-epic's settings name no transition to close an epic by: set `jira-finish-transition` and `jira-finish-status` in ~/.config/build-release/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\""), (wrong_status, "ABC-12's transition 'Start' leads to the status 'In Progress', not to 'Done', which `jira-finish-status` names"), (unconverted, "cannot convert the summary to a Jira comment: adf-codec refused it"), ): @@ -523,7 +523,7 @@ class Jira(Case): unnamed = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) wrong_status = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Mark as done", "Closed")) no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) - self.assertEqual(unnamed.finish_issue(key), Failure("do-epic's settings name no transition to finish an issue by: set `jira-finish-transition` and `jira-finish-status` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"")) + self.assertEqual(unnamed.finish_issue(key), Failure("do-epic's settings name no transition to finish an issue by: set `jira-finish-transition` and `jira-finish-status` in ~/.config/build-release/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"")) self.assertEqual(wrong_status.finish_issue(key), Failure(f"{key}'s transition 'Mark as done' leads to the status 'Done', not to 'Closed', which `jira-finish-status` names")) refused = no_such.finish_issue(key) assert isinstance(refused, Failure) diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index 6a83ae8b..01192dad 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -1,4 +1,4 @@ -"""do-epic's machine-wide settings: `~/.claude-projects/do-epic/config.toml`, and `repo-rule.md` beside it. +"""do-epic's machine-wide settings: `~/.config/build-release/do-epic/config.toml`, and `repo-rule.md` beside it. One pair per machine, the same for every epic (docs/decisions.md → `do-epic: drives one Jira epic …`). The config is TOML: @@ -12,7 +12,7 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d twu-4 = "tenant-web-ui-4" - `jira-url` is the Jira site's address: https, a host, and no path. -- `env-file` is the file of Jira credentials: a path that starts with / or ~/, outside every folder of `~/.claude-projects` and outside the clone folder, which hold git checkouts. `~/.claude-projects/<key>.env` is fine. +- `env-file` is the file of Jira credentials: a path that starts with / or ~/, outside every folder of `~/.config/build-release` and outside the clone folder, which hold git checkouts. `~/.config/build-release/<key>.env` is fine. - `repoless-model` is the model that works an epic item with no repo: a model on the routing ladder, `model_routing/routing-ladder.json`. - `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out. - `language` is the default language of Jira text, by its English name. English where left out. @@ -27,12 +27,14 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d - `[label-repos]` has one line for each label of the team's own that names a repo: the label, then that repo's name, such as `twu-4 = "tenant-web-ui-4"`. do-epic reads such a label as it reads its own `repo:<name>`. A team whose label is the repo's name maps the name to itself. Where several lines name one repo, do-epic writes the label of the first. - `repo-rule.md` is prose that says how to tell an item's repo, and mustn't be blank.""" import dataclasses +from collections.abc import Mapping import pathlib import re import string import types -from project_config.settings import anywhere, CONFIG, DEFAULT_ISSUE_TYPE, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINDING_TYPE, JIRA_FINISH, JIRA_REVIEW_TYPE, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE, type_fault +from project_config.settings import anywhere, CONFIG, DEFAULT_ISSUE_TYPE, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINDING_TYPE, JIRA_FINISH, JIRA_REVIEW_TYPE, LANGUAGE, language_fault, lies_in, name_of, parsed, SITE, type_fault +from loop_state.paths import config_folder from failure import Failure from do_epic.backend.protocol import LABEL, REVIEW_LABEL from do_epic.repo_pick import LabelRepos, of_label, REPO_NAME @@ -64,7 +66,7 @@ LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTION @dataclasses.dataclass(frozen=True) class DoEpicConfig: - """folder is `~/.claude-projects/do-epic`; repo_rule is `repo-rule.md`'s text.""" + """folder is `~/.config/build-release/do-epic`; repo_rule is `repo-rule.md`'s text.""" folder: pathlib.Path jira_url: str env_file: pathlib.Path @@ -151,9 +153,10 @@ def workflow_faults(values: dict[str, object]) -> list[str]: ] -def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfig | Failure: - """The settings and the repo rule under home; a Failure naming the file it can't read, else each missing or misspelt setting it finds, so that do-epic refuses to start.""" - folder = home / PROJECTS / DO_EPIC +def load(home: pathlib.Path, env: Mapping[str, str], ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfig | Failure: + """The settings and the repo rule in the config folder; a Failure naming the file it can't read, else each missing or misspelt setting it finds, so that do-epic refuses to start.""" + configs = config_folder(env, home) + folder = configs / DO_EPIC values = parsed(folder / CONFIG) if isinstance(values, Failure): return Failure(f"{values.reason}. {LISTED}") @@ -166,7 +169,7 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi rule = (folder / REPO_RULE).read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as failure: rule = Failure(f"cannot read {folder / REPO_RULE}: {failure}") - config_folders = [path for path in (home / PROJECTS).iterdir() if path.is_dir()] + config_folders = [path for path in configs.iterdir() if path.is_dir()] clone_folder = anywhere(values.get(CLONE_FOLDER, "~/code"), home) env_file = anywhere(values.get(ENV_FILE), home) language = values.get(LANGUAGE, "English") @@ -177,7 +180,7 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi *([f"`{JIRA_URL}` is {url!r}, not a site's https address without a path, such as \"https://acme.atlassian.net\""] if JIRA_URL in values and not (isinstance(url, str) and re.fullmatch(SITE, url)) else []), *([f"`{CLONE_FOLDER}` is {values[CLONE_FOLDER]!r}, not a path that starts with / or ~/"] if clone_folder is None else []), *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not a path that starts with / or ~/"] if ENV_FILE in values and env_file is None else []), - *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, inside a folder of ~/{PROJECTS} or the clone folder, which hold git checkouts"] if env_file and lies_in(env_file, *config_folders, *([clone_folder] if clone_folder else [])) else []), + *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, inside a folder of {configs} or the clone folder, which hold git checkouts"] if env_file and lies_in(env_file, *config_folders, *([clone_folder] if clone_folder else [])) else []), *([f"`{LANGUAGE}` is {language!r}, {fault}"] if LANGUAGE in values and (fault := language_fault(language)) else []), *([f"`{REPOLESS_MODEL}` is {model!r}, not a model on the routing ladder: {', '.join(models)}"] if REPOLESS_MODEL in values and model not in models else []), *finish_faults(values), diff --git a/bin/do_epic/e2e/scenario.py b/bin/do_epic/e2e/scenario.py index 6a87f38b..c07c7e2d 100644 --- a/bin/do_epic/e2e/scenario.py +++ b/bin/do_epic/e2e/scenario.py @@ -6,7 +6,7 @@ import tempfile import typing from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL -from loop_state.paths import CONFIG_FOLDER +from loop_state.paths import config_folder, without_xdg_folders from project_config.settings import Epic, Finish from do_epic import epic_record, findings, finish from record_store.jira_description import EpicDescription @@ -56,7 +56,9 @@ class Machine: def machine_made(home: pathlib.Path, sandbox: Sandbox, launcher: pathlib.Path, env: typing.Mapping[str, str]) -> Machine | Failure: - folder = home / CONFIG_FOLDER / "do-epic" + # So that do-epic keeps its config and state under home. + env = without_xdg_folders(env) + folder = config_folder(env, home) / "do-epic" folder.mkdir(parents=True) ladder = read_ladder(SHIPPED) if isinstance(ladder, Failure): diff --git a/bin/do_epic/e2e/test_scenario.py b/bin/do_epic/e2e/test_scenario.py index 94b9381c..2f753255 100644 --- a/bin/do_epic/e2e/test_scenario.py +++ b/bin/do_epic/e2e/test_scenario.py @@ -254,7 +254,7 @@ class MachineTest(unittest.TestCase): machine = scenario.machine_made(home, self.sandbox, pathlib.Path("do-epic"), {"A": "b"}) assert not isinstance(machine, Failure), machine self.assertEqual((machine.home, machine.launcher, machine.env), (home, pathlib.Path("do-epic"), {"A": "b"})) - config = load(home) + config = load(home, {}) assert not isinstance(config, Failure), config self.assertEqual((config.jira_url, config.env_file, config.repo_rule), ("https://acme.atlassian.net", self.env_file, scenario.RULE)) self.assertEqual((config.finish.transition, config.finish.status) if config.finish else None, ("Done", "Done")) diff --git a/bin/do_epic/epic_run.py b/bin/do_epic/epic_run.py index fd05e869..06adb826 100644 --- a/bin/do_epic/epic_run.py +++ b/bin/do_epic/epic_run.py @@ -57,7 +57,7 @@ def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None, told def planned_epic(epic: EpicRun) -> planning.Planned: """The epic as planning reads and writes it.""" - return planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.effects) + return planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.env, epic.effects) def scheduled_epic(epic: EpicRun, order: tuple[str, ...]) -> scheduler.Epic | Failure: @@ -69,7 +69,7 @@ def scheduled_epic(epic: EpicRun, order: tuple[str, ...]) -> scheduler.Epic | Fa seen: list[pathlib.Path] = [] def located(name: str) -> tuple[pathlib.Path, int] | Failure: - found = locate(name, [checkout for checkout in seen], epic.config, epic.paths.home, epic.effects.git) + found = locate(name, [checkout for checkout in seen], epic.config, epic.paths.home, epic.env, epic.effects.git) if isinstance(found, Failure): return found seen.append(found.checkout) diff --git a/bin/do_epic/human_tasks.py b/bin/do_epic/human_tasks.py index 070e9d7e..2205ab54 100644 --- a/bin/do_epic/human_tasks.py +++ b/bin/do_epic/human_tasks.py @@ -1,6 +1,7 @@ """A human's task that holds up other issues of an epic (docs/decisions.md → `do-epic: drives one Jira epic …`, "Human tasks"). A window that starts again, as after a reboot, DMs again, and so does one whose DM failed, on its next read.""" +from collections.abc import Mapping import pathlib from project_config.settings import by_name, ProjectConfig @@ -27,17 +28,17 @@ def message(task: EpicIssue, epic: str, held: list[str]) -> str: return f"do-epic {epic} awaits you: {task.key}, \"{task.summary}\", blocks {' and '.join(held)}. do-epic goes on once you close {task.key} in Jira." -def notifier_checkout(issues: list[EpicIssue], team: LabelRepos, home: pathlib.Path) -> str | None: +def notifier_checkout(issues: list[EpicIssue], team: LabelRepos, home: pathlib.Path, env: Mapping[str, str]) -> str | None: """The checkout of the first of issues whose repo has a git checkout and a project config that names a notifier: where the DM finds that notifier, since the window runs in no checkout. None where there is none.""" for issue in issues: pick = recorded(issue, team) - found = by_name(pick.name, home) if isinstance(pick, Repo) else None + found = by_name(pick.name, home, env) if isinstance(pick, Repo) else None if isinstance(found, ProjectConfig) and found.notifier and (found.top / ".git").exists(): return str(found.top) return None -def awaited(task: EpicIssue, epic: str, store: EpicStore, team: LabelRepos, unblocking: tuple[str, ...], window: tmux.Window, poll: int, home: pathlib.Path, effects: Effects) -> None: +def awaited(task: EpicIssue, epic: str, store: EpicStore, team: LabelRepos, unblocking: tuple[str, ...], window: tmux.Window, poll: int, home: pathlib.Path, env: Mapping[str, str], effects: Effects) -> None: """Waits in window for the human to close the human's task `task` of the epic called epic, and returns once it no longer holds up any issue. A read of the epic that fails is said once and tried again.""" tmux.park(window, AWAITS, effects.tmux) told, said = False, None @@ -53,7 +54,7 @@ def awaited(task: EpicIssue, epic: str, store: EpicStore, team: LabelRepos, unbl text = message(task, epic, held) say(text, effects, stdout=True) # The issues it holds up come first; any other issue of the epic may do where they have no repo with a notifier. - where = notifier_checkout(sorted(issues, key=lambda issue: issue.key not in held), team, home) + where = notifier_checkout(sorted(issues, key=lambda issue: issue.key not in held), team, home, env) if where is None: say("no DM went out: no issue of the epic has a repo whose project config names a notifier and whose checkout exists", effects, stdout=True) told = where is None or tell(text, effects, where) diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 015f60d7..45258e19 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -14,7 +14,6 @@ from chunk_driver.claims import CHUNK_FLAG from do_epic import chunk_prompt, dry_run, findings, finish, human_tasks, parent_moves, planning, scheduler, split, status from chunk_driver.chunk_run import ChunkRun, closed_cycle from do_epic.epic_run import chunks_started, EpicRun, planned_epic, POLL_SECONDS, real -from loop_state.paths import CLAUDE_HOME, Paths from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo from project_config.main import located as config_located from chunk_driver.project.records import CONSEQUENCE, read_records @@ -36,6 +35,7 @@ from do_epic.repos import locate from chunk_driver.this_loop import Loop from do_epic.parking import Merged, parked_through from chunk_driver.project.model_choice import Models, overridden +from loop_state.paths import Paths from chunk_driver.project.premises import read_premises from git_cli.git_repo import record_chunk_base from forge.commands import Run, runner @@ -73,9 +73,9 @@ request is ready, with nothing else to wait on, the window's name says `awaits y A repo that is missing isn't cloned. Planning then stops there, so its writes are only those made before it, and the issues of that repo wait, and a chunk of another repo may start in the place a real run gives them; a real run would clone it and go on. {findings.HELP} {finish.HELP} -The Jira site and its credentials are set in ~/.claude-projects/do-epic/config.toml.""" -# Under the home folder, where a chunk's cycles are archived, a folder per epic. It is not build-release's archive, since that archive's readers, such as judge-replay and the routing figures, read build-release's prompts. -ARCHIVE = f"{CLAUDE_HOME}/do-epic-transcripts" +The Jira site and its credentials are set in ~/.config/build-release/do-epic/config.toml.""" +# In the state folder, where a chunk's cycles are archived, a folder per epic. It is not build-release's archive, since that archive's readers, such as judge-replay and the routing figures, read build-release's prompts. +ARCHIVE = "do-epic-transcripts" # The flag that prints what each open issue does. STATUS_FLAG = "--status" # The flag that prints what planning and the scheduler would do, without doing it. @@ -119,11 +119,11 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: if (len(words) != 1 and not writes and not closes) or not ISSUE_KEY.fullmatch(words[0]) or (chunk is not None and not ISSUE_KEY.fullmatch(chunk)): return Stop(0 if words in (["-h"], ["--help"]) else 1, HELP) if writes or closes: - return epic_written(words[0], writes, paths, backend, stdin) + return epic_written(words[0], writes, paths, env, backend, stdin) # Before anything starts: a clone, a claude session or a tmux window. if not dry_run_asked and (reason := tmux.unusable(effects.tmux, chunk_prompt.DRIVER)): return Stop(1, reason) - config = load(paths.home) + config = load(paths.home, env) if isinstance(config, Failure): return Stop(1, config.reason) store, record = backend(config, words[0]) @@ -142,17 +142,17 @@ def status_printed(epic: EpicRun) -> Stop: reading = dataclasses.replace(epic, effects=dataclasses.replace(epic.effects, git=dry_run.without_clones(epic.effects.git))) order = issues if isinstance(issues, Failure) else planning.start_order(planned_epic(reading), issues) # Where the issues cannot be put in order of score, they start in the backlog's order, as a run says. - lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.paths.home, issues, epic.config.label_repos, epic.config.unblocking, epic.effects.tmux, () if isinstance(order, Failure) else tuple(order)) + lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.paths.state_folder, issues, epic.config.label_repos, epic.config.unblocking, epic.effects.tmux, () if isinstance(order, Failure) else tuple(order)) return Stop(1, lines.reason) if isinstance(lines, Failure) else Stop(0, "\n".join(lines) or f"the epic {epic.key} has no open issue") -def epic_written(key: str, writes: findings.Write | None, paths: Paths, backend: Backend, stdin: typing.TextIO) -> Stop: +def epic_written(key: str, writes: findings.Write | None, paths: Paths, env: typing.Mapping[str, str], backend: Backend, stdin: typing.TextIO) -> Stop: """Files a finding in the epic or records a decision in its description, as writes says; closes the epic where writes is None. It needs no tmux, so a chunk's worker may run it anywhere.""" - config = load(paths.home) + config = load(paths.home, env) if isinstance(config, Failure): return Stop(1, config.reason) store, record = backend(config, key) - done = findings.written(key, writes, store, config.label_repos, record, stdin, paths.home / scheduler.STATE / key) if writes else finish.closed(key, store, config.label_repos, stdin, config.pull_merged_status) + done = findings.written(key, writes, store, config.label_repos, record, stdin, scheduler.epic_folder(paths.state_folder, key)) if writes else finish.closed(key, store, config.label_repos, stdin, config.pull_merged_status) return Stop(1, done.reason) if isinstance(done, Failure) else Stop(0, done) @@ -243,7 +243,7 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: if isinstance(issue, Stop): return issue if issue and isinstance(recorded(issue, epic.config.label_repos), HumanTask): - human_tasks.awaited(issue, epic.key, epic.store, epic.config.label_repos, epic.config.unblocking, tmux.Window(epic.session, key, pane), POLL_SECONDS, epic.paths.home, epic.effects) + human_tasks.awaited(issue, epic.key, epic.store, epic.config.label_repos, epic.config.unblocking, tmux.Window(epic.session, key, pane), POLL_SECONDS, epic.paths.home, epic.env, epic.effects) return handed_on(key, epic, Landed.WITH_A_HUMAN) place = chunk_root(key, issue, epic) if isinstance(place, Stop): @@ -289,7 +289,7 @@ def chunk_run(key: str, epic: EpicRun) -> Stop: def epic_based(key: str, root: str, epic: EpicRun) -> str | None | Stop: """Readies the epic's working branch for the chunk called key, whose repo is checked out at root: the branch, or None where the repo's config sets no `epic-branch`. It makes the branch on origin, or brings it level with the default branch, and records it as the base of the chunk's branch. A default branch that doesn't merge into it cleanly stops the loop, since a person resolves the conflict (docs/decisions.md → `epic-branch: an epic's chunks branch off and merge into a working branch …`).""" - config = config_located(root, epic.paths.home) + config = config_located(root, epic.paths.home, epic.env) if isinstance(config, Failure): return Stop(1, config.reason) if config.epic_branch is None: @@ -328,10 +328,10 @@ def chunk_root(key: str, issue: EpicIssue | None, epic: EpicRun) -> tuple[str, s if isinstance(pick, Failure): return Stop(1, pick.reason) if isinstance(pick, ClaudeWork): - return str(epic.paths.home / scheduler.STATE / epic.key), None + return str(scheduler.epic_folder(epic.paths.state_folder, epic.key)), None if not isinstance(pick, Repo): return Stop(1, f"{key} is no chunk: no label names its repo") - found = locate(pick.name, [], epic.config, epic.paths.home, epic.effects.git) + found = locate(pick.name, [], epic.config, epic.paths.home, epic.env, epic.effects.git) return Stop(1, found.reason) if isinstance(found, Failure) else (str(real(found.checkout)), pick.name) @@ -507,7 +507,7 @@ def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: st routing = project_routing(loop, chunk_prompt.DRIVER) if in_repo else routing_on(repoless_models(epic), SHIPPED) if isinstance(routing, Stop): return routing - archive_folder = epic.paths.home / ARCHIVE / epic.key + archive_folder = epic.paths.state_folder / ARCHIVE / epic.key route = announced_route(run.cycle_number, run.route, routing, archive_folder, lambda: issue, loop) prompts = chunk_prompt.unparked(news) if news else chunk_prompt.restating(task) if loop.window.name == epic.key else chunk_prompt.WORKER return cycle_of(loop, routing, route, archive_folder, task=task, facts="", premises=premises, records=records, unfinished_evidence=run.unfinished_evidence, prompts=prompts, taken_in=lambda entries: TakenIn()) @@ -524,7 +524,7 @@ def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> issue = issue_read(key, epic) if isinstance(issue, Stop): return issue - config = config_located(checkout, epic.paths.home) if checkout else None + config = config_located(checkout, epic.paths.home, epic.env) if checkout else None if isinstance(config, Failure): return Stop(1, config.reason) return chunk_prompt.task(issue, epic.key, epic.config.label_repos, checkout, epic.launcher, language, config), RoutingIssue(issue) if "L" in issue.scores else None @@ -550,7 +550,7 @@ def records_read(root: str | None, epic: EpicRun) -> str | Failure: if isinstance(body, Failure): return Failure(f"the epic {epic.key}'s description: {body.reason} - {CONSEQUENCE}.") sections.append((f"the epic {epic.key}'s description, ## {name}", body)) - return read_records(root, epic.paths.home, epic.paths.claude_dir, tuple(sections)) + return read_records(root, epic.paths.home, epic.env, epic.paths.claude_dir, tuple(sections)) def premises_read(root: str | None, epic: EpicRun) -> str | Failure: @@ -563,7 +563,7 @@ def premises_read(root: str | None, epic: EpicRun) -> str | Failure: if not body.strip(): return Failure(f"the epic {epic.key}'s description has no text under a `## {name}` heading - no premises.") bodies.append(body) - theirs = read_premises(root, epic.paths.home) if root else "" + theirs = read_premises(root, epic.paths.home, epic.env) if root else "" if isinstance(theirs, Failure): return theirs return f"the epic {epic.key}'s description:\n## Goals\n{bodies[0]}\n\n## Audience\n{bodies[1]}" + (f"\n\nThe repo's goals, which rank after the epic's and after code health, are from {theirs}" if theirs else "") diff --git a/bin/do_epic/parking.py b/bin/do_epic/parking.py index b63f8cf6..4af5ef18 100644 --- a/bin/do_epic/parking.py +++ b/bin/do_epic/parking.py @@ -30,11 +30,11 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finis A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` gives it a running slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again. """ - key, folder = loop.window.name, epic.paths.home / scheduler.STATE / epic.key + key, folder = loop.window.name, scheduler.epic_folder(epic.paths.state_folder, epic.key) recorded_as = parked.parked_chunks(folder) if isinstance(recorded_as, Failure): return Stop(1, recorded_as.reason) - config = config_located(loop.root, epic.paths.home) + config = config_located(loop.root, epic.paths.home, epic.env) if isinstance(config, Failure): return Stop(1, config.reason) # A pull request into an epic's working branch merges without a person, whatever `merge` says. The base recorded says so, not the config: the gate fails where the forge merges the pull request elsewhere. diff --git a/bin/do_epic/planning.py b/bin/do_epic/planning.py index 12f1944a..85708fc1 100644 --- a/bin/do_epic/planning.py +++ b/bin/do_epic/planning.py @@ -6,12 +6,14 @@ Planning runs only in the `do-epic <EPIC-KEY>` the human starts. A chunk that fi Planning holds no lock: one `do-epic <EPIC-KEY>` at a time is assumed. A second one started meanwhile finds the sub-tasks the first filed, since `split` reads them before it files, unless Jira's search lags.""" import dataclasses +from collections.abc import Mapping import pathlib import re -from loop_state.paths import CLAUDE_HOME +from loop_state.paths import CLAUDE_HOME, state_folder from do_epic.config import DoEpicConfig from loop_effects.effects import Effects, say +from do_epic.scheduler import epic_folder, unblocks from do_epic.backend.protocol import EpicIssue, EpicStore, no_scores from do_epic.epic_record import EpicRecord from failure import Failure @@ -22,7 +24,6 @@ from claude_code.reply import Limited from plan_store.jira_epic import number from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder import Rung -from do_epic.scheduler import STATE, unblocks from plan_store.scoring import weighing_texts # The epic's formula, stated under its `## Scoring` as a todo.md states its own. @@ -41,6 +42,7 @@ class Planned: store: EpicStore record: EpicRecord home: pathlib.Path + env: Mapping[str, str] effects: Effects @@ -92,7 +94,7 @@ def placed(epic: Planned, issues: list[EpicIssue], unplaced: list[EpicIssue], ad if failed := next((each for each in (rung, language, places) if isinstance(each, Failure)), None): return failed assert isinstance(rung, Rung) and not isinstance(language, Failure) and isinstance(places, dict) - folder = epic.home / STATE / epic.key + folder = epic_folder(state_folder(epic.env, epic.home), epic.key) folder.mkdir(parents=True, exist_ok=True) checkouts = tuple(str(place.checkout) for place in places.values()) for issue in unplaced: @@ -151,7 +153,7 @@ def located(epic: Planned, picks: list[repo_pick.Repo]) -> dict[str, repos.Locat """Each picked repo's checkout and project config, by the repo's name.""" places: dict[str, repos.Located] = {} for name in sorted({pick.name for pick in picks}): - place = repos.locate(name, [each.checkout for each in places.values()], epic.config, epic.home, epic.effects.git) + place = repos.locate(name, [each.checkout for each in places.values()], epic.config, epic.home, epic.env, epic.effects.git) if isinstance(place, Failure): return place places[name] = place @@ -210,7 +212,7 @@ def scored(epic: Planned, issues: list[EpicIssue]) -> tuple[list[EpicIssue], Fai if failed := next((each for each in (rung, language, rule, weighed) if isinstance(each, Failure)), None): return issues, failed assert isinstance(rung, Rung) and not isinstance(language, Failure) and isinstance(rule, str) and isinstance(weighed, Weighing) - folder = epic.home / STATE / epic.key + folder = epic_folder(state_folder(epic.env, epic.home), epic.key) folder.mkdir(parents=True, exist_ok=True) for issue in bare: say(f"scoring {issue.key}", epic.effects, stdout=True) diff --git a/bin/do_epic/repos.py b/bin/do_epic/repos.py index 35ca8479..ddb1b502 100644 --- a/bin/do_epic/repos.py +++ b/bin/do_epic/repos.py @@ -2,11 +2,13 @@ A missing checkout is cloned from the host and owner of the epic's other repos (docs/decisions.md → `do-epic: drives one Jira epic …`). Where that is unclear, the answer is an Unsure.""" import dataclasses +from collections.abc import Mapping import pathlib import re import shutil -from project_config.settings import by_name, CONFIG, ProjectConfig, PROJECTS +from project_config.settings import by_name, CONFIG, ProjectConfig +from loop_state.paths import config_folder from do_epic.config import DoEpicConfig from failure import Failure from git_cli.git_repo import Git @@ -34,14 +36,14 @@ class Unsure(Failure): """reason is a question for the human.""" -def locate(name: str, others: list[pathlib.Path], config: DoEpicConfig, home: pathlib.Path, git: Git) -> Located | Failure: +def locate(name: str, others: list[pathlib.Path], config: DoEpicConfig, home: pathlib.Path, env: Mapping[str, str], git: Git) -> Located | Failure: """The checkout and project config of the repo called name; others are the checkouts of the epic's other repos. A project config names the repo's checkout, and it is cloned where missing. Where no config names the repo, it is cloned into the clone folder, if it isn't there, and the human is asked to write the config, since the repo's plan, goals and records are theirs to place. A name that is no repo's name, or a config that can't be read, is a plain Failure. Any other fault is an Unsure.""" if not re.fullmatch(REPO_NAME, name): return Failure(f"{name!r} is not a repo's name: one folder name that starts with a letter, digit or underscore") - found = by_name(name, home) + found = by_name(name, home, env) if isinstance(found, Failure): return found checkout = found.top if found else config.clone_folder / name @@ -49,7 +51,7 @@ def locate(name: str, others: list[pathlib.Path], config: DoEpicConfig, home: pa if isinstance(cloned, Failure): return cloned if found is None: - return Unsure(f"{checkout} {'was cloned' if cloned else 'holds the repo'}, but no project config names it. Write {home / PROJECTS}/<key>/{CONFIG} with `checkout = \"{checkout}\"`, as `project-config --help` shows, and run do-epic again.") + return Unsure(f"{checkout} {'was cloned' if cloned else 'holds the repo'}, but no project config names it. Write {config_folder(env, home)}/<key>/{CONFIG} with `checkout = \"{checkout}\"`, as `project-config --help` shows, and run do-epic again.") return Located(checkout, found) diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index ebcbc093..19822d35 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -15,11 +15,16 @@ from text_files.markdown_text import listed from project_config.settings import PARALLEL_CHUNKS from do_epic.parked import parked_chunks from chunk_pr.approval import PARKS -from loop_state.paths import STATE_FOLDER +from loop_state.paths import state_folder from agent_cycle import tmux -# Under the home folder, a folder per epic key holds the epic's lock file, which `claims.LOCK` names. A chunk without a repo works there. -STATE = f"{STATE_FOLDER}/do-epic" +# In the state folder, where a folder per epic key holds the epic's lock file, which `claims.LOCK` names. A chunk without a repo works there. +STATE = "do-epic" + + +def epic_folder(state: pathlib.Path, key: str) -> pathlib.Path: + """The folder of the epic called key, in the state folder state.""" + return state / STATE / key # Why a human's task with a live window waits, as the epic's status says. HUMAN_WAIT = "it is a human's task; do-epic polls Jira until you close it" @@ -82,7 +87,7 @@ class Epic: @property def folder(self) -> pathlib.Path: - return self.home / STATE / self.key + return epic_folder(state_folder(self.env, self.home), self.key) def unblocks(status: str, unblocking: tuple[str, ...]) -> bool: @@ -228,7 +233,7 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li if isinstance(located, Failure): return Waits(chunk.issue, located.reason) checkout, limit = located - with starting(project_lock(str(checkout), epic.home)) as unlocked: + with starting(project_lock(str(checkout), epic.home, epic.env)) as unlocked: if unlocked: return unlocked if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.home, run)): @@ -254,7 +259,7 @@ def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | if isinstance(located, Failure): return located.reason checkout, limit = located - with starting(project_lock(str(checkout), epic.home)) as unlocked: + with starting(project_lock(str(checkout), epic.home, epic.env)) as unlocked: if unlocked: return unlocked.reason if reason := refusal(repo, room_in(str(checkout), limit, (window.session, window.name), epic.home, run)): diff --git a/bin/do_epic/status.py b/bin/do_epic/status.py index 1a4007c2..530547c4 100644 --- a/bin/do_epic/status.py +++ b/bin/do_epic/status.py @@ -2,7 +2,7 @@ import datetime import pathlib -from do_epic.scheduler import chunks, HUMAN_WAIT, STATE +from do_epic.scheduler import chunks, epic_folder, HUMAN_WAIT from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.parked import file_of, Parked, parked_chunks, SLOT @@ -20,10 +20,10 @@ def since(folder: pathlib.Path, chunk: Parked) -> str: return "" -def lines(key: str, home: pathlib.Path, issues: list[EpicIssue], team: LabelRepos, unblocking: tuple[str, ...], run: tmux.Tmux, order: tuple[str, ...]) -> list[str] | Failure: +def lines(key: str, state: pathlib.Path, issues: list[EpicIssue], team: LabelRepos, unblocking: tuple[str, ...], run: tmux.Tmux, order: tuple[str, ...]) -> list[str] | Failure: """A line per open issue of the epic called key, in the tracker's rank order: that its chunk runs or asks the human, or why it waits. order holds the keys of the issues that start by score, as planning.start_order puts them; a chunk it leaves out says that it starts after them. It doesn't start anything or check any limit, so the line of a chunk that has yet to start doesn't say which limit holds it back.""" found, waits = chunks(issues, team, unblocking) - folder = home / STATE / key + folder = epic_folder(state, key) parked = parked_chunks(folder) if isinstance(parked, Failure): return parked diff --git a/bin/do_epic/test_do_epic.py b/bin/do_epic/test_do_epic.py index 3a22f5dd..fad87ff8 100644 --- a/bin/do_epic/test_do_epic.py +++ b/bin/do_epic/test_do_epic.py @@ -21,7 +21,7 @@ class ConfigTest(unittest.TestCase): made = tempfile.TemporaryDirectory() self.addCleanup(made.cleanup) self.home = pathlib.Path(made.name).resolve() - self.folder = self.home / ".claude-projects" / "do-epic" + self.folder = self.home / ".config/build-release" / "do-epic" self.folder.mkdir(parents=True) def write(self, settings: str | None = SETTINGS, rule: str | None = "A label that equals a repo's name names that repo.\n") -> None: @@ -31,17 +31,17 @@ class ConfigTest(unittest.TestCase): (self.folder / "repo-rule.md").write_text(rule, encoding="utf-8") def failure(self) -> str: - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, Failure), found return found.reason def test_reads_the_settings_and_the_rule_and_defaults_the_clone_folder_and_language(self) -> None: self.write() - self.assertEqual(load(self.home), DoEpicConfig(self.folder, "https://acme.atlassian.net", self.home / "jira.env", self.home / "code", "English", "claude-opus-5-5", "A label that equals a repo's name names that repo.\n")) + self.assertEqual(load(self.home, {}), DoEpicConfig(self.folder, "https://acme.atlassian.net", self.home / "jira.env", self.home / "code", "English", "claude-opus-5-5", "A label that equals a repo's name names that repo.\n")) def test_reads_the_teams_labels_for_its_repos(self) -> None: self.write(SETTINGS + '[label-repos]\ntwu-4 = "tenant-web-ui-4"\n"core-4" = "core-4"\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual(dict(found.label_repos), {"twu-4": "tenant-web-ui-4", "core-4": "core-4"}) @@ -63,13 +63,13 @@ class ConfigTest(unittest.TestCase): def test_reads_a_template_for_a_sub_tasks_summary(self) -> None: self.write(SETTINGS + 'sub-task-summary = "{label}: {Summary}"\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual(found.sub_task_summary, "{label}: {Summary}") def test_leaves_a_sub_tasks_summary_to_its_default_where_the_config_has_no_template(self) -> None: self.write() - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertIsNone(found.sub_task_summary) @@ -92,7 +92,7 @@ class ConfigTest(unittest.TestCase): for template in ("{Summary}", "{Summary}{{", "{Summary} for {label} in Jira"): with self.subTest(template=template): self.write(SETTINGS + f'sub-task-summary = "{template}"\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual(found.sub_task_summary, template) @@ -102,13 +102,13 @@ class ConfigTest(unittest.TestCase): def test_reads_a_clone_folder_and_language_the_config_sets(self) -> None: self.write(SETTINGS + 'clone-folder = "/srv/repos"\nlanguage = "Brazilian Portuguese"\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual((found.clone_folder, found.language), (pathlib.Path("/srv/repos"), "Brazilian Portuguese")) def test_reads_how_a_finished_epic_closes_and_wants_both_names_or_neither(self) -> None: self.write(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual(found.finish, Finish("Mark as done", "Done")) self.write(SETTINGS + 'jira-finish-status = " "\n') @@ -116,11 +116,11 @@ class ConfigTest(unittest.TestCase): def test_reads_how_a_starting_issue_moves_and_which_boards_sprint_it_joins(self) -> None: self.write(SETTINGS) - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual(found.start, Start(None, None)) self.write(SETTINGS + 'jira-start-transition = "In Progress"\njira-sprint-board = 1\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual(found.start, Start("In Progress", 1)) for board, read in (('"6"', "'6'"), ("0", "0"), ("true", "True"), ("6.0", "6.0")): @@ -130,11 +130,11 @@ class ConfigTest(unittest.TestCase): def test_reads_the_transition_that_moves_a_parent_whose_sub_tasks_have_all_landed(self) -> None: self.write(SETTINGS) - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertIsNone(found.sub_tasks_landed_transition) self.write(SETTINGS + 'jira-sub-tasks-landed-transition = "Release Ready"\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual(found.sub_tasks_landed_transition, "Release Ready") self.write(SETTINGS + 'jira-sub-tasks-landed-transition = 5\n') @@ -142,23 +142,23 @@ class ConfigTest(unittest.TestCase): def test_reads_the_unblocking_statuses_and_that_the_teams_automation_moves_issues(self) -> None: self.write(SETTINGS) - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual((found.unblocking, found.automation_moves), ((), False)) self.write(SETTINGS + 'jira-unblocking-statuses = ["Release Ready", "Done"]\njira-automation-moves-issues = true\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual((found.unblocking, found.automation_moves), (("Release Ready", "Done"), True)) def test_the_issue_types_of_a_finding_and_a_release_review_are_task_where_left_out(self) -> None: self.write() - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual((found.finding_type, found.review_type), ("Task", "Task")) def test_reads_the_issue_types_of_a_finding_and_a_release_review(self) -> None: self.write(SETTINGS + 'jira-finding-type = "Feature"\njira-review-type = "Chore"\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual((found.finding_type, found.review_type), ("Feature", "Chore")) @@ -171,11 +171,11 @@ class ConfigTest(unittest.TestCase): def test_reads_the_statuses_of_an_issue_whose_pull_request_into_an_epic_branch_opened_and_merged(self) -> None: self.write(SETTINGS) - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual((found.pull_open_status, found.pull_merged_status), (None, None)) self.write(SETTINGS + 'jira-unblocking-statuses = ["release ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n') - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual((found.pull_open_status, found.pull_merged_status), ("Code Review", "Release Ready")) @@ -243,8 +243,8 @@ class ConfigTest(unittest.TestCase): self.assertIn(f"`{name}` is", self.failure()) def test_keeps_the_credentials_outside_every_config_folder_and_the_clone_folder(self) -> None: - (self.home / ".claude-projects" / "acme").mkdir() - for env_file in ("~/.claude-projects/do-epic/jira.env", "~/.claude-projects/acme/jira.env", "~/code/acme/jira.env"): + (self.home / ".config/build-release" / "acme").mkdir() + for env_file in ("~/.config/build-release/do-epic/jira.env", "~/.config/build-release/acme/jira.env", "~/code/acme/jira.env"): with self.subTest(env_file): self.write(SETTINGS.replace("~/jira.env", env_file)) self.assertIn("`env-file` is", self.failure()) @@ -254,14 +254,14 @@ class ConfigTest(unittest.TestCase): self.assertIn("`env-file` is", self.failure()) def test_accepts_credentials_beside_the_config_folders(self) -> None: - self.write(SETTINGS.replace("~/jira.env", "~/.claude-projects/do-epic.env")) - found = load(self.home) + self.write(SETTINGS.replace("~/jira.env", "~/.config/build-release/do-epic.env")) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found - self.assertEqual(found.env_file, self.home / ".claude-projects" / "do-epic.env") + self.assertEqual(found.env_file, self.home / ".config/build-release" / "do-epic.env") def test_refuses_while_the_routing_ladder_cannot_be_read(self) -> None: self.write() - found = load(self.home, self.home / "no-ladder.json") + found = load(self.home, {}, self.home / "no-ladder.json") assert isinstance(found, Failure), found self.assertIn("no-ladder.json", found.reason) @@ -276,12 +276,12 @@ class ConfigTest(unittest.TestCase): ladder = self.home / "ladder.json" ladder.write_text('[{"model": "claude-sonnet-5-5", "effort": "low"}, {"model": "claude-opus-5-5", "effort": "low"}]', encoding="utf-8") self.write(SETTINGS.replace("claude-opus-5-5", "claude-haiku-5-5")) - found = load(self.home, ladder) + found = load(self.home, {}, ladder) assert isinstance(found, Failure), found self.assertIn("not a model on the routing ladder: claude-opus-5-5, claude-sonnet-5-5.", found.reason) def test_reads_the_rule_and_the_settings_as_utf8(self) -> None: self.write(SETTINGS + 'language = "Svenska"\n', rule="Etiketten är repots namn.\n") - found = load(self.home) + found = load(self.home, {}) assert isinstance(found, DoEpicConfig), found self.assertEqual(found.repo_rule, "Etiketten är repots namn.\n") diff --git a/bin/do_epic/test_findings.py b/bin/do_epic/test_findings.py index 5e3981d5..4fcc108f 100644 --- a/bin/do_epic/test_findings.py +++ b/bin/do_epic/test_findings.py @@ -53,7 +53,7 @@ class FindingsTest(DoEpicTest): def setUp(self) -> None: super().setUp() self.store = MemoryEpic("ABC-12", list(self.issues)) - self.written = WrittenDescription([DESCRIPTION], self.home / ".local/state/do-epic/ABC-12/decisions.lock") + self.written = WrittenDescription([DESCRIPTION], self.home / ".local/state/build-release/do-epic/ABC-12/decisions.lock") self.keys: list[str] = [] def backend(self, config: object, key: str) -> tuple[MemoryEpic, EpicRecord]: @@ -63,7 +63,7 @@ class FindingsTest(DoEpicTest): def run_with(self, argv: list[str], stdin: str = "") -> tuple[int, str, str, FakeEffects]: out, err, fake = io.StringIO(), io.StringIO(), FakeEffects() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = main.main(argv, {}, paths_from(self.home), pathlib.Path("/b/do-epic"), fake.effects(), self.backend, io.StringIO(stdin)) + code = main.main(argv, {}, paths_from(self.home, {}), pathlib.Path("/b/do-epic"), fake.effects(), self.backend, io.StringIO(stdin)) # Without the time each line of do-epic opens with. return code, out.getvalue().replace("<1790000000> ", ""), err.getvalue().replace("<1790000000> ", ""), fake @@ -85,7 +85,7 @@ class FilingAFinding(FindingsTest): self.assertEqual((code, out, filed.labels, filed.detail), (0, f"Filed {filed.key} in the epic ABC-12.\n", (label,), "")) def test_a_label_of_the_teams_says_where_the_issue_is_worked(self) -> None: - with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config: + with (self.home / ".config/build-release/do-epic/config.toml").open("a", encoding="utf-8") as config: config.write('\n[label-repos]\ntwu-4 = "tenant-web-ui-4"\n') code, out, _, _ = self.run_with(["ABC-12", "--file", "Retry", "--label", "twu-4"]) filed = self.store.issues[-1] @@ -139,7 +139,7 @@ class FilingAFinding(FindingsTest): self.assertEqual((code, err), (1, "cannot file the finding in the epic ABC-12: Jira answered 401\n")) def test_stops_where_the_machines_settings_cannot_be_read(self) -> None: - (self.home / ".claude-projects/do-epic/config.toml").unlink() + (self.home / ".config/build-release/do-epic/config.toml").unlink() code, out, err, _ = self.run_with(["ABC-12", "--file", "Retry"]) self.assertEqual((code, out, len(self.store.issues)), (1, "", 2)) self.assertIn("config.toml", err) diff --git a/bin/do_epic/test_finish.py b/bin/do_epic/test_finish.py index 0ee91448..15a9583a 100644 --- a/bin/do_epic/test_finish.py +++ b/bin/do_epic/test_finish.py @@ -102,7 +102,7 @@ class ClosingTheEpic(DoEpicTest): def close(self, summary: str = "## Shipped\n\napi: the import.\n") -> tuple[int, str, str]: out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = main.main(["ABC-12", "--close-epic"], {}, paths_from(self.home), LAUNCHER, FakeEffects().effects(), self.backend, io.StringIO(summary)) + code = main.main(["ABC-12", "--close-epic"], {}, paths_from(self.home, {}), LAUNCHER, FakeEffects().effects(), self.backend, io.StringIO(summary)) return code, out.getvalue(), err.getvalue() def test_posts_the_summary_on_the_epic_and_closes_it(self) -> None: @@ -127,15 +127,15 @@ class ClosingTheEpic(DoEpicTest): self.assertEqual(finish.closed("ABC-12", Unreadable("ABC-12", list(REVIEWED)), {}, io.StringIO("Shipped.")), Failure("cannot close the epic ABC-12: Jira answered 503")) def test_the_jira_backend_closes_an_epic_by_the_transition_the_settings_name(self) -> None: - with open(self.home / ".claude-projects/do-epic/config.toml", "a", encoding="utf-8") as settings: + with open(self.home / ".config/build-release/do-epic/config.toml", "a", encoding="utf-8") as settings: settings.write('jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n') - config = load(self.home) + config = load(self.home, {}) assert isinstance(config, DoEpicConfig), config store, _ = main.jira_backend(config, "ABC-12") self.assertEqual(store.finish, Finish("Mark as done", "Done")) # type: ignore[attr-defined] def test_closes_an_epic_whose_open_issues_all_have_the_merged_status(self) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n', encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n', encoding="utf-8") self.issues.append(issue("ABC-31", "repo:api", status="Release Ready")) code, out, err = self.close() self.assertEqual(code, 0, err) @@ -201,7 +201,7 @@ class TheFinishingChunk(DoEpicTest): self.assertIn(["/b/do-epic", "--chunk", "ABC-12", "ABC-12"], [args[-4:] for args in fake.tmux_calls]) def test_starts_once_each_open_issue_has_the_merged_status(self) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n', encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n', encoding="utf-8") self.issues = [issue("ABC-20", "do-epic-claude", status="Release Ready"), issue("ABC-21", "do-epic-claude", done=True)] fake = FakeEffects(on_terminal=False) code, out, err = self.run_main(["ABC-12"], fake) @@ -227,7 +227,7 @@ class TheFinishingChunk(DoEpicTest): def test_its_worker_is_handed_the_finishing_task_and_runs_until_the_judge_rules_it_finished(self) -> None: self.issues = list(REVIEWED) - worker = Worker(paths_from(self.home).claude_code_transcripts.parent) + worker = Worker(paths_from(self.home, {}).claude_code_transcripts.parent) fake = FakeEffects(streams=[worker], claude=[judged("finished")], git=UNREAD, windows="ABC-12\t0\t@9\n") code, out, err = self.run_main(["--chunk", "ABC-12", "ABC-12"], fake, MODELS) self.assertEqual(code, 0, err) @@ -237,11 +237,11 @@ class TheFinishingChunk(DoEpicTest): self.assertIn("`/b/do-epic ABC-12 --close-epic`", streamed) self.assertIn("From the epic ABC-12's description:\n## Goals\nShip the import.", streamed) self.assertIn("write a summary in English, the epic's language", streamed) - self.assertTrue((self.home / ".local/state/do-epic/ABC-12").is_dir()) + self.assertTrue((self.home / ".local/state/build-release/do-epic/ABC-12").is_dir()) def test_a_worker_that_resumes_is_told_the_task_as_the_epic_now_stands(self) -> None: self.issues = list(REVIEWED) - transcripts = paths_from(self.home).claude_code_transcripts + transcripts = paths_from(self.home, {}).claude_code_transcripts worker = Worker(transcripts.parent) session = session_named("A ABC-12 do-epic ABC-12", transcripts) (transcripts / "-fake").mkdir(parents=True) @@ -256,7 +256,7 @@ class TheFinishingChunk(DoEpicTest): def test_stops_where_the_epics_issues_cannot_be_read_or_its_lock_cannot_be_taken(self) -> None: self.issues = [issue("ABC-20", "do-epic-claude", done=True)] - (self.home / ".local/state/do-epic/ABC-12" / LOCK).mkdir(parents=True) + (self.home / ".local/state/build-release/do-epic/ABC-12" / LOCK).mkdir(parents=True) code, _, err = self.run_main(["ABC-12"], FakeEffects(on_terminal=False)) self.assertEqual(code, 1) self.assertIn("cannot lock ", err) diff --git a/bin/do_epic/test_human_tasks.py b/bin/do_epic/test_human_tasks.py index 29050405..dbe9df67 100644 --- a/bin/do_epic/test_human_tasks.py +++ b/bin/do_epic/test_human_tasks.py @@ -35,7 +35,7 @@ class AHumanTaskThatBlocksAnIssue(DoEpicTest): folder = configured(self, checkout, home=self.home) if notifier: with (folder / "config.toml").open("a") as config: - config.write('env-file = "~/.claude-projects/notifier.env"\nnotifier = "slack"\n') + config.write('env-file = "~/.config/build-release/notifier.env"\nnotifier = "slack"\n') return checkout def awaited(self, fake: FakeEffects, closes_after: int) -> tuple[int, str, str]: @@ -52,7 +52,7 @@ class AHumanTaskThatBlocksAnIssue(DoEpicTest): def moved_to_an_unblocking_status(self, switch: str, frees: tuple[str, dict[str, object]] = ("ABC-19", {"status": "Release Ready"}), starts: str = "ABC-21") -> bool: """Whether Jira counts the task done after its window's run, where the config ends with switch. frees is the change in Jira that ends the wait: by default the human moves the task to an unblocking status. starts is what the window then starts.""" - with (self.home / ".claude-projects" / "do-epic" / "config.toml").open("a") as config: + with (self.home / ".config/build-release" / "do-epic" / "config.toml").open("a") as config: config.write('jira-unblocking-statuses = ["Release Ready"]\n' + switch) fake = FakeEffects(git=UNREAD, windows=WINDOW) slept: list[int] = [] diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index c461eaf7..59968dd1 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -56,7 +56,7 @@ class DoEpicTest(unittest.TestCase): made = tempfile.TemporaryDirectory() self.addCleanup(made.cleanup) self.home = pathlib.Path(made.name).resolve() - folder = self.home / ".claude-projects" / "do-epic" + folder = self.home / ".config/build-release" / "do-epic" folder.mkdir(parents=True) (folder / "config.toml").write_text(SETTINGS, encoding="utf-8") (folder / "repo-rule.md").write_text("A label that equals a repo's name names that repo.\n", encoding="utf-8") @@ -77,7 +77,7 @@ class DoEpicTest(unittest.TestCase): return MemoryEpic(key, list(self.issues)), EpicRecord(Description(self.description)) # type: ignore[arg-type] def worker(self) -> Worker: - return Worker(paths_from(self.home).claude_code_transcripts.parent) + return Worker(paths_from(self.home, {}).claude_code_transcripts.parent) def repo_chunk(self) -> pathlib.Path: """Makes ABC-20 the one issue, a chunk in the repo api whose checkout holds its premises; the folder of the repo's config.""" @@ -88,15 +88,15 @@ class DoEpicTest(unittest.TestCase): return folder def epic_run(self, fake: FakeEffects, env: dict[str, str] | None = None) -> epic_run.EpicRun: - config = main.load(self.home) + config = main.load(self.home, {}) assert not isinstance(config, Failure) store, record = self.backend(config, "ABC-12") - return epic_run.EpicRun("ABC-12", config, store, record, paths_from(self.home), env or {}, pathlib.Path("/b/do-epic"), fake.effects()) + return epic_run.EpicRun("ABC-12", config, store, record, paths_from(self.home, env or {}), env or {}, pathlib.Path("/b/do-epic"), fake.effects()) def run_main(self, argv: list[str], fake: FakeEffects, env: dict[str, str] | None = None) -> tuple[int, str, str]: out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - code = main.main(argv, env or {}, paths_from(self.home), pathlib.Path("/b/do-epic"), fake.effects(), self.backend, forge_at=self.forge_at) + code = main.main(argv, env or {}, paths_from(self.home, env or {}), pathlib.Path("/b/do-epic"), fake.effects(), self.backend, forge_at=self.forge_at) return code, out.getvalue(), err.getvalue() @@ -146,7 +146,7 @@ class TheCommand(DoEpicTest): self.assertIn("started ABC-21 in the tmux session epic-ABC-12\n", out) self.assertIn("ABC-20 waits: it is a human's task\n", out) started = [args for args in fake.tmux_calls if args[0] == "new-session"] - self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/do-epic/ABC-12"), "-e", "BUILD_RELEASE_WORKER_MODEL=m", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]]) + self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/build-release/do-epic/ABC-12"), "-e", "BUILD_RELEASE_WORKER_MODEL=m", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]]) # The session is no checkout's, so nothing marks it as one's. self.assertNotIn(tmux.OWNER, [args[3] for args in fake.tmux_calls if args[0] == "set-option"]) @@ -195,22 +195,22 @@ class TheCommand(DoEpicTest): class ACycleOfAChunkWithoutARepo(DoEpicTest): def test_naming_the_chunks_folder_doesnt_make_it(self) -> None: - folder = self.home / ".local/state/do-epic/ABC-12" + folder = self.home / ".local/state/build-release/do-epic/ABC-12" self.assertEqual(main.chunk_root("ABC-21", self.issues[1], self.epic_run(FakeEffects())), (str(folder), None)) self.assertFalse(folder.exists()) self.assertIsNone(main.folder_made(str(folder))) self.assertTrue(folder.is_dir()) def test_a_chunk_whose_folder_cannot_be_made_stops_with_the_reason(self) -> None: - (self.home / ".local/state").mkdir(parents=True, exist_ok=True) - (self.home / ".local/state/do-epic").write_text("", encoding="utf-8") + (self.home / ".local/state/build-release").mkdir(parents=True, exist_ok=True) + (self.home / ".local/state/build-release/do-epic").write_text("", encoding="utf-8") code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(), {"TMUX_PANE": "%1"}) self.assertEqual(code, 1) - self.assertRegex(err, f"could not make the chunk's folder {self.home}/.local/state/do-epic/ABC-12: \\w") + self.assertRegex(err, f"could not make the chunk's folder {self.home}/.local/state/build-release/do-epic/ABC-12: \\w") def cycle(self, env: dict[str, str] | None = None, run: ChunkRun = ChunkRun(1)) -> main.Cycle: fake = FakeEffects(git=[Failure("no git"), Failure("no git")]) - paths = paths_from(self.home) + paths = paths_from(self.home, env or {}) epic = self.epic_run(fake, env) place = main.chunk_root("ABC-21", self.issues[1], epic) assert isinstance(place, tuple) @@ -243,7 +243,7 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest): def test_works_in_the_epics_folder_and_archives_apart_from_build_release(self) -> None: cycle = self.cycle() - self.assertEqual((cycle.root, cycle.project_archive, cycle.records), (str(self.home / ".local/state/do-epic/ABC-12"), self.home / ".claude/do-epic-transcripts/ABC-12", "")) + self.assertEqual((cycle.root, cycle.project_archive, cycle.records), (str(self.home / ".local/state/build-release/do-epic/ABC-12"), self.home / ".local/state/build-release/do-epic-transcripts/ABC-12", "")) def test_the_records_are_the_epics_scoring_and_decisions_then_the_humans_rules(self) -> None: self.description = DESCRIPTION + "\n## Scoring\nE + I, bar 4.\n\n## Decisions\n### Merges squash\nAlways.\n" @@ -315,7 +315,7 @@ class TheHumansRun(DoEpicTest): code, _, err = self.run_main(["ABC-12"], FakeEffects()) self.assertEqual(code, 1) self.assertIn("`**Max parallel chunks:** many`, which is not a whole number of 1 or more", err) - (self.home / ".claude-projects/do-epic/config.toml").unlink() + (self.home / ".config/build-release/do-epic/config.toml").unlink() code, out, err = self.run_main(["ABC-12"], FakeEffects()) self.assertEqual((code, out), (1, "")) self.assertIn("config.toml", err) @@ -413,9 +413,9 @@ class AChunksRun(DoEpicTest): self.assertNotIn("=== cycle 3", out) self.assertIn("the chunk finished; started ABC-22\n", out) self.assertEqual(fake.dms, []) - archive = self.home / ".claude/do-epic-transcripts/ABC-12" + archive = self.home / ".local/state/build-release/do-epic-transcripts/ABC-12" self.assertTrue(any(archive.iterdir())) - self.assertFalse((self.home / ".claude/loop-claude-transcripts").exists()) + self.assertFalse((self.home / ".local/state/build-release/transcripts").exists()) streamed = [what for seam, what in fake.calls if seam == "stream_claude"] self.assertIn("Work the Jira issue ABC-21 of the epic ABC-12 as one chunk", " ".join(streamed[0])) self.assertNotIn("Work the Jira issue", " ".join(streamed[1])) @@ -428,7 +428,7 @@ class AChunksRun(DoEpicTest): judged_with = [" ".join(what[0]) + (what[1] or "") for seam, what in fake.calls if seam == "claude"] self.assertEqual((len(prompts), len(judged_with)), (3, 3)) for text in (*prompts, *judged_with, *fake.dms, *[str(what) for seam, what in fake.calls if seam == "input"]): - self.assertNotIn("build-release", text) + self.assertNotIn("build-release", text.replace(str(self.home / ".local/state/build-release"), "<state>"), "but for the state folder's name") self.assertNotIn("None", text) self.assertIn(" do-epic runs you on claude-", prompts[1]) self.assertIn("The human answered your question at do-epic's terminal:\nUse B.", prompts[2]) @@ -449,7 +449,7 @@ class AChunksRun(DoEpicTest): fake = FakeEffects(streams=[self.worker()] * 6, claude=[judged("unfinished", escalation="working")] + [judged("unfinished")] * 5, git=UNREAD) code, out, _ = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS) self.assertEqual(code, 2, out) - outcomes = [path.read_text(encoding="utf-8") for path in (self.home / ".claude/do-epic-transcripts/ABC-12").glob("*/*.outcomes.md")] + outcomes = [path.read_text(encoding="utf-8") for path in (self.home / ".local/state/build-release/do-epic-transcripts/ABC-12").glob("*/*.outcomes.md")] self.assertTrue(any("Z Stepped up\n" in text for text in outcomes) and any("Z Stopped: " in text for text in outcomes), outcomes) self.assertEqual([text for text in outcomes if not text.startswith("Task: Work the Jira issue ABC-21 of the epic ABC-12 as one chunk")], []) @@ -460,7 +460,7 @@ class AChunksRun(DoEpicTest): """Writes the file, and adds a line to the worker's transcript after each copy of it, as a worker that still writes does.""" unwritten = replace_file(path, data) if path.suffix == ".jsonl": - for transcript in (paths_from(self.home).claude_code_transcripts.parent / "projects" / "-fake").glob("*.jsonl"): + for transcript in (paths_from(self.home, {}).claude_code_transcripts.parent / "projects" / "-fake").glob("*.jsonl"): with open(transcript, "a", encoding="utf-8") as handle: handle.write(json.dumps({"type": "queue-operation", "timestamp": str(path)}) + "\n") return unwritten @@ -468,7 +468,7 @@ class AChunksRun(DoEpicTest): fake.replace_file = grown_after_each_copy code, out, _ = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS) self.assertEqual(code, 2, out) - outcomes = [path.read_text(encoding="utf-8") for path in (self.home / ".claude/do-epic-transcripts/ABC-12").glob("*/*.outcomes.md")] + outcomes = [path.read_text(encoding="utf-8") for path in (self.home / ".local/state/build-release/do-epic-transcripts/ABC-12").glob("*/*.outcomes.md")] self.assertTrue(any("Z Stepped up\n" in text for text in outcomes) and any("Z Stopped: " in text for text in outcomes), outcomes) self.assertEqual([text for text in outcomes if not text.startswith("Task: Work the Jira issue ABC-21 of the epic ABC-12 as one chunk")], []) @@ -492,7 +492,7 @@ class AChunksRun(DoEpicTest): self.assertIn("the chunk finished; started ABC-22\n", out) def test_where_the_teams_automation_moves_issues_a_finished_chunk_without_a_repo_still_moves_its_own(self) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n', encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n', encoding="utf-8") parent = issue("ABC-23", "split-by-repo") store = MemoryEpic("ABC-12", [self.issues[0], parent, issue("ABC-21", "do-epic-claude", parent="ABC-23"), issue("ABC-22", "do-epic-claude", blockers=("ABC-23",))]) self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] @@ -515,7 +515,7 @@ class AChunksRun(DoEpicTest): self.assertIn("the chunk finished; started ABC-22\n", out) def test_the_last_sub_task_a_person_filed_to_finish_moves_its_parent_to_done_and_starts_what_it_blocks(self) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8") tasks = [issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="ABC-21", done=True)] store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-21"), *tasks, issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))]) self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] @@ -526,7 +526,7 @@ class AChunksRun(DoEpicTest): self.assertIn("the chunk finished; started ABC-22\n", out) def test_a_parent_jira_will_not_move_is_said_and_the_next_chunk_still_starts(self) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8") store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-21"), issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-22", "do-epic-claude")]) finish = store.finish_issue store.finish_issue = lambda key: Failure("no way to done") if key == "ABC-21" else finish(key) # type: ignore[method-assign] @@ -614,7 +614,7 @@ class AChunksRun(DoEpicTest): def test_a_chunk_in_a_repo_routes_on_the_repos_model(self) -> None: folder = self.repo_chunk() - models = self.home / ".claude/loop-claude-models.json" + models = self.home / ".config/build-release/models.json" models.parent.mkdir(parents=True, exist_ok=True) models.write_text(json.dumps({folder.name: "claude-fable-5-2", "other": "claude-opus-5-5"}), encoding="utf-8") fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD) @@ -661,7 +661,7 @@ class AChunksRun(DoEpicTest): store.issues[:] = [issue("ABC-20", "do-epic-claude")] return super().__call__(*args, **kwargs) - worker = Relabelling(paths_from(self.home).claude_code_transcripts.parent) + worker = Relabelling(paths_from(self.home, {}).claude_code_transcripts.parent) fake = FakeEffects(streams=[worker, self.worker()], claude=[judged("unfinished"), judged("finished")], git=UNREAD) code, _, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS) self.assertEqual(code, 0, err) @@ -710,7 +710,7 @@ class WhatAWorkerJudgeAndHumanRead(DoEpicTest): str(judge.judge_schema(prompts.driver)), ] for text in texts: - self.assertNotIn("build-release", text) + self.assertNotIn("build-release", text.replace(str(self.home / ".local/state/build-release"), "<state>"), "but for the state folder's name") self.assertIn(f"do-epic runs you on {cycle.route.rung}, routed by the issue's L of 3. Where a sentence below names item 21, it means the issue.", texts[0]) self.assertRegex(texts[0], r"it means the issue\.( \S|\n\n)") self.assertNotIn("Chunk items:", texts[1]) @@ -738,8 +738,8 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest): super().setUp() self.repo_config = self.repo_chunk() / "config.toml" self.issues.append(issue("ABC-22", "do-epic-claude")) - self.file = parked.file_of(self.home / ".local/state/do-epic/ABC-12", "ABC-20") - self.session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home).claude_code_transcripts) + self.file = parked.file_of(self.home / ".local/state/build-release/do-epic/ABC-12", "ABC-20") + self.session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home, {}).claude_code_transcripts) def parked_run(self, fake: FakeEffects) -> tuple[int, str, str, list[str]]: """The chunk's run, as its exit code, what it printed, and each prompt its workers got.""" @@ -855,7 +855,7 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest): self.assertEqual((code, len(prompts)), (0, 1), err) def test_where_the_teams_automation_moves_issues_a_finished_chunk_in_a_repo_moves_none_and_waits_for_the_move(self) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready", "Shipped"]\njira-automation-moves-issues = true\n', encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready", "Shipped"]\njira-automation-moves-issues = true\n', encoding="utf-8") store = MemoryEpic("ABC-12", [*self.issues[:-1], issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))]) self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] self.forges = [awaiting(pulls="")] @@ -953,7 +953,7 @@ class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest): self.assertFalse(self.file.exists()) def test_where_the_teams_automation_moves_issues_a_merged_parked_chunk_waits_for_the_move_as_a_finished_one_does(self) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready", "Shipped"]\njira-automation-moves-issues = true\n', encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready", "Shipped"]\njira-automation-moves-issues = true\n', encoding="utf-8") store = MemoryEpic("ABC-12", [*self.issues[:-1], issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))]) self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] self.forges = [awaiting(), awaiting(pulls="", merged=True)] @@ -1117,7 +1117,7 @@ class AnEpicsWorkingBranch(DoEpicTest): self.git_timeouts: list[tuple[str, object]] = [] def settings(self, more: str) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + more, encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + more, encoding="utf-8") def with_git(self, fake: FakeEffects, **answers: str | Failure) -> FakeEffects: """fake, whose git answers each command by its first word: as answers has it, else as a checkout whose origin has the branch ABC-12, which holds origin/main.""" @@ -1157,7 +1157,7 @@ class AnEpicsWorkingBranch(DoEpicTest): def test_a_folder_no_checkout_holds_stops_with_the_reason_its_config_cannot_be_found(self) -> None: elsewhere = self.home / "elsewhere" elsewhere.mkdir() - unnamed = main.config_located(str(elsewhere), self.home) + unnamed = main.config_located(str(elsewhere), self.home, {}) assert isinstance(unnamed, Failure), unnamed self.assertEqual(main.epic_based("ABC-20", str(elsewhere), self.epic_run(self.with_git(FakeEffects()))), main.Stop(1, unnamed.reason)) @@ -1210,8 +1210,8 @@ class AnEpicsWorkingBranch(DoEpicTest): def test_a_chunk_parked_on_a_persons_merge_into_the_default_branch_stays_parked_until_its_pull_request_goes_into_the_branch(self) -> None: self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n') - session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home).claude_code_transcripts) - parked.park(self.home / ".local/state/do-epic/ABC-12", parked.Parked("ABC-20", "/code/api-ABC-20", "7", str(session.id), "your merge")) + session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home, {}).claude_code_transcripts) + parked.park(self.home / ".local/state/build-release/do-epic/ABC-12", parked.Parked("ABC-20", "/code/api-ABC-20", "7", str(session.id), "your merge")) self.worker()(["--session-id", str(session.id)]) # The pull request was opened into main before the setting was on; a person then changes its base to ABC-12. self.forges = [self.recorded(decision="APPROVED"), self.recorded(decision="APPROVED"), self.recorded(base="ABC-12", decision="APPROVED")] @@ -1419,7 +1419,7 @@ class TheDryRun(DoEpicTest): self.assertEqual([args for args in fake.tmux_calls if args[0] in changing], []) def test_prints_each_move_of_a_parent_whose_sub_tasks_a_person_filed(self) -> None: - (self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-sub-tasks-landed-transition = "Release Ready"\njira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8") + (self.home / ".config/build-release" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-sub-tasks-landed-transition = "Release Ready"\njira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8") self.issues = [issue("ABC-20", status="In Progress"), issue("ABC-30", "do-epic-claude", parent="ABC-20", status="Release Ready"), issue("ABC-21"), issue("ABC-31", "do-epic-claude", parent="ABC-21", done=True), issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))] code, out, err = self.run_main(["ABC-12", "--dry-run"], FakeEffects()) self.assertEqual((code, err), (0, "")) diff --git a/bin/do_epic/test_planning.py b/bin/do_epic/test_planning.py index e23ee9e4..25fb9715 100644 --- a/bin/do_epic/test_planning.py +++ b/bin/do_epic/test_planning.py @@ -38,10 +38,10 @@ def scored(key: str, moves: str, *labels: str, blockers: tuple[str, ...] = (), b class Planning(DoEpicTest): def plan(self, fake: FakeEffects) -> tuple[list[EpicIssue] | Failure | Limited, MemoryEpic, str]: """What planning answers for self.issues, the store it changed and what it printed on stdout. self.asked holds what it asked the human, on stderr.""" - config = load(self.home) + config = load(self.home, {}) assert not isinstance(config, Failure), config store = MemoryEpic("ABC-12", list(self.issues)) - epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, fake.effects()) # type: ignore[arg-type] + epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, fake.effects()) # type: ignore[arg-type] out, self.asked = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(self.asked): read = store.read() @@ -73,7 +73,7 @@ class Planning(DoEpicTest): self.assertEqual((found, out, fake.made("claude")), (self.issues, "", [])) def test_an_epic_shaped_as_a_teams_is_planned_without_claude_and_without_a_write(self) -> None: - with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config: + with (self.home / ".config/build-release/do-epic/config.toml").open("a", encoding="utf-8") as config: config.write('\n[label-repos]\ntwu-4 = "tenant-web-ui-4"\ncore-4 = "core-4"\n') self.description = RANKED self.repo("tenant-web-ui-4") @@ -120,7 +120,7 @@ class Planning(DoEpicTest): self.assertIn("in English, that tells the team why it is split by repo", fake.made("claude")[0][1]) def test_a_failed_runs_sub_task_under_the_teams_label_is_not_filed_again_and_another_label_is_no_pick(self) -> None: - with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config: + with (self.home / ".config/build-release/do-epic/config.toml").open("a", encoding="utf-8") as config: config.write('\n[label-repos]\nbackend = "api"\n') configured(self, self.home / "code" / "api", home=self.home) self.issues = [issue("ABC-20", "urgent"), dataclasses.replace(issue("ABC-23", "backend", parent="ABC-20"), by_loop=True), issue("ABC-21", "urgent")] @@ -151,11 +151,11 @@ class Planning(DoEpicTest): def claude(args: object, cwd: str, stdin: object) -> object: folders.append(cwd) return effects.claude(args, cwd, stdin) # type: ignore[arg-type] - config = load(self.home) - epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description("")), self.home, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type] + config = load(self.home, {}) + epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description("")), self.home, {}, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type] with contextlib.redirect_stdout(io.StringIO()): planning.planned(epic, list(self.issues)) - folder = self.home / ".local" / "state" / "do-epic" / "ABC-12" + folder = self.home / ".local" / "state" / "build-release" / "do-epic" / "ABC-12" self.assertEqual((folders, folder.is_dir()), ([str(folder)] * 2, True)) def test_a_model_off_the_routing_ladder_has_no_rung(self) -> None: @@ -181,7 +181,7 @@ class Planning(DoEpicTest): self.assertEqual(args[args.index("--add-dir") + 1], str(checkout)) def test_asks_for_one_of_the_teams_labels_too_and_takes_it(self) -> None: - with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config: + with (self.home / ".config/build-release/do-epic/config.toml").open("a", encoding="utf-8") as config: config.write('\n[label-repos]\nbackend = "api"\n') self.issues = [issue("ABC-20")] fake = FakeEffects(claude=[says({"parts": []}), says({"pick": "unclear", "question": "Is the importer in api or in web?"})], inputs=["backend"]) @@ -190,7 +190,7 @@ class Planning(DoEpicTest): def configure_team(self, *above: str) -> None: """Gives the config the team's label `backend` for api, and the settings in above.""" - path = self.home / ".claude-projects/do-epic/config.toml" + path = self.home / ".config/build-release/do-epic/config.toml" path.write_text("".join(f"{line}\n" for line in above) + path.read_text(encoding="utf-8") + '\n[label-repos]\nbackend = "api"\n', encoding="utf-8") def test_files_sub_tasks_under_the_teams_label_and_summary_template(self) -> None: @@ -379,7 +379,7 @@ class Planning(DoEpicTest): self.description = RANKED self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude", by_loop=False), issue("ABC-21", "do-epic-claude")] # An earlier run made the folder the scoring runs in. - (self.home / planning.STATE / "ABC-12").mkdir(parents=True, exist_ok=True) + (self.home / ".local/state/build-release/do-epic/ABC-12").mkdir(parents=True, exist_ok=True) fake = FakeEffects(claude=[says(ANSWER)]) found, store, out = self.plan(fake) assert not isinstance(found, Failure | Limited), found @@ -402,7 +402,7 @@ class Planning(DoEpicTest): self.assertEqual((found, store.writes, out, fake.made("claude")), (self.issues, [], "", [])) def test_scores_no_issue_whose_work_has_landed(self) -> None: - with (self.home / ".claude-projects/do-epic/config.toml").open("a", encoding="utf-8") as config: + with (self.home / ".config/build-release/do-epic/config.toml").open("a", encoding="utf-8") as config: config.write('\njira-unblocking-statuses = ["Release Ready"]\n') self.rule() self.description = RANKED @@ -446,11 +446,11 @@ class Planning(DoEpicTest): def claude(args: object, cwd: str, stdin: object) -> object: folders.append(cwd) return effects.claude(args, cwd, stdin) # type: ignore[arg-type] - config = load(self.home) - epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description(RANKED)), self.home, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type] + config = load(self.home, {}) + epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description(RANKED)), self.home, {}, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type] with contextlib.redirect_stdout(io.StringIO()): planning.planned(epic, list(self.issues)) - self.assertEqual(folders, [str(self.home / ".local" / "state" / "do-epic" / "ABC-12")] * 2) + self.assertEqual(folders, [str(self.home / ".local" / "state" / "build-release" / "do-epic" / "ABC-12")] * 2) self.rule() self.description = RANKED @@ -467,9 +467,9 @@ class Planning(DoEpicTest): store = MemoryEpic("ABC-12", list(self.issues)) store.fails = "Jira answered 503" out = io.StringIO() - config = load(self.home) + config = load(self.home, {}) assert not isinstance(config, Failure), config - epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, FakeEffects(claude=[says(ANSWER)]).effects()) # type: ignore[arg-type] + epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, FakeEffects(claude=[says(ANSWER)]).effects()) # type: ignore[arg-type] with contextlib.redirect_stdout(out): found, stopped = planning.scored(epic, list(self.issues)) self.assertEqual((found, stopped, out.getvalue()), (self.issues, None, "<1790000000> scoring ABC-20\n<1790000000> ABC-20 is not scored: Jira answered 503\n")) @@ -518,9 +518,9 @@ class Planning(DoEpicTest): def planned_on(self, store: MemoryEpic, fake: FakeEffects) -> tuple[list[EpicIssue], Failure | Limited | None]: """What planning answers for self.issues on a store that doesn't read as MemoryEpic does.""" - config = load(self.home) + config = load(self.home, {}) assert not isinstance(config, Failure), config - epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, fake.effects()) # type: ignore[arg-type] + epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, fake.effects()) # type: ignore[arg-type] with contextlib.redirect_stdout(io.StringIO()): return planning.planned(epic, list(self.issues)) diff --git a/bin/do_epic/test_repos.py b/bin/do_epic/test_repos.py index 1f59e1f7..dc9dabdd 100644 --- a/bin/do_epic/test_repos.py +++ b/bin/do_epic/test_repos.py @@ -43,7 +43,7 @@ class LocateTest(unittest.TestCase): made = tempfile.TemporaryDirectory() self.addCleanup(made.cleanup) self.home = pathlib.Path(made.name).resolve() - self.projects = self.home / ".claude-projects" + self.projects = self.home / ".config/build-release" self.config = DoEpicConfig(self.projects / "do-epic", "https://acme.atlassian.net", self.home / "jira.env", self.home / "clones", "English", "claude-opus-5-5", "rule") self.billing, self.payments = self.home / "elsewhere" / "billing", self.home / "elsewhere" / "payments" self.origins: dict[str, str | Failure] = {str(self.billing): "git@github.com:acme/billing.git", str(self.payments): "git@github.com:acme/payments"} @@ -52,7 +52,7 @@ class LocateTest(unittest.TestCase): write_config(self.home, self.home / "code" / "ledger") def locate(self, git: FakeGit, name: str = "ledger") -> Located | Failure: - return locate(name, [self.billing, self.payments], self.config, self.home, git) + return locate(name, [self.billing, self.payments], self.config, self.home, {}, git) def unsure(self, git: FakeGit, name: str = "ledger") -> str: found = self.locate(git, name) @@ -100,7 +100,7 @@ class LocateTest(unittest.TestCase): def test_asks_where_no_other_repo_shows_where_to_clone_from(self) -> None: self.configure() - found = locate("ledger", [], self.config, self.home, FakeGit({})) + found = locate("ledger", [], self.config, self.home, {}, FakeGit({})) assert isinstance(found, Unsure), found self.assertIn("no other repo of the epic", found.reason) diff --git a/bin/do_epic/test_scheduler.py b/bin/do_epic/test_scheduler.py index a7bc8e34..635c1d6a 100644 --- a/bin/do_epic/test_scheduler.py +++ b/bin/do_epic/test_scheduler.py @@ -222,12 +222,12 @@ class StartingAnEpicsChunks(unittest.TestCase): found = self.start(self.epic(2, api=1, web=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "do-epic-claude"), issue("ABC-22", "repo:web")], run) self.assertEqual(found, Started(["ABC-20", "ABC-21"], [Waits("ABC-22", "the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 2")])) self.assertEqual(run.started(), [("epic-ABC-12", "ABC-20", f"{CHUNK_FLAG} ABC-20 ABC-12"), ("epic-ABC-12", "ABC-21", f"{CHUNK_FLAG} ABC-21 ABC-12")]) - self.assertEqual([args[args.index("-c") + 1] for args in run.calls if args[0] in ("new-session", "new-window")], [str(self.home / "code/api"), str(self.home / ".local/state/do-epic/ABC-12")]) + self.assertEqual([args[args.index("-c") + 1] for args in run.calls if args[0] in ("new-session", "new-window")], [str(self.home / "code/api"), str(self.home / ".local/state/build-release/do-epic/ABC-12")]) self.assertIn("BUILD_RELEASE_X=1", run.calls[[args[0] for args in run.calls].index("new-session")]) self.assertNotIn("OTHER=2", run.calls[[args[0] for args in run.calls].index("new-session")]) def parked(self, issue_key: str, on: str = "an approval") -> None: - self.assertIsNone(park(self.home / ".local/state/do-epic/ABC-12", Parked(issue_key, f"/code/api-{issue_key}", "7", "0c0f", on))) + self.assertIsNone(park(self.home / ".local/state/build-release/do-epic/ABC-12", Parked(issue_key, f"/code/api-{issue_key}", "7", "0c0f", on))) def test_starts_the_chunks_in_the_epics_start_order_and_those_it_leaves_out_last_in_backlog_order(self) -> None: self.order = ("ABC-23", "ABC-21") @@ -260,7 +260,7 @@ class StartingAnEpicsChunks(unittest.TestCase): run = Tmux(*windows, ("epic-ABC-12", "ABC-21", False, str(self.home / "code/api"))) found = self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], run) self.assertEqual(found, Started(["ABC-20"], [])) - self.assertEqual(run.windows[-1], ("epic-ABC-12", "ABC-20", False, str(self.home / ".local/state/do-epic/ABC-12"))) + self.assertEqual(run.windows[-1], ("epic-ABC-12", "ABC-20", False, str(self.home / ".local/state/build-release/do-epic/ABC-12"))) self.assertEqual([name for _, name, dead, _ in run.windows if dead], [""] * len(windows)) def test_a_human_task_that_blocks_an_issue_gets_a_window_that_takes_no_slot_of_the_epics_cap(self) -> None: @@ -292,7 +292,7 @@ class StartingAnEpicsChunks(unittest.TestCase): def test_stops_on_a_parked_chunk_it_cannot_read_and_starts_none(self) -> None: self.parked("ABC-20") - file_of(self.home / ".local/state/do-epic/ABC-12", "ABC-20").write_text("{") + file_of(self.home / ".local/state/build-release/do-epic/ABC-12", "ABC-20").write_text("{") run = Tmux() found = start_chunks(self.epic(2, api=2), [issue("ABC-21", "repo:api")], False, None, run) assert isinstance(found, Failure) @@ -314,7 +314,7 @@ class StartingAnEpicsChunks(unittest.TestCase): self.assertEqual(run.windows[0], ("epic-ABC-12", "ABC-20", False, str(self.home / "code/api"))) def test_a_parked_chunk_whose_window_started_again_doesnt_count_itself_as_running(self) -> None: - for root in (str(self.home / ".local/state/do-epic/ABC-12"), str(self.home / "code/api")): + for root in (str(self.home / ".local/state/build-release/do-epic/ABC-12"), str(self.home / "code/api")): with self.subTest(root=root): run = Tmux(("epic-ABC-12", "ABC-20", False, root)) self.assertIsNone(self.resumed(self.epic(1, api=1), run)) @@ -373,12 +373,12 @@ class StartingAnEpicsChunks(unittest.TestCase): def test_holds_each_repos_starting_lock_that_build_release_holds(self) -> None: self.start(self.epic(1, api=1), [issue("ABC-20", "repo:api")], Tmux()) - self.assertTrue((self.home / ".local/state/loop-claude/api/starting").is_file()) - self.assertTrue((self.home / ".local/state/do-epic/ABC-12/starting").is_file()) + self.assertTrue((self.home / ".local/state/build-release/claims/api/starting").is_file()) + self.assertTrue((self.home / ".local/state/build-release/do-epic/ABC-12/starting").is_file()) def test_a_parked_chunk_resumes_under_the_starting_lock_of_its_repos_checkout(self) -> None: self.assertIsNone(self.resumed(self.epic(1, api=1), Tmux(("epic-ABC-12", "ABC-20 awaits an approval", False, "")))) - self.assertEqual([lock.parent.name for lock in (self.home / ".local/state/loop-claude").glob("*/starting")], ["api"]) + self.assertEqual([lock.parent.name for lock in (self.home / ".local/state/build-release/claims").glob("*/starting")], ["api"]) def test_the_waits_keep_the_trackers_rank_order(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20", True, str(self.home / "code/api")), ("epic-ABC-12", "ABC-22", False, str(self.home / "code/api"))) @@ -393,19 +393,19 @@ class StartingAnEpicsChunks(unittest.TestCase): self.assertNotIn(tmux.OWNER, options) def test_says_which_lock_it_could_not_take(self) -> None: - (self.home / ".local/state/do-epic").mkdir(parents=True) - (self.home / ".local/state/do-epic/ABC-12").write_text("", encoding="utf-8") + (self.home / ".local/state/build-release/do-epic").mkdir(parents=True) + (self.home / ".local/state/build-release/do-epic/ABC-12").write_text("", encoding="utf-8") found = start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, Tmux()) assert isinstance(found, Failure) - self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/do-epic/ABC-12: \\w") + self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/build-release/do-epic/ABC-12: \\w") def test_says_which_repos_lock_it_could_not_take(self) -> None: - (self.home / ".local/state").mkdir(parents=True) - (self.home / ".local/state/loop-claude").write_text("", encoding="utf-8") + (self.home / ".local/state/build-release").mkdir(parents=True) + (self.home / ".local/state/build-release/claims").write_text("", encoding="utf-8") found = start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, Tmux()) assert isinstance(found, Failure) - self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/loop-claude/\\S+: \\w") - self.assertRegex(self.resumed(self.epic(1, api=1), Tmux()) or "", f"^cannot lock {self.home}/.local/state/loop-claude/\\S+: \\w") + self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/build-release/claims/\\S+: \\w") + self.assertRegex(self.resumed(self.epic(1, api=1), Tmux()) or "", f"^cannot lock {self.home}/.local/state/build-release/claims/\\S+: \\w") def test_an_error_raised_under_the_lock_is_not_reported_as_the_locks(self) -> None: def failing(args: list[str]) -> subprocess.CompletedProcess[str]: diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index ee621a36..a5d5703f 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -3,7 +3,7 @@ usage: judge-replay <model> [--offline] <model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the -verdicts archived for the projects that ~/.claude/loop-claude-models.json runs on it: the latest +verdicts archived for the projects that ~/.config/build-release/models.json runs on it: the latest 15 of each kind, finished, unfinished, interrupt and quoted answer. Where the archive kept the judge's own prompt (docs/decisions.md → `build-release: the archive keeps the raw transcript and each judge run, …`), the replay hands the judge that prompt, which holds what the judge read then. For a verdict from before the @@ -28,7 +28,7 @@ keeps the judge to its own model's rungs; a rung above them that misses no inter evidence to let the judge climb onto it. It keeps each run and the report it prints in build-release's archive, in -replays/judge-replay-<model>-<UTC stamp>/ under ~/.claude/loop-claude-transcripts or $BUILD_RELEASE_TRANSCRIPTS. +replays/judge-replay-<model>-<UTC stamp>/ under ~/.local/state/build-release/transcripts or $BUILD_RELEASE_TRANSCRIPTS. A run's .jsonl file starts with a line holding claude's arguments, working directory, prompt, exit code and stderr, then holds claude's stream-json output; result.md holds the report. @@ -93,7 +93,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff project = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: model_argument(ladder, [arg for arg in argv if arg != OFFLINE])) if isinstance(project, int): return project - cases = archived_cases(project.rung.model, archive_root(home, env), home) + cases = archived_cases(project.rung.model, archive_root(home, env), home, env) if isinstance(cases, Failure): return failed(TOOL, cases.reason) if not cases: @@ -105,7 +105,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff effects = archiving(effects, folder, say) reference = Rung(project.rung.model, REFERENCE_EFFORT) # The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge. - replay = replayed(cases, reference, down_from(ladder, project.rung, project.lowest_worker_rung()), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", say, AT_ONCE, climbs(project, reference)) + replay = replayed(cases, reference, down_from(ladder, project.rung, project.lowest_worker_rung()), lambda found, rung: rule(found, rung, home, env, effects), reproduced, "verdicts", say, AT_ONCE, climbs(project, reference)) if isinstance(replay, Limited): return limited_exit(TOOL, replay) print_report(folder, report(project.rung.model, reference, cases, replay)) @@ -138,8 +138,8 @@ def climbs(project: ProjectRung, reference: Rung) -> list[Rung]: return sorted({project.review_floor(score) for score in REVIEW_STEPS} - {project.rung, reference}, key=project.ladder.position) -def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure: - projects = projects_on(model, home) +def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path, env: typing.Mapping[str, str]) -> list[Case] | Failure: + projects = projects_on(model, home, env) if isinstance(projects, Failure): return projects listed = archived_outcomes(root) @@ -155,7 +155,7 @@ def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[C return found -def rule(case: Case, rung: Rung, home: pathlib.Path, effects: Effects) -> Kind | Limited: +def rule(case: Case, rung: Rung, home: pathlib.Path, env: typing.Mapping[str, str], effects: Effects) -> Kind | Limited: entries = read_transcript(str(case.transcript)) if isinstance(entries, Failure): return verdict_kind(entries) @@ -168,7 +168,7 @@ def rule(case: Case, rung: Rung, home: pathlib.Path, effects: Effects) -> Kind | return verdict_kind(grounds) verdict: Verdict | Failure | Limited = first_reply(lambda: judge_archived(case.root, kept.prompt, grounds, len(entries), rung, BUILD_RELEASE, effects)) return verdict if isinstance(verdict, Limited) else verdict_kind(verdict) - premises, records = read_premises(case.root, home), read_records(case.root, home, home / CLAUDE_HOME) + premises, records = read_premises(case.root, home, env), read_records(case.root, home, env, home / CLAUDE_HOME) if isinstance(premises, Failure): return verdict_kind(premises) if isinstance(records, Failure): diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index df34918d..4b24a8e7 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -122,13 +122,14 @@ class Main(unittest.TestCase): def setUp(self): self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) (self.home / ".claude").mkdir() - (self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"})) + (self.home / ".config/build-release").mkdir(parents=True) + (self.home / ".config/build-release" / "models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"})) (self.home / ".claude" / "CLAUDE.md").write_text("Be kind.\n") for key, verdicts in (("proj", (FINISHED, INTERRUPTED)), ("other", (FINISHED,))): (self.home / "code" / key).mkdir(parents=True) (self.home / "code" / key / "README.md").write_text("# p\n\n## Goals\n\n1. Ship.\n\n## Audience\n\nMe.\n") configured(self, self.home / "code" / key, home=self.home) - chunk = self.home / ".claude" / "loop-claude-transcripts" / key / "c1" + chunk = self.home / ".local/state/build-release" / "transcripts" / key / "c1" chunk.mkdir(parents=True) for n, verdict in enumerate(verdicts): (chunk / f"t{n}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": f"said {verdict}"}]}}) + "\n") @@ -187,18 +188,18 @@ class Main(unittest.TestCase): self.assertEqual(self.calls, []) self.assertIn("Replayed 2 archived verdicts of claude-opus-5-5 projects offline, without sending anything to an outside service. The archive gives them as 1 finished, 1 interrupt.", out) self.assertIn("\"?\" rule, on the whole archive: decided 2 of 2: finished 2 (of these, archived interrupt 1). Missed interrupts: 1.", out) - folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "judge-replay-claude-opus-5-5-offline-20260921T141320Z" + folder = self.home / ".local/state/build-release" / "transcripts" / "replays" / "judge-replay-claude-opus-5-5-offline-20260921T141320Z" self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out) def test_offline_exits_1_where_no_transcript_can_be_read(self): - for path in (self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1").glob("*.jsonl"): + for path in (self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1").glob("*.jsonl"): path.unlink() code, out, err = self.run_main(["claude-opus-5-5", "--offline"], unused) self.assertEqual((code, out), (1, "")) self.assertEqual(err.splitlines()[-1], "judge-replay: no archived verdict has a transcript that can be read") def test_offline_skips_each_verdict_whose_transcript_cannot_be_read_and_says_how_many_on_stderr_and_in_the_report(self): - kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" + kept = self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1" (kept / "t2.outcomes.md").write_text(f"Task: Do it.\n\n2026-10-14T10:00:02Z {FINISHED}\n\nEvidence:\n> e\n") (kept / "t0.jsonl").unlink() code, out, err = self.run_main(["claude-opus-5-5", "--offline"], unused) @@ -211,7 +212,7 @@ class Main(unittest.TestCase): def test_offline_keeps_its_report_in_the_same_folder_wherever_the_flag_stands(self): code, out, err = self.run_main(["--offline", "claude-opus-5-5"], unused) self.assertEqual(code, 0, err) - folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "judge-replay-claude-opus-5-5-offline-20260921T141320Z" + folder = self.home / ".local/state/build-release" / "transcripts" / "replays" / "judge-replay-claude-opus-5-5-offline-20260921T141320Z" self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out) def test_offline_says_the_usage_on_arguments_that_name_no_model(self): @@ -222,13 +223,13 @@ class Main(unittest.TestCase): def test_keeps_each_run_and_the_printed_report_in_one_folder_of_the_archive_beside_the_projects(self): code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) self.assertEqual(code, 0, err) - folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "judge-replay-claude-opus-5-5-20260921T141320Z" + folder = self.home / ".local/state/build-release" / "transcripts" / "replays" / "judge-replay-claude-opus-5-5-20260921T141320Z" self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out) runs = [json.loads(path.read_text(encoding="utf-8").splitlines()[0]) for path in folder.glob("*.jsonl")] self.assertEqual({run["prompt"] for run in runs}, set(self.prompts)) def test_says_where_it_could_not_keep_a_run_and_still_prints_the_report(self): - replays = self.home / ".claude" / "loop-claude-transcripts" / "replays" + replays = self.home / ".local/state/build-release" / "transcripts" / "replays" replays.write_text("") code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) self.assertEqual(code, 0, err) @@ -241,7 +242,7 @@ class Main(unittest.TestCase): self.assertEqual(err.splitlines()[:2], ["replaying 2 verdicts on claude-opus-5-5 at xhigh effort", "replaying 2 verdicts on claude-fable-5-2 at low effort"]) def test_replays_four_verdicts_at_once(self): - chunk = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" + chunk = self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1" for n in range(2, 8): (chunk / f"t{n}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": f"said {FINISHED} {n}"}]}}) + "\n") (chunk / f"t{n}.outcomes.md").write_text(f"Task: Do it.\n\n2026-10-14T10:00:0{n}Z {FINISHED}\n\nEvidence:\n> e\n") @@ -267,7 +268,7 @@ class Main(unittest.TestCase): self.assertNotIn("None", schema) def test_hands_the_judge_the_prompt_the_archive_kept_and_rebuilds_the_prompt_of_a_verdict_with_none(self): - kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" + kept = self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1" prompt = "From the goals file, OLD premises\n\nThe records: none\n\nThe task the worker was given:\nDo it.\n\nWhat the worker did and said, what the human typed on [human] lines and what build-release told it on [loop] lines, latest last:\nsaid Verdict: finished\n\nOLD rules" (kept / "judge").mkdir() (kept / "judge" / "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json").write_text(json.dumps({"prompt": prompt, "reply": {"type": "result"}})) @@ -285,7 +286,7 @@ class Main(unittest.TestCase): self.assertIn("1. Ship.", self.prompts[1]) def test_a_verdict_whose_archived_judge_run_cannot_be_read_replays_as_failed(self): - kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" + kept = self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1" (kept / "t0.outcomes.md").write_text("Task: Do it.\n\n2026-10-14T10:00:00Z Verdict: finished\n\nJudge: j\nJudge run: judge/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.json\nWorker: x\n") code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) self.assertEqual(code, 0, err) @@ -299,7 +300,7 @@ class Main(unittest.TestCase): self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"), out) def test_a_fable_project_tries_no_rung_below_opus_at_medium_and_its_report_names_fable(self): - (self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-fable-5-2"})) + (self.home / ".config/build-release" / "models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-fable-5-2"})) code, out, err = self.run_main(["claude-fable-5-2"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) self.assertEqual(code, 0, err) self.assertEqual([(model, effort) for model, effort, _ in self.calls][-1], ("claude-opus-5-5", "medium")) @@ -314,13 +315,13 @@ class Main(unittest.TestCase): self.assertTrue(out.endswith(": none, the project's rung misses one\n")) def test_replays_a_verdict_whose_transcript_is_gone_as_failed(self): - (self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" / "t0.jsonl").unlink() + (self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1" / "t0.jsonl").unlink() code, out, _ = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED}")) self.assertEqual(code, 0) self.assertIn("replayed failed: could not read the transcript", out) def test_replays_a_verdict_whose_transcript_is_compressed(self): - self.assertIsNone(compress(self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" / "t0.jsonl")) + self.assertIsNone(compress(self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1" / "t0.jsonl")) code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}")) self.assertEqual(code, 0, err) self.assertNotIn("replayed failed", out) @@ -352,7 +353,7 @@ class Main(unittest.TestCase): self.assertIn("no archived verdicts of projects on claude-fable-5-2", err) def test_exits_1_on_an_unreadable_models_file(self): - (self.home / ".claude" / "loop-claude-models.json").write_text("[") + (self.home / ".config/build-release" / "models.json").write_text("[") self.assertEqual(self.run_main(["claude-opus-5-5"], unused)[0], 1) def test_prints_the_help(self): @@ -365,7 +366,7 @@ class Main(unittest.TestCase): self.assertIn("usage: judge-replay <model>", ran.stdout) def test_exits_1_on_a_usage_limit_met_on_an_archived_prompt(self): - kept = self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" + kept = self.home / ".local/state/build-release" / "transcripts" / "proj" / "c1" (kept / "judge").mkdir() (kept / "judge" / "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json").write_text(json.dumps({"prompt": "P", "reply": {}})) (kept / "t0.outcomes.md").write_text("Task: Do it.\n\n2026-10-14T10:00:00Z Verdict: finished\n\nJudge: j\nJudge run: judge/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json\nWorker: x\n") diff --git a/bin/larv_review/history_changes.py b/bin/larv_review/history_changes.py index ad0ea0c7..63159dcd 100644 --- a/bin/larv_review/history_changes.py +++ b/bin/larv_review/history_changes.py @@ -1,3 +1,4 @@ +from collections.abc import Mapping import pathlib from failure import Failure @@ -7,11 +8,11 @@ from project_config.main import located from record_store.stores import store -def history_changes(default: str, home: pathlib.Path) -> list[HistoryChange] | Failure: +def history_changes(default: str, home: pathlib.Path, env: Mapping[str, str]) -> list[HistoryChange] | Failure: """Each merged change on the default branch that touched the history, newest first. A Failure where no commit holds the history, as for one the project's config puts outside the checkout.""" if partial := full_history(): return partial - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config record = store(config, "comprehension-history") diff --git a/bin/larv_review/history_commands.py b/bin/larv_review/history_commands.py index cebd2b80..8c837592 100644 --- a/bin/larv_review/history_commands.py +++ b/bin/larv_review/history_commands.py @@ -18,9 +18,9 @@ from larv_review.scoring_setup import removed_setup Say = typing.Callable[[str], None] -def record_ruling(votes_file: pathlib.Path, home: pathlib.Path, now: float) -> str | Failure: +def record_ruling(votes_file: pathlib.Path, home: pathlib.Path, env: typing.Mapping[str, str], now: float) -> str | Failure: """Records the ruling the votes file's seats reach, and returns what the tool prints: the ruling and where it went, or which seats to launch where they split.""" - read = read_seats(votes_file, True, home, now) + read = read_seats(votes_file, True, home, env, now) if isinstance(read, Failure): return read heading_read, seats_read = read @@ -35,25 +35,25 @@ def record_ruling(votes_file: pathlib.Path, home: pathlib.Path, now: float) -> s if split(overall_votes): return f"Split: {tally}. Launch the maintainability senior and Junior A together, add their lines to the votes file, and run this again." ruled = ruling(overall_votes) - appended_to = append(seats_read.read, ruling_entry(heading_read.title, seats_read.seats, written, counts, ruled), home) + appended_to = append(seats_read.read, ruling_entry(heading_read.title, seats_read.seats, written, counts, ruled), home, env) return appended_to if isinstance(appended_to, Failure) else f"Ruling: {ruled}. Overall votes as counted: {tally}.\n{appended_to}" -def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int], home: pathlib.Path, now: float, say: Say, warn: Say) -> Failure | None: +def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int], home: pathlib.Path, env: typing.Mapping[str, str], now: float, say: Say, warn: Say) -> Failure | None: """Records the scoring run the scores file holds in the comprehension history, and ranks the plan again. It says each result as soon as it has it, since a later step may fail after the run is recorded.""" - read = read_seats(scores_file, False, home, now) + read = read_seats(scores_file, False, home, env, now) if isinstance(read, Failure): return read named, given = read scoring = scored_seats(given) if isinstance(scoring, Failure): return scoring - reasons = plan_reasons(default, ids, home) + reasons = plan_reasons(default, ids, home, env) if isinstance(reasons, Failure): return reasons if not reasons: return Failure("no plan item or release calls this scoring run; name the item IDs the chunk ships, as needs-scoring-run took them") - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config checkout = str(config.top) @@ -61,7 +61,7 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int], home if isinstance(todo, Failure): return todo plan = todo.items - appended_to = append(given.read, scoring_entry(named.title, scoring), home) + appended_to = append(given.read, scoring_entry(named.title, scoring), home, env) if isinstance(appended_to, Failure): return appended_to say(appended_to) @@ -70,14 +70,14 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int], home say(f"Floor: {', '.join(under)} under the floor of {config.readability_floor}.") if step := floor_step(scoring.means, plan, ids, config.readability_floor): say(step) - reranked = rerank(home, warn) - removed = removed_setup(checkout, home) + reranked = rerank(home, env, warn) + removed = removed_setup(checkout, home, env) return reranked or (removed and Failure(f"recorded the run, but {removed.reason}")) -def rerank(home: pathlib.Path, warn: Say) -> Failure | None: +def rerank(home: pathlib.Path, env: typing.Mapping[str, str], warn: Say) -> Failure | None: """Rank the project's todo.md again as rank_todo.py does, since the overall sets code health's weight, and fail where rank_todo.py would. The run stays recorded whatever happens, so those failures say to settle todo.md and run rank_todo.py on it, not to record the run again.""" - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config todo = config.plan_file @@ -102,13 +102,13 @@ def scored_seats(given: SeatsFile) -> ScoringRun | Failure: return ScoringRun(given.seats, found, means(list(found.values()))) -def read_seats(path: pathlib.Path, paired: bool, home: pathlib.Path, now: float) -> tuple[Heading, SeatsFile] | Failure: +def read_seats(path: pathlib.Path, paired: bool, home: pathlib.Path, env: typing.Mapping[str, str], now: float) -> tuple[Heading, SeatsFile] | Failure: """The heading the seats file's entry goes under, and the file, as decided says. Its callers run it first, so a file it refuses fails before anything is printed.""" try: text = path.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read {path}: {failure}") - history = history_file(home) + history = history_file(home, env) if isinstance(history, Failure): return history return decided(text, now, paired, commit_exists, history) @@ -129,8 +129,8 @@ def decided(text: str, now: float, paired: bool, commit_known: typing.Callable[[ return named, given -def read_places(home: pathlib.Path) -> str | Failure: - history = history_file(home) +def read_places(home: pathlib.Path, env: typing.Mapping[str, str]) -> str | Failure: + history = history_file(home, env) return history if isinstance(history, Failure) else places_report(history[1]) @@ -139,20 +139,20 @@ def places_report(history: str) -> str: return (latest_places(history) or "Seats found no places hard.").rstrip("\n") -def read_agreement(home: pathlib.Path) -> str | Failure: - history = history_file(home) +def read_agreement(home: pathlib.Path, env: typing.Mapping[str, str]) -> str | Failure: + history = history_file(home, env) return history if isinstance(history, Failure) else agreement_report(history[1]) -def history_file(home: pathlib.Path) -> tuple[RecordStore, str] | Failure: +def history_file(home: pathlib.Path, env: typing.Mapping[str, str]) -> tuple[RecordStore, str] | Failure: """The store the project's config names for its comprehension history, and the history's text, empty where there is none yet.""" - held = held_history(home) + held = held_history(home, env) return held if isinstance(held, Failure) else (held[0], held[1].text) -def held_history(home: pathlib.Path) -> tuple[RecordStore, Held] | Failure: +def held_history(home: pathlib.Path, env: typing.Mapping[str, str]) -> tuple[RecordStore, Held] | Failure: """The store the project's config names for its comprehension history, and the history as it stands, with the version a write over it names.""" - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config history = store(config, "comprehension-history") @@ -160,9 +160,9 @@ def held_history(home: pathlib.Path) -> tuple[RecordStore, Held] | Failure: return held if isinstance(held, Failure) else (history, held) -def append(read: str, entry: str, home: pathlib.Path) -> str | Failure: +def append(read: str, entry: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> str | Failure: """Appends entry and returns the line the tool prints; a Failure where the history already holds an entry on what the seats read.""" - read_history = held_history(home) + read_history = held_history(home, env) return read_history if isinstance(read_history, Failure) else appended_to(*read_history, read, entry) diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index 3535c957..dccc2a6a 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -15,8 +15,8 @@ stderr; the other four exit 1. The history is docs/comprehension-history.md in the checkout. review-folder makes the chunk's review folder, where each reviewer writes its report, and prints its -path: ~/.local/state/larv-review/ followed by the worktree's path relative to ~, or to / outside it. -It leaves ~/.local/state/larv-review readable by you alone. +path: ~/.local/state/build-release/larv-review/ followed by the worktree's path relative to ~, or to / outside it. +It leaves ~/.local/state/build-release/larv-review readable by you alone. ruling-base prints the commit a paired ruling reads against, then which of these found it. The last measured commit is the default branch's newest merged change that adds a paired ruling or a scoring @@ -165,6 +165,7 @@ when git cannot start, finds no checkout or no default branch, cannot fetch orig needs-scoring-run, scoring-run-owed or record-scoring, or cannot read or write the history, todo.md, the review folder or a file prepare-scoring reads. """ +import os import pathlib import re import sys @@ -209,11 +210,11 @@ def are_ids(given: list[str]) -> bool: def run_needs_scoring_run(given: list[str]) -> Failure | None: - return with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given], pathlib.Path.home()), stale_ok=False) + return with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given], pathlib.Path.home(), os.environ), stale_ok=False) def run_record_scoring(given: list[str]) -> Failure | None: - return with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]], pathlib.Path.home(), time.time(), print, warn), stale_ok=False) + return with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]], pathlib.Path.home(), os.environ, time.time(), print, warn), stale_ok=False) def fits_reviewer_header(given: list[str]) -> bool: @@ -221,23 +222,23 @@ def fits_reviewer_header(given: list[str]) -> bool: def run_reviewer_header(given: list[str]) -> Failure | None: - return with_default_branch(lambda default: printed(reviewer_header(default, given[0], given[1:] == ["--rerun"], pathlib.Path.home())), stale_ok=True) + return with_default_branch(lambda default: printed(reviewer_header(default, given[0], given[1:] == ["--rerun"], pathlib.Path.home(), os.environ)), stale_ok=True) # One row per subcommand: main, USAGE and `--help` all read this table. COMMANDS = { "review-folder": Command("review-folder", no_arguments, lambda given: make_review_folder()), - "ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(lambda default: show_ruling_base(default, pathlib.Path.home()), stale_ok=False)), + "ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(lambda default: show_ruling_base(default, pathlib.Path.home(), os.environ), stale_ok=False)), "round-count": Command("round-count", no_arguments, lambda given: with_default_branch(round_count, stale_ok=True)), "needs-scoring-run": Command("needs-scoring-run [<item ID>...]", are_ids, run_needs_scoring_run, ids_from=0), - "scoring-run-owed": Command("scoring-run-owed", no_arguments, lambda given: with_default_branch(lambda default: owed(default, pathlib.Path.home()), stale_ok=False)), - "record-ruling": Command("record-ruling <votes file>", lambda given: len(given) == 1, lambda given: printed(record_ruling(pathlib.Path(given[0]), pathlib.Path.home(), time.time()))), + "scoring-run-owed": Command("scoring-run-owed", no_arguments, lambda given: with_default_branch(lambda default: owed(default, pathlib.Path.home(), os.environ), stale_ok=False)), + "record-ruling": Command("record-ruling <votes file>", lambda given: len(given) == 1, lambda given: printed(record_ruling(pathlib.Path(given[0]), pathlib.Path.home(), os.environ, time.time()))), "prepare-scoring": Command("prepare-scoring", no_arguments, lambda given: prepared_scoring()), "record-scoring": Command("record-scoring <scores file> [<item ID>...]", lambda given: bool(given) and are_ids(given[1:]), run_record_scoring, ids_from=1), - "places": Command("places", no_arguments, lambda given: printed(read_places(pathlib.Path.home()))), - "agreement": Command("agreement", no_arguments, lambda given: printed(read_agreement(pathlib.Path.home()))), + "places": Command("places", no_arguments, lambda given: printed(read_places(pathlib.Path.home(), os.environ))), + "agreement": Command("agreement", no_arguments, lambda given: printed(read_agreement(pathlib.Path.home(), os.environ))), "reviewer-header": Command("reviewer-header <pass> [--rerun]", fits_reviewer_header, run_reviewer_header), - "round-title": Command("round-title <pass>", lambda given: len(given) == 1 and given[0] in REVIEWERS, lambda given: with_default_branch(lambda default: printed(round_title(default, given[0], pathlib.Path.home())), stale_ok=True)), + "round-title": Command("round-title <pass>", lambda given: len(given) == 1 and given[0] in REVIEWERS, lambda given: with_default_branch(lambda default: printed(round_title(default, given[0], pathlib.Path.home(), os.environ)), stale_ok=True)), "reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))), } SHAPES = " | ".join(command.shape for command in COMMANDS.values()) @@ -291,22 +292,22 @@ def with_default_branch(command: typing.Callable[[str], Failure | None], stale_o def prepared_scoring() -> Failure | None: worktree = top() - return worktree if isinstance(worktree, Failure) else printed(prepare_scoring(worktree, pathlib.Path.home())) + return worktree if isinstance(worktree, Failure) else printed(prepare_scoring(worktree, pathlib.Path.home(), os.environ)) def make_review_folder() -> Failure | None: worktree = top() if isinstance(worktree, Failure): return worktree - folder = made_review_folder(worktree, pathlib.Path.home()) + folder = made_review_folder(worktree, pathlib.Path.home(), os.environ) if isinstance(folder, Failure): return folder print(folder) return None -def show_ruling_base(default: str, home: pathlib.Path) -> Failure | None: - changes = history_changes(default, home) +def show_ruling_base(default: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> Failure | None: + changes = history_changes(default, home, env) if isinstance(changes, Failure): return changes if found := measured_commit(changes): @@ -320,7 +321,7 @@ def show_ruling_base(default: str, home: pathlib.Path) -> Failure | None: def round_count(default: str) -> Failure | None: - summaries = branch_summaries(default, pathlib.Path.home()) + summaries = branch_summaries(default, pathlib.Path.home(), os.environ) if isinstance(summaries, Failure): return summaries for name, count in round_counts(summaries).items(): @@ -334,15 +335,15 @@ def cap_note(count: int, most: int) -> str: return f", {'at' if count == most else 'past'} the cap: no more rounds" -def owed(default: str, home: pathlib.Path) -> Failure | None: - unrecorded = owed_scoring_run(default, home, warn) +def owed(default: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> Failure | None: + unrecorded = owed_scoring_run(default, home, env, warn) if unrecorded is None: print("No scoring run owed.") return unrecorded -def needs_scoring_run(default: str, ids: list[int], home: pathlib.Path) -> Failure | None: - reasons = plan_reasons(default, ids, home) +def needs_scoring_run(default: str, ids: list[int], home: pathlib.Path, env: typing.Mapping[str, str]) -> Failure | None: + reasons = plan_reasons(default, ids, home, env) if isinstance(reasons, Failure): return reasons print(f"Scoring run due: the chunk {' and '.join(reasons)}." if reasons else "No scoring run due.") diff --git a/bin/larv_review/owed.py b/bin/larv_review/owed.py index 079ba26b..04081912 100644 --- a/bin/larv_review/owed.py +++ b/bin/larv_review/owed.py @@ -12,12 +12,12 @@ from plan_store.plans import PlanStore from record_store.stores import store -def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[str], None]) -> Failure | None: +def owed_scoring_run(default: str, home: pathlib.Path, env: typing.Mapping[str, str], warn: typing.Callable[[str], None]) -> Failure | None: """A Failure saying which scoring runs the chunk owes and has not recorded; None where it owes none. The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began doesn't count. A project with no plan owes none. Neither does one whose plan or history is outside the checkout: it warns that it cannot tell. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking. """ - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config checkout = str(config.top) @@ -33,7 +33,7 @@ def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[st base = git("merge-base", default, "HEAD", cwd=checkout) if isinstance(base, Failure): return base - reasons = plan_reasons(base.strip(), None, home) + reasons = plan_reasons(base.strip(), None, home, env) if isinstance(reasons, Failure): return reasons if not reasons: diff --git a/bin/larv_review/reviewer_header.py b/bin/larv_review/reviewer_header.py index d80b2239..a0073180 100644 --- a/bin/larv_review/reviewer_header.py +++ b/bin/larv_review/reviewer_header.py @@ -1,5 +1,6 @@ """reviewer-header: write the branch diff, the places and the plan into the chunk's review folder, and print the header of a reviewer's prompt.""" import dataclasses +from collections.abc import Mapping import pathlib from git_cli.git_repo import branch_titles, git, top @@ -80,18 +81,18 @@ def unanswered_round(titles: list[str], pass_: str) -> int | Failure: return done + 1 -def branch_summaries(default: str, home: pathlib.Path) -> list[str] | Failure: +def branch_summaries(default: str, home: pathlib.Path, env: Mapping[str, str]) -> list[str] | Failure: """The branch's commit titles since default, each read as its summary in the project's title templates, so round titles count under any template. rule-hook's round-cap reads them its own way: guarded, and counting zero rounds where git fails.""" titles = branch_titles(default) if isinstance(titles, Failure): return titles - templates = title_templates(None, home) + templates = title_templates(None, home, env) return templates if isinstance(templates, Failure) else [templates.summary(title) for title in titles] -def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -> str | Failure: +def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path, env: Mapping[str, str]) -> str | Failure: """Writes the branch diff, the places and the plan's listing into the review folder, and returns the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun.""" - summaries = branch_summaries(default, home) + summaries = branch_summaries(default, home, env) round_ = summaries if isinstance(summaries, Failure) else unanswered_round(summaries, pass_) if isinstance(round_, Failure): return round_ @@ -100,10 +101,10 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) - if failed is not None: return failed worktree, branch, head, base = (str(answer).strip() for answer in found) - folder = made_review_folder(worktree, home) + folder = made_review_folder(worktree, home, env) if isinstance(folder, Failure): return folder - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config principles, standards = config.paths["principles"], config.paths["standards"] @@ -125,18 +126,18 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) - launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, standards, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language, config.coding_conventions) if rerun and not launch.asked().exists(): return Failure(f"no report asked for a rerun of {pass_}'s round {round_}: {launch.asked()} is missing; relaunch before you commit the round's answers") - written = write_inputs(launch, base, home, plan_listing(plan_store(config))) + written = write_inputs(launch, base, home, env, plan_listing(plan_store(config))) if isinstance(written, Failure): return written return launch.header() -def write_inputs(launch: Launch, base: str, home: pathlib.Path, listing: str) -> Failure | None: +def write_inputs(launch: Launch, base: str, home: pathlib.Path, env: Mapping[str, str], listing: str) -> Failure | None: """Writes the branch diff from base to HEAD, what `larv-review places` prints, and the plan's listing into the review folder.""" diff = git("diff", base, "HEAD", errors="replace") if isinstance(diff, Failure): return diff - history = history_file(home) + history = history_file(home, env) if isinstance(history, Failure): return history try: diff --git a/bin/larv_review/round_title.py b/bin/larv_review/round_title.py index 0485cac5..930fbd16 100644 --- a/bin/larv_review/round_title.py +++ b/bin/larv_review/round_title.py @@ -1,4 +1,5 @@ """round-title: print the opening of a round commit's title, counted from the round's report.""" +from collections.abc import Mapping import pathlib from larv_review.reviewer_header import branch_summaries, unanswered_round @@ -8,14 +9,14 @@ from review_rules.round_titles import round_prefix from git_cli.git_repo import top -def round_title(default: str, pass_: str, home: pathlib.Path) -> str | Failure: +def round_title(default: str, pass_: str, home: pathlib.Path, env: Mapping[str, str]) -> str | Failure: """The title prefix of pass_'s unanswered round, counted from that round's report in the chunk's review folder.""" - summaries = branch_summaries(default, home) + summaries = branch_summaries(default, home, env) round_ = summaries if isinstance(summaries, Failure) else unanswered_round(summaries, pass_) if isinstance(round_, Failure): return round_ worktree = top() if isinstance(worktree, Failure): return worktree - findings = findings_in(standing_report(pathlib.Path(review_folder(str(home), worktree)), pass_, round_)) + findings = findings_in(standing_report(pathlib.Path(review_folder(str(home), env, worktree)), pass_, round_)) return findings if isinstance(findings, Failure) else round_prefix(pass_, round_, findings) diff --git a/bin/larv_review/scoring_due.py b/bin/larv_review/scoring_due.py index b5d75b73..fd6f9635 100644 --- a/bin/larv_review/scoring_due.py +++ b/bin/larv_review/scoring_due.py @@ -1,5 +1,6 @@ """When the plan calls a scoring run: a chunk that ships a floor item, one that empties a release that work has already landed towards, or one after a release cut unmeasured; and each reason it gives.""" +from collections.abc import Mapping import pathlib from release_plan.release_standing import Cut, LastCut, next_release, project_plan, standing_of, Unknown @@ -79,9 +80,9 @@ def finished_unseen(config: ProjectConfig, ids: list[int], chunk: list[Item]) -> return None -def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[str] | Failure: +def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path, env: Mapping[str, str]) -> list[str] | Failure: """Why the plan calls a scoring run, from todo.md at ref and the checkout's, each file where the project's config puts it; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not.""" - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config checkout = str(config.top) diff --git a/bin/larv_review/scoring_setup.py b/bin/larv_review/scoring_setup.py index 46ba1c49..62807489 100644 --- a/bin/larv_review/scoring_setup.py +++ b/bin/larv_review/scoring_setup.py @@ -1,4 +1,5 @@ """Set up a scoring run: the worktree its seats read and each seat's prompt, filled from skills/comprehension-panel/seat-prompts.md.""" +from collections.abc import Mapping import pathlib import re import shutil @@ -127,18 +128,18 @@ def prompt_parts() -> dict[str, str] | Failure: return parts -def scoring_folder(worktree: str, home: pathlib.Path) -> pathlib.Path: - return pathlib.Path(review_folder(str(home), worktree)) / "scoring" +def scoring_folder(worktree: str, home: pathlib.Path, env: Mapping[str, str]) -> pathlib.Path: + return pathlib.Path(review_folder(str(home), env, worktree)) / "scoring" -def prepare_scoring(worktree: str, home: pathlib.Path, run: Git = git) -> str | Failure: +def prepare_scoring(worktree: str, home: pathlib.Path, env: Mapping[str, str], run: Git = git) -> str | Failure: """Makes the scoring run's worktree at worktree's HEAD and writes each seat's prompt beside it, in the chunk's review folder; what it made, as the tool prints it.""" - folder = scoring_folder(worktree, home) + folder = scoring_folder(worktree, home, env) # A setup record-scoring never removed, as where the seats failed, would otherwise block every later run. replaced = folder.exists() - if replaced and isinstance(removed := removed_setup(worktree, home, run), Failure): + if replaced and isinstance(removed := removed_setup(worktree, home, env, run), Failure): return removed - config = located(worktree, home, run) + config = located(worktree, home, env, run) if isinstance(config, Failure): return config source = config.paths["working-rules"] @@ -170,7 +171,7 @@ def prepare_scoring(worktree: str, home: pathlib.Path, run: Git = git) -> str | if isinstance(head, Failure): return head main = listing.splitlines()[0].removeprefix("worktree ") - made = made_review_folder(worktree, home) + made = made_review_folder(worktree, home, env) if isinstance(made, Failure): return made checkout = folder / "checkout" @@ -206,9 +207,9 @@ def prepare_scoring(worktree: str, home: pathlib.Path, run: Git = git) -> str | return before + f"Scoring worktree, at {head.strip()}: {checkout}\nPrompts, each for one {SEAT_AGENT} agent:\n" + "\n".join(written) -def removed_setup(worktree: str, home: pathlib.Path, run: Git = git) -> Failure | None: +def removed_setup(worktree: str, home: pathlib.Path, env: Mapping[str, str], run: Git = git) -> Failure | None: """Removes the scoring worktree and prompts prepare_scoring made for the chunk at worktree, where they exist.""" - folder = scoring_folder(worktree, home) + folder = scoring_folder(worktree, home, env) if not folder.exists(): return None if (folder / "checkout").exists() and isinstance(removed := run("worktree", "remove", "--force", str(folder / "checkout"), cwd=worktree), Failure): diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 177e0189..9746608d 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -512,7 +512,7 @@ class LarvReviewTool(unittest.TestCase): self.git("remote", "set-head", "origin", "main") self.git("switch", "-q", "-c", "chunk") self.start = self.git("rev-parse", "--short", "HEAD").strip() - self.config = root / ".claude-projects" / "proj" / "config.toml" + self.config = root / ".config/build-release" / "proj" / "config.toml" self.config.parent.mkdir(parents=True) self.config.write_text(PROJECT_CONFIG) (root / "principles").mkdir() @@ -613,16 +613,16 @@ class LarvReviewTool(unittest.TestCase): (self.config.parent / "todo.md").write_text(todo(row, "| 2 | 0.2.0 | | **Reach the comprehension floor: do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")) self.addCleanup(os.chdir, os.getcwd()) os.chdir(self.checkout) - home = self.config.parents[2] - self.assertEqual(plan_reasons("origin/main", [2], home), ["ships item 2, a floor item", "leaves release 0.2.0 with no plan item"]) + home = self.config.parents[3] + self.assertEqual(plan_reasons("origin/main", [2], home, {}), ["ships item 2, a floor item", "leaves release 0.2.0 with no plan item"]) (self.config.parent / "decisions.md").write_text("# Decisions\n\n## review opt-out: the comprehension check\n\nServes goal 1.\n") - self.assertEqual(plan_reasons("origin/main", [2], home), []) + self.assertEqual(plan_reasons("origin/main", [2], home, {}), []) (self.config.parent / "decisions.md").unlink() - gone = plan_reasons("origin/main", [1, 7], home) + gone = plan_reasons("origin/main", [1, 7], home, {}) assert isinstance(gone, Failure), gone self.assertEqual(gone.reason, f"the plan as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md") (self.config.parent / "todo.md").write_bytes(b"\xff") - unreadable = plan_reasons("origin/main", [2], home) + unreadable = plan_reasons("origin/main", [2], home, {}) assert isinstance(unreadable, Failure), unreadable self.assertEqual(unreadable.reason, f"the project's plan: {self.config.parent}/todo.md: not UTF-8") @@ -782,7 +782,7 @@ class LarvReviewTool(unittest.TestCase): def test_refuses_where_the_default_branchs_unreleased_changes_cannot_be_read(self): self.addCleanup(os.chdir, os.getcwd()) os.chdir(self.checkout) - self.assertIsInstance(plan_reasons("no-such-ref", [], pathlib.Path.home()), Failure) + self.assertIsInstance(plan_reasons("no-such-ref", [], pathlib.Path.home(), {}), Failure) def test_refuses_a_checkout_plan_whose_renamed_section_does_not_parse(self): self.commit("Break the mark", {"todo.md": todo("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |") + "\n## Renamed\n\nsoon\n"}) @@ -935,7 +935,7 @@ class LarvReviewTool(unittest.TestCase): self.plan() ran = self.record_sevens() self.assertEqual(ran.returncode, 0, ran.stderr) - self.assertFalse((self.checkout.parent / ".local" / "state" / "larv-review" / "proj" / "scoring").exists()) + self.assertFalse((self.checkout.parent / ".local" / "state" / "build-release" / "larv-review" / "proj" / "scoring").exists()) self.assertEqual(len(self.git("worktree", "list").splitlines()), 1) VALUES = {"AGENTS.md": "## Scoring run\n\n- Language: Python\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n"} @@ -991,7 +991,7 @@ class LarvReviewTool(unittest.TestCase): (checkout / "todo.md").write_text("the owners' own notes\n") self.enterContext(contextlib.chdir(checkout)) said: list[str] = [] - self.assertIsNone(rerank(config.parents[2], said.append)) + self.assertIsNone(rerank(config.parents[3], {}, said.append)) self.assertEqual((said, (checkout / "todo.md").read_text()), ([], "the owners' own notes\n")) def test_reranks_todo_md_by_the_overall_it_records(self): @@ -1044,21 +1044,21 @@ class LarvReviewTool(unittest.TestCase): self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n") def test_makes_and_prints_the_worktrees_review_folder_from_anywhere_in_it(self): - reports = self.checkout.parent / ".local" / "state" / "larv-review" + reports = self.checkout.parent / ".local" / "state" / "build-release" / "larv-review" (self.checkout / "sub").mkdir() ran = subprocess.run([sys.executable, str(TOOL), "review-folder"], capture_output=True, cwd=self.checkout / "sub", env=self.env, text=True) self.assertEqual((ran.returncode, ran.stdout), (0, f"{reports}/proj\n"), ran.stderr) self.assertTrue((reports / "proj").is_dir()) def test_leaves_the_reports_folder_readable_by_the_user_alone_where_it_was_not(self): - reports = self.checkout.parent / ".local" / "state" / "larv-review" + reports = self.checkout.parent / ".local" / "state" / "build-release" / "larv-review" reports.mkdir(parents=True, mode=0o755) self.assertEqual(self.run_tool("review-folder").returncode, 0) self.assertEqual(reports.stat().st_mode & 0o777, 0o700) def test_fails_where_it_cannot_make_the_review_folder(self): - (self.checkout.parent / ".local" / "state").mkdir(parents=True) - (self.checkout.parent / ".local" / "state" / "larv-review").write_text("") + (self.checkout.parent / ".local" / "state" / "build-release").mkdir(parents=True) + (self.checkout.parent / ".local" / "state" / "build-release" / "larv-review").write_text("") ran = self.run_tool("review-folder") self.assertEqual(ran.returncode, 1) self.assertIn("could not make the review folder", ran.stderr) @@ -1125,7 +1125,7 @@ class LarvReviewTool(unittest.TestCase): self.commit("Unpushed fix", {"a.txt": "two\n"}) short = self.git("rev-parse", "--short", "HEAD").strip() base = self.git("rev-parse", self.start).strip() - folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj" + folder = self.checkout.parent / ".local" / "state" / "build-release" / "larv-review" / "proj" ran = self.run_tool("reviewer-header", "stability") self.assertEqual((ran.returncode, ran.stdout), (0, ( "Pass: stability, round 1.\n" @@ -1152,7 +1152,7 @@ class LarvReviewTool(unittest.TestCase): def test_counts_the_round_from_the_branchs_answers_and_names_the_report_that_asked_for_a_rerun(self): self.commit("Answer prose round 1: a") - folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj" + folder = self.checkout.parent / ".local" / "state" / "build-release" / "larv-review" / "proj" missing = self.run_tool("reviewer-header", "prose", "--rerun") self.assertEqual(missing.returncode, 1) self.assertIn(f"{folder}/prose-round-2.md is missing", missing.stderr) @@ -1166,7 +1166,7 @@ class LarvReviewTool(unittest.TestCase): self.assertFalse(any(line.startswith("Places:") for line in lines), "only architecture and stability take the places") def test_round_title_counts_the_unanswered_rounds_report_and_names_one_that_is_missing(self): - folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj" + folder = self.checkout.parent / ".local" / "state" / "build-release" / "larv-review" / "proj" folder.mkdir(parents=True) (folder / "prose-round-1.md").write_text("BLOCK\n\n### 🔴 [misread] `a.md:1`: wrong\n\n### 🟡 `b.md:2`: worse\n\n### 🟢 `c.md:3`: nit\n") ran = self.run_tool("round-title", "prose") @@ -1192,7 +1192,7 @@ class LarvReviewTool(unittest.TestCase): def test_reviewer_header_leaves_an_unchanged_diff_places_and_plan_untouched_so_an_earlier_rounds_replay_keeps_them(self): self.commit("Work", {"a.txt": "one\n"}) - folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj" + folder = self.checkout.parent / ".local" / "state" / "build-release" / "larv-review" / "proj" self.assertEqual(self.run_tool("reviewer-header", "stability").returncode, 0) written = [folder / f"branch-{self.git('rev-parse', '--short', 'HEAD').strip()}.diff", folder / "places.md", folder / "plan.md"] for path in written: @@ -1229,8 +1229,8 @@ class LarvReviewTool(unittest.TestCase): detached = self.run_tool("reviewer-header", "prose") self.assertEqual((detached.returncode, detached.stdout), (1, "")) self.git("switch", "-q", "chunk") - (self.checkout.parent / ".local" / "state").mkdir(parents=True) - (self.checkout.parent / ".local" / "state" / "larv-review").write_text("") + (self.checkout.parent / ".local" / "state" / "build-release").mkdir(parents=True) + (self.checkout.parent / ".local" / "state" / "build-release" / "larv-review").write_text("") unmade = self.run_tool("reviewer-header", "prose") self.assertEqual(unmade.returncode, 1) self.assertIn("could not make the review folder", unmade.stderr) @@ -1267,7 +1267,7 @@ class LarvReviewTool(unittest.TestCase): def test_reviewer_header_fails_naming_the_epic_where_it_cannot_read_goals_kept_in_jira(self): # Port 1 on the loopback refuses the connection, so the read fails without leaving the machine. epic = "jira:https://127.0.0.1:1/browse/ABC-12" - credentials = self.config.parents[2] / "acme.env" + credentials = self.config.parents[3] / "acme.env" credentials.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n") credentials.chmod(0o600) self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n') @@ -1317,7 +1317,7 @@ class LarvReviewTool(unittest.TestCase): self.assertIn(f"{self.checkout}/CONVENTIONS.md is not a file; {self.config} sets it in `coding-conventions`", ran.stderr) def test_reviewer_header_gives_the_architect_the_places(self): - folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj" + folder = self.checkout.parent / ".local" / "state" / "build-release" / "larv-review" / "proj" self.assertEqual(self.header_line("Places:", "architecture"), f"Places: {folder}/places.md") def test_reviewer_header_names_the_file_that_holds_the_principles_last_where_the_project_keeps_one(self): diff --git a/bin/larv_review/test_scoring_setup.py b/bin/larv_review/test_scoring_setup.py index 07dbee3b..36dc4324 100644 --- a/bin/larv_review/test_scoring_setup.py +++ b/bin/larv_review/test_scoring_setup.py @@ -104,7 +104,7 @@ class PrepareScoring(unittest.TestCase): def prepare(self): """What prepare-scoring returns in the checkout, run in this process so mutation tests see the lines it runs.""" - return prepare_scoring(str(self.checkout), self.root, functools.partial(git, env=self.env)) + return prepare_scoring(str(self.checkout), self.root, {}, functools.partial(git, env=self.env)) def run_tool(self, *args): return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True) @@ -112,7 +112,7 @@ class PrepareScoring(unittest.TestCase): def test_writes_each_seats_prompt_with_every_placeholder_filled_and_a_worktree_at_head(self): self.commit("# A\n\n## Scoring run\n\n- Language: Python\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n") ran = self.prepare() - folder = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" + folder = self.root / ".local" / "state" / "build-release" / "larv-review" / "proj" / "scoring" worktree = folder / "checkout" prompts = [folder / f"{seat}.md" for seat in ("junior-a", "mid-a", "maintainability-senior", "inherited-architect")] self.assertEqual(ran, f"Scoring worktree, at {self.git('rev-parse', '--short', 'HEAD').strip()}: {worktree}\nPrompts, each for one comprehension-seat agent:\n" + "\n".join(str(prompt) for prompt in prompts)) @@ -137,9 +137,9 @@ class PrepareScoring(unittest.TestCase): def test_says_it_could_not_remove_a_checkout_git_does_not_hold(self): self.commit() - checkout = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "checkout" + checkout = self.root / ".local" / "state" / "build-release" / "larv-review" / "proj" / "scoring" / "checkout" checkout.mkdir(parents=True) - removed = removed_setup(str(self.checkout), self.root, functools.partial(git, env=self.env)) + removed = removed_setup(str(self.checkout), self.root, {}, functools.partial(git, env=self.env)) self.assertIsInstance(removed, Failure) self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason) self.assertTrue(checkout.exists()) @@ -176,7 +176,7 @@ class PrepareScoring(unittest.TestCase): ran = self.prepare() assert isinstance(ran, str), ran self.assertIn("Your background: ~2 years in Go, first codebase of this kind (a CLI)", pathlib.Path(ran.splitlines()[2]).read_text()) - self.assertIsNone(removed_setup(str(self.checkout), self.root, functools.partial(git, env=self.env))) + self.assertIsNone(removed_setup(str(self.checkout), self.root, {}, functools.partial(git, env=self.env))) def test_keeps_the_working_rules_values_where_the_checkout_has_seat_prompts_too(self): own = self.checkout / "skills" / "comprehension-panel" / "seat-prompts.md" @@ -192,7 +192,7 @@ class PrepareScoring(unittest.TestCase): ran = self.run_tool("prepare-scoring") self.assertEqual(ran.returncode, 1) self.assertIn("AGENTS.md has no \"Scoring run\" section", ran.stderr) - self.assertFalse((self.root / ".local" / "state" / "larv-review" / "proj" / "scoring").exists()) + self.assertFalse((self.root / ".local" / "state" / "build-release" / "larv-review" / "proj" / "scoring").exists()) self.assertEqual(len(self.git("worktree", "list").splitlines()), 1) def test_fails_before_it_makes_the_worktree_where_a_file_it_reads_does_not_decode(self): diff --git a/bin/loop_effects/effects.py b/bin/loop_effects/effects.py index 1a2cff55..136b8ae6 100644 --- a/bin/loop_effects/effects.py +++ b/bin/loop_effects/effects.py @@ -124,7 +124,7 @@ def system_effects(home: pathlib.Path, env: typing.Mapping[str, str], backends: claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, env=with_release_tools(env), input=stdin, text=True), claude_on_terminal=claude_on_terminal, discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), - dm=lambda text, directory: notify(text, directory, home, backends), + dm=lambda text, directory: notify(text, directory, home, env, backends), execv=os.execv, forge=lambda cwd: runner(cwd, forge_timeout), git=git_repo.git, diff --git a/bin/loop_state/paths.py b/bin/loop_state/paths.py index 470cb201..54a24f78 100644 --- a/bin/loop_state/paths.py +++ b/bin/loop_state/paths.py @@ -12,10 +12,14 @@ RELEASE_ROOT = pathlib.Path(__file__).resolve().parents[2] # The Claude home: Claude Code's own folder, with its settings and transcripts. A release is deployed into it, so its CLAUDE.md, rules/ and agents/ are read from it. CLAUDE_HOME = ".claude" -# The config folder, which holds one folder per project, and do-epic's. -CONFIG_FOLDER = ".claude-projects" -# The state folder, which holds one folder per tool. -STATE_FOLDER = ".local/state" +# The setup's own folder under each of the two below. +SETUP = "build-release" +# Where the config folder is, unless the variable XDG_CONFIG_HOME names another place. +CONFIG_HOME = ".config" +XDG_CONFIG_HOME = "XDG_CONFIG_HOME" +# Where the state folder is, unless the variable XDG_STATE_HOME names another place. +STATE_HOME = ".local/state" +XDG_STATE_HOME = "XDG_STATE_HOME" # Only a claude started through this has the tools on PATH. One a person starts by hand lacks them, as their shell does: the plan keeps short names such as `wait-for` out of a person's shell. README.md → Tools says how to call a tool there. @@ -28,9 +32,26 @@ def with_release_tools(env: Mapping[str, str]) -> dict[str, str]: return {**env, "PATH": f"{tools}{os.pathsep}{rest}" if rest else tools} +def config_folder(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path: + """The config folder, which a person writes and backs up: one folder per project, do-epic's, and the model of each project.""" + # The models file is here though the tools write it: it holds a person's choice per project, and is backed up with the configs. + return xdg_folder(env.get(XDG_CONFIG_HOME), home / CONFIG_HOME) / SETUP + + def state_folder(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path: - """The state folder of a tool that honours `XDG_STATE_HOME`.""" - return pathlib.Path(env.get("XDG_STATE_HOME") or home / STATE_FOLDER) + """The state folder, which the tools write: one folder per tool.""" + # Every tool keeps its state here, none beside it, so that deleting this folder removes all the state the setup wrote. + return xdg_folder(env.get(XDG_STATE_HOME), home / STATE_HOME) / SETUP + + +# The XDG Base Directory Specification calls a relative path in one of its variables invalid, to be ignored: https://specifications.freedesktop.org/basedir-spec/latest/ +def xdg_folder(named: str | None, default: pathlib.Path) -> pathlib.Path: + return pathlib.Path(named) if named and os.path.isabs(named) else default + + +def without_xdg_folders(env: Mapping[str, str]) -> dict[str, str]: + """env without the person's own config and state folders, so that both lie under the home folder a caller names.""" + return {name: value for name, value in env.items() if name not in (XDG_CONFIG_HOME, XDG_STATE_HOME)} @dataclasses.dataclass(frozen=True) @@ -39,18 +60,23 @@ class Paths: claude_dir: pathlib.Path # The development clone of this setup, where a change to it is made: claude_dir holds only a release, docs/decisions.md → `deploy:`. config_clone: pathlib.Path + config_folder: pathlib.Path home: pathlib.Path model_catalog: pathlib.Path models_file: pathlib.Path + state_folder: pathlib.Path -def paths_from(home: pathlib.Path) -> Paths: +def paths_from(home: pathlib.Path, env: Mapping[str, str]) -> Paths: claude = home / CLAUDE_HOME + config = config_folder(env, home) return Paths( claude_code_transcripts=claude / "projects", claude_dir=claude, config_clone=home / "code" / "claude-config", + config_folder=config, home=home, model_catalog=claude / "cache" / "model-catalog", - models_file=claude / "loop-claude-models.json", + models_file=config / "models.json", + state_folder=state_folder(env, home), ) diff --git a/bin/loop_state/test_paths.py b/bin/loop_state/test_paths.py index f40882f3..192995a3 100644 --- a/bin/loop_state/test_paths.py +++ b/bin/loop_state/test_paths.py @@ -4,7 +4,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from loop_state.paths import RELEASE_ROOT, with_release_tools +from loop_state.paths import config_folder, paths_from, RELEASE_ROOT, state_folder, with_release_tools, without_xdg_folders TOOLS = str(RELEASE_ROOT / "bin") @@ -20,5 +20,33 @@ class WithReleaseTools(unittest.TestCase): self.assertEqual(with_release_tools({}), {"PATH": TOOLS}) +HOME = pathlib.Path("/home/me") + + +class SetupFolders(unittest.TestCase): + def test_both_lie_under_the_home_folder_where_no_xdg_variable_is_set(self): + self.assertEqual(config_folder({}, HOME), HOME / ".config" / "build-release") + self.assertEqual(state_folder({}, HOME), HOME / ".local" / "state" / "build-release") + + def test_each_lies_under_the_folder_its_xdg_variable_names(self): + env = {"XDG_CONFIG_HOME": "/x/config", "XDG_STATE_HOME": "/x/state"} + self.assertEqual(config_folder(env, HOME), pathlib.Path("/x/config/build-release")) + self.assertEqual(state_folder(env, HOME), pathlib.Path("/x/state/build-release")) + + def test_an_xdg_variable_that_is_empty_or_relative_is_ignored(self): + for named in ("", "config", "./state"): + with self.subTest(named=named): + env = {"XDG_CONFIG_HOME": named, "XDG_STATE_HOME": named} + self.assertEqual(config_folder(env, HOME), HOME / ".config" / "build-release") + self.assertEqual(state_folder(env, HOME), HOME / ".local" / "state" / "build-release") + + def test_the_models_file_is_in_the_config_folder(self): + found = paths_from(HOME, {"XDG_CONFIG_HOME": "/x/config", "XDG_STATE_HOME": "/x/state"}) + self.assertEqual((found.config_folder, found.models_file, found.state_folder), (pathlib.Path("/x/config/build-release"), pathlib.Path("/x/config/build-release/models.json"), pathlib.Path("/x/state/build-release"))) + + def test_an_environment_without_the_xdg_folders_keeps_every_other_variable(self): + self.assertEqual(without_xdg_folders({"HOME": "/h", "XDG_CONFIG_HOME": "/c", "XDG_STATE_HOME": "/s", "XDG_DATA_HOME": "/d"}), {"HOME": "/h", "XDG_DATA_HOME": "/d"}) + + if __name__ == "__main__": unittest.main() diff --git a/bin/machine_load/test_machine_load.py b/bin/machine_load/test_machine_load.py index d79b2568..be18acd4 100644 --- a/bin/machine_load/test_machine_load.py +++ b/bin/machine_load/test_machine_load.py @@ -50,8 +50,8 @@ class SlotShare(unittest.TestCase): class SlotFolder(unittest.TestCase): def test_every_session_shares_the_slots_under_the_users_state_folder(self): - self.assertEqual(slots.slot_folder({}, pathlib.Path.home()), pathlib.Path.home() / ".local" / "state" / "run-heavy") - self.assertEqual(slots.slot_folder({"XDG_STATE_HOME": "/s"}, pathlib.Path.home()), pathlib.Path("/s/run-heavy")) + self.assertEqual(slots.slot_folder({}, pathlib.Path.home()), pathlib.Path.home() / ".local" / "state" / "build-release" / "run-heavy") + self.assertEqual(slots.slot_folder({"XDG_STATE_HOME": "/s"}, pathlib.Path.home()), pathlib.Path("/s/build-release/run-heavy")) class TakenSlot(unittest.TestCase): diff --git a/bin/model_routing/ladder_file.py b/bin/model_routing/ladder_file.py index c9caeeb4..b3579401 100644 --- a/bin/model_routing/ladder_file.py +++ b/bin/model_routing/ladder_file.py @@ -1,5 +1,6 @@ """Read a routing ladder from its JSON file: the one this setup ships, or a project's own, kept in its config's folder. docs/decisions.md → `routing: one ladder of (model, effort) rungs`.""" import json +from collections.abc import Mapping import pathlib import re @@ -17,9 +18,9 @@ MODEL = re.compile(r"[^\s-]+(-[^\s-]+)+") SHAPE = f'a JSON list of rungs, least competent first, each as {{"model": "claude-opus-5-5", "effort": "medium"}}: a model\'s full name, one model for each family such as opus, and an effort of {", ".join(EFFORTS[:-1])} or {EFFORTS[-1]}' -def project_ladder_file(directory: str | None, home: pathlib.Path, shipped: pathlib.Path = SHIPPED) -> pathlib.Path | Failure: +def project_ladder_file(directory: str | None, home: pathlib.Path, env: Mapping[str, str], shipped: pathlib.Path = SHIPPED) -> pathlib.Path | Failure: """The file that holds the ladder of the project whose checkout holds directory, else the current directory: the file NAME in its config's folder under home, or shipped where that folder holds none. Also shipped where no config names a checkout there, or git fails there. A Failure where the project's config is faulty or cannot be read, since its folder may hold the ladder.""" - config = located(directory, home) + config = located(directory, home, env) if isinstance(config, Unnamed): return shipped if isinstance(config, Failure): @@ -28,9 +29,9 @@ def project_ladder_file(directory: str | None, home: pathlib.Path, shipped: path return own if own.exists() else shipped -def project_ladder(directory: str | None, home: pathlib.Path, shipped: pathlib.Path = SHIPPED) -> Ladder | Failure: +def project_ladder(directory: str | None, home: pathlib.Path, env: Mapping[str, str], shipped: pathlib.Path = SHIPPED) -> Ladder | Failure: """The ladder project_ladder_file's file holds. A Failure where that file holds a fault too: the shipped ladder never stands in for a project's own, since work routed on it could run on a model the project cannot reach.""" - file = project_ladder_file(directory, home, shipped) + file = project_ladder_file(directory, home, env, shipped) return file if isinstance(file, Failure) else read_ladder(file) diff --git a/bin/model_routing/test_ladder_file.py b/bin/model_routing/test_ladder_file.py index 73ffef27..338e20e8 100644 --- a/bin/model_routing/test_ladder_file.py +++ b/bin/model_routing/test_ladder_file.py @@ -106,41 +106,41 @@ class ProjectLadder(LadderCase): def test_a_project_runs_on_the_ladder_its_configs_folder_holds_from_a_worktree_too(self): checkout = self.checkout() (write_config(self.home, checkout) / NAME).write_text(FABLE_ONLY, encoding="utf-8") - self.assertEqual(project_ladder(str(checkout), self.home, self.shipped), FABLE_LADDER) + self.assertEqual(project_ladder(str(checkout), self.home, {}, self.shipped), FABLE_LADDER) worktree = self.home / "code" / "acme-item-7" self.git(checkout, "worktree", "add", "--quiet", str(worktree), "-b", "item-7") - self.assertEqual(project_ladder(str(worktree), self.home, self.shipped), FABLE_LADDER) + self.assertEqual(project_ladder(str(worktree), self.home, {}, self.shipped), FABLE_LADDER) def test_names_the_file_it_reads_the_projects_own_or_else_the_shipped_one(self): checkout = self.checkout() folder = write_config(self.home, checkout) - self.assertEqual(project_ladder_file(str(checkout), self.home, self.shipped), self.shipped) + self.assertEqual(project_ladder_file(str(checkout), self.home, {}, self.shipped), self.shipped) (folder / NAME).write_text(FABLE_ONLY, encoding="utf-8") - self.assertEqual(project_ladder_file(str(checkout), self.home, self.shipped), folder / NAME) - self.assertEqual(project_ladder_file(str(self.home), self.home), SHIPPED, "outside a checkout, the ladder this setup ships") + self.assertEqual(project_ladder_file(str(checkout), self.home, {}, self.shipped), folder / NAME) + self.assertEqual(project_ladder_file(str(self.home), self.home, {}), SHIPPED, "outside a checkout, the ladder this setup ships") def test_another_projects_ladder_is_not_read(self): checkout, other = self.checkout(), self.checkout("other") write_config(self.home, checkout) (write_config(self.home, other) / NAME).write_text(FABLE_ONLY, encoding="utf-8") - self.assertEqual(project_ladder(str(checkout), self.home, self.shipped), Ladder((Rung("claude-opus-5-5", "medium"),))) + self.assertEqual(project_ladder(str(checkout), self.home, {}, self.shipped), Ladder((Rung("claude-opus-5-5", "medium"),))) def test_a_checkout_no_config_names_and_a_folder_outside_any_checkout_run_on_the_shipped_ladder(self): shipped = Ladder((Rung("claude-opus-5-5", "medium"),)) - self.assertEqual(project_ladder(str(self.checkout()), self.home, self.shipped), shipped) - self.assertEqual(project_ladder(str(self.home), self.home, self.shipped), shipped) + self.assertEqual(project_ladder(str(self.checkout()), self.home, {}, self.shipped), shipped) + self.assertEqual(project_ladder(str(self.home), self.home, {}, self.shipped), shipped) def test_a_faulty_ladder_of_the_projects_own_fails_and_the_shipped_one_does_not_stand_in(self): checkout = self.checkout() own = write_config(self.home, checkout) / NAME own.write_text("[]", encoding="utf-8") - self.assertEqual(project_ladder(str(checkout), self.home, self.shipped).reason.split(". ")[0], f"{own}: it holds no list of rungs") + self.assertEqual(project_ladder(str(checkout), self.home, {}, self.shipped).reason.split(". ")[0], f"{own}: it holds no list of rungs") def test_a_faulty_config_fails_since_its_folder_may_hold_the_ladder(self): checkout = self.checkout() config = write_config(self.home, checkout) / "config.toml" config.write_text(config.read_text(encoding="utf-8") + 'readme = "checkout:README.md"\n', encoding="utf-8") - self.assertIn("`readme` is not a setting", project_ladder(str(checkout), self.home, self.shipped).reason) + self.assertIn("`readme` is not a setting", project_ladder(str(checkout), self.home, {}, self.shipped).reason) if __name__ == "__main__": diff --git a/bin/notifier/main.py b/bin/notifier/main.py index 8501a5ad..daa6eafe 100644 --- a/bin/notifier/main.py +++ b/bin/notifier/main.py @@ -4,9 +4,9 @@ usage: notify [<message>] Sends <message>, or else stdin, through the notifier that a project's config names, from the bot to the recipient that the project's env file names. Run it inside the project's checkout, or a worktree of it. -The project's config, ~/.claude-projects/<key>/config.toml, sets `notifier` to "mattermost" or "slack" +The project's config, ~/.config/build-release/<key>/config.toml, sets `notifier` to "mattermost" or "slack" and `env-file` to a path outside the checkout and the config's folder, such as -"~/.claude-projects/<key>.env". The env file holds the notifier's KEY=value lines, and only its owner +"~/.config/build-release/<key>.env". The env file holds the notifier's KEY=value lines, and only its owner may read it, since it holds the bot's token. For mattermost: MATTERMOST_URL=https://chat.example diff --git a/bin/notifier/notify.py b/bin/notifier/notify.py index 37413764..edd3d5db 100644 --- a/bin/notifier/notify.py +++ b/bin/notifier/notify.py @@ -43,18 +43,18 @@ def sender_of(project: ProjectConfig, backends: typing.Mapping[Notifier, Backend return lambda message: backend.send(config, message, backend.http) -def notify(text: str, directory: str | None, home: pathlib.Path, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Failure | None: +def notify(text: str, directory: str | None, home: pathlib.Path, env: typing.Mapping[str, str], backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Failure | None: """Sends text through the notifier of the project whose checkout holds directory. The DM is skipped where the config names no notifier, since the project hasn't asked for DMs. It is skipped too where no config can be read: build-release has stopped with that reason, and without a config there is no notifier to ask.""" - project = located(directory, home) + project = located(directory, home, env) if isinstance(project, Failure) or project.notifier is None: return None sender = sender_of(project, backends) return sender if isinstance(sender, Failure) else sender(text) -def sender_in(directory: str | None, home: pathlib.Path, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Sender | Failure: +def sender_in(directory: str | None, home: pathlib.Path, env: typing.Mapping[str, str], backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Sender | Failure: """sender_of the project whose checkout holds directory.""" - project = located(directory, home) + project = located(directory, home, env) return project if isinstance(project, Failure) else sender_of(project, backends) diff --git a/bin/notifier/test_notifier.py b/bin/notifier/test_notifier.py index a92cd46e..2cb4ade8 100644 --- a/bin/notifier/test_notifier.py +++ b/bin/notifier/test_notifier.py @@ -47,10 +47,10 @@ class Project(unittest.TestCase): self.folder = configured(self, self.checkout, home=self.home) def name_notifier(self, notifier: str | None, keys: str | None = None) -> pathlib.Path: - """Makes the config name ~/.claude-projects/proj.env as its env file, and the notifier where there is one; the file holds keys where that is not None.""" + """Makes the config name ~/.config/build-release/proj.env as its env file, and the notifier where there is one; the file holds keys where that is not None.""" with (self.folder / "config.toml").open("a") as config: - config.write('env-file = "~/.claude-projects/proj.env"\n' + (f'notifier = "{notifier}"\n' if notifier else "")) - path = self.home / ".claude-projects" / "proj.env" + config.write('env-file = "~/.config/build-release/proj.env"\n' + (f'notifier = "{notifier}"\n' if notifier else "")) + path = self.home / ".config/build-release" / "proj.env" if keys is not None: path.write_text(keys) path.chmod(0o600) @@ -61,13 +61,13 @@ class Notify(Project): def test_sends_through_mattermost_where_the_config_names_it(self): self.name_notifier("mattermost", MATTERMOST_KEYS) server = mattermost() - self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("mattermost", server))) + self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, {}, through("mattermost", server))) self.assertEqual(server.requests[-1], MATTERMOST_POST) def test_sends_through_slack_where_the_config_names_it(self): self.name_notifier("slack", SLACK_KEYS) slack = Slack({"ok": True}) - self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("slack", slack))) + self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, {}, through("slack", slack))) self.assertEqual(slack.requests, [SLACK_POST]) def test_build_releases_dm_goes_through_the_notifier_for_the_project_holding_the_current_directory(self): @@ -87,7 +87,7 @@ class Notify(Project): def test_skips_the_notice_for_a_project_that_names_no_notifier_even_where_its_env_file_holds_the_keys(self): self.name_notifier(None, MATTERMOST_KEYS) server = mattermost() - self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("mattermost", server))) + self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, {}, through("mattermost", server))) self.assertEqual(server.requests, []) def test_skips_the_notice_where_no_config_names_the_checkout_since_build_release_stops_on_that_itself(self): @@ -95,32 +95,32 @@ class Notify(Project): other.mkdir() subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env()) server = mattermost() - self.assertIsNone(notify.notify("Which one?", str(other), self.home, through("mattermost", server))) + self.assertIsNone(notify.notify("Which one?", str(other), self.home, {}, through("mattermost", server))) self.assertEqual(server.requests, []) def test_fails_naming_the_file_or_the_key_where_the_env_file_is_missing_or_wrong(self): path = self.name_notifier("slack") - self.assertEqual(notify.notify("hi", str(self.checkout), self.home, through("slack", Slack({"ok": True}))), Failure(f"{path} does not exist; it needs SLACK_TOKEN and SLACK_RECIPIENT")) + self.assertEqual(notify.notify("hi", str(self.checkout), self.home, {}, through("slack", Slack({"ok": True}))), Failure(f"{path} does not exist; it needs SLACK_TOKEN and SLACK_RECIPIENT")) path.write_text("SLACK_TOKEN=xoxb-secret\n") path.chmod(0o600) - self.assertEqual(notify.notify("hi", str(self.checkout), self.home, through("slack", Slack({"ok": True}))), Failure(f"{path} lacks SLACK_RECIPIENT")) + self.assertEqual(notify.notify("hi", str(self.checkout), self.home, {}, through("slack", Slack({"ok": True}))), Failure(f"{path} lacks SLACK_RECIPIENT")) def test_the_failure_for_an_unreachable_server_names_the_server_and_not_the_token(self): self.name_notifier("mattermost", MATTERMOST_KEYS.replace("https://chat.example", "https://127.0.0.1:1")) - failed = notify.notify("Which one?", str(self.checkout), self.home, notify.BACKENDS) + failed = notify.notify("Which one?", str(self.checkout), self.home, {}, notify.BACKENDS) assert isinstance(failed, Failure), failed self.assertIn("cannot reach https://127.0.0.1:1", failed.reason) self.assertNotIn("secret-token", failed.reason) def test_sender_in_fails_for_an_env_file_that_no_notifier_reads(self): self.name_notifier(None, MATTERMOST_KEYS) - failed = notify.sender_in(str(self.checkout), self.home, notify.BACKENDS) + failed = notify.sender_in(str(self.checkout), self.home, {}, notify.BACKENDS) assert isinstance(failed, Failure), failed self.assertIn("sets no `notifier`", failed.reason) def test_sender_of_names_the_missing_env_file_for_a_config_built_by_hand_with_a_notifier_and_none(self): self.name_notifier("slack", SLACK_KEYS) - project = located(str(self.checkout), self.home) + project = located(str(self.checkout), self.home, {}) assert not isinstance(project, Failure), project failed = notify.sender_of(dataclasses.replace(project, env_file=None), notify.BACKENDS) self.assertEqual(failed, Failure(f"{self.folder / 'config.toml'} sets `notifier` but no `env-file`, the file that holds its credentials")) @@ -129,10 +129,10 @@ class Notify(Project): other = self.home / "code" / "other" other.mkdir() subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env()) - self.assertIsInstance(notify.sender_in(str(other), self.home, notify.BACKENDS), Failure) + self.assertIsInstance(notify.sender_in(str(other), self.home, {}, notify.BACKENDS), Failure) def test_sender_in_names_the_settings_to_add_where_the_config_names_no_notifier(self): - failed = notify.sender_in(str(self.checkout), self.home, notify.BACKENDS) + failed = notify.sender_in(str(self.checkout), self.home, {}, notify.BACKENDS) assert isinstance(failed, Failure), failed self.assertEqual(failed.reason, f"{self.folder / 'config.toml'} sets no `notifier`; set `notifier` to mattermost or slack, and `env-file` to the file that holds that service's keys (mattermost: MATTERMOST_URL, MATTERMOST_TOKEN, MATTERMOST_RECIPIENT; slack: SLACK_TOKEN, SLACK_RECIPIENT)") diff --git a/bin/notify b/bin/notify index bb36d2df..aa3b441c 100755 --- a/bin/notify +++ b/bin/notify @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import os import pathlib import sys @@ -6,4 +7,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from notifier import main, notify -sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: notify.sender_in(None, pathlib.Path.home(), notify.BACKENDS), sys.stderr)) +sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: notify.sender_in(None, pathlib.Path.home(), os.environ, notify.BACKENDS), sys.stderr)) diff --git a/bin/plan/test_ranking.py b/bin/plan/test_ranking.py index 46fc7628..a9248b77 100644 --- a/bin/plan/test_ranking.py +++ b/bin/plan/test_ranking.py @@ -293,7 +293,7 @@ class CodeHealth(unittest.TestCase): pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00")) with contextlib.redirect_stderr(io.StringIO()): - ranked = file_plan(located(temp, folder.parents[1]), todo).rank() + ranked = file_plan(located(temp, folder.parents[2], {}), todo).rank() self.assertIsInstance(ranked, ranking.Ranked) self.assertEqual(ranked.under_bar, []) self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) @@ -310,10 +310,10 @@ class CodeHealth(unittest.TestCase): pathlib.Path(temp, "docs").mkdir() pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="6.50")) with contextlib.redirect_stderr(io.StringIO()): - ranked = file_plan(located(temp, folder.parents[1]), todo).rank() + ranked = file_plan(located(temp, folder.parents[2], {}), todo).rank() self.assertIsInstance(ranked, ranking.Ranked) self.assertIn("| code health by 1 | 25.4 |", todo.read_text()) - self.assertEqual(file_plan(located(temp, folder.parents[1]), todo).check(), []) + self.assertEqual(file_plan(located(temp, folder.parents[2], {}), todo).check(), []) class Risk(unittest.TestCase): diff --git a/bin/project_config/doubles.py b/bin/project_config/doubles.py index 2784acdc..26122dfb 100644 --- a/bin/project_config/doubles.py +++ b/bin/project_config/doubles.py @@ -4,7 +4,7 @@ import subprocess import tempfile import unittest -from loop_state.paths import CONFIG_FOLDER +from loop_state.paths import config_folder from test_env import isolated_env CLIENT = """checkout = "~/code/acme-billing" @@ -26,7 +26,7 @@ JIRA_SCORING = 'jira-score-formula = "100 * V / (2**S + 8)"\njira-score-bar = 1\ def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "checkout:README.md") -> pathlib.Path: """A config under home that names checkout, every setting inside it but goals-and-audience; for the tests of each tool that reads the config.""" - folder = home / CONFIG_FOLDER / checkout.name + folder = config_folder({}, home) / checkout.name folder.mkdir(parents=True, exist_ok=True) (folder / "config.toml").write_text(CLIENT.replace('"~/code/acme-billing"', f'"{checkout}"').replace('"folder:', '"checkout:').replace('"checkout:goals.md"', f'"{goals}"'), encoding="utf-8") return folder diff --git a/bin/project_config/main.py b/bin/project_config/main.py index f536f777..b8ec797b 100644 --- a/bin/project_config/main.py +++ b/bin/project_config/main.py @@ -3,10 +3,11 @@ usage: project-config [<setting>] Run inside a checkout, or a worktree of one. It finds the config that names the checkout, -~/.claude-projects/<key>/config.toml, and prints each setting and its absolute path, as in +~/.config/build-release/<key>/config.toml, and prints each setting and its absolute path, as in `plan: /home/me/code/acme/todo.md`. Given a setting, it prints only that setting's path. +Where XDG_CONFIG_HOME is set, the configs are in $XDG_CONFIG_HOME/build-release/ instead. -`~/.claude-projects/do-epic/` holds do-epic's machine-wide settings, not a project's. It needs no `checkout`, +`~/.config/build-release/do-epic/` holds do-epic's machine-wide settings, not a project's. It needs no `checkout`, and project-config doesn't read anything from it, so no project may use `do-epic` as its key. The config is TOML. `checkout` names the project's main checkout, and every setting in the example below is a path: @@ -74,7 +75,7 @@ rule-hook ranks a plan kept as a file before tool calls, and a read from Conflue `env-file` is an optional setting: the file of KEY=value credentials the project's tools read, a path that starts with / or ~/ and lies outside the checkout and the config's folder, such as -"~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and +"~/.config/build-release/acme-billing.env". Where it is left out, the project has no credentials file, and a tool that needs one fails naming the setting. It is printed with the others only where it is set. `touch-predictions` is an optional setting, a path spelt as the others are, never a page: the record @@ -179,6 +180,8 @@ one of those two without a `plan` in Jira, sets the formula to one that doesn't but a number, sets `readability-floor` to anything but a number from 1 to 10, sets `parallel-chunks` to anything but a whole number of 1 or more, or sets `jira-finding-type` to anything but a name or without a `plan` in Jira, and where `bench-tasks`, `coding-conventions`, `env-file`, `epic-branch`, `jira-finish-transition`, `jira-finish-status`, `notifier`, `review-request-comment` or `touch-predictions` is asked for and not set. No path setting has a default. """ +from collections.abc import Mapping +import os import pathlib import sys @@ -195,7 +198,7 @@ def main(argv: list[str]) -> int: if len(argv) > 1 or (argv and argv[0] not in (*SETTINGS, *OPTIONAL)): print(f"usage: project-config [<setting>], where <setting> is one of {', '.join((*SETTINGS, *OPTIONAL))}", file=sys.stderr) return 1 - config = located(None, pathlib.Path.home()) + config = located(None, pathlib.Path.home(), os.environ) if isinstance(config, Failure): print(config.reason, file=sys.stderr) return 1 @@ -216,7 +219,7 @@ def main(argv: list[str]) -> int: return 0 -def located(directory: str | None, home: pathlib.Path, run: Git = git) -> ProjectConfig | Failure: +def located(directory: str | None, home: pathlib.Path, env: Mapping[str, str], run: Git = git) -> ProjectConfig | Failure: """The config under home of the checkout that holds directory, else the current directory.""" found = run("rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir", cwd=directory) if isinstance(found, Failure): @@ -224,12 +227,12 @@ def located(directory: str | None, home: pathlib.Path, run: Git = git) -> Projec if len(lines := found.splitlines()) != 2: return Failure(f"git rev-parse printed {found!r}, not a checkout's top folder and git directory on two lines") # The common dir is the main checkout's .git, whichever worktree runs this. - return load(pathlib.Path(lines[0]), pathlib.Path(lines[1]).parent, home) + return load(pathlib.Path(lines[0]), pathlib.Path(lines[1]).parent, home, env) -def title_templates(directory: str | None, home: pathlib.Path, run: Git = git) -> templates.Titles | Failure: +def title_templates(directory: str | None, home: pathlib.Path, env: Mapping[str, str], run: Git = git) -> templates.Titles | Failure: """The title templates of the project whose checkout holds directory, else the current directory. Bare summaries where no config names a checkout there, as in a third party's clone, so every title is read as it stands. A Failure where a config is faulty or cannot be read: read bare, a templated project's round titles would count for nothing.""" - config = located(directory, home, run) + config = located(directory, home, env, run) if isinstance(config, Unnamed): return templates.BARE return config if isinstance(config, Failure) else config.titles @@ -237,5 +240,5 @@ def title_templates(directory: str | None, home: pathlib.Path, run: Git = git) - def project() -> ProjectConfig | Failure: """The config of the project whose checkout holds the current directory, under the user's home.""" - return located(None, pathlib.Path.home()) + return located(None, pathlib.Path.home(), os.environ) diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index 9dc96fcf..db9ea9ed 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -1,22 +1,22 @@ -"""A project's settings, read from the one config that names its checkout: `~/.claude-projects/<key>/config.toml`. +"""A project's settings, read from the one config that names its checkout: `<key>/config.toml` in the config folder, `~/.config/build-release/` unless `XDG_CONFIG_HOME` is set. No path setting has a default, so that a client's project never runs on another project's files: a missing config or setting is a Failure that names it.""" import dataclasses import decimal +from collections.abc import Mapping import math import pathlib import re import tomllib import typing -from loop_state.paths import CONFIG_FOLDER +from loop_state.paths import config_folder from failure import Failure from plan.formula import parse_formula from plan.todo_table import SHAPE from project_config import templates from plan.ranking import variables -PROJECTS = CONFIG_FOLDER CONFIG = "config.toml" # The key of do-epic's machine-wide settings: the folder's config.toml has no `checkout`, so no project may use the key. DO_EPIC = "do-epic" @@ -133,7 +133,7 @@ class Unnamed(Failure): @dataclasses.dataclass(frozen=True) class ProjectConfig: - """folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except three kinds that pages or epics hold instead: `plan` and `goals-and-audience` where they are kept in Jira, and a record kept on a Confluence page.""" + """folder is `<key>` in the config folder, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except three kinds that pages or epics hold instead: `plan` and `goals-and-audience` where they are kept in Jira, and a record kept on a Confluence page.""" key: str folder: pathlib.Path top: pathlib.Path @@ -203,13 +203,13 @@ class ProjectConfig: return path.relative_to(self.top).as_posix() if path.is_relative_to(self.top) else None -def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure: +def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path, env: Mapping[str, str]) -> ProjectConfig | Failure: """The config that names main, the project's main checkout. top is the worktree that asks, and main itself outside a worktree. A `checkout:` path lands in top. A config that cannot be read fails every project, since it may be the one that names main.""" named: list[tuple[pathlib.Path, dict[str, object]]] = [] - for file in configs(home): + for file in configs(home, env): config = read(file, home) if isinstance(config, Failure): return config @@ -217,7 +217,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo if config[0].resolve() == main.resolve(): named.append((file, config[1])) if not named: - return Unnamed(f"no config names the checkout {main}: write ~/{PROJECTS}/<key>/{CONFIG}, as `project-config --help` shows") + return Unnamed(f"no config names the checkout {main}: write {config_folder(env, home)}/<key>/{CONFIG}, as `project-config --help` shows") if len(named) > 1: return Failure(f"{' and '.join(str(file) for file, _ in named)} each name the checkout {main}; only one config may") file, values = named[0] @@ -413,20 +413,20 @@ def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool: return any(path.resolve().is_relative_to(place.resolve()) for place in places) -def held(folder: pathlib.Path, home: pathlib.Path) -> ProjectConfig | Failure | None: +def held(folder: pathlib.Path, home: pathlib.Path, env: Mapping[str, str]) -> ProjectConfig | Failure | None: """The config in folder, read as its project's main checkout reads it; None where folder is not a config's folder under home.""" # Matched on resolved paths, as git names a folder, so a config's folder reached through a symlink is still found. - file = next((file for file in configs(home) if file.parent.resolve() == folder.resolve()), None) + file = next((file for file in configs(home, env) if file.parent.resolve() == folder.resolve()), None) if file is None: return None config = read(file, home) - return config if isinstance(config, Failure) else load(config[0], config[0], home) + return config if isinstance(config, Failure) else load(config[0], config[0], home, env) -def by_name(name: str, home: pathlib.Path) -> ProjectConfig | Failure | None: +def by_name(name: str, home: pathlib.Path, env: Mapping[str, str]) -> ProjectConfig | Failure | None: """The config of the project whose main checkout is a folder called name, though that folder may not exist yet, loaded as `held` does; None where no config names one. A config that cannot be read fails every name, since it may be the one asked for.""" files = [] - for file in configs(home): + for file in configs(home, env): config = read(file, home) if isinstance(config, Failure): return config @@ -434,17 +434,17 @@ def by_name(name: str, home: pathlib.Path) -> ProjectConfig | Failure | None: files.append(file) if len(files) > 1: return Failure(f"{' and '.join(str(file) for file in files)} each name a checkout called {name}; only one config may") - return held(files[0].parent, home) if files else None + return held(files[0].parent, home, env) if files else None -def configs(home: pathlib.Path) -> list[pathlib.Path]: - """Every project's config file under home, in key order. do-epic's machine-wide config is not a project's.""" - return sorted(file for file in (home / PROJECTS).glob(f"*/{CONFIG}") if file.parent.name != DO_EPIC) +def configs(home: pathlib.Path, env: Mapping[str, str]) -> list[pathlib.Path]: + """Every project's config file in the config folder, in key order. do-epic's machine-wide config is not a project's.""" + return sorted(file for file in config_folder(env, home).glob(f"*/{CONFIG}") if file.parent.name != DO_EPIC) -def env_files(home: pathlib.Path) -> list[pathlib.Path]: +def env_files(home: pathlib.Path, env: Mapping[str, str]) -> list[pathlib.Path]: """Every config's env-file, do-epic's included. Each is read without the checks load makes, so a config that fails them still keeps its credentials guarded. A config that can't be read doesn't name one.""" - values = [parsed(file) for file in (*configs(home), home / PROJECTS / DO_EPIC / CONFIG)] + values = [parsed(file) for file in (*configs(home, env), config_folder(env, home) / DO_EPIC / CONFIG)] return [path for found in values if not isinstance(found, Failure) and (path := anywhere(found.get(ENV_FILE), home))] diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index ac5e0c4d..93a0d63f 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -29,7 +29,7 @@ class ConfigCase(unittest.TestCase): self.checkout.mkdir(parents=True) def write(self, key: str, text: str) -> pathlib.Path: - folder = self.home / ".claude-projects" / key + folder = self.home / ".config/build-release" / key folder.mkdir(parents=True) (folder / "config.toml").write_text(text, encoding="utf-8") return folder @@ -37,14 +37,14 @@ class ConfigCase(unittest.TestCase): class LoadTest(ConfigCase): def failure(self, top: pathlib.Path | None = None) -> str: - found = load(top or self.checkout, self.checkout, self.home) + found = load(top or self.checkout, self.checkout, self.home, {}) assert isinstance(found, Failure), found return found.reason def test_resolves_each_setting_by_its_prefix(self) -> None: folder = self.write("acme", CLIENT) self.write("other", CLIENT.replace("acme-billing", "other")) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual((found.key, found.folder), ("acme", folder)) self.assertEqual(found.paths["plan"], folder / "todo.md") @@ -57,13 +57,13 @@ class LoadTest(ConfigCase): def test_the_do_epic_folder_is_no_projects_config_so_it_needs_no_checkout(self) -> None: self.write("do-epic", 'jira-url = "https://acme.atlassian.net"\n') self.write("acme", CLIENT) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.key, "acme") def test_a_plan_spelt_as_a_jira_epic_is_no_path(self) -> None: self.write("acme", JIRA_CLIENT) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.epic, Epic("https://acme.atlassian.net", "ABC-12")) self.assertEqual((found.plan_file, found.tracked("plan"), found.plan_label), (None, None, JIRA_PLAN)) @@ -73,7 +73,7 @@ class LoadTest(ConfigCase): def test_a_plan_kept_as_a_file_has_no_epic(self) -> None: folder = self.write("acme", CLIENT) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual((found.epic, found.plan_file, found.plan_label, found.places["plan"]), (None, folder / "todo.md", str(folder / "todo.md"), str(folder / "todo.md"))) @@ -88,12 +88,12 @@ class LoadTest(ConfigCase): reason = self.failure() self.assertIn(f"`plan` is {spelled!r}, not ", reason) self.assertIn("jira:https://<site>/browse/<epic's key>", reason) - for config in (self.home / ".claude-projects").glob("*/config.toml"): + for config in (self.home / ".config/build-release").glob("*/config.toml"): config.unlink() def test_goals_and_audience_spelt_as_a_jira_epic_is_no_path(self) -> None: self.write("acme", JIRA_CLIENT.replace("folder:goals.md", "jira:https://acme.atlassian.net/browse/ABC-7")) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.goals_epic, Epic("https://acme.atlassian.net", "ABC-7")) self.assertEqual(found.places["goals-and-audience"], "jira:https://acme.atlassian.net/browse/ABC-7") @@ -102,7 +102,7 @@ class LoadTest(ConfigCase): def test_goals_and_the_plan_may_name_the_same_epic(self) -> None: self.write("acme", JIRA_CLIENT.replace("folder:goals.md", JIRA_PLAN)) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.goals_epic, found.epic) @@ -112,7 +112,7 @@ class LoadTest(ConfigCase): def test_goals_kept_as_a_file_have_no_epic(self) -> None: folder = self.write("acme", CLIENT) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual((found.goals_epic, found.places["goals-and-audience"]), (None, str(folder / "goals.md"))) @@ -129,7 +129,7 @@ class LoadTest(ConfigCase): def test_a_record_spelt_as_a_confluence_page_is_no_path_and_prints_as_written(self) -> None: self.write("acme", JIRA_CLIENT.replace("folder:docs/decisions.md", DECISIONS_PAGE)) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.pages, {"decisions": Page("https://acme.atlassian.net", "2293761", DECISIONS_PAGE)}) self.assertEqual(found.places["decisions"], DECISIONS_PAGE) @@ -140,11 +140,11 @@ class LoadTest(ConfigCase): def test_a_confluence_page_may_leave_out_its_title(self) -> None: for spelled in ("confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761", "confluence:https://acme.atlassian.net/wiki/spaces/~5b1e/pages/2293761/R%C3%A5d+och+beslut"): with self.subTest(spelled): - for config in (self.home / ".claude-projects").glob("*/config.toml"): + for config in (self.home / ".config/build-release").glob("*/config.toml"): config.unlink() config.parent.rmdir() self.write("acme", CLIENT.replace("checkout:CHANGELOG.md", spelled) + 'env-file = "~/acme.env"\n') - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.pages["changelog"].page_id, "2293761") @@ -165,7 +165,7 @@ class LoadTest(ConfigCase): reason = self.failure() self.assertIn(f"`decisions` is {spelled!r}, not ", reason) self.assertIn("confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>", reason) - for config in (self.home / ".claude-projects").glob("*/config.toml"): + for config in (self.home / ".config/build-release").glob("*/config.toml"): config.unlink() def test_only_a_record_may_name_a_confluence_page(self) -> None: @@ -177,14 +177,14 @@ class LoadTest(ConfigCase): def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None: self.write("acme", CLIENT) worktree = self.home / "code" / "acme-billing-item-3" - found = load(worktree, self.checkout, self.home) + found = load(worktree, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.paths["changelog"], worktree / "CHANGELOG.md") def test_names_a_file_in_the_checkout_as_git_does_and_none_outside_it(self) -> None: self.write("acme", CLIENT.replace("folder:docs/decisions.md", "checkout:project/decisions.md")) worktree = self.home / "code" / "acme-billing-item-3" - found = load(worktree, self.checkout, self.home) + found = load(worktree, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.tracked("changelog"), "CHANGELOG.md") self.assertEqual(found.tracked("decisions"), "project/decisions.md") @@ -192,7 +192,7 @@ class LoadTest(ConfigCase): def test_an_absolute_checkout_and_path_are_taken_as_written(self) -> None: self.write("acme", CLIENT.replace("~/code/acme-billing", str(self.checkout)).replace("~/.claude/principles", "/srv/principles")) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.paths["principles"], pathlib.Path("/srv/principles")) @@ -201,7 +201,7 @@ class LoadTest(ConfigCase): (self.home / "work").symlink_to(self.home / "code") for case, main in {"a symlink": self.home / "work" / "acme-billing", "dots": self.home / "code" / "other" / ".." / "acme-billing"}.items(): with self.subTest(case=case): - self.assertIsInstance(load(main, main, self.home), ProjectConfig) + self.assertIsInstance(load(main, main, self.home, {}), ProjectConfig) def test_no_config_fails_naming_the_checkout_and_the_file_to_write(self) -> None: for write_other in (False, True): @@ -210,10 +210,10 @@ class LoadTest(ConfigCase): self.write("other", CLIENT.replace("acme-billing", "other")) reason = self.failure() self.assertIn(str(self.checkout), reason) - self.assertIn("~/.claude-projects/<key>/config.toml", reason) + self.assertIn(f"{self.home}/.config/build-release/<key>/config.toml", reason) def test_a_folder_that_is_no_checkout_fails_as_unnamed_with_gits_reason(self) -> None: - outside = located(str(self.checkout), self.home) + outside = located(str(self.checkout), self.home, {}) self.assertIsInstance(outside, Unnamed) self.assertIn("not a git repository", outside.reason) @@ -249,77 +249,77 @@ class LoadTest(ConfigCase): def test_env_file_is_the_one_optional_setting_and_names_a_file_outside_the_checkout_and_the_configs_folder(self) -> None: self.write("acme", CLIENT) - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertIsNone(found.env_file, "a project that sets none has asked for no credentials, and never falls back to another project's") - for case, spelled in {"~/": '"~/.claude-projects/acme.env"', "absolute": f'"{self.home}/.claude-projects/acme.env"'}.items(): + for case, spelled in {"~/": '"~/.config/build-release/acme.env"', "absolute": f'"{self.home}/.config/build-release/acme.env"'}.items(): with self.subTest(case=case): self.write(f"acme-{case[0]}", CLIENT.replace("acme-billing", f"acme-{case[0]}") + f"env-file = {spelled}\n") - named = load(self.home / "code" / f"acme-{case[0]}", self.home / "code" / f"acme-{case[0]}", self.home) + named = load(self.home / "code" / f"acme-{case[0]}", self.home / "code" / f"acme-{case[0]}", self.home, {}) assert isinstance(named, ProjectConfig), named - self.assertEqual(named.env_file, self.home / ".claude-projects" / "acme.env") + self.assertEqual(named.env_file, self.home / ".config/build-release" / "acme.env") def test_the_notifier_is_optional_and_names_mattermost_or_slack_beside_an_env_file(self) -> None: self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertIsNone(left_out.notifier, "a project that names none has asked for no notices") for index, name in enumerate(NOTIFIERS): with self.subTest(name): self.write(f"acme-{index}", CLIENT.replace("acme-billing", f"acme-{index}") + f'env-file = "~/acme.env"\nnotifier = "{name}"\n') - named = load(self.home / "code" / f"acme-{index}", self.home / "code" / f"acme-{index}", self.home) + named = load(self.home / "code" / f"acme-{index}", self.home / "code" / f"acme-{index}", self.home, {}) assert isinstance(named, ProjectConfig), named self.assertEqual(named.notifier, name) def test_the_epic_branch_and_its_review_request_comment_are_optional(self) -> None: self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertEqual((left_out.epic_branch, left_out.review_request_comment), (None, None)) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "epic/{epic}"\nreview-request-comment = "@coderabbitai review"\n') - named = load(self.checkout, self.checkout, self.home) + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "epic/{epic}"\nreview-request-comment = "@coderabbitai review"\n') + named = load(self.checkout, self.checkout, self.home, {}) assert isinstance(named, ProjectConfig), named self.assertEqual((named.epic_branch, named.review_request_comment), ("epic/{epic}", "@coderabbitai review")) def test_an_epic_branch_without_the_epic_or_a_comment_without_an_epic_branch_fails_naming_it(self) -> None: self.write("acme", CLIENT + 'epic-branch = "develop"\n') self.assertIn("`epic-branch` is 'develop', not text with exactly one {epic}", self.failure()) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'review-request-comment = "@coderabbitai review"\n') + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(CLIENT + 'review-request-comment = "@coderabbitai review"\n') self.assertIn("`review-request-comment` is set, so `epic-branch` must be set", self.failure()) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "{epic}"\nreview-request-comment = " "\n') + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "{epic}"\nreview-request-comment = " "\n') self.assertIn("`review-request-comment` is ' ', not one line of text", self.failure()) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "{epic}"\nreview-request-comment = "--help"\n') + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "{epic}"\nreview-request-comment = "--help"\n') self.assertIn("`review-request-comment` is '--help', not one line of text that doesn't start with `-`", self.failure()) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "{epic}"\nreview-request-comment = "@coderabbitai\\nreview"\n') + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(CLIENT + 'epic-branch = "{epic}"\nreview-request-comment = "@coderabbitai\\nreview"\n') self.assertIn("`review-request-comment` is '@coderabbitai\\nreview', not one line of text", self.failure()) def test_a_jira_plan_may_name_the_transition_and_status_that_finish_an_item(self) -> None: self.write("acme", JIRA_CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertIsNone(left_out.jira_finish) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n') - named = load(self.checkout, self.checkout, self.home) + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n') + named = load(self.checkout, self.checkout, self.home, {}) assert isinstance(named, ProjectConfig), named self.assertEqual(named.jira_finish, Finish("Mark as done", "Done")) def test_a_finish_setting_alone_misspelt_or_beside_a_plan_in_a_file_fails_naming_it(self) -> None: self.write("acme", JIRA_CLIENT + 'jira-finish-status = "Done"\n') self.assertIn("`jira-finish-status` is set, so `jira-finish-transition` must be too", self.failure()) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\n') + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\n') self.assertIn("`jira-finish-transition` is set, so `jira-finish-status` must be too", self.failure()) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = 31\njira-finish-status = " "\n') + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = 31\njira-finish-status = " "\n') self.assertIn("`jira-finish-transition` is 31, not the name Jira shows, such as \"Mark as done\"; `jira-finish-status` is ' ', not the name Jira shows, such as \"Done\"", self.failure()) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n') + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n') self.assertIn("`jira-finish-transition` is set, so `plan` must name a Jira epic; `jira-finish-status` is set, so `plan` must name a Jira epic", self.failure()) def test_a_jira_plan_may_name_the_issue_type_it_files_items_as_which_is_task_where_left_out(self) -> None: folder = self.write("acme", JIRA_CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertEqual(left_out.jira_finding_type, "Task") (folder / "config.toml").write_text(JIRA_CLIENT + 'jira-finding-type = "Feature"\n') - named = load(self.checkout, self.checkout, self.home) + named = load(self.checkout, self.checkout, self.home, {}) assert isinstance(named, ProjectConfig), named self.assertEqual(named.jira_finding_type, "Feature") @@ -333,13 +333,13 @@ class LoadTest(ConfigCase): def test_a_jira_plan_holds_the_formula_and_bar_it_scores_by(self) -> None: self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5")) - named = load(self.checkout, self.checkout, self.home) + named = load(self.checkout, self.checkout, self.home, {}) assert isinstance(named, ProjectConfig), named self.assertEqual(named.jira_scoring, JiraScoring("100 * V / (2**S + 8)", 0.5)) def test_a_plan_in_a_file_holds_no_formula_or_bar_of_the_configs(self) -> None: self.write("acme", CLIENT) - named = load(self.checkout, self.checkout, self.home) + named = load(self.checkout, self.checkout, self.home, {}) assert isinstance(named, ProjectConfig), named self.assertIsNone(named.jira_scoring) @@ -368,7 +368,7 @@ class LoadTest(ConfigCase): def test_a_notifier_that_is_unknown_or_has_no_env_file_fails_naming_it(self) -> None: self.write("acme", CLIENT + 'env-file = "~/acme.env"\nnotifier = "teams"\n') self.assertIn("`notifier` is 'teams', not mattermost or slack", self.failure()) - (self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'notifier = "slack"\n') + (self.home / ".config/build-release" / "acme" / "config.toml").write_text(CLIENT + 'notifier = "slack"\n') self.assertIn("`notifier` names a notifier, so `env-file` must name the file that holds its credentials", self.failure()) def test_an_env_file_in_the_checkout_or_the_configs_folder_or_spelt_loosely_fails_naming_it(self) -> None: @@ -377,7 +377,7 @@ class LoadTest(ConfigCase): "a folder: path": lambda home: '"folder:acme.env"', "no prefix": lambda home: '".env"', "a path in the checkout": lambda home: f'"{home}/code/acme-billing/.env"', - "a path in the config's folder": lambda home: f'"{home}/.claude-projects/acme/acme.env"', + "a path in the config's folder": lambda home: f'"{home}/.config/build-release/acme/acme.env"', "not text": lambda home: "3", } for case, spelled in cases.items(): @@ -395,17 +395,17 @@ class LoadTest(ConfigCase): self.home = pathlib.Path(made).resolve() self.checkout = self.home / "code" / "acme-billing" self.write("acme", CLIENT + f'env-file = "{self.home}/code/{folder}/.env"\n') - found = load(self.home / "code" / "acme-billing-item-3", self.checkout, self.home) + found = load(self.home / "code" / "acme-billing-item-3", self.checkout, self.home, {}) assert isinstance(found, Failure), found self.assertIn("`env-file`", found.reason) def test_bench_tasks_is_an_optional_path_listed_last_only_where_set(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig) self.assertNotIn("bench-tasks", left_out.places) (folder / "config.toml").write_text(CLIENT + 'bench-tasks = "checkout:bench-tasks"\ntouch-predictions = "folder:docs/touch-predictions.md"\n', encoding="utf-8") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig) self.assertEqual(list(found.places)[-3:], ["standards", "touch-predictions", "bench-tasks"]) self.assertEqual(found.paths["bench-tasks"], self.checkout / "bench-tasks") @@ -414,11 +414,11 @@ class LoadTest(ConfigCase): def test_touch_predictions_is_an_optional_path_listed_after_the_others_only_where_set(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig) self.assertNotIn("touch-predictions", left_out.places) (folder / "config.toml").write_text(CLIENT + 'touch-predictions = "folder:docs/touch-predictions.md"\n', encoding="utf-8") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig) self.assertEqual(list(found.places)[-2:], ["standards", "touch-predictions"]) self.assertEqual(found.paths["touch-predictions"], folder / "docs/touch-predictions.md") @@ -428,11 +428,11 @@ class LoadTest(ConfigCase): def test_coding_conventions_is_an_optional_list_of_paths_spelt_as_the_others_are(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig) self.assertEqual(left_out.coding_conventions, ()) (folder / "config.toml").write_text(CLIENT + 'coding-conventions = ["checkout:CONVENTIONS.md", "folder:style.md", "~/shared/php.md"]\n', encoding="utf-8") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig) self.assertEqual(found.coding_conventions, (self.checkout / "CONVENTIONS.md", folder / "style.md", self.home / "shared/php.md")) @@ -445,13 +445,13 @@ class LoadTest(ConfigCase): def test_merge_is_chunk_where_left_out_and_takes_human(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertEqual(left_out.merge, "chunk") for spelled in ("chunk", "human"): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f'merge = "{spelled}"\n') - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.merge, spelled) @@ -460,19 +460,19 @@ class LoadTest(ConfigCase): for spelled, named in (('"person"', "'person'"), ("true", "True")): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f"merge = {spelled}\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, Failure), found self.assertIn(f'`merge` is {named}, not "chunk" or "human"', found.reason) def test_wait_for_approval_is_an_optional_boolean_that_is_false_where_left_out(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertFalse(left_out.wait_for_approval) for spelled, expected in (("true", True), ("false", False)): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f"wait-for-approval = {spelled}\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.wait_for_approval, expected) @@ -481,35 +481,35 @@ class LoadTest(ConfigCase): for spelled in ('"yes"', "1", '"true"'): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f"wait-for-approval = {spelled}\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, Failure), found self.assertIn(f"`wait-for-approval` is {eval(spelled)!r}, not true or false", found.reason) def test_tooling_on_host_is_an_optional_boolean_that_is_false_where_left_out(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertFalse(left_out.tooling_on_host) for spelled, expected in (("true", True), ("false", False)): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f"tooling-on-host = {spelled}\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.tooling_on_host, expected) (folder / "config.toml").write_text(CLIENT + 'tooling-on-host = "yes"\n') - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, Failure), found self.assertIn("`tooling-on-host` is 'yes', not true or false", found.reason) def test_the_readability_floor_is_an_optional_number_from_1_to_10_that_is_7_where_left_out(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertEqual(left_out.readability_floor, decimal.Decimal("7.0")) for spelled, expected in (("5", "5"), ("6.5", "6.5"), ("1", "1"), ("10.0", "10.0")): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f"readability-floor = {spelled}\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.readability_floor, decimal.Decimal(expected)) @@ -518,20 +518,20 @@ class LoadTest(ConfigCase): for spelled in ('"7.0"', "0.5", "11", "true", "nan", "inf", "1" + "0" * 400): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f"readability-floor = {spelled}\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, Failure), found self.assertIn("`readability-floor` is ", found.reason) self.assertIn(", not a number from 1 to 10; write a bare number, such as `readability-floor = 7.0`", found.reason) def test_parallel_chunks_is_an_optional_whole_number_from_1_that_is_1_where_left_out(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertEqual(left_out.parallel_chunks, 1) for spelled in (1, 3, 12): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f"parallel-chunks = {spelled}\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual(found.parallel_chunks, spelled) @@ -540,18 +540,18 @@ class LoadTest(ConfigCase): for spelled in ('"2"', "0", "-1", "2.0", "true", "inf"): with self.subTest(spelled): (folder / "config.toml").write_text(CLIENT + f"parallel-chunks = {spelled}\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, Failure), found self.assertIn("`parallel-chunks` is ", found.reason) self.assertIn(", not a whole number of 1 or more, such as `parallel-chunks = 2`", found.reason) def test_the_language_and_the_templates_are_optional_and_default_to_english_bare_summaries_and_item_branches(self) -> None: folder = self.write("acme", CLIENT) - left_out = load(self.checkout, self.checkout, self.home) + left_out = load(self.checkout, self.checkout, self.home, {}) assert isinstance(left_out, ProjectConfig), left_out self.assertEqual((left_out.language, left_out.commit_title, left_out.pull_request_title, left_out.branch), ("English", "{summary}", "{summary}", "item-{id}")) (folder / "config.toml").write_text(CLIENT + 'language = "Swedish"\ncommit-title = "PAY-{id} - {summary}"\npull-request-title = "fix: {summary} (#{id})"\nbranch = "feature/PAY-{id}"\n') - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual((found.language, found.commit_title, found.pull_request_title, found.branch), ("Swedish", "PAY-{id} - {summary}", "fix: {summary} (#{id})", "feature/PAY-{id}")) @@ -561,22 +561,22 @@ class LoadTest(ConfigCase): for line, named in cases.items(): with self.subTest(line): (folder / "config.toml").write_text(CLIENT + line + "\n") - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, Failure), found self.assertIn(named, found.reason) def test_a_language_of_more_than_words_fails_saying_what_is_accepted(self) -> None: folder = self.write("acme", CLIENT + 'language = "Chinese (Simplified)"\n') - found = load(self.checkout, self.checkout, self.home) + found = load(self.checkout, self.checkout, self.home, {}) assert isinstance(found, Failure), found self.assertIn("`language` is 'Chinese (Simplified)', not a language's English name in words of letters, such as \"Swedish\" or \"Brazilian Portuguese\"", found.reason) (folder / "config.toml").write_text(CLIENT + 'language = "Brazilian Portuguese"\n') - self.assertIsInstance(load(self.checkout, self.checkout, self.home), ProjectConfig) + self.assertIsInstance(load(self.checkout, self.checkout, self.home, {}), ProjectConfig) def test_a_checkout_no_config_names_fails_as_unnamed_and_a_faulty_config_does_not(self) -> None: - self.assertIsInstance(load(self.checkout, self.checkout, self.home), Unnamed) + self.assertIsInstance(load(self.checkout, self.checkout, self.home, {}), Unnamed) self.write("acme", CLIENT + "language = 3\n") - self.assertNotIsInstance(load(self.checkout, self.checkout, self.home), Unnamed) + self.assertNotIsInstance(load(self.checkout, self.checkout, self.home, {}), Unnamed) def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None: folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n') @@ -600,27 +600,27 @@ class LoadTest(ConfigCase): def test_a_folder_with_no_config_is_skipped(self) -> None: self.write("acme", CLIENT) - (self.home / ".claude-projects" / "notes").mkdir() - self.assertIsInstance(load(self.checkout, self.checkout, self.home), ProjectConfig) + (self.home / ".config/build-release" / "notes").mkdir() + self.assertIsInstance(load(self.checkout, self.checkout, self.home, {}), ProjectConfig) class TitleTemplatesTest(ConfigCase): def test_names_the_configs_templates_and_bare_summaries_where_no_config_names_the_checkout_or_git_finds_none(self) -> None: subprocess.run(["git", "init", "--quiet", str(self.checkout)], check=True, env=isolated_env()) - self.assertEqual(title_templates(str(self.checkout), self.home), Titles("{summary}", "{summary}")) + self.assertEqual(title_templates(str(self.checkout), self.home, {}), Titles("{summary}", "{summary}")) self.write("acme", CLIENT + 'commit-title = "PAY-{id} - {summary}"\npull-request-title = "fix: {summary} (#{id})"\n') - self.assertEqual(title_templates(str(self.checkout), self.home), Titles("PAY-{id} - {summary}", "fix: {summary} (#{id})")) - self.assertEqual(title_templates(str(self.home), self.home), Titles("{summary}", "{summary}")) + self.assertEqual(title_templates(str(self.checkout), self.home, {}), Titles("PAY-{id} - {summary}", "fix: {summary} (#{id})")) + self.assertEqual(title_templates(str(self.home), self.home, {}), Titles("{summary}", "{summary}")) def test_fails_where_the_checkouts_config_or_any_other_cannot_be_read(self) -> None: subprocess.run(["git", "init", "--quiet", str(self.checkout)], check=True, env=isolated_env()) folder = self.write("acme", CLIENT + 'commit-title = "PAY-{id}"\n') - faulty = title_templates(str(self.checkout), self.home) + faulty = title_templates(str(self.checkout), self.home, {}) assert isinstance(faulty, Failure), faulty self.assertIn("`commit-title` is 'PAY-{id}'", faulty.reason) (folder / "config.toml").write_text(CLIENT) other = self.write("other", "checkout = [") - unread = title_templates(str(self.checkout), self.home) + unread = title_templates(str(self.checkout), self.home, {}) assert isinstance(unread, Failure), unread self.assertIn(f"cannot read {other / 'config.toml'}", unread.reason) @@ -628,54 +628,54 @@ class TitleTemplatesTest(ConfigCase): class HeldTest(ConfigCase): def test_a_configs_folder_holds_its_config_as_the_main_checkout_reads_it(self) -> None: folder = self.write("acme", CLIENT) - found = held(folder, self.home) + found = held(folder, self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual((found.folder, found.top, found.paths["plan"]), (folder, self.checkout, folder / "todo.md"), "the config's ~/ checkout read under home") def test_a_folder_holds_no_config_unless_it_is_under_the_projects_folder_and_has_one(self) -> None: - self.assertIsNone(held(self.home / ".claude-projects" / "empty", self.home), "no config.toml") + self.assertIsNone(held(self.home / ".config/build-release" / "empty", self.home, {}), "no config.toml") elsewhere = self.home / "code" / "acme" elsewhere.mkdir() (elsewhere / "config.toml").write_text(CLIENT, encoding="utf-8") - self.assertIsNone(held(elsewhere, self.home), "a config.toml outside ~/.claude-projects/") + self.assertIsNone(held(elsewhere, self.home, {}), "a config.toml outside ~/.config/build-release/") def test_the_do_epic_folder_holds_no_projects_config(self) -> None: folder = self.write("do-epic", CLIENT) - self.assertIsNone(held(folder, self.home)) + self.assertIsNone(held(folder, self.home, {})) def test_a_configs_folder_reached_through_a_symlink_holds_its_config(self) -> None: target = self.home / "kept" / "acme" target.mkdir(parents=True) (target / "config.toml").write_text(CLIENT, encoding="utf-8") - (self.home / ".claude-projects").mkdir() - (self.home / ".claude-projects" / "acme").symlink_to(target) - self.assertIsInstance(held(target, self.home), ProjectConfig, "git names the folder by its resolved path") + (self.home / ".config/build-release").mkdir(parents=True) + (self.home / ".config/build-release" / "acme").symlink_to(target) + self.assertIsInstance(held(target, self.home, {}), ProjectConfig, "git names the folder by its resolved path") class ByNameTest(ConfigCase): def test_finds_the_config_of_the_project_whose_main_checkout_has_the_name_though_the_checkout_is_missing(self) -> None: folder = self.write("acme", CLIENT) - found = by_name("acme-billing", self.home) + found = by_name("acme-billing", self.home, {}) assert isinstance(found, ProjectConfig), found self.assertEqual((found.folder, found.top), (folder, self.checkout)) def test_finds_none_where_no_config_names_a_checkout_of_that_name(self) -> None: self.write("acme", CLIENT) - self.assertIsNone(by_name("billing", self.home), "a part of a name is not the name") - self.assertIsNone(by_name("acme", self.home), "a config's key is not a repo's name") - self.assertIsNone(by_name("do-epic", self.home)) + self.assertIsNone(by_name("billing", self.home, {}), "a part of a name is not the name") + self.assertIsNone(by_name("acme", self.home, {}), "a config's key is not a repo's name") + self.assertIsNone(by_name("do-epic", self.home, {})) def test_fails_where_two_configs_name_a_checkout_of_that_name(self) -> None: self.write("acme", CLIENT) self.write("acme-two", CLIENT.replace("~/code/acme-billing", "~/other/acme-billing")) - found = by_name("acme-billing", self.home) + found = by_name("acme-billing", self.home, {}) assert isinstance(found, Failure), found self.assertIn("acme/config.toml and ", found.reason) self.assertIn("acme-two/config.toml each name a checkout called acme-billing", found.reason) def test_fails_where_a_config_cannot_be_read_since_it_may_be_the_one_asked_for(self) -> None: self.write("acme", "this is not toml") - self.assertIsInstance(by_name("acme-billing", self.home), Failure) + self.assertIsInstance(by_name("acme-billing", self.home, {}), Failure) class EnvFilesTest(ConfigCase): @@ -684,11 +684,11 @@ class EnvFilesTest(ConfigCase): self.write("misplaced", 'checkout = "~/code/other"\nenv-file = "/srv/other.env"\n') self.write("broken", "checkout = ") self.write("none", CLIENT) - self.assertEqual(env_files(self.home), [self.home / "acme.env", pathlib.Path("/srv/other.env")]) + self.assertEqual(env_files(self.home, {}), [self.home / "acme.env", pathlib.Path("/srv/other.env")]) def test_lists_do_epics_env_file_though_its_config_names_no_checkout(self) -> None: self.write("do-epic", 'env-file = "~/jira.env"\n') - self.assertEqual(env_files(self.home), [self.home / "jira.env"]) + self.assertEqual(env_files(self.home, {}), [self.home / "jira.env"]) class ToolTest(ConfigCase): @@ -729,17 +729,17 @@ class ToolTest(ConfigCase): unset = self.run_tool("env-file") self.assertEqual((unset.returncode, unset.stdout, unset.stderr), (1, "", f"{folder / 'config.toml'} sets no `env-file`\n")) self.assertNotIn("env-file", self.run_tool().stdout) - (folder / "config.toml").write_text(CLIENT + 'env-file = "~/.claude-projects/acme.env"\n') + (folder / "config.toml").write_text(CLIENT + 'env-file = "~/.config/build-release/acme.env"\n') one = self.run_tool("env-file") - self.assertEqual((one.returncode, one.stdout), (0, f"{self.home}/.claude-projects/acme.env\n")) - self.assertEqual(self.run_tool().stdout.splitlines()[-1], f"env-file: {self.home}/.claude-projects/acme.env") + self.assertEqual((one.returncode, one.stdout), (0, f"{self.home}/.config/build-release/acme.env\n")) + self.assertEqual(self.run_tool().stdout.splitlines()[-1], f"env-file: {self.home}/.config/build-release/acme.env") def test_prints_the_notifier_where_the_config_sets_one_and_fails_asking_for_it_where_it_does_not(self) -> None: folder = self.write("acme", CLIENT) unset = self.run_tool("notifier") self.assertEqual((unset.returncode, unset.stdout, unset.stderr), (1, "", f"{folder / 'config.toml'} sets no `notifier`\n")) self.assertNotIn("notifier", self.run_tool().stdout) - (folder / "config.toml").write_text(CLIENT + 'env-file = "~/.claude-projects/acme.env"\nnotifier = "slack"\n') + (folder / "config.toml").write_text(CLIENT + 'env-file = "~/.config/build-release/acme.env"\nnotifier = "slack"\n') self.assertEqual(self.run_tool("notifier").stdout, "slack\n") self.assertEqual(self.run_tool().stdout.splitlines()[-1], "notifier: slack") diff --git a/bin/project_record/main.py b/bin/project_record/main.py index 4b3d80a5..49de4ba5 100644 --- a/bin/project_record/main.py +++ b/bin/project_record/main.py @@ -10,7 +10,7 @@ kept in a Jira epic's description: edit those two in Jira. open prints the path of a file holding the record's text, and nothing else. Read and edit that file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the -path is a copy under ~/.local/state/project-record/<key>/<worktree>/, a folder named for the +path is a copy under ~/.local/state/build-release/project-record/<key>/<worktree>/, a folder named for the worktree that ran open, so two worktrees of one project don't share a copy. The copy is written afresh with the record as it stands, so open it again before each edit. open also removes the folders of worktrees git no longer lists. A record that doesn't exist yet has no file at the path: @@ -27,6 +27,7 @@ until open runs again and writes the copy afresh. Exit 2 on bad arguments, and 1, saying why, on any other failure. """ import hashlib +import os import pathlib import shutil import sys @@ -36,12 +37,12 @@ from record_store.stores import FileStore, goals_store, local_file, RECORDS, Rec from git_cli.git_repo import git, Git from project_config.main import located from project_config.settings import ProjectConfig -from loop_state.paths import STATE_FOLDER +from loop_state.paths import state_folder # Not git's verbs, such as checkout and commit: those read as acting on the repo. COMMANDS = ("open", "save") # Where the copy of a record kept outside files goes, under the user's home, in a folder per project and worktree. -COPIES = f"{STATE_FOLDER}/project-record" +COPIES = "project-record" # The goals file opens like a record, though it is a setting of its own. GOALS = "goals-and-audience" @@ -54,8 +55,8 @@ def main(argv: list[str]) -> int: print(f"usage: project-record {'|'.join(COMMANDS)} <record>, where <record> is one of {', '.join((*RECORDS, GOALS))}", file=sys.stderr) return 2 home = pathlib.Path.home() - config = located(None, home) - done = config if isinstance(config, Failure) else performed(config, argv[0], argv[1], home) + config = located(None, home, os.environ) + done = config if isinstance(config, Failure) else performed(config, argv[0], argv[1], state_folder(os.environ, home)) if isinstance(done, Failure): print(f"project-record: {done.reason}", file=sys.stderr) return 1 @@ -63,16 +64,16 @@ def main(argv: list[str]) -> int: return 0 -def performed(config: ProjectConfig, command: str, name: str, home: pathlib.Path, run: Git = git) -> str | Failure: +def performed(config: ProjectConfig, command: str, name: str, state: pathlib.Path, run: Git = git) -> str | Failure: """What command, one of COMMANDS, prints for the record called name. An open also prunes the copies of removed worktrees.""" if command == "open": - pruned(config, home, run) - return act(command, *opened(config, name, home)) + pruned(config, state, run) + return act(command, *opened(config, name, state)) -def opened(config: ProjectConfig, name: str, home: pathlib.Path) -> tuple[RecordStore, pathlib.Path]: +def opened(config: ProjectConfig, name: str, state: pathlib.Path) -> tuple[RecordStore, pathlib.Path]: """The store of the record called name, and the copy it gets where it isn't kept as a file.""" - copy = home / COPIES / config.key / worktree_folder(config.top) / f"{name}.md" + copy = state / COPIES / config.key / worktree_folder(config.top) / f"{name}.md" return (goals_store(config) if name == GOALS else store(config, name)), copy @@ -81,10 +82,10 @@ def worktree_folder(top: pathlib.Path) -> str: return f"{top.name}-{hashlib.sha256(str(top).encode()).hexdigest()[:8]}" -def pruned(config: ProjectConfig, home: pathlib.Path, run: Git = git) -> None: +def pruned(config: ProjectConfig, state: pathlib.Path, run: Git = git) -> None: """Remove the copies of the worktrees git no longer lists, so the folders don't pile up one per chunk. Best effort: a folder that stays only takes disk, and where git can't list the worktrees nothing is removed.""" listed = run("worktree", "list", "--porcelain") - folders = home / COPIES / config.key + folders = state / COPIES / config.key if isinstance(listed, Failure) or not folders.is_dir(): return worktrees = [config.top, *(pathlib.Path(line.removeprefix("worktree ")) for line in listed.splitlines() if line.startswith("worktree "))] diff --git a/bin/project_record/test_project_record.py b/bin/project_record/test_project_record.py index 5ef5cde3..5090db2d 100644 --- a/bin/project_record/test_project_record.py +++ b/bin/project_record/test_project_record.py @@ -17,38 +17,39 @@ from project_config.settings import Page, ProjectConfig TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-record" -COPIES = pathlib.Path("/home/me/.local/state/project-record/acme") +STATE = pathlib.Path("/home/me/.local/state/build-release") +COPIES = STATE / "project-record/acme" def worktree_config(top: str, **kept: Page) -> ProjectConfig: - return ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path(top), {"goals-and-audience": pathlib.Path(top, "README.md")}, pathlib.Path("/home/me/acme.env"), pages=kept) + return ProjectConfig("acme", pathlib.Path("/home/me/.config/build-release/acme"), pathlib.Path(top), {"goals-and-audience": pathlib.Path(top, "README.md")}, pathlib.Path("/home/me/acme.env"), pages=kept) class Opened(unittest.TestCase): def test_a_record_on_a_confluence_page_gets_a_copy_in_a_folder_of_its_worktree(self): page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761") - record, copy = main.opened(worktree_config("/code/acme", decisions=page), "decisions", pathlib.Path("/home/me")) + record, copy = main.opened(worktree_config("/code/acme", decisions=page), "decisions", STATE) self.assertEqual((copy.parent.parent, copy.name), (COPIES, "decisions.md")) self.assertRegex(copy.parent.name, r"^acme-[0-9a-f]{8}$") self.assertIsInstance(record, ConfluencePage) def test_the_goals_file_opens_through_the_goals_store(self): - record, copy = main.opened(worktree_config("/code/acme"), "goals-and-audience", pathlib.Path("/home/me")) + record, copy = main.opened(worktree_config("/code/acme"), "goals-and-audience", STATE) self.assertEqual((record.label, copy.parent.parent, copy.name), ("/code/acme/README.md", COPIES, "goals-and-audience.md")) def test_two_worktrees_of_one_project_get_copies_that_differ(self): - home = pathlib.Path("/home/me") + home = STATE main_checkout = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1] other = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1] self.assertNotEqual(main_checkout, other) def test_one_worktree_always_gets_the_same_copy(self): - home = pathlib.Path("/home/me") + home = STATE first = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1] self.assertEqual(first, main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]) def test_two_worktrees_named_alike_in_different_folders_get_copies_that_differ(self): - home = pathlib.Path("/home/me") + home = STATE first = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1] second = main.opened(worktree_config("/other/acme-item-5"), "goals-and-audience", home)[1] self.assertNotEqual(first, second) @@ -58,9 +59,10 @@ class Pruned(unittest.TestCase): def setUp(self) -> None: self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) self.config = worktree_config("/code/acme-item-5") - self.folders = self.home / ".local/state/project-record/acme" + self.state = self.home / ".local/state/build-release" + self.folders = self.state / "project-record/acme" for top in ("/code/acme", "/code/acme-item-5", "/code/acme-item-6"): - copy = main.opened(worktree_config(top), "goals-and-audience", self.home)[1] + copy = main.opened(worktree_config(top), "goals-and-audience", self.state)[1] copy.parent.mkdir(parents=True) copy.write_text("edit") @@ -71,37 +73,37 @@ class Pruned(unittest.TestCase): return lambda *args, **kwargs: "" if args != ("worktree", "list", "--porcelain") else "".join(f"worktree {top}\nHEAD abc\nbranch refs/heads/x\n\n" for top in tops) def test_removes_the_copies_of_worktrees_git_no_longer_lists_and_keeps_the_others(self): - main.pruned(self.config, self.home, self.listed("/code/acme", "/code/acme-item-5")) + main.pruned(self.config, self.state, self.listed("/code/acme", "/code/acme-item-5")) self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")}) def test_always_keeps_the_copy_of_the_worktree_that_asked(self): - main.pruned(self.config, self.home, self.listed("/code/acme")) + main.pruned(self.config, self.state, self.listed("/code/acme")) self.assertIn(main.worktree_folder(pathlib.Path("/code/acme-item-5")), self.kept()) def test_removes_nothing_where_git_cannot_list_the_worktrees(self): - main.pruned(self.config, self.home, lambda *args, **kwargs: Failure("not a repository")) + main.pruned(self.config, self.state, lambda *args, **kwargs: Failure("not a repository")) self.assertEqual(len(self.kept()), 3) def test_leaves_files_beside_the_folders_alone(self): (self.folders / "decisions.md").write_text("from before the folders") - main.pruned(self.config, self.home, self.listed("/code/acme")) + main.pruned(self.config, self.state, self.listed("/code/acme")) self.assertTrue((self.folders / "decisions.md").exists()) def test_a_copy_that_cannot_be_removed_does_not_fail_the_open(self): self.folders.chmod(0o500) self.addCleanup(self.folders.chmod, 0o700) - main.pruned(self.config, self.home, self.listed("/code/acme")) + main.pruned(self.config, self.state, self.listed("/code/acme")) self.assertEqual(len(self.kept()), 3) def test_an_open_prunes_and_a_save_does_not(self): run = self.listed("/code/acme", "/code/acme-item-5") - self.assertEqual(main.performed(self.config, "save", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md is the record itself, so nothing is left to store.") + self.assertEqual(main.performed(self.config, "save", "goals-and-audience", self.state, run), "/code/acme-item-5/README.md is the record itself, so nothing is left to store.") self.assertEqual(len(self.kept()), 3) - self.assertEqual(main.performed(self.config, "open", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md") + self.assertEqual(main.performed(self.config, "open", "goals-and-audience", self.state, run), "/code/acme-item-5/README.md") self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")}) def test_does_nothing_where_the_project_has_no_copies(self): - main.pruned(worktree_config("/code/acme"), self.home / "elsewhere", self.listed("/code/acme")) + main.pruned(worktree_config("/code/acme"), self.state / "elsewhere", self.listed("/code/acme")) class Act(unittest.TestCase): @@ -130,7 +132,7 @@ class Act(unittest.TestCase): class BlackBox(unittest.TestCase): def setUp(self) -> None: self.top = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())).resolve() - self.home = configured(self, self.top).parents[1] + self.home = configured(self, self.top).parents[2] def run_tool(self, *args: str) -> subprocess.CompletedProcess[str]: return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.top, env=os.environ | {"HOME": str(self.home)}, text=True) @@ -153,7 +155,7 @@ class BlackBox(unittest.TestCase): self.assertIn("usage: project-record open|save <record>, where <record> is one of decisions, score-anchors, comprehension-history, reading-cost, changelog, goals-and-audience", ran.stderr) def test_exits_1_saying_why_where_no_config_names_the_checkout(self): - (self.home / ".claude-projects" / self.top.name / "config.toml").unlink() + (self.home / ".config/build-release" / self.top.name / "config.toml").unlink() ran = self.run_tool("open", "decisions") self.assertEqual((ran.returncode, ran.stdout), (1, "")) self.assertIn("no config names the checkout", ran.stderr) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index fbe3f961..7e2e095f 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -91,6 +91,8 @@ rules above, a scoring run on docs/comprehension-history.md's newest scored comm ending in its overall, an item that is not exempt scoring under the bar, or --check finding the file unranked, or an item's `Touches:` list unreadable. """ +from collections.abc import Mapping +import os import pathlib import sys @@ -99,14 +101,14 @@ from plan_store.stores import file_plan from project_config.main import located -def main(argv: list[str], home: pathlib.Path) -> int: +def main(argv: list[str], home: pathlib.Path, env: Mapping[str, str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 args = parse_args(argv) if isinstance(args, Failure): return fail(args) - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return fail(config) if config.plan_file is None and args == (True, None): @@ -145,4 +147,4 @@ def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path | None] | Failure: if __name__ == "__main__": - sys.exit(main(sys.argv[1:], pathlib.Path.home())) + sys.exit(main(sys.argv[1:], pathlib.Path.home(), os.environ)) diff --git a/bin/reading_cost/main.py b/bin/reading_cost/main.py index 35627705..fe6ed7bf 100644 --- a/bin/reading_cost/main.py +++ b/bin/reading_cost/main.py @@ -4,7 +4,7 @@ usage: reading-cost [--reset] [record] Run it inside a project checkout or one of its worktrees. record defaults to the docs/reading-cost.md the project's config names, created when missing. It reads build-release's archive of the project, -$BUILD_RELEASE_TRANSCRIPTS/<key> (default ~/.claude/loop-claude-transcripts), <key> being the +$BUILD_RELEASE_TRANSCRIPTS/<key> (default ~/.local/state/build-release/transcripts), <key> being the checkout's path relative to ~/code, or to / outside it. For each finished chunk the record does not yet hold, it measures what the worker and its subagents read before the worker's first commit: their new input tokens (uncached and cache-written; cache reads excluded), and how often they opened or diff --git a/bin/reading_cost/test_reading_cost.py b/bin/reading_cost/test_reading_cost.py index 52e1a708..601913cb 100644 --- a/bin/reading_cost/test_reading_cost.py +++ b/bin/reading_cost/test_reading_cost.py @@ -161,7 +161,7 @@ class ReadingCostTool(unittest.TestCase): return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd, env=self.env, text=True) def test_writes_the_record_where_the_config_puts_it_and_fails_without_a_config(self): - config = self.home / ".claude-projects" / "proj" / "config.toml" + config = self.home / ".config/build-release" / "proj" / "config.toml" config.write_text(config.read_text().replace('"checkout:docs/reading-cost.md"', '"folder:docs/reading-cost.md"')) record = config.parent / "docs" / "reading-cost.md" record.parent.mkdir() @@ -194,17 +194,17 @@ class ReadingCostTool(unittest.TestCase): ran = self.run_tool(worktree) self.assertEqual(ran.returncode, 0, ran.stderr) history = worktree / "docs" / "reading-cost.md" - self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} to {history}.\n2 chunks measured since the last reset; the trend needs 10.\n") + self.assertEqual(ran.stdout, f"Appended 2 reading-cost figures from {self.home / '.local/state/build-release' / 'transcripts' / 'proj'} to {history}.\n2 chunks measured since the last reset; the trend needs 10.\n") figure = "## Reading cost, chunk {}, finished {}\n\n33 new input tokens before the first commit.\n\nRead most (opens and searches):\n\n- `a.py` 1\n" self.assertEqual(history.read_text(), "# Reading cost\n\n" + "\n".join(figure.format(chunk.folder[:12], chunk.finished) for chunk in chunks)) self.assertTrue(self.run_tool(worktree).stdout.startswith(f"Appended 0 reading-cost figures from")) self.assertEqual(history.read_text().count("## Reading cost"), 2) reset = self.run_tool(worktree, "--reset") - self.assertEqual(reset.stdout, f"Appended 0 reading-cost figures from {self.home / '.claude' / 'loop-claude-transcripts' / 'proj'} and a reset to {history}.\n0 chunks measured since the last reset; the trend needs 10.\n") + self.assertEqual(reset.stdout, f"Appended 0 reading-cost figures from {self.home / '.local/state/build-release' / 'transcripts' / 'proj'} and a reset to {history}.\n0 chunks measured since the last reset; the trend needs 10.\n") self.assertRegex(history.read_text(), r"\n## Reading cost reset, \d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ\n$") def test_counts_a_file_read_in_a_worktree_the_configs_branch_template_names(self): - config = self.home / ".claude-projects" / "proj" / "config.toml" + config = self.home / ".config/build-release" / "proj" / "config.toml" config.write_text(config.read_text() + 'branch = "feature/PAY-{id}"\n') self.archive_chunk(1790000100, worktree=self.home / "code" / "proj-feature-PAY-7") ran = self.run_tool(self.checkout) diff --git a/bin/record_store/test_stores.py b/bin/record_store/test_stores.py index 62796778..7b833c63 100644 --- a/bin/record_store/test_stores.py +++ b/bin/record_store/test_stores.py @@ -168,33 +168,33 @@ class Store(unittest.TestCase): return ProjectConfig("acme", folder, top, paths) def test_a_record_in_the_checkout_is_tracked_by_its_path_from_the_top(self): - store = stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "decisions") + store = stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.config/build-release/acme")), "decisions") self.assertEqual((store.label, store.tracked), ("/code/acme/decisions.md", "decisions.md")) def test_a_record_in_the_configs_folder_is_not_tracked(self): - store = stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "changelog") - self.assertEqual((store.label, store.tracked), ("/home/me/.claude-projects/acme/CHANGELOG.md", None)) + store = stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.config/build-release/acme")), "changelog") + self.assertEqual((store.label, store.tracked), ("/home/me/.config/build-release/acme/CHANGELOG.md", None)) def test_the_plan_is_not_a_record(self): with self.assertRaises(ValueError) as refused: - stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "plan") + stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.config/build-release/acme")), "plan") self.assertEqual(str(refused.exception), "plan is not a record; the records are decisions, score-anchors, comprehension-history, reading-cost, changelog") def test_a_record_on_a_confluence_page_is_that_page(self): page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761") - config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page}) + config = ProjectConfig("acme", pathlib.Path("/home/me/.config/build-release/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page}) self.assertEqual(stores.store(config, "decisions"), ConfluencePage(page, pathlib.Path("/home/me/acme.env"))) class GoalsStore(unittest.TestCase): def test_goals_kept_as_a_file_are_that_file(self): top = pathlib.Path("/code/acme") - store = stores.goals_store(ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), top, {"goals-and-audience": top / "README.md"})) + store = stores.goals_store(ProjectConfig("acme", pathlib.Path("/home/me/.config/build-release/acme"), top, {"goals-and-audience": top / "README.md"})) self.assertEqual((store.label, store.tracked), ("/code/acme/README.md", "README.md")) def test_goals_kept_in_jira_are_the_epics_description(self): epic = Epic("https://acme.atlassian.net", "ABC-12") - store = stores.goals_store(ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), goals_epic=epic)) + store = stores.goals_store(ProjectConfig("acme", pathlib.Path("/home/me/.config/build-release/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), goals_epic=epic)) self.assertEqual(store, EpicDescription(epic, pathlib.Path("/home/me/acme.env"))) diff --git a/bin/repo_checks/test_gitignore.py b/bin/repo_checks/test_gitignore.py index 546caf11..90c8991f 100644 --- a/bin/repo_checks/test_gitignore.py +++ b/bin/repo_checks/test_gitignore.py @@ -16,11 +16,9 @@ PRIVATE = [ "daemon.log", "daemon/control.key", "debug/a.txt", - "do-epic-transcripts/a/b.jsonl", "file-history/a/b.md", "history.jsonl", "jobs/a/b.json", - "loop-claude-transcripts/a/b.jsonl", "memory/MEMORY.md", "paste-cache/a.txt", "projects/-home-a/a.jsonl", diff --git a/bin/repo_checks/test_paths_in_one_module.py b/bin/repo_checks/test_paths_in_one_module.py index 50243ed3..cf76f3a8 100644 --- a/bin/repo_checks/test_paths_in_one_module.py +++ b/bin/repo_checks/test_paths_in_one_module.py @@ -9,9 +9,9 @@ OWNER = "bin/loop_state/paths.py" # How code spells one of those folders itself, in place of asking OWNER. Prose such as help text, which names `~/.claude` to its reader, is not matched. RESOLVED_ELSEWHERE = re.compile( r"""["']\.claude["'/]""" - r"""|["']\.claude-projects["'/]""" + r"""|["']\.config["'/]""" r"""|["']\.local["'/]""" - r"""|["']XDG_STATE_HOME["']""" + r"""|["']XDG_(CONFIG|STATE)_HOME["']""" r"""|__file__\)\.resolve\(\)\.parents\[""" ) diff --git a/bin/review_replay/main.py b/bin/review_replay/main.py index 85ff874c..95efe0d9 100644 --- a/bin/review_replay/main.py +++ b/bin/review_replay/main.py @@ -5,7 +5,7 @@ usage: review-replay <pass> <model> [--omit-claude-md | --bash-ceiling | --read- <pass> is one of architecture, principles, overrides, stability, product-owner or prose. <model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the latest 10 archived rounds of the pass whose report holds a 🔴 or 🟡 finding, from the projects -that ~/.claude/loop-claude-models.json runs on the model. It replays each round on the code it +that ~/.config/build-release/models.json runs on the model. It replays each round on the code it reviewed: in a throwaway clone of the project's checkout, at the newest commit of origin/HEAD authored by the time the round began, on the branch the reviewer started on. The clone's default branch stands at the newest commit authored before the round's chunk began, so a diff against it @@ -57,7 +57,7 @@ result, is in the archive. It refuses to run where its own environment already h replays as archived would inherit it. It keeps each run, a reviewer's tool calls included, and the report it prints in build-release's archive, in -replays/review-replay-<pass>-<model>[-<flag without its leading dashes>]-<UTC stamp>/ under ~/.claude/loop-claude-transcripts +replays/review-replay-<pass>-<model>[-<flag without its leading dashes>]-<UTC stamp>/ under ~/.local/state/build-release/transcripts or $BUILD_RELEASE_TRANSCRIPTS. A run's .jsonl file starts with a line holding claude's arguments, working directory, prompt, exit code and stderr, then holds claude's stream-json output; result.md holds the report. @@ -103,7 +103,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff # The replays as archived start under this environment too, so a change it already holds would reach all four. if change and (inherited := [name for name in change.env if name in env]): return failed(TOOL, f"the replays as archived would inherit {', '.join(inherited)} from this environment, and the comparison needs them without it: unset it and run again") - rounds = archived_rounds(REVIEWERS[reviewed], project.model, archive_root(home, env), home) + rounds = archived_rounds(REVIEWERS[reviewed], project.model, archive_root(home, env), home, env) if isinstance(rounds, Failure): return failed(TOOL, rounds.reason) codes = codes_found(rounds, effects, say) @@ -113,14 +113,14 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff folder = replay_folder(archive_root(home, env), TOOL, argv, effects.now()) effects = archiving(effects, folder, say) if change: - report = compared(reviewed, project, chosen, change, lambda found, applied: findings_replayed(found, codes[found], project, project, home, effects, applied, scratch), say, at_once) + report = compared(reviewed, project, chosen, change, lambda found, applied: findings_replayed(found, codes[found], project, project, home, env, effects, applied, scratch), say, at_once) if isinstance(report, Limited): return limited_exit(TOOL, report) print_report(folder, report) return 0 def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited: - matched = findings_replayed(found, codes[found], rung, project, home, effects, None, scratch) + matched = findings_replayed(found, codes[found], rung, project, home, env, effects, None, scratch) if isinstance(matched, Failure): say(f" {found.root} {found.at} on {rung} failed: {matched.reason}") return matched diff --git a/bin/review_replay/replay.py b/bin/review_replay/replay.py index 5fb1a544..ce899341 100644 --- a/bin/review_replay/replay.py +++ b/bin/review_replay/replay.py @@ -1,6 +1,7 @@ """Replay one archived review round on one rung: the code the round reviewed, found again in a throwaway clone, the reviewer's report on it, and the match of that report to the round's archived findings: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`.""" import dataclasses import json +from collections.abc import Mapping import os import pathlib import shutil @@ -18,10 +19,13 @@ from record_store.stores import local_file, store from project_config.main import located from review_rules.reviewer_context import principles_line, reviewer_context from text_files.compressed import read_stored, SUFFIX -from review_rules.review_folder import REPORTS, review_folder +from review_rules.review_folder import reports_folder, review_folder from model_routing.ladder import Rung +from loop_state.paths import STATE_HOME from claude_code.entries import structured_output +# Where, under the home folder, the review folders were until 0.18.0: the prompt of a round archived before then names its review folder there. +REPORTS_BEFORE_0_18 = f"{STATE_HOME}/larv-review" MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False} @@ -75,9 +79,9 @@ def commit_log(listed: str) -> list[tuple[str, float]]: return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())] -def findings_replayed(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects, change: Change | None, scratch: pathlib.Path | None) -> set[int] | Failure | Limited: +def findings_replayed(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, env: Mapping[str, str], effects: Effects, change: Change | None, scratch: pathlib.Path | None) -> set[int] | Failure | Limited: """The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them, or the Failure of the review or the match; where change is given, the replay runs with it, as `launch` says. The clone is made under scratch, or under the system's temporary folder where it is None.""" - reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects, change, scratch)) + reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, env, effects, change, scratch)) if isinstance(reviewed, (Failure, Limited)): return reviewed return first_reply(lambda: match(found.findings, reviewed, found.root, project, effects)) @@ -91,27 +95,27 @@ class Copies: # The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is. -def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, change: Change | None, scratch: pathlib.Path | None) -> str | Failure | Limited: +def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, env: Mapping[str, str], effects: Effects, change: Change | None, scratch: pathlib.Path | None) -> str | Failure | Limited: try: - (home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix="review-replay-", dir=scratch, ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports: - return reviewed_in(found, code, rung, Copies(clone, reports), home, effects, change) + reports_folder(home, env).mkdir(mode=0o700, parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="review-replay-", dir=scratch, ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=reports_folder(home, env), ignore_cleanup_errors=True) as reports: + return reviewed_in(found, code, rung, Copies(clone, reports), home, env, effects, change) except OSError as failure: return Failure(f"could not prepare the replay: {failure}") -def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects, change: Change | None) -> str | Failure | Limited: +def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, env: Mapping[str, str], effects: Effects, change: Change | None) -> str | Failure | Limited: """The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports; with change where given.""" - folder = pathlib.Path(review_folder(str(home), code.path)) + folder = pathlib.Path(review_folder(str(home), env, code.path)) copy_reports(found, folder, copies.reports) - prompt = redirected(found.prompt, home, folder, code.path, copies) + prompt = redirected(found.prompt, home, folder, reports_folder(home, env), code.path, copies) if isinstance(prompt, Failure): return prompt if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()): return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's") if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure): return cloned - launched = launch(found.reviewer, rung, prompt, found.root, copies, home, change) + launched = launch(found.reviewer, rung, prompt, found.root, copies, home, env, change) if isinstance(launched, Failure): return launched reply = claude_reply(effects.claude, launched[0], copies.clone, launched[1], "claude") @@ -120,7 +124,7 @@ def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: path return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report") -def launch(reviewer: str, rung: Rung, prompt: str, checkout: str, copies: Copies, home: pathlib.Path, change: Change | None) -> tuple[list[str], str] | Failure: +def launch(reviewer: str, rung: Rung, prompt: str, checkout: str, copies: Copies, home: pathlib.Path, env: Mapping[str, str], change: Change | None) -> tuple[list[str], str] | Failure: """claude's arguments and prompt for reviewer on rung, in copies.clone, a copy of the project whose checkout is checkout. Where change is given, claude starts under the environment change holds, which claude's settings set; where change turns the instruction files off, the prompt holds what the SubagentStart hook and the header's last line hand such a reviewer.""" args = ["--agent", reviewer, *rung.flags()] if change is None: @@ -132,7 +136,7 @@ def launch(reviewer: str, rung: Rung, prompt: str, checkout: str, copies: Copies context = reviewer_context(home) if isinstance(context, Failure): return context - config = located(checkout, home) + config = located(checkout, home, env) if isinstance(config, Failure): return config record = store(config, "decisions") @@ -160,12 +164,18 @@ def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None: (pathlib.Path(reports) / name).write_bytes(read_stored(folder / name)) -def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure: - """prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder.""" +def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, reports: pathlib.Path, worktree: str, copies: Copies) -> str | Failure: + """prompt naming copies.reports in place of the review folder, in each spelling, and copies.clone in place of the worktree; a Failure where it still names a review folder. folder is the chunk's review folder, in the reports folder reports.""" # Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's. - prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone) + for root in (reports, home / REPORTS_BEFORE_0_18): + named = root / folder.relative_to(reports) + prompt = prompt.replace(str(named), copies.reports) + if named.is_relative_to(home): + prompt = prompt.replace(f"~/{named.relative_to(home)}", copies.reports) + prompt = prompt.replace(worktree, copies.clone) # A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it. - if REPORTS in prompt.replace(copies.reports, ""): + rest = prompt.replace(copies.reports, "") + if any(spelling in rest for spelling in (REPORTS_BEFORE_0_18, f"{reports.parent.name}/{reports.name}")): return Failure("the prompt names the review folder in a spelling the replay does not redirect") return prompt diff --git a/bin/review_replay/rounds.py b/bin/review_replay/rounds.py index 013a3d1f..e2d84dbb 100644 --- a/bin/review_replay/rounds.py +++ b/bin/review_replay/rounds.py @@ -112,8 +112,8 @@ def sample(rounds: list[Round], latest: int) -> list[Round]: return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:] -def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure: - projects = projects_on(model, home) +def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path, env: typing.Mapping[str, str]) -> list[Round] | Failure: + projects = projects_on(model, home, env) if isinstance(projects, Failure): return projects found = [] diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index 9b586428..e441894b 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -129,11 +129,11 @@ class Launch(unittest.TestCase): self.config = configured(self, self.checkout, home=self.home) / "config.toml" def test_runs_the_reviewer_as_archived_with_claude_md(self): - self.assertEqual(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, None), (["--agent", "prose-reviewer", *REFERENCE.flags()], "Review it.")) + self.assertEqual(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, None), (["--agent", "prose-reviewer", *REFERENCE.flags()], "Review it.")) def test_drops_claude_md_and_hands_the_reviewer_what_the_hook_and_the_header_would(self): (self.clone / "AGENTS.md").write_text("") - args, prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, changes.OMIT) + args, prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, changes.OMIT) self.assertEqual(args, ["--agent", "prose-reviewer", *REFERENCE.flags(), "--settings", json.dumps({"env": {"CLAUDE_CODE_DISABLE_CLAUDE_MDS": "1"}})]) self.assertEqual(prompt, f"{reviewer_context(self.home)}\n\nReview it.\nPrinciples: read {self.clone}/AGENTS.md first, for the project principles and the decision titles.") @@ -141,7 +141,7 @@ class Launch(unittest.TestCase): self.config.write_text(self.config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"')) (self.clone / "AGENTS.md").write_text("") (self.config.parent / "AGENTS.md").write_text("") - prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, changes.OMIT)[1] + prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, changes.OMIT)[1] self.assertTrue(prompt.endswith(f"Principles: read {self.config.parent}/AGENTS.md first, for the project principles and the decision titles."), prompt) def test_names_the_decision_log_in_the_clone_or_where_it_stands_outside_the_checkout_without_agents_md(self): @@ -151,16 +151,16 @@ class Launch(unittest.TestCase): self.config.write_text(self.config.read_text().replace('"checkout:docs/decisions.md"', f'"{setting}"')) decisions.parent.mkdir(exist_ok=True) decisions.write_text("1. A principle.\n\n# Decisions\n") - prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, changes.OMIT)[1] + prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, changes.OMIT)[1] self.assertTrue(prompt.endswith(f"Principles: read {decisions} first, up to `# Decisions`, for the project principles and the decision titles."), prompt) def test_fails_without_a_config_for_the_checkout(self): self.config.unlink() - self.assertIn("no config names the checkout", replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, changes.OMIT).reason) + self.assertIn("no config names the checkout", replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, changes.OMIT).reason) def test_fails_without_the_sections_to_hand_over(self): (self.home / ".claude" / "CLAUDE.md").write_text("") - self.assertIsInstance(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, changes.OMIT), Failure) + self.assertIsInstance(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, {}, changes.OMIT), Failure) class Match(unittest.TestCase): @@ -204,9 +204,10 @@ class Main(unittest.TestCase): def setUp(self): self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) - self.archive = self.home / ".claude" / "loop-claude-transcripts" + self.archive = self.home / ".local/state/build-release" / "transcripts" (self.home / ".claude").mkdir() - (self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"})) + (self.home / ".config/build-release").mkdir(parents=True) + (self.home / ".config/build-release" / "models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"})) origin, self.checkout = self.home / "origin.git", self.home / "code" / "proj" run_git(self.home, "init", "-q", "--bare", "-b", "main", str(origin)) run_git(self.home, "clone", "-q", str(origin), str(self.checkout)) @@ -278,7 +279,7 @@ class Main(unittest.TestCase): def test_keeps_each_reviewer_and_match_run_and_the_printed_report_in_one_folder_of_the_archive(self): code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}) self.assertEqual(code, 0, err) - folder = self.home / ".claude" / "loop-claude-transcripts" / "replays" / "review-replay-stability-claude-opus-5-5-20260921T141320Z" + folder = self.home / ".local/state/build-release" / "transcripts" / "replays" / "review-replay-stability-claude-opus-5-5-20260921T141320Z" self.assertEqual((folder / "result.md").read_text(encoding="utf-8"), out) runs = [json.loads(path.read_text(encoding="utf-8").splitlines()[0]) for path in folder.glob("*.jsonl")] # A run that repeats another word for word, as the fakes' do, is kept once. @@ -445,7 +446,7 @@ class Main(unittest.TestCase): def review_folder_with_round_1(self): """The chunk's review folder. The chunk began at 09:15 and the replayed round 2 at 10:00. It holds round 1's report, written at 09:15:00; round 2's report, written after 10:00; the prose pass's report, written at 10:00:00; and an earlier attempt's report, from before 09:15.""" - folder = self.home / ".local" / "state" / "larv-review" / "code" / "proj-x" + folder = self.home / ".local" / "state" / "build-release" / "larv-review" / "code" / "proj-x" folder.mkdir(parents=True) (folder / "stability-round-1.md").write_text("round 1\n") began = stamp_seconds("2026-10-14T09:15:00Z") @@ -469,7 +470,7 @@ class Main(unittest.TestCase): def test_copies_a_compressed_report_from_before_the_round_under_its_plain_name(self): folder = self.review_folder_with_round_1() self.assertIsNone(compress(folder / "stability-round-1.md")) - self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/larv-review/code/proj-x/stability-round-1.md.") + self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/build-release/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/build-release/larv-review/code/proj-x/stability-round-1.md.") seen = [] def review(rung): @@ -483,7 +484,7 @@ class Main(unittest.TestCase): def test_points_the_prompts_review_folder_at_a_copy_of_the_reports_from_before_the_round_that_it_removes(self): folder = self.review_folder_with_round_1() - self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/larv-review/code/proj-x/stability-round-1.md.") + self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/build-release/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/build-release/larv-review/code/proj-x/stability-round-1.md.") seen = [] def review(rung): @@ -512,9 +513,19 @@ class Main(unittest.TestCase): self.assertNotIn(str(folder), prompt) self.assertRegex(prompt, rf"report to {folder.parents[1]}/review-replay-\w+/stability-round-2\.md\.$") + def test_points_a_review_folder_named_where_it_was_before_0_18_at_the_copy(self): + folder = self.review_folder_with_round_1() + for spelling in (f"{self.home}/.local/state/larv-review", "~/.local/state/larv-review"): + with self.subTest(spelling=spelling): + self.reviews.clear() + self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to {spelling}/{folder.relative_to(folder.parents[1])}/stability-round-2.md.") + code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}) + self.assertEqual(code, 0, err) + self.assertRegex(self.reviews[0][4], rf"report to {folder.parents[1]}/review-replay-\w+/stability-round-2\.md\.$") + def test_replays_no_round_whose_prompt_still_names_the_review_folder_after_the_rewrite(self): self.review_folder_with_round_1() - self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to $HOME/.local/state/larv-review/code/proj-x/stability-round-2.md.") + self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to $HOME/.local/state/build-release/larv-review/code/proj-x/stability-round-2.md.") code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused) self.assertEqual(code, 0, err) self.assertEqual(self.reviews, []) @@ -527,7 +538,7 @@ class Main(unittest.TestCase): (folder / "branch.diff").write_text("the diff\n") before = stamp_seconds("2026-10-14T09:50:00Z") os.utime(folder / "branch.diff", (before, before)) - self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.") + self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/build-release/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/build-release/larv-review/code/proj-x/stability-round-2.md.") code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}) self.assertEqual(code, 0, err) self.assertRegex(self.reviews[0][4], rf"The diff is {folder.parents[1]}/review-replay-\w+/branch\.diff\.") @@ -535,7 +546,7 @@ class Main(unittest.TestCase): def test_replays_no_round_whose_prompt_names_an_input_the_folder_holds_only_as_rewritten_after_the_round_began(self): folder = self.review_folder_with_round_1() (folder / "branch.diff").write_text("a later diff\n") - self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.") + self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/build-release/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/build-release/larv-review/code/proj-x/stability-round-2.md.") code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused) self.assertEqual(code, 0, err) self.assertEqual(self.reviews, []) @@ -544,7 +555,7 @@ class Main(unittest.TestCase): def test_fails_the_replay_and_leaves_no_folder_behind_when_it_cannot_copy_the_reports(self): folder = self.review_folder_with_round_1() (folder / "stability-round-1.md").chmod(0) - self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.") + self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/build-release/larv-review/code/proj-x/stability-round-2.md.") scratch = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) self.limits["scratch"] = scratch code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused) diff --git a/bin/review_rules/review_folder.py b/bin/review_rules/review_folder.py index be2491a1..3a33f707 100644 --- a/bin/review_rules/review_folder.py +++ b/bin/review_rules/review_folder.py @@ -1,27 +1,31 @@ """The chunk's review folder, where each reviewer writes its report: skills/larv-review/SKILL.md → "Reports".""" +from collections.abc import Mapping import os import pathlib from failure import Failure from review_rules.round_titles import Findings, reported -from loop_state.paths import STATE_FOLDER +from loop_state.paths import state_folder # Why here: docs/decisions.md → `review: each reviewer under agents/ writes its full report into the chunk's review folder`. -REPORTS = f"{STATE_FOLDER}/larv-review" +def reports_folder(home: pathlib.Path, env: Mapping[str, str]) -> pathlib.Path: + """The folder that holds every chunk's review folder.""" + return state_folder(env, home) / "larv-review" -def review_folder(home: str, worktree: str) -> str: - """The review folder of the chunk whose worktree is at worktree: its path relative to home, or to / outside it, under REPORTS.""" +def review_folder(home: str, env: Mapping[str, str], worktree: str) -> str: + """The review folder of the chunk whose worktree is at worktree: its path relative to home, or to / outside it, under the reports folder.""" inside = worktree.startswith(home.rstrip("/") + "/") - return os.path.join(home, REPORTS, os.path.relpath(worktree, home) if inside else worktree.lstrip("/")) + return os.path.join(reports_folder(pathlib.Path(home), env), os.path.relpath(worktree, home) if inside else worktree.lstrip("/")) -def made_review_folder(worktree: str, home: pathlib.Path) -> pathlib.Path | Failure: - """Makes the review folder of the chunk whose worktree is at worktree, leaving REPORTS readable by the user alone, and returns its path.""" - folder = pathlib.Path(review_folder(str(home), worktree)) +def made_review_folder(worktree: str, home: pathlib.Path, env: Mapping[str, str]) -> pathlib.Path | Failure: + """Makes the review folder of the chunk whose worktree is at worktree, leaving the reports folder readable by the user alone, and returns its path.""" + folder = pathlib.Path(review_folder(str(home), env, worktree)) + reports = reports_folder(home, env) try: - (home / REPORTS).mkdir(parents=True, exist_ok=True) - (home / REPORTS).chmod(0o700) + reports.mkdir(parents=True, exist_ok=True) + reports.chmod(0o700) folder.mkdir(parents=True, exist_ok=True) except OSError as failure: return Failure(f"could not make the review folder {folder}: {failure}") diff --git a/bin/review_rules/test_review_folder.py b/bin/review_rules/test_review_folder.py index 8eb244de..b40892d2 100644 --- a/bin/review_rules/test_review_folder.py +++ b/bin/review_rules/test_review_folder.py @@ -12,11 +12,11 @@ from review_rules.review_folder import findings_in, review_folder, standing_repo class ReviewFolder(unittest.TestCase): def test_keys_a_worktree_under_home_by_its_path_relative_to_home(self): - self.assertEqual(review_folder("/h", "/h/code/proj-item-3"), "/h/.local/state/larv-review/code/proj-item-3") + self.assertEqual(review_folder("/h", {}, "/h/code/proj-item-3"), "/h/.local/state/build-release/larv-review/code/proj-item-3") def test_keys_a_worktree_outside_home_by_its_path_relative_to_the_root(self): - self.assertEqual(review_folder("/h", "/srv/proj-item-3"), "/h/.local/state/larv-review/srv/proj-item-3") - self.assertEqual(review_folder("/h", "/hx/proj"), "/h/.local/state/larv-review/hx/proj", "a sibling of home that shares its prefix is outside it") + self.assertEqual(review_folder("/h", {}, "/srv/proj-item-3"), "/h/.local/state/build-release/larv-review/srv/proj-item-3") + self.assertEqual(review_folder("/h", {}, "/hx/proj"), "/h/.local/state/build-release/larv-review/hx/proj", "a sibling of home that shares its prefix is outside it") class RoundReport(unittest.TestCase): diff --git a/bin/routing_figures/archive.py b/bin/routing_figures/archive.py index 4748774b..52744130 100644 --- a/bin/routing_figures/archive.py +++ b/bin/routing_figures/archive.py @@ -63,12 +63,12 @@ class ArchiveChunks: unread: tuple[str, ...] = () -def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> ArchiveChunks | Failure: +def measure_archive(root: pathlib.Path, home: str, env: typing.Mapping[str, str], since: str, git: Git) -> ArchiveChunks | Failure: """The figures of each chunk that finished after since, measured one chunk at a time because the archive outgrows memory. Only an archive that cannot be listed fails.""" listed = archived_outcomes(root) if isinstance(listed, Failure): return listed - projects = [measure_project(root, project, home, since, git) for project in sorted({root / key for key, _ in listed})] + projects = [measure_project(root, project, home, env, since, git) for project in sorted({root / key for key, _ in listed})] return ArchiveChunks( [chunk for project in projects for chunk in project.chunks], tuple(skipped for project in projects for skipped in project.skipped), @@ -76,7 +76,7 @@ def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> Arch ) -def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since: str, git: Git) -> ArchiveChunks: +def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, env: typing.Mapping[str, str], since: str, git: Git) -> ArchiveChunks: """The figures of each of one project's chunks that finished after since, as measure_archive measures them.""" key = str(project.relative_to(root)) listed = finished_chunks(project) @@ -86,11 +86,11 @@ def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since: if not chunks: return ArchiveChunks([], ()) checkout = checkout_of(key, pathlib.Path(home)) - titles = title_templates(checkout, pathlib.Path(home), functools.partial(git, timeout=GIT_TIMEOUT, guarded=True)) + titles = title_templates(checkout, pathlib.Path(home), env, functools.partial(git, timeout=GIT_TIMEOUT, guarded=True)) if isinstance(titles, Failure): # Read bare, a templated project's round titles would count as no round. return ArchiveChunks([], (), (f"{key}: none of its chunks is measured: {titles.reason}",)) - history = branch_history(checkout, pathlib.Path(home), titles, git) + history = branch_history(checkout, pathlib.Path(home), env, titles, git) found = [] skipped = [] for chunk in chunks: @@ -106,10 +106,10 @@ def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since: return ArchiveChunks(found, tuple(skipped), (f"{key}: {history.reason}",) if isinstance(history, Failure) else ()) -def branch_history(checkout: str, home: pathlib.Path, titles: Titles, git: Git) -> list[BranchChunk] | Failure: +def branch_history(checkout: str, home: pathlib.Path, env: typing.Mapping[str, str], titles: Titles, git: Git) -> list[BranchChunk] | Failure: """The chunks on the checkout's default branch as last fetched, each title read through titles, the project's title templates; read guarded, since the checkout's config may name a program. A Failure where the project's config under home puts the plan or a record where branch_chunks reads no commits.""" guarded = functools.partial(git, cwd=checkout, timeout=GIT_TIMEOUT, guarded=True) - if why := unsupported(checkout, home, guarded): + if why := unsupported(checkout, home, env, guarded): return Failure(f"its chunks' items and later fixes are not counted: {why}") ref = default_ref(checkout, GIT_TIMEOUT, guarded=True, run=git) return ref if isinstance(ref, Failure) else branch_chunks(ref, guarded, titles) diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index 61f251f6..ffd9b4c0 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -320,7 +320,7 @@ class BranchHistory(unittest.TestCase): folder = configured(self, checkout) config = folder / "config.toml" config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) - found = archive.branch_history(str(checkout), folder.parents[1], BARE, functools.partial(git_repo.git, env=isolated_env())) + found = archive.branch_history(str(checkout), folder.parents[2], {}, BARE, functools.partial(git_repo.git, env=isolated_env())) assert isinstance(found, Failure), found self.assertEqual(found.reason, f"its chunks' items and later fixes are not counted: the project's config puts {folder}/todo.md elsewhere than todo.md, docs/comprehension-history.md, docs/reading-cost.md in the checkout, the only paths whose commits are read so far") @@ -349,16 +349,16 @@ class Archive(unittest.TestCase): def test_measures_each_finished_chunk_keyed_by_its_project(self): self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")])) self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, "/h", "", no_checkout) + found = archive.measure_archive(self.root, "/h", {}, "", no_checkout) self.assertEqual([chunk.dollars["project"] for chunk in found.chunks], [{"home/x": 4.0}]) self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0}) - self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.ArchiveChunks([], ())) + self.assertEqual(archive.measure_archive(self.root, "/h", {}, "2026-10-14T10:00:00Z", no_checkout), archive.ArchiveChunks([], ())) def test_measures_a_chunk_whose_transcripts_are_compressed(self): self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")])) for copy in self.root.rglob("*.jsonl"): self.assertIsNone(compress(copy)) - found = archive.measure_archive(self.root, "/h", "", no_checkout) + found = archive.measure_archive(self.root, "/h", {}, "", no_checkout) self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0}) def test_counts_each_chunks_later_fixes_from_its_projects_checkout(self): @@ -366,7 +366,7 @@ class Archive(unittest.TestCase): env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)} self.ship_then_fix(home / "code" / "log", env) self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) + found = archive.measure_archive(self.root, str(home), {}, "", functools.partial(git_repo.git, env=env)) self.assertEqual([(chunk.dollars["project"].keys(), chunk.fixed_later) for chunk in found.chunks], [({"log": 0}.keys(), 1)]) def test_reads_a_projects_round_titles_and_its_branchs_history_through_its_configs_templates(self): @@ -377,9 +377,9 @@ class Archive(unittest.TestCase): config = write_config(home, home / "code" / "log") / "config.toml" worker = [message(f"m{n}", "2026-10-14T09:00:00Z", call("Bash", command=f"git commit -m '{round_title.format(n)}'")) for n in (1, 2)] self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), worker) - bare = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) + bare = archive.measure_archive(self.root, str(home), {}, "", functools.partial(git_repo.git, env=env)) config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\n') - templated = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) + templated = archive.measure_archive(self.root, str(home), {}, "", functools.partial(git_repo.git, env=env)) self.assertEqual([(chunk.rounds_past_first, chunk.fixed_later) for chunk in bare.chunks], [(0, 0)]) self.assertEqual([(chunk.rounds_past_first, chunk.fixed_later) for chunk in templated.chunks], [(1, 1)]) @@ -390,7 +390,7 @@ class Archive(unittest.TestCase): config = write_config(home, home / "code" / "log") / "config.toml" config.write_text(config.read_text() + 'commit-title = "PAY-{id}"\n') self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) + found = archive.measure_archive(self.root, str(home), {}, "", functools.partial(git_repo.git, env=env)) self.assertEqual(found.chunks, []) self.assertEqual(len(found.unread), 1) self.assertRegex(found.unread[0], r"^log: none of its chunks is measured: .*`commit-title` is 'PAY-\{id\}'") @@ -405,7 +405,7 @@ class Archive(unittest.TestCase): def recording(*args, **options): made.append((args[0], options)) return git_repo.git(*args, **options, env=env) - archive.measure_archive(self.root, str(home), "", recording) + archive.measure_archive(self.root, str(home), {}, "", recording) self.assertTrue(all(options.get("guarded") is True for _, options in made)) read = [options.get("timeout") for command, options in made if command in ("log", "ls-tree", "show", "diff", "blame")] self.assertEqual(set(read), {archive.GIT_TIMEOUT}) @@ -417,12 +417,12 @@ class Archive(unittest.TestCase): (home / "code" / "log").mkdir(parents=True) subprocess.run(["git", "init", "-q"], cwd=home / "code" / "log", check=True, env=env, capture_output=True) self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, str(home), "", functools.partial(git_repo.git, env=env)) + found = archive.measure_archive(self.root, str(home), {}, "", functools.partial(git_repo.git, env=env)) self.assertEqual(found.unread, ("log: no origin remote, and no main or master branch to take as the default branch",)) def test_names_each_project_whose_history_it_cannot_read(self): self.chunk("gone", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, "/h", "", no_checkout) + found = archive.measure_archive(self.root, "/h", {}, "", no_checkout) self.assertEqual(([chunk.fixed_later for chunk in found.chunks], found.unread), ([None], ("gone: no checkout",))) def ship_then_fix(self, checkout, env, fix_title="Fix six", ships_fix=True): @@ -457,7 +457,7 @@ class Archive(unittest.TestCase): self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000, replace=replace_file)) transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n") self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "m", "j"), 4070908800, replace=replace_file)) - (found,) = archive.measure_archive(kept, "/h", "", no_checkout).chunks + (found,) = archive.measure_archive(kept, "/h", {}, "", no_checkout).chunks self.assertEqual((found.start, found.unfinished), (LOW, 1)) self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 2.0}) @@ -467,7 +467,7 @@ class Archive(unittest.TestCase): self.chunk("other", "c2", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) self.chunk("broken", "c3", "", []) (self.root / "broken" / "c3" / "copy.outcomes.md").write_bytes(b"\xff") - found = archive.measure_archive(self.root, "/h", "", no_checkout) + found = archive.measure_archive(self.root, "/h", {}, "", no_checkout) self.assertEqual((len(found.chunks), found.skipped), (1, ("broken", "log/c1"))) self.assertIn("## Chunks skipped, unreadable\n\n- log/c1\n", render(LADDER, totals([], ("log/c1",)), [], "2026-10-15T00:00:00Z", 20, "")) diff --git a/bin/rule_hook/env_file.py b/bin/rule_hook/env_file.py index 294de2d1..5b451e83 100644 --- a/bin/rule_hook/env_file.py +++ b/bin/rule_hook/env_file.py @@ -22,9 +22,9 @@ NAMES = "the command names {}, a file of credentials that must stay out of the t SEARCHES = "the command searches a folder holding {}, a file of credentials that must stay out of the transcript; search a folder without it" -def env_file_breaches(call: Call, home: str) -> list[Breach]: +def env_file_breaches(call: Call, home: str, env: typing.Mapping[str, str]) -> list[Breach]: guarded: dict[str, pathlib.Path] = {} - for path in (pathlib.Path(home, CLAUDE_HOME, ".env"), *env_files(pathlib.Path(home))): + for path in (pathlib.Path(home, CLAUDE_HOME, ".env"), *env_files(pathlib.Path(home), env)): if path.is_file(): # Several configs may name one file: it is checked, and reported, once. guarded.setdefault(os.path.realpath(path), path) diff --git a/bin/rule_hook/main.py b/bin/rule_hook/main.py index 24d75366..3e2d848c 100644 --- a/bin/rule_hook/main.py +++ b/bin/rule_hook/main.py @@ -99,18 +99,18 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup return text(call.given, "args"), text(call.given, "skill"), skill_breaches(call, environ, home) if call.tool in COMMAND_TOOLS: command = text(call.given, "command") - return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home, call.tool == "Monitor") + read_breaches(call, home) + env_file_breaches(call, home) + return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home, environ, call.tool == "Monitor") + read_breaches(call, home) + env_file_breaches(call, home, environ) if call.tool == "Read": - return "", text(call.given, "file_path"), read_breaches(call, home) + env_file_breaches(call, home) + transcript_breaches(call, home) + return "", text(call.given, "file_path"), read_breaches(call, home) + env_file_breaches(call, home, environ) + transcript_breaches(call, home) if call.tool == "Grep": # Only env-file-read checks a Grep, and it takes no override, so no marker or log line concerns the call. - return "", "", env_file_breaches(call, home) + return "", "", env_file_breaches(call, home, environ) path = text(call.given, "file_path") if call.tool not in FILE_TOOLS or not path: return None before = read(path) added, after = applied(call, before) - return added, path, report_breaches(call, path, home) + file_breaches(path, before, added, after) + return added, path, report_breaches(call, path, home, environ) + file_breaches(path, before, added, after) def answer(checked: Checked, what: str, now: float) -> int: @@ -130,25 +130,25 @@ def answer(checked: Checked, what: str, now: float) -> int: return 2 if unloggable else 0 -def bash_breaches(command: str, cwd: str, home: str, monitor: bool = False) -> list[Breach]: +def bash_breaches(command: str, cwd: str, home: str, env: typing.Mapping[str, str], monitor: bool = False) -> list[Breach]: """The breaches of the command's own words, then of each commit it makes, then of the files those commits may take.""" simples = simple_commands(command, cwd, home) found = commits(simples, home) - in_commits = [breach for commit in found for breach in commit_breaches(commit, pathlib.Path(home))] + in_commits = [breach for commit in found for breach in commit_breaches(commit, pathlib.Path(home), env)] in_files = [breach for directory in dict.fromkeys(commit.directory for commit in found) for breach in committed_file_breaches(directory)] return command_breaches(command, simples, monitor) + in_commits + in_files -def commit_breaches(commit: CommitCall, home: pathlib.Path) -> list[Breach]: +def commit_breaches(commit: CommitCall, home: pathlib.Path, env: typing.Mapping[str, str]) -> list[Breach]: """The breaches of one commit: its title's and its round's, read through the title templates of the project's config, and its plan's. A config that cannot be read is a breach itself, since no title can then be checked.""" - config = located(commit.directory, home, functools.partial(git, guarded=True)) + config = located(commit.directory, home, env, functools.partial(git, guarded=True)) unread = [] if isinstance(config, Failure) and not isinstance(config, Unnamed): unread = [Breach("commit-title", f"the project's config cannot be read, so the title is not checked against its template: {config.reason}", commit.directory)] titles = config.titles if isinstance(config, ProjectConfig) else templates.BARE # A checkout no config names has no branch template, so no title of its must fit one. branch = checkout_branch(commit.directory) if isinstance(config, ProjectConfig) else None - return unread + title_breaches(commit, titles, config.branch if isinstance(config, ProjectConfig) else templates.BRANCH, branch) + round_cap_breaches(commit, titles) + round_report_breaches(commit, titles, home) + todo_breaches(commit.directory, home) + return unread + title_breaches(commit, titles, config.branch if isinstance(config, ProjectConfig) else templates.BRANCH, branch) + round_cap_breaches(commit, titles) + round_report_breaches(commit, titles, home, env) + todo_breaches(commit.directory, home, env) def checkout_branch(directory: str) -> str | None: diff --git a/bin/rule_hook/reviewer_report.py b/bin/rule_hook/reviewer_report.py index 63001fa4..931ed8ba 100644 --- a/bin/rule_hook/reviewer_report.py +++ b/bin/rule_hook/reviewer_report.py @@ -1,21 +1,23 @@ """Refuse a reviewer's file call other than a Write of its report into the reports folder: skills/larv-review/review-findings.md → "Report".""" +from collections.abc import Mapping import os +import pathlib from rule_hook.rules import Breach from rule_hook.call import Call from loop_state.paths import RELEASE_ROOT -from review_rules.review_folder import REPORTS +from review_rules.review_folder import reports_folder # Each agent under agents/, read from the folder, so an agent the routing tables miss is still confined. AGENT_FILES = frozenset(path.stem for path in (RELEASE_ROOT / "agents").glob("*.md")) -def report_breaches(call: Call, path: str, home: str) -> list[Breach]: - """The breach of a file call from a reviewer that is not a Write under REPORTS in home; none from any other agent.""" +def report_breaches(call: Call, path: str, home: str, env: Mapping[str, str]) -> list[Breach]: + """The breach of a file call from a reviewer that is not a Write under the reports folder; none from any other agent.""" if call.agent not in AGENT_FILES: return [] written = os.path.realpath(os.path.join(call.cwd, path)) - reports = os.path.realpath(os.path.join(home, REPORTS)) + reports = os.path.realpath(reports_folder(pathlib.Path(home), env)) if call.tool == "Write" and written.startswith(reports + "/"): return [] return [Breach("reviewer-report", f"{call.agent} would {call.tool.lower()} {written}; write your report with Write to the path your prompt names, under {reports}/", call.cwd)] diff --git a/bin/rule_hook/reviewer_rung.py b/bin/rule_hook/reviewer_rung.py index 83ebdc13..266cc11b 100644 --- a/bin/rule_hook/reviewer_rung.py +++ b/bin/rule_hook/reviewer_rung.py @@ -30,7 +30,7 @@ def reviewer_breaches(call: Call, environ: typing.Mapping[str, str], home: str) kind = review_kind(call.given) if kind is None or not hands_rungs(environ): return [] - ladder = project_ladder(call.cwd, pathlib.Path(home)) + ladder = project_ladder(call.cwd, pathlib.Path(home), environ) if isinstance(ladder, Failure): return [unread(ladder, call.cwd)] project, worker, escape_and_impact = handed(environ, ladder) @@ -56,7 +56,7 @@ def skill_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> skill = text(call.given, "skill").lstrip("/").rsplit(":", 1)[-1] if skill not in SECURITY_SKILLS or not hands_rungs(environ) or opening_prompt(call.transcript).startswith(SECURITY_OPENER): return [] - ladder = project_ladder(call.cwd, pathlib.Path(home)) + ladder = project_ladder(call.cwd, pathlib.Path(home), environ) if isinstance(ladder, Failure): return [unread(ladder, call.cwd)] project, worker, _ = handed(environ, ladder) diff --git a/bin/rule_hook/round_report.py b/bin/rule_hook/round_report.py index c500135e..b2da8a51 100644 --- a/bin/rule_hook/round_report.py +++ b/bin/rule_hook/round_report.py @@ -1,4 +1,5 @@ """rule-hook's check of a round commit's counts against the round's report in the chunk's review folder.""" +from collections.abc import Mapping import pathlib from rule_hook.rules import Breach @@ -10,7 +11,7 @@ from review_rules.round_titles import ROUND, round_prefix, title_counts from project_config.templates import Titles -def round_report_breaches(commit: CommitCall, titles: Titles, home: pathlib.Path) -> list[Breach]: +def round_report_breaches(commit: CommitCall, titles: Titles, home: pathlib.Path, env: Mapping[str, str]) -> list[Breach]: """A breach for each round title whose counts differ from those its round's report gives. The round title is the commit title's summary, as `titles` cuts it. A title without all three counts is title_breaches' to refuse. A round whose report is missing or unreadable, or says BLOCK without a finding heading, goes through, as does every round where git cannot name the commit's checkout within 5 seconds.""" summaries = [titles.summary(message.strip()) for message in commit.messages] rounds = [(named, counts) for summary in summaries if (named := ROUND.match(summary)) and (counts := title_counts(summary)) and counts.misread is not None] @@ -19,7 +20,7 @@ def round_report_breaches(commit: CommitCall, titles: Titles, home: pathlib.Path worktree = git("rev-parse", "--show-toplevel", cwd=commit.directory, timeout=5, guarded=True) if isinstance(worktree, Failure): return [] - folder = pathlib.Path(review_folder(str(home), worktree.strip())) + folder = pathlib.Path(review_folder(str(home), env, worktree.strip())) breaches = [] for named, counts in rounds: pass_, round_ = named.group(1).lower(), int(named.group(2)) diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index ce355168..8354bf8d 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -9,7 +9,6 @@ from rule_hook.endless_wait import endless_waits from run_heavy.capped_docker import finds_this_docker from rule_hook.heavy_command import heavy from command_lines.shell_command import launched, LAUNCHERS, Simple -from review_rules.review_folder import REPORTS from project_config import templates from command_lines.docker_command import unlimited @@ -48,7 +47,7 @@ RULES: dict[RuleName, Rule] = { # A marker would let the credentials into the transcript all the same, so no marker waives it. "env-file-read": Rule( "an agent never reads ~/.claude/.env or a project's env-file, the file of credentials the project's config names, since a value the agent reads lands in its transcript, which build-release archives and the backups copy; it leaves a tool that needs a credential to read the file itself, gets the file's path from `project-config env-file`, and spells the path another way, such as \"the .env in ~/.claude\", in a command that must mention it without reading it, such as a commit's title, and searches only a folder without it", - "against ~/.claude/.env and the env-file of every config under ~/.claude-projects: a Read of one; a Grep of one, or of a folder holding one, unless a checkout ignores the file and the Grep's glob cannot match it; and a Bash command that spells one's path, or names it in a word or a redirect's target from the directory `cd` left the command in, whether or not the command reads it; and a Bash command that runs `ag`, `grep -r` or `rg` over a folder holding one, or over the directory `cd` left the command in where it names no folder, unless the tool skips the file: `ag` and `rg` skip a hidden file, one below a hidden folder of the search and one a checkout ignores, and `rg` one that none of its globs matches", + "against ~/.claude/.env and the env-file of every config under ~/.config/build-release: a Read of one; a Grep of one, or of a folder holding one, unless a checkout ignores the file and the Grep's glob cannot match it; and a Bash command that spells one's path, or names it in a word or a redirect's target from the directory `cd` left the command in, whether or not the command reads it; and a Bash command that runs `ag`, `grep -r` or `rg` over a folder holding one, or over the directory `cd` left the command in where it names no folder, unless the tool skips the file: `ag` and `rg` skip a hidden file, one below a hidden folder of the search and one a checkout ignores, and `rg` one that none of its globs matches", overridable=False, ), "ignorefile-sorted": Rule( @@ -71,7 +70,7 @@ RULES: dict[RuleName, Rule] = { ), # A reviewer only reports, so no marker waives it. "reviewer-report": Rule( - f"a reviewer writes only its report, with Write, into a file under ~/{REPORTS}/", + "a reviewer writes only its report, with Write, into a file under the review reports folder, ~/.local/state/build-release/larv-review/ unless `XDG_STATE_HOME` is set", "a Write, Edit or MultiEdit call from inside an agent under agents/", overridable=False, ), @@ -97,7 +96,7 @@ RULES: dict[RuleName, Rule] = { ), "todo-rank-check": Rule( "while todo.md has changes, staged or not, a git commit waits until rank_todo.py --check passes on it: the checkout's own bin/rank_todo.py where the checkout is of this setup's repo, else the release's", - "a git commit in a checkout whose todo.md has changes, and every git commit where the project's config puts todo.md outside the checkout, where the checkout's commits don't say whether it changed; and a git commit in the config's folder, `~/.claude-projects/<key>/`, whose todo.md has changes", + "a git commit in a checkout whose todo.md has changes, and every git commit where the project's config puts todo.md outside the checkout, where the checkout's commits don't say whether it changed; and a git commit in the config's folder, `~/.config/build-release/<key>/`, whose todo.md has changes", ), # A Read carries no text for a marker, so no marker waives it. "transcript-read": Rule( diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index d9def82f..98f35529 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -426,7 +426,7 @@ class ReviewerRung(unittest.TestCase): def test_a_review_is_refused_where_the_projects_ladder_cannot_be_read_and_build_release_handed_rungs(self): checkout, home = self.project("[]") - own = pathlib.Path(home, ".claude-projects", "acme", "routing-ladder.json") + own = pathlib.Path(home, ".config/build-release", "acme", "routing-ladder.json") reviewer = Call("Agent", {"subagent_type": "stability-reviewer", "model": "fable", "effort": "max"}, checkout) for breaches in (reviewer_breaches(reviewer, self.ON_TWO_RUNGS, home), skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), self.ON_TWO_RUNGS, home)): self.assertEqual(rules(breaches), ["reviewer-rung"]) @@ -491,7 +491,7 @@ class EnvFileRead(unittest.TestCase): (self.home / ".claude").mkdir() (self.home / ".claude" / ".env").write_text("TOKEN=x\n") write_config(self.home, self.home / "code" / "acme") - config = self.home / ".claude-projects" / "acme" / "config.toml" + config = self.home / ".config/build-release" / "acme" / "config.toml" config.write_text(config.read_text() + 'env-file = "~/secrets/acme.env"\n') (self.home / "secrets").mkdir() (self.home / "secrets" / "acme.env").write_text("TOKEN=y\n") @@ -504,6 +504,26 @@ class EnvFileRead(unittest.TestCase): self.assertEqual(self.breached("Read", {"file_path": f"{self.home}/.claude/.env"}), ["env-file-read"]) self.assertEqual(self.breached("Read", {"file_path": "acme.env"}, f"{self.home}/secrets"), ["env-file-read"]) + def test_a_config_under_xdg_config_home_names_the_env_file_in_place_of_one_under_home(self): + moved = self.home / "xdg" / "build-release" / "other" + moved.mkdir(parents=True) + (moved / "config.toml").write_text((self.home / ".config/build-release" / "acme" / "config.toml").read_text().replace("acme", "other")) + env = {"XDG_CONFIG_HOME": str(self.home / "xdg")} + (self.home / "secrets" / "other.env").write_text("TOKEN=z\n") + + def refused(name: str) -> bool: + found = breaches_of(Call("Read", {"file_path": f"{self.home}/secrets/{name}.env"}, "/r"), str(self.home), env) + return bool(found) and "env-file-read" in rules(found[2]) + + self.assertEqual((refused("other"), refused("acme")), (True, False)) + + def test_a_config_in_the_folder_of_before_0_18_names_no_env_file(self): + old = self.home / ".claude-projects" / "old" + old.mkdir(parents=True) + (old / "config.toml").write_text((self.home / ".config/build-release" / "acme" / "config.toml").read_text().replace("acme", "old")) + (self.home / "secrets" / "old.env").write_text("TOKEN=z\n") + self.assertEqual(self.breached("Read", {"file_path": f"{self.home}/secrets/old.env"}), []) + def test_a_read_spelt_from_home_is_refused_naming_the_file(self): found = breaches_of(Call("Read", {"file_path": "~/.claude/.env"}, "/r"), str(self.home), {}) self.assertEqual([breach.detail for breach in found[2]], [f"the call reads {self.home}/.claude/.env, whose credentials would land in the transcript"]) @@ -627,7 +647,7 @@ class EnvFileRead(unittest.TestCase): def test_a_folder_that_starts_with_a_dash_is_searched_after_double_dash(self): write_config(self.home, self.home / "code" / "other") - config = self.home / ".claude-projects" / "other" / "config.toml" + config = self.home / ".config/build-release" / "other" / "config.toml" config.write_text(config.read_text() + 'env-file = "~/real/x.env"\n') (self.home / "real").mkdir() (self.home / "real" / "x.env").write_text("TOKEN=z\n") @@ -644,10 +664,10 @@ class EnvFileRead(unittest.TestCase): def test_a_search_that_starts_in_a_hidden_folder_reaches_a_visible_file_below_it(self): write_config(self.home, self.home / "code" / "other") - config = self.home / ".claude-projects" / "other" / "config.toml" - config.write_text(config.read_text() + 'env-file = "~/.claude-projects/other.env"\n') - (self.home / ".claude-projects" / "other.env").write_text("TOKEN=z\n") - for command, expected in (("rg TOKEN ~/.claude-projects", ["env-file-read"]), ("ag TOKEN ~/.claude-projects", ["env-file-read"]), ("grep -r TOKEN ~/.claude-projects", ["env-file-read"])): + config = self.home / ".config/build-release" / "other" / "config.toml" + config.write_text(config.read_text() + 'env-file = "~/.config/build-release/other.env"\n') + (self.home / ".config/build-release" / "other.env").write_text("TOKEN=z\n") + for command, expected in (("rg TOKEN ~/.config/build-release", ["env-file-read"]), ("ag TOKEN ~/.config/build-release", ["env-file-read"]), ("grep -r TOKEN ~/.config/build-release", ["env-file-read"])): with self.subTest(command): self.assertEqual(self.breached("Bash", {"command": command}), expected) (self.home / "code").mkdir() @@ -655,7 +675,7 @@ class EnvFileRead(unittest.TestCase): def test_rg_and_ag_skip_a_file_below_any_hidden_folder_of_the_search(self): write_config(self.home, self.home / "code" / "other") - config = self.home / ".claude-projects" / "other" / "config.toml" + config = self.home / ".config/build-release" / "other" / "config.toml" config.write_text(config.read_text() + 'env-file = "~/outer/deep/.h/b.env"\n') (self.home / "outer" / "deep" / ".h").mkdir(parents=True) (self.home / "outer" / "deep" / ".h" / "b.env").write_text("TOKEN=z\n") @@ -692,7 +712,7 @@ class EnvFileRead(unittest.TestCase): def test_a_file_several_configs_name_is_reported_once(self): write_config(self.home, self.home / "code" / "other") - config = self.home / ".claude-projects" / "other" / "config.toml" + config = self.home / ".config/build-release" / "other" / "config.toml" config.write_text(config.read_text() + 'env-file = "~/secrets/../secrets/acme.env"\n') found = breaches_of(Call("Read", {"file_path": "~/secrets/acme.env"}, "/r"), str(self.home), {}) self.assertEqual(len([breach for breach in found[2] if breach.rule == "env-file-read"]), 1) @@ -708,25 +728,25 @@ class ReviewerReport(unittest.TestCase): return rules(found[2]) if found else [] def test_a_reviewer_writes_its_report_into_the_reports_folder(self): - self.assertEqual(self.breached("Write", "/h/.local/state/larv-review/.claude-item-73/prose-round-1.md"), []) + self.assertEqual(self.breached("Write", "/h/.local/state/build-release/larv-review/.claude-item-73/prose-round-1.md"), []) def test_a_relative_path_resolves_against_the_calls_cwd(self): - self.assertEqual(self.breached("Write", "prose-round-1.md", cwd="/h/.local/state/larv-review/x"), []) + self.assertEqual(self.breached("Write", "prose-round-1.md", cwd="/h/.local/state/build-release/larv-review/x"), []) def test_a_symlink_in_the_reports_folder_is_followed_to_where_it_points(self): home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) - (home / ".local" / "state" / "larv-review").mkdir(parents=True) - (home / ".local" / "state" / "larv-review" / "out").symlink_to(home) - found = breaches_of(Call("Write", {"file_path": f"{home}/.local/state/larv-review/out/a.md", "content": "x"}, "/r", "prose-reviewer"), str(home), {}) + (home / ".local" / "state" / "build-release" / "larv-review").mkdir(parents=True) + (home / ".local" / "state" / "build-release" / "larv-review" / "out").symlink_to(home) + found = breaches_of(Call("Write", {"file_path": f"{home}/.local/state/build-release/larv-review/out/a.md", "content": "x"}, "/r", "prose-reviewer"), str(home), {}) self.assertEqual(rules(found[2]), ["reviewer-report"]) def test_a_reviewer_writing_anywhere_else_is_refused(self): - for path in ["/r/README.md", "/h/.local/state/larv-review", "/h/.local/state/larv-review-x/a.md", "/h/.local/state/larv-review/../a.md", "/tmp/larv-review/a.md"]: + for path in ["/r/README.md", "/h/.local/state/build-release/larv-review", "/h/.local/state/build-release/larv-review-x/a.md", "/h/.local/state/build-release/larv-review/../a.md", "/tmp/larv-review/a.md"]: with self.subTest(path): self.assertEqual(self.breached("Write", path), ["reviewer-report"]) def test_a_reviewer_edits_no_file_even_in_the_reports_folder(self): - self.assertEqual(self.breached("Edit", "/h/.local/state/larv-review/x/prose-round-1.md"), ["reviewer-report"]) + self.assertEqual(self.breached("Edit", "/h/.local/state/build-release/larv-review/x/prose-round-1.md"), ["reviewer-report"]) def test_a_reviewers_multiedit_is_refused(self): self.assertEqual(self.breached("MultiEdit", "/r/a.py", "stability-reviewer"), ["reviewer-report"]) @@ -989,7 +1009,7 @@ class Hook(unittest.TestCase): def configured(self) -> pathlib.Path: folder = configured(self, pathlib.Path(self.repo)) - self.env = {"HOME": str(folder.parents[1])} + self.env = {"HOME": str(folder.parents[2])} return folder def test_runs_git_guarded(self): @@ -1102,7 +1122,7 @@ class Hook(unittest.TestCase): ran = hook(call, self.repo) self.assertEqual(ran.returncode, 2) self.assertIn("Blocked by rule reviewer-report: prose-reviewer would write ", ran.stderr) - self.assertIn("/.local/state/larv-review/", ran.stderr) + self.assertIn("/.local/state/build-release/larv-review/", ran.stderr) self.assertNotIn("rule-override", ran.stderr) def test_a_commit_override_is_logged_in_the_commit_s_checkout(self): @@ -1123,7 +1143,7 @@ class Hook(unittest.TestCase): def test_a_round_commit_whose_counts_differ_from_its_report_is_refused(self): home = tempfile.mkdtemp() self.addCleanup(subprocess.run, ["rm", "-rf", home]) - folder = pathlib.Path(home, ".local", "state", "larv-review", self.repo.lstrip("/")) + folder = pathlib.Path(home, ".local", "state", "build-release", "larv-review", self.repo.lstrip("/")) folder.mkdir(parents=True) (folder / "stability-round-1.md").write_text("BLOCK\n\n### 🔴 [misread] `a.py:1`: wrong\n\n### 🟡 `b.py:2`: worse\n") @@ -1325,7 +1345,7 @@ class TodoRankCheck(unittest.TestCase): pathlib.Path(checkout, "bin", "rank_todo.py").write_text(stub) pathlib.Path(checkout, "todo.md").write_text("# todo\n") self.config = configured(self, pathlib.Path(checkout)) / "config.toml" - self.home = self.config.parents[2] + self.home = self.config.parents[3] return checkout def test_a_changed_plan_that_cannot_be_read_is_a_breach(self): @@ -1335,15 +1355,15 @@ class TodoRankCheck(unittest.TestCase): self.assertEqual(["Permission denied" in detail for detail in self.details(checkout)], [True]) def details(self, checkout: str, **limit: float) -> list[str]: - return [breach.detail for breach in todo_breaches(checkout, self.home, pathlib.Path(self.own), **limit)] + return [breach.detail for breach in todo_breaches(checkout, self.home, {}, pathlib.Path(self.own), **limit)] def test_a_checkout_of_the_hooks_repo_runs_its_own_rank_todo(self): checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) self.assertEqual(self.details(checkout), [f"own script checked {checkout}/todo.md"]) top = str(pathlib.Path(checkout).resolve()) - self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, self.home, pathlib.Path(self.own))], [("todo-rank-check", top)]) + self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, self.home, {}, pathlib.Path(self.own))], [("todo-rank-check", top)]) self.config.unlink() - self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, self.home, pathlib.Path(self.own))], [("todo-rank-check", top)], "a todo.md with no config") + self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(checkout, self.home, {}, pathlib.Path(self.own))], [("todo-rank-check", top)], "a todo.md with no config") def test_its_own_rank_todo_passing_passes(self): self.assertEqual(self.details(self.changed_plan(f"{self.folder}/clone", "")), []) @@ -1384,7 +1404,7 @@ class TodoRankCheck(unittest.TestCase): self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) (self.config.parent / "todo.md").write_text("# todo\n") self.assertEqual(self.details(folder), [f"own script checked {folder}/todo.md"], "checked with the checkout's own rank_todo.py, as a commit there would be") - self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(folder, self.home, pathlib.Path(self.own))], [("todo-rank-check", str(pathlib.Path(folder).resolve()))]) + self.assertEqual([(breach.rule, breach.directory) for breach in todo_breaches(folder, self.home, {}, pathlib.Path(self.own))], [("todo-rank-check", str(pathlib.Path(folder).resolve()))]) git(folder, "add", "-A") git(folder, "commit", "-q", "-m", "plan") self.assertEqual(self.details(folder), [], "committed, so unchanged") @@ -1420,7 +1440,7 @@ class TodoRankCheck(unittest.TestCase): def test_a_checkout_with_a_changed_todo_md_and_no_config_is_told_to_write_one(self): checkout = self.changed_plan(self.other, self.STUB) self.config.unlink() - self.assertEqual(self.details(checkout), [f"no config names the checkout {checkout}: write ~/.claude-projects/<key>/config.toml, as `project-config --help` shows"]) + self.assertEqual(self.details(checkout), [f"no config names the checkout {checkout}: write {self.home}/.config/build-release/<key>/config.toml, as `project-config --help` shows"]) git(checkout, "add", "todo.md") git(checkout, "commit", "-q", "-m", "plan") self.assertEqual(self.details(checkout), [], "a commit that leaves todo.md alone, as in a clone of someone else's project, is not held") @@ -1591,7 +1611,7 @@ class TranscriptRead(unittest.TestCase): def test_a_jsonl_file_outside_the_projects_folder_passes(self): self.assertEqual(self.breached("Read", {"file_path": "/home/h/code/acme/cases.jsonl"}), []) - self.assertEqual(self.breached("Read", {"file_path": "/home/h/.claude/loop-claude-transcripts/x.jsonl"}), []) + self.assertEqual(self.breached("Read", {"file_path": "/home/h/.local/state/build-release/transcripts/x.jsonl"}), []) def test_a_search_of_a_transcript_is_not_checked(self): self.assertEqual(self.breached("Grep", {"pattern": "x", "path": self.TRANSCRIPT}), []) diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index 06b233d0..87ccd4fd 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -1,5 +1,6 @@ import functools import hashlib +from collections.abc import Mapping import pathlib import subprocess import sys @@ -20,15 +21,15 @@ OWN = RELEASE_ROOT OWN_CHECK_SECONDS = 20 -def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN, seconds: float = OWN_CHECK_SECONDS) -> list[Breach]: +def todo_breaches(directory: str, home: pathlib.Path, env: Mapping[str, str], own: pathlib.Path = OWN, seconds: float = OWN_CHECK_SECONDS) -> list[Breach]: """Why the plan of directory's project is not ranked, where the plan has changed; the plan is the todo.md its config names. directory may also be in a config's folder, a git repo of its own.""" top = guarded_git(directory, "rev-parse", "--show-toplevel") if isinstance(top, Failure): return [] - held_here = held(pathlib.Path(top), home) + held_here = held(pathlib.Path(top), home, env) if held_here is not None: return folder_breaches(top, held_here, own, seconds) - config = located(top, home, functools.partial(git, guarded=True)) + config = located(top, home, env, functools.partial(git, guarded=True)) if isinstance(config, Failure): # A checkout whose todo.md changes with no config is one whose config is still to write. An unchanged todo.md may be a third party's, whose clone needs no config. unconfigured = pathlib.Path(top) / "todo.md" diff --git a/bin/run_heavy/main.py b/bin/run_heavy/main.py index 4b12e509..ff08bdff 100644 --- a/bin/run_heavy/main.py +++ b/bin/run_heavy/main.py @@ -5,7 +5,7 @@ usage: run-heavy <command> [<arg>...] A heavy command is one that loads the machine for minutes: a full gate, mutation tests, an e2e run, a docker build. The machine has one heavy slot for every 4 CPUs that run-heavy may use, and at least one, shared by every session that runs run-heavy. Each slot is a file locked with flock, under -$XDG_STATE_HOME/run-heavy (default ~/.local/state/run-heavy). While every slot is held, run-heavy +$XDG_STATE_HOME/build-release/run-heavy (default ~/.local/state/build-release/run-heavy). While every slot is held, run-heavy says so once on stderr and waits. It then replaces itself with the command. The slot's lock stays held until the command, and every process that inherited the lock, exits. Its exit code is the command's. diff --git a/bin/run_heavy/test_run_heavy.py b/bin/run_heavy/test_run_heavy.py index c64b55b7..4e193d7b 100644 --- a/bin/run_heavy/test_run_heavy.py +++ b/bin/run_heavy/test_run_heavy.py @@ -22,7 +22,7 @@ class RunHeavy(unittest.TestCase): self.addCleanup(state.cleanup) self.env = {**os.environ, "XDG_STATE_HOME": state.name} self.env.pop(main.HELD, None) - self.slots = pathlib.Path(state.name) / "run-heavy" + self.slots = pathlib.Path(state.name) / "build-release" / "run-heavy" def run_tool(self, *args: str, env=None) -> subprocess.CompletedProcess[str]: return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True, env=env or self.env, timeout=30) diff --git a/bin/rung_replay/command.py b/bin/rung_replay/command.py index 4c137bda..21b8de54 100644 --- a/bin/rung_replay/command.py +++ b/bin/rung_replay/command.py @@ -25,9 +25,9 @@ def arguments_or_exit(tool: str, argv: list[str], help_text: str, usage: str, re return arguments -def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure: +def projects_on(model: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> list[str] | Failure: """The keys of the projects build-release's models file, under home, runs on model, sorted.""" - models = read_models_file(paths_from(home).models_file) + models = read_models_file(paths_from(home, env).models_file) if isinstance(models, Failure): return models return sorted(key for key, on in models.items() if on == model) diff --git a/bin/score-outcomes b/bin/score-outcomes index f29ff785..e2cc6c01 100755 --- a/bin/score-outcomes +++ b/bin/score-outcomes @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import os import pathlib import sys @@ -6,4 +7,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from score_outcomes import main -sys.exit(main.main(sys.argv[1:], pathlib.Path.home())) +sys.exit(main.main(sys.argv[1:], pathlib.Path.home(), os.environ)) diff --git a/bin/score_outcomes/main.py b/bin/score_outcomes/main.py index 527c7b0b..daada110 100644 --- a/bin/score_outcomes/main.py +++ b/bin/score_outcomes/main.py @@ -88,6 +88,7 @@ clone, or the default branch cannot be read; or, after the rest of the report, w build-release's archive cannot be read. """ import functools +from collections.abc import Mapping import os import pathlib import re @@ -119,7 +120,7 @@ UNMERGED = [ ] -def main(argv: list[str], home: pathlib.Path) -> int: +def main(argv: list[str], home: pathlib.Path, env: Mapping[str, str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 @@ -133,10 +134,10 @@ def main(argv: list[str], home: pathlib.Path) -> int: default, note = found if note: print(f"score-outcomes: {note}", file=sys.stderr) - results = read_results(default, home) + results = read_results(default, home, env) if isinstance(results, Failure): return failed(results) - anchored = read_anchors(home) + anchored = read_anchors(home, env) reversal = read_reversals(home) print(report_text(results, anchored, dict(zip(GIVEN, map(int, argv))) if argv else None, reversal)) unread = [found for found in (anchored, reversal) if isinstance(found, Failure)] @@ -167,9 +168,9 @@ def failed(failure: Failure) -> int: return 1 -def read_anchors(home: pathlib.Path) -> Anchors | Failure: +def read_anchors(home: pathlib.Path, env: Mapping[str, str]) -> Anchors | Failure: """The project's anchors as they stand in the store its config names, so a branch that edits them shows its edit; none where it keeps none.""" - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config text = store(config, "score-anchors").read() @@ -184,17 +185,17 @@ def read_reversals(home: pathlib.Path) -> list[str] | Failure: return reversal_lines(project_archive(str(pathlib.Path(common.strip()).parent), home, os.environ)) -def read_results(default: str, home: pathlib.Path) -> list[Result] | Failure: +def read_results(default: str, home: pathlib.Path, env: Mapping[str, str]) -> list[Result] | Failure: """What each chunk on the default branch's first-parent line measured.""" if partial := full_history(): return partial - if why := unsupported(None, home): + if why := unsupported(None, home, env): return Failure(f"this project is not supported yet: {why}") root = top() if isinstance(root, Failure): return root run = functools.partial(git, cwd=root) - templates = title_templates(None, home) + templates = title_templates(None, home, env) if isinstance(templates, Failure): return templates chunks = branch_chunks(default, run, templates) diff --git a/bin/score_outcomes/test_score_outcomes.py b/bin/score_outcomes/test_score_outcomes.py index d2438307..b18e6847 100644 --- a/bin/score_outcomes/test_score_outcomes.py +++ b/bin/score_outcomes/test_score_outcomes.py @@ -316,7 +316,7 @@ class ScoreOutcomesTool(unittest.TestCase): return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.checkout, env=self.env, text=True) def test_says_it_does_not_support_a_plan_outside_the_checkout_and_reads_the_anchors_where_the_config_puts_them(self): - config = pathlib.Path(self.env["HOME"], ".claude-projects", "proj", "config.toml") + config = pathlib.Path(self.env["HOME"], ".config/build-release", "proj", "config.toml") config.write_text(config.read_text().replace('"checkout:docs/score-anchors.md"', '"folder:score-anchors.md"')) (config.parent / "score-anchors.md").write_text("| Level | Items |\n|---|---|\n| L 9 | 1 |\n") ran = self.run_tool() @@ -438,7 +438,7 @@ class ScoreOutcomesTool(unittest.TestCase): self.assertNotIn("by rebase", ran.stdout) def test_reads_a_drop_title_through_the_configs_title_template(self): - config = pathlib.Path(self.env["HOME"], ".claude-projects", "proj", "config.toml") + config = pathlib.Path(self.env["HOME"], ".config/build-release", "proj", "config.toml") config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\n') self.commit("PAY-5 - Drop item 5: moot", {"b.py": "1\n", "todo.md": todo(FIRST)}) self.git("switch", "-q", "-c", "chunk") @@ -570,12 +570,12 @@ class Reversals(unittest.TestCase): class ReadAnchors(unittest.TestCase): def test_fails_on_anchors_it_cannot_read_rather_than_scoring_without_them(self): checkout = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) - home = configured(self, checkout).parents[1] + home = configured(self, checkout).parents[2] self.enterContext(contextlib.chdir(checkout)) anchors = checkout.resolve() / "docs" / "score-anchors.md" anchors.parent.mkdir() anchors.write_bytes(b"\xff") - self.assertEqual(read_anchors(home), Failure(f"cannot read {anchors}: not UTF-8 on line 1")) + self.assertEqual(read_anchors(home, {}), Failure(f"cannot read {anchors}: not UTF-8 on line 1")) if __name__ == "__main__": diff --git a/bin/subagent-rung b/bin/subagent-rung index 5a724160..8fe1053e 100755 --- a/bin/subagent-rung +++ b/bin/subagent-rung @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import os import pathlib import sys @@ -6,4 +7,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from subagent_rung import main -sys.exit(main.main(sys.argv[1:], pathlib.Path.home())) +sys.exit(main.main(sys.argv[1:], pathlib.Path.home(), os.environ)) diff --git a/bin/subagent_rung/main.py b/bin/subagent_rung/main.py index 9090101c..43a62d6c 100644 --- a/bin/subagent_rung/main.py +++ b/bin/subagent_rung/main.py @@ -11,12 +11,13 @@ plan. For a model off the routing ladder, the tool doesn't print anything on std naming the ladder's file, and exits 0; launch the subagent with no model or effort. It reads the routing ladder of the project whose checkout it runs in: routing-ladder.json in the -folder of the project's config, ~/.claude-projects/<key>/, or else the one this setup ships, as in +folder of the project's config, ~/.config/build-release/<key>/, or else the one this setup ships, as in a checkout no config names. build-release --help shows the file's shape. Exit 1, saying why, on bad arguments, or where the project's config or its routing ladder is faulty or cannot be read. """ +from collections.abc import Mapping import pathlib import re import sys @@ -37,7 +38,7 @@ def agent_args(ladder: Ladder, model: str, likelihood: int, planning: bool = Fal return (project.planning_rung if planning else project.worker_rung)(likelihood).agent_args() -def main(argv: list[str], home: pathlib.Path) -> int: +def main(argv: list[str], home: pathlib.Path, env: Mapping[str, str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 @@ -47,7 +48,7 @@ def main(argv: list[str], home: pathlib.Path) -> int: print(f"subagent-rung: cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; {USAGE}", file=sys.stderr) return 1 model, likelihood = operands - file = project_ladder_file(None, home) + file = project_ladder_file(None, home, env) ladder = file if isinstance(file, Failure) else read_ladder(file) if isinstance(ladder, Failure): print(f"subagent-rung: {ladder.reason}", file=sys.stderr) diff --git a/bin/subagent_rung/test_subagent_rung.py b/bin/subagent_rung/test_subagent_rung.py index b7755473..4c5dc665 100644 --- a/bin/subagent_rung/test_subagent_rung.py +++ b/bin/subagent_rung/test_subagent_rung.py @@ -39,14 +39,14 @@ class SubagentRung(unittest.TestCase): # On the shipped ladder an L of 1 steps Fable 5.2 down to Opus 5.5, and an L of 4 up to Opus 5.5 at xhigh. self.assertEqual([self.run_tool("claude-fable-5-2", level, cwd=checkout / "nested").stdout for level in ("1", "4")], ["model fable, effort low\n", "model fable, effort max\n"]) off = self.run_tool("claude-opus-5-5", "3", cwd=checkout) - own = self.home / ".claude-projects" / "acme" / "routing-ladder.json" + own = self.home / ".config/build-release" / "acme" / "routing-ladder.json" self.assertEqual((off.returncode, off.stdout, off.stderr), (0, "", f"subagent-rung: claude-opus-5-5 is not on the routing ladder {own}; pass the Agent tool no model or effort\n")) def test_exits_1_naming_the_file_where_the_projects_ladder_holds_a_fault(self): checkout = self.project('[{"model": "claude-fable-5-2", "effort": "low"},]') refused = self.run_tool("claude-fable-5-2", "3", cwd=checkout) self.assertEqual((refused.returncode, refused.stdout), (1, "")) - self.assertTrue(refused.stderr.startswith(f"subagent-rung: cannot read the routing ladder {self.home / '.claude-projects' / 'acme' / 'routing-ladder.json'}: "), refused.stderr) + self.assertTrue(refused.stderr.startswith(f"subagent-rung: cannot read the routing ladder {self.home / '.config/build-release' / 'acme' / 'routing-ladder.json'}: "), refused.stderr) def test_prints_the_agent_tools_model_and_effort_for_the_rung_an_l_picks(self): self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 3), "model fable, effort low") diff --git a/bin/task_bench/features/feature_tasks.py b/bin/task_bench/features/feature_tasks.py index ed04568a..8e63480c 100644 --- a/bin/task_bench/features/feature_tasks.py +++ b/bin/task_bench/features/feature_tasks.py @@ -46,19 +46,19 @@ class Features(typing.NamedTuple): found: list[Feature] -def read_features(home: pathlib.Path, kind: Kind) -> Features | Failure: +def read_features(home: pathlib.Path, env: typing.Mapping[str, str], kind: Kind) -> Features | Failure: """The features of the current directory's project, or its data sources where kind is DATA_SOURCE, read from the folder its config names.""" - folder = features_folder(home) + folder = features_folder(home, env) if isinstance(folder, Failure): return folder found = features(folder, kind) return found if isinstance(found, Failure) else Features(folder, found) -def features_folder(home: pathlib.Path) -> pathlib.Path | Failure: +def features_folder(home: pathlib.Path, env: typing.Mapping[str, str]) -> pathlib.Path | Failure: """The folder the config of the current directory's project names as `bench-tasks`.""" - config = located(None, home) + config = located(None, home, env) if isinstance(config, Failure): return config return config.paths.get(BENCH_TASKS) or Failure(f"{config.folder / CONFIG} sets no `{BENCH_TASKS}`, the folder of the tasks to bench, as `project-config --help` describes it") diff --git a/bin/task_bench/features/shipped_features.py b/bin/task_bench/features/shipped_features.py index 951344d1..350dbf78 100644 --- a/bin/task_bench/features/shipped_features.py +++ b/bin/task_bench/features/shipped_features.py @@ -52,15 +52,15 @@ class ShippedFeatures(typing.NamedTuple): records: list[str] -def read_shipped(home: pathlib.Path, checkout: str, base: str, git: Git) -> ShippedFeatures | Failure: +def read_shipped(home: pathlib.Path, env: typing.Mapping[str, str], checkout: str, base: str, git: Git) -> ShippedFeatures | Failure: """The features that the project in checkout shipped on the first-parent line of the commit base. A Failure where no config names the checkout, where its config puts the plan or a record at a path branch_chunks doesn't read, where git fails, and where that line shipped no item.""" in_checkout = functools.partial(git, cwd=checkout) - config = located(checkout, home, in_checkout) + config = located(checkout, home, env, in_checkout) if isinstance(config, Failure): return config - if why := unsupported(checkout, home, in_checkout): + if why := unsupported(checkout, home, env, in_checkout): return Failure(f"task-bench cannot tell what the project shipped: {why}") cut = cut_with_shipped(base, in_checkout, config.titles) if isinstance(cut, Failure): diff --git a/bin/task_bench/features/test_feature_tasks.py b/bin/task_bench/features/test_feature_tasks.py index 0e294c86..52aa51fc 100644 --- a/bin/task_bench/features/test_feature_tasks.py +++ b/bin/task_bench/features/test_feature_tasks.py @@ -88,7 +88,7 @@ class BenchOfTasksCase(unittest.TestCase): self.addCleanup(folder.cleanup) self.root = pathlib.Path(folder.name).resolve() self.home, self.repo, fakes = self.root / "home", self.root / "repo", self.root / "fakes" - for made in (self.home / ".claude-projects/calc", self.repo, fakes): + for made in (self.home / ".config/build-release/calc", self.repo, fakes): made.mkdir(parents=True) (fakes / "docker").write_text(DOCKER) (fakes / "docker").chmod(0o755) @@ -96,7 +96,7 @@ class BenchOfTasksCase(unittest.TestCase): self.log = self.root / "docker.log" self.env = {**isolated_env(), "HOME": str(self.home), "PATH": f"{fakes}{os.pathsep}{os.environ['PATH']}", "FAKE_LOG": str(self.log), "FAKE_CLAUDE": str(fakes / "claude.py"), "CLAUDE_CODE_OAUTH_TOKEN": "sk-secret-token"} self.given = {"--image": "golang:1.27.4", "--test": TEST, "--tasks": "features", "--runs": "2", "--base": "main"} - self.config = self.home / ".claude-projects/calc/config.toml" + self.config = self.home / ".config/build-release/calc/config.toml" self.config.write_text(f'checkout = "{self.repo}"\n{CONFIG}bench-tasks = "checkout:bench-tasks"\n') self.tasks = self.repo / "bench-tasks" self.git("init", "--quiet", "--initial-branch", "main") @@ -188,7 +188,7 @@ class FeatureBenchTest(BenchOfTasksCase): ]) def test_reads_the_features_from_a_folder_outside_the_checkout(self): - outside = self.home / ".claude-projects/calc/bench-tasks" + outside = self.home / ".config/build-release/calc/bench-tasks" self.tasks.rename(outside) self.config.write_text(self.config.read_text().replace("checkout:bench-tasks", "folder:bench-tasks")) self.head = self.commit("Move the features out") diff --git a/bin/task_bench/features/test_shipped_features.py b/bin/task_bench/features/test_shipped_features.py index 911b42c6..a2d65ba3 100644 --- a/bin/task_bench/features/test_shipped_features.py +++ b/bin/task_bench/features/test_shipped_features.py @@ -236,7 +236,7 @@ class ShippedFeatureBenchTest(ShippedFeaturesCase): class ReadShippedTest(ShippedFeaturesCase): def read(self, run=git): - return read_shipped(self.home, str(self.repo), "main", functools.partial(run, env=self.env)) + return read_shipped(self.home, {}, str(self.repo), "main", functools.partial(run, env=self.env)) def test_reads_the_features_newest_first_with_the_paths_a_revert_leaves_alone(self): shipped = self.read() diff --git a/bin/task_bench/figures/gather.py b/bin/task_bench/figures/gather.py index ca00aec8..b51f2526 100644 --- a/bin/task_bench/figures/gather.py +++ b/bin/task_bench/figures/gather.py @@ -30,10 +30,10 @@ def gather(env: typing.Mapping[str, str], home: pathlib.Path, claude: Claude) -> checkout = top(git) if isinstance(checkout, Failure): return checkout - rung = project_rung(home, git) + rung = project_rung(home, env, git) if isinstance(rung, Failure): return rung - review = made_review_folder(checkout, home) + review = made_review_folder(checkout, home, env) if isinstance(review, Failure): return review with held(review) as folder: @@ -61,20 +61,20 @@ def run_claude(args: list[str], cwd: str, prompt: str) -> subprocess.CompletedPr return subprocess.run(["claude", *args], capture_output=True, cwd=cwd, env=with_release_tools(os.environ), input=prompt, text=True) -def project_rung(home: pathlib.Path, git: Git) -> Rung | Failure: +def project_rung(home: pathlib.Path, env: typing.Mapping[str, str], git: Git) -> Rung | Failure: """The cheapest rung for the model build-release runs the project on. The routing ladder is that of the project the process runs in.""" common = git("rev-parse", "--path-format=absolute", "--git-common-dir") if isinstance(common, Failure): return common # A worktree's project is its main checkout's, which holds the folder every worktree shares. key = project_key(os.path.dirname(common.strip()), home) - saved = paths_from(home).models_file + saved = paths_from(home, env).models_file models = read_models_file(saved) if isinstance(models, Failure): return models if key not in models: return Failure(f"{saved} names no model for {key}: run build-release in the project once, which asks for it.") - ladder = project_ladder(None, home) + ladder = project_ladder(None, home, env) if isinstance(ladder, Failure): return ladder project = ladder.project_rung(models[key]) diff --git a/bin/task_bench/figures/record_figures.py b/bin/task_bench/figures/record_figures.py index b6b3b302..864c0e0e 100644 --- a/bin/task_bench/figures/record_figures.py +++ b/bin/task_bench/figures/record_figures.py @@ -23,23 +23,23 @@ COMMIT_LENGTH = 8 TASKS_NAMED = {f"| {kind.noun.capitalize()} |": f" {tasks}" for tasks, kind in KINDS.items() if kind is not BUG} -def recorded_bench(run: typing.Callable[[], list[str] | Failure], folder: pathlib.Path, git: Git, home: pathlib.Path, now: typing.Callable[[], float]) -> list[str] | Failure: +def recorded_bench(run: typing.Callable[[], list[str] | Failure], folder: pathlib.Path, git: Git, home: pathlib.Path, env: typing.Mapping[str, str], now: typing.Callable[[], float]) -> list[str] | Failure: """The report of the bench that run runs in folder, plus the line that says where its figures went. It refuses before the bench where the history cannot be read, since a bench takes hours. A bench that fails or stops records nothing.""" branch = git("rev-parse", "--abbrev-ref", "HEAD") if isinstance(branch, Failure): return branch - if isinstance(unreadable := held_history(home), Failure): + if isinstance(unreadable := held_history(home, env), Failure): return unreadable report = run() if isinstance(report, Failure): return report - recorded = record_figures(folder, branch.strip(), home, now()) + recorded = record_figures(folder, branch.strip(), home, env, now()) if isinstance(recorded, Failure): return Failure(f"the bench finished and {folder} holds its results, but its figures are not recorded: {recorded.reason}") return [*report, recorded] -def record_figures(folder: pathlib.Path, branch: str, home: pathlib.Path, now: float) -> str | Failure: +def record_figures(folder: pathlib.Path, branch: str, home: pathlib.Path, env: typing.Mapping[str, str], now: float) -> str | Failure: """Appends the entry of the bench whose digest folder holds, stamped with now, and returns the line the tool prints.""" try: digest = (folder / DIGEST).read_text(encoding="utf-8") @@ -48,7 +48,7 @@ def record_figures(folder: pathlib.Path, branch: str, home: pathlib.Path, now: f entry = bench_entry(digest, branch, now) if entry is None: return Failure(f"{folder / DIGEST} is no task-bench digest: it lacks the line that names its base and head, or the table's three All rows") - read = held_history(home) + read = held_history(home, env) return read if isinstance(read, Failure) else bench_appended(*read, *entry) diff --git a/bin/task_bench/figures/test_gather.py b/bin/task_bench/figures/test_gather.py index 265a34fd..3a91da91 100644 --- a/bin/task_bench/figures/test_gather.py +++ b/bin/task_bench/figures/test_gather.py @@ -29,10 +29,10 @@ class GatherTest(unittest.TestCase): self.env = {**isolated_env(), "HOME": str(self.home)} self.git("init", "--quiet", "--initial-branch", "main") self.git("commit", "--quiet", "--allow-empty", "--message", "Base") - self.models = self.home / ".claude/loop-claude-models.json" - self.models.parent.mkdir() + self.models = self.home / ".config/build-release/models.json" + self.models.parent.mkdir(parents=True) self.models.write_text(json.dumps({"calc": "claude-opus-5-5"})) - self.bench = self.home / ".local/state/larv-review/code/calc/task-bench" + self.bench = self.home / ".local/state/build-release/larv-review/code/calc/task-bench" (self.bench / "runs").mkdir(parents=True) (self.bench / "digest.md").write_text("# task-bench digest\n\n## Bug 1: calc.go:4:11 ARITHMETIC_BASE\n") self.calls: list[tuple[list[str], str, str]] = [] @@ -61,7 +61,7 @@ class GatherTest(unittest.TestCase): def test_a_worktrees_project_is_its_main_checkouts(self): worktree = self.home / "code/calc-item-7" self.git("worktree", "add", "--quiet", str(worktree), "-b", "item-7") - bench = self.home / ".local/state/larv-review/code/calc-item-7/task-bench" + bench = self.home / ".local/state/build-release/larv-review/code/calc-item-7/task-bench" bench.mkdir(parents=True) (bench / "digest.md").write_text("worktree's\n") with contextlib.chdir(worktree): @@ -77,7 +77,7 @@ class GatherTest(unittest.TestCase): def test_a_gather_before_any_review_makes_the_review_folders_private(self): shutil.rmtree(self.home / ".local") self.assertIsInstance(gather(self.env, self.home, self.claude), Failure) - self.assertEqual((self.home / ".local/state/larv-review").stat().st_mode & 0o777, 0o700) + self.assertEqual((self.home / ".local/state/build-release/larv-review").stat().st_mode & 0o777, 0o700) def test_a_claude_that_fails_or_hits_a_limit_keeps_the_folder_for_another_try(self): self.code = 1 diff --git a/bin/task_bench/figures/test_record_figures.py b/bin/task_bench/figures/test_record_figures.py index 62c366b2..a7e03dff 100644 --- a/bin/task_bench/figures/test_record_figures.py +++ b/bin/task_bench/figures/test_record_figures.py @@ -45,10 +45,10 @@ class RecordFiguresTest(unittest.TestCase): self.repo.mkdir(parents=True) # The project's config is found from the checkout's top, which git names. subprocess.run(["git", "init", "--quiet"], cwd=self.repo, env={**isolated_env(), "HOME": str(self.home)}, check=True) - config = self.home / ".claude-projects/calc/config.toml" + config = self.home / ".config/build-release/calc/config.toml" config.parent.mkdir(parents=True) config.write_text(PROJECT_CONFIG) - self.bench = self.home / ".local/state/larv-review/code/calc/task-bench" + self.bench = self.home / ".local/state/build-release/larv-review/code/calc/task-bench" self.bench.mkdir(parents=True) self.history = self.repo / "docs/comprehension-history.md" self.ran = 0 @@ -67,7 +67,7 @@ class RecordFiguresTest(unittest.TestCase): return report def recorded(self, run=None) -> list[str] | str: - found = recorded_bench(run or self.left, self.bench, self.git, self.home, lambda: NOW) + found = recorded_bench(run or self.left, self.bench, self.git, self.home, {}, lambda: NOW) return found.reason if isinstance(found, Failure) else found def unrecorded(self, why: str) -> str: @@ -95,7 +95,7 @@ class RecordFiguresTest(unittest.TestCase): self.git = lambda *args: Failure("git failed") self.assertEqual(self.recorded(), "git failed") del self.git - (self.home / ".claude-projects/calc/config.toml").unlink() + (self.home / ".config/build-release/calc/config.toml").unlink() self.assertTrue(self.recorded().startswith(f"no config names the checkout {self.repo}"), self.recorded()) self.assertEqual(self.ran, 0) @@ -125,7 +125,7 @@ class RecordFiguresTest(unittest.TestCase): def test_says_why_where_the_history_cannot_be_read_once_the_bench_has_run(self): def run(): - (self.home / ".claude-projects/calc/config.toml").unlink() + (self.home / ".config/build-release/calc/config.toml").unlink() return self.left() self.assertTrue(self.recorded(run).startswith(self.unrecorded(f"no config names the checkout {self.repo}"))) diff --git a/bin/task_bench/main.py b/bin/task_bench/main.py index e70f5276..72866992 100644 --- a/bin/task_bench/main.py +++ b/bin/task_bench/main.py @@ -216,7 +216,7 @@ from failure import Failure from task_bench.features.feature_tasks import feature_tasks, Features, read_features from task_bench.figures.run_figures import Figures, figures, Result, table from git_cli import git_repo -from review_rules.review_folder import made_review_folder, REPORTS +from review_rules.review_folder import made_review_folder, reports_folder from larv_review.history_commands import read_places from task_bench.features.shipped_features import read_shipped, shipped_tasks from task_bench.figures.record_figures import recorded_bench @@ -258,7 +258,7 @@ class Call(typing.NamedTuple): and the home folder.""" given: dict[str, str] env: typing.Mapping[str, str] - read: typing.Callable[[pathlib.Path], str | Failure] + read: typing.Callable[[pathlib.Path, typing.Mapping[str, str]], str | Failure] home: pathlib.Path @@ -272,7 +272,7 @@ def host_user() -> str: return f"{os.getuid()}:{os.getgid()}" -def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude, name: typing.Callable[[], str] = new_name, user: typing.Callable[[], str] = host_user) -> int: +def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path, typing.Mapping[str, str]], str | Failure] = read_places, claude: Claude = run_claude, name: typing.Callable[[], str] = new_name, user: typing.Callable[[], str] = host_user) -> int: """Runs task-bench with the arguments argv; git, docker and the mutation tool run in the environment env, `read` reads what `larv-review places` prints for the checkout, and `claude` runs the claude that gathers. `name` names a bench's containers, and `user` is the user they run as.""" @@ -356,7 +356,7 @@ def progress(line: str) -> None: print(line, file=sys.stderr) -def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure], home: pathlib.Path, name: str, user: str) -> list[str] | Failure: +def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path, typing.Mapping[str, str]], str | Failure], home: pathlib.Path, name: str, user: str) -> list[str] | Failure: """The report of one bench of the checkout the process runs in, where `read` reads what `larv-review places` prints. Its containers are named name and run as user. It tells its progress on stderr.""" kind = KINDS[given[TASKS]] @@ -375,16 +375,16 @@ def bench(given: dict[str, str], env: typing.Mapping[str, str], read: typing.Cal if isinstance(planning, Failure): return planning progress(f"task-bench: base {sides['base'][:12]}, head {sides['head'][:12]}.") - review = made_review_folder(checkout, home) + review = made_review_folder(checkout, home, env) if isinstance(review, Failure): return review with held(review) as folder: if isinstance(folder, Failure): return folder - clear_left(home / REPORTS) + clear_left(reports_folder(home, env)) containers = Containers(docker_cli(env), name, given["--test"], int(env.get(SHARE_VARIABLE) or MEMORY_MIB), user) run = functools.partial(bench_in, folder, given["--image"], containers, Asked(kind, int(given["--runs"])), planning, checkout, sides, git) - return recorded_bench(run, folder, git, home, time.time) if RECORD in given else run() + return recorded_bench(run, folder, git, home, env, time.time) if RECORD in given else run() def bench_in(folder: pathlib.Path, image: str, containers: Containers, asked: Asked, planning: Planning, checkout: str, sides: dict[Side, str], git: Git) -> list[str] | Failure: @@ -409,7 +409,7 @@ def bench_in(folder: pathlib.Path, image: str, containers: Containers, asked: As def bugs_source(call: Call, kind: Kind) -> Source | Failure: """Reads the seats' places, the only places bugs are planted.""" - places = call.read(call.home) + places = call.read(call.home, call.env) if isinstance(places, Failure): return places return lambda checkout, sides, git: functools.partial(bugs_planner, call.given, call.env, places) @@ -417,7 +417,7 @@ def bugs_source(call: Call, kind: Kind) -> Source | Failure: def features_source(call: Call, kind: Kind) -> Source | Failure: """Reads the features, or the data sources where kind is DATA_SOURCE, from the project's folder.""" - features = read_features(call.home, kind) + features = read_features(call.home, call.env, kind) if isinstance(features, Failure): return features return lambda checkout, sides, git: functools.partial(features_planner, features, checkout) @@ -426,7 +426,7 @@ def features_source(call: Call, kind: Kind) -> Source | Failure: def shipped_source(call: Call, kind: Kind) -> Source: """Shipped features are read from the base's history, so only once the base is known.""" def source(checkout: str, sides: dict[Side, str], git: Git) -> Planning | Failure: - shipped = read_shipped(call.home, checkout, sides["base"], git) + shipped = read_shipped(call.home, call.env, checkout, sides["base"], git) if isinstance(shipped, Failure): return shipped return lambda trees: functools.partial(shipped_tasks, shipped=shipped, count=int(call.given["--shipped"])) diff --git a/bin/task_bench/test_task_bench.py b/bin/task_bench/test_task_bench.py index 7ac67aed..8979a705 100644 --- a/bin/task_bench/test_task_bench.py +++ b/bin/task_bench/test_task_bench.py @@ -139,7 +139,7 @@ class BenchTest(unittest.TestCase): def bench(self, **given: str): with contextlib.redirect_stderr(io.StringIO()) as self.progress: - return main.bench({**self.given, "--base": "main", **given}, self.env, lambda home: PLACES, self.home, NAME, USER) + return main.bench({**self.given, "--base": "main", **given}, self.env, lambda home, env: PLACES, self.home, NAME, USER) def calls(self) -> list[list[str]]: return [json.loads(line) for line in self.log.read_text().splitlines()] @@ -161,7 +161,7 @@ class BenchTest(unittest.TestCase): "| All | change | +2 | 0 % | 0 % | 0 % | 0 % | 0 | 0 % | 0 |", "", ]) - self.assertTrue(folder.is_relative_to(self.home / ".local/state/larv-review") and folder.name == "task-bench", folder) + self.assertTrue(folder.is_relative_to(self.home / ".local/state/build-release/larv-review") and folder.name == "task-bench", folder) results = json.loads((folder / "results.json").read_text()) self.assertEqual((results["sides"], results["bugs"], len(results["runs"])), ({"base": self.base, "head": self.head}, {"1": "calc.go:4:11 ARITHMETIC_BASE"}, 4)) self.assertEqual(results["runs"][0], {"bug": 1, "side": "base", "run": 1, "passed": False, "finished": True, "claude_code": "2.1.330", "model": "claude-haiku-5-5", "tokens": {"input": 40, "write_5m": 9000, "write_1h": 0, "read": 52000, "output": 800}, "turns": 3, "seconds": 61.5, "reads": 1}) @@ -215,7 +215,7 @@ class BenchTest(unittest.TestCase): ]) def test_removes_the_folders_other_benches_left_but_not_one_in_use_or_one_that_is_no_benchs(self): - reports = self.home / ".local/state/larv-review" + reports = self.home / ".local/state/build-release/larv-review" for name in ("crashed", "running", "a-project"): (reports / name / "task-bench/runs").mkdir(parents=True) (reports / "crashed/task-bench.lock").touch() @@ -237,7 +237,7 @@ class BenchTest(unittest.TestCase): self.assertEqual(main.host_user(), f"{os.getuid()}:{os.getgid()}") argv = [part for name, value in {**self.given, "--runs": "1"}.items() for part in (name, value)] with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(main.main(argv, self.env, lambda home: PLACES, name=lambda: "task-bench-other", user=lambda: "7:8"), 0) + self.assertEqual(main.main(argv, self.env, lambda home, env: PLACES, name=lambda: "task-bench-other", user=lambda: "7:8"), 0) calls = self.calls() self.assertEqual(calls[1], ["network", "create", "--internal", "task-bench-other"]) self.assertIn(["--user", "7:8"], [call[at:at + 2] for call in calls if "claude" in call for at in range(len(call))]) @@ -249,7 +249,7 @@ class BenchTest(unittest.TestCase): argv = [part for name, value in self.given.items() for part in (name, value)] homes = [] with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(main.main(argv, self.env, lambda home: homes.append(home) or PLACES), 0) + self.assertEqual(main.main(argv, self.env, lambda home, env: homes.append(home) or PLACES), 0) self.assertEqual(homes, [self.home]) # Without --base, the base is the merge base with the default branch. self.assertEqual(out.getvalue().splitlines()[0], f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 bug, each run 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.") @@ -260,7 +260,7 @@ class BenchTest(unittest.TestCase): argv = [part for name, value in self.given.items() for part in (name, value)] for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.\n")): with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as errors: - self.assertEqual(main.main(argv, self.env, lambda home: places), 1) + self.assertEqual(main.main(argv, self.env, lambda home, env: places), 1) self.assertEqual((out.getvalue(), errors.getvalue().splitlines(keepends=True)[-1]), ("", said)) def test_the_head_is_the_commit_asked_for(self): @@ -335,7 +335,7 @@ class BenchTest(unittest.TestCase): def test_fails_where_the_places_name_no_file_of_the_base_in_a_language_the_bench_plants_in(self): with contextlib.redirect_stderr(io.StringIO()): - found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home, NAME, USER) + found = main.bench({**self.given, "--base": "main"}, self.env, lambda home, env: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home, NAME, USER) self.assertEqual(found, Failure("The places the seats found hard don't name any file at the base in a language the bench plants bugs in, so there is nowhere to plant a bug.")) self.assertFalse(self.log.exists()) @@ -361,14 +361,14 @@ class BenchTest(unittest.TestCase): found = self.bench() self.assertIsInstance(found, Failure) lines = found.reason.splitlines() - folder = next(self.home.glob(".local/state/larv-review/**/task-bench")) + folder = next(self.home.glob(".local/state/build-release/larv-review/**/task-bench")) self.assertEqual(lines[:3], ["claude could not use the API: API Error: 401", f"task-bench stopped after 2 of 4 runs, which results.json holds in {folder}:", ""]) self.assertEqual(lines[-3:-1], ["| All | base | 0/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |", "| All | head | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |"]) self.assertEqual([(run["side"], run["run"]) for run in json.loads((folder / "results.json").read_text())["runs"]], [("base", 1), ("head", 1)]) def project_config(self) -> pathlib.Path: """Writes the config that puts the project's records in the checkout, and returns its comprehension history's path.""" - config = self.home / ".claude-projects/calc/config.toml" + config = self.home / ".config/build-release/calc/config.toml" config.parent.mkdir(parents=True) records = {"plan": "todo.md", "working-rules": "AGENTS.md", "decisions": "docs/decisions.md", "score-anchors": "docs/score-anchors.md", "comprehension-history": "docs/comprehension-history.md", "reading-cost": "docs/reading-cost.md", "changelog": "CHANGELOG.md", "goals-and-audience": "README.md"} config.write_text(f'checkout = "{self.repo}"\n' + "".join(f'{name} = "checkout:{path}"\n' for name, path in records.items()) + 'principles = "~/principles"\nstandards = "~/standards"\n') @@ -461,7 +461,7 @@ class MainTest(unittest.TestCase): def test_takes_a_value_after_an_equals_sign_too(self): with contextlib.redirect_stderr(io.StringIO()) as errors: - self.assertEqual(main.main(["--image=golang:1.27.4", "--test=go test ./...", "--bugs=2"], {"CLAUDE_CODE_OAUTH_TOKEN": "t", "HOME": "/nonexistent"}, lambda home: Failure("read the places")), 1) + self.assertEqual(main.main(["--image=golang:1.27.4", "--test=go test ./...", "--bugs=2"], {"CLAUDE_CODE_OAUTH_TOKEN": "t", "HOME": "/nonexistent"}, lambda home, env: Failure("read the places")), 1) self.assertEqual(errors.getvalue(), "read the places\n") def test_refuses_a_missing_image_or_test_command(self): diff --git a/bin/test_env.py b/bin/test_env.py index 50b978de..7d776d81 100644 --- a/bin/test_env.py +++ b/bin/test_env.py @@ -5,7 +5,7 @@ import unittest # A git hook's GIT_DIR, the host's BUILD_RELEASE_* or PYTHONPATH would point the program under test at the host's own state, # and the host's CLAUDE_CODE_SANDBOXED would hide whether build-release sets it. def isolated_env() -> dict[str, str]: - return {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "BUILD_RELEASE_", "PYTHON")) and name != "CLAUDE_CODE_SANDBOXED"} + return {name: value for name, value in os.environ.items() if not name.startswith(("GIT_", "BUILD_RELEASE_", "PYTHON")) and name not in ("CLAUDE_CODE_SANDBOXED", "XDG_CONFIG_HOME", "XDG_STATE_HOME")} # Call it first in a test that takes a file's or a folder's permissions away. diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 52bb64a1..832e9e27 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -24,12 +24,12 @@ class Main(unittest.TestCase): def configured(self, checkout: str) -> pathlib.Path: folder = configured(self, pathlib.Path(checkout)) - self.home = folder.parents[1] + self.home = folder.parents[2] return folder def run_main(self, *argv): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: - code = rank_todo.main(list(argv), self.home) + code = rank_todo.main(list(argv), self.home, {}) return code, said.getvalue() def test_ranks_the_file_in_place_and_check_writes_nothing(self): diff --git a/bin/todo-item b/bin/todo-item index 09ba0244..df7f7998 100755 --- a/bin/todo-item +++ b/bin/todo-item @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import os import pathlib import sys @@ -6,4 +7,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from todo_item import main -sys.exit(main.main(sys.argv[1:], pathlib.Path(), pathlib.Path.home(), sys.stdin)) +sys.exit(main.main(sys.argv[1:], pathlib.Path(), pathlib.Path.home(), os.environ, sys.stdin)) diff --git a/bin/todo_item/main.py b/bin/todo_item/main.py index 0f2d59e1..b28c70ea 100644 --- a/bin/todo_item/main.py +++ b/bin/todo_item/main.py @@ -107,12 +107,12 @@ NAMED = {"release": "Release", "blocked_by": BLOCKED_BY, "exempt": "Exempt", "ta # plan_of is plan_store, except in the tests of a plan in Jira, which hand it a plan in memory. -def main(argv: list[str], folder: pathlib.Path, home: pathlib.Path, stdin: typing.TextIO, plan_of: typing.Callable[[ProjectConfig], PlanStore] = plan_store) -> int: +def main(argv: list[str], folder: pathlib.Path, home: pathlib.Path, env: typing.Mapping[str, str], stdin: typing.TextIO, plan_of: typing.Callable[[ProjectConfig], PlanStore] = plan_store) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 args = parser().parse_args(argv) - config = located(str(folder), home) + config = located(str(folder), home, env) if isinstance(config, Failure): done: str | Failure = config else: diff --git a/bin/todo_item/test_todo_item.py b/bin/todo_item/test_todo_item.py index f3e4a16c..2d1f5eb2 100644 --- a/bin/todo_item/test_todo_item.py +++ b/bin/todo_item/test_todo_item.py @@ -40,7 +40,7 @@ class TodoItem(unittest.TestCase): self.addCleanup(temp.cleanup) self.folder = pathlib.Path(temp.name) self.config = configured(self, self.folder) / "config.toml" - self.home = self.config.parents[2] + self.home = self.config.parents[3] # The plan main is handed in place of the one the config names. self.plan_of = {} self.todo = self.folder / "todo.md" @@ -54,16 +54,16 @@ class TodoItem(unittest.TestCase): def run_main(self, *argv, stdin: str | io.StringIO = ""): with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: - code = main.main(list(argv), self.folder, self.home, io.StringIO(stdin) if isinstance(stdin, str) else stdin, **self.plan_of) + code = main.main(list(argv), self.folder, self.home, {}, io.StringIO(stdin) if isinstance(stdin, str) else stdin, **self.plan_of) return code, out.getvalue(), err.getvalue() def exit_code(self, *argv): with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as raised: - main.main(list(argv), self.folder, self.home, io.StringIO()) + main.main(list(argv), self.folder, self.home, {}, io.StringIO()) return raised.exception.code def assert_ranked(self): - self.assertEqual(file_plan(located(str(self.folder), self.home), self.todo).check(), []) + self.assertEqual(file_plan(located(str(self.folder), self.home, {}), self.todo).check(), []) def details(self): text = self.todo.read_text() @@ -409,7 +409,7 @@ class List(TodoItem): def test_fails_on_a_release_that_is_no_version(self): errors = io.StringIO() with contextlib.redirect_stderr(errors), self.assertRaises(SystemExit) as raised: - main.main(["list", "--release", "next"], self.folder, self.home, io.StringIO()) + main.main(["list", "--release", "next"], self.folder, self.home, {}, io.StringIO()) self.assertEqual(raised.exception.code, 2) self.assertIn("argument --release: 'next' is not a semver version", errors.getvalue()) @@ -536,7 +536,7 @@ class Move(TodoItem): class OtherFile(TodoItem): def test_ranking_works_on_the_file_it_is_given_not_the_configured_plan(self): - config = located(str(self.folder), self.home) + config = located(str(self.folder), self.home, {}) other = self.folder / "other.md" other.write_text("not a plan\n") self.assertNotEqual(file_plan(config, other).check(), []) diff --git a/bin/touch_predictions/test_touch_predictions.py b/bin/touch_predictions/test_touch_predictions.py index 4c92aaac..96aadea8 100644 --- a/bin/touch_predictions/test_touch_predictions.py +++ b/bin/touch_predictions/test_touch_predictions.py @@ -341,7 +341,7 @@ class RecordCommandTest(unittest.TestCase): def test_stamps_the_entry_at_the_clock_it_is_handed(self) -> None: path = self.set_record() - config = located(str(self.checkout), self.home) + config = located(str(self.checkout), self.home, {}) assert isinstance(config, ProjectConfig), config self.assertNotIsInstance(main.recorded(config, [3], lambda: 0.0, main.git), Failure) self.assertIn("## Chunk 3, 1970-01-01T00:00:00Z, at ", path.read_text(encoding="utf-8")) diff --git a/bin/transcript_archive/__init__.py b/bin/transcript_archive/__init__.py index ce333f9f..3181f346 100644 --- a/bin/transcript_archive/__init__.py +++ b/bin/transcript_archive/__init__.py @@ -5,7 +5,7 @@ <archive root>/<project key>/<chunk>/session/... <archive root>/<project key>/<chunk>/judge/<sha256>.json -- The archive root is $BUILD_RELEASE_TRANSCRIPTS, or ~/.claude/loop-claude-transcripts (location.archive_root). +- The archive root is $BUILD_RELEASE_TRANSCRIPTS, or ~/.local/state/build-release/transcripts (location.archive_root). - The project key is the checkout's path relative to ~/code, or to / outside it (project_key.project_key). - <chunk> is the hash of the transcript's first line with a timestamp (location.chunk_folder). It is the same for every cycle of a chunk, and differs between chunks, since a finished chunk's session is deleted diff --git a/bin/transcript_archive/location.py b/bin/transcript_archive/location.py index 9f62f2eb..71f20bae 100644 --- a/bin/transcript_archive/location.py +++ b/bin/transcript_archive/location.py @@ -2,9 +2,9 @@ import hashlib import pathlib import typing -from loop_state.paths import CLAUDE_HOME from claude_code.transcript import first_timestamped_line from transcript_archive.project_key import project_key +from loop_state.paths import state_folder # What an outcomes file's name ends with, in place of its transcript copy's .jsonl. FILE_SUFFIX = ".outcomes.md" @@ -12,7 +12,7 @@ FILE_SUFFIX = ".outcomes.md" def archive_root(home: pathlib.Path, env: typing.Mapping[str, str]) -> pathlib.Path: """Where build-release archives every project's chunks.""" - return pathlib.Path(env["BUILD_RELEASE_TRANSCRIPTS"]).expanduser() if env.get("BUILD_RELEASE_TRANSCRIPTS") else home / CLAUDE_HOME / "loop-claude-transcripts" + return pathlib.Path(env["BUILD_RELEASE_TRANSCRIPTS"]).expanduser() if env.get("BUILD_RELEASE_TRANSCRIPTS") else state_folder(env, home) / "transcripts" def project_archive(checkout_root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> pathlib.Path: diff --git a/bin/transcript_archive/test_transcript_archive.py b/bin/transcript_archive/test_transcript_archive.py index 5dbe8cec..318b8a3d 100644 --- a/bin/transcript_archive/test_transcript_archive.py +++ b/bin/transcript_archive/test_transcript_archive.py @@ -262,7 +262,7 @@ class Location(unittest.TestCase): self.assertEqual(project_key("/h/code/log", home), "log") self.assertEqual(project_key("/h/code", home), "h/code") self.assertEqual(project_key("/srv/log", home), "srv/log") - self.assertEqual(project_archive("/h/code/log", home, {}), pathlib.Path("/h/.claude/loop-claude-transcripts/log")) + self.assertEqual(project_archive("/h/code/log", home, {}), pathlib.Path("/h/.local/state/build-release/transcripts/log")) self.assertEqual(project_archive("/h/code/log", home, {"BUILD_RELEASE_TRANSCRIPTS": "/a"}), pathlib.Path("/a/log")) def test_finds_the_checkout_a_key_names_under_code_or_else_under_the_root(self): diff --git a/docs/decisions.md b/docs/decisions.md index 657a6943..66e64a36 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -4,7 +4,7 @@ Each project principle states one rule that the decisions below apply; their ent 1. **Cut cost only where a measurement of archived chunks shows quality holds.** Chunk bundling, the round cap, which fixes rerun a pass, a reviewer of its own for each pass, the review a branch changing only Markdown no agent follows gets, the passes kept for the release review, review opt-outs, the security pass, compaction and the routing ladder all apply it. 2. **A measurement files or ranks work, and never blocks a merge.** The comprehension floor and check, and a reading-cost rise, apply it. A merge waits on a scoring run the plan calls for only until the run is recorded, whatever it scores. -3. **Each file has one writer.** `~/.claude/loop-claude-models.json` is written only by `save_model`, which the entry points, build-release and do-epic, both call. `~/.claude.json` is Claude Code's, and `~/.claude` moves only through `deploy-release`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo. +3. **Each file has one writer.** `~/.config/build-release/models.json` is written only by `save_model`, which the entry points, build-release and do-epic, both call. `~/.claude.json` is Claude Code's, and `~/.claude` moves only through `deploy-release`. The exception is `~/.claude/settings.json`, which Claude Code writes from any session. Git's clean filter `bin/settings_filter.py` keeps each machine's model and Claude Code's key order out of every commit, and `README.md` → "Update" carries its other changes into this repo. 4. **A rule a program can check is enforced by a program, and reviewers rule on the rest.** rule-hook and its overrides, `docker-run-memory`, the refused writes of reviewers under `agents/`, and CI with `main`'s branch protection apply it. 5. **A chunk can't vouch for itself.** What a chunk writes is approved by a review pass, by the human, or by a precedent the repo held before the chunk began. So an unanswered ask leaves the PR unmerged, the human approves the premises chunk and runs `deploy-release --cut`, and the judge holds a chunk open while an answer the human typed isn't recorded anywhere. 6. **An unattended run never waits on a prompt, and a lasting failure stops it.** Every claude build-release starts bypasses permissions inside its sandbox, each claude it opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, and interactive sessions run in auto mode with the dangerous-mode prompt skipped. A failed archive stops the loop, while a `claude` that cannot start, as during an update, is retried. @@ -58,7 +58,7 @@ Each project principle states one rule that the decisions below apply; their ent # Working rules -**Routing calls: file them in the plan.** A routing call is a change to the routing ladder, its steps or the delegation rule that build-release's figures call for. build-release puts each call to the human once, and appends it to `routing-calls-raised.md`, at the root of its archive (`$BUILD_RELEASE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Each line of that file is a call or a `Reset`, with a stamp. A call is new when it is stamped after the latest `Reset` and after the latest stamp that `todo.md` or `docs/decisions.md` → `routing:` cites. +**Routing calls: file them in the plan.** A routing call is a change to the routing ladder, its steps or the delegation rule that build-release's figures call for. build-release puts each call to the human once, and appends it to `routing-calls-raised.md`, at the root of its archive (`$BUILD_RELEASE_TRANSCRIPTS`, default `~/.local/state/build-release/transcripts`). Each line of that file is a call or a `Reset`, with a stamp. A call is new when it is stamped after the latest `Reset` and after the latest stamp that `todo.md` or `docs/decisions.md` → `routing:` cites. When there are new calls, file one `todo.md` item to settle them, or refresh the item already filed. Its detail quotes the new calls with their stamps. It also quotes the routed-chunks table of `routing-figures.md`, which sits in the same folder, and none of that file's other tables, since they name other projects. @@ -68,7 +68,7 @@ Settling a call is the human's. The chunk that settles the calls cites, in `docs ## archives: gzip each transcript in build-release's archive and each file in the review folders 30 days after it last changed, keeping all of them -2026-11-17, the worker of todo item 306. Serves goal 4, backing up the transcripts, and goal 1, whose measures read them: the routing figures, `reading-cost`, `score-outcomes` and both replays rest on the whole archive, so nothing is pruned. On 2026-11-17 the archive held 7.9 GB and `~/.local/state/larv-review` 1.1 GB, both growing with every chunk. +2026-11-17, the worker of todo item 306. Serves goal 4, backing up the transcripts, and goal 1, whose measures read them: the routing figures, `reading-cost`, `score-outcomes` and both replays rest on the whole archive, so nothing is pruned. On 2026-11-17 the archive held 7.9 GB and `~/.local/state/build-release/larv-review` 1.1 GB, both growing with every chunk. - **What.** `compress-archives`, run daily from the crontab line in `README.md` → "Install", gzips each file that last changed over 30 days ago, but for a lock, `*.lock`: a lock is held by its name and never written, so its age doesn't say that it is out of use. The gzip is `<name>.gz`, beside the plain name, with the same times. In the archive it takes only the transcripts, `*.jsonl`, which held 7.8 GB of the 7.9 GB; the outcomes files stay plain, since build-release appends to them every cycle. In the review folders it takes every file, since the probes' build output fills most of them. - **Last changed.** A file's age is the later of its mtime and its ctime. A copy or an unpacked archive keeps old mtimes, but its ctime is when it landed, so a tree a chunk or a replay unpacks today stays plain while they use it. @@ -165,14 +165,14 @@ Valid while `~/.claude` is a checkout of this repo. 2026-11-18, lilleman's answers to claude's questions while planning release 0.12.0. Serves goal 1, so development scales past one repo, and goal 1.6, since the epic stays in the client's Jira. Valid while Jira is the only backend; another backend goes behind the same interface. - **What it is.** `do-epic <EPIC-KEY>` is a sibling of build-release, built on the same cycle, judge, interrupt, tmux and routing packages, not a copy (goal 1.3). It runs one tmux session per epic. -- **Machine settings.** `~/.claude-projects/do-epic/` holds `config.toml` (the Jira site, env-file, the folder repos are cloned into, the default language, and the model for a no-repo item) and `repo-rule.md`. `repo-rule.md` is a prose instruction that says how to tell an item's repo. It is the same for every epic on the machine. On the first machine, an item's label that equals a repo's name names that repo. A `[label-repos]` table in `config.toml` maps a team's own label to a repo, so do-epic reads that label as a pick without a claude call. +- **Machine settings.** `~/.config/build-release/do-epic/` holds `config.toml` (the Jira site, env-file, the folder repos are cloned into, the default language, and the model for a no-repo item) and `repo-rule.md`. `repo-rule.md` is a prose instruction that says how to tell an item's repo. It is the same for every epic on the machine. On the first machine, an item's label that equals a repo's name names that repo. A `[label-repos]` table in `config.toml` maps a team's own label to a repo, so do-epic reads that label as a pick without a claude call. - **The epic's description is its record.** It holds `## Goals`, `## Audience`, `## Scoring` (formula and bar), `## Decisions` and a language line. do-epic writes all of it, but it changes Goals or Audience only after the human approves in an interrupt. - **Items live only in the epic.** A repo's own plan never mirrors them. Where `repo-rule.md` leaves an item's repo unclear, do-epic asks. An item without a repo is either Claude's work, done without a PR, or a human task; where the item doesn't say which, do-epic asks. - **One item, several repos.** do-epic splits such an item when it plans it, into one Jira sub-task per repo, each labelled for its repo. The parent tracks the whole change. A person's issue is split too, with a comment for the team. An item a person filed a sub-task under counts as split already: do-epic works it through the team's own sub-tasks and doesn't file any of its own. It plans no such sub-task, so one without a label waits for the team's. It moves such an item itself (lilleman's call of 2026-11-20), since every issue the item blocks waits until the item moves, and the team's automation sees a pull request only on the sub-task that carries it. Once every sub-task is done, the item moves to done. Once every sub-task has landed, each done or in one of `jira-unblocking-statuses`, the item moves by the transition `jira-sub-tasks-landed-transition` names, which must lead to one of those statuses. A move that is not made is said, and the run goes on. - **Ranking.** Score, then Blocked by, in one weight chain: the epic's achieve goals, then code health, then the repo's goals. Where the epic and a repo disagree, the epic wins. do-epic re-ranks the issues it filed in Jira's backlog to match. A person's issue keeps its rank there: goal 1.6 has the loop plug in without changing what the owners keep. On 2026-11-20 the human chose that the order the issues start in is do-epic's, while the board's order stays the team's: do-epic starts the open issues by score. Where two or more may start, it scores each of them that holds no scores, a person's included but not a human's task, and tells the team the scores in a comment. It never overwrites scores an issue holds. An issue that cannot be scored starts after those that can, in the backlog's order; where no order of score can be made at all, such as without the epic's formula, every issue starts in the backlog's order and do-epic says why. - **Releases.** An epic item has no release. It ships into its repo's unreleased work: where the repo publishes something others consume, a bullet under `CHANGELOG.md` → `## Unreleased`, or nothing where the repo's plan is in Jira. The issue is no item of the repo's plan, so the chunk's worker writes the bullet in its branch and runs `chunk-pr merge` without `--finish`. - **Repos.** A repo's name is its main checkout's folder name, and a project config names that checkout. A missing checkout is cloned from the host of the epic's other repos; where unsure, do-epic asks. Unsure means the other repos don't all sit under one host and owner (the same host spelt as https and as ssh counts as two), an origin can't be read or isn't an https, ssh or scp-style address, the folder to clone into holds something else, or the clone fails. A repo no config names is cloned into the clone folder, and the human is asked to write its config. Each chunk uses its repo's model, routing, and language for commits and PRs. Jira text is in the epic's language, or else the machine's default. -- **Running.** The epic caps the chunks running at once, and each repo's `parallel-chunks` still applies. do-epic and build-release never run chunks in the same repo at once. The cap is a line of the epic's description, `**Max parallel chunks:** 2`, and 1 without it, as `parallel-chunks` is. A repo's `parallel-chunks` counts the chunks of every epic in its checkout. Each window is named for its issue's key, and a tmux window option, `@chunk-root`, names the folder its chunk works in, which is how build-release sees do-epic's chunks in a checkout. do-epic and build-release each hold the checkout's `starting` lock from checking the checkout's chunks to starting a window there. A chunk without a repo works in `~/.local/state/do-epic/<EPIC-KEY>/`. do-epic archives its cycles under `~/.claude/do-epic-transcripts/`, not in build-release's archive, whose readers parse build-release's prompts. An open issue runs once a label records its repo; until do-epic picks repos itself, an issue without one waits, and `do-epic <EPIC-KEY>` says so. +- **Running.** The epic caps the chunks running at once, and each repo's `parallel-chunks` still applies. do-epic and build-release never run chunks in the same repo at once. The cap is a line of the epic's description, `**Max parallel chunks:** 2`, and 1 without it, as `parallel-chunks` is. A repo's `parallel-chunks` counts the chunks of every epic in its checkout. Each window is named for its issue's key, and a tmux window option, `@chunk-root`, names the folder its chunk works in, which is how build-release sees do-epic's chunks in a checkout. do-epic and build-release each hold the checkout's `starting` lock from checking the checkout's chunks to starting a window there. A chunk without a repo works in `~/.local/state/build-release/do-epic/<EPIC-KEY>/`. do-epic archives its cycles under `~/.local/state/build-release/do-epic-transcripts/`, not in build-release's archive, whose readers parse build-release's prompts. An open issue runs once a label records its repo; until do-epic picks repos itself, an issue without one waits, and `do-epic <EPIC-KEY>` says so. - **Long gates.** A chunk whose PR waits on a gate, such as a human approval, parks. It keeps its worktree, PR and session, and its state is in a file that survives a reboot. A parked chunk takes no running slot, and the items it blocks wait. do-epic polls the forge and resumes the chunk's session when the gate passes or a reviewer comments. It fixes reasonable feedback, replies to the rest, and changes the setup so review would have caught it. `do-epic <key> --status` and the tmux window names show what each chunk waits on. A gate is a pull request's pending checks or, on GitHub, the approval its branch protection requires; a draft waits on neither, since its worker has yet to mark it ready. On Gitea a draft is a pull request whose title opens with `WIP:` or `[WIP]`, Gitea's default `WORK_IN_PROGRESS_PREFIXES`. Changes a reviewer requested resume the chunk only while that review was made on the pull request's head commit and the pull request's author has not commented or replied after it; once the worker pushed or replied, the chunk parks on a new review, since GitHub keeps the decision until the reviewer reviews again. The chunk's window reads the forge once a minute, which no forge's rate limit notices. A chunk resumes only into a free slot, under the limits a starting chunk meets, and stays parked until then. `do-epic <key>` starts a parked chunk's window again whatever the limits, since the chunk stays parked. do-epic sets `CHUNK_PR_PARKS=1` for each worker, so `chunk-pr merge` fails at once where the pull request awaits an approval, and the worker's run doesn't hold a slot while the pull request waits. In a repo whose config sets `merge = "human"`, the merge itself is a gate: `chunk-pr merge` leaves the pull request ready, the chunk parks on `your merge` once nothing else holds the pull request, and it gets its gate read again when the forge no longer reports the pull request open, so that its worktree is removed and the chunk finishes. It resumes too once the pull request conflicts with its base branch, or is behind it where GitHub's branch protection requires an up-to-date branch, so the person finds a pull request they can merge. The worker then runs `chunk-pr merge` again, which levels the branch, waits for the checks and leaves the pull request ready. A chunk whose cycle ends on such a pull request is not handed on: its worker is told after each cycle until the pull request merges into its base. While GitHub still computes whether the pull request merges, the chunk stays parked until the next read. Gitea also reports a pull request as not mergeable for the seconds it checks for conflicts. A read in those seconds resumes the chunk for a run that doesn't change anything, which costs less than reading every gate twice to tell the two apart. The judge may rule such a chunk finished while its pull request is open, since its worker ends each run there. So do-epic reads a gate it could not read again before it hands the chunk on, and does the removal itself where it can. For a chunk whose pull request is no longer open, do-epic runs `chunk-pr clean` in the chunk's worktree. That command acts only on a pull request the forge reports merged at the worktree's head, and refuses a worktree with uncommitted or untracked files. Where it removed the worktree, the chunk finishes without a worker and, where it was parked, without a running slot, even if the command then failed on the main checkout, whose reason do-epic says. Where it left the worktree, as for a pull request closed unmerged, do-epic tells the worker once to remove it, and a parked chunk waits for a slot as for any other news. - **Human tasks.** do-epic leaves a human task's issue as the team filed it. The task gets a window of its own while it is open, no issue blocks it, and it blocks another open issue. The window DMs the human once, through the notifier of the first repo whose project config names one (the repos of the issues it holds up come first, then those of the epic's other issues; where none does, the window says so), shows as parked (`awaits a human's task`) so that it doesn't take a running slot, and polls the epic every minute until the task no longer holds up an open issue. Then the issues it held up may start. A window that starts again, as after a reboot, DMs again. - **Findings.** A finding about the epic's goals is filed in the epic. A finding about a repo's goals follows that repo's rules. Where unsure which, do-epic asks. A set of new items toward an epic goal needs the human's approval before work starts; a finding filed during a chunk doesn't. @@ -225,9 +225,9 @@ Valid while `~/.claude` is a checkout of this repo. 2026-10-30, lilleman, todo item 6. Serves goal 1. Until then build-release marked each worktree trusted in `~/.claude.json`, reading the file, changing it and writing it back. Claude Code owns and writes that file, so a write it made in between could be lost. Claude Code 2.1.314 treats every folder as trusted while `CLAUDE_CODE_SANDBOXED` is set, and doesn't persist that trust. A claude started in a new folder with the variable set showed no dialog, and Claude Code recorded the folder untrusted. `hand_over` sets the variable for every claude it opens on a terminal: for `/talk`, a release ready to cut and the routing calls. The variable tells Claude Code it runs inside a sandbox, which holds here: build-release runs only in the sandbox README → Install names (`build-release: every claude it starts bypasses permissions inside its sandbox`). Claude Code doesn't document the variable. Where a later version drops it, the trust dialog comes back on those claudes, and nothing is lost. Valid while Claude Code honours `CLAUDE_CODE_SANDBOXED`. -## build-release: each project's model lives in `~/.claude/loop-claude-models.json`, which only build-release and do-epic write, through one locked function +## build-release: each project's model lives in `~/.config/build-release/models.json`, which only build-release and do-epic write, through one locked function -2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last. `~/.claude/loop-claude-models.json` has one writer: `save_model` in `bin/chunk_driver/project/model_choice.py`. The entry points, build-release and do-epic, both call it, and it holds a lock from its read to its write. Every claude they start gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 has others run the setup on their own machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session. +2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last. `~/.config/build-release/models.json` has one writer: `save_model` in `bin/chunk_driver/project/model_choice.py`. The entry points, build-release and do-epic, both call it, and it holds a lock from its read to its write. Every claude they start gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 has others run the setup on their own machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session. ## build-release: every claude it starts bypasses permissions inside its sandbox @@ -245,7 +245,7 @@ Valid while `~/.claude` is a checkout of this repo. 2026-11-16, lilleman's second call of 2026-11-13 splitting item 361: lilleman knows tmux and prefers it. Each chunk runs in its own window of one tmux session per project, `loop-<key>`, up to the number the config's `parallel-chunks` sets, 1 by default. tmux runs even at 1, so every project runs the same workflow (goal 1.3). A window waiting for the human ends its name in ` ?` and rings the bell, and the DM names `<session>:<window>`. The worker's choices, for what the call left open (`bin/agent_cycle/tmux.py`, `bin/build_release/loop/chunk_windows.py`): - **The window, in place of item 372's lock-file slot, names the claude session**, as `A <key> build-release item-372`. The build-release the human runs starts the windows and attaches; each window runs `build-release --chunk <window>`, so a loop knows its chunk before it names its claude session, and a rerun still resumes the chunk left open. -- **A finishing chunk starts the next; only the human restarts a stopped one.** As its chunk finishes, a window's loop starts each chunk that may start then and exits, so its window closes. `remain-on-exit failed` keeps the window of a loop that stopped any other way, Ctrl-C included, with its last lines, and its chunk keeps its items. A finishing chunk never restarts it, since the human may have stopped it on purpose; the next `build-release <task>` starts it again before any other chunk. One flock under `~/.local/state/loop-claude/<key>/` serializes the starts, so two chunks finishing together don't start one chunk twice. +- **A finishing chunk starts the next; only the human restarts a stopped one.** As its chunk finishes, a window's loop starts each chunk that may start then and exits, so its window closes. `remain-on-exit failed` keeps the window of a loop that stopped any other way, Ctrl-C included, with its last lines, and its chunk keeps its items. A finishing chunk never restarts it, since the human may have stopped it on purpose; the next `build-release <task>` starts it again before any other chunk. One flock under `~/.local/state/build-release/claims/<key>/` serializes the starts, so two chunks finishing together don't start one chunk twice. - **The other chunks' items are told, not locked.** A fresh worker is told the items each other chunk holds, running or stopped: its window's item and those on its latest `Chunk items:` line. A chunk starts beside the others only where its item's `Touches:` prediction overlaps none of those items' predictions, since the plan's next item, which chunk-preflight's pick checks against, may already have merged. - **The tmux session names its checkout.** Two checkouts whose keys differ only in a character other than a letter, a digit, `_` or `-` map to one session name, so the session's `@loop-root` option names the checkout that made it, and another checkout's build-release refuses it. - **tmux 3.2 is the oldest that has every command and option used.** tmux's `CHANGES` dates the newest two to "CHANGES FROM 3.1c TO 3.2": `new-session -e`, and the `remain-on-exit` value that keeps only a failed program's pane. @@ -421,7 +421,7 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r - **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, pasted from the browser with or without the title at its end, over the bare address, a page ID beside a `confluence-site` key, and a table. Each named the match with `jira:`. Any of the five records may name a page; the goals file, the plan, the working rules and the principles may not. - **`decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic.** rule-hook ranks a plan kept as a file before tool calls, inside its 30-second limit, and ranking reads those two records. A Confluence read and two adf-codec container runs would hold up every guarded tool call, and fail it while Confluence is down. `load` refuses goals in Jira beside a plan in a file for the same reason. - **A write sends the version number it writes over, plus one, and Confluence refuses it with 409 where someone saved the page since.** The store then fails, saying to ask the human, and doesn't write the page; the loop never overwrites a teammate's edit on its own (lilleman, 2026-11-12). A write handed no version replaces the page as it stands, as the record contract asks. -- **A store keeps no version: its caller hands each write the version it writes over.** lilleman chose this on 2026-11-16, when 0.11.0's release review found the version kept as the store's hidden state, which made a write rest on whichever read came before it. `project-record` keeps the version `open` read in a file beside its copy, `~/.local/state/project-record/<key>/<worktree>/<record>.version`, since `save` runs in a later process, and each save keeps the version it left for the next. Every other tool writes over the version its own read gave, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on. The folder `<worktree>` is named for the worktree that ran `open`, and `open` removes the folders of worktrees git no longer lists, so a chunk's copy doesn't outlive its worktree. +- **A store keeps no version: its caller hands each write the version it writes over.** lilleman chose this on 2026-11-16, when 0.11.0's release review found the version kept as the store's hidden state, which made a write rest on whichever read came before it. `project-record` keeps the version `open` read in a file beside its copy, `~/.local/state/build-release/project-record/<key>/<worktree>/<record>.version`, since `save` runs in a later process, and each save keeps the version it left for the next. Every other tool writes over the version its own read gave, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on. The folder `<worktree>` is named for the worktree that ran `open`, and `open` removes the folders of worktrees git no longer lists, so a chunk's copy doesn't outlive its worktree. - **The page holds ADF, which adf-codec converts both ways**, so a teammate reads the record as Confluence renders it. Where adf-codec cannot convert the markdown, the write fails with adf-codec's error. A node markdown cannot hold reads as text: a mention as its name, a macro as `_(<macro> not included)_`. So the next write replaces it with that text, and a record page should hold only what markdown can. ## project config: a tool that reads a file's commits says where it does not support that file, and the work goes on @@ -501,13 +501,13 @@ Valid while the ladder orders its rungs by competence. 2026-11-09, lilleman asked for the trials. Serves goals 1.1 and 1.4. Merged reviewers were replayed on archived first rounds, beside the separate reviewers (`reviewer-merge-trials/README.md`). Each merge cost a third to a half less, and in each, one absorbed pass lost findings. Stability, product-owner and prose as one reviewer recovered 15 of 34 prose findings, against 22 and 23 for two separate runs. The architect and the principles auditor as one recovered 5 of 17 principles findings, against 10 for one separate run, and lost both principles 🔴. Stability and product-owner as one, run twice, recovered 4 and 5 of 16 product-owner findings, against 7 and 10 for two separate runs. Folding override-reviewer into stability had no data: no archived override round holds a 🔴 or 🟡. Valid until a reviewer's definition changes, and for a project only while its rung is Opus 5.5 at medium, the rung the trials ran on: replay the merge then, with the scripts in `reviewer-merge-trials/`. -## review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/` +## review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/build-release/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/build-release/larv-review/` 2026-10-18, lilleman through todo item 73. Serves goal 1.4: a report the worker does not need line by line no longer fills its context. Goal 1.1 holds because the worker reads a finding's full entry before it answers a 🔴 or 🟡. -Each reviewer holds Write for its report. Claude Code passes a subagent's type to a PreToolUse hook as `agent_type`. So `bin/rule_hook/reviewer_report.py` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`; no marker overrides it. A reviewer's Bash, as stability-reviewer holds, is not confined. +Each reviewer holds Write for its report. Claude Code passes a subagent's type to a PreToolUse hook as `agent_type`. So `bin/rule_hook/reviewer_report.py` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/build-release/larv-review/`; no marker overrides it. A reviewer's Bash, as stability-reviewer holds, is not confined. -The folder is fixed, since build-release's headless sessions have no scratchpad, and it also holds any other file a session parks outside its checkout, such as the comprehension panel's base worktree or a build probe's output. It sits outside every checkout, so no project sees a report. It survives a reboot, unlike `/tmp`, so a resumed chunk still reads its earlier rounds. It is in the user's home, so no other local user plants a symlink that widens it. A report may quote a secret, so `larv-review review-folder`, which makes the chunk's folder, leaves `~/.local/state/larv-review` readable by the user alone. +The folder is fixed, since build-release's headless sessions have no scratchpad, and it also holds any other file a session parks outside its checkout, such as the comprehension panel's base worktree or a build probe's output. It sits outside every checkout, so no project sees a report. It survives a reboot, unlike `/tmp`, so a resumed chunk still reads its earlier rounds. It is in the user's home, so no other local user plants a symlink that widens it. A report may quote a secret, so `larv-review review-folder`, which makes the chunk's folder, leaves `~/.local/state/build-release/larv-review` readable by the user alone. A chunk keeps its folder after the merge. `review-replay` hands a replayed reviewer a copy holding only the reports written after the chunk began and before the round did. So the replay reads the earlier rounds its prompt names, never the findings it is to find. The chunk's own reports stay as they were. @@ -732,7 +732,7 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default 2026-11-14, lilleman ruled that L 3 is to step one rung up and L 4 two up, in every project and for delegated subagents. The steps take effect in 0.12.0, as lilleman chose on 2026-11-16. On an Opus 5.5 project, an L 3 worker or subagent runs on Fable 5.2 at low, and an escalation stops without lilleman's yes at Opus 5.5 at xhigh. An L 4 one runs on Fable 5.2 at medium, and stops at Fable 5.2 at high. The ruling settles the two calls that `routing-calls-raised.md` stamps 2026-11-14T13:57:34Z, raised on the routing figures measured at 2026-11-14T00:59:50Z. The figures came from 276 chunks finished since the 2026-10-29 reset. Chunks started on Opus 5.5 at medium, 79 of them, took a mean 0.8 review rounds past each pass's first, 0.3 unfinished verdicts and 0.2 later fixes. Chunks started on Fable 5.2 at low, 5 of them, took 0.4, 0.0 and 0.0. Under the old steps, only L 4 items started on Fable 5.2 at low on an Opus 5.5 project, so it did better on harder items. Two things weaken the evidence: 5 chunks is the fewest a call allows, and the Opus 5.5 figures include chunks from before Fable 5.2 joined the ladder. On the 2026-11-11 index, an L 3 task's cost rises about 1.3 times, from $2.45 to $3.10, for fewer rounds and fewer unfinished verdicts (goal 1.4). The chunks started on Sonnet 5.5 at high, 164 of the 276, don't move. -2026-11-15, lilleman asked for the ladder as a file that a project can replace, on a day when an outage left only Fable 5.2 answering: the rungs were a constant in `bin/model_routing/ladder.py`, so no project could leave Sonnet 5.5 and Opus 5.5 without a release. The shipped ladder is `bin/model_routing/routing-ladder.json`, a JSON list of rungs, least competent first. A project that keeps a `routing-ladder.json` in its config's folder, `~/.claude-projects/<key>/`, runs on that ladder whole, and the steps count on it as on the shipped one. Every project still runs the same routing rules and steps, so the workflow of goal 1.3 holds; the ladder joins what a project's config folder may supply, which that goal's list does not name yet. lilleman chose a file per project over one per machine, so a single project can differ. A ladder holds one model of each family, since the Agent tool launches a subagent or a review by its family's name. The project's file is lilleman's to write, as any change to the ladder is, and the loop never commits it. build-release reads the project's ladder as each cycle starts; `subagent-rung` and rule-hook's `reviewer-rung` read it each time they run, from the checkout they run in. A ladder file that holds a fault stops each of them, since work routed on the shipped ladder in its place could run on a model the project cannot reach. The routing figures, `judge-replay` and `review-replay` span every project, so they read the shipped ladder: a rung only a project's own ladder holds is left out of the figures' calls, and no replay qualifies it. lilleman shipped the change as 0.10.1, a patch cut from the tag v0.10.0, on the day of the outage: it adds a file format and an exit 1 to `subagent-rung`, which the technical principles' semantic versioning gives a minor, and lilleman asked for the patch "even if that breaks semver", so that the release in use could run again without taking the unreleased work on `main`. +2026-11-15, lilleman asked for the ladder as a file that a project can replace, on a day when an outage left only Fable 5.2 answering: the rungs were a constant in `bin/model_routing/ladder.py`, so no project could leave Sonnet 5.5 and Opus 5.5 without a release. The shipped ladder is `bin/model_routing/routing-ladder.json`, a JSON list of rungs, least competent first. A project that keeps a `routing-ladder.json` in its config's folder, `~/.config/build-release/<key>/`, runs on that ladder whole, and the steps count on it as on the shipped one. Every project still runs the same routing rules and steps, so the workflow of goal 1.3 holds; the ladder joins what a project's config folder may supply, which that goal's list does not name yet. lilleman chose a file per project over one per machine, so a single project can differ. A ladder holds one model of each family, since the Agent tool launches a subagent or a review by its family's name. The project's file is lilleman's to write, as any change to the ladder is, and the loop never commits it. build-release reads the project's ladder as each cycle starts; `subagent-rung` and rule-hook's `reviewer-rung` read it each time they run, from the checkout they run in. A ladder file that holds a fault stops each of them, since work routed on the shipped ladder in its place could run on a model the project cannot reach. The routing figures, `judge-replay` and `review-replay` span every project, so they read the shipped ladder: a rung only a project's own ladder holds is left out of the figures' calls, and no replay qualifies it. lilleman shipped the change as 0.10.1, a patch cut from the tag v0.10.0, on the day of the outage: it adds a file format and an exit 1 to `subagent-rung`, which the technical principles' semantic versioning gives a minor, and lilleman asked for the patch "even if that breaks semver", so that the release in use could run again without taking the unreleased work on `main`. 2026-11-18, lilleman kept the ladder and the steps, settling the call raised on the routing figures measured at 2026-11-18T15:04:48Z: chunks routed onto Sonnet 5.5 at high took more review rounds past each pass's first than chunks routed onto Opus 5.5 at medium. The figures came from 19 chunks finished since the 2026-11-17 reset. The 13 chunks started on Sonnet 5.5 at high took a mean 0.5 rounds and 0.0 unfinished verdicts; the 6 started on Opus 5.5 at medium took 0.5 and 0.2. Neither rung had later fixes, among the 11 and the 4 chunks whose later fixes are known. Both means show 0.5, so the gap is under 0.1 rounds. Sonnet 5.5 did better on unfinished verdicts, and it is the cheaper rung (goal 1.4). build-release lists the call in `routing-calls-raised.md` only once the session that put it to lilleman ends, stamped with the time the figures were measured, so this note cites that time. @@ -836,7 +836,7 @@ Valid while Claude Code loads `~/.claude/rules/*.md` in every project, a path-sc ## settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit -2026-10-21, lilleman. Serves goal 2: Claude Code rewrites `"model"` in `settings.json` on every `/model` and plugin install, so a tracked model let one machine's pick override every other's. lilleman chose a model per machine over one synced in `env.ANTHROPIC_MODEL`, which would override a `/model` pick from the next session on. A model per machine is simpler, and build-release picks each project's model in `~/.claude/loop-claude-models.json` anyway. The filter also sorts the keys, since each write puts them back in Claude Code's order. The cost: a move or pull that changes `settings.json` drops the machine's model. The effort keys, `effortLevel` and `modelSettings`, stay synced: the routing decision on a chunk's worker rung relies on the effort `settings.json` gives every interactive session. Valid while Claude Code writes the model it picks into `settings.json`. +2026-10-21, lilleman. Serves goal 2: Claude Code rewrites `"model"` in `settings.json` on every `/model` and plugin install, so a tracked model let one machine's pick override every other's. lilleman chose a model per machine over one synced in `env.ANTHROPIC_MODEL`, which would override a `/model` pick from the next session on. A model per machine is simpler, and build-release picks each project's model in `~/.config/build-release/models.json` anyway. The filter also sorts the keys, since each write puts them back in Claude Code's order. The cost: a move or pull that changes `settings.json` drops the machine's model. The effort keys, `effortLevel` and `modelSettings`, stay synced: the routing decision on a chunk's worker rung relies on the effort `settings.json` gives every interactive session. Valid while Claude Code writes the model it picks into `settings.json`. ## task-bench: a bench takes 5 bugs and 5 runs per side, after a 2 × 2 pilot on a new setup, and at no affordable count does a chunk-sized change rise above the noise diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 178487e8..f7a6b462 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -4016,3 +4016,15 @@ Read most (opens and searches): - `bin/agent_cycle/run.py` 2 - `bin/loop_claude/loop/test_usage.py` 2 - `bin/model_routing/worker_rungs.py` 2 + +## Reading cost, chunk 6036c9ce08ad, finished 2026-12-03T16:14:50Z + +74380 new input tokens before the first commit. + +Read most (opens and searches): + +- `.gitignore` 5 +- `ci.sh` 2 +- `bin/repo_checks/test_gitignore.py` 1 +- `bin/run-tests` 1 +- `settings.json` 1 diff --git a/reviewer-merge-trials/driver.py b/reviewer-merge-trials/driver.py index b6edc462..2cf7422c 100644 --- a/reviewer-merge-trials/driver.py +++ b/reviewer-merge-trials/driver.py @@ -5,7 +5,7 @@ from claude_code.reply import claude_reply, Limited from review_replay.replay import clone_reviewed, Copies, copy_reports, match, redirected from failure import Failure from review_replay.rounds import lost_inputs, Round -from review_rules.review_folder import REPORTS, review_folder +from review_rules.review_folder import reports_folder, review_folder from review_replay import replay as rm from model_routing.ladder import Rung from loop_effects.effects import system_effects @@ -21,10 +21,10 @@ def as_round(r): return Round(r["reviewer"], r["checkout"], r["branch"], r["at"], r["began"], r["prompt"], tuple(r["findings"])) def prepared(rnd, code, copies, clone=None, cutoff=None): - folder = pathlib.Path(review_folder(str(HOME), code.path)) + folder = pathlib.Path(review_folder(str(HOME), os.environ, code.path)) # Every variant of a case sees only the reports written before the case's first round, so no variant is handed another pass's findings. copy_reports(cutoff or rnd, folder, copies.reports) - p = redirected(rnd.prompt, HOME, folder, code.path, copies) + p = redirected(rnd.prompt, HOME, folder, reports_folder(HOME, os.environ), code.path, copies) if isinstance(p, Failure): return p # Inputs rewritten after the round: ls-files is regenerated from the clone; a places list cannot be, so its file says it is missing. for name in lost_inputs(p, copies.reports, lambda n: (pathlib.Path(copies.reports) / n).exists()): @@ -42,11 +42,11 @@ def run(rounds, codes, agent_args, prompt_of, out, cutoff=None): """Clone at the first round's code, prepare prompts, run claude, keep reply and reports written.""" if out.exists(): return json.loads(out.read_text()) - (HOME / REPORTS).mkdir(parents=True, exist_ok=True) + reports_folder(HOME, os.environ).mkdir(parents=True, exist_ok=True) (HERE / "clones").mkdir(exist_ok=True) first = rounds[0] with tempfile.TemporaryDirectory(prefix="rm-", dir=HERE / "clones", ignore_cleanup_errors=True) as clone, \ - tempfile.TemporaryDirectory(prefix="review-replay-rm-", dir=HOME / REPORTS, ignore_cleanup_errors=True) as reports: + tempfile.TemporaryDirectory(prefix="review-replay-rm-", dir=reports_folder(HOME, os.environ), ignore_cleanup_errors=True) as reports: copies = Copies(clone, reports) if isinstance(c := clone_reviewed(first, codes[first], clone, FX), Failure): return {"error": c.reason} prompts = [] diff --git a/rules/goals-and-audience.md b/rules/goals-and-audience.md index cf91ff11..534e4e01 100644 --- a/rules/goals-and-audience.md +++ b/rules/goals-and-audience.md @@ -1,7 +1,7 @@ --- paths: - "**/README.md" - - "**/.claude-projects/*/goals.md" + - "**/.config/build-release/*/goals.md" --- # Goals and Audience diff --git a/settings.json b/settings.json index 2159d926..cd8e80af 100644 --- a/settings.json +++ b/settings.json @@ -56,7 +56,7 @@ }, "permissions": { "additionalDirectories": [ - "~/.local/state/larv-review", + "~/.local/state/build-release/larv-review", "~/code" ], "defaultMode": "auto" diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 246e3b68..d638cd8f 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -72,7 +72,7 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h `larv-review` holds this section's mechanical rules: the chunk's review folder, the round count and each round commit's counts, the paired ruling's base and vote count, the scoring run's trigger; the history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt. Run it in the chunk's worktree; `larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user. -**Reports.** Run `larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folders of technical principles and review standards the project's config sets, the files of coding conventions where it lists any, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names, and `compress-archives` gzips each file 30 days after it last changed. +**Reports.** Run `larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folders of technical principles and review standards the project's config sets, the files of coding conventions where it lists any, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/build-release/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names, and `compress-archives` gzips each file 30 days after it last changed. **Claimed output.** Before the Product-owner or Prose pass launches in a round, find the lines the diff adds or changes that say what a command, flag or error prints, such as "the error names the fix", or what a command writes, such as "the diff of the regenerated file holds only X". In round 2, take only the lines the round's fixes changed. Those reviewers have no shell, and reading code can't show that an output holds the words a line claims. -- 2.52.0 From 1ace7ee8d97a4c57bf2631126cd395c913219e1c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 19:04:04 +0100 Subject: [PATCH 04/15] Record the reading cost of item 484's chunk --- docs/reading-cost.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index f7a6b462..30b43221 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -4028,3 +4028,11 @@ Read most (opens and searches): - `bin/repo_checks/test_gitignore.py` 1 - `bin/run-tests` 1 - `settings.json` 1 + +## Reading cost, chunk df66ed70af32, finished 2026-12-03T17:15:08Z + +50093 new input tokens before the first commit. + +Read most (opens and searches): + +- `agents/stability-reviewer.md` 2 -- 2.52.0 From dc8504e4cabdaa49ce9f9e4931fd67c973cb1bc8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 19:06:00 +0100 Subject: [PATCH 05/15] Drop the changelog sentence the folder move makes false --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d23aeb29..d8a9ed23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- Renamed `loop-claude` to `build-release`, with no alias. Before you update, finish your open chunks, since a chunk left open under `loop-claude` starts a fresh session, and stop every running `loop-claude`, since a loop that runs across the update can't reload and hands its workers variables the new rule-hook ignores. Then remove `~/.local/bin/loop-claude`, link the new name with `ln -s ~/.claude/bin/build-release ~/.local/bin/build-release`, and rename each `LOOP_CLAUDE_*` variable you set, in your shell profile and in your crontab, to `BUILD_RELEASE_*`, such as `BUILD_RELEASE_TRANSCRIPTS`. The folders and the file it keeps, `~/.claude/loop-claude-transcripts`, `~/.claude/loop-claude-models.json` and `~/.local/state/loop-claude`, keep their names for now. +- Renamed `loop-claude` to `build-release`, with no alias. Before you update, finish your open chunks, since a chunk left open under `loop-claude` starts a fresh session, and stop every running `loop-claude`, since a loop that runs across the update can't reload and hands its workers variables the new rule-hook ignores. Then remove `~/.local/bin/loop-claude`, link the new name with `ln -s ~/.claude/bin/build-release ~/.local/bin/build-release`, and rename each `LOOP_CLAUDE_*` variable you set, in your shell profile and in your crontab, to `BUILD_RELEASE_*`, such as `BUILD_RELEASE_TRANSCRIPTS`. - A claude that build-release, do-epic or `task-bench gather` starts has the release's tools first on its `PATH`, and the rules, the skills and each tool's help and errors name a tool bare, as in `todo-item`. In your own shell, and in a claude you start from it yourself, call a tool other than `build-release` by its path, `~/.claude/bin/<tool>`. - do-epic runs `chunk-pr clean` itself for a chunk whose pull request merged, finishes the chunk and closes its window, without a running slot or a worker, where it used to wait for a free slot and a worker for that. - Make `task-bench` commit the copy it runs each side's tests in, so a project's tests that call git, such as `git ls-files`, pass the baseline instead of failing with "not a git repository". -- 2.52.0 From 6df7bed25b5539ec68ee2da093a7d54b6782b7ac Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 19:25:40 +0100 Subject: [PATCH 06/15] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20say=20what?= =?UTF-8?q?=20holds=20under=20an=20XDG=20variable=20in=20the=20decision=20?= =?UTF-8?q?and=20the=20path=20comments?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_driver/project/model_choice.py | 2 +- bin/do_epic/config.py | 6 +++--- bin/do_epic/scheduler.py | 2 +- bin/loop_state/paths.py | 8 ++++---- bin/project_config/settings.py | 2 +- bin/project_record/main.py | 4 +++- bin/transcript_archive/__init__.py | 2 +- docs/decisions.md | 2 +- 8 files changed, 15 insertions(+), 13 deletions(-) diff --git a/bin/chunk_driver/project/model_choice.py b/bin/chunk_driver/project/model_choice.py index 0797cc23..114bdfdd 100644 --- a/bin/chunk_driver/project/model_choice.py +++ b/bin/chunk_driver/project/model_choice.py @@ -21,7 +21,7 @@ class Models: # The environment variables that name the judge's and the worker's model for one run, over the model saved or configured. JUDGE_MODEL = "BUILD_RELEASE_JUDGE_MODEL" WORKER_MODEL = "BUILD_RELEASE_WORKER_MODEL" -# The file, in the claims folder, that save_model keeps locked with flock while it rereads and replaces the models file. The models file's own folder is the config folder, which a person backs up, so it takes no lock file. +# The file, in the claims folder, that save_model keeps locked with flock while it rereads and replaces the models file. The models file's own folder is the config folder, which a person backs up, so the lock file is kept out of it. MODELS_LOCK = "models.lock" diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index 01192dad..f4c6f04c 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -1,4 +1,4 @@ -"""do-epic's machine-wide settings: `~/.config/build-release/do-epic/config.toml`, and `repo-rule.md` beside it. +"""do-epic's machine-wide settings: `do-epic/config.toml` in the config folder (`loop_state.paths.config_folder`), and `repo-rule.md` beside it. One pair per machine, the same for every epic (docs/decisions.md → `do-epic: drives one Jira epic …`). The config is TOML: @@ -12,7 +12,7 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d twu-4 = "tenant-web-ui-4" - `jira-url` is the Jira site's address: https, a host, and no path. -- `env-file` is the file of Jira credentials: a path that starts with / or ~/, outside every folder of `~/.config/build-release` and outside the clone folder, which hold git checkouts. `~/.config/build-release/<key>.env` is fine. +- `env-file` is the file of Jira credentials: a path that starts with / or ~/, outside every folder of the config folder and outside the clone folder, which hold git checkouts. `<key>.env` in the config folder itself is fine. - `repoless-model` is the model that works an epic item with no repo: a model on the routing ladder, `model_routing/routing-ladder.json`. - `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out. - `language` is the default language of Jira text, by its English name. English where left out. @@ -66,7 +66,7 @@ LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTION @dataclasses.dataclass(frozen=True) class DoEpicConfig: - """folder is `~/.config/build-release/do-epic`; repo_rule is `repo-rule.md`'s text.""" + """folder is `do-epic` in the config folder; repo_rule is `repo-rule.md`'s text.""" folder: pathlib.Path jira_url: str env_file: pathlib.Path diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index 19822d35..b088cf2c 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -18,7 +18,7 @@ from chunk_pr.approval import PARKS from loop_state.paths import state_folder from agent_cycle import tmux -# In the state folder, where a folder per epic key holds the epic's lock file, which `claims.LOCK` names. A chunk without a repo works there. +# The folder in the state folder where a folder per epic key holds the epic's lock file, which `claims.LOCK` names. A chunk without a repo works there. STATE = "do-epic" diff --git a/bin/loop_state/paths.py b/bin/loop_state/paths.py index 54a24f78..383d6f7b 100644 --- a/bin/loop_state/paths.py +++ b/bin/loop_state/paths.py @@ -12,12 +12,12 @@ RELEASE_ROOT = pathlib.Path(__file__).resolve().parents[2] # The Claude home: Claude Code's own folder, with its settings and transcripts. A release is deployed into it, so its CLAUDE.md, rules/ and agents/ are read from it. CLAUDE_HOME = ".claude" -# The setup's own folder under each of the two below. +# The name of the setup's own folder, in the config home and in the state home. SETUP = "build-release" -# Where the config folder is, unless the variable XDG_CONFIG_HOME names another place. +# The config home, which holds the config folder, unless the variable XDG_CONFIG_HOME names another. CONFIG_HOME = ".config" XDG_CONFIG_HOME = "XDG_CONFIG_HOME" -# Where the state folder is, unless the variable XDG_STATE_HOME names another place. +# The state home, which holds the state folder, unless the variable XDG_STATE_HOME names another. STATE_HOME = ".local/state" XDG_STATE_HOME = "XDG_STATE_HOME" @@ -40,7 +40,7 @@ def config_folder(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path: def state_folder(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path: """The state folder, which the tools write: one folder per tool.""" - # Every tool keeps its state here, none beside it, so that deleting this folder removes all the state the setup wrote. + # Every tool keeps its state here, none beside it in the state home. Only an archive that BUILD_RELEASE_TRANSCRIPTS names is elsewhere. return xdg_folder(env.get(XDG_STATE_HOME), home / STATE_HOME) / SETUP diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index db9ea9ed..be25fba7 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -1,4 +1,4 @@ -"""A project's settings, read from the one config that names its checkout: `<key>/config.toml` in the config folder, `~/.config/build-release/` unless `XDG_CONFIG_HOME` is set. +"""A project's settings, read from the one config that names its checkout: `<key>/config.toml` in the config folder, `~/.config/build-release/` unless `XDG_CONFIG_HOME` holds an absolute path. No path setting has a default, so that a client's project never runs on another project's files: a missing config or setting is a Failure that names it.""" import dataclasses diff --git a/bin/project_record/main.py b/bin/project_record/main.py index 49de4ba5..5917fade 100644 --- a/bin/project_record/main.py +++ b/bin/project_record/main.py @@ -25,6 +25,8 @@ saved it after open read it or after save last wrote it, and the human decides w until open runs again and writes the copy afresh. Exit 2 on bad arguments, and 1, saying why, on any other failure. + +Where XDG_STATE_HOME holds an absolute path, read ~/.local/state in this help as that path. """ import hashlib import os @@ -41,7 +43,7 @@ from loop_state.paths import state_folder # Not git's verbs, such as checkout and commit: those read as acting on the repo. COMMANDS = ("open", "save") -# Where the copy of a record kept outside files goes, under the user's home, in a folder per project and worktree. +# Where the copy of a record kept outside files goes, under the state folder, in a folder per project and worktree. COPIES = "project-record" # The goals file opens like a record, though it is a setting of its own. GOALS = "goals-and-audience" diff --git a/bin/transcript_archive/__init__.py b/bin/transcript_archive/__init__.py index 3181f346..f81a7016 100644 --- a/bin/transcript_archive/__init__.py +++ b/bin/transcript_archive/__init__.py @@ -5,7 +5,7 @@ <archive root>/<project key>/<chunk>/session/... <archive root>/<project key>/<chunk>/judge/<sha256>.json -- The archive root is $BUILD_RELEASE_TRANSCRIPTS, or ~/.local/state/build-release/transcripts (location.archive_root). +- The archive root is $BUILD_RELEASE_TRANSCRIPTS, or `transcripts` in the state folder (location.archive_root). - The project key is the checkout's path relative to ~/code, or to / outside it (project_key.project_key). - <chunk> is the hash of the transcript's first line with a timestamp (location.chunk_folder). It is the same for every cycle of a chunk, and differs between chunks, since a finished chunk's session is deleted diff --git a/docs/decisions.md b/docs/decisions.md index 66e64a36..82df78e3 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -507,7 +507,7 @@ Valid while the ladder orders its rungs by competence. Each reviewer holds Write for its report. Claude Code passes a subagent's type to a PreToolUse hook as `agent_type`. So `bin/rule_hook/reviewer_report.py` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/build-release/larv-review/`; no marker overrides it. A reviewer's Bash, as stability-reviewer holds, is not confined. -The folder is fixed, since build-release's headless sessions have no scratchpad, and it also holds any other file a session parks outside its checkout, such as the comprehension panel's base worktree or a build probe's output. It sits outside every checkout, so no project sees a report. It survives a reboot, unlike `/tmp`, so a resumed chunk still reads its earlier rounds. It is in the user's home, so no other local user plants a symlink that widens it. A report may quote a secret, so `larv-review review-folder`, which makes the chunk's folder, leaves `~/.local/state/build-release/larv-review` readable by the user alone. +The folder is the same for every session on the machine, since build-release's headless sessions have no scratchpad, and it also holds any other file a session parks outside its checkout, such as the comprehension panel's base worktree or a build probe's output. It sits outside every checkout, so no project sees a report. It survives a reboot, unlike `/tmp`, so a resumed chunk still reads its earlier rounds. It is in the user's home, so no other local user plants a symlink that widens it; a user who sets `XDG_STATE_HOME` to a path outside their home answers for that. rule-hook takes the variable from its own environment, which a reviewer cannot change. A report may quote a secret, so `larv-review review-folder`, which makes the chunk's folder, leaves the review reports folder, `~/.local/state/build-release/larv-review` by default, readable by the user alone. A chunk keeps its folder after the merge. `review-replay` hands a replayed reviewer a copy holding only the reports written after the chunk began and before the round did. So the replay reads the earlier rounds its prompt names, never the findings it is to find. The chunk's own reports stay as they were. -- 2.52.0 From 55f87fb34edd743e5d65d921566708248cc7d372 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 19:25:40 +0100 Subject: [PATCH 07/15] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20each=20h?= =?UTF-8?q?elp=20says=20how=20an=20XDG=20variable=20moves=20its=20paths,?= =?UTF-8?q?=20the=20goals=20rule=20loads=20under=20any=20config=20home,=20?= =?UTF-8?q?and=20the=20cron=20line=20makes=20its=20folder?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CLAUDE.md | 4 ++-- README.md | 6 +++--- bin/build_release/loop/usage.py | 11 +++++++---- bin/compress_archives/main.py | 2 ++ bin/do_epic/backend/jira.py | 2 +- bin/do_epic/backend/test_jira.py | 4 ++-- bin/do_epic/main.py | 6 ++++-- bin/judge_replay/main.py | 3 +++ bin/larv_review/main.py | 2 ++ bin/notifier/main.py | 2 ++ bin/project_config/main.py | 3 ++- bin/reading_cost/main.py | 2 ++ bin/review_replay/main.py | 3 +++ bin/rule_hook/rules.py | 6 +++--- bin/subagent_rung/main.py | 2 ++ rules/goals-and-audience.md | 2 +- skills/larv-review/SKILL.md | 2 +- 17 files changed, 42 insertions(+), 20 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 12033dfe..850a38bd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -89,7 +89,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, are th 4. A review rules the work below standard: systems-architect's BLOCK, a finding against the review standards' `quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up"). It doesn't fire where the fix changes only prose (`larv-review` §3 says what is prose): fix that on your own rung. When one fires, hand the hard part, edits included, to a subagent on the rung build-release's prompt names, one above yours. Open the subagent's prompt with the marker build-release's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung build-release's prompt names. Ask the human before going higher. Where build-release's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread. -- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/build-release/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`larv-review review-folder` prints it), and removes no image or file it did not create. +- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/build-release/larv-review/` (under `$XDG_STATE_HOME` instead of `~/.local/state`, where that holds an absolute path), and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`larv-review review-folder` prints it), and removes no image or file it did not create. - Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer. - Where `rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest or a `docker run` line, pin a container image to its full patch version and a GitHub Action to a semver tag. @@ -105,7 +105,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, are th - PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title). - Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`. - Branch for a plan item without a ticket: `item-<ID>`, in the worktree `<checkout>-item-<ID>` beside the checkout, as `chunk-preflight` makes them. Under a `branch` template, `chunk-preflight` names both by the template. -- Where the project's config keeps a file in the config's folder, `~/.config/build-release/<key>/`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Two chunks may commit there at once, so commit only that file: `git commit -m <title> -- <file>`, after `git add <file>` where it is new. Where git finds `index.lock` held, the other chunk is committing: try again. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title. +- Where the project's config keeps a file in the config's folder, `~/.config/build-release/<key>/` (under `$XDG_CONFIG_HOME` instead of `~/.config`, where that holds an absolute path), such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Two chunks may commit there at once, so commit only that file: `git commit -m <title> -- <file>`, after `git add <file>` where it is new. Where git finds `index.lock` held, the other chunk is committing: try again. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title. - Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both. - On GitHub and Gitea, open a chunk's pull request as a draft, mark it ready and merge it with `chunk-pr`, which picks `gh` or `tea` from the remote; `chunk-pr --help` says how. Once it has merged, run `chunk-pr clean` in the chunk's worktree: it removes the worktree and the branch and fast-forwards the main checkout. diff --git a/README.md b/README.md index 9d4351f0..558d5942 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ Then pick a model with `/model`. Link `build-release` onto `PATH`: `ln -s ~/.claude/bin/build-release ~/.local/bin/build-release`. Every claude it starts, the interactive ones included, skips every permission prompt. build-release runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later. -The setup keeps what you write in the config folder, `~/.config/build-release/`, and what its tools write in the state folder, `~/.local/state/build-release/`. Where `XDG_CONFIG_HOME` or `XDG_STATE_HOME` is set, the folder is `build-release/` under the folder that variable names instead. Back up these four folders: +The setup keeps each project's config, and what you choose for a project, in the config folder, `~/.config/build-release/`. Everything else its tools write is in the state folder, `~/.local/state/build-release/`. Where `XDG_CONFIG_HOME` holds an absolute path, the config folder is `build-release/` under that path instead, and likewise the state folder under `XDG_STATE_HOME`; this README spells the defaults. Set such a variable in the environment Claude Code starts in, since rule-hook reads it there. `settings.json` names only the default review folder, `~/.local/state/build-release/larv-review`, in `additionalDirectories`: where `XDG_STATE_HOME` moves that folder, add it there yourself, or an interactive session asks before a reviewer writes its report. Back up these four folders: - `~/.config/build-release/`: each project's config, a client project's plan and records, and `models.json`, the model of each project, which build-release and do-epic write. A project's `env-file`, if you keep it here as below, puts credentials in the backup, so keep the backup private. - `~/.local/state/build-release/transcripts`: every transcript build-release keeps. Where you set `BUILD_RELEASE_TRANSCRIPTS`, back up the folder it names instead. @@ -95,10 +95,10 @@ Leave out Claude Code's memory files in `~/.claude/projects/<folder>/memory/`: C To keep build-release's transcripts and the reports small, add a crontab line that gzips each transcript and review file 30 days after it last changed, and logs each run with its date: ```sh -17 4 * * * { date; $HOME/.claude/bin/compress-archives; } >> $HOME/.local/state/build-release/compress-archives.log 2>&1 +17 4 * * * mkdir -p $HOME/.local/state/build-release && { date; $HOME/.claude/bin/compress-archives; } >> $HOME/.local/state/build-release/compress-archives.log 2>&1 ``` -Cron runs it with its own `PATH` and environment. Where the `python3` on cron's `PATH` is older than 3.14, or you set `BUILD_RELEASE_TRANSCRIPTS`, set `PATH` or that variable in the crontab too. +Cron runs it with its own `PATH` and environment. Where the `python3` on cron's `PATH` is older than 3.14, or you set `BUILD_RELEASE_TRANSCRIPTS` or `XDG_STATE_HOME`, set `PATH` or that variable in the crontab too. With `XDG_STATE_HOME`, write its folder in place of `$HOME/.local/state` in the line as well. To get build-release's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.config/build-release/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.config/build-release/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes. diff --git a/bin/build_release/loop/usage.py b/bin/build_release/loop/usage.py index 7a86d33d..56cb2a3f 100644 --- a/bin/build_release/loop/usage.py +++ b/bin/build_release/loop/usage.py @@ -4,9 +4,9 @@ usage: build-release <task> Run it anywhere inside a project checkout whose goals file has ## Goals and ## Audience, the premises. The goals file is the one the project's config, ~/.config/build-release/<key>/config.toml, -sets as goals-and-audience: a file, or a Jira epic's description. `project-config -goals-and-audience` -prints where it is. The task runs at the checkout root. Each cycle a worker runs the task. A chunk's +sets as goals-and-audience: a file, or a Jira epic's description. +`project-config goals-and-audience` prints where it is. The task runs at the checkout root. Each +cycle a worker runs the task. A chunk's first worker prompt also quotes the premises. They, with code health (the setup's CLAUDE.md → "Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the chunk's plan items, or else the task, and never widen them. A judge then reads the transcript's end, @@ -207,4 +207,7 @@ Exit 2, when the human is needed to go on: anything typed - the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more Rerunning build-release <task> starts the chunks that may start, a stopped one first, and each -resumes its claude session where it is open.""" +resumes its claude session where it is open. + +Where XDG_CONFIG_HOME holds an absolute path, read ~/.config in this help as that path. +Where XDG_STATE_HOME holds an absolute path, read ~/.local/state in this help as that path.""" diff --git a/bin/compress_archives/main.py b/bin/compress_archives/main.py index e80d59df..278d14aa 100644 --- a/bin/compress_archives/main.py +++ b/bin/compress_archives/main.py @@ -13,6 +13,8 @@ its plain name. README.md → Install has the crontab line that runs it daily. It prints how many files it compressed. It exits 1, saying why, on any argument but --help or -h, and at the first file it cannot compress, leaving that file and every one after it plain. + +Where XDG_STATE_HOME holds an absolute path, read ~/.local/state in this help as that path. """ import pathlib import stat diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 67c59985..8ab9c9c9 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -17,7 +17,7 @@ from do_epic.backend.jira_start import Start, started FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"] # How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes. PARENTS_PER_SEARCH = 50 -NO_FINISH = "do-epic's settings name no transition to {to} by: set `{transition}` and `{status}` in ~/.config/build-release/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"" +NO_FINISH = "do-epic's settings name no transition to {to} by: set `{transition}` and `{status}` in do-epic's config.toml (`do-epic --help` says where), to the names Jira shows, such as \"Mark as done\" and \"Done\"" @dataclasses.dataclass(frozen=True) diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 48f66c83..f7161a4f 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -228,7 +228,7 @@ class Jira(Case): no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) unconverted = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it"), Finish("Mark as done", "Done")) for store, reason in ( - (unnamed, "do-epic's settings name no transition to close an epic by: set `jira-finish-transition` and `jira-finish-status` in ~/.config/build-release/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\""), + (unnamed, "do-epic's settings name no transition to close an epic by: set `jira-finish-transition` and `jira-finish-status` in do-epic's config.toml (`do-epic --help` says where), to the names Jira shows, such as \"Mark as done\" and \"Done\""), (wrong_status, "ABC-12's transition 'Start' leads to the status 'In Progress', not to 'Done', which `jira-finish-status` names"), (unconverted, "cannot convert the summary to a Jira comment: adf-codec refused it"), ): @@ -523,7 +523,7 @@ class Jira(Case): unnamed = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) wrong_status = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Mark as done", "Closed")) no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) - self.assertEqual(unnamed.finish_issue(key), Failure("do-epic's settings name no transition to finish an issue by: set `jira-finish-transition` and `jira-finish-status` in ~/.config/build-release/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"")) + self.assertEqual(unnamed.finish_issue(key), Failure("do-epic's settings name no transition to finish an issue by: set `jira-finish-transition` and `jira-finish-status` in do-epic's config.toml (`do-epic --help` says where), to the names Jira shows, such as \"Mark as done\" and \"Done\"")) self.assertEqual(wrong_status.finish_issue(key), Failure(f"{key}'s transition 'Mark as done' leads to the status 'Done', not to 'Closed', which `jira-finish-status` names")) refused = no_such.finish_issue(key) assert isinstance(refused, Failure) diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 45258e19..7f2fbc61 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -73,8 +73,10 @@ request is ready, with nothing else to wait on, the window's name says `awaits y A repo that is missing isn't cloned. Planning then stops there, so its writes are only those made before it, and the issues of that repo wait, and a chunk of another repo may start in the place a real run gives them; a real run would clone it and go on. {findings.HELP} {finish.HELP} -The Jira site and its credentials are set in ~/.config/build-release/do-epic/config.toml.""" -# In the state folder, where a chunk's cycles are archived, a folder per epic. It is not build-release's archive, since that archive's readers, such as judge-replay and the routing figures, read build-release's prompts. +The Jira site and its credentials are set in ~/.config/build-release/do-epic/config.toml. + +Where XDG_CONFIG_HOME holds an absolute path, read ~/.config in this help as that path.""" +# The folder in the state folder where a chunk's cycles are archived, in a folder per epic. It is not build-release's archive, since that archive's readers, such as judge-replay and the routing figures, read build-release's prompts. ARCHIVE = "do-epic-transcripts" # The flag that prints what each open issue does. STATUS_FLAG = "--status" diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index a5d5703f..5d49423f 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -48,6 +48,9 @@ fifths. The classifier trains 330 regressions in Python, about 12 minutes on 1,1 kept in replays/judge-replay-<model>-offline-<UTC stamp>/result.md. A verdict whose transcript cannot be read is skipped, and the report counts the skipped. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived verdict of the model's projects, or none with a transcript that can be read. + +Where XDG_CONFIG_HOME holds an absolute path, read ~/.config in this help as that path. +Where XDG_STATE_HOME holds an absolute path, read ~/.local/state in this help as that path. """ import pathlib import sys diff --git a/bin/larv_review/main.py b/bin/larv_review/main.py index dccc2a6a..81891e3e 100644 --- a/bin/larv_review/main.py +++ b/bin/larv_review/main.py @@ -164,6 +164,8 @@ breaks the shape above, a todo.md that fails rank_todo.py after record-scoring r when git cannot start, finds no checkout or no default branch, cannot fetch origin for ruling-base, needs-scoring-run, scoring-run-owed or record-scoring, or cannot read or write the history, todo.md, the review folder or a file prepare-scoring reads. + +Where XDG_STATE_HOME holds an absolute path, read ~/.local/state in this help as that path. """ import os import pathlib diff --git a/bin/notifier/main.py b/bin/notifier/main.py index daa6eafe..81258afa 100644 --- a/bin/notifier/main.py +++ b/bin/notifier/main.py @@ -25,6 +25,8 @@ Exit 2, saying why, on misuse: bad arguments, an empty message, a directory with a config that sets no `notifier` or no `env-file`, or an env file that is missing or unreadable, lacks a key, names a Mattermost server off https, or that others may read. None of these messages holds the token. + +Where XDG_CONFIG_HOME holds an absolute path, read ~/.config in this help as that path. """ import typing diff --git a/bin/project_config/main.py b/bin/project_config/main.py index b8ec797b..93e7ae70 100644 --- a/bin/project_config/main.py +++ b/bin/project_config/main.py @@ -5,7 +5,6 @@ usage: project-config [<setting>] Run inside a checkout, or a worktree of one. It finds the config that names the checkout, ~/.config/build-release/<key>/config.toml, and prints each setting and its absolute path, as in `plan: /home/me/code/acme/todo.md`. Given a setting, it prints only that setting's path. -Where XDG_CONFIG_HOME is set, the configs are in $XDG_CONFIG_HOME/build-release/ instead. `~/.config/build-release/do-epic/` holds do-epic's machine-wide settings, not a project's. It needs no `checkout`, and project-config doesn't read anything from it, so no project may use `do-epic` as its key. @@ -179,6 +178,8 @@ without a `plan` in Jira, names a Jira `plan` and leaves out `jira-score-formula one of those two without a `plan` in Jira, sets the formula to one that doesn't parse or the bar to anything but a number, sets `readability-floor` to anything but a number from 1 to 10, sets `parallel-chunks` to anything but a whole number of 1 or more, or sets `jira-finding-type` to anything but a name or without a `plan` in Jira, and where `bench-tasks`, `coding-conventions`, `env-file`, `epic-branch`, `jira-finish-transition`, `jira-finish-status`, `notifier`, `review-request-comment` or `touch-predictions` is asked for and not set. No path setting has a default. + +Where XDG_CONFIG_HOME holds an absolute path, read ~/.config in this help as that path. """ from collections.abc import Mapping import os diff --git a/bin/reading_cost/main.py b/bin/reading_cost/main.py index fe6ed7bf..5d36f3b7 100644 --- a/bin/reading_cost/main.py +++ b/bin/reading_cost/main.py @@ -21,6 +21,8 @@ lists the files the last 5 chunks read most. With fewer than 10 figures, it says Exit 1, saying why, on unknown arguments, or when git cannot start or finds no checkout, the archive or the record cannot be read or written, or a figure in the record cannot be read back. + +Where XDG_STATE_HOME holds an absolute path, read ~/.local/state in this help as that path. """ import dataclasses import os diff --git a/bin/review_replay/main.py b/bin/review_replay/main.py index 95efe0d9..a802dea2 100644 --- a/bin/review_replay/main.py +++ b/bin/review_replay/main.py @@ -65,6 +65,9 @@ Like the loop, it tries claude three times running before it counts a reply as f review or match leaves its round out, except on a rung below the project's, where it finds none. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived round to replay, or a usage limit. + +Where XDG_CONFIG_HOME holds an absolute path, read ~/.config in this help as that path. +Where XDG_STATE_HOME holds an absolute path, read ~/.local/state in this help as that path. """ import pathlib import typing diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 8354bf8d..77cf3b3a 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -47,7 +47,7 @@ RULES: dict[RuleName, Rule] = { # A marker would let the credentials into the transcript all the same, so no marker waives it. "env-file-read": Rule( "an agent never reads ~/.claude/.env or a project's env-file, the file of credentials the project's config names, since a value the agent reads lands in its transcript, which build-release archives and the backups copy; it leaves a tool that needs a credential to read the file itself, gets the file's path from `project-config env-file`, and spells the path another way, such as \"the .env in ~/.claude\", in a command that must mention it without reading it, such as a commit's title, and searches only a folder without it", - "against ~/.claude/.env and the env-file of every config under ~/.config/build-release: a Read of one; a Grep of one, or of a folder holding one, unless a checkout ignores the file and the Grep's glob cannot match it; and a Bash command that spells one's path, or names it in a word or a redirect's target from the directory `cd` left the command in, whether or not the command reads it; and a Bash command that runs `ag`, `grep -r` or `rg` over a folder holding one, or over the directory `cd` left the command in where it names no folder, unless the tool skips the file: `ag` and `rg` skip a hidden file, one below a hidden folder of the search and one a checkout ignores, and `rg` one that none of its globs matches", + "against ~/.claude/.env and the env-file of every config under the config folder, ~/.config/build-release unless `XDG_CONFIG_HOME` holds an absolute path: a Read of one; a Grep of one, or of a folder holding one, unless a checkout ignores the file and the Grep's glob cannot match it; and a Bash command that spells one's path, or names it in a word or a redirect's target from the directory `cd` left the command in, whether or not the command reads it; and a Bash command that runs `ag`, `grep -r` or `rg` over a folder holding one, or over the directory `cd` left the command in where it names no folder, unless the tool skips the file: `ag` and `rg` skip a hidden file, one below a hidden folder of the search and one a checkout ignores, and `rg` one that none of its globs matches", overridable=False, ), "ignorefile-sorted": Rule( @@ -70,7 +70,7 @@ RULES: dict[RuleName, Rule] = { ), # A reviewer only reports, so no marker waives it. "reviewer-report": Rule( - "a reviewer writes only its report, with Write, into a file under the review reports folder, ~/.local/state/build-release/larv-review/ unless `XDG_STATE_HOME` is set", + "a reviewer writes only its report, with Write, into a file under the review reports folder, ~/.local/state/build-release/larv-review/ unless `XDG_STATE_HOME` holds an absolute path", "a Write, Edit or MultiEdit call from inside an agent under agents/", overridable=False, ), @@ -96,7 +96,7 @@ RULES: dict[RuleName, Rule] = { ), "todo-rank-check": Rule( "while todo.md has changes, staged or not, a git commit waits until rank_todo.py --check passes on it: the checkout's own bin/rank_todo.py where the checkout is of this setup's repo, else the release's", - "a git commit in a checkout whose todo.md has changes, and every git commit where the project's config puts todo.md outside the checkout, where the checkout's commits don't say whether it changed; and a git commit in the config's folder, `~/.config/build-release/<key>/`, whose todo.md has changes", + "a git commit in a checkout whose todo.md has changes, and every git commit where the project's config puts todo.md outside the checkout, where the checkout's commits don't say whether it changed; and a git commit in the config's folder, `<key>/` in the config folder, whose todo.md has changes", ), # A Read carries no text for a marker, so no marker waives it. "transcript-read": Rule( diff --git a/bin/subagent_rung/main.py b/bin/subagent_rung/main.py index 43a62d6c..80228689 100644 --- a/bin/subagent_rung/main.py +++ b/bin/subagent_rung/main.py @@ -16,6 +16,8 @@ a checkout no config names. build-release --help shows the file's shape. Exit 1, saying why, on bad arguments, or where the project's config or its routing ladder is faulty or cannot be read. + +Where XDG_CONFIG_HOME holds an absolute path, read ~/.config in this help as that path. """ from collections.abc import Mapping import pathlib diff --git a/rules/goals-and-audience.md b/rules/goals-and-audience.md index 534e4e01..278a1335 100644 --- a/rules/goals-and-audience.md +++ b/rules/goals-and-audience.md @@ -1,7 +1,7 @@ --- paths: - "**/README.md" - - "**/.config/build-release/*/goals.md" + - "**/build-release/*/goals.md" --- # Goals and Audience diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index d638cd8f..39e53300 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -72,7 +72,7 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h `larv-review` holds this section's mechanical rules: the chunk's review folder, the round count and each round commit's counts, the paired ruling's base and vote count, the scoring run's trigger; the history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt. Run it in the chunk's worktree; `larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user. -**Reports.** Run `larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folders of technical principles and review standards the project's config sets, the files of coding conventions where it lists any, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/build-release/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names, and `compress-archives` gzips each file 30 days after it last changed. +**Reports.** Run `larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folders of technical principles and review standards the project's config sets, the files of coding conventions where it lists any, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/build-release/larv-review/`, which is under `$XDG_STATE_HOME` instead of `~/.local/state` where that holds an absolute path. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names, and `compress-archives` gzips each file 30 days after it last changed. **Claimed output.** Before the Product-owner or Prose pass launches in a round, find the lines the diff adds or changes that say what a command, flag or error prints, such as "the error names the fix", or what a command writes, such as "the diff of the regenerated file holds only X". In round 2, take only the lines the round's fixes changed. Those reviewers have no shell, and reading code can't show that an output holds the words a line claims. -- 2.52.0 From a014e751018e18bb30e765f1d76b0808b62cd869 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 19:45:15 +0100 Subject: [PATCH 08/15] =?UTF-8?q?Answer=20architecture=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20chunks=5Fto?= =?UTF-8?q?=5Fstart=20and=20the=20epic's=20folder=20take=20the=20resolved?= =?UTF-8?q?=20paths;=20branch=5Fsummaries=20and=20reviewer=5Fbreaches=20wa?= =?UTF-8?q?it=20for=20item=20300?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/build_release/loop/chunk_start.py | 2 +- bin/build_release/loop/chunk_windows.py | 26 +++++++++----------- bin/build_release/loop/test_chunk_start.py | 7 ++++-- bin/build_release/loop/test_chunk_windows.py | 4 +-- bin/chunk_driver/claims.py | 7 +++--- bin/do_epic/epic_run.py | 8 ++++-- bin/do_epic/main.py | 4 +-- bin/do_epic/parking.py | 6 ++--- bin/do_epic/planning.py | 18 +++++++------- bin/do_epic/scheduler.py | 18 +++++++------- bin/do_epic/status.py | 5 ++-- bin/do_epic/test_planning.py | 21 +++++++++------- bin/do_epic/test_scheduler.py | 3 ++- bin/do_epic/test_status.py | 8 +++--- bin/project_config/doubles.py | 2 +- 15 files changed, 72 insertions(+), 67 deletions(-) diff --git a/bin/build_release/loop/chunk_start.py b/bin/build_release/loop/chunk_start.py index 50baa539..2588e338 100644 --- a/bin/build_release/loop/chunk_start.py +++ b/bin/build_release/loop/chunk_start.py @@ -37,7 +37,7 @@ def chunk_facts(loop: Loop) -> str: item = item_of(loop.window.name) done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root) facts = fresh_prompt.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else fresh_prompt.preflight_facts(done.stdout.strip()) - held = held_beside(loop.window.name, loop.root, loop.paths, loop.env, loop.effects) + held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects) return facts + (fresh_prompt.held_by_others(held) if held else "") diff --git a/bin/build_release/loop/chunk_windows.py b/bin/build_release/loop/chunk_windows.py index 34659244..ac412b9d 100644 --- a/bin/build_release/loop/chunk_windows.py +++ b/bin/build_release/loop/chunk_windows.py @@ -17,6 +17,7 @@ from plan.touches import overlaps, predicted, Touches from loop_state.paths import Paths from transcript_archive.project_key import project_key from release_plan.release_standing import project_plan +from project_config.settings import ProjectConfig from claude_code.transcript import read_transcript from claude_code.session import Session, session_named, transcript_file from agent_cycle import tmux @@ -100,11 +101,8 @@ def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | No return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs)) -def next_plan(root: str, home: pathlib.Path, env: typing.Mapping[str, str], effects: Effects) -> NextChunk | NoItem | Failure: - """The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it.""" - config = located(root, home, env) - if isinstance(config, Failure): - return config +def next_plan(root: str, config: ProjectConfig, effects: Effects) -> NextChunk | NoItem | Failure: + """The plan config names, on the default branch of the checkout root, fetched now where origin answers, with its next item, as chunk-preflight reads it.""" # A chunk that just merged left the plan on origin. A fetch that fails leaves the plan as last fetched, which chunk-preflight then reads too. effects.git("fetch", "--quiet", "origin", cwd=root, timeout=FETCH_TIMEOUT) ref = default_ref(root, FETCH_TIMEOUT, run=effects.git) @@ -121,13 +119,13 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map return config session = loop_session(loop_run.root, paths.home) handed = {name: value for name, value in env.items() if name.startswith(HANDED)} - with starting(project_lock(loop_run.root, paths.home, env)) as unlocked: + with starting(project_lock(loop_run.root, paths)) as unlocked: if unlocked: return unlocked windows = tmux.listed(session, effects.tmux) if refused := refusal(session, windows, loop_run.root, effects.tmux): return refused - chunks = chunks_to_start(windows, loop_run, leaving, config.parallel_chunks, paths, env, effects) + chunks = chunks_to_start(windows, loop_run, leaving, config, paths, effects) if isinstance(chunks, AwaitedMerges): return chunks for chunk in chunks: @@ -147,12 +145,12 @@ def refusal(session: str, windows: list[tmux.Listed], root: str, run: tmux.Tmux) return None -def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, limit: int, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> list[str] | AwaitedMerges: +def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool, config: ProjectConfig, paths: Paths, effects: Effects) -> list[str] | AwaitedMerges: """The chunks to start beside windows, the session's: the stopped ones room_of restarts, then those of the plan that may_start picks. A plan that cannot be read starts NO_ITEM, as a plan without an item does. AwaitedMerges where no chunk runs or restarts and every item left awaits a person's merge.""" - room = room_of(windows, loop_run.chunk, leaving, limit) + room = room_of(windows, loop_run.chunk, leaving, config.parallel_chunks) if not room.left: return room.restart - plan = next_plan(loop_run.root, paths.home, env, effects) + plan = next_plan(loop_run.root, config, effects) if isinstance(plan, Failure): # Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself. say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects) @@ -164,14 +162,14 @@ def chunks_to_start(windows: list[tmux.Listed], loop_run: LoopRun, leaving: bool return room.restart + [chunk for chunk in picked if chunk not in room.stopped] -def held_beside(chunk: str, root: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> list[int]: +def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]: """The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it.""" - wait_for_starts(root, paths.home, env) + wait_for_starts(root, paths) others = [window.name for window in tmux.listed(loop_session(root, paths.home), effects.tmux) if window.name != chunk] return sorted(held_items(others, project_key(root, paths.home), paths.claude_code_transcripts)) -def wait_for_starts(root: str, home: pathlib.Path, env: typing.Mapping[str, str]) -> None: +def wait_for_starts(root: str, paths: Paths) -> None: """Returns once no loop of the project is starting windows: start_chunks holds the lock file `claims.LOCK` names while it starts them. Where the lock cannot be taken, it returns at once.""" - with starting(project_lock(root, home, env)): + with starting(project_lock(root, paths)): pass diff --git a/bin/build_release/loop/test_chunk_start.py b/bin/build_release/loop/test_chunk_start.py index 0789a6d5..9d292ad4 100644 --- a/bin/build_release/loop/test_chunk_start.py +++ b/bin/build_release/loop/test_chunk_start.py @@ -15,6 +15,7 @@ from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES from failure import Failure from loop_effects.doubles import FakeEffects, ran, STAMP from build_release.chunk import fresh_prompt +from project_config.main import located from build_release.doubles import NO_CUT, TODO from loop_state import paths from plan_store.todo_md import plan_of @@ -100,9 +101,11 @@ class RouteSources(unittest.TestCase): self.assertEqual([(item.id, item.awaits_merge) for item in held.plan.items], [(7, ""), (3, "#12 https://github.com/o/r/pull/12"), (1, "")]) self.assertEqual(fake.made("forge")[0][:4], [root, "gh", "pr", "list"]) self.assertIsNone(chunk_start.plan_item(held, None, fake.effects()), "items 7 and 3 wait, so no item of the next release routes the chunk") - window = chunk_windows.next_plan(root, folder.parents[2], {}, dataclasses.replace(fake.effects(), git=git)) + config = located(root, folder.parents[2], {}) + assert not isinstance(config, Failure), config + window = chunk_windows.next_plan(root, config, dataclasses.replace(fake.effects(), git=git)) self.assertEqual((window.awaits_merge, fake.made("forge")[1][:4]), (True, [root, "gh", "pr", "list"]), "a window starts by the same pick") - stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, 1, paths.paths_from(folder.parents[2], {}), {}, dataclasses.replace(fake.effects(), git=git)) + stopped = chunk_windows.chunks_to_start([], reload.LoopRun(1, root, "do it", ""), False, config, paths.paths_from(folder.parents[2], {}), dataclasses.replace(fake.effects(), git=git)) self.assertEqual(stopped, chunk_windows.AwaitedMerges(window.why), "so the loop starts no chunk, and says which pull requests it waits on") def test_reads_a_plan_outside_the_checkout_as_it_stands_and_stops_without_a_config(self): diff --git a/bin/build_release/loop/test_chunk_windows.py b/bin/build_release/loop/test_chunk_windows.py index 44d39e1d..288a5744 100644 --- a/bin/build_release/loop/test_chunk_windows.py +++ b/bin/build_release/loop/test_chunk_windows.py @@ -106,7 +106,7 @@ class ChunkWindows(unittest.TestCase): (folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines)) # Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item. fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n") - self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, {}, fake.effects()), [8, 9, 10, 11]) + self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11]) self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]]) @@ -271,7 +271,7 @@ class StartChunks(unittest.TestCase): (self.home / ".local" / "state" / "build-release").mkdir(parents=True, exist_ok=True) (self.home / ".local" / "state" / "build-release" / "claims").write_text("") fake = FakeEffects(windows="item-7\t0\t@1\nitem-9\t1\t@3\n") - self.assertEqual(chunk_windows.held_beside("item-7", str(self.root), paths.paths_from(self.home, {}), {}, fake.effects()), [9]) + self.assertEqual(chunk_windows.held_beside("item-7", str(self.root), paths.paths_from(self.home, {}), fake.effects()), [9]) def test_a_chunk_holds_its_own_item_and_those_on_its_latest_chunk_items_line(self): with tempfile.TemporaryDirectory() as temp: diff --git a/bin/chunk_driver/claims.py b/bin/chunk_driver/claims.py index 1c925800..7be1b4ed 100644 --- a/bin/chunk_driver/claims.py +++ b/bin/chunk_driver/claims.py @@ -4,13 +4,12 @@ An entry point holds `starting` on `project_lock` while it lists the windows of """ import contextlib import fcntl -from collections.abc import Mapping import pathlib import typing from failure import Failure +from loop_state.paths import Paths from transcript_archive.project_key import project_key -from loop_state.paths import state_folder from agent_cycle import tmux # The file an entry point keeps locked with flock while it lists the windows of a project's chunks and starts new ones. Two loops whose chunks finish together then don't start a chunk twice, and do-epic, which holds the same lock, never starts a chunk in a checkout while build-release does. @@ -51,9 +50,9 @@ def claims_folder(state: pathlib.Path) -> pathlib.Path: return state / "claims" -def project_lock(root: str, home: pathlib.Path, env: Mapping[str, str]) -> pathlib.Path: +def project_lock(root: str, paths: Paths) -> pathlib.Path: """The folder of the LOCK that everything starting a chunk in the checkout root holds.""" - return claims_folder(state_folder(env, home)) / project_key(root, home) + return claims_folder(paths.state_folder) / project_key(root, paths.home) def loop_session(root: str, home: pathlib.Path) -> str: diff --git a/bin/do_epic/epic_run.py b/bin/do_epic/epic_run.py index 06adb826..ece1b092 100644 --- a/bin/do_epic/epic_run.py +++ b/bin/do_epic/epic_run.py @@ -36,6 +36,10 @@ class EpicRun: def session(self) -> str: return tmux.session_name(tmux.EPIC, self.key) + @property + def folder(self) -> pathlib.Path: + return scheduler.epic_folder(self.paths.state_folder, self.key) + def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None, told: str = "") -> scheduler.Started | Failure: """scheduler.start_chunks on the epic's issues, as read, in order of score, and its cap, read afresh; own is the issue of the chunk that asks, and told is the reason the planning just gave for stopping, which isn't said twice. Where no issue is open, the chunk to start is the epic's finishing, unless the epic is closed.""" @@ -57,7 +61,7 @@ def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None, told def planned_epic(epic: EpicRun) -> planning.Planned: """The epic as planning reads and writes it.""" - return planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.env, epic.effects) + return planning.Planned(epic.key, epic.config, epic.store, epic.record, epic.paths.home, epic.env, epic.folder, epic.effects) def scheduled_epic(epic: EpicRun, order: tuple[str, ...]) -> scheduler.Epic | Failure: @@ -75,7 +79,7 @@ def scheduled_epic(epic: EpicRun, order: tuple[str, ...]) -> scheduler.Epic | Fa seen.append(found.checkout) return real(found.checkout), found.config.parallel_chunks - return scheduler.Epic(epic.key, cap, located, epic.paths.home, epic.launcher, epic.env, epic.config.label_repos, order, epic.config.unblocking) + return scheduler.Epic(epic.key, cap, located, epic.paths, epic.launcher, epic.env, epic.config.label_repos, order, epic.config.unblocking) def real(checkout: pathlib.Path) -> pathlib.Path: diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 7f2fbc61..6b6424ef 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -144,7 +144,7 @@ def status_printed(epic: EpicRun) -> Stop: reading = dataclasses.replace(epic, effects=dataclasses.replace(epic.effects, git=dry_run.without_clones(epic.effects.git))) order = issues if isinstance(issues, Failure) else planning.start_order(planned_epic(reading), issues) # Where the issues cannot be put in order of score, they start in the backlog's order, as a run says. - lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.paths.state_folder, issues, epic.config.label_repos, epic.config.unblocking, epic.effects.tmux, () if isinstance(order, Failure) else tuple(order)) + lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.folder, issues, epic.config.label_repos, epic.config.unblocking, epic.effects.tmux, () if isinstance(order, Failure) else tuple(order)) return Stop(1, lines.reason) if isinstance(lines, Failure) else Stop(0, "\n".join(lines) or f"the epic {epic.key} has no open issue") @@ -330,7 +330,7 @@ def chunk_root(key: str, issue: EpicIssue | None, epic: EpicRun) -> tuple[str, s if isinstance(pick, Failure): return Stop(1, pick.reason) if isinstance(pick, ClaudeWork): - return str(scheduler.epic_folder(epic.paths.state_folder, epic.key)), None + return str(epic.folder), None if not isinstance(pick, Repo): return Stop(1, f"{key} is no chunk: no label names its repo") found = locate(pick.name, [], epic.config, epic.paths.home, epic.env, epic.effects.git) diff --git a/bin/do_epic/parking.py b/bin/do_epic/parking.py index 4af5ef18..964cd92e 100644 --- a/bin/do_epic/parking.py +++ b/bin/do_epic/parking.py @@ -30,15 +30,15 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, told: str | None, finis A chunk parks in three steps: its file is written, its window is shown as parked, and the epic's next chunks start in the slot it frees. It resumes in the reverse order: `scheduler.resume` gives it a running slot, then its file is removed. So a window that ends in between finds the chunk parked when it starts again. """ - key, folder = loop.window.name, scheduler.epic_folder(epic.paths.state_folder, epic.key) - recorded_as = parked.parked_chunks(folder) + key = loop.window.name + recorded_as = parked.parked_chunks(epic.folder) if isinstance(recorded_as, Failure): return Stop(1, recorded_as.reason) config = config_located(loop.root, epic.paths.home, epic.env) if isinstance(config, Failure): return Stop(1, config.reason) # A pull request into an epic's working branch merges without a person, whatever `merge` says. The base recorded says so, not the config: the gate fails where the forge merges the pull request elsewhere. - poll = Poll(key, repo, config.merge == "human" and based is None, folder, loop, epic) + poll = Poll(key, repo, config.merge == "human" and based is None, epic.folder, loop, epic) if key in recorded_as: return resumed_news(poll, recorded_as[key].on, shown=None) entered = None if told is None else poll.first_gate(again=finished) diff --git a/bin/do_epic/planning.py b/bin/do_epic/planning.py index 85708fc1..f01ce0ad 100644 --- a/bin/do_epic/planning.py +++ b/bin/do_epic/planning.py @@ -10,10 +10,9 @@ from collections.abc import Mapping import pathlib import re -from loop_state.paths import CLAUDE_HOME, state_folder +from loop_state.paths import CLAUDE_HOME from do_epic.config import DoEpicConfig from loop_effects.effects import Effects, say -from do_epic.scheduler import epic_folder, unblocks from do_epic.backend.protocol import EpicIssue, EpicStore, no_scores from do_epic.epic_record import EpicRecord from failure import Failure @@ -24,6 +23,7 @@ from claude_code.reply import Limited from plan_store.jira_epic import number from model_routing.ladder_file import read_ladder, SHIPPED from model_routing.ladder import Rung +from do_epic.scheduler import unblocks from plan_store.scoring import weighing_texts # The epic's formula, stated under its `## Scoring` as a todo.md states its own. @@ -43,6 +43,8 @@ class Planned: record: EpicRecord home: pathlib.Path env: Mapping[str, str] + # The epic's folder, where claude plans and scores its issues. + folder: pathlib.Path effects: Effects @@ -94,17 +96,16 @@ def placed(epic: Planned, issues: list[EpicIssue], unplaced: list[EpicIssue], ad if failed := next((each for each in (rung, language, places) if isinstance(each, Failure)), None): return failed assert isinstance(rung, Rung) and not isinstance(language, Failure) and isinstance(places, dict) - folder = epic_folder(state_folder(epic.env, epic.home), epic.key) - folder.mkdir(parents=True, exist_ok=True) + epic.folder.mkdir(parents=True, exist_ok=True) checkouts = tuple(str(place.checkout) for place in places.values()) for issue in unplaced: say(f"planning {issue.key}", epic.effects, stdout=True) - parts = split.split(epic.store, issue, epic.config.label_repos, not issue.by_loop, epic.config.repo_rule, language or epic.config.language, checkouts, rung, epic.effects.claude, str(folder), epic.config.sub_task_summary) + parts = split.split(epic.store, issue, epic.config.label_repos, not issue.by_loop, epic.config.repo_rule, language or epic.config.language, checkouts, rung, epic.effects.claude, str(epic.folder), epic.config.sub_task_summary) if isinstance(parts, split.Split) and parts.repos: added[issue.key] = split.SPLIT_LABEL say(f"{issue.key} is split into a sub-task for each of {', '.join(parts.repos)}", epic.effects, stdout=True) continue - pick: repo_pick.Pick | repo_pick.Unclear | Failure | Limited | None = parts if not isinstance(parts, split.Split) else repo_pick.picked(epic.store, issue, epic.config.label_repos, epic.config.repo_rule, rung, epic.effects.claude, str(folder)) + pick: repo_pick.Pick | repo_pick.Unclear | Failure | Limited | None = parts if not isinstance(parts, split.Split) else repo_pick.picked(epic.store, issue, epic.config.label_repos, epic.config.repo_rule, rung, epic.effects.claude, str(epic.folder)) if isinstance(pick, repo_pick.Unclear): pick = answered(epic, issue, pick.question) if isinstance(pick, Limited): @@ -212,13 +213,12 @@ def scored(epic: Planned, issues: list[EpicIssue]) -> tuple[list[EpicIssue], Fai if failed := next((each for each in (rung, language, rule, weighed) if isinstance(each, Failure)), None): return issues, failed assert isinstance(rung, Rung) and not isinstance(language, Failure) and isinstance(rule, str) and isinstance(weighed, Weighing) - folder = epic_folder(state_folder(epic.env, epic.home), epic.key) - folder.mkdir(parents=True, exist_ok=True) + epic.folder.mkdir(parents=True, exist_ok=True) for issue in bare: say(f"scoring {issue.key}", epic.effects, stdout=True) repo = repo_of(epic, issue) goals = ranking.goals_named(weighed.goals, repo, weighed.repos.get(repo) if repo else None) - answer = goals if isinstance(goals, Failure) else issue_scores.asked(issue, rule, goals, language or epic.config.language, rung, epic.effects.claude, str(folder)) + answer = goals if isinstance(goals, Failure) else issue_scores.asked(issue, rule, goals, language or epic.config.language, rung, epic.effects.claude, str(epic.folder)) if isinstance(answer, Limited): return issues, answer held = answer if isinstance(answer, Failure) else scores_set(epic, issue, answer, weighed) diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index b088cf2c..9713ae41 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -15,18 +15,18 @@ from text_files.markdown_text import listed from project_config.settings import PARALLEL_CHUNKS from do_epic.parked import parked_chunks from chunk_pr.approval import PARKS -from loop_state.paths import state_folder +from loop_state.paths import Paths from agent_cycle import tmux # The folder in the state folder where a folder per epic key holds the epic's lock file, which `claims.LOCK` names. A chunk without a repo works there. STATE = "do-epic" +# Why a human's task with a live window waits, as the epic's status says. +HUMAN_WAIT = "it is a human's task; do-epic polls Jira until you close it" def epic_folder(state: pathlib.Path, key: str) -> pathlib.Path: """The folder of the epic called key, in the state folder state.""" return state / STATE / key -# Why a human's task with a live window waits, as the epic's status says. -HUMAN_WAIT = "it is a human's task; do-epic polls Jira until you close it" @dataclasses.dataclass(frozen=True) @@ -74,7 +74,7 @@ class Epic: cap: int # The checkout of the repo with this name and its `parallel-chunks`, or why the repo cannot be used. locate: typing.Callable[[str], tuple[pathlib.Path, int] | Failure] - home: pathlib.Path + paths: Paths # The do-epic script each window runs. launcher: pathlib.Path env: typing.Mapping[str, str] @@ -87,7 +87,7 @@ class Epic: @property def folder(self) -> pathlib.Path: - return epic_folder(state_folder(self.env, self.home), self.key) + return epic_folder(self.paths.state_folder, self.key) def unblocks(status: str, unblocking: tuple[str, ...]) -> bool: @@ -233,10 +233,10 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li if isinstance(located, Failure): return Waits(chunk.issue, located.reason) checkout, limit = located - with starting(project_lock(str(checkout), epic.home, epic.env)) as unlocked: + with starting(project_lock(str(checkout), epic.paths)) as unlocked: if unlocked: return unlocked - if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.home, run)): + if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.paths.home, run)): return Waits(chunk.issue, reason) return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(checkout), handed, command, windows, False, run) @@ -259,10 +259,10 @@ def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | if isinstance(located, Failure): return located.reason checkout, limit = located - with starting(project_lock(str(checkout), epic.home, epic.env)) as unlocked: + with starting(project_lock(str(checkout), epic.paths)) as unlocked: if unlocked: return unlocked.reason - if reason := refusal(repo, room_in(str(checkout), limit, (window.session, window.name), epic.home, run)): + if reason := refusal(repo, room_in(str(checkout), limit, (window.session, window.name), epic.paths.home, run)): return reason tmux.unpark(window, str(checkout), run) return None diff --git a/bin/do_epic/status.py b/bin/do_epic/status.py index 530547c4..9cf50801 100644 --- a/bin/do_epic/status.py +++ b/bin/do_epic/status.py @@ -2,7 +2,7 @@ import datetime import pathlib -from do_epic.scheduler import chunks, epic_folder, HUMAN_WAIT +from do_epic.scheduler import chunks, HUMAN_WAIT from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.parked import file_of, Parked, parked_chunks, SLOT @@ -20,10 +20,9 @@ def since(folder: pathlib.Path, chunk: Parked) -> str: return "" -def lines(key: str, state: pathlib.Path, issues: list[EpicIssue], team: LabelRepos, unblocking: tuple[str, ...], run: tmux.Tmux, order: tuple[str, ...]) -> list[str] | Failure: +def lines(key: str, folder: pathlib.Path, issues: list[EpicIssue], team: LabelRepos, unblocking: tuple[str, ...], run: tmux.Tmux, order: tuple[str, ...]) -> list[str] | Failure: """A line per open issue of the epic called key, in the tracker's rank order: that its chunk runs or asks the human, or why it waits. order holds the keys of the issues that start by score, as planning.start_order puts them; a chunk it leaves out says that it starts after them. It doesn't start anything or check any limit, so the line of a chunk that has yet to start doesn't say which limit holds it back.""" found, waits = chunks(issues, team, unblocking) - folder = epic_folder(state, key) parked = parked_chunks(folder) if isinstance(parked, Failure): return parked diff --git a/bin/do_epic/test_planning.py b/bin/do_epic/test_planning.py index 25fb9715..c51bfbb5 100644 --- a/bin/do_epic/test_planning.py +++ b/bin/do_epic/test_planning.py @@ -36,12 +36,16 @@ def scored(key: str, moves: str, *labels: str, blockers: tuple[str, ...] = (), b class Planning(DoEpicTest): + def setUp(self) -> None: + super().setUp() + self.folder = self.home / ".local/state/build-release/do-epic/ABC-12" + def plan(self, fake: FakeEffects) -> tuple[list[EpicIssue] | Failure | Limited, MemoryEpic, str]: """What planning answers for self.issues, the store it changed and what it printed on stdout. self.asked holds what it asked the human, on stderr.""" config = load(self.home, {}) assert not isinstance(config, Failure), config store = MemoryEpic("ABC-12", list(self.issues)) - epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, fake.effects()) # type: ignore[arg-type] + epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, self.folder, fake.effects()) # type: ignore[arg-type] out, self.asked = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(self.asked): read = store.read() @@ -152,11 +156,10 @@ class Planning(DoEpicTest): folders.append(cwd) return effects.claude(args, cwd, stdin) # type: ignore[arg-type] config = load(self.home, {}) - epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description("")), self.home, {}, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type] + epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description("")), self.home, {}, self.folder, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type] with contextlib.redirect_stdout(io.StringIO()): planning.planned(epic, list(self.issues)) - folder = self.home / ".local" / "state" / "build-release" / "do-epic" / "ABC-12" - self.assertEqual((folders, folder.is_dir()), ([str(folder)] * 2, True)) + self.assertEqual((folders, self.folder.is_dir()), ([str(self.folder)] * 2, True)) def test_a_model_off_the_routing_ladder_has_no_rung(self) -> None: found = planning.planning_rung("claude-nope-1") @@ -379,7 +382,7 @@ class Planning(DoEpicTest): self.description = RANKED self.issues = [scored("ABC-20", "epic 1 by 2", "do-epic-claude", by_loop=False), issue("ABC-21", "do-epic-claude")] # An earlier run made the folder the scoring runs in. - (self.home / ".local/state/build-release/do-epic/ABC-12").mkdir(parents=True, exist_ok=True) + self.folder.mkdir(parents=True, exist_ok=True) fake = FakeEffects(claude=[says(ANSWER)]) found, store, out = self.plan(fake) assert not isinstance(found, Failure | Limited), found @@ -447,10 +450,10 @@ class Planning(DoEpicTest): folders.append(cwd) return effects.claude(args, cwd, stdin) # type: ignore[arg-type] config = load(self.home, {}) - epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description(RANKED)), self.home, {}, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type] + epic = planning.Planned("ABC-12", config, MemoryEpic("ABC-12", list(self.issues)), EpicRecord(Description(RANKED)), self.home, {}, self.folder, dataclasses.replace(effects, claude=claude)) # type: ignore[arg-type] with contextlib.redirect_stdout(io.StringIO()): planning.planned(epic, list(self.issues)) - self.assertEqual(folders, [str(self.home / ".local" / "state" / "build-release" / "do-epic" / "ABC-12")] * 2) + self.assertEqual(folders, [str(self.folder)] * 2) self.rule() self.description = RANKED @@ -469,7 +472,7 @@ class Planning(DoEpicTest): out = io.StringIO() config = load(self.home, {}) assert not isinstance(config, Failure), config - epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, FakeEffects(claude=[says(ANSWER)]).effects()) # type: ignore[arg-type] + epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, self.folder, FakeEffects(claude=[says(ANSWER)]).effects()) # type: ignore[arg-type] with contextlib.redirect_stdout(out): found, stopped = planning.scored(epic, list(self.issues)) self.assertEqual((found, stopped, out.getvalue()), (self.issues, None, "<1790000000> scoring ABC-20\n<1790000000> ABC-20 is not scored: Jira answered 503\n")) @@ -520,7 +523,7 @@ class Planning(DoEpicTest): """What planning answers for self.issues on a store that doesn't read as MemoryEpic does.""" config = load(self.home, {}) assert not isinstance(config, Failure), config - epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, fake.effects()) # type: ignore[arg-type] + epic = planning.Planned("ABC-12", config, store, EpicRecord(Description(self.description)), self.home, {}, self.folder, fake.effects()) # type: ignore[arg-type] with contextlib.redirect_stdout(io.StringIO()): return planning.planned(epic, list(self.issues)) diff --git a/bin/do_epic/test_scheduler.py b/bin/do_epic/test_scheduler.py index 635c1d6a..e9393dc8 100644 --- a/bin/do_epic/test_scheduler.py +++ b/bin/do_epic/test_scheduler.py @@ -14,6 +14,7 @@ from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.parked import file_of, park, Parked from do_epic.epic_record import parallel_chunks_in +from loop_state.paths import paths_from from chunk_driver import prompts from model_routing.route import Route from model_routing.ladder import Rung @@ -210,7 +211,7 @@ class StartingAnEpicsChunks(unittest.TestCase): """An epic whose repos are checked out under the home folder, each with its `parallel-chunks`.""" def locate(name: str) -> tuple[pathlib.Path, int] | Failure: return (self.home / "code" / name, limits[name]) if name in limits else Failure(f"no project config names {name}") - return Epic("ABC-12", cap, locate, self.home, pathlib.Path("/bin/do-epic"), {"BUILD_RELEASE_X": "1", "OTHER": "2"}, {}, self.order) + return Epic("ABC-12", cap, locate, paths_from(self.home, {}), pathlib.Path("/bin/do-epic"), {"BUILD_RELEASE_X": "1", "OTHER": "2"}, {}, self.order) def start(self, epic: Epic, issues: list[EpicIssue], run: Tmux, own: str | None = None) -> Started: found = start_chunks(epic, issues, False, own, run) diff --git a/bin/do_epic/test_status.py b/bin/do_epic/test_status.py index 161bb186..48c5f335 100644 --- a/bin/do_epic/test_status.py +++ b/bin/do_epic/test_status.py @@ -7,7 +7,6 @@ import unittest from failure import Failure from do_epic.test_scheduler import issue, Tmux from do_epic import parked, status -from do_epic.scheduler import STATE SINCE = 1_700_000_000 # SINCE as the status prints it. @@ -17,15 +16,14 @@ EPIC = "epic-ABC-12" class TheStatusLines(unittest.TestCase): def setUp(self) -> None: - self.home = pathlib.Path(tempfile.mkdtemp()) - self.folder = self.home / STATE / "ABC-12" + self.folder = pathlib.Path(tempfile.mkdtemp()) def park(self, key: str, on: str) -> None: parked.park(self.folder, parked.Parked(key, f"/code/api-{key}", "7", "s", on)) os.utime(parked.file_of(self.folder, key), (SINCE, SINCE)) def lines(self, issues: list, *windows: tuple[str, str, bool, str], unblocking: tuple[str, ...] = ()) -> list[str] | Failure: - return status.lines("ABC-12", self.home, issues, {}, unblocking, Tmux(*windows), ()) + return status.lines("ABC-12", self.folder, issues, {}, unblocking, Tmux(*windows), ()) def test_a_chunk_that_asks_says_where_to_answer_and_one_that_works_runs(self) -> None: found = self.lines([issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], (EPIC, "ABC-20 ?", False, ""), (EPIC, "ABC-21", False, "")) @@ -54,7 +52,7 @@ class TheStatusLines(unittest.TestCase): def test_an_issue_without_scores_says_that_it_starts_after_each_that_holds_them(self) -> None: held = dataclasses.replace(issue("ABC-21", "repo:api"), scores={"L": 1, "E": 1, "I": 1, "S": 1}) room = "it has not started; `do-epic ABC-12` starts it once the epic and its repo have room" - found = status.lines("ABC-12", self.home, [issue("ABC-20", "repo:api"), held], {}, (), Tmux(), ("ABC-21",)) + found = status.lines("ABC-12", self.folder, [issue("ABC-20", "repo:api"), held], {}, (), Tmux(), ("ABC-21",)) self.assertEqual(found, [f"ABC-20 waits: {room}, after each issue that holds every score, since it doesn't", f"ABC-21 waits: {room}"]) # Where no issue starts by score, each starts in the tracker's rank order. self.assertEqual(self.lines([issue("ABC-20", "repo:api"), held]), [f"ABC-20 waits: {room}", f"ABC-21 waits: {room}"]) diff --git a/bin/project_config/doubles.py b/bin/project_config/doubles.py index 26122dfb..3d429cab 100644 --- a/bin/project_config/doubles.py +++ b/bin/project_config/doubles.py @@ -33,7 +33,7 @@ def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "check def configured(test: unittest.TestCase, checkout: pathlib.Path, goals: str = "checkout:README.md", home: pathlib.Path | None = None) -> pathlib.Path: - """Makes checkout a git checkout that a config names, under home, else under a folder of its own for the rest of the test; the config's folder, two levels under that home.""" + """Makes checkout a git checkout that a config names, under home, else under a folder of its own for the rest of the test; the config's folder, three levels under that home.""" subprocess.run(["git", "init", "--quiet", str(checkout)], check=True, env=isolated_env()) if home is None: made = tempfile.TemporaryDirectory() -- 2.52.0 From 797bba69d37ff5867e06830212ec97cfe8781a2a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 20:09:47 +0100 Subject: [PATCH 09/15] =?UTF-8?q?Answer=20prose=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20the=20READM?= =?UTF-8?q?E=20names=20what=20the=20state=20folder=20holds,=20and=20the=20?= =?UTF-8?q?comment=20drops=20its=20Only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- bin/loop_state/paths.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 558d5942..07daf10a 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ Then pick a model with `/model`. Link `build-release` onto `PATH`: `ln -s ~/.claude/bin/build-release ~/.local/bin/build-release`. Every claude it starts, the interactive ones included, skips every permission prompt. build-release runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later. -The setup keeps each project's config, and what you choose for a project, in the config folder, `~/.config/build-release/`. Everything else its tools write is in the state folder, `~/.local/state/build-release/`. Where `XDG_CONFIG_HOME` holds an absolute path, the config folder is `build-release/` under that path instead, and likewise the state folder under `XDG_STATE_HOME`; this README spells the defaults. Set such a variable in the environment Claude Code starts in, since rule-hook reads it there. `settings.json` names only the default review folder, `~/.local/state/build-release/larv-review`, in `additionalDirectories`: where `XDG_STATE_HOME` moves that folder, add it there yourself, or an interactive session asks before a reviewer writes its report. Back up these four folders: +The setup keeps each project's config, and what you choose for a project, in the config folder, `~/.config/build-release/`. Its tools keep their own state, such as transcripts, review reports and locks, in the state folder, `~/.local/state/build-release/`. Where `XDG_CONFIG_HOME` holds an absolute path, the config folder is `build-release/` under that path instead, and likewise the state folder under `XDG_STATE_HOME`; this README spells the defaults. Set such a variable in the environment Claude Code starts in, since rule-hook reads it there. `settings.json` names only the default review folder, `~/.local/state/build-release/larv-review`, in `additionalDirectories`: where `XDG_STATE_HOME` moves that folder, add it there yourself, or an interactive session asks before a reviewer writes its report. Back up these four folders: - `~/.config/build-release/`: each project's config, a client project's plan and records, and `models.json`, the model of each project, which build-release and do-epic write. A project's `env-file`, if you keep it here as below, puts credentials in the backup, so keep the backup private. - `~/.local/state/build-release/transcripts`: every transcript build-release keeps. Where you set `BUILD_RELEASE_TRANSCRIPTS`, back up the folder it names instead. diff --git a/bin/loop_state/paths.py b/bin/loop_state/paths.py index 383d6f7b..290fca03 100644 --- a/bin/loop_state/paths.py +++ b/bin/loop_state/paths.py @@ -40,7 +40,7 @@ def config_folder(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path: def state_folder(env: Mapping[str, str], home: pathlib.Path) -> pathlib.Path: """The state folder, which the tools write: one folder per tool.""" - # Every tool keeps its state here, none beside it in the state home. Only an archive that BUILD_RELEASE_TRANSCRIPTS names is elsewhere. + # Every tool keeps its state here, none beside it in the state home. An archive that BUILD_RELEASE_TRANSCRIPTS names is elsewhere. return xdg_folder(env.get(XDG_STATE_HOME), home / STATE_HOME) / SETUP -- 2.52.0 From 173d5919866ff3278b85661cb0ab3281a9c5096c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 20:09:47 +0100 Subject: [PATCH 10/15] =?UTF-8?q?Answer=20product-owner=20round=202:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(1=20misread);=20the=20ch?= =?UTF-8?q?angelog=20bullet=20names=20the=20old=20lock=20folder=20as=20one?= =?UTF-8?q?=20to=20delete,=20not=20move?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 9b8f9e05e7fa5c5d4839f8b6e58b38e9c725763e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 21:30:06 +0100 Subject: [PATCH 11/15] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20a=20chunk?= =?UTF-8?q?=20window=20is=20handed=20the=20two=20XDG=20variables,=20rule-h?= =?UTF-8?q?ook's=20checks=20are=20tested=20under=20them,=20and=20three=20t?= =?UTF-8?q?ests=20stop=20passing=20the=20developer's?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/build_release/loop/chunk_windows.py | 5 +-- bin/chunk_driver/claims.py | 14 ++++-- bin/chunk_driver/test_claims.py | 11 ++++- bin/do_epic/scheduler.py | 8 ++-- bin/notifier/test_notifier.py | 5 +-- bin/project_record/test_project_record.py | 3 +- bin/rule_hook/test_rule_hook.py | 52 +++++++++++++++++++++++ 7 files changed, 82 insertions(+), 16 deletions(-) diff --git a/bin/build_release/loop/chunk_windows.py b/bin/build_release/loop/chunk_windows.py index ac412b9d..42ee5942 100644 --- a/bin/build_release/loop/chunk_windows.py +++ b/bin/build_release/loop/chunk_windows.py @@ -5,7 +5,7 @@ import re import typing from touch_predictions.beside import Beside, chunks_beside -from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_session, project_lock, starting +from chunk_driver.claims import CHUNK_FLAG, epic_chunks, handed, loop_session, project_lock, starting from build_release.chunk import chunk_items from git_cli.git_repo import default_ref from loop_effects.effects import Effects, say @@ -118,7 +118,6 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map if isinstance(config, Failure): return config session = loop_session(loop_run.root, paths.home) - handed = {name: value for name, value in env.items() if name.startswith(HANDED)} with starting(project_lock(loop_run.root, paths)) as unlocked: if unlocked: return unlocked @@ -129,7 +128,7 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map if isinstance(chunks, AwaitedMerges): return chunks for chunk in chunks: - started = tmux.start_chunk(tmux.Window(session, chunk, ""), loop_run.root, handed, [str(launcher), CHUNK_FLAG, chunk, loop_run.task], windows, True, effects.tmux) + started = tmux.start_chunk(tmux.Window(session, chunk, ""), loop_run.root, handed(env), [str(launcher), CHUNK_FLAG, chunk, loop_run.task], windows, True, effects.tmux) if isinstance(started, Failure): return started windows = started diff --git a/bin/chunk_driver/claims.py b/bin/chunk_driver/claims.py index 7be1b4ed..aad014c5 100644 --- a/bin/chunk_driver/claims.py +++ b/bin/chunk_driver/claims.py @@ -1,6 +1,6 @@ """How entry points claim a checkout before they start a chunk in it, so that two never start the same chunk and do-epic never starts one where build-release runs. -An entry point holds `starting` on `project_lock` while it lists the windows of the checkout's chunks and starts new ones. Where the lock cannot be taken, `starting` yields a Failure, and the entry point doesn't start any chunk. It starts each chunk in a tmux window with CHUNK_FLAG, and hands that window the variables named with HANDED. +An entry point holds `starting` on `project_lock` while it lists the windows of the checkout's chunks and starts new ones. Where the lock cannot be taken, `starting` yields a Failure, and the entry point doesn't start any chunk. It starts each chunk in a tmux window with CHUNK_FLAG, and hands that window the variables `handed` picks. """ import contextlib import fcntl @@ -8,7 +8,7 @@ import pathlib import typing from failure import Failure -from loop_state.paths import Paths +from loop_state.paths import Paths, XDG_CONFIG_HOME, XDG_STATE_HOME from transcript_archive.project_key import project_key from agent_cycle import tmux @@ -16,8 +16,14 @@ from agent_cycle import tmux LOCK = "starting" # The flag that tells the entry point in a window its chunk, as `--chunk item-372` for build-release and `--chunk ABC-34 ABC-12` for do-epic. Nobody types it, so no panel picked it. CHUNK_FLAG = "--chunk" -# The prefix of the variables both entry points read. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name. -HANDED = "BUILD_RELEASE_" +# The prefix of the variables both entry points read. +OWN = "BUILD_RELEASE_" + + +# A window gets the tmux server's environment, not the starting terminal's. Without the two XDG variables, a window would lock and write in other folders than the entry point that started it. +def handed(env: typing.Mapping[str, str]) -> dict[str, str]: + """The variables of env that an entry point hands each window it starts: those both entry points read, and the two that move the config folder and the state folder.""" + return {name: value for name, value in env.items() if name.startswith(OWN) or name in (XDG_CONFIG_HOME, XDG_STATE_HOME)} @contextlib.contextmanager diff --git a/bin/chunk_driver/test_claims.py b/bin/chunk_driver/test_claims.py index 9ccb694d..b7346b04 100644 --- a/bin/chunk_driver/test_claims.py +++ b/bin/chunk_driver/test_claims.py @@ -6,7 +6,16 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from failure import Failure -from chunk_driver.claims import LOCK, starting +from chunk_driver.claims import handed, LOCK, starting + + +class Handed(unittest.TestCase): + def test_hands_a_window_the_setups_own_variables_and_the_two_that_move_its_folders(self) -> None: + env = {"BUILD_RELEASE_JUDGE_MODEL": "judge", "XDG_CONFIG_HOME": "/configs", "XDG_STATE_HOME": "/state", "XDG_DATA_HOME": "/data", "PATH": "/bin"} + self.assertEqual(handed(env), {"BUILD_RELEASE_JUDGE_MODEL": "judge", "XDG_CONFIG_HOME": "/configs", "XDG_STATE_HOME": "/state"}) + + def test_hands_no_variable_the_starter_lacks(self) -> None: + self.assertEqual(handed({"PATH": "/bin"}), {}) class Starting(unittest.TestCase): diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index 9713ae41..9887d118 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -6,7 +6,7 @@ import pathlib import typing from do_epic.epic_record import CAP -from chunk_driver.claims import CHUNK_FLAG, epic_chunks, HANDED, loop_chunks, project_lock, starting +from chunk_driver.claims import CHUNK_FLAG, epic_chunks, handed, loop_chunks, project_lock, starting from do_epic.backend.protocol import EpicIssue from failure import Failure from do_epic.split import finished, is_split, SPLIT_LABEL @@ -225,10 +225,10 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, own: str def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | Waits | Failure: """Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; a Waits with the reason where its repo takes no chunk now, and a Failure where tmux started none, or where the repo's lock cannot be taken. It holds that lock from the check to the start. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo.""" session = tmux.session_name(tmux.EPIC, epic.key) - handed = {**{name: value for name, value in epic.env.items() if name.startswith(HANDED)}, PARKS: "1"} + env = {**handed(epic.env), PARKS: "1"} command = [str(epic.launcher), CHUNK_FLAG, chunk.issue, epic.key] if chunk.repo is None: - return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(epic.folder), handed, command, windows, False, run) + return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(epic.folder), env, command, windows, False, run) located = epic.locate(chunk.repo) if isinstance(located, Failure): return Waits(chunk.issue, located.reason) @@ -238,7 +238,7 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li return unlocked if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.paths.home, run)): return Waits(chunk.issue, reason) - return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(checkout), handed, command, windows, False, run) + return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(checkout), env, command, windows, False, run) def room_in(checkout: str, limit: int, leaving: tuple[str, str | None], home: pathlib.Path, run: tmux.Tmux) -> RepoRoom: diff --git a/bin/notifier/test_notifier.py b/bin/notifier/test_notifier.py index 2cb4ade8..805c88c3 100644 --- a/bin/notifier/test_notifier.py +++ b/bin/notifier/test_notifier.py @@ -1,7 +1,6 @@ import contextlib import dataclasses import io -import os import pathlib import subprocess import sys @@ -74,14 +73,14 @@ class Notify(Project): self.name_notifier("slack", SLACK_KEYS) slack = Slack({"ok": True}) with contextlib.chdir(self.checkout): - self.assertIsNone(system_effects(self.home, os.environ, through("slack", slack)).dm("Which one?", None)) + self.assertIsNone(system_effects(self.home, {}, through("slack", slack)).dm("Which one?", None)) self.assertEqual(slack.requests, [SLACK_POST]) def test_a_dm_that_names_a_directory_goes_through_the_notifier_for_the_project_holding_it_from_any_current_directory(self): self.name_notifier("slack", SLACK_KEYS) slack = Slack({"ok": True}) with contextlib.chdir(self.home): - self.assertIsNone(system_effects(self.home, os.environ, through("slack", slack)).dm("Which one?", str(self.checkout))) + self.assertIsNone(system_effects(self.home, {}, through("slack", slack)).dm("Which one?", str(self.checkout))) self.assertEqual(slack.requests, [SLACK_POST]) def test_skips_the_notice_for_a_project_that_names_no_notifier_even_where_its_env_file_holds_the_keys(self): diff --git a/bin/project_record/test_project_record.py b/bin/project_record/test_project_record.py index 5090db2d..7d8779be 100644 --- a/bin/project_record/test_project_record.py +++ b/bin/project_record/test_project_record.py @@ -13,6 +13,7 @@ from failure import Failure from project_record import main from record_store.fakes import MemoryStore from project_config.settings import Page, ProjectConfig +from loop_state.paths import without_xdg_folders TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-record" @@ -135,7 +136,7 @@ class BlackBox(unittest.TestCase): self.home = configured(self, self.top).parents[2] def run_tool(self, *args: str) -> subprocess.CompletedProcess[str]: - return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.top, env=os.environ | {"HOME": str(self.home)}, text=True) + return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.top, env=without_xdg_folders(os.environ) | {"HOME": str(self.home)}, text=True) def test_a_file_record_opens_as_its_own_file_and_save_has_nothing_to_store(self): opened = self.run_tool("open", "decisions") diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 98f35529..805de0b8 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -413,6 +413,20 @@ class ReviewerRung(unittest.TestCase): self.assertEqual(reviewer_breaches(reviewer, environ, home), []) self.assertEqual(skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), environ, home), []) + def test_the_projects_ladder_is_read_from_a_config_under_xdg_config_home(self): + checkout, home = self.project(self.TWO_RUNGS) + pathlib.Path(home, ".config").rename(pathlib.Path(home, "moved")) + moved = {"XDG_CONFIG_HOME": f"{home}/moved"} + reviewer = Call("Agent", {"subagent_type": "stability-reviewer", "model": "fable", "effort": "medium"}, checkout) + self.assertEqual(rules(reviewer_breaches(reviewer, self.ON_TWO_RUNGS | moved, home)), ["reviewer-rung"]) + self.assertEqual(rules(reviewer_breaches(reviewer, self.ON_TWO_RUNGS, home)), [], "without the variable the shipped ladder holds") + # On the shipped ladder the worker's high effort ranks above the project's low one; the project's ladder holds them the other way round. + pathlib.Path(home, "moved", "build-release", "acme", "routing-ladder.json").write_text('[{"model": "claude-fable-5-2", "effort": "high"}, {"model": "claude-fable-5-2", "effort": "low"}]') + environ = {"BUILD_RELEASE_PROJECT_RUNG": "claude-fable-5-2 at low effort", "BUILD_RELEASE_WORKER_RUNG": "claude-fable-5-2 at high effort"} + skill = Call("Skill", {"skill": "security-review"}, checkout) + self.assertEqual(rules(skill_breaches(skill, environ | moved, home)), ["reviewer-rung"]) + self.assertEqual(skill_breaches(skill, environ, home), []) + def test_a_security_skill_is_held_to_the_projects_rung_on_the_projects_own_ladder(self): checkout, home = self.project('[{"model": "claude-fable-5-2", "effort": "high"}, {"model": "claude-fable-5-2", "effort": "low"}]') # On this ladder the worker's low effort ranks above the project's high one; on the shipped ladder it ranks below. @@ -745,6 +759,13 @@ class ReviewerReport(unittest.TestCase): with self.subTest(path): self.assertEqual(self.breached("Write", path), ["reviewer-report"]) + def test_the_reports_folder_follows_xdg_state_home(self): + env = {"XDG_STATE_HOME": "/state"} + for path, expected in [("/state/build-release/larv-review/x/prose-round-1.md", []), ("/h/.local/state/build-release/larv-review/x/prose-round-1.md", ["reviewer-report"])]: + with self.subTest(path): + found = breaches_of(Call("Write", {"file_path": path, "content": "x"}, "/r", "prose-reviewer"), "/h", env) + self.assertEqual(rules(found[2]), expected) + def test_a_reviewer_edits_no_file_even_in_the_reports_folder(self): self.assertEqual(self.breached("Edit", "/h/.local/state/build-release/larv-review/x/prose-round-1.md"), ["reviewer-report"]) @@ -1233,6 +1254,21 @@ class Hook(unittest.TestCase): self.assertEqual(self.round_commit("PAY-7 - Answer prose round 1: 0 🔴, 0 🟡 (0 misread); x").returncode, 0) self.assertEqual(self.round_commit("Tidy # rule-override commit-title: the client asked for this title").returncode, 0) + def test_a_commit_is_checked_against_the_config_and_the_report_under_the_xdg_folders(self): + home = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(subprocess.run, ["rm", "-rf", str(home)]) + config = configured(self, pathlib.Path(self.repo), home=home) / "config.toml" + config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\n') + (home / ".config").rename(home / "configs") + git(self.repo, "checkout", "-q", "-b", "item-7") + folder = home / "state" / "build-release" / "larv-review" / self.repo.lstrip("/") + folder.mkdir(parents=True) + (folder / "stability-round-1.md").write_text("BLOCK\n\n### 🟡 `b.py:2`: worse\n") + self.env = {"HOME": str(home), "XDG_CONFIG_HOME": str(home / "configs"), "XDG_STATE_HOME": str(home / "state")} + self.assertIn("Blocked by rule commit-title: title the commit as the project's config asks, `PAY-{id} - {summary}`", self.round_commit("Tidy").stderr) + self.assertIn("Blocked by rule round-title-counts", self.round_commit("PAY-7 - Answer stability round 1: 0 🔴, 0 🟡 (0 misread); x").stderr) + self.assertEqual(self.round_commit("PAY-7 - Answer stability round 1: 0 🔴, 1 🟡 (0 misread); x").returncode, 0) + def test_a_commit_on_a_branch_that_doesnt_fit_the_configs_branch_template_takes_a_bare_title(self): config = self.configured() / "config.toml" config.write_text(config.read_text() + 'commit-title = "PAY-{id} - {summary}"\nbranch = "feature/PAY-{id}"\n') @@ -1381,6 +1417,22 @@ class TodoRankCheck(unittest.TestCase): self.assertTrue(reasons) self.assertNotIn("own script", " ".join(reasons)) + def test_a_config_under_xdg_config_home_names_the_checkout_and_holds_its_plan(self): + checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) + moved = self.home / "moved" + (self.home / ".config").rename(moved) + env = {"XDG_CONFIG_HOME": str(moved)} + + def details(directory: str) -> list[str]: + return [breach.detail for breach in todo_breaches(directory, self.home, env, pathlib.Path(self.own))] + + self.assertEqual(details(checkout), [f"own script checked {checkout}/todo.md"]) + config = moved / self.config.relative_to(self.home / ".config") + config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) + (config.parent / "todo.md").write_text("# todo\n") + git(str(config.parent), "init", "-q", "-b", "main") + self.assertEqual(details(str(config.parent)), [f"own script checked {config.parent}/todo.md"], "a commit in the config's folder checks the plan it holds") + def test_a_plan_the_config_puts_outside_the_checkout_is_checked_in_place_of_the_checkouts_todo_md(self): checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"')) -- 2.52.0 From 9ae3e85cba603e79005cc889d49dcc53a74f0794 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 22:00:44 +0100 Subject: [PATCH 12/15] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20a=20window?= =?UTF-8?q?=20is=20handed=20an=20XDG=20variable=20its=20starter=20lacks=20?= =?UTF-8?q?as=20empty,=20and=20a=20test=20pins=20the=20plan=20check=20unde?= =?UTF-8?q?r=20XDG=5FCONFIG=5FHOME?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/build_release/loop/test_chunk_windows.py | 4 ++-- bin/build_release/test_black_box.py | 2 +- bin/chunk_driver/claims.py | 7 ++++--- bin/chunk_driver/test_claims.py | 4 ++-- bin/do_epic/test_main.py | 2 +- bin/rule_hook/test_rule_hook.py | 4 ++++ 6 files changed, 14 insertions(+), 9 deletions(-) diff --git a/bin/build_release/loop/test_chunk_windows.py b/bin/build_release/loop/test_chunk_windows.py index 288a5744..3118ae8b 100644 --- a/bin/build_release/loop/test_chunk_windows.py +++ b/bin/build_release/loop/test_chunk_windows.py @@ -167,8 +167,8 @@ class StartChunks(unittest.TestCase): self.assertEqual(self.starts(fake), [("new-session", "item-1", [str(self.LAUNCHER), "--chunk", "item-1", "ship it"]), ("new-window", "item-3", [str(self.LAUNCHER), "--chunk", "item-3", "ship it"])]) first = next(call for call in fake.tmux_calls if call[0] == "new-session") self.assertEqual((first[first.index("-s") + 1], first[first.index("-c") + 1]), (self.session, str(self.root))) - # Only build-release's own variables are handed on, since a window gets the tmux server's environment. - self.assertEqual([word for word in first if "=" in word], ["BUILD_RELEASE_WORKER_MODEL=m"]) + # Only build-release's own variables and the two XDG ones are handed on, since a window gets the tmux server's environment. + self.assertEqual([word for word in first if "=" in word], ["BUILD_RELEASE_WORKER_MODEL=m", "XDG_CONFIG_HOME=", "XDG_STATE_HOME="]) self.assertEqual(fake.tmux_calls[0], ["list-windows", "-t", f"={self.session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]) # The session names the checkout whose chunks it runs. self.assertIn(["set-option", "-t", f"={self.session}:", "@loop-root", str(self.root)], fake.tmux_calls) diff --git a/bin/build_release/test_black_box.py b/bin/build_release/test_black_box.py index c24f3655..c8b7b165 100644 --- a/bin/build_release/test_black_box.py +++ b/bin/build_release/test_black_box.py @@ -836,7 +836,7 @@ class Windows(unittest.TestCase): ["-V"], ["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"], ["list-windows", "-a", "-F", "#{session_name}\t#{window_name}\t#{pane_dead}\t#{window_id}\t#{@chunk-root}"], - ["new-session", "-d", "-s", "loop-proj", "-n", "item-4", "-c", str(checkout.root), "-e", "BUILD_RELEASE_JUDGE_MODEL=judge-model", "-e", "BUILD_RELEASE_WORKER_MODEL=worker-model", "-P", "-F", "#{window_id}", "--", str(checkout.script), "--chunk", "item-4", "ship it"], + ["new-session", "-d", "-s", "loop-proj", "-n", "item-4", "-c", str(checkout.root), "-e", "BUILD_RELEASE_JUDGE_MODEL=judge-model", "-e", "BUILD_RELEASE_WORKER_MODEL=worker-model", "-e", "XDG_CONFIG_HOME=", "-e", "XDG_STATE_HOME=", "-P", "-F", "#{window_id}", "--", str(checkout.script), "--chunk", "item-4", "ship it"], ["set-option", "-t", "=loop-proj:", "@loop-root", str(checkout.root)], ["set-option", "-w", "-t", "@7", "@chunk-root", str(checkout.root)], ["set-option", "-w", "-t", "@7", "remain-on-exit", "failed"], diff --git a/bin/chunk_driver/claims.py b/bin/chunk_driver/claims.py index aad014c5..b6bdd518 100644 --- a/bin/chunk_driver/claims.py +++ b/bin/chunk_driver/claims.py @@ -20,10 +20,11 @@ CHUNK_FLAG = "--chunk" OWN = "BUILD_RELEASE_" -# A window gets the tmux server's environment, not the starting terminal's. Without the two XDG variables, a window would lock and write in other folders than the entry point that started it. +# A window gets the tmux server's environment, not the starting terminal's. With another XDG value than its starter's, a window would lock and write in other folders. So each is handed even where the starter lacks it, as empty: an empty value moves no folder. def handed(env: typing.Mapping[str, str]) -> dict[str, str]: - """The variables of env that an entry point hands each window it starts: those both entry points read, and the two that move the config folder and the state folder.""" - return {name: value for name, value in env.items() if name.startswith(OWN) or name in (XDG_CONFIG_HOME, XDG_STATE_HOME)} + """The variables an entry point hands each window it starts: those of env that both entry points read, and the two that move the config folder and the state folder.""" + own = {name: value for name, value in env.items() if name.startswith(OWN)} + return {**own, XDG_CONFIG_HOME: env.get(XDG_CONFIG_HOME, ""), XDG_STATE_HOME: env.get(XDG_STATE_HOME, "")} @contextlib.contextmanager diff --git a/bin/chunk_driver/test_claims.py b/bin/chunk_driver/test_claims.py index b7346b04..0c5f4076 100644 --- a/bin/chunk_driver/test_claims.py +++ b/bin/chunk_driver/test_claims.py @@ -14,8 +14,8 @@ class Handed(unittest.TestCase): env = {"BUILD_RELEASE_JUDGE_MODEL": "judge", "XDG_CONFIG_HOME": "/configs", "XDG_STATE_HOME": "/state", "XDG_DATA_HOME": "/data", "PATH": "/bin"} self.assertEqual(handed(env), {"BUILD_RELEASE_JUDGE_MODEL": "judge", "XDG_CONFIG_HOME": "/configs", "XDG_STATE_HOME": "/state"}) - def test_hands_no_variable_the_starter_lacks(self) -> None: - self.assertEqual(handed({"PATH": "/bin"}), {}) + def test_hands_an_xdg_variable_the_starter_lacks_as_empty_so_the_tmux_servers_value_moves_no_folder(self) -> None: + self.assertEqual(handed({"PATH": "/bin", "XDG_STATE_HOME": "/state"}), {"XDG_CONFIG_HOME": "", "XDG_STATE_HOME": "/state"}) class Starting(unittest.TestCase): diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 59968dd1..ab4b4c77 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -146,7 +146,7 @@ class TheCommand(DoEpicTest): self.assertIn("started ABC-21 in the tmux session epic-ABC-12\n", out) self.assertIn("ABC-20 waits: it is a human's task\n", out) started = [args for args in fake.tmux_calls if args[0] == "new-session"] - self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/build-release/do-epic/ABC-12"), "-e", "BUILD_RELEASE_WORKER_MODEL=m", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]]) + self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/build-release/do-epic/ABC-12"), "-e", "BUILD_RELEASE_WORKER_MODEL=m", "-e", "XDG_CONFIG_HOME=", "-e", "XDG_STATE_HOME=", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]]) # The session is no checkout's, so nothing marks it as one's. self.assertNotIn(tmux.OWNER, [args[3] for args in fake.tmux_calls if args[0] == "set-option"]) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 805de0b8..261d9ba3 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -1268,6 +1268,10 @@ class Hook(unittest.TestCase): self.assertIn("Blocked by rule commit-title: title the commit as the project's config asks, `PAY-{id} - {summary}`", self.round_commit("Tidy").stderr) self.assertIn("Blocked by rule round-title-counts", self.round_commit("PAY-7 - Answer stability round 1: 0 🔴, 0 🟡 (0 misread); x").stderr) self.assertEqual(self.round_commit("PAY-7 - Answer stability round 1: 0 🔴, 1 🟡 (0 misread); x").returncode, 0) + pathlib.Path(self.repo, "todo.md").write_text("# todo\n") + plan = self.round_commit("PAY-7 - Tidy").stderr + self.assertIn("Blocked by rule todo-rank-check", plan) + self.assertNotIn("no config names the checkout", plan) def test_a_commit_on_a_branch_that_doesnt_fit_the_configs_branch_template_takes_a_bare_title(self): config = self.configured() / "config.toml" -- 2.52.0 From 2e0b0fb0eb246679e86940b1aba0699dd078325d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 22:08:35 +0100 Subject: [PATCH 13/15] =?UTF-8?q?Answer=20overrides=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20the=20overr?= =?UTF-8?q?ide=20of=20todo-rank-check=20on=20the=20merge=20of=20main=20is?= =?UTF-8?q?=20accepted?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 8ccc97acfbe696828dd1c69311610f726ad4c5eb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 22:08:51 +0100 Subject: [PATCH 14/15] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20/security-r?= =?UTF-8?q?eview=20found=20nothing=20to=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From e6b025caaaf51b6f550cc72650ea77bfa536ba84 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv <lilleman@larvit.se> Date: Thu, 3 Dec 2026 22:13:47 +0100 Subject: [PATCH 15/15] Finish item 484 in the plan --- CHANGELOG.md | 1 + todo.md | 87 ++-------------------------------------------------- 2 files changed, 3 insertions(+), 85 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e99ce197..c34b4b8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- The setup's folders moved, and nothing reads or migrates the old ones. Before you update, stop every running `build-release` and `do-epic`. Then move `~/.claude-projects/` to `~/.config/build-release/` and `~/.claude/loop-claude-models.json` to `~/.config/build-release/models.json`; move `~/.claude/loop-claude-transcripts` to `~/.local/state/build-release/transcripts` and `~/.claude/do-epic-transcripts` to `~/.local/state/build-release/do-epic-transcripts`; move `larv-review`, `do-epic`, `project-record`, `run-heavy` and `deploy-release` from `~/.local/state/` into `~/.local/state/build-release/`; and delete `~/.local/state/loop-claude/`, which held only locks. Respell each setting that names `~/.claude-projects/`, such as `env-file`, and the log path in your crontab line. Where `XDG_CONFIG_HOME` or `XDG_STATE_HOME` holds an absolute path, the two folders are `build-release/` under it instead, and a chunk's tmux window is handed both variables. - The stability reviewer traces every path that can reach a callback, handler or hook that a change guards, background and process-wide ones included, and reports each path the guard leaves open. - Interactive sessions start with permissions bypassed (`defaultMode: bypassPermissions`) instead of in auto mode, so a session on the sandbox this checkout requires asks for permission only where Claude Code always does. - Renamed `loop-claude` to `build-release`, with no alias. Before you update, finish your open chunks, since a chunk left open under `loop-claude` starts a fresh session, and stop every running `loop-claude`, since a loop that runs across the update can't reload and hands its workers variables the new rule-hook ignores. Then remove `~/.local/bin/loop-claude`, link the new name with `ln -s ~/.claude/bin/build-release ~/.local/bin/build-release`, and rename each `LOOP_CLAUDE_*` variable you set, in your shell profile and in your crontab, to `BUILD_RELEASE_*`, such as `BUILD_RELEASE_TRANSCRIPTS`. diff --git a/todo.md b/todo.md index 651cf6af..30749b18 100644 --- a/todo.md +++ b/todo.md @@ -12,10 +12,9 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 484 | 0.18.0 | | owner | **Keep project configs and this machine's rules in `~/.config/build-release/`, and transcripts and review reports in `~/.local/state/build-release/`, each under its `XDG_*` variable where set, read no old place, and have rule-hook guard the new ones.** | 4 | 2 | 4 | 8 | 6 | 2 by 4 | 0.4 | -| 575 | 0.18.0 | 484 | owner | **Rename `do-epic` to `build-epic`, with no alias, and its config folder with it.** | 2 | 2 | 2 | 4 | 4 | 2 by 2, 6 by 1 | 0.6 | +| 575 | 0.18.0 | | owner | **Rename `do-epic` to `build-epic`, with no alias, and its config folder with it.** | 2 | 2 | 2 | 4 | 4 | 2 by 2, 6 by 1 | 0.6 | | 482 | 0.18.0 | | owner | **Run the setup from a clone of a release by the path of its `bin/`, with no install step, and replace `deploy-release` with a command that moves that clone to the newest tag.** | 3 | 2 | 3 | 6 | 7 | 2 by 6 | 0.4 | -| 483 | 0.18.0 | 482, 484 | owner | **Run every claude the loop starts in a Claude home that the commands generate under `~/.local/share/build-release/` and refresh when the clone's tag changes, with the enabled plugins installed there and the person signed in by `/login` in that home.** | 4 | 2 | 3 | 7 | 7 | 2 by 8 | 0.5 | +| 483 | 0.18.0 | 482 | owner | **Run every claude the loop starts in a Claude home that the commands generate under `~/.local/share/build-release/` and refresh when the clone's tag changes, with the enabled plugins installed there and the person signed in by `/login` in that home.** | 4 | 2 | 3 | 7 | 7 | 2 by 8 | 0.5 | | 486 | 0.18.0 | 483 | owner | **Open an interactive claude with the setup loaded through one wrapper command, which sets the generated home and `PATH` and passes every argument on to claude.** | 2 | 1 | 1 | 2 | 3 | 2 by 2 | 0.5 | | 577 | 0.18.0 | 483, 486, 575 | owner | **Test in the gate that a container holding only a stock Claude Code runs a chunk from a clone, against a mock Messages API, and that the run leaves the container's own `~/.claude` as it was.** | 3 | 1 | 2 | 4 | 6 | 3 by 9, 2 by 5 | 5.2 | | 576 | 0.18.0 | 575 | owner | **Name the project `dev-factory` in the README, the prose and the tools, and say in the changelog that the repo moved.** | 2 | 2 | 2 | 4 | 4 | 2 by 1, 6 by 1 | 0.4 | @@ -106,88 +105,6 @@ ## Details -### 484. Keep project configs and this machine's rules in `~/.config/build-release/`, and transcripts and review reports in `~/.local/state/build-release/`, each under its `XDG_*` variable where set, read no old place, and have rule-hook guard the new ones. - -Part of the standalone-install plan lilleman approved on 2026-11-20, as reshaped on 2026-12-03 when 0.18.0 was planned. Today they live in `~/.claude-projects/`, `~/.claude/*-transcripts`, `~/.claude/loop-claude-models.json` and `~/.local/state/larv-review`. `rules/goals-and-audience.md` loads by the glob `**/.claude-projects/*/goals.md`, which moves with the folder. The release ships no migrate command and reads no old place: the only two machines move once, after the cut, by a throwaway script that is never committed. From the first release that reads project configs from `~/.config/build-release/`, rule-hook must read each `env-file` from those configs and refuse a read of it, as it does today from the old folder. - -Item 480 lands first and gathers these paths in one module, so how many of the call sites below still change here is not predictable; the list names each. Whether the other state the tools keep under `~/.local/state`, such as the chunk claims, do-epic's epic state and the project-record copies, moves too is not predictable either, so the list holds it. The trial records under `judge-field-trials/`, `reviewer-merge-trials/`, `stability-skip-count/` and `presentation/` name the old transcript folders, and the list leaves them out as history. - -L is 4 since the change is S 6, spans some twenty packages under `bin/`, moves live config and state, and threads the `XDG_*` environment to call sites that today hold only `home`. - -Touches: - -- `bin/loop_state/paths.py`: `Paths` (small), `paths_from` (small) -- `bin/project_config/settings.py`: `(module)`, `PROJECTS`, `DO_EPIC`, `ProjectConfig`, `load`, `held`, `by_name`, `configs`, `env_files` -- `bin/project_config/main.py`: `(module)` (small) -- `bin/review_rules/review_folder.py`: `REPORTS`, `review_folder`, `made_review_folder` -- `bin/transcript_archive/__init__.py`: `(module)` (small) -- `bin/transcript_archive/location.py`: `archive_root`, `project_archive` -- `bin/chunk_driver/claims.py`: `CLAIMS`, `project_lock` (small) -- `bin/chunk_driver/project/model_choice.py`: `save_model` (small) -- `bin/project_record/main.py`: `(module)` (small), `COPIES`, `opened` (small), `pruned` (small) -- `bin/do_epic/config.py`: `(module)`, `DoEpicConfig`, `load` -- `bin/do_epic/repos.py`: `locate` (small) -- `bin/do_epic/main.py`: `HELP` (small), `ARCHIVE`, `next_cycle` (small) -- `bin/do_epic/scheduler.py`: `STATE`, `Epic.folder` (small) -- `bin/do_epic/backend/jira.py`: `NO_FINISH` (small) -- `bin/do_epic/e2e/scenario.py`: `machine_made` (small) -- `bin/rule_hook/env_file.py`: `(module)`, `env_file_breaches`, `reaching` -- `bin/rule_hook/reviewer_report.py`: `(module)` (small), `report_breaches` -- `bin/rule_hook/rules.py`: `RULES` (small) -- `bin/compress_archives/main.py`: `(module)`, `main` -- `bin/review_replay/main.py`: `(module)` (small) -- `bin/review_replay/replay.py`: `review` (small), `redirected` (small) -- `bin/judge_replay/main.py`: `(module)` (small) -- `bin/larv_review/main.py`: `(module)` (small) -- `bin/build_release/loop/usage.py`: `HELP` (small) -- `bin/notifier/main.py`: `(module)` (small) -- `bin/reading_cost/main.py`: `(module)` (small) -- `bin/subagent_rung/main.py`: `(module)` (small) -- `bin/task_bench/main.py`: `bench` (small) -- `settings.json`: lines 59-59 -- `rules/goals-and-audience.md`: `(top)` (small) -- `CLAUDE.md`: `## Working with the codebase` (small), `## Git, commits, and PRs` (small) -- `README.md`: `## Install`, `### Set up a project`, `## Release` (small), `## Test` (small) -- `bin/chunk_driver/project/test_model_choice.py`: `SavingAModel` -- `bin/chunk_driver/project/test_records.py`: `Records` -- `bin/chunk_driver/test_claims.py`: `Starting` -- `bin/chunk_pr/test_chunk_pr.py`: `Checkout`, `Merge` -- `bin/chunk_preflight/test_chunk_preflight.py`: `Repo`, `ChunkPreflightTool`, `EpicBranchWorktree` -- `bin/command_patterns/test_command_patterns.py`: `Main` -- `bin/compress_archives/test_compress_archives.py`: `Main` -- `bin/do_epic/backend/test_jira.py`: `Jira` -- `bin/do_epic/test_do_epic.py`: `ConfigTest` -- `bin/do_epic/test_findings.py`: `FindingsTest`, `FilingAFinding` -- `bin/do_epic/test_finish.py`: `ClosingTheEpic`, `TheFinishingChunk` -- `bin/do_epic/test_human_tasks.py`: `AHumanTaskThatBlocksAnIssue` -- `bin/do_epic/test_main.py`: `DoEpicTest`, `TheCommand`, `ACycleOfAChunkWithoutARepo`, `TheHumansRun`, `AChunksRun`, `AChunkWhosePullRequestWaitsOnAGate`, `AnEpicsWorkingBranch`, `TheDryRun` -- `bin/do_epic/test_planning.py`: `Planning` -- `bin/do_epic/test_repos.py`: `LocateTest` -- `bin/do_epic/test_scheduler.py`: `StartingAnEpicsChunks` -- `bin/judge_replay/test_judge_replay.py`: `Main` -- `bin/larv_review/test_larv_review.py`: `LarvReviewTool` -- `bin/larv_review/test_scoring_setup.py`: `PrepareScoring` -- `bin/build_release/loop/test_chunk_windows.py`: `StartChunks` -- `bin/build_release/loop/test_main.py`: `WindowStarts`, `OwnLadder` -- `bin/build_release/test_black_box.py`: `Checkout`, `Premises`, `Cycles`, `Windows`, `Interrupt` -- `bin/notifier/test_notifier.py`: `Project` -- `bin/project_config/doubles.py`: `write_config` -- `bin/project_config/test_project_config.py`: `ConfigCase`, `LoadTest`, `HeldTest`, `ToolTest` -- `bin/project_record/test_project_record.py`: `COPIES`, `worktree_config`, `Pruned`, `BlackBox` -- `bin/reading_cost/test_reading_cost.py`: `ReadingCostTool` -- `bin/record_store/test_stores.py`: `Store`, `GoalsStore` -- `bin/repo_checks/test_gitignore.py`: `PRIVATE` -- `bin/review_replay/test_review_replay.py`: `Main` -- `bin/review_rules/test_review_folder.py`: `ReviewFolder` -- `bin/rule_hook/test_rule_hook.py`: `ReviewerRung`, `EnvFileRead`, `ReviewerReport`, `Hook`, `TodoRankCheck`, `TranscriptRead` -- `bin/score_outcomes/test_score_outcomes.py`: `ScoreOutcomesTool` -- `bin/subagent_rung/test_subagent_rung.py`: `SubagentRung` -- `bin/task_bench/features/test_feature_tasks.py`: `BenchOfTasksCase`, `FeatureBenchTest` -- `bin/task_bench/figures/test_gather.py`: `GatherTest` -- `bin/task_bench/figures/test_record_figures.py`: `RecordFiguresTest` -- `bin/task_bench/test_task_bench.py`: `BenchTest` -- `bin/transcript_archive/test_transcript_archive.py`: `Location` - ### 575. Rename `do-epic` to `build-epic`, with no alias, and its config folder with it. Part of the standalone-install plan lilleman approved on 2026-11-20, as reshaped on 2026-12-03 when 0.18.0 was planned. The decision "names" set `build-epic` beside `build-release`. Its machine settings move from `~/.claude-projects/do-epic/` to a folder named for `build-epic` under `~/.config/build-release/`. The changelog names the successor, and nothing forwards from the old name. -- 2.52.0