Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2062e91920 | |||
| 15fb37dc0c | |||
| 1f65b5512b | |||
| 27b5409479 | |||
| 6cdbcbc08b | |||
| 89a85f88df | |||
| 9b6303f561 | |||
| 9508838439 | |||
| 4fc00a0b89 | |||
| b2142ee620 | |||
| d15380249d | |||
| 4718baca27 | |||
| 084bc74b1c | |||
| 854eb63407 |
@@ -72,12 +72,17 @@
|
||||
!bin/mutate_changes/
|
||||
!bin/mutate_changes/*.py
|
||||
!bin/project-config
|
||||
!bin/project-record
|
||||
!bin/project_config/
|
||||
!bin/project_config/*.py
|
||||
!bin/project_record/
|
||||
!bin/project_record/*.py
|
||||
!bin/rank_todo.py
|
||||
!bin/reading-cost
|
||||
!bin/reading_cost/
|
||||
!bin/reading_cost/*.py
|
||||
!bin/record_store/
|
||||
!bin/record_store/*.py
|
||||
!bin/release_plan/
|
||||
!bin/release_plan/*.py
|
||||
!bin/repo_checks/
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `chunk-pr merge` waits for a human's approval of the pull request where the project's config sets `wait-for-approval = true`: it merges once GitHub reports the pull request approved, and gives up after 90 minutes. It reads approvals on GitHub only. Set it for a client whose pull requests need another person's approval.
|
||||
- The technical principles ask for code in files and folders before `// --- name ---` banner comments. They also ask for an entry point a newcomer finds at once: the root holds it, the README and the files a tool reads only from there.
|
||||
- In a client project, the loop reads the team's own `CLAUDE.md` and `AGENTS.md` and proposes each change that aligns them with this setup in a pull request of its own. Where the team declines or doesn't answer, the loop follows the team's rule unless it breaks a project goal, and records the conflict as a decision in the `decisions` record.
|
||||
- The new `project-record open <record>` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save <record>` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change.
|
||||
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The Mattermost DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link. Once every loop started before the upgrade has reloaded or ended, remove the folder `~/.local/state/loop-claude/`, which nothing reads any more.
|
||||
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
|
||||
- To keep Mattermost DMs, move the keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, and name it in the project's config as `env-file`; `mattermost-dm` and loop-claude's DMs no longer read `~/.claude/.env`, and a project with no `env-file` gets none. A failure names each missing key and holds no token.
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
|
||||
## Working loop
|
||||
|
||||
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. A rule names a project's files by their usual paths: `todo.md`, `AGENTS.md`, `CHANGELOG.md` and the files under `docs/`. Each is where the project's config puts it, which `~/.claude/bin/project-config` prints and `chunk-preflight`'s facts quote. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
|
||||
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. A rule names a project's files by their usual paths: `todo.md`, `AGENTS.md`, `CHANGELOG.md` and the files under `docs/`. Each is where the project's config puts it, which `~/.claude/bin/project-config` prints and `chunk-preflight`'s facts quote. Read and edit a project record in the file `~/.claude/bin/project-record open <record>` prints, and run `project-record save <record>` after each edit. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
|
||||
|
||||
- **Until the goals file has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. In a README both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
|
||||
- **Plan `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
|
||||
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
|
||||
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
|
||||
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that doesn't publish anything says so once.
|
||||
- **A client project's `CLAUDE.md` and `AGENTS.md` in its repo belong to its team.** Read both at the start of each chunk there. Propose each change that aligns them with this setup in a pull request of its own, never inside a chunk's; the one edit a chunk makes there is a decision's title in `AGENTS.md`. Until the team accepts a proposal, and after it declines or doesn't answer, follow the team's rule unless it breaks one of the project's goals. Record each such conflict as a decision in the `decisions` record, as `rules/decisions.md` asks: which rule you follow, why, and the open proposal's PR. Then nobody is asked twice.
|
||||
- **Read the goals file's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
|
||||
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and each item that may join it with its L, E + I, S, tagline and detail; open `todo.md` only for what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes, with `~/.claude/bin/todo-item show <ID>`, which prints an item's row and detail. `AGENTS.md` lists the project principles and the title of each decision no project principle covers. Read an entry in `docs/decisions.md` only where the project principle or the title leaves open what the chunk or the review needs.
|
||||
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in `todo.md`, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
|
||||
@@ -134,6 +135,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
|
||||
- **plan** — the project's `todo.md`, at the path its config names as `plan`.
|
||||
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's goals file, with code health ("Shared goal") first among the goals unless the goals file voids it.
|
||||
- **project's rung** — the cheapest rung on loop-claude's routing ladder of the project's model, which is the model loop-claude's prompt names as the project's, or else your own.
|
||||
- **project record** — one of five documents a project keeps beside its plan, each where its config names it: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`.
|
||||
- **release** — a semver version the human cuts.
|
||||
- **release review** — a release's last chunk: the architecture and principles passes over the whole project, before the release is ready to cut; `larv-review` §3 → "Release review".
|
||||
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
|
||||
|
||||
@@ -79,7 +79,7 @@ To get loop-claude's questions and stops as Mattermost DMs from a bot, write the
|
||||
|
||||
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.
|
||||
|
||||
The config names the project's main checkout and the path of every file the loop keeps for it. No 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. 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 in its checkout:
|
||||
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 in its checkout:
|
||||
|
||||
```toml
|
||||
checkout = "~/code/log"
|
||||
@@ -96,6 +96,8 @@ principles = "~/.claude/principles"
|
||||
|
||||
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 whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false.
|
||||
|
||||
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
|
||||
|
||||
```sh
|
||||
@@ -145,6 +147,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
|
||||
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
|
||||
- `project-config [<setting>]` prints the paths a project's config sets, or the one asked for, and fails naming each setting the config leaves out; Install → "Set up a project" shows a config.
|
||||
- `project-record open <record>` prints the path of a file holding one of a project's records, for an agent to read and edit, and `project-record save <record>` stores the edit; for a record kept as a file, that file is the record.
|
||||
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`, by default the one its config names; `rank_todo.py --help` states the format.
|
||||
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round three times as archived and once without the instruction files, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
@@ -158,7 +161,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `todo-item add …` files an item in a project's `todo.md`, taking `Next ID` as the item's ID, and `todo-item finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`; both rank the file. `todo-item show <ID>` prints an item's row and detail. `todo-item --help` states the flags.
|
||||
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
|
||||
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool.
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool.
|
||||
|
||||
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
|
||||
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
@@ -173,6 +176,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`.
|
||||
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
|
||||
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` reads, ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py`, `rule_hook` and `todo_item`.
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
|
||||
|
||||
@@ -5,6 +5,8 @@ from branch_chunks.cut import BranchChunk, cut_branch, LOG, NOT_WORK, plan_revis
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git, Git, text_at
|
||||
from project_config.main import located
|
||||
from project_config.settings import ProjectConfig
|
||||
from record_store.stores import store
|
||||
|
||||
|
||||
# Where branch_chunks reads the plan and the records, by the setting that names each in a project's config.
|
||||
@@ -16,12 +18,20 @@ def unsupported(checkout: str | None, home: pathlib.Path, run: Git = git) -> str
|
||||
config = located(checkout, home, run)
|
||||
if isinstance(config, Failure):
|
||||
return None
|
||||
elsewhere = [str(config.paths[setting]) for setting, path in READ_AT.items() if config.tracked(setting) != path]
|
||||
elsewhere = [label for name, path in READ_AT.items() for label, tracked in [held(config, name)] if tracked != path]
|
||||
if not elsewhere:
|
||||
return None
|
||||
return f"the project's config puts {', '.join(elsewhere)} elsewhere than {', '.join(READ_AT.values())} in the checkout, the only paths whose commits are read so far"
|
||||
|
||||
|
||||
def held(config: ProjectConfig, name: str) -> tuple[str, str | None]:
|
||||
"""What a message calls the plan or the record that setting name names in config, and its path from the checkout's top, None where it is kept elsewhere."""
|
||||
if name == "plan":
|
||||
return str(config.paths[name]), config.tracked(name)
|
||||
record = store(config, name)
|
||||
return record.label, record.tracked
|
||||
|
||||
|
||||
def branch_chunks(default: str, run: Git) -> list[BranchChunk] | Failure:
|
||||
"""Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped.
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""The human approval that `chunk-pr merge` waits for where the project's config sets `wait-for-approval`."""
|
||||
import json
|
||||
import pathlib
|
||||
import time
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge
|
||||
from deploy_release.forge import Run
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes, which leaves room for the checks wait inside the 2 hours a background command may run, so that the give-up message prints.
|
||||
POLL_SECONDS = 60
|
||||
WAIT_SECONDS = 90 * 60
|
||||
|
||||
|
||||
def awaited(forge: Forge, run: Run) -> bool | Failure:
|
||||
"""Whether merge waits for an approval: the project config's `wait-for-approval`. A config that cannot be read fails, so that merge never skips an approval the config may require. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails too."""
|
||||
answer = run([str(BIN / "project-config"), "wait-for-approval"])
|
||||
if isinstance(answer, Failure):
|
||||
return answer
|
||||
if answer.strip() not in ("true", "false"):
|
||||
return Failure(f"project-config wait-for-approval printed {answer.strip()[:80]!r}, not true or false")
|
||||
if answer.strip() == "true" and forge != "gh":
|
||||
return Failure("the project's config sets wait-for-approval, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it")
|
||||
return answer.strip() == "true"
|
||||
|
||||
|
||||
def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
|
||||
"""None once GitHub reports pull request number approved, as its branch protection asks; a Failure where a reviewer requested changes, where the protection asks for no review, or where no approval came within WAIT_SECONDS."""
|
||||
for waited in range(0, WAIT_SECONDS + 1, POLL_SECONDS):
|
||||
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
|
||||
try:
|
||||
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
|
||||
if isinstance(decision, Failure):
|
||||
return decision
|
||||
if decision == "APPROVED":
|
||||
return None
|
||||
if decision == "CHANGES_REQUESTED":
|
||||
return Failure(f"a reviewer requested changes on pull request {number}")
|
||||
if not decision:
|
||||
return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false")
|
||||
if decision != "REVIEW_REQUIRED":
|
||||
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
|
||||
if waited < WAIT_SECONDS:
|
||||
sleep(POLL_SECONDS)
|
||||
return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is")
|
||||
@@ -31,6 +31,12 @@ merge waits for the pull request's checks, and those origin's default branch
|
||||
only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the
|
||||
merge commit, the rebase and the squash. It also refuses where `larv-review
|
||||
scoring-run-owed` exits 1, because the chunk owes a scoring run it has not recorded.
|
||||
Where the project's config sets `wait-for-approval = true` (`project-config --help`), it
|
||||
also waits, once the checks have passed, until GitHub reports the pull request approved
|
||||
as its branch protection requires. It refuses at once where a reviewer requested changes,
|
||||
where the protection requires no review, on Gitea, and where it cannot read the config.
|
||||
After 90 minutes without an approval it refuses too; run it again once the pull request
|
||||
is approved.
|
||||
clean acts once the forge reports the branch's pull request merged at the commit checked out,
|
||||
by any merge method. It fetches origin, fast-forwards the main checkout to origin's
|
||||
default branch, removes the chunk's worktree, then deletes the local branch; origin's
|
||||
@@ -49,6 +55,7 @@ import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
from chunk_pr.approval import approved, awaited
|
||||
from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, required_checks, Run, runner
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge
|
||||
@@ -223,6 +230,9 @@ def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> str
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
forge, number, head = found
|
||||
waits = awaited(forge, run)
|
||||
if isinstance(waits, Failure):
|
||||
return waits
|
||||
owed = run([str(BIN / "larv-review"), "scoring-run-owed"])
|
||||
if isinstance(owed, Failure):
|
||||
return owed
|
||||
@@ -234,6 +244,9 @@ def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> str
|
||||
checked = required if isinstance(required, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
approval = approved(number, run, sleep) if waits else None
|
||||
if isinstance(approval, Failure):
|
||||
return approval
|
||||
if forge == "gh":
|
||||
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", head])
|
||||
else:
|
||||
|
||||
@@ -25,6 +25,8 @@ GH_CHECKS = ["gh", "pr", "checks", "12", "--watch", "--fail-fast"]
|
||||
TEA_BRANCH = ["tea", "api", "repos/{owner}/{repo}/branches/main"]
|
||||
TEA_STATUS = ["tea", "api", f"repos/{{owner}}/{{repo}}/commits/{HEAD}/status"]
|
||||
OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scoring-run-owed"]
|
||||
WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "wait-for-approval"]
|
||||
GH_DECISION = ["gh", "pr", "view", "12", "--json", "reviewDecision"]
|
||||
|
||||
|
||||
class Checkout:
|
||||
@@ -37,12 +39,17 @@ class Checkout:
|
||||
self.open = open
|
||||
self.allowed = allowed
|
||||
self.statuses: list[str] = []
|
||||
# What GitHub reports as the pull request's review decision on each read; the last one repeats.
|
||||
self.decisions = ["APPROVED"]
|
||||
# Set, what GitHub prints instead of a decision's JSON.
|
||||
self.unreadable: str | Failure | None = None
|
||||
self.ran: list[list[str]] = []
|
||||
self.answers: dict[tuple[str, ...], str | Failure] = {
|
||||
("git", "remote", "get-url", "origin"): f"{origin}\n",
|
||||
("git", "symbolic-ref", "--short", "HEAD"): "item-7\n",
|
||||
("git", "rev-parse", "HEAD"): f"{HEAD}\n",
|
||||
("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"): "origin/main\n",
|
||||
tuple(WAITS): "false\n",
|
||||
}
|
||||
|
||||
def __call__(self, command: list[str]) -> str | Failure:
|
||||
@@ -59,6 +66,10 @@ class Checkout:
|
||||
return json.dumps([{"number": 12, "head": {"ref": "item-7", "label": "item-7", "sha": HEAD, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}] if self.open else [])
|
||||
if command == TEA_STATUS:
|
||||
return self.statuses.pop(0) if self.statuses else json.dumps({"total_count": 1, "state": "success", "statuses": [{"context": "CI / tests (pull_request)", "status": "success"}]})
|
||||
if command == GH_DECISION and self.unreadable is not None:
|
||||
return self.unreadable
|
||||
if command == GH_DECISION:
|
||||
return json.dumps({"reviewDecision": self.decisions.pop(0) if len(self.decisions) > 1 else self.decisions[0]})
|
||||
if command == TEA_BRANCH:
|
||||
return json.dumps({"enable_status_check": False})
|
||||
if command in (GH_SETTINGS, TEA_SETTINGS):
|
||||
@@ -67,7 +78,7 @@ class Checkout:
|
||||
|
||||
def acted(self) -> list[list[str]]:
|
||||
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
|
||||
reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS]
|
||||
reads = [GH_LIST, GH_DECISION, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS]
|
||||
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
|
||||
|
||||
|
||||
@@ -273,6 +284,85 @@ class Merge(unittest.TestCase):
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 60)
|
||||
|
||||
def requiring_approval(self, origin: str = GITHUB, *decisions: str) -> Checkout:
|
||||
"""A Checkout whose project config sets wait-for-approval, and which reports each of decisions in turn as the review decision."""
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(WAITS)] = "true\n"
|
||||
checkout.decisions = list(decisions) or ["APPROVED"]
|
||||
return checkout
|
||||
|
||||
def test_a_project_without_wait_for_approval_never_reads_the_review_decision(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.decisions = ["REVIEW_REQUIRED"]
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertNotIn(GH_DECISION, checkout.ran)
|
||||
|
||||
def test_an_approved_pull_request_merges_after_the_checks_and_the_approval(self):
|
||||
checkout = self.requiring_approval()
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(checkout.ran[-3:], [GH_CHECKS, GH_DECISION, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_it_waits_a_minute_at_a_time_while_the_branch_protection_still_wants_a_review(self):
|
||||
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED")
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(slept, [60, 60])
|
||||
|
||||
def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self):
|
||||
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED")
|
||||
slept: list[float] = []
|
||||
failed = merged(checkout, slept.append)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("90 minutes", failed.reason)
|
||||
self.assertEqual(sum(slept), 90 * 60)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_an_approval_that_comes_in_the_last_minute_still_merges(self):
|
||||
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 90, "APPROVED")
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 90 * 60)
|
||||
|
||||
def test_a_review_decision_it_cannot_read_or_does_not_know_leaves_it_unmerged(self):
|
||||
for answer in (Failure("gh pr view failed"), "not json", "[]", "{}", json.dumps({"reviewDecision": "DISMISSED"})):
|
||||
with self.subTest(answer):
|
||||
checkout = self.requiring_approval()
|
||||
checkout.unreadable = answer
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_requested_changes_leave_it_unmerged_without_waiting(self):
|
||||
checkout = self.requiring_approval(GITHUB, "CHANGES_REQUESTED")
|
||||
slept: list[float] = []
|
||||
failed = merged(checkout, slept.append)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("requested changes", failed.reason)
|
||||
self.assertEqual((slept, checkout.acted()), ([], []))
|
||||
|
||||
def test_a_branch_protection_that_asks_for_no_review_leaves_it_unmerged_naming_the_setting(self):
|
||||
for decision in ("", None):
|
||||
with self.subTest(decision):
|
||||
checkout = self.requiring_approval(GITHUB, decision)
|
||||
failed = step(["merge"], checkout)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("requires no review", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_gitea_with_wait_for_approval_leaves_it_unmerged_since_chunk_pr_reads_approvals_on_github_only(self):
|
||||
checkout = self.requiring_approval(GITEA)
|
||||
failed = step(["merge"], checkout)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("GitHub", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_a_config_it_cannot_read_or_that_prints_neither_true_nor_false_leaves_it_unmerged(self):
|
||||
for answer in (Failure("no config names the checkout"), "maybe\n", ""):
|
||||
with self.subTest(answer):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = answer
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def protected(self, *reads: list[tuple[str, str]]) -> Checkout:
|
||||
"""A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn."""
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
|
||||
@@ -71,6 +71,7 @@ from chunk_preflight.choices import forge_of, plan_name, planned, pulls_command,
|
||||
from chunk_preflight.facts import JOINING_DETAILS, render
|
||||
from project_config.main import located
|
||||
from release_plan.named_code import named_paths
|
||||
from record_store.stores import store
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# Each tool run in the item's worktree, {item} standing for the item's ID.
|
||||
@@ -125,7 +126,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Fai
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
outside = None if config.tracked("plan") else config.paths["plan"]
|
||||
held = default_plan(str(root), ref, config.place("plan"), config.place("changelog"))
|
||||
held = default_plan(str(root), ref, config.place("plan"), store(config, "changelog"))
|
||||
plan = planned(held.todo, held.cut, ref, outside)
|
||||
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
|
||||
# A `checkout:` path lands in the worktree the chunk works in.
|
||||
|
||||
@@ -12,6 +12,7 @@ from release_plan.release_standing import chunk_item, Cut, default_plan, Next, R
|
||||
from git_cli.git_repo import default_ref, git
|
||||
from deploy_release.deploy import deploy
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore
|
||||
from deploy_release import forge
|
||||
from chunk_preflight.choices import forge_of
|
||||
from release_plan.todo_table import items
|
||||
@@ -108,7 +109,8 @@ def same_origin(clone: str, checkout: str) -> Failure | None:
|
||||
|
||||
def ready_release(clone: str, ref: str) -> Release | Failure:
|
||||
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed and changes are unreleased."""
|
||||
plan = default_plan(clone, ref, "todo.md", "CHANGELOG.md")
|
||||
# No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan.
|
||||
plan = default_plan(clone, ref, "todo.md", FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"))
|
||||
found = items(plan.todo) if isinstance(plan.todo, str) else plan.todo
|
||||
if isinstance(found, Failure):
|
||||
return Failure(f"todo.md on {ref} cannot be read: {found.reason}")
|
||||
|
||||
@@ -4,18 +4,20 @@ from failure import Failure
|
||||
from git_cli.git_repo import file_at, full_history, git
|
||||
from review_rules.comprehension_history import HistoryChange
|
||||
from project_config.main import located
|
||||
from record_store.stores import store
|
||||
|
||||
|
||||
def history_changes(default: str, home: pathlib.Path) -> list[HistoryChange] | Failure:
|
||||
"""Each merged change on the default branch that touched the history, newest first. A Failure where the project's config puts the history outside the checkout, where no commit holds it."""
|
||||
"""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)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
history = config.tracked("comprehension-history")
|
||||
record = store(config, "comprehension-history")
|
||||
history = record.tracked
|
||||
if history is None:
|
||||
return Failure(f"larv-review doesn't support a comprehension history outside the checkout: no commit holds {config.paths['comprehension-history']}, so it cannot tell which commit was last measured")
|
||||
return Failure(f"larv-review doesn't support a comprehension history outside the checkout: no commit holds {record.label}, so it cannot tell which commit was last measured")
|
||||
# history names the file from the checkout's top, and git reads a path from the directory it runs in.
|
||||
root = str(config.top)
|
||||
commits = git("log", "--first-parent", "--format=%H", default, "--", history, cwd=root)
|
||||
|
||||
@@ -11,8 +11,8 @@ from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
|
||||
from larv_review.scoring import floor_step, means, under_floor
|
||||
from project_config.main import located
|
||||
from release_plan import plan_file
|
||||
from record_store.stores import RecordStore, store
|
||||
from larv_review.scoring_setup import removed_setup
|
||||
from text_files.file_writes import replace_file
|
||||
|
||||
Say = typing.Callable[[str], None]
|
||||
|
||||
@@ -109,7 +109,7 @@ def read_seats(path: pathlib.Path, paired: bool, home: pathlib.Path, now: float)
|
||||
return decided(text, now, paired, commit_exists, history)
|
||||
|
||||
|
||||
def decided(text: str, now: float, paired: bool, commit_known: typing.Callable[[str], bool], history: tuple[pathlib.Path, str]) -> tuple[Heading, SeatsFile] | Failure:
|
||||
def decided(text: str, now: float, paired: bool, commit_known: typing.Callable[[str], bool], history: tuple[RecordStore, str]) -> tuple[Heading, SeatsFile] | Failure:
|
||||
"""The heading the seats file's entry goes under, stamped with now, and the file parsed from text. Fails when text names a commit that commit_known denies, or when the history already holds an entry on what the seats read."""
|
||||
given = seats_file(text)
|
||||
if isinstance(given, Failure):
|
||||
@@ -120,7 +120,7 @@ def decided(text: str, now: float, paired: bool, commit_known: typing.Callable[[
|
||||
if unknown := [commit for commit in (named.commit, named.against) if commit and not commit_known(commit)]:
|
||||
return Failure(f"the seats file names {', '.join(unknown)}, which is no commit in this checkout")
|
||||
if recorded(history[1], given.read):
|
||||
return Failure(f"{history[0]} already holds an entry on {given.read}; record each ruling or run once")
|
||||
return Failure(f"{history[0].label} already holds an entry on {given.read}; record each ruling or run once")
|
||||
return named, given
|
||||
|
||||
|
||||
@@ -139,16 +139,14 @@ def read_agreement(home: pathlib.Path) -> str | Failure:
|
||||
return history if isinstance(history, Failure) else agreement_report(history[1])
|
||||
|
||||
|
||||
def history_file(home: pathlib.Path) -> tuple[pathlib.Path, str] | Failure:
|
||||
"""The project's comprehension history, where its config puts it, and its text, empty when the file is missing."""
|
||||
def history_file(home: pathlib.Path) -> 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."""
|
||||
config = located(None, home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
history = config.paths["comprehension-history"]
|
||||
try:
|
||||
return history, history.read_text(encoding="utf-8") if history.exists() else ""
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {history}: {failure}")
|
||||
history = store(config, "comprehension-history")
|
||||
text = history.read()
|
||||
return text if isinstance(text, Failure) else (history, text)
|
||||
|
||||
|
||||
def append(read: str, entry: str, home: pathlib.Path) -> str | Failure:
|
||||
@@ -158,11 +156,7 @@ def append(read: str, entry: str, home: pathlib.Path) -> str | Failure:
|
||||
return read_history
|
||||
history, text = read_history
|
||||
if recorded(text, read):
|
||||
return Failure(f"{history} already holds an entry on {read}; record each ruling or run once")
|
||||
try:
|
||||
history.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not create {history.parent}: {failure}")
|
||||
if unwritten := replace_file(history, appended(text, entry).encode()):
|
||||
return Failure(f"could not write {history}: {unwritten.reason}")
|
||||
return f"Appended to {history}."
|
||||
return Failure(f"{history.label} already holds an entry on {read}; record each ruling or run once")
|
||||
if unwritten := history.write(appended(text, entry)):
|
||||
return unwritten
|
||||
return f"Appended to {history.label}."
|
||||
|
||||
@@ -7,6 +7,7 @@ from failure import Failure
|
||||
from git_cli.git_repo import file_at, git
|
||||
from release_plan.todo_table import items, NoItemsTable
|
||||
from project_config.main import located
|
||||
from record_store.stores import store
|
||||
|
||||
|
||||
def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[str], None]) -> Failure | None:
|
||||
@@ -20,11 +21,12 @@ def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[st
|
||||
checkout = str(config.top)
|
||||
if not has_plan(config.paths["plan"]):
|
||||
return None
|
||||
# No commit holds a file outside the checkout. So the plan as the chunk found it cannot be read, nor the runs the branch recorded counted; the merge goes on, as `docs/decisions.md` → "project config: a tool that reads a file's commits …" says.
|
||||
plan, history = config.tracked("plan"), config.tracked("comprehension-history")
|
||||
# No commit holds a file outside the checkout, nor a record kept outside git. So the plan as the chunk found it cannot be read, nor the runs the branch recorded counted; the merge goes on, as `docs/decisions.md` → "project config: a tool that reads a file's commits …" says.
|
||||
record = store(config, "comprehension-history")
|
||||
plan, history = config.tracked("plan"), record.tracked
|
||||
if plan is None or history is None:
|
||||
name, setting = ("plan", "plan") if plan is None else ("comprehension history", "comprehension-history")
|
||||
warn(f"larv-review doesn't support a {name} outside the checkout, so it cannot tell whether the chunk owes a scoring run: {config.paths[setting]}")
|
||||
name, where = ("plan", str(config.paths["plan"])) if plan is None else ("comprehension history", record.label)
|
||||
warn(f"larv-review doesn't support a {name} outside the checkout, so it cannot tell whether the chunk owes a scoring run: {where}")
|
||||
return None
|
||||
base = git("merge-base", default, "HEAD", cwd=checkout)
|
||||
if isinstance(base, Failure):
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import pathlib
|
||||
|
||||
from release_plan.release_standing import Cut, default_plan, held_at, LastCut, next_release, Unknown
|
||||
from release_plan.release_standing import Cut, default_plan, LastCut, next_release, Unknown
|
||||
from failure import Failure
|
||||
from larv_review.scoring import is_floor_item
|
||||
from release_plan.todo_table import Item, items, NoItemsTable, renames
|
||||
from project_config.main import located
|
||||
from release_plan.goals_file import OPTED_OUT
|
||||
from release_plan.release import Release, version
|
||||
from record_store import stores
|
||||
from larv_review.unmeasured import unmeasured_cut
|
||||
|
||||
|
||||
@@ -69,12 +70,12 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
checkout = str(config.top)
|
||||
decisions = held_at(ref, config.place("decisions"), checkout)
|
||||
decisions = stores.held_at(ref, stores.store(config, "decisions"), checkout)
|
||||
if isinstance(decisions, Failure):
|
||||
return decisions
|
||||
if OPTED_OUT.search(decisions):
|
||||
return []
|
||||
held = default_plan(checkout, ref, config.place("plan"), config.place("changelog"))
|
||||
held = default_plan(checkout, ref, config.place("plan"), stores.store(config, "changelog"))
|
||||
before = held.todo
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
@@ -94,7 +95,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st
|
||||
landed_release = landed_towards(planned, held.cut)
|
||||
if isinstance(landed_release, Failure):
|
||||
return landed_release
|
||||
unmeasured = unmeasured_cut(ref, config.place("comprehension-history"), checkout)
|
||||
unmeasured = unmeasured_cut(ref, stores.store(config, "comprehension-history"), checkout)
|
||||
if isinstance(unmeasured, Failure):
|
||||
return unmeasured
|
||||
if ids is None:
|
||||
|
||||
@@ -7,6 +7,7 @@ from review_rules.round_titles import cap, round_counts
|
||||
from failure import Failure
|
||||
from chunk_preflight.choices import forge_of
|
||||
from larv_review.history_commands import history_file, places_report
|
||||
from record_store.stores import local_file, store
|
||||
from project_config.main import located
|
||||
from review_rules.review_folder import made_review_folder
|
||||
from deploy_release.forge import open_pull, runner
|
||||
@@ -33,7 +34,7 @@ class Launch:
|
||||
principles: pathlib.Path
|
||||
goals: pathlib.Path
|
||||
bare: bool
|
||||
# The project's `AGENTS.md` and its decision log, where its config puts them.
|
||||
# The project's `AGENTS.md`, where its config puts it, and a local file of its decision log.
|
||||
rules: pathlib.Path
|
||||
decisions: pathlib.Path
|
||||
|
||||
@@ -89,7 +90,10 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
|
||||
# A typo in the config would otherwise hand every reviewer an empty folder, and the review would run with no principles.
|
||||
if not principles.is_dir() or not any(principles.iterdir()):
|
||||
return Failure(f"{principles} is not a folder with a file in it; {config.folder / 'config.toml'} sets it as `principles`")
|
||||
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, config.paths["goals-and-audience"], starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], config.paths["decisions"])
|
||||
decisions = local_file(store(config, "decisions"), folder / "decisions.md")
|
||||
if isinstance(decisions, Failure):
|
||||
return decisions
|
||||
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, config.paths["goals-and-audience"], starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions)
|
||||
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)
|
||||
|
||||
@@ -11,6 +11,7 @@ from git_cli.git_repo import git
|
||||
from project_config.main import located
|
||||
from review_rules.review_folder import made_review_folder, review_folder
|
||||
from project_config.settings import ProjectConfig
|
||||
from record_store.stores import store
|
||||
|
||||
CLAUDE_MD = "CLAUDE.md"
|
||||
PANEL = pathlib.Path(__file__).resolve().parents[2] / "skills" / "comprehension-panel"
|
||||
@@ -79,8 +80,8 @@ def project_values(text: str, source: str) -> dict[str, str] | Failure:
|
||||
|
||||
|
||||
def forbidden(config: ProjectConfig) -> tuple[list[str], str]:
|
||||
"""The files no seat may open, as git names them, and the words that tell a seat so. A file the project's config puts outside the checkout is in neither: the scoring worktree doesn't hold it."""
|
||||
held = [(path, what) for setting, what in FORBIDDEN if (path := config.tracked(setting))]
|
||||
"""The files no seat may open, as git names them, and the words that tell a seat so. The plan or a record that no commit holds is in neither: the scoring worktree doesn't hold it."""
|
||||
held = [(path, what) for setting, what in FORBIDDEN if (path := config.tracked(setting) if setting == "plan" else store(config, setting).tracked)]
|
||||
files = [path for path, _ in held]
|
||||
return files, f"{listed(files, 'or')} ({listed([what for _, what in held], 'and')})" if held else "any record of a past panel"
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ from test_env import isolated_env
|
||||
from release_plan.todo_table import Item, items, NoItemsTable
|
||||
from release_plan.release_standing import LastCut
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from record_store.fakes import MemoryStore
|
||||
from larv_review.seats import score_line, scores, seats_file, SeatsFile
|
||||
from larv_review.owed import shortfall
|
||||
|
||||
@@ -322,7 +323,7 @@ class Agreement(unittest.TestCase):
|
||||
|
||||
class Decided(unittest.TestCase):
|
||||
AT = 1_700_000_000.0
|
||||
HISTORY = (pathlib.Path("history.md"), "")
|
||||
HISTORY = (MemoryStore(label="history.md"), "")
|
||||
|
||||
def test_heads_the_entry_with_the_time_it_is_given(self):
|
||||
decided_on = decided("PR #2 at abcdef1\n", self.AT, False, lambda commit: True, self.HISTORY)
|
||||
@@ -336,7 +337,7 @@ class Decided(unittest.TestCase):
|
||||
|
||||
def test_fails_where_the_history_already_holds_an_entry_on_the_file(self):
|
||||
held = scored("2023-11-14T22:13:20Z", "PR #2", "abcdef1", "7", "7")
|
||||
failed = decided("PR #2 at abcdef1\n", self.AT, False, lambda commit: True, (pathlib.Path("history.md"), appended("", held)))
|
||||
failed = decided("PR #2 at abcdef1\n", self.AT, False, lambda commit: True, (MemoryStore(label="history.md"), appended("", held)))
|
||||
self.assertEqual(failed, Failure("history.md already holds an entry on PR #2 at abcdef1; record each ruling or run once"))
|
||||
|
||||
def test_fails_on_a_seats_file_that_does_not_parse_without_asking_about_a_commit(self):
|
||||
@@ -810,6 +811,16 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.assertIn("already holds an entry on", again.stderr)
|
||||
self.assertEqual([entry.ruling for entry in entries((self.checkout / "docs" / "comprehension-history.md").read_text())], ["better"])
|
||||
|
||||
def test_leaves_a_history_it_cannot_read_as_it_is(self):
|
||||
history = self.checkout / "docs" / "comprehension-history.md"
|
||||
history.parent.mkdir(exist_ok=True)
|
||||
history.write_bytes(b"# Comprehension history\n\xff\n")
|
||||
votes_file = self.seats_file(f"PR #2 at {self.start}, against {self.start}\n\nMid A: {said('better')}\n\nInherited architect: {said('better')}\n", "votes.md")
|
||||
ran = self.run_tool("record-ruling", votes_file)
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn(f"cannot read {history}: not UTF-8 on line 2", ran.stderr)
|
||||
self.assertEqual(history.read_bytes(), b"# Comprehension history\n\xff\n")
|
||||
|
||||
def test_records_a_scoring_run_with_its_means(self):
|
||||
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
|
||||
seats = "".join(f"\n{seat}: {line}\n\n- `bin/a.py:3` `f`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
|
||||
@@ -857,7 +868,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.addCleanup(docs.chmod, 0o700)
|
||||
for ran in (self.run_tool("record-ruling", votes_file), self.record_sevens()):
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""), ran.stderr)
|
||||
self.assertIn("could not write", ran.stderr)
|
||||
self.assertIn("cannot write", ran.stderr)
|
||||
|
||||
def record_sevens(self):
|
||||
"""Run record-scoring for item 1 on a scores file in which every seat scores 7 throughout."""
|
||||
@@ -1190,6 +1201,14 @@ class LarvReviewTool(unittest.TestCase):
|
||||
ran = self.run_tool("reviewer-header", "prose")
|
||||
self.assertEqual(ran.stdout.splitlines()[-1], f"Principles: read {self.checkout}/AGENTS.md first, for the project principles and the decision titles.")
|
||||
|
||||
def test_reviewer_header_names_the_decision_log_where_the_project_keeps_no_agents_md(self):
|
||||
(self.checkout / "docs").mkdir(exist_ok=True)
|
||||
(self.checkout / "docs" / "decisions.md").write_text("1. A principle.\n\n# Decisions\n")
|
||||
(self.checkout / "CHANGELOG.md").write_text("# Changelog\n")
|
||||
self.bare("prose-reviewer")
|
||||
ran = self.run_tool("reviewer-header", "prose")
|
||||
self.assertEqual(ran.stdout.splitlines()[-1], f"Principles: read {self.checkout}/docs/decisions.md first, up to `# Decisions`, for the project principles and the decision titles.")
|
||||
|
||||
def bare(self, agent):
|
||||
(self.checkout.parent / ".claude" / "agents").mkdir(parents=True, exist_ok=True)
|
||||
(self.checkout.parent / ".claude" / "agents" / f"{agent}.md").write_text("---\nomitClaudeMd: true\n---\n")
|
||||
|
||||
@@ -3,12 +3,11 @@ import datetime
|
||||
from review_rules.comprehension_history import entries
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git
|
||||
from release_plan.release_standing import held_at
|
||||
from project_config.settings import Place
|
||||
from record_store.stores import held_at, RecordStore
|
||||
|
||||
|
||||
def unmeasured_cut(default: str, history: Place, checkout: str) -> str | None | Failure:
|
||||
"""Whether the default branch's newest release was cut unmeasured, as `v0.7.0, cut with no scoring run since v0.6.0`. It was where no scoring run in the default branch's history, the file at history, is newer than the second-newest v* tag. None where the branch holds fewer than two such tags, or a run since the earlier one.
|
||||
def unmeasured_cut(default: str, history: RecordStore, checkout: str) -> str | None | Failure:
|
||||
"""Whether the default branch's newest release was cut unmeasured, as `v0.7.0, cut with no scoring run since v0.6.0`. It was where no scoring run in the default branch's comprehension history is newer than the second-newest v* tag. None where the branch holds fewer than two such tags, or a run since the earlier one.
|
||||
|
||||
The reason ends once a run follows the earlier tag, so it asks only after a release was cut with none; it lets the chunk that finds the gap record the run.
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ from loop_claude.cycle import prompts
|
||||
from model_routing.route import Route, route_from
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.session import session_open, transcript_file
|
||||
from record_store.stores import store
|
||||
|
||||
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
|
||||
ORIGIN_TIMEOUT = 60
|
||||
@@ -79,7 +80,7 @@ def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
|
||||
if config.tracked("plan") is None:
|
||||
say(UNSEEN_RELEASES, loop.effects)
|
||||
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
|
||||
return ref if isinstance(ref, Failure) else default_plan(loop.root, ref, config.place("plan"), config.place("changelog"), loop.effects.git)
|
||||
return ref if isinstance(ref, Failure) else default_plan(loop.root, ref, config.place("plan"), store(config, "changelog"), loop.effects.git)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
|
||||
|
||||
@@ -3,6 +3,7 @@ import pathlib
|
||||
from failure import Failure
|
||||
from project_config.main import located
|
||||
from loop_claude.project.text_file import read_utf8
|
||||
from record_store.stores import store
|
||||
|
||||
# The records the judge reads beside the premises: these project files, then the human's rules below.
|
||||
RECORD_FILES = ("AGENTS.md", "docs/decisions.md")
|
||||
@@ -14,22 +15,29 @@ HUMAN_RULE_DIRS = ("rules", "skills/larv-review/standards")
|
||||
HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", *(f"~/.claude/{folder}/" for folder in HUMAN_RULE_DIRS))
|
||||
|
||||
|
||||
def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str | Failure:
|
||||
"""The project's record files, then the human's rules for every project, CLAUDE.md first, each headed by its name; a file that does not exist is left out.
|
||||
CONSEQUENCE = "the judge cannot read the records"
|
||||
|
||||
The record files are read where the config under home of root's project puts them, and headed by their names in RECORD_FILES wherever that is."""
|
||||
|
||||
def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str | Failure:
|
||||
"""The project's `AGENTS.md` and decision log, then the human's rules for every project, CLAUDE.md first, each headed by its name; one that does not exist, or is empty, is left out.
|
||||
|
||||
`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."""
|
||||
config = located(root, home)
|
||||
if isinstance(config, Failure):
|
||||
return Failure(f"{config.reason} - the judge cannot read the records.")
|
||||
return Failure(f"{config.reason} - {CONSEQUENCE}.")
|
||||
rules = [claude_dir / HUMAN_RULES_FILE] + [rule for folder in HUMAN_RULE_DIRS for rule in sorted((claude_dir / folder).glob("*.md"))]
|
||||
sources = [(str(config.paths[setting].parent), config.paths[setting].name, name) for setting, name in zip(RECORD_SETTINGS, RECORD_FILES)]
|
||||
sources += [(str(rule.parent), rule.name, f"~/.claude/{rule.relative_to(claude_dir)}") for rule in rules]
|
||||
decisions = store(config, RECORD_SETTINGS[1]).read()
|
||||
texts = [(RECORD_FILES[0], file_text(config.paths[RECORD_SETTINGS[0]])), (RECORD_FILES[1], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)]
|
||||
texts += [(f"~/.claude/{rule.relative_to(claude_dir)}", file_text(rule)) for rule in rules]
|
||||
records = []
|
||||
for folder, name, heading in sources:
|
||||
if not pathlib.Path(folder, name).exists():
|
||||
continue
|
||||
text = read_utf8(folder, name, "the judge cannot read the records")
|
||||
for heading, text in texts:
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
records.append(f"From {heading}:\n{text.strip()}")
|
||||
if text:
|
||||
records.append(f"From {heading}:\n{text.strip()}")
|
||||
return "\n\n".join(records)
|
||||
|
||||
|
||||
def file_text(path: pathlib.Path) -> str | Failure:
|
||||
"""path's text, empty where no such file exists."""
|
||||
return read_utf8(str(path.parent), path.name, CONSEQUENCE) if path.exists() else ""
|
||||
|
||||
@@ -1133,6 +1133,17 @@ class RouteSources(unittest.TestCase):
|
||||
chunk_start.fetched_todo(a_loop(FakeEffects(git=git).effects(), root=root, paths=paths.paths_from(home)))
|
||||
self.assertEqual(stderr.getvalue(), f"{STAMP} {said}" if said else "")
|
||||
|
||||
def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self):
|
||||
def git(*args, **options):
|
||||
answers = {"remote": "origin\n", "symbolic-ref": "origin/main\n", "show": f"what {args[-1]} holds\n"}
|
||||
return answers.get(args[0], "1\n")
|
||||
|
||||
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])))
|
||||
self.assertEqual(held.cut.changelog, "what origin/main:CHANGELOG.md holds\n")
|
||||
|
||||
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))
|
||||
@@ -1468,7 +1479,7 @@ class Records(unittest.TestCase):
|
||||
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."))
|
||||
pathlib.Path(root, "docs", "decisions.md").mkdir(parents=True)
|
||||
self.assertEqual(records.read_records(root, claude_md.parents[1], claude_md.parent), Failure(f"decisions.md in {root}/docs: 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."))
|
||||
|
||||
|
||||
+11
-10
@@ -38,6 +38,7 @@ import sys
|
||||
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score, tracked_places
|
||||
from review_rules.comprehension_history import entries, Entry
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore, RecordStore, store
|
||||
from git_cli.git_repo import git
|
||||
from metric_bench.python_units import measured, python_units, Unit
|
||||
from project_config.main import project
|
||||
@@ -64,25 +65,25 @@ def main(argv: list[str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def read_history(given: pathlib.Path | None) -> tuple[str, pathlib.Path, str] | Failure:
|
||||
"""The checkout that holds the history, the history's path and its text."""
|
||||
def read_history(given: pathlib.Path | None) -> tuple[str, str, str] | Failure:
|
||||
"""The checkout that holds the history, the history's label for a message, and the history's text. The history is the file given, else the one in the store the project's config names."""
|
||||
if given and not given.parent.is_dir():
|
||||
return Failure(f"could not read {given}: no folder {given.parent}")
|
||||
found = git("rev-parse", "--show-toplevel", cwd=str(given.parent) if given else None)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
if given:
|
||||
history = given
|
||||
history: RecordStore = FileStore(given, None)
|
||||
elif isinstance(config := project(), Failure):
|
||||
return config
|
||||
else:
|
||||
history = config.paths["comprehension-history"]
|
||||
if not given and not history.exists():
|
||||
return Failure(f"no comprehension history at {history}; larv-review writes one at a project's first paired ruling or scoring run")
|
||||
try:
|
||||
return found.strip(), history, history.read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {history}: {failure}")
|
||||
history = store(config, "comprehension-history")
|
||||
text = history.read()
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
if not text:
|
||||
return Failure(f"no comprehension history at {history.label}; larv-review writes one at a project's first paired ruling or scoring run")
|
||||
return found.strip(), history.label, text
|
||||
|
||||
|
||||
def scored_runs(found: list[Entry]) -> list[Entry]:
|
||||
|
||||
@@ -232,7 +232,7 @@ class BlackBox(unittest.TestCase):
|
||||
|
||||
def test_exits_1_naming_a_history_it_cannot_read_and_unknown_arguments(self):
|
||||
top = self.project("")
|
||||
self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr)
|
||||
self.assertIn(f"no comprehension history at {top}/missing.md", self.run_tool(top, str(pathlib.Path(top, "missing.md"))).stderr)
|
||||
pathlib.Path(top, "docs", "comprehension-history.md").unlink()
|
||||
self.assertIn("no comprehension history at", self.run_tool(top).stderr)
|
||||
self.assertIn("could not read", self.run_tool(top, str(pathlib.Path(top, "gone", "x.md"))).stderr)
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from project_record import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:]))
|
||||
@@ -6,7 +6,7 @@ Run inside a checkout, or a worktree of one. It finds the config that names the
|
||||
~/.claude-projects/<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.
|
||||
|
||||
The config is TOML. `checkout` names the project's main checkout, and every other setting is a path:
|
||||
The config is TOML. `checkout` names the project's main checkout, and every other setting but `wait-for-approval` is a path:
|
||||
"checkout:<path>" inside the checkout, "folder:<path>" inside the config's own folder, or one that
|
||||
starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own file.
|
||||
|
||||
@@ -21,19 +21,24 @@ starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own fil
|
||||
goals-and-audience = "folder:goals.md"
|
||||
principles = "folder:principles"
|
||||
|
||||
`env-file` is the one optional setting: the file of KEY=value credentials the project's tools read,
|
||||
`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
|
||||
a tool that needs one fails naming the setting. It is printed with the others only where it is set.
|
||||
|
||||
`wait-for-approval` is the other optional setting, true or false: whether `chunk-pr merge` waits for a human's
|
||||
approval of the pull request, as its branch protection requires on GitHub, before it merges. Left out, it is
|
||||
false. `project-config wait-for-approval` prints true or false; the full listing shows the setting only where
|
||||
it is true.
|
||||
|
||||
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
|
||||
setting, names an unknown one or misspells a path, and where `env-file` is asked for and not set.
|
||||
No setting has a default.
|
||||
setting, names an unknown one, misspells a path or sets `wait-for-approval` to anything but true or
|
||||
false, and where `env-file` is asked for and not set. No path setting has a default.
|
||||
"""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from project_config.settings import CONFIG, ENV_FILE, load, ProjectConfig, SETTINGS
|
||||
from project_config.settings import CONFIG, ENV_FILE, load, ProjectConfig, SETTINGS, WAIT_FOR_APPROVAL
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git, Git
|
||||
|
||||
@@ -42,18 +47,22 @@ def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if len(argv) > 1 or (argv and argv[0] not in (*SETTINGS, ENV_FILE)):
|
||||
print(f"usage: project-config [<setting>], where <setting> is one of {', '.join((*SETTINGS, ENV_FILE))}", file=sys.stderr)
|
||||
if len(argv) > 1 or (argv and argv[0] not in (*SETTINGS, ENV_FILE, WAIT_FOR_APPROVAL)):
|
||||
print(f"usage: project-config [<setting>], where <setting> is one of {', '.join((*SETTINGS, ENV_FILE, WAIT_FOR_APPROVAL))}", file=sys.stderr)
|
||||
return 1
|
||||
config = located(None, pathlib.Path.home())
|
||||
if isinstance(config, Failure):
|
||||
print(config.reason, file=sys.stderr)
|
||||
return 1
|
||||
if argv == [WAIT_FOR_APPROVAL]:
|
||||
print("true" if config.wait_for_approval else "false")
|
||||
return 0
|
||||
paths = {**config.paths, **({ENV_FILE: config.env_file} if config.env_file else {})}
|
||||
if argv and argv[0] not in paths:
|
||||
print(f"{config.folder / CONFIG} sets no `{ENV_FILE}`", file=sys.stderr)
|
||||
return 1
|
||||
print(paths[argv[0]] if argv else "\n".join(f"{name}: {path}" for name, path in paths.items()))
|
||||
listed = [f"{name}: {path}" for name, path in paths.items()] + ([f"{WAIT_FOR_APPROVAL}: true"] if config.wait_for_approval else [])
|
||||
print(paths[argv[0]] if argv else "\n".join(listed))
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""A project's settings, read from the one config that names its checkout: `~/.claude-projects/<key>/config.toml`.
|
||||
|
||||
No 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."""
|
||||
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 pathlib
|
||||
import tomllib
|
||||
@@ -13,8 +13,10 @@ CONFIG = "config.toml"
|
||||
SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles")
|
||||
# They also picked a prefix over bare relative paths: each line says its own place, and a relative path with no prefix fails instead of landing somewhere by default.
|
||||
SPELLING = '"checkout:<path>" for a path in the checkout, "folder:<path>" for one in the config\'s folder, or a path that starts with / or ~/'
|
||||
# The one setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's.
|
||||
# A path setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's.
|
||||
ENV_FILE = "env-file"
|
||||
# The optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out.
|
||||
WAIT_FOR_APPROVAL = "wait-for-approval"
|
||||
OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials"
|
||||
|
||||
# Where a project keeps a file, for a tool that reads it at a commit: a path from the checkout's top, as git names it; or, outside the checkout, the file itself, which the tool reads as it stands, since the checkout's commits hold no version of it.
|
||||
@@ -30,6 +32,7 @@ class ProjectConfig:
|
||||
paths: dict[str, pathlib.Path]
|
||||
# The config's `env-file`, or None where it sets none.
|
||||
env_file: pathlib.Path | None = None
|
||||
wait_for_approval: bool = False
|
||||
|
||||
def tracked(self, setting: str) -> str | None:
|
||||
"""setting's path from top, as git names a file in a commit; None where the config puts it outside the checkout, whose commits hold no version of it."""
|
||||
@@ -61,15 +64,17 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
paths = {name: placed(values[name], top, file.parent, home) for name in SETTINGS if name in values}
|
||||
env_file = anywhere(values.get(ENV_FILE), home)
|
||||
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
|
||||
waits = values.get(WAIT_FOR_APPROVAL, False)
|
||||
faults = [
|
||||
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
|
||||
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, ENV_FILE)),
|
||||
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, ENV_FILE, WAIT_FOR_APPROVAL)),
|
||||
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None),
|
||||
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
|
||||
*([f"`{WAIT_FOR_APPROVAL}` is {waits!r}, not true or false"] if not isinstance(waits, bool) else []),
|
||||
]
|
||||
if faults:
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {ENV_FILE}.")
|
||||
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file)
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {ENV_FILE} and {WAIT_FOR_APPROVAL}.")
|
||||
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True)
|
||||
|
||||
|
||||
def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool:
|
||||
|
||||
@@ -189,9 +189,30 @@ class LoadTest(ConfigCase):
|
||||
assert isinstance(found, Failure), found
|
||||
self.assertIn("`env-file`", 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)
|
||||
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)
|
||||
assert isinstance(found, ProjectConfig), found
|
||||
self.assertEqual(found.wait_for_approval, expected)
|
||||
|
||||
def test_a_wait_for_approval_that_is_not_true_or_false_fails_naming_it(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
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)
|
||||
assert isinstance(found, Failure), found
|
||||
self.assertIn(f"`wait-for-approval` is {eval(spelled)!r}, not true or false", found.reason)
|
||||
|
||||
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')
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally env-file.")
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally env-file and wait-for-approval.")
|
||||
|
||||
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
@@ -275,6 +296,15 @@ class ToolTest(ConfigCase):
|
||||
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")
|
||||
|
||||
def test_prints_true_or_false_for_wait_for_approval_and_lists_it_only_where_the_config_sets_it(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
left_out = self.run_tool("wait-for-approval")
|
||||
self.assertEqual((left_out.returncode, left_out.stdout, left_out.stderr), (0, "false\n", ""))
|
||||
self.assertNotIn("wait-for-approval", self.run_tool().stdout)
|
||||
(folder / "config.toml").write_text(CLIENT + "wait-for-approval = true\n")
|
||||
self.assertEqual(self.run_tool("wait-for-approval").stdout, "true\n")
|
||||
self.assertEqual(self.run_tool().stdout.splitlines()[-1], "wait-for-approval: true")
|
||||
|
||||
def test_fails_on_stderr(self) -> None:
|
||||
cases = {"no config": ((), "no config names the checkout"), "an unknown setting": (("readme",), "usage:"), "two arguments": (("plan", "changelog"), "usage:")}
|
||||
for case, (args, said) in cases.items():
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Open one of a project's records as a file to read and edit, and save the edit.
|
||||
|
||||
usage: project-record open <record>
|
||||
project-record save <record>
|
||||
|
||||
Run inside a checkout, or a worktree of one. <record> is one of decisions, score-anchors,
|
||||
comprehension-history, reading-cost and changelog, each kept where the project's config names it.
|
||||
|
||||
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>/, written afresh with the record as it
|
||||
stands, so open it again before each edit. A record that doesn't exist yet has no file at the path:
|
||||
create it there.
|
||||
|
||||
save stores the file's text in the record, and prints one line saying so. Where the record is kept
|
||||
as a file there is nothing left to store, and it says that. Run it after every edit, so the same
|
||||
steps work wherever a project keeps the record.
|
||||
|
||||
Exit 2 on bad arguments, and 1, saying why, on any other failure.
|
||||
"""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore, local_file, RECORDS, RecordStore, store, stored
|
||||
from project_config.main import located
|
||||
|
||||
# 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.
|
||||
COPIES = ".local/state/project-record"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if len(argv) != 2 or argv[0] not in COMMANDS or argv[1] not in RECORDS:
|
||||
print(f"usage: project-record {'|'.join(COMMANDS)} <record>, where <record> is one of {', '.join(RECORDS)}", file=sys.stderr)
|
||||
return 2
|
||||
home = pathlib.Path.home()
|
||||
config = located(None, home)
|
||||
done = config if isinstance(config, Failure) else act(argv[0], store(config, argv[1]), home / COPIES / config.key / f"{argv[1]}.md")
|
||||
if isinstance(done, Failure):
|
||||
print(f"project-record: {done.reason}", file=sys.stderr)
|
||||
return 1
|
||||
print(done)
|
||||
return 0
|
||||
|
||||
|
||||
def act(command: str, record: RecordStore, copy: pathlib.Path) -> str | Failure:
|
||||
"""What command, one of COMMANDS, prints for record. copy is where a record kept outside files gets its file."""
|
||||
if command == "open":
|
||||
opened = local_file(record, copy)
|
||||
return opened if isinstance(opened, Failure) else str(opened)
|
||||
if unstored := stored(record, copy):
|
||||
return unstored
|
||||
return f"{record.path} is the record itself, so nothing is left to store." if isinstance(record, FileStore) else f"Stored {copy} in {record.label}."
|
||||
@@ -0,0 +1,75 @@
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.test_project_config import configured
|
||||
from failure import Failure
|
||||
from project_record import main
|
||||
from record_store.fakes import MemoryStore
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-record"
|
||||
|
||||
|
||||
class Act(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.copy = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()), "acme", "decisions.md")
|
||||
|
||||
def test_open_prints_only_the_path_of_a_copy_holding_the_record(self):
|
||||
self.assertEqual(main.act("open", MemoryStore("# Decisions\n"), self.copy), str(self.copy))
|
||||
self.assertEqual(self.copy.read_text(), "# Decisions\n")
|
||||
|
||||
def test_save_stores_the_edited_copy_and_says_where(self):
|
||||
record = MemoryStore("# Decisions\n", label="the wiki page Decisions")
|
||||
main.act("open", record, self.copy)
|
||||
self.copy.write_text("# Decisions\n\n- New\n")
|
||||
self.assertEqual(main.act("save", record, self.copy), f"Stored {self.copy} in the wiki page Decisions.")
|
||||
self.assertEqual(record.text, "# Decisions\n\n- New\n")
|
||||
|
||||
def test_a_record_that_fails_is_a_failure(self):
|
||||
self.assertEqual(main.act("open", MemoryStore(fails="the wiki is down"), self.copy), Failure("the wiki is down"))
|
||||
record = MemoryStore("# Decisions\n")
|
||||
main.act("open", record, self.copy)
|
||||
record.fails = "the wiki is down"
|
||||
self.assertEqual(main.act("save", record, self.copy), Failure("the wiki is down"))
|
||||
|
||||
|
||||
class BlackBox(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.top = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())).resolve()
|
||||
configured(self, self.top)
|
||||
|
||||
def run_tool(self, *args: str) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.top, env=dict(os.environ), 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")
|
||||
self.assertEqual((opened.returncode, opened.stdout, opened.stderr), (0, f"{self.top}/docs/decisions.md\n", ""))
|
||||
saved = self.run_tool("save", "decisions")
|
||||
self.assertEqual((saved.returncode, saved.stdout, saved.stderr), (0, f"{self.top}/docs/decisions.md is the record itself, so nothing is left to store.\n", ""))
|
||||
self.assertFalse((pathlib.Path(os.environ["HOME"]) / ".local").exists(), "a file record gets no copy")
|
||||
|
||||
def test_exits_2_with_the_usage_on_an_unknown_command_or_record(self):
|
||||
for args in ([], ["open"], ["open", "plan"], ["close", "decisions"], ["open", "decisions", "changelog"]):
|
||||
ran = self.run_tool(*args)
|
||||
self.assertEqual((ran.returncode, ran.stdout), (2, ""), args)
|
||||
self.assertIn("usage: project-record open|save <record>, where <record> is one of decisions, score-anchors, comprehension-history, reading-cost, changelog", ran.stderr)
|
||||
|
||||
def test_exits_1_saying_why_where_no_config_names_the_checkout(self):
|
||||
(pathlib.Path(os.environ["HOME"]) / ".claude-projects" / 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)
|
||||
|
||||
def test_help_prints_the_usage(self):
|
||||
ran = self.run_tool("--help")
|
||||
self.assertEqual(ran.returncode, 0)
|
||||
self.assertIn("usage: project-record open <record>", ran.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -31,11 +31,11 @@ import time
|
||||
from reading_cost.measure import Checkout, measure, Reading
|
||||
from failure import Failure
|
||||
from reading_cost.figures import figure, merged, readings_of, RESET, trend, unheld
|
||||
from record_store.stores import FileStore, RecordStore, store
|
||||
from transcript_archive.read import finished_chunks, read_threads
|
||||
from git_cli.git_repo import git
|
||||
from project_config.main import project
|
||||
from transcript_archive.location import project_archive
|
||||
from text_files.file_writes import replace_file
|
||||
from text_files.utc_stamp import utc
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -61,19 +61,21 @@ def main(argv: list[str]) -> int:
|
||||
config = project()
|
||||
if not given and isinstance(config, Failure):
|
||||
return failed(config)
|
||||
record = pathlib.Path(given[0]) if given or isinstance(config, Failure) else config.paths["reading-cost"]
|
||||
record: RecordStore = FileStore(pathlib.Path(given[0]), None) if given or isinstance(config, Failure) else store(config, "reading-cost")
|
||||
updated = update(record, archive, checkout, str(home), utc(time.time()) if reset else None)
|
||||
if isinstance(updated, Failure):
|
||||
return failed(updated)
|
||||
print(f"Appended {updated.appended} reading-cost figure{'' if updated.appended == 1 else 's'} from {archive}{' and a reset' if reset else ''} to {record}.")
|
||||
print(f"Appended {updated.appended} reading-cost figure{'' if updated.appended == 1 else 's'} from {archive}{' and a reset' if reset else ''} to {record.label}.")
|
||||
print(trend(updated.readings))
|
||||
return 0
|
||||
|
||||
|
||||
def update(record: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> Updated | Failure:
|
||||
text = read_record(record)
|
||||
def update(record: RecordStore, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> Updated | Failure:
|
||||
text = record.read()
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
# An empty record starts with its title.
|
||||
text = text or "# Reading cost\n"
|
||||
figures = new_figures(text, archive, checkout, home)
|
||||
if isinstance(figures, Failure):
|
||||
return figures
|
||||
@@ -82,7 +84,7 @@ def update(record: pathlib.Path, archive: pathlib.Path, checkout: Checkout, home
|
||||
readings = readings_of(text)
|
||||
if isinstance(readings, Failure):
|
||||
return readings
|
||||
if marks and (unwritten := write_record(record, text)):
|
||||
if marks and (unwritten := record.write(text)):
|
||||
return unwritten
|
||||
return Updated(len(figures), readings)
|
||||
|
||||
@@ -101,15 +103,6 @@ def new_figures(record: str, archive: pathlib.Path, checkout: Checkout, home: st
|
||||
return figures
|
||||
|
||||
|
||||
def write_record(record: pathlib.Path, text: str) -> Failure | None:
|
||||
try:
|
||||
record.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not write {record}: {failure.strerror}")
|
||||
unwritten = replace_file(record, text.encode())
|
||||
return Failure(f"could not write {record}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def failed(failure: Failure) -> int:
|
||||
print(failure.reason, file=sys.stderr)
|
||||
return 1
|
||||
@@ -129,8 +122,3 @@ def located() -> Checkout | Failure:
|
||||
return Checkout(top, str(pathlib.Path(common).parent), frozenset(filter(None, listed.split("\0"))))
|
||||
|
||||
|
||||
def read_record(record: pathlib.Path) -> str | Failure:
|
||||
try:
|
||||
return record.read_text(encoding="utf-8") if record.exists() else "# Reading cost\n"
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {record}: {failure}")
|
||||
|
||||
@@ -19,6 +19,7 @@ from failure import Failure
|
||||
from reading_cost import figures, main, measure
|
||||
from transcript_archive.read import finished_chunks, FinishedChunk
|
||||
from test_env import isolated_env
|
||||
from record_store.fakes import MemoryStore
|
||||
from transcript_archive import outcomes
|
||||
from transcript_archive.location import project_archive
|
||||
from reading_cost.shell_reads import Reads, shell_reads
|
||||
@@ -216,5 +217,16 @@ class Located(unittest.TestCase):
|
||||
self.assertIsInstance(main.located(), Failure)
|
||||
|
||||
|
||||
class Update(unittest.TestCase):
|
||||
def test_fails_where_the_record_refuses_the_write(self):
|
||||
class Unwritable(MemoryStore):
|
||||
def write(self, text: str) -> Failure | None:
|
||||
return Failure("the wiki is down")
|
||||
|
||||
archive = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
updated = main.update(Unwritable("# Reading cost\n"), archive, Checkout("/c/p", "/c/p", frozenset()), "/h", "2026-11-14T00:00:00Z")
|
||||
self.assertEqual(updated, Failure("the wiki is down"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""What every record backend must hold, as tests. A backend's test case inherits RecordStoreContract and unittest.TestCase, and builds its store in new_store."""
|
||||
import typing
|
||||
|
||||
from record_store.stores import RecordStore
|
||||
|
||||
|
||||
class RecordStoreContract:
|
||||
"""Runs against the store new_store returns: one that holds no record yet."""
|
||||
assertEqual: typing.Callable[..., None]
|
||||
assertIsNone: typing.Callable[..., None]
|
||||
assertTrue: typing.Callable[..., None]
|
||||
|
||||
def new_store(self) -> RecordStore:
|
||||
raise NotImplementedError
|
||||
|
||||
def test_a_record_never_written_reads_empty(self) -> None:
|
||||
self.assertEqual(self.new_store().read(), "")
|
||||
|
||||
def test_reads_back_what_it_wrote_to_the_character(self) -> None:
|
||||
store = self.new_store()
|
||||
text = "# Decisions\n\n- Å, 🔴 and a | pipe\n\n\n"
|
||||
self.assertIsNone(store.write(text))
|
||||
self.assertEqual(store.read(), text)
|
||||
|
||||
def test_a_write_replaces_the_whole_record(self) -> None:
|
||||
store = self.new_store()
|
||||
store.write("first\nsecond\n")
|
||||
self.assertIsNone(store.write("third\n"))
|
||||
self.assertEqual(store.read(), "third\n")
|
||||
|
||||
def test_names_itself_for_a_message(self) -> None:
|
||||
self.assertTrue(self.new_store().label.strip())
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Record stores for tests, held to record_store.contract like every backend."""
|
||||
import dataclasses
|
||||
|
||||
from failure import Failure
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class MemoryStore:
|
||||
"""A record held in memory, as a backend outside git holds one. Set fails to make every read and write fail with that reason."""
|
||||
text: str = ""
|
||||
label: str = "the record in memory"
|
||||
tracked: str | None = None
|
||||
fails: str | None = None
|
||||
|
||||
def read(self) -> str | Failure:
|
||||
return Failure(self.fails) if self.fails else self.text
|
||||
|
||||
def write(self, text: str) -> Failure | None:
|
||||
if self.fails:
|
||||
return Failure(self.fails)
|
||||
self.text = text
|
||||
return None
|
||||
@@ -0,0 +1,100 @@
|
||||
"""The one way a tool reads or writes a project's records: through the store its config names for each.
|
||||
|
||||
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, the only backend so far."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, git, Git
|
||||
from project_config.settings import ProjectConfig
|
||||
from text_files.file_writes import replace_file
|
||||
|
||||
# The settings in a project's config that each name a record.
|
||||
RECORDS = ("decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog")
|
||||
|
||||
|
||||
class RecordStore(typing.Protocol):
|
||||
"""One record, as text. record_store.contract holds every backend to the same behaviour."""
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
"""What a message calls the record, such as its path."""
|
||||
|
||||
@property
|
||||
def tracked(self) -> str | None:
|
||||
"""The record's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a wiki page."""
|
||||
|
||||
def read(self) -> str | Failure:
|
||||
"""The record's text as it stands, empty where it doesn't exist yet."""
|
||||
|
||||
def write(self, text: str) -> Failure | None:
|
||||
"""Replaces the record's whole text, creating the record where it doesn't exist yet."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class FileStore:
|
||||
"""A record kept as a markdown file at path."""
|
||||
path: pathlib.Path
|
||||
tracked: str | None
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return str(self.path)
|
||||
|
||||
def read(self) -> str | Failure:
|
||||
try:
|
||||
return self.path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return ""
|
||||
except UnicodeDecodeError as failure:
|
||||
return Failure(f"cannot read {self.path}: not UTF-8 on line {failure.object[: failure.start].count(b'\n') + 1}")
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot read {self.path}: {failure.strerror}")
|
||||
|
||||
def write(self, text: str) -> Failure | None:
|
||||
try:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot write {self.path}: {failure.strerror}")
|
||||
unwritten = replace_file(self.path, text.encode("utf-8"))
|
||||
return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def store(config: ProjectConfig, record: str) -> RecordStore:
|
||||
"""The store config names for record, one of RECORDS."""
|
||||
if record not in RECORDS:
|
||||
raise ValueError(f"{record} is not a record; the records are {', '.join(RECORDS)}")
|
||||
return FileStore(config.paths[record], config.tracked(record))
|
||||
|
||||
|
||||
def held_at(revision: str, record: RecordStore, cwd: str, run: Git = git) -> str | Failure:
|
||||
"""record's text at revision, read in the checkout at cwd, where its commits hold the record; else as it stands. Empty where there is no such record."""
|
||||
return record.read() if record.tracked is None else file_at(revision, record.tracked, cwd, run)
|
||||
|
||||
|
||||
def local_file(record: RecordStore, copy: pathlib.Path) -> pathlib.Path | Failure:
|
||||
"""A file holding record's text, for an agent, which reads and edits files: the record's own file where a file is its backend, else copy, written with the text as it stands. Neither exists where the record doesn't yet. `stored` puts an edited copy back."""
|
||||
if isinstance(record, FileStore):
|
||||
return record.path
|
||||
text = record.read()
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
if text:
|
||||
return FileStore(copy, None).write(text) or copy
|
||||
try:
|
||||
# An earlier copy would read as the record's text, and `stored` would put it back.
|
||||
copy.unlink(missing_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot remove {copy}: {failure.strerror}")
|
||||
return copy
|
||||
|
||||
|
||||
def stored(record: RecordStore, copy: pathlib.Path) -> Failure | None:
|
||||
"""Stores in record the text of copy, the file `local_file` gave for it. Where that is the record's own file, the edit is already the record."""
|
||||
if isinstance(record, FileStore):
|
||||
return None
|
||||
text = FileStore(copy, None).read()
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
return record.write(text) if text else Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}")
|
||||
@@ -0,0 +1,175 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from record_store.fakes import MemoryStore
|
||||
from project_config.settings import ProjectConfig
|
||||
from record_store.contract import RecordStoreContract
|
||||
from record_store import stores
|
||||
|
||||
|
||||
class MemoryStoreContract(RecordStoreContract, unittest.TestCase):
|
||||
def new_store(self) -> stores.RecordStore:
|
||||
return MemoryStore()
|
||||
|
||||
|
||||
class FileStoreContract(RecordStoreContract, unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
|
||||
def new_store(self) -> stores.RecordStore:
|
||||
return stores.FileStore(self.folder / "docs" / "decisions.md", None)
|
||||
|
||||
|
||||
class FileStoreInACheckoutContract(FileStoreContract):
|
||||
def new_store(self) -> stores.RecordStore:
|
||||
return stores.FileStore(self.folder / "docs" / "decisions.md", "docs/decisions.md")
|
||||
|
||||
|
||||
class FileStore(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
|
||||
def test_names_its_path(self):
|
||||
self.assertEqual(stores.FileStore(self.folder / "CHANGELOG.md", "CHANGELOG.md").label, str(self.folder / "CHANGELOG.md"))
|
||||
|
||||
def test_a_file_that_is_not_utf8_is_a_failure_naming_it(self):
|
||||
path = self.folder / "decisions.md"
|
||||
path.write_bytes(b"# Decisions\n\xff\xfe")
|
||||
self.assertEqual(stores.FileStore(path, None).read(), Failure(f"cannot read {path}: not UTF-8 on line 2"))
|
||||
|
||||
def test_a_folder_where_the_file_goes_is_a_failure_naming_it_once(self):
|
||||
path = self.folder / "decisions.md"
|
||||
path.mkdir()
|
||||
read = stores.FileStore(path, None).read()
|
||||
self.assertIsInstance(read, Failure)
|
||||
self.assertTrue(read.reason.startswith(f"cannot read {path}: "))
|
||||
self.assertEqual(read.reason.count(str(path)), 1)
|
||||
|
||||
def test_a_write_that_fails_is_a_failure_naming_it(self):
|
||||
(self.folder / "docs").write_text("a file where the folder goes")
|
||||
path = self.folder / "docs" / "decisions.md"
|
||||
written = stores.FileStore(path, None).write("text\n")
|
||||
self.assertIsInstance(written, Failure)
|
||||
self.assertIn(f"cannot write {path}: ", written.reason)
|
||||
|
||||
def test_a_write_makes_each_folder_the_file_lacks(self):
|
||||
path = self.folder / "records" / "acme" / "decisions.md"
|
||||
self.assertIsNone(stores.FileStore(path, None).write("text\n"))
|
||||
self.assertEqual(path.read_text(), "text\n")
|
||||
|
||||
def test_a_write_onto_a_folder_is_a_failure_naming_it(self):
|
||||
path = self.folder / "decisions.md"
|
||||
path.mkdir()
|
||||
written = stores.FileStore(path, None).write("text\n")
|
||||
self.assertIsInstance(written, Failure)
|
||||
self.assertIn(f"cannot write {path}: ", written.reason)
|
||||
|
||||
def test_a_file_with_windows_line_ends_reads_with_plain_ones(self):
|
||||
path = self.folder / "CHANGELOG.md"
|
||||
path.write_bytes(b"# Changelog\r\n\r\n## Unreleased\r\n")
|
||||
self.assertEqual(stores.FileStore(path, None).read(), "# Changelog\n\n## Unreleased\n")
|
||||
|
||||
|
||||
class HeldAt(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.top = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
self.git("init", "-q", "-b", "main")
|
||||
(self.top / "CHANGELOG.md").write_text("committed\n")
|
||||
self.git("add", "-A")
|
||||
self.git("-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-qm", "first")
|
||||
(self.top / "CHANGELOG.md").write_text("as it stands\n")
|
||||
|
||||
def git(self, *args: str) -> None:
|
||||
subprocess.run(["git", *args], cwd=self.top, check=True, capture_output=True)
|
||||
|
||||
def test_a_record_in_the_checkout_reads_as_the_revision_holds_it(self):
|
||||
store = stores.FileStore(self.top / "CHANGELOG.md", "CHANGELOG.md")
|
||||
self.assertEqual(stores.held_at("main", store, str(self.top)), "committed\n")
|
||||
|
||||
def test_a_record_the_revision_lacks_reads_empty(self):
|
||||
store = stores.FileStore(self.top / "docs" / "decisions.md", "docs/decisions.md")
|
||||
self.assertEqual(stores.held_at("main", store, str(self.top)), "")
|
||||
|
||||
def test_a_record_outside_the_checkout_reads_as_it_stands(self):
|
||||
store = stores.FileStore(self.top / "CHANGELOG.md", None)
|
||||
self.assertEqual(stores.held_at("no-such-revision", store, "/nowhere", run=self.refuse), "as it stands\n")
|
||||
|
||||
def refuse(self, *args: str, **options: object) -> str:
|
||||
self.fail(f"git {' '.join(args)} ran for a record no commit holds")
|
||||
|
||||
|
||||
class LocalFile(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
|
||||
def test_a_file_record_is_its_own_local_file_and_no_copy_is_made(self):
|
||||
record = stores.FileStore(self.folder / "decisions.md", None)
|
||||
record.write("kept\n")
|
||||
self.assertEqual(stores.local_file(record, self.folder / "copies" / "decisions.md"), self.folder / "decisions.md")
|
||||
self.assertIsNone(stores.stored(record, self.folder / "copies" / "decisions.md"))
|
||||
self.assertEqual((record.read(), (self.folder / "copies").exists()), ("kept\n", False))
|
||||
|
||||
def test_a_record_outside_files_is_copied_and_an_edited_copy_is_stored_back(self):
|
||||
record, copy = MemoryStore("# Decisions\n"), self.folder / "copies" / "decisions.md"
|
||||
self.assertEqual(stores.local_file(record, copy), copy)
|
||||
self.assertEqual(copy.read_text(), "# Decisions\n")
|
||||
copy.write_text("# Decisions\n\n- One more\n")
|
||||
self.assertIsNone(stores.stored(record, copy))
|
||||
self.assertEqual(record.text, "# Decisions\n\n- One more\n")
|
||||
|
||||
def test_a_record_that_does_not_exist_yet_gets_no_copy(self):
|
||||
copy = self.folder / "decisions.md"
|
||||
self.assertEqual((stores.local_file(MemoryStore(), copy), copy.exists()), (copy, False))
|
||||
|
||||
def test_a_record_that_is_empty_now_loses_the_copy_made_earlier(self):
|
||||
record, copy = MemoryStore("# Decisions\n"), self.folder / "decisions.md"
|
||||
stores.local_file(record, copy)
|
||||
record.text = ""
|
||||
self.assertEqual((stores.local_file(record, copy), copy.exists()), (copy, False))
|
||||
|
||||
def test_a_copy_that_cannot_be_written_is_a_failure_naming_it(self):
|
||||
(self.folder / "copies").write_text("a file where the folder goes")
|
||||
copy = self.folder / "copies" / "decisions.md"
|
||||
opened = stores.local_file(MemoryStore("# Decisions\n"), copy)
|
||||
self.assertIsInstance(opened, Failure)
|
||||
self.assertIn(f"cannot write {copy}: ", opened.reason)
|
||||
|
||||
def test_storing_a_missing_copy_fails_and_leaves_the_record(self):
|
||||
record = MemoryStore("kept\n")
|
||||
self.assertIn("is missing or empty", stores.stored(record, self.folder / "decisions.md").reason)
|
||||
self.assertEqual(record.text, "kept\n")
|
||||
|
||||
def test_a_record_that_cannot_be_read_or_written_fails_with_its_reason(self):
|
||||
record, copy = MemoryStore(fails="the wiki is down"), self.folder / "decisions.md"
|
||||
self.assertEqual(stores.local_file(record, copy), Failure("the wiki is down"))
|
||||
copy.write_text("edited\n")
|
||||
self.assertEqual(stores.stored(record, copy), Failure("the wiki is down"))
|
||||
|
||||
|
||||
class Store(unittest.TestCase):
|
||||
def config(self, top: pathlib.Path, folder: pathlib.Path) -> ProjectConfig:
|
||||
paths = {record: top / f"{record}.md" for record in stores.RECORDS} | {"changelog": folder / "CHANGELOG.md", "plan": top / "todo.md"}
|
||||
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")
|
||||
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))
|
||||
|
||||
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")
|
||||
self.assertEqual(str(refused.exception), "plan is not a record; the records are decisions, score-anchors, comprehension-history, reading-cost, changelog")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,6 +5,7 @@ from failure import Failure
|
||||
from project_config.settings import ProjectConfig
|
||||
from release_plan.ranking import rank, Ranked
|
||||
from text_files.file_writes import replace_file
|
||||
from record_store.stores import store
|
||||
|
||||
|
||||
def rank_file(todo: pathlib.Path, config: ProjectConfig) -> Ranked | Failure:
|
||||
@@ -38,11 +39,11 @@ def check_failures(todo: pathlib.Path, config: ProjectConfig) -> list[str]:
|
||||
|
||||
|
||||
def read_all(todo: pathlib.Path, config: ProjectConfig) -> tuple[str, str, str, str] | Failure:
|
||||
"""todo, the plan, then the goals file, the decision log and the comprehension history that config names. The last two are empty when missing; a missing plan or goals file is a Failure."""
|
||||
"""todo, the plan, then the goals file config names, and the decision log and the comprehension history, each from the store config names for it. The last two are empty when missing; a missing plan or goals file is a Failure."""
|
||||
plan = read(todo, "every project keeps a todo.md, and rank_todo.py --help shows one")
|
||||
if isinstance(plan, Failure):
|
||||
return plan
|
||||
goals_text, decisions, history = read(config.paths["goals-and-audience"], "rank_todo.py weighs goals from the file the project's config names as goals-and-audience"), read(config.paths["decisions"], None), read(config.paths["comprehension-history"], None)
|
||||
goals_text, decisions, history = read(config.paths["goals-and-audience"], "rank_todo.py weighs goals from the file the project's config names as goals-and-audience"), store(config, "decisions").read(), store(config, "comprehension-history").read()
|
||||
if isinstance(goals_text, Failure):
|
||||
return goals_text
|
||||
if isinstance(decisions, Failure):
|
||||
@@ -52,12 +53,12 @@ def read_all(todo: pathlib.Path, config: ProjectConfig) -> tuple[str, str, str,
|
||||
return plan, goals_text, decisions, history
|
||||
|
||||
|
||||
def read(path: pathlib.Path, missing: str | None) -> str | Failure:
|
||||
"""path's text; where it is missing, a Failure saying missing, or "" where missing is None."""
|
||||
def read(path: pathlib.Path, missing: str) -> str | Failure:
|
||||
"""path's text; where it is missing, a Failure saying missing."""
|
||||
try:
|
||||
return path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return Failure(f"{path}: not found; {missing}") if missing else ""
|
||||
return Failure(f"{path}: not found; {missing}")
|
||||
except OSError as failure:
|
||||
return Failure(f"{path}: {failure.strerror}")
|
||||
except UnicodeDecodeError:
|
||||
|
||||
@@ -8,6 +8,7 @@ from failure import Failure
|
||||
from release_plan.todo_table import Item, items, next_item, renames
|
||||
from project_config.settings import Place
|
||||
from text_files.markdown_text import sections
|
||||
from record_store import stores
|
||||
|
||||
# The version a branch with no v* tag and no dated CHANGELOG.md heading counts as cut: below every release, 0.0.0 included, so that every release todo.md names comes after it.
|
||||
BEFORE_FIRST_RELEASE = (-1, 0, 0)
|
||||
@@ -94,10 +95,10 @@ class DefaultPlan:
|
||||
cut: LastCut
|
||||
|
||||
|
||||
def default_plan(root: str, ref: str, plan: Place, changelog: Place, run: Git = git) -> DefaultPlan:
|
||||
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root through run. plan and changelog are where the project's config puts todo.md and CHANGELOG.md."""
|
||||
def default_plan(root: str, ref: str, plan: Place, changelog: stores.RecordStore, run: Git = git) -> DefaultPlan:
|
||||
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root through run. plan is where the project's config puts todo.md, and changelog the store it names for the changelog."""
|
||||
tag = newest_tag(root, merged_into=ref, run=run)
|
||||
changes = held_at(ref, changelog, root, run)
|
||||
changes = stores.held_at(ref, changelog, root, run)
|
||||
after = dated_cut(tag, changes)
|
||||
since = tag if after is None else heading_commit(after, ref, changelog, root, run)
|
||||
commits = since if isinstance(since, Failure) else commits_since(since, ref, root, run)
|
||||
@@ -117,12 +118,12 @@ def held_at(revision: str, place: Place, cwd: str, run: Git = git) -> str | Fail
|
||||
return Failure(f"cannot read {place}: {failure}")
|
||||
|
||||
|
||||
def heading_commit(release: Release, ref: str, changelog: Place, cwd: str, run: Git = git) -> str | None | Failure:
|
||||
"""The oldest commit on ref that added release's dated heading to CHANGELOG.md, which a branch with no tag counts the unreleased commits from; None where git finds none, as for a changelog outside the checkout."""
|
||||
if isinstance(changelog, pathlib.Path):
|
||||
def heading_commit(release: Release, ref: str, changelog: stores.RecordStore, cwd: str, run: Git = git) -> str | None | Failure:
|
||||
"""The oldest commit on ref that added release's dated heading to the changelog, which a branch with no tag counts the unreleased commits from; None where git finds none, as for a changelog no commit holds."""
|
||||
if changelog.tracked is None:
|
||||
return None
|
||||
# -G matches the heading line itself, so a changelog entry that quotes the heading doesn't count.
|
||||
added = run("log", "--reverse", "--format=%H", "-G", dated_heading_pattern(release), ref, "--", changelog, cwd=cwd)
|
||||
added = run("log", "--reverse", "--format=%H", "-G", dated_heading_pattern(release), ref, "--", changelog.tracked, cwd=cwd)
|
||||
return added if isinstance(added, Failure) else next(iter(added.split()), None)
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore
|
||||
from test_env import isolated_env
|
||||
from release_plan import release_standing
|
||||
from release_plan import todo_table
|
||||
@@ -17,6 +18,11 @@ HEADER = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I |
|
||||
ROW = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
|
||||
|
||||
|
||||
def changelog_of(repo: str) -> FileStore:
|
||||
"""The changelog at its usual path in the checkout at repo."""
|
||||
return FileStore(pathlib.Path(repo, "CHANGELOG.md"), "CHANGELOG.md")
|
||||
|
||||
|
||||
def naming(named: set[tuple[int, int, int]] | Failure) -> list[str] | Failure:
|
||||
"""LastCut.todos_since holding one todo.md text that files an item under each release in named."""
|
||||
if isinstance(named, Failure):
|
||||
@@ -157,7 +163,7 @@ class ChunkItem(unittest.TestCase):
|
||||
self.assertIs(release_standing.release_reviewed("v0.1.0", "main", repo), True)
|
||||
self.assertIs(release_standing.release_reviewed(None, "main", repo), True)
|
||||
self.assertIsInstance(release_standing.release_reviewed("v9.9.9", "main", repo), Failure)
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.reviewed, True)
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut.reviewed, True)
|
||||
|
||||
def test_counts_no_release_review_of_a_release_cut_under_a_dated_heading_on_a_branch_with_no_tag(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
@@ -168,13 +174,13 @@ class ChunkItem(unittest.TestCase):
|
||||
pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.0.1 - 2026-10-03\n")
|
||||
run("add", "CHANGELOG.md")
|
||||
run("commit", "-q", "-m", "Cut 0.0.1")
|
||||
self.assertIs(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.reviewed, False, "that review reviewed 0.0.1, which is cut")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.commits, 0, "no commit follows the one that cut 0.0.1")
|
||||
self.assertEqual(release_standing.chunk_item([], release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut), release_standing.Unplanned(None))
|
||||
self.assertIs(release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut.reviewed, False, "that review reviewed 0.0.1, which is cut")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut.commits, 0, "no commit follows the one that cut 0.0.1")
|
||||
self.assertEqual(release_standing.chunk_item([], release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut), release_standing.Unplanned(None))
|
||||
run("commit", "-q", "--allow-empty", "-m", "Ship item 2")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.commits, 1)
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut.commits, 1)
|
||||
run("commit", "-q", "--allow-empty", "-m", "Release review of 0.1.0")
|
||||
self.assertIs(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.reviewed, True)
|
||||
self.assertIs(release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut.reviewed, True)
|
||||
|
||||
def test_counts_from_the_commit_on_the_named_branch_that_first_added_the_dated_heading_to_changelog_md(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
@@ -193,7 +199,28 @@ class ChunkItem(unittest.TestCase):
|
||||
run("commit", "-q", "--allow-empty", "-m", "Ship item 2")
|
||||
run("checkout", "-q", "-b", "side")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Side work")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut.commits, 2, "the commits after Cut 0.0.1 on main")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut.commits, 2, "the commits after Cut 0.0.1 on main")
|
||||
|
||||
def test_reads_the_changelog_and_its_cut_on_the_named_branch_whatever_is_checked_out(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
|
||||
run = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=repo, env=isolated_env(), text=True)
|
||||
changelog = pathlib.Path(repo, "CHANGELOG.md")
|
||||
run("init", "-q", "-b", "main")
|
||||
changelog.write_text("# Changelog\n\n## Unreleased\n")
|
||||
run("add", ".")
|
||||
run("commit", "-q", "-m", "Start")
|
||||
run("checkout", "-q", "-b", "side")
|
||||
changelog.write_text("# Changelog\n\n## 0.0.1 - 2026-10-02\n\n- Side.\n")
|
||||
run("commit", "-q", "-am", "Cut 0.0.1 on the side")
|
||||
run("checkout", "-q", "main")
|
||||
changelog.write_text("# Changelog\n\n## 0.0.1 - 2026-10-03\n")
|
||||
run("commit", "-q", "-am", "Cut 0.0.1")
|
||||
run("commit", "-q", "--allow-empty", "-m", "Ship item 2")
|
||||
run("checkout", "-q", "side")
|
||||
changelog.write_text("# Changelog\n\nAn edit nobody committed.\n")
|
||||
cut = release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut
|
||||
self.assertEqual((cut.changelog, cut.commits), ("# Changelog\n\n## 0.0.1 - 2026-10-03\n", 1), "main's changelog, and the commit after Cut 0.0.1 on main")
|
||||
|
||||
def test_takes_the_tag_over_a_dated_heading_and_counts_every_commit_without_either(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
@@ -203,12 +230,12 @@ class ChunkItem(unittest.TestCase):
|
||||
pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.2.0"))
|
||||
run("add", "todo.md")
|
||||
run("commit", "-q", "-m", "Plan")
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md").cut, release_standing.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False))
|
||||
self.assertEqual(release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo)).cut, release_standing.LastCut(None, "", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False))
|
||||
run("tag", "v0.1.0")
|
||||
pathlib.Path(repo, "CHANGELOG.md").write_text("# Changelog\n\n## 0.2.0 - 2026-10-03\n")
|
||||
run("add", "CHANGELOG.md")
|
||||
run("commit", "-q", "-m", "Date 0.2.0")
|
||||
held = release_standing.default_plan(repo, "main", "todo.md", "CHANGELOG.md")
|
||||
held = release_standing.default_plan(repo, "main", "todo.md", changelog_of(repo))
|
||||
self.assertEqual(held.todo, HEADER + ROW.format(id=1, release="0.2.0"))
|
||||
self.assertEqual(held.cut, release_standing.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 2, 0)), held.cut), release_standing.Next((0, 2, 0), one((0, 2, 0))))
|
||||
@@ -221,16 +248,16 @@ class ChunkItem(unittest.TestCase):
|
||||
pathlib.Path(repo, "todo.md").write_text(HEADER + ROW.format(id=1, release="0.9.0"))
|
||||
run("add", "todo.md")
|
||||
run("commit", "-q", "-m", "A todo.md the project's owners keep")
|
||||
held = release_standing.default_plan(repo, "main", folder / "todo.md", folder / "CHANGELOG.md")
|
||||
held = release_standing.default_plan(repo, "main", folder / "todo.md", FileStore(folder / "CHANGELOG.md", None))
|
||||
self.assertEqual((held.todo, held.cut), ("", release_standing.LastCut(None, "", 1, [""], False)), "neither file exists yet")
|
||||
plan = HEADER + ROW.format(id=2, release="0.2.0")
|
||||
(folder / "todo.md").write_text(plan)
|
||||
(folder / "CHANGELOG.md").write_text("# Changelog\n\n## 0.1.0 - 2026-10-03\n")
|
||||
held = release_standing.default_plan(repo, "main", folder / "todo.md", folder / "CHANGELOG.md")
|
||||
held = release_standing.default_plan(repo, "main", folder / "todo.md", FileStore(folder / "CHANGELOG.md", None))
|
||||
self.assertEqual(held.todo, plan)
|
||||
self.assertEqual(held.cut, release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 1, [plan], False))
|
||||
(folder / "todo.md").write_bytes(b"\xff")
|
||||
unreadable = release_standing.default_plan(repo, "main", folder / "todo.md", "CHANGELOG.md")
|
||||
unreadable = release_standing.default_plan(repo, "main", folder / "todo.md", changelog_of(repo))
|
||||
assert isinstance(unreadable.todo, Failure) and isinstance(unreadable.cut.todos_since, Failure), unreadable
|
||||
self.assertTrue(unreadable.todo.reason.startswith(f"cannot read {folder}/todo.md: "), unreadable.todo.reason)
|
||||
self.assertEqual(unreadable.cut.todos_since, unreadable.todo)
|
||||
@@ -247,7 +274,7 @@ class ChunkItem(unittest.TestCase):
|
||||
run("commit", "-q", "-m", "Cut 0.1.0")
|
||||
# Only this git knows where the checkout is, so a read that goes round it fails.
|
||||
there = lambda *args, cwd: release_standing.git(*args, cwd=repo)
|
||||
held = release_standing.default_plan("/nowhere", "main", "todo.md", "CHANGELOG.md", there)
|
||||
held = release_standing.default_plan("/nowhere", "main", "todo.md", changelog_of("/nowhere"), there)
|
||||
self.assertEqual(held, release_standing.DefaultPlan(plan, release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 0, [plan], False)))
|
||||
|
||||
def test_counts_the_changes_unreleased_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self):
|
||||
|
||||
+12
-11
@@ -13,9 +13,9 @@ from git_cli.git_repo import default_ref
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply
|
||||
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 project_config.settings import ProjectConfig
|
||||
from review_rules.review_folder import REPORTS, review_folder
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.entries import structured_output
|
||||
@@ -111,7 +111,7 @@ def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: path
|
||||
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.clone, home, bare)
|
||||
launched = launch(found.reviewer, rung, prompt, found.root, copies, home, bare)
|
||||
if isinstance(launched, Failure):
|
||||
return launched
|
||||
reply = claude_reply(effects.claude, launched[0], copies.clone, launched[1], "claude")
|
||||
@@ -120,8 +120,8 @@ 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, clone: str, home: pathlib.Path, bare: bool) -> tuple[list[str], str] | Failure:
|
||||
"""claude's arguments and prompt for reviewer on rung, in clone, a copy of the project whose checkout is checkout. Where bare, it starts without CLAUDE.md, and the prompt holds what the SubagentStart hook and the header's last line hand such a reviewer."""
|
||||
def launch(reviewer: str, rung: Rung, prompt: str, checkout: str, copies: Copies, home: pathlib.Path, bare: bool) -> 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 bare, it starts without CLAUDE.md, and the prompt holds what the SubagentStart hook and the header's last line hand such a reviewer."""
|
||||
args = ["--agent", reviewer, *rung.flags()]
|
||||
if not bare:
|
||||
return args, prompt
|
||||
@@ -131,16 +131,17 @@ def launch(reviewer: str, rung: Rung, prompt: str, checkout: str, clone: str, ho
|
||||
config = located(checkout, home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
rules, decisions = (cloned(config, setting, clone) for setting in ("working-rules", "decisions"))
|
||||
record = store(config, "decisions")
|
||||
# No commit holds a decision log outside the checkout, so the reviewer reads it as it stands today.
|
||||
decisions = local_file(record, pathlib.Path(copies.reports, "decisions.md")) if record.tracked is None else pathlib.Path(copies.clone, record.tracked)
|
||||
if isinstance(decisions, Failure):
|
||||
return decisions
|
||||
tracked = config.tracked("working-rules")
|
||||
# Likewise for an `AGENTS.md` outside the checkout.
|
||||
rules = config.paths["working-rules"] if tracked is None else pathlib.Path(copies.clone, tracked)
|
||||
return [*args, *NO_CLAUDE_MD], "\n".join([f"{context}\n\n{prompt}", *([principles] if (principles := principles_line(rules, decisions)) else [])])
|
||||
|
||||
|
||||
def cloned(config: ProjectConfig, setting: str, clone: str) -> pathlib.Path:
|
||||
"""Where the reviewer in clone reads the file the config names as setting: the clone's copy of a file in the checkout, else the file as it stands today, which has no copy at the reviewed commit."""
|
||||
tracked = config.tracked(setting)
|
||||
return config.paths[setting] if tracked is None else pathlib.Path(clone, tracked)
|
||||
|
||||
|
||||
def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None:
|
||||
"""Copies into reports each report written to folder after found's chunk began and before its round did."""
|
||||
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
|
||||
|
||||
@@ -122,17 +122,18 @@ class Launch(unittest.TestCase):
|
||||
(self.home / ".claude").mkdir()
|
||||
(self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
|
||||
self.clone = self.home / "clone"
|
||||
self.reports = self.home / "reports"
|
||||
self.clone.mkdir()
|
||||
self.checkout = self.home / "proj"
|
||||
self.checkout.mkdir()
|
||||
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), str(self.clone), self.home, False), (["--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, False), (["--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), str(self.clone), self.home, True)
|
||||
args, prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, True)
|
||||
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.")
|
||||
|
||||
@@ -140,16 +141,26 @@ 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), str(self.clone), self.home, True)[1]
|
||||
prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, True)[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):
|
||||
places = {"checkout:docs/decisions.md": self.clone / "docs" / "decisions.md", "folder:decisions.md": self.config.parent / "decisions.md"}
|
||||
for setting, decisions in places.items():
|
||||
with self.subTest(setting):
|
||||
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, True)[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), str(self.clone), self.home, True).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, True).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), str(self.clone), self.home, True), Failure)
|
||||
self.assertIsInstance(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.checkout), replay.Copies(str(self.clone), str(self.reports)), self.home, True), Failure)
|
||||
|
||||
|
||||
class Match(unittest.TestCase):
|
||||
|
||||
@@ -104,6 +104,7 @@ from release_plan.named_code import named_files
|
||||
from project_config.main import project
|
||||
from transcript_archive.location import project_archive
|
||||
from score_outcomes.reversals import reversal_lines
|
||||
from record_store.stores import store
|
||||
|
||||
# The scores score-outcomes takes, in order.
|
||||
GIVEN = ("L", "E", "I", "S")
|
||||
@@ -167,17 +168,12 @@ def failed(failure: Failure) -> int:
|
||||
|
||||
|
||||
def read_anchors() -> Anchors | Failure:
|
||||
"""The project's anchors as they stand where its config puts them, so a branch that edits them shows its edit; none where it has no such file."""
|
||||
"""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 = project()
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
anchors = config.paths["score-anchors"]
|
||||
try:
|
||||
return parse_anchors(anchors.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"cannot read {anchors}: {failure}")
|
||||
text = store(config, "score-anchors").read()
|
||||
return text if isinstance(text, Failure) else parse_anchors(text)
|
||||
|
||||
|
||||
def read_reversals() -> list[str] | Failure:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import contextlib
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
@@ -9,6 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from score_outcomes.anchors import anchor_lines, parse_anchors
|
||||
from branch_chunks.cut import BranchChunk, Landing
|
||||
from project_config.test_project_config import configured, write_config
|
||||
from failure import Failure
|
||||
from score_outcomes.results import file_lines, NamedCode, nearest, rank_correlation, render, report, Result, results_of
|
||||
from review_rules.round_titles import Findings
|
||||
@@ -16,9 +18,8 @@ from test_env import isolated_env
|
||||
from release_plan.todo_table import Item
|
||||
from transcript_archive import outcomes
|
||||
from transcript_archive.location import project_archive
|
||||
from score_outcomes.main import report_text
|
||||
from score_outcomes.main import read_anchors, report_text
|
||||
from score_outcomes.reversals import reversal_lines
|
||||
from project_config.test_project_config import write_config
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
|
||||
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
@@ -549,5 +550,16 @@ class Reversals(unittest.TestCase):
|
||||
self.assertTrue(found.reason.startswith(f"could not read the archive file {archive / 'kept' / 'b.outcomes.md'}: "), found.reason)
|
||||
|
||||
|
||||
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()))
|
||||
configured(self, checkout)
|
||||
self.enterContext(contextlib.chdir(checkout))
|
||||
anchors = checkout.resolve() / "docs" / "score-anchors.md"
|
||||
anchors.parent.mkdir()
|
||||
anchors.write_bytes(b"\xff")
|
||||
self.assertEqual(read_anchors(), Failure(f"cannot read {anchors}: not UTF-8 on line 1"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -55,7 +55,7 @@ class Main(unittest.TestCase):
|
||||
self.assertEqual(self.run_main("--check"), (0, ""))
|
||||
self.assertEqual(pathlib.Path(temp, "todo.md").read_text(), "the project owners' own notes\n")
|
||||
(folder / "decisions.md").write_bytes(b"\xff")
|
||||
self.assertEqual(self.run_main(), (1, f"{folder}/decisions.md: not UTF-8\n"))
|
||||
self.assertEqual(self.run_main(), (1, f"cannot read {folder}/decisions.md: not UTF-8 on line 1\n"))
|
||||
|
||||
def test_refuses_a_file_that_is_not_the_plan_the_config_names_and_a_checkout_no_config_names(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
|
||||
+12
-13
@@ -18,7 +18,7 @@ It prints `Filed item <ID> in <todo.md's path>.` It doesn't write anything where
|
||||
finish removes the item's row and its detail. With --changelog it adds the bullet first under
|
||||
CHANGELOG.md's ## Unreleased, or a ## heading that says unreleased, creating the section, or the
|
||||
file, where missing. It refuses where that section holds ### subsections: add the bullet by hand.
|
||||
Where CHANGELOG.md exists, finish needs --changelog or --no-changelog, so no bullet is left out by
|
||||
Where CHANGELOG.md holds text, finish needs --changelog or --no-changelog, so no bullet is left out by
|
||||
mistake. It prints `Finished item <ID> in <todo.md's path>.` It doesn't write anything while docs/decisions.md cites the item.
|
||||
|
||||
show reads only todo.md. It prints `From <todo.md's path>:`, then the items table's header and divider, item <ID>'s row, and its detail
|
||||
@@ -39,6 +39,7 @@ from failure import Failure
|
||||
from project_config.main import located
|
||||
from release_plan import plan_file, ranking
|
||||
from project_config.settings import ProjectConfig
|
||||
from record_store.stores import store
|
||||
|
||||
# Each score flag, as --l or --L, and the column it fills.
|
||||
LETTERS = ("L", "E", "I", "S")
|
||||
@@ -118,14 +119,14 @@ def add(args: argparse.Namespace, config: ProjectConfig, stdin: typing.TextIO) -
|
||||
|
||||
|
||||
def finish(args: argparse.Namespace, config: ProjectConfig) -> str | Failure:
|
||||
todo, changelog = config.paths["plan"], config.paths["changelog"]
|
||||
todo, changelog = config.paths["plan"], store(config, "changelog")
|
||||
texts = finish_texts(args, config)
|
||||
if isinstance(texts, Failure):
|
||||
return Failure(f"not finished: {texts.reason}")
|
||||
ranked, news = texts
|
||||
if unwritten := plan_file.write(todo, ranked.text):
|
||||
return Failure(f"not finished: {unwritten.reason}")
|
||||
if news is not None and (unwritten := plan_file.write(changelog, news)):
|
||||
if news is not None and (unwritten := changelog.write(news)):
|
||||
return Failure(f"{unwritten.reason}; todo.md no longer holds item {args.id}, so add its bullet by hand")
|
||||
for line in plan_file.report_lines(todo, ranked):
|
||||
print(line, file=sys.stderr)
|
||||
@@ -134,9 +135,12 @@ def finish(args: argparse.Namespace, config: ProjectConfig) -> str | Failure:
|
||||
|
||||
def finish_texts(args: argparse.Namespace, config: ProjectConfig) -> tuple[ranking.Ranked, str | None] | Failure:
|
||||
"""What finish writes: the plan ranked without item args.id, and the changelog's new text, None where finish leaves it as is."""
|
||||
todo, changelog = config.paths["plan"], config.paths["changelog"]
|
||||
if changelog.exists() and args.changelog is None and not args.no_changelog:
|
||||
return Failure(f"{changelog} exists; pass --changelog <bullet>, or --no-changelog where the repo doesn't publish anything")
|
||||
todo, changelog = config.paths["plan"], store(config, "changelog")
|
||||
news = changelog.read()
|
||||
if isinstance(news, Failure):
|
||||
return news
|
||||
if news and args.changelog is None and not args.no_changelog:
|
||||
return Failure(f"{changelog.label} exists; pass --changelog <bullet>, or --no-changelog where the repo doesn't publish anything")
|
||||
texts = plan_file.read_all(todo, config)
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
@@ -148,11 +152,6 @@ def finish_texts(args: argparse.Namespace, config: ProjectConfig) -> tuple[ranki
|
||||
return ranked
|
||||
if args.changelog is None:
|
||||
return ranked, None
|
||||
try:
|
||||
news = with_bullet(changelog.read_text(encoding="utf-8") if changelog.exists() else "", args.changelog)
|
||||
except OSError as failure:
|
||||
return Failure(f"{changelog}: {failure.strerror}")
|
||||
except UnicodeDecodeError:
|
||||
return Failure(f"{changelog}: not UTF-8")
|
||||
return news if isinstance(news, Failure) else (ranked, news)
|
||||
added = with_bullet(news, args.changelog)
|
||||
return added if isinstance(added, Failure) else (ranked, added)
|
||||
|
||||
|
||||
@@ -188,6 +188,10 @@ class Finish(TodoItem):
|
||||
self.assertEqual(self.run_main("finish", "2", "--changelog", "Tests are tight.")[0], 0)
|
||||
self.assertEqual(self.changelog.read_text(), "# Changelog\n\n## Unreleased\n\n- Tests are tight.\n")
|
||||
|
||||
def test_needs_no_changelog_choice_where_the_project_has_no_changelog(self):
|
||||
self.assertEqual(self.run_main("finish", "2"), (0, f"Finished item 2 in {self.todo}.\n", ""))
|
||||
self.assertFalse(self.changelog.exists())
|
||||
|
||||
def test_needs_a_changelog_choice_where_a_changelog_exists(self):
|
||||
self.changelog.write_text(CHANGELOG)
|
||||
before = self.todo.read_text()
|
||||
|
||||
@@ -1964,3 +1964,26 @@ Read most (opens and searches):
|
||||
- `bin/repo_checks/test_import_order.py` 1
|
||||
- `bin/rule_hook/rules.py` 1
|
||||
- `docs/decisions.md` 1
|
||||
|
||||
## Reading cost, chunk f9ab213f23c1, finished 2026-11-13T23:28:47Z
|
||||
|
||||
86144 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 2
|
||||
- `CLAUDE.md` 1
|
||||
|
||||
## Reading cost, chunk 46e330d60137, finished 2026-11-13T23:40:04Z
|
||||
|
||||
46201 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `CLAUDE.md` 2
|
||||
- `principles/technical-principles.md` 2
|
||||
- `skills/larv-review/SKILL.md` 2
|
||||
- `CHANGELOG.md` 1
|
||||
- `docs/decisions.md` 1
|
||||
- `rules/decisions.md` 1
|
||||
- `todo.md` 1
|
||||
|
||||
@@ -79,7 +79,11 @@
|
||||
- Things a reader finds by name may run far past seven: 100 files named by locale, the cases of an enum, a reference list. A predictable name and a sorted order serve them better than a group would.
|
||||
- Each added level makes a reader open one more folder, file or function to find a thing, so a split must save more than it costs. Keep eight, nine or ten things in one level when splitting them would add more names, files or jumps than it removes. Say why where the level is declared: a comment, the folder's README.
|
||||
- Group by what a reader would name: a feature, a step, what changes together. BANNED: `misc/`, `part2()` or a parameter object that exists only to bring a count down. GOOD: `invoices/`, `payments/`, `reports/`, each holding what changes together; `locales/` holding `de.json` to `zh.json`, flat.
|
||||
- Group code into files, and files into folders. A banner comment (`// --- name ---`) that groups a file's sections is the last resort, kept only where the language or the build cannot split the file, and the file says why it can't be split.
|
||||
- Crossing a limit asks for one of two answers, never a split at any cost: group the things, or record why they stay. Keep a limit only while the comprehension panel's readers (`~/.claude/skills/comprehension-panel/`) find the code it flags hard.
|
||||
* Make the entry point the first thing a newcomer finds.
|
||||
- The root holds the README and the files a tool reads only from there, such as the manifest, the lockfile and the licence, and the entry point where the ecosystem puts it there. Source, tests and tooling live in folders named by what they hold. A repo of several tools applies this to each tool's folder.
|
||||
- The entry point carries the name and the place its ecosystem expects, such as `index.js` at the root of an npm package or `src/main.rs` in a Cargo crate, with no other source file beside it.
|
||||
* Keep It Simple, Stupid (KISS): keep solutions simple, so a reader new to the project understands each part on one read.
|
||||
* Don't Repeat Yourself (DRY) is a guide, not an absolute rule. It aims at one authoritative home per piece of knowledge, one obvious way per need. Before applying it, ask whether the code would be easier to understand, easier to reason about, or easier to maintain if DRY were broken; if so, break it, so long as the spellings cannot disagree (below). A surface people write — a template, data, an API — may accept a second spelling where that makes it easier to use.
|
||||
- A value, rule, definition or concept lives in one place, and everywhere else derives it from there or points at it. A copy that can drift is a second spelling: derive it from its owner, or, for config a human writes, reject it where it is read and name the owner.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
paths:
|
||||
- "**/AGENTS.md"
|
||||
- "**/docs/decisions.md"
|
||||
- "**/project-record/*/decisions.md"
|
||||
---
|
||||
|
||||
# Decisions: one home, each linked to a goal or a technical principle
|
||||
|
||||
@@ -202,7 +202,7 @@ Launch prose-reviewer with what the diff touched and every section this review c
|
||||
1. Read the finished PR against the goals file's goals and code health, unless that file voids it: does anything in it work against one? It breaks a maintain goal → do not merge; redesign the change or drop its item. It works against an achieve goal → do not merge; ask the human, stating the conflict.
|
||||
2. Run the comprehension check (§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to §4, and keep the ruling and scoring run already recorded.
|
||||
3. Remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop" in the branch, commit and push that; the commit re-enters no pass.
|
||||
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background, since its wait can outlast the Bash tool's timeout. It waits for the pull request's checks to pass, then takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, once the pull request's checks pass and `~/.claude/bin/larv-review scoring-run-owed` exits 0. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background with its `timeout` set to 7200000 ms, since its wait can outlast the Bash tool's default. It waits for the pull request's checks to pass, and for a human's approval where the project's config sets `wait-for-approval` (`chunk-pr --help`), then takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, once the pull request's checks pass, `~/.claude/bin/larv-review scoring-run-owed` exits 0 and, where `~/.claude/bin/project-config wait-for-approval` prints `true`, GitHub reports the pull request approved. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
5. Merged → run `~/.claude/bin/chunk-pr clean` in the chunk's worktree, and put a failure it prints in the summary.
|
||||
6. Stop. The next chunk gets a fresh session.
|
||||
|
||||
|
||||
@@ -12,10 +12,6 @@
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 354 | 0.11.0 | | | **Read and write the decisions, score anchors, comprehension history, reading cost and changelog each through the backend its project's config names, with markdown files as one backend.** | 3 | 2 | 3 | 6 | 6 | 1.6 by 4, code health by 1 | 1.2 |
|
||||
| 364 | 0.11.0 | 354 | | **Read a client repo's own `CLAUDE.md` and `AGENTS.md`, propose to its team each change that aligns them with this setup, and record each conflict left as a decision in the project's records.** | 2 | 2 | 2 | 4 | 2 | 1.6 by 4, 1.2 by 2 | 2.2 |
|
||||
| 376 | 0.11.0 | | owner | **Make `principles/technical-principles.md` ask for files in folders before comment banners, and for an entry point a newcomer finds at once.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 4 | 1.6 |
|
||||
| 360 | 0.11.0 | | | **Make `chunk-pr merge` wait for the human approvals a project's config requires, as part of the gate, before it merges.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 5 | 1.6 |
|
||||
| 357 | 0.11.0 | | | **Write prose in the language a project's config names, and title its commits, pull requests and branches by the templates it names.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 5 | 1.4 |
|
||||
| 350 | 0.11.0 | | | **Route every read and write of the plan, by tools and by agents, through one plan-store interface and `todo-item`, with the markdown file as one backend.** | 4 | 2 | 3 | 7 | 7 | 1.6 by 4, code health by 2 | 1.1 |
|
||||
| 349 | 0.11.0 | | | **Convert markdown to ADF and back with `@larvit/adf-codec`'s portable calls, through a pinned Node shim run in a container with a memory limit.** | 2 | 1 | 2 | 3 | 2 | 1.6 by 3 | 1.1 |
|
||||
@@ -26,10 +22,10 @@
|
||||
| 363 | 0.11.0 | 362 | | **Add a Slack backend to the notifier, sending each notice as a DM from a bot.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 4 | 1.3 |
|
||||
| 373 | 0.11.0 | | | **Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 4, 1.4 by 2 | 1.3 |
|
||||
| 352 | 0.11.0 | 351 | | **Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 355 | 0.11.0 | 349, 354 | | **Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 355 | 0.11.0 | 349 | | **Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 356 | 0.11.0 | | | **Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 3 | 1.1 |
|
||||
| 372 | 0.11.0 | | | **Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.** | 3 | 2 | 3 | 6 | 6 | 1.5 by 3 | 0.4 |
|
||||
| 374 | 0.11.0 | 360, 372 | | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
|
||||
| 374 | 0.11.0 | 372 | | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
|
||||
| 359 | 0.11.0 | 350 | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
|
||||
| 375 | 0.11.0 | 372, 373, 374 | | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
|
||||
| 319 | 0.12.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.2 |
|
||||
@@ -90,46 +86,13 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 354. Read and write the decisions, score anchors, comprehension history, reading cost and changelog each through the backend its project's config names, with markdown files as one backend.
|
||||
|
||||
lilleman's call, 2026-11-12: each record has its own backend setting, so a client project can keep, say, decisions and changelog in Confluence and anchors and comprehension history as files. Which goes where is asked per client at setup. Every tool and agent that reads or writes a record goes through the interface: the judge's records, `rank_todo.py`'s decision check, `todo-item finish --changelog`, larv-review's scoring and places, `score-outcomes`, `rules/decisions.md`. The plan store's contract suite has a twin for records, on fakes. R is above 5, so this item ships alone.
|
||||
|
||||
### 364. Read a client repo's own `CLAUDE.md` and `AGENTS.md`, propose to its team each change that aligns them with this setup, and record each conflict left as a decision in the project's records.
|
||||
|
||||
lilleman's call, 2026-11-12: the loop may change every file in a client repo, but in agreement with the team, so a change to their instruction files goes to them as a proposal in a pull request. Where a conflict stays, the loop records which rule it follows and why as a decision in the project's decision record, so it is never asked twice. This is a working rule in `CLAUDE.md`.
|
||||
|
||||
### 376. Make `principles/technical-principles.md` ask for files in folders before comment banners, and for an entry point a newcomer finds at once.
|
||||
|
||||
On 2026-11-13 the maintainer asked for both, after `@larvit/log` grew one 2,462-line `index.ts`
|
||||
of 16 `// --- name ---` sections that no review asked to split until its 2.5.0 release review.
|
||||
"About seven things per level" counts a file's sections but lets banners serve as the grouping.
|
||||
|
||||
Draft wording, under "About seven things per level":
|
||||
|
||||
- Group code into files, and files into folders. A banner comment grouping a file's sections is
|
||||
the last resort, kept only where the language or the build cannot split the file, and the file
|
||||
says which limit holds it.
|
||||
|
||||
Draft wording, as a principle of its own:
|
||||
|
||||
* Make the entry point the first thing a newcomer finds.
|
||||
- The root holds the entry point, the README and the files a tool reads only from there, such as
|
||||
the manifest, the lockfile and the licence. Source, tests and tooling live in folders named by
|
||||
what they hold.
|
||||
- The entry point carries the name its ecosystem expects, such as `index.ts` in an npm package,
|
||||
with no other source file beside it.
|
||||
|
||||
### 360. Make `chunk-pr merge` wait for the human approvals a project's config requires, as part of the gate, before it merges.
|
||||
|
||||
lilleman's call, 2026-11-12: this client requires another human's approval on every pull request, so the gate covers it, and the loop still merges once the gate passes. Until this ships, lilleman merges such pull requests by hand and restarts the loop. On GitHub, read the approvals the branch protection asks for; this client's forge is GitHub.
|
||||
|
||||
### 357. Write prose in the language a project's config names, and title its commits, pull requests and branches by the templates it names.
|
||||
|
||||
lilleman's call, 2026-11-12: a client may want docs and Jira text in another language than English, and may use a commit, PR or branch format other than `CLAUDE.md`'s `ABC-123 - ...` and `ABC-123`. Everything reads the project's setting: `CLAUDE.md` → "Prose" and "Git, commits, and PRs", `chunk-preflight`'s branch and worktree names, `chunk-pr`'s titles, rule-hook's round-title checks and `score-outcomes`' `Drop item` titles. The prose reviewer judges prose in the configured language.
|
||||
|
||||
### 350. Route every read and write of the plan, by tools and by agents, through one plan-store interface and `todo-item`, with the markdown file as one backend.
|
||||
|
||||
After item 344 every reader finds `todo.md` by its configured path, but each still parses the markdown itself, and agents still Read and grep the file. After this item agents list, show, add, edit, move and finish items only through `todo-item`, which gains list, edit and move commands. `rules/todo-items.md` loads today only when a session touches a `todo.md`, so it must load another way for a plan with no file. The interface carries what ranking needs: ID, release, blocked by, exempt, tagline, L, E, I, S, moves, detail, and an order the backend supplies (score order for markdown, Jira rank for Jira). One contract suite runs against every backend, on fakes only, per lilleman's call of 2026-11-12. R is above 5, so this item ships alone.
|
||||
After item 344 every reader finds `todo.md` by its configured path, but each still parses the markdown itself, and agents still Read and grep the file. After this item agents list, show, add, edit, move and finish items only through `todo-item`, which gains list, edit and move commands. `rules/todo-items.md` loads today only when a session touches a `todo.md`, so it must load another way for a plan with no file. The interface carries what ranking needs: ID, release, blocked by, exempt, tagline, L, E, I, S, moves, detail, and an order the backend supplies (score order for markdown, Jira rank for Jira). One contract suite runs against every backend, on fakes only, per lilleman's call of 2026-11-12; `bin/record_store/contract.py` is its twin for records. R is above 5, so this item ships alone.
|
||||
|
||||
### 349. Convert markdown to ADF and back with `@larvit/adf-codec`'s portable calls, through a pinned Node shim run in a container with a memory limit.
|
||||
|
||||
@@ -169,7 +132,7 @@ lilleman's calls, 2026-11-12. Without asking, the loop may create child issues i
|
||||
|
||||
### 355. Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.
|
||||
|
||||
lilleman's calls, 2026-11-12: one page per record, whose ID the config names. The loop reads the page's ADF as portable markdown and writes markdown back through adf-codec. It writes with the version number it read; where Confluence reports a newer version, the loop asks the human, and never overwrites a teammate's edit on its own. Auth: email plus API token from the project's env file.
|
||||
lilleman's calls, 2026-11-12: one page per record, whose ID the config names. The loop reads the page's ADF as portable markdown and writes markdown back through adf-codec. It writes with the version number it read; where Confluence reports a newer version, the loop asks the human, and never overwrites a teammate's edit on its own. Auth: email plus API token from the project's env file. The page is one more `RecordStore` in `bin/record_store/stores.py`, held to `contract.py`. `store` picks it by the setting's value. `project-config` and `chunk-preflight` print each record's setting as a path, so make both print a page's setting as it is written. `write` takes only the text, so the store itself keeps the version it read.
|
||||
|
||||
### 356. Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user