diff --git a/.gitignore b/.gitignore index d1c867d8..ebd762be 100644 --- a/.gitignore +++ b/.gitignore @@ -17,10 +17,13 @@ !agents/ !agents/*.md !bin/ +!bin/failure.py +!bin/file_writes.py !bin/loop-claude !bin/loop_claude/ !bin/loop_claude/**/ !bin/loop_claude/**/*.py +!bin/markdown_sections.py !bin/rank_todo.py !bin/statusline.py !bin/test_*.py @@ -35,6 +38,6 @@ !skills/larv-review/*.md !workflow-bench/ !workflow-bench/bench.py -!workflow-bench/judge-prompt.md -!workflow-bench/judge.py +!workflow-bench/compare-prompt.md +!workflow-bench/compare.py !workflow-bench/run-prompt.md diff --git a/AGENTS.md b/AGENTS.md index 8c449c13..640a7ed5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ Decisions live in `docs/decisions.md`: - loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes - review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human - review: a fix for a ๐ŸŸข or โ“ re-enters review like any fix -- review: a pass skips only on a record older than the chunk +- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop - loop-claude: a `claude` that cannot start is a failed worker run, retried - review: an ask no user answers leaves the PR unmerged diff --git a/CHANGELOG.md b/CHANGELOG.md index b63864d0..9ddc3fe1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,6 @@ - `loop-claude` retries a failed worker within its cycle. - `loop-claude` counts an interrupt reply starting with `<` as typed. - `loop-claude`'s judge sees a reply the human types while claude works, and an interrupt counts one as typed. -- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and failures included, in one folder per chunk. Each distinct transcript is kept once, named by its SHA-256, with `.verdict.md` beside it holding the verdict and why the loop stopped. The subagents' transcripts and the session's other files go in the chunk folder's `session/` subfolder. `loop-claude` exits 1 when it cannot archive. +- `loop-claude` archives the raw `.jsonl` transcript at every interrupt and as every cycle ends, Ctrl-C and failures included, in one folder per chunk. Each distinct transcript is kept once, named by its SHA-256, with `.outcomes.md` beside it holding the verdict and why the loop stopped. The subagents' transcripts and the session's other files go in the chunk folder's `session/` subfolder. `loop-claude` exits 1 when it cannot archive. - `loop-claude` exits 1 when it cannot delete a finished chunk's session, naming what to delete before rerunning; the next chunk would otherwise resume it. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/README.md b/README.md index 0282a310..4c880137 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `AGENTS.md` for ins ## Goals 1. Make my claude setup shareable between computers. -2. Keep my claude setup and the transcripts of unattended runs, backed up. +2. Keep my claude setup and the transcripts of unattended runs, the bench's included, backed up. 3. Leak nothing to the remote โ€” no credentials, no transcripts, no memory files. 4. Get the highest quality out of Claude Code while interrupting me the least, so development scales. 1. Proven, stellar output quality: code, documentation and plans. diff --git a/bin/loop_claude/failure.py b/bin/failure.py similarity index 100% rename from bin/loop_claude/failure.py rename to bin/failure.py diff --git a/bin/loop_claude/file_writes.py b/bin/file_writes.py similarity index 95% rename from bin/loop_claude/file_writes.py rename to bin/file_writes.py index cca4bdaa..0a799cf7 100644 --- a/bin/loop_claude/file_writes.py +++ b/bin/file_writes.py @@ -3,7 +3,7 @@ import os import pathlib import typing -from loop_claude.failure import Failure +from failure import Failure def make_private(folder: pathlib.Path) -> None: diff --git a/bin/loop_claude/claude_code/session.py b/bin/loop_claude/claude_code/session.py index a04ff067..8496af13 100644 --- a/bin/loop_claude/claude_code/session.py +++ b/bin/loop_claude/claude_code/session.py @@ -5,7 +5,7 @@ import pathlib import shutil import uuid -from loop_claude.failure import Failure +from failure import Failure from loop_claude.paths import Paths NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") diff --git a/bin/loop_claude/claude_code/transcript.py b/bin/loop_claude/claude_code/transcript.py index 29eaa246..0eef90b3 100644 --- a/bin/loop_claude/claude_code/transcript.py +++ b/bin/loop_claude/claude_code/transcript.py @@ -1,7 +1,7 @@ import json from loop_claude.claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call -from loop_claude.failure import Failure +from failure import Failure JUDGED_TOOL_INPUT = 400 diff --git a/bin/loop_claude/claude_code/trust.py b/bin/loop_claude/claude_code/trust.py index d6cb662e..a6d5bb2a 100644 --- a/bin/loop_claude/claude_code/trust.py +++ b/bin/loop_claude/claude_code/trust.py @@ -2,8 +2,8 @@ import json import pathlib import sys -from loop_claude.failure import Failure -from loop_claude.file_writes import replace_json +from failure import Failure +from file_writes import replace_json # A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog. diff --git a/bin/loop_claude/cycle/archive.py b/bin/loop_claude/cycle/archive.py index 03f1b4a7..404ce080 100644 --- a/bin/loop_claude/cycle/archive.py +++ b/bin/loop_claude/cycle/archive.py @@ -3,9 +3,9 @@ import os import pathlib import sys -from loop_claude.failure import Failure +from failure import Failure from loop_claude.claude_code.transcript import first_timestamped_line -from loop_claude.file_writes import make_private, replace_file +from file_writes import make_private, replace_file from loop_claude.paths import Paths from loop_claude.claude_code.session import session_files @@ -23,11 +23,11 @@ def archive(project_key: str, path: str, task: str, outcome: str, paths: Paths) if sibling != path and (unkept := mirror(pathlib.Path(sibling), folder / "session" / os.path.basename(sibling))): return unkept copy = folder / f"{hashlib.sha256(raw).hexdigest()}.jsonl" - verdict = copy.with_suffix(".verdict.md") - if copy.exists(): - return add_outcome(verdict, outcome) - # The copy lands last, so a copy on disk always has its verdict and its session's files beside it. - for dest, data in ((verdict, f"Task: {task}\n\n{outcome}\n".encode()), (copy, raw)): + outcomes = copy.with_suffix(".outcomes.md") + if copy.exists() and outcomes.exists(): + return add_outcome(outcomes, outcome) + # The copy lands last, so a copy on disk always has its outcomes and its session's files beside it. + for dest, data in ((outcomes, f"Task: {task}\n\n{outcome}\n".encode()), (copy, raw)): if unwritten := replace_file(dest, data): return unarchived(dest, unwritten.reason) print(f"transcript: {copy}", file=sys.stderr) @@ -38,13 +38,13 @@ def unarchived(where: object, why: str | None) -> Failure: return Failure(f"could not archive the transcript: {where}: {why}") -def add_outcome(verdict: pathlib.Path, outcome: str) -> Failure | None: +def add_outcome(outcomes: pathlib.Path, outcome: str) -> Failure | None: try: - outcomes = verdict.read_bytes() + kept = outcomes.read_bytes() except OSError as failure: return unarchived(failure.filename, failure.strerror) - if unwritten := replace_file(verdict, outcomes + f"\n{outcome}\n".encode()): - return unarchived(verdict, unwritten.reason) + if unwritten := replace_file(outcomes, kept + f"\n{outcome}\n".encode()): + return unarchived(outcomes, unwritten.reason) return None diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index d36ee638..c61883cf 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -2,7 +2,7 @@ import sys import uuid from loop_claude.effects import Effects -from loop_claude.failure import Failure +from failure import Failure from loop_claude.claude_code.transcript import human_turns, read_transcript from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 7d7d5062..130544b9 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -1,64 +1,16 @@ -import dataclasses import json import re -import typing from loop_claude.effects import Effects -from loop_claude.failure import Failure -from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict +from failure import Failure from loop_claude.claude_code.entries import hit_limit, limit_said, parse_entry, structured_output -from loop_claude.cycle.limited import Limited -from loop_claude.cycle.retry import retried +from loop_claude.cycle.judge_reply import Interrupt, JUDGE_RULES, JUDGE_SCHEMA, QuotedAnswer, Verdict, verdict_from +from loop_claude.cycle.retry import Limited, retried from loop_claude.stop import Stop # At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03. JUDGE_PROMPT_CHARS = 400000 -JUDGE_RULES = ( - "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" - "- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither " - "README.md nor the project's records settle the matter, or it asks again a question a [loop] line already answered\n" - "- it carried on under an assumption that decides the deliverable, that the human could " - "reasonably reject and that neither README.md nor the project's records settle; a caveat about " - "transient state it then handled is not one\n" - "- it is blocked on something only the human can supply: a credential, a version bump, a choice " - "outside the repo, or a release ready to cut, which only the human may publish\n" - "- it flags that the goals, the plan in todo.md or the task itself is unclear, missing or in need of change\n" - "- it chose between alternatives that neither README.md nor the project's records discriminate " - "between - neither rules the rejected one out - and the choice materially changes the deliverable\n" - "interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, " - "where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what " - "is still open, never a question they already answered there. A [loop] line is what loop-claude told " - "the agent, such as an answer quoted from README.md or the project's records. A question a [loop] " - "line answered is settled. If the agent asks it again, interrupt with that question.\n" - "Where the agent asked or flagged something itself, the question is that one, in the agent's own " - "wording; never construct another from facts it stated.\n" - "Where README.md or the project's records answer the agent's own question and no [loop] line has " - "quoted that answer yet, set interrupt=false, put that question in question and quote the passage that answers it in answer, verbatim; the agent is " - "then given that passage in place of the human's reply.\n" - "The chunk is the piece of work the agent is on, shipped as one pull request. " - "finished=true when the chunk is complete: merged, or nothing remains that the agent could do on " - "its own. finished=false when work remains that a further run can continue: an open PR, a review " - "not yet run, CI not yet reported." -) - -@dataclasses.dataclass(frozen=True) -class Reply: - answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the project's records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."}) - evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."}) - finished: bool - interrupt: bool - question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."}) - - -REPLY_TYPES = typing.get_type_hints(Reply) -JSON_TYPES = {bool: "boolean", str: "string"} -JUDGE_SCHEMA = { - "properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)}, - "required": list(REPLY_TYPES), - "type": "object", -} - def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop: # --json-schema has claude check its reply against the schema and return it as the json result's structured_output. @@ -72,11 +24,11 @@ def judge(root: str, task: str, premises: str, records: str, rendered_transcript "--permission-mode", "bypassPermissions", "--tools", "", ] - prompt = judge_prompt(task, premises, records, rendered_transcript) - return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, f"{premises}\n\n{records}", effects), effects) + prompt, shown = judge_prompt(task, premises, records, rendered_transcript) + return retried("judge", lambda: run_judge(root, args, prompt, shown, f"{premises}\n\n{records}", effects), effects) -def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited: +def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited: try: proc = effects.claude(args, root, prompt) except OSError as failure: @@ -90,7 +42,7 @@ def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, verdict = verdict_from(structured_output(reply)) if isinstance(verdict, Failure): return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}") - if not grounded(verdict.evidence, rendered_transcript): + if not grounded(verdict.evidence, shown): return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else "")) # Not a Failure: a misquote would otherwise exit an unattended loop. Never elided: stitched fragments can say what the records do not. if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable): @@ -98,7 +50,8 @@ def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, return verdict -def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> str: +def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> tuple[str, str]: + """The prompt, and the part of the transcript it shows, which the judge's evidence must quote.""" head = ( f"From README.md:\n{premises}\n\n" f"The project's records, its working rules and decisions:\n{records or 'none'}\n\n" @@ -107,25 +60,8 @@ def judge_prompt(task: str, premises: str, records: str, rendered_transcript: st ) room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2) # The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle. - return f"{head}{rendered_transcript[max(0, len(rendered_transcript) - room):]}\n\n{JUDGE_RULES}" - - -def verdict_from(output: object) -> Verdict | Failure: - if not isinstance(output, dict): - return Failure("the judge returned no reply") - for name, kind in REPLY_TYPES.items(): - if not isinstance(output.get(name), kind): - return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}") - # An interrupt outranks a quoted answer and finished: the human answers before the chunk can close. - if output["interrupt"]: - if not output["question"].strip(): - return Failure("the judge interrupted without a question") - return Interrupt(output["evidence"], output["question"]) - if output["answer"].strip(): - if not output["question"].strip(): - return Failure("the judge quoted an answer without a question") - return QuotedAnswer(output["evidence"], output["question"], output["answer"]) - return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"]) + shown = rendered_transcript[max(0, len(rendered_transcript) - room):] + return f"{head}{shown}\n\n{JUDGE_RULES}", shown def grounded(evidence: str, rendered_transcript: str) -> bool: diff --git a/bin/loop_claude/cycle/judge_reply.py b/bin/loop_claude/cycle/judge_reply.py new file mode 100644 index 00000000..c7f8e1db --- /dev/null +++ b/bin/loop_claude/cycle/judge_reply.py @@ -0,0 +1,95 @@ +import dataclasses +import typing + +from failure import Failure + +JUDGE_RULES = ( + "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" + "- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither " + "README.md nor the project's records settle the matter\n" + "- it asks again a question a [loop] line already answered\n" + "- it carried on under an assumption that decides the deliverable, that the human could " + "reasonably reject and that neither README.md nor the project's records settle; a caveat about " + "transient state it then handled is not one\n" + "- it is blocked on something only the human can supply: a credential, a version bump, a choice " + "outside the repo, or a release ready to cut, which only the human may publish\n" + "- it flags that the goals, the plan in todo.md or the task itself is unclear, missing or in need of change\n" + "- it chose between alternatives that neither README.md nor the project's records discriminate " + "between - neither rules the rejected one out - and the choice materially changes the deliverable\n" + "interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, " + "where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what " + "is still open, never a question they already answered there. A [loop] line is what loop-claude told " + "the agent, such as an answer quoted from README.md or the project's records.\n" + "Where the agent asked or flagged something itself, the question is that one, in the agent's own " + "wording; never construct another from facts it stated.\n" + "Where README.md or the project's records answer the agent's own question and no [loop] line has " + "quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is " + "then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either " + "outranks finished.\n" + "The chunk is the piece of work the agent is on, shipped as one pull request. " + "finished=true when the chunk is complete: merged, or nothing remains that the agent could do on " + "its own. finished=false when work remains that a further run can continue: an open PR, a review " + "not yet run, CI not yet reported." +) + + +@dataclasses.dataclass(frozen=True) +class Reply: + answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the project's records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."}) + evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."}) + finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."}) + interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."}) + question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."}) + + +REPLY_TYPES = typing.get_type_hints(Reply) +JSON_TYPES = {bool: "boolean", str: "string"} +JUDGE_SCHEMA = { + "properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)}, + "required": list(REPLY_TYPES), + "type": "object", +} + + +@dataclasses.dataclass(frozen=True) +class Interrupt: + evidence: str + question: str + + +@dataclasses.dataclass(frozen=True) +class QuotedAnswer: + """The agent asked a question that README.md or the project's records answer. The answer field quotes the passage.""" + evidence: str + question: str + answer: str + + +@dataclasses.dataclass(frozen=True) +class Finished: + evidence: str + + +@dataclasses.dataclass(frozen=True) +class Unfinished: + evidence: str + + +Verdict = Interrupt | QuotedAnswer | Finished | Unfinished + + +def verdict_from(output: object) -> Verdict | Failure: + if not isinstance(output, dict): + return Failure("the judge returned no reply") + for name, kind in REPLY_TYPES.items(): + if not isinstance(output.get(name), kind): + return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}") + if output["interrupt"]: + if not output["question"].strip(): + return Failure("the judge interrupted without a question") + return Interrupt(output["evidence"], output["question"]) + if output["answer"].strip(): + if not output["question"].strip(): + return Failure("the judge quoted an answer without a question") + return QuotedAnswer(output["evidence"], output["question"], output["answer"]) + return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"]) diff --git a/bin/loop_claude/cycle/limited.py b/bin/loop_claude/cycle/limited.py deleted file mode 100644 index 5ed69bc6..00000000 --- a/bin/loop_claude/cycle/limited.py +++ /dev/null @@ -1,8 +0,0 @@ -import dataclasses - - -@dataclasses.dataclass(frozen=True) -class Limited: - """claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown.""" - resets_at: int | None - said: str diff --git a/bin/loop_claude/cycle/retry.py b/bin/loop_claude/cycle/retry.py index c6a52464..bb9a4215 100644 --- a/bin/loop_claude/cycle/retry.py +++ b/bin/loop_claude/cycle/retry.py @@ -1,17 +1,26 @@ +import dataclasses import sys import typing from loop_claude.effects import Effects -from loop_claude.failure import Failure -from loop_claude.cycle.limited import Limited +from failure import Failure from loop_claude.stop import Stop T = typing.TypeVar("T") +FAILURES_RUNNING = 3 PAST_RESET = 120 +RETRY_DELAY = 60 UNKNOWN_RESET_POLL = 600 +@dataclasses.dataclass(frozen=True) +class Limited: + """claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown.""" + resets_at: int | None + said: str + + def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop: failures = 0 while True: @@ -27,10 +36,10 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec if not isinstance(result, Failure): return result failures += 1 - if failures == 3: + if failures == FAILURES_RUNNING: return Stop(1, f"the {who} failed three times running: {result.reason}") print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr) - effects.sleep(60) + effects.sleep(RETRY_DELAY) def limit_wait(limited: Limited, now: float) -> float: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 898f168a..7fdc4a90 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -1,12 +1,12 @@ import dataclasses import typing -from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, Ruled, State, transition, WorkerRan, Working +from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working from loop_claude.cycle.archive import archive from loop_claude.claude_code.session import delete_session, Session, session_open, transcript_file from loop_claude.effects import Effects -from loop_claude.failure import Failure -from loop_claude.cycle.verdicts import Finished, QuotedAnswer, Unfinished +from failure import Failure +from loop_claude.cycle.judge_reply import Finished, Interrupt, QuotedAnswer, Unfinished from loop_claude.cycle.interrupt import interrupt from loop_claude.cycle.judge import judge from loop_claude.project.model_choice import Models @@ -57,8 +57,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop: return work(cycle, answered) case Judging(transcript_path, _): return rule(cycle, transcript_path) - case Interrupting(transcript_path, question, _): - return ask(cycle, transcript_path, question) + case Interrupting(transcript_path, ruling, _): + return ask(cycle, transcript_path, ruling) case Closing(transcript_path, verdict): return close(cycle, transcript_path, verdict) case _: @@ -83,13 +83,20 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: return verdict if isinstance(verdict, Stop) else Ruled(verdict) -def ask(cycle: Cycle, transcript_path: str, question: str) -> HumanAnswered | Stop: +def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | Stop: + question = question_for(ruling) # Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript. if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: interrupt\n\n{question}", cycle.paths): return Stop(1, failure.reason) return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered() +def question_for(ruling: Interrupt | QuotedAnswer) -> str: + if isinstance(ruling, Interrupt): + return ruling.question + return f"{ruling.question}\n\n{QUOTE_SOURCES} says:\n{ruling.answer}\n\nThose files have answered {QUOTED_ANSWERS_PER_CYCLE} questions this cycle, the most allowed, so this one comes to you." + + def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: finished = isinstance(verdict, Finished) if failure := archive(cycle.project_key, transcript_path, cycle.task, f"Verdict: {'finished' if finished else 'unfinished'}", cycle.paths): diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index aa74f42d..8b64a743 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -1,7 +1,6 @@ import dataclasses -from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict -from loop_claude.project.records import QUOTE_SOURCES +from loop_claude.cycle.judge_reply import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict # A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records. QUOTED_ANSWERS_PER_CYCLE = 3 @@ -16,15 +15,16 @@ class Working: @dataclasses.dataclass(frozen=True) class Judging: - """The judge rules; quoted_answers counts the questions README.md or the records answered this cycle.""" + """The judge rules; quoted_answers counts the questions README.md or the records answered this cycle, and an interrupt does not reset it.""" transcript_path: str quoted_answers: int = 0 @dataclasses.dataclass(frozen=True) class Interrupting: + """The human answers; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE.""" transcript_path: str - question: str + ruling: Interrupt | QuotedAnswer quoted_answers: int = 0 @@ -72,10 +72,8 @@ def transition(state: State, event: Event) -> State: return Judging(transcript_path, quoted_answers) case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE: return Working(answered, quoted_answers + 1) - case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer(question=question, answer=answer)): - return Interrupting(transcript_path, f"{question}\n\n{QUOTE_SOURCES} says:\n{answer}\n\nThose files have answered {quoted_answers} questions this cycle, the most allowed, so this one comes to you.", quoted_answers) - case Judging(transcript_path, quoted_answers), Ruled(Interrupt(question=question)): - return Interrupting(transcript_path, question, quoted_answers) + case Judging(transcript_path, quoted_answers), Ruled(Interrupt() | QuotedAnswer() as ruling): + return Interrupting(transcript_path, ruling, quoted_answers) case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict): return Closing(transcript_path, verdict) # The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves. diff --git a/bin/loop_claude/cycle/verdicts.py b/bin/loop_claude/cycle/verdicts.py deleted file mode 100644 index 172e8159..00000000 --- a/bin/loop_claude/cycle/verdicts.py +++ /dev/null @@ -1,28 +0,0 @@ -import dataclasses - - -@dataclasses.dataclass(frozen=True) -class Interrupt: - evidence: str - question: str - - -@dataclasses.dataclass(frozen=True) -class QuotedAnswer: - """The agent asked a question that README.md or the project's records answer. The answer field quotes the passage.""" - evidence: str - question: str - answer: str - - -@dataclasses.dataclass(frozen=True) -class Finished: - evidence: str - - -@dataclasses.dataclass(frozen=True) -class Unfinished: - evidence: str - - -Verdict = Interrupt | QuotedAnswer | Finished | Unfinished diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index fd6013c4..55775434 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -1,10 +1,10 @@ from loop_claude.claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until from loop_claude.effects import Effects -from loop_claude.failure import Failure -from loop_claude.cycle.limited import Limited +from failure import Failure +from loop_claude.cycle.retry import Limited from loop_claude.claude_code.transcript import part_line from loop_claude.project.records import QUOTE_SOURCES -from loop_claude.cycle.verdicts import QuotedAnswer +from loop_claude.cycle.judge_reply import QuotedAnswer from loop_claude.claude_code.session import Session PRINTED_TOOL_INPUT = 160 diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 489b76f8..70b91729 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -21,7 +21,7 @@ relative to ~/code, or to / outside it. The session is deleted when its chunk fi interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is copied to $LOOP_CLAUDE_TRANSCRIPTS///.jsonl (default ~/.claude/loop-claude-transcripts), named by its hash. is the hash of the transcript's first -line with a timestamp, the same for every cycle of a chunk. Beside the copy, .verdict.md +line with a timestamp, the same for every cycle of a chunk. Beside the copy, .outcomes.md holds the verdict, and why the loop stopped. Claude Code keeps a folder per session beside its transcript, holding the subagents' transcripts among other files; that folder, and every other file named after the session except the transcript, are copied into /session/. A file there is @@ -33,7 +33,7 @@ Every claude loop-claude starts runs the project's model, saved per in run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the interrupt; with both set, nothing is asked. -A change to bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next cycle boundary, once +A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once loop-claude --help succeeds: the loop reloads into the edited script. Exit 1, saying why, when: diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index e7fc5bc0..22acc436 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -36,7 +36,7 @@ def decode_handed(handed: str, kind: type[T]) -> T | None: def fingerprint(launcher: pathlib.Path) -> str: digest = hashlib.sha256() - for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]: + for path in [launcher, *sorted(launcher.parent.rglob("*.py"))]: try: content = path.read_bytes() except OSError as failure: diff --git a/bin/loop_claude/project/model_choice.py b/bin/loop_claude/project/model_choice.py index 53868918..03a8e681 100644 --- a/bin/loop_claude/project/model_choice.py +++ b/bin/loop_claude/project/model_choice.py @@ -6,10 +6,10 @@ import typing from loop_claude.claude_code.model_catalog import catalog_models from loop_claude.effects import Effects -from loop_claude.failure import Failure +from failure import Failure from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths -from loop_claude.file_writes import replace_json +from file_writes import replace_json @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/project/premises.py b/bin/loop_claude/project/premises.py index 5f3f02c7..a00b3647 100644 --- a/bin/loop_claude/project/premises.py +++ b/bin/loop_claude/project/premises.py @@ -1,5 +1,5 @@ from loop_claude.project.checkout import read_checkout_file -from loop_claude.markdown_sections import sections +from markdown_sections import sections from loop_claude.stop import Stop diff --git a/bin/loop_claude/markdown_sections.py b/bin/markdown_sections.py similarity index 100% rename from bin/loop_claude/markdown_sections.py rename to bin/markdown_sections.py diff --git a/bin/rank_todo.py b/bin/rank_todo.py index 8b9d0848..c41af4fe 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -57,10 +57,9 @@ import pathlib import re import sys -# Kept inside loop_claude/ so reload's fingerprint covers them. -from loop_claude.failure import Failure -from loop_claude.markdown_sections import FENCE, sections -from loop_claude.file_writes import replace_file +from failure import Failure +from markdown_sections import FENCE, sections +from file_writes import replace_file EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security") ITEMS_HEADER = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |" diff --git a/bin/test_file_writes.py b/bin/test_file_writes.py new file mode 100644 index 00000000..420a62c7 --- /dev/null +++ b/bin/test_file_writes.py @@ -0,0 +1,22 @@ +import os +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from failure import Failure +import file_writes + + +class ReplaceFile(unittest.TestCase): + def test_removes_what_it_staged_when_the_replace_fails(self): + with tempfile.TemporaryDirectory() as root: + os.mkdir(os.path.join(root, "in-the-way")) + self.assertEqual(file_writes.replace_file(pathlib.Path(root, "in-the-way"), b"data"), Failure("Is a directory")) + self.assertEqual(os.listdir(root), ["in-the-way"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/test_gitignore.py b/bin/test_gitignore.py index c87f84ea..173975c9 100644 --- a/bin/test_gitignore.py +++ b/bin/test_gitignore.py @@ -27,7 +27,7 @@ PRIVATE = [ "tasks/a/b.json", "workflow-bench/a-1-1.md", "workflow-bench/a-1-1/README.md", - "workflow-bench/judge/a/A1/fixes.diff", + "workflow-bench/compare/a/A1/fixes.diff", "workflow-bench/logs/a.jsonl", ] diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 32e38ace..ff7f8dfd 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -20,11 +20,11 @@ from loop_claude.cycle import archive, interrupt, judge, retry, run, states, wor from loop_claude.project import checkout, model_choice, records from loop_claude.effects import Effects from loop_claude.claude_code import entries, session, transcript, trust -from loop_claude.failure import Failure -from loop_claude import file_writes, markdown_sections, paths -from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished -from loop_claude.cycle.limited import Limited +from failure import Failure +from loop_claude.cycle.judge_reply import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from +from loop_claude.cycle.retry import Limited from loop_claude.loop import main, reload +from loop_claude import paths from loop_claude.stop import Stop CWD = pathlib.Path("/c") @@ -131,23 +131,23 @@ class Transitions(unittest.TestCase): legal = ( (states.Working(), states.WorkerRan("/t"), states.Judging("/t")), (states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.WorkerRan("/t"), states.Judging("/t", 3)), - (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")), - (states.Judging("/t", 3), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?", 3)), + (states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"))), + (states.Judging("/t", 3), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", Interrupt("e", "Which one?"), 3)), (states.Judging("/t"), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 1)), (states.Judging("/t", 2), answered, states.Working(QuotedAnswer("e", "Which one?", "A."), 3)), - (states.Judging("/t", 3), answered, states.Interrupting("/t", "Which one?\n\nREADME.md's Goals and Audience, AGENTS.md or docs/decisions.md says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.", 3)), + (states.Judging("/t", 3), answered, states.Interrupting("/t", QuotedAnswer("e", "Which one?", "A."), 3)), (states.Judging("/t"), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), (states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))), (states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))), - (states.Interrupting("/t", "q"), states.HumanAnswered(), states.Judging("/t")), - (states.Interrupting("/t", "q", 3), states.HumanAnswered(), states.Judging("/t", 3)), + (states.Interrupting("/t", Interrupt("e", "q")), states.HumanAnswered(), states.Judging("/t")), + (states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanAnswered(), states.Judging("/t", 3)), (states.Closing("/t", Finished("e")), states.Archived(), states.Ended()), ) for state, event, after in legal: with self.subTest(state=state, event=event): self.assertEqual(states.transition(state, event), after) - every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", "q"), states.Interrupting("/t", "q", 3), states.Closing("/t", Finished("e")), states.Ended()) + every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Closing("/t", Finished("e")), states.Ended()) every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.HumanAnswered(), states.Archived()) for state in every_state: for event in every_event: @@ -156,6 +156,12 @@ class Transitions(unittest.TestCase): states.transition(state, event) +class QuestionFor(unittest.TestCase): + def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self): + self.assertEqual(run.question_for(Interrupt("e", "Which one?")), "Which one?") + self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nREADME.md's Goals and Audience, AGENTS.md or docs/decisions.md says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.") + + class Cycles(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() @@ -167,13 +173,13 @@ class Cycles(unittest.TestCase): def cycle(self, fake, records=""): return run.Cycle(effects=fake.effects(), models=model_choice.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="proj", records=records, root=str(self.home), session=self.session, task="Do it.") - def archived_verdicts(self): - return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*/*.verdict.md")) + def archived_outcomes(self): + return sorted(path.read_text() for path in (self.paths.transcript_archive / "proj").glob("*/*.outcomes.md")) def test_a_finished_chunk_is_archived_and_its_session_deleted(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) self.assertIsNone(run.run_cycle(self.cycle(fake))) - self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"]) + self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\nVerdict: finished\n"]) self.assertIsNone(session.transcript_file(self.session)) def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session(self): @@ -184,14 +190,14 @@ class Cycles(unittest.TestCase): workers = fake.made("stream_claude") self.assertIn("--session-id", workers[0]) self.assertIn("--resume", workers[1]) - self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: unfinished\n"] * 2) + self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\nVerdict: unfinished\n"] * 2) def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3) self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()]) self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, "")) - self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nStopped: Ctrl-C\n", "Task: Do it.\n\nStopped: the judge failed three times running: the judge exited 1\n"]) + self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\nStopped: Ctrl-C\n", "Task: Do it.\n\nStopped: the judge failed three times running: the judge exited 1\n"]) def test_archives_each_chunks_session_folder_replacing_a_copy_only_with_what_grew_from_it(self): folder = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) @@ -237,7 +243,7 @@ class Cycles(unittest.TestCase): return 0 fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()]) self.assertIsNone(run.run_cycle(self.cycle(fake))) - self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n", "Task: Do it.\n\nVerdict: unfinished\n"]) + self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n", "Task: Do it.\n\nVerdict: unfinished\n"]) self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) prompts = [stdin for args, stdin in fake.made("claude")] self.assertEqual(len(prompts), 2) @@ -273,7 +279,7 @@ class Cycles(unittest.TestCase): stop = run.run_cycle(self.cycle(fake)) self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session")) self.assertTrue(session.session_open(self.session)) - self.assertEqual(self.archived_verdicts(), [f"Task: Do it.\n\nVerdict: finished\n\nStopped: {stop.reason}\n"]) + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\nVerdict: finished\n\nStopped: {stop.reason}\n"]) def test_stops_when_the_worker_leaves_no_transcript(self): fake = FakeEffects(streams=[Streamed(0)]) @@ -394,17 +400,6 @@ class Records(unittest.TestCase): self.assertEqual(records.read_records(root), Stop(1, f"AGENTS.md in {root} is not UTF-8 on line 2 - the judge cannot read the project's records.")) -class Sections(unittest.TestCase): - def test_keeps_every_headed_section_with_its_bodies(self): - text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" - self.assertEqual(markdown_sections.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) - - def test_closes_a_fence_only_on_its_own_marker(self): - text = "## Goals\n````md\n~~~\n## Quoted\n```\n````\n ~~~\n## Also quoted\n ~~~\n1. one\n## Audience\nme\n" - self.assertEqual(list(markdown_sections.sections(text)), ["Goals", "Audience"]) - self.assertEqual(list(markdown_sections.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"]) - - class Render(unittest.TestCase): def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self): said = transcript.render([ @@ -421,6 +416,20 @@ class Render(unittest.TestCase): self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.') +class Archive(unittest.TestCase): + def test_writes_afresh_a_copy_whose_outcomes_file_is_missing(self): + with tempfile.TemporaryDirectory() as root: + kept = paths.paths_from(pathlib.Path(root), {}) + transcript = pathlib.Path(root, "t.jsonl") + transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n') + with contextlib.redirect_stderr(io.StringIO()): + self.assertIsNone(archive.archive("proj", str(transcript), "Do it.", "Verdict: unfinished", kept)) + (outcomes,) = kept.transcript_archive.glob("proj/*/*.outcomes.md") + outcomes.unlink() + self.assertIsNone(archive.archive("proj", str(transcript), "Do it.", "Stopped: Ctrl-C", kept)) + self.assertEqual(outcomes.read_text(), "Task: Do it.\n\nStopped: Ctrl-C\n") + + class CopyFor(unittest.TestCase): def test_skips_a_version_already_kept_beside_its_copy(self): with tempfile.TemporaryDirectory() as temp: @@ -486,6 +495,15 @@ class MarkTrusted(unittest.TestCase): self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"])) +class JudgePrompt(unittest.TestCase): + def test_shows_the_transcripts_tail_and_returns_what_it_showed(self): + prompt, shown = judge.judge_prompt("Do it.", "## Goals", "", "old " + "x" * judge.JUDGE_PROMPT_CHARS + " new") + self.assertTrue(shown.endswith(" new")) + self.assertNotIn("old", shown) + self.assertIn(shown, prompt) + self.assertLessEqual(len(prompt), judge.JUDGE_PROMPT_CHARS) + + class Grounded(unittest.TestCase): def test_every_verdict_must_quote_the_transcript(self): self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n")) @@ -512,16 +530,16 @@ class Grounded(unittest.TestCase): class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertEqual(judge.verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e")) - self.assertEqual(judge.verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e")) - self.assertEqual(judge.verdict_from({"answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?")) - self.assertEqual(judge.verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A.")) - self.assertEqual(judge.verdict_from({"answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?")) - self.assertEqual(judge.verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Failure("the judge quoted an answer without a question")) - self.assertEqual(judge.verdict_from({"answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean")) - self.assertEqual(judge.verdict_from({"answer": "", "interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string")) - self.assertEqual(judge.verdict_from({"answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question")) - self.assertEqual(judge.verdict_from(None), Failure("the judge returned no reply")) + self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e")) + self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e")) + self.assertEqual(verdict_from({"answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?")) + self.assertEqual(verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A.")) + self.assertEqual(verdict_from({"answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?")) + self.assertEqual(verdict_from({"answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Failure("the judge quoted an answer without a question")) + self.assertEqual(verdict_from({"answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean")) + self.assertEqual(verdict_from({"answer": "", "interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string")) + self.assertEqual(verdict_from({"answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question")) + self.assertEqual(verdict_from(None), Failure("the judge returned no reply")) class LoopRuns(unittest.TestCase): @@ -548,7 +566,12 @@ class LoopRuns(unittest.TestCase): class HelpLimits(unittest.TestCase): def test_help_states_the_limits_the_code_holds(self): - self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", main.__doc__.replace("\n", " ")) + said = " ".join(main.__doc__.split()) + self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", said) + # The retry messages say these limits in words too. + self.assertEqual((retry.FAILURES_RUNNING, retry.RETRY_DELAY), (3, 60)) + self.assertIn("fails three times running, retried a minute apart", said) + self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said) class ExitContract(unittest.TestCase): @@ -596,19 +619,39 @@ class ExitContract(unittest.TestCase): self.assertEqual([clause for *_, clause in clauses if f"- {clause}" not in help_exit_1], []) +class JudgeFailures(unittest.TestCase): + def test_every_failed_judge_run_has_its_clause_in_help(self): + started, field, unasked = "claude cannot start or exits non-zero", "its reply misses or mistypes a field", "interrupts or quotes an answer without a question" + # Every Failure the judge's run returns, in source order: path, function, start of reason, its --help clause. + clauses = [ + ("cycle/judge.py", "run_judge", "f'could not start claude:", started), + ("cycle/judge.py", "run_judge", "proc.stderr.strip() or f'the judge exited", started), + ("cycle/judge.py", "run_judge", 'f"{verdict.reason}; it replied:', field), + ("cycle/judge.py", "run_judge", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"), + ("cycle/judge_reply.py", "verdict_from", "'the judge returned no reply'", field), + ("cycle/judge_reply.py", "verdict_from", 'f"the judge\'s reply has no {name}', field), + ("cycle/judge_reply.py", "verdict_from", "'the judge interrupted without a question'", unasked), + ("cycle/judge_reply.py", "verdict_from", "'the judge quoted an answer without a question'", unasked), + ] + root = pathlib.Path(main.__file__).parents[1] + found = [] + for path in ("cycle/judge.py", "cycle/judge_reply.py"): + functions = [node for node in ast.walk(ast.parse((root / path).read_text())) if isinstance(node, ast.FunctionDef)] + failures = sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Failure") + found += [(path, function, reason) for _, function, reason in failures] + self.assertEqual(len(found), len(clauses), found) + for (path, function, reason), (want_path, want_function, reason_start, _) in zip(found, clauses): + self.assertEqual((path, function), (want_path, want_function)) + self.assertTrue(reason.startswith(reason_start), f"{path} {function}: {reason}") + judge_clause = " ".join(main.__doc__[main.__doc__.index("a judge when"):main.__doc__.index("A usage limit")].split()) + self.assertEqual([clause for *_, clause in clauses if clause not in judge_clause], []) + + class Worktrees(unittest.TestCase): def test_lists_the_root_alone_when_git_cannot_start(self): fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")]) self.assertEqual(checkout.worktrees("/r", fake.effects()), ["/r"]) -class ReplaceFile(unittest.TestCase): - def test_removes_what_it_staged_when_the_replace_fails(self): - with tempfile.TemporaryDirectory() as root: - os.mkdir(os.path.join(root, "in-the-way")) - self.assertEqual(file_writes.replace_file(pathlib.Path(root, "in-the-way"), b"data"), Failure("Is a directory")) - self.assertEqual(os.listdir(root), ["in-the-way"]) - - if __name__ == "__main__": unittest.main() diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 8c9f0209..884221b2 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -250,17 +250,17 @@ class Checkout: return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts")) def archived(self): - """Each archived transcript's verdict, after checking the copy is named by its content hash.""" - verdicts = {} + """Each archived transcript's outcomes, after checking the copy is named by its content hash.""" + outcomes = {} for folder in (self.archive(), self.archive() / "proj", *(self.archive() / "proj").iterdir()): self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder) for copy in sorted((self.archive() / "proj").glob("*/*.jsonl")): self.test.assertEqual(copy.stem, hashlib.sha256(copy.read_bytes()).hexdigest()) - verdict = copy.with_suffix(".verdict.md") - for archived in (copy, verdict): + kept = copy.with_suffix(".outcomes.md") + for archived in (copy, kept): self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600) - verdicts[copy.read_text()] = verdict.read_text() - return verdicts + outcomes[copy.read_text()] = kept.read_text() + return outcomes def argument(call, flag): @@ -670,14 +670,15 @@ class Reload(unittest.TestCase): worker(append=["loop-claude", "\ndef\n"]), judge(), worker(replace=["loop-claude", "\ndef\n", "\n# edited\n"]), judge(), worker(append=["loop_claude/nested/edited.py", "# edited\n"]), judge(), + worker(append=["file_writes.py", "# edited\n"]), judge(), worker(), ]) self.assertEqual(run.code, 130) - self.assertEqual(run.roles(), ["worker", "judge"] * 4) + self.assertEqual(run.roles(), ["worker", "judge"] * 5) self.assertIn("keeping the running script", run.stderr) reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]] - self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK} for cycle in (2, 3)]) - self.assertIn("=== cycle 4 ===", run.stdout) + self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK} for cycle in (2, 3, 4)]) + self.assertIn("=== cycle 5 ===", run.stdout) outside = checkout.temp / "outside" outside.mkdir() diff --git a/bin/test_markdown_sections.py b/bin/test_markdown_sections.py new file mode 100644 index 00000000..3f5aa545 --- /dev/null +++ b/bin/test_markdown_sections.py @@ -0,0 +1,22 @@ +import pathlib +import sys +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +import markdown_sections + + +class Sections(unittest.TestCase): + def test_keeps_every_headed_section_with_its_bodies(self): + text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" + self.assertEqual(markdown_sections.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) + + def test_closes_a_fence_only_on_its_own_marker(self): + text = "## Goals\n````md\n~~~\n## Quoted\n```\n````\n ~~~\n## Also quoted\n ~~~\n1. one\n## Audience\nme\n" + self.assertEqual(list(markdown_sections.sections(text)), ["Goals", "Audience"]) + self.assertEqual(list(markdown_sections.sections("```\nquoted:\n```python\n## Inside\n```\n## Goals\n1. one\n")), ["Goals"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index c7430f75..52d44512 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -7,7 +7,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude.failure import Failure +from failure import Failure import rank_todo from test_python_floor import ROOT diff --git a/docs/decisions.md b/docs/decisions.md index 4f54f378..831c84fe 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -34,7 +34,9 @@ 2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The same seats on `rebuild` scored 7.5, 6.63, 6.88, 6.5, 7.0 at 37edc9a, later that day, 7.5, 6.75, 6.88, 6.75, 7.0 at 7f9de5c, 7.38, 6.25, 6.88, 6.75, 6.88 at 2f9ab2f on 2026-09-29, Locality lowest again and every seat naming the reload state and the two retry counters, and 7.5, 7.0, 7.25, 6.75, 7.13 at 2c74bbc later that day, Self-sufficiency lowest and every seat naming the round's definition split across larv-review's two files, and 7.38, 6.75, 7.25, 6.5, 6.88 at 8585257 on 2026-10-01, lowering every dimension but Shape, and the overall, Self-sufficiency lowest and every seat naming larv-review ยง3's round rules; the places it named under Self-sufficiency and Locality are filed in `todo.md` under 0.1.0, and a later scoring run may not score any dimension or the overall below its best run on `rebuild`, 2026-10-01, lilleman. `rebuild` merged into main under the floor at 8585257's scores, 2026-10-01, lilleman. The 2026-10-01 run on PR #182 (the loop state machine) scored 7.5, 6.5, 6.88, 6.25, 6.38; lilleman shipped that PR under the floor and below `rebuild`'s best run the same day, its places filed in `todo.md` under 0.1.0. The 2026-10-02 run on PR #187 (`loop_claude`'s names, the exit contract) scored 7.75, 7.25, 7.38, 6.88, 7.25 at 70362d0, every seat naming larv-review ยง3 under Self-sufficiency, and 7.63, 7.13, 7.38, 7.0, 7.13 at 1971dba later that day, the first run at the floor, with no dimension or the overall below its best run on `rebuild`. The 2026-10-02 runs on PR #191 (the status line in Python) scored 7.5, 7.0, 7.13, 6.88, 7.13; 7.25, 6.75, 7.25, 6.88, 7.0; 7.63, 6.88, 7.38, 7.0, 7.13; and 7.63, 7.0, 7.25, 6.75, 7.25. Every seat rated the status line easy. The places they named under Locality and Self-sufficiency are filed in `todo.md` under 0.1.0, except `entries.py`'s heuristics over Claude Code's transcript format, which the seats scored as the problem's own difficulty. lilleman decided the same day to ship that PR under the floor. The 2026-10-02 runs on PR #194 (each cycle's transcript archived) scored 8.0, 7.25, 7.38, 7.13, 7.5 at 6ccd5b1 and 7.75, 7.13, 7.25, 7.0, 7.25 at d104ea0, both at the floor, every seat naming `archive` as the unit it would least want to modify. On 2026-10-02, applying `todo.md`'s bar deleted every place these scoring runs filed except larv-review ยง3's round rules and the Claude Code flags no comment explained. The 2026-10-02 runs on PR #196 (`todo.md` as one scored table) scored 7.63, 6.88, 7.25, 6.88, 7.13 at c0dba66; 7.5, 6.88, 7.13, 6.75, 7.0 at 798dfd7; and 7.5, 7.0, 7.0, 6.75, 7.0 at b712076. Under Self-sufficiency, every seat named larv-review ยง3 and the agents, which a reader follows only with `CLAUDE.md` open. lilleman decided the same day to ship that PR under the floor; the place filed was larv-review ยง3's round rules. The 2026-10-02 run on PR #198 (a usage limit waited out) scored 7.63, 6.88, 7.38, 6.75, 7.13 at 8e85033. Under Self-sufficiency, every seat named larv-review ยง3; under Locality, they named `archive`'s invariants spread over `session.py` and `run.py`, `rank_todo.py` reaching into `premises.sections`, and `stopped` comparing reason strings, each under `todo.md`'s bar and not filed. lilleman decided the same day to ship that PR under the floor. -The 2026-10-03 runs on PR #202 (the judge reads the project's records) scored 7.75, 7.13, 7.25, 7.0, 7.25 in the first round and 7.5, 7.0, 7.0, 6.75, 7.0 in the eighth; between them a dimension moved by up to 0.4 on near-identical code. Under Self-sufficiency every seat named larv-review ยง3 and the agents leaning on `CLAUDE.md`, the Claude Code flags left unexplained, and the judge's contract spread over its prompt, schema, parser and `--help`; under Shape, that "record", "verdict" and "judge" each name two things, and that `loop_claude/` holds modules `rank_todo.py` also uses. lilleman decided the same day to ship that PR under the floor and to fix those places next: larv-review ยง3 and `todo.md` items 42, 43 and 44. The flags, and the words the judge's prompt left undefined (chunk, plan, a release ready to cut), were explained on 2026-10-03, and larv-review ยง3 was made readable on its own the same day. Valid until the next scoring run, which uses the same four seats. +The 2026-10-03 runs on PR #202 (the judge reads the project's records) scored 7.75, 7.13, 7.25, 7.0, 7.25 in the first round and 7.5, 7.0, 7.0, 6.75, 7.0 in the eighth; between them a dimension moved by up to 0.4 on near-identical code. Under Self-sufficiency every seat named larv-review ยง3 and the agents leaning on `CLAUDE.md`, the Claude Code flags left unexplained, and the judge's contract spread over its prompt, schema, parser and `--help`; under Shape, that "record", "verdict" and "judge" each name two things, and that `loop_claude/` holds modules `rank_todo.py` also uses. lilleman decided the same day to ship that PR under the floor and to fix those places next; all were fixed on 2026-10-03. + +The 2026-10-03 runs on PR #208 (the judge's contract in one home, the shared modules out of `loop_claude/`) scored 7.5, 7.25, 7.0, 6.88, 7.0; 7.5, 7.0, 6.88, 7.25, 7.0; and 7.5, 7.0, 7.13, 6.63, 6.88, each overall below PR #202's first round's 7.25. Under Self-sufficiency every seat named the skills leaning on `CLAUDE.md`; the worst was the chain from larv-review's comprehension floor through the panel skill and its scoring-run file to `AGENTS.md`. Under Shape, they named the flat `bin/` and larv-review ยง3 counting rounds by a pass name the table does not fix. lilleman decided the same day to ship that PR under the floor; the places above `todo.md`'s bar are filed there. Valid until the next scoring run, which uses the same four seats. ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes @@ -48,13 +50,13 @@ The 2026-10-03 runs on PR #202 (the judge reads the project's records) scored 7. 2026-09-30, lilleman. Serves goal 4: no human reads an unattended chunk before it merges, so every change it makes, a nit's wording included, is reviewed. In the 2026-09-30 bench this cost four of nine rounds in one run and drove two passes to the round cap. Valid while a pass is the only reader of a fix before merge. -## review: a pass skips only on a record older than the chunk +## review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began -2026-09-30, lilleman. Serves goal 4: a record the chunk writes is the chunk's own unreviewed decision, and an unattended run has no human to catch it. Valid while a pass is the only reader of a chunk before merge. +2026-09-30, lilleman. Serves goal 4: a decision the chunk writes is the chunk's own and unreviewed, and an unattended run has no human to catch it. Valid while a pass is the only reader of a chunk before merge. ## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop -2026-09-28, lilleman. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with the verdict beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. +2026-09-28, lilleman. Serves goals 2 and 4: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. ## loop-claude: a `claude` that cannot start is a failed worker run, retried diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index 52eece06..58564ae1 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -41,12 +41,12 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod Give a reviewer without Bash the branch diff and `git ls-files`'s output in its prompt: some harnesses grant it Read alone. -**Record, then ask** โ€” for the architecture pass and the full scan: +**Precedent, then ask** โ€” for the architecture pass and the full scan: -- **Skip.** A record is a `docs/decisions.md` entry, or a planning item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite the record. -- **Departure.** A change that departs from the record is unreviewed, however thorough the record is. +- **Skip.** A precedent is a `docs/decisions.md` entry, or a plan item crediting the pass, that the repo held before the chunk began. Where one holds the decision this change executes, skip the pass and cite that entry or item. +- **Departure.** A change that departs from the precedent is unreviewed, however thorough the precedent is. - **Ask.** Fired and not skipped โ†’ ask the user whether to run it, with the evidence and your recommendation; no user reachable โ†’ run it. For the full scan, give the evidence and your recommendation, then launch it: the plugin asks the user to confirm its cost, and that prompt is the ask. -- **Audit.** A record or the user's no skips only the architect, never the principles audit or the scoring run: no record older than the chunk checked the code it writes. +- **Audit.** A precedent or the user's no skips only the architect, never the principles audit or the scoring run: no precedent checked the code this chunk writes. **Round cap.** @@ -67,10 +67,10 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its **Findings.** A reviewer rates each finding ๐Ÿ”ด must fix, ๐ŸŸก should fix, ๐ŸŸข nit, โ“ question, or ๐Ÿ”€ escalation naming the reviewer whose concern it is. - **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/CLAUDE.md` โ†’ "Todo items". A ๐Ÿ”ด is marked `defect`. A ๐ŸŸก against a file under `~/.claude/principles/` is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". -- **Goal or decision.** A fix that would change a goal, or a decision the repo held before the chunk began, is asked; no user reachable โ†’ filed, marked `question`, the goal or decision left as is. +- **Goal or decision.** A fix that would change a goal, or a `docs/decisions.md` entry the repo held before the chunk began, is asked; no user reachable โ†’ filed, marked `question`, the goal or decision left as is. - **๐Ÿ”ด.** A ๐Ÿ”ด is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/CLAUDE.md` โ†’ "Decisions: one home, each linked to a goal or a technical principle": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined. - **๐ŸŸก.** A ๐ŸŸก is fixed, shown factually wrong like a ๐Ÿ”ด, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` โ†’ "Working loop", "Ask, don't guess"; no user reachable โ†’ fix. Never drop one silently, and never decline one for convenience or the size of the fix. -- **๐ŸŸข and โ“.** A ๐ŸŸข or โ“ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test or a record settles it, and quote what in the summary. A โ“ only the user can answer is asked; no user reachable โ†’ filed, marked `question`. +- **๐ŸŸข and โ“.** A ๐ŸŸข or โ“ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test, a goal or a decision the repo held before the chunk began settles it, and quote what in the summary. A โ“ only the user can answer is asked; no user reachable โ†’ filed, marked `question`. - **๐Ÿ”€.** A ๐Ÿ”€ runs the named reviewer's pass once the current pass is done. - **Other scales.** Other reviewers map onto this scale: `/security-review`'s HIGH is ๐Ÿ”ด, MEDIUM ๐ŸŸก, LOW ๐ŸŸข; what a forge's auto-reviewer marks blocking is ๐Ÿ”ด. A finding of theirs repeating one declined or filed does not stand. diff --git a/todo.md b/todo.md index 2920e683..84b75543 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 9` -`Next ID = 46` +`Next ID = 57` | Goal | W | |---|---| @@ -25,16 +25,24 @@ | ID | Release | Exempt | Item | R | S | A | G | Goals | Score | |---|---|---|---|---|---|---|---|---|---| | 1 | 0.1.0 | question | **Say in README โ†’ Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 8 | 9 | 2, 3 | 27.8 | -| 42 | 0.1.0 | decision | **Give the judge's contract one home, so its prompt, reply schema, parser and `--help` cannot drift apart.** | 3 | 4 | 9 | 9 | 4, 4.1 | 26.1 | -| 44 | 0.1.0 | decision | **Move the modules `rank_todo.py` shares out from under `loop_claude/`, keeping them inside reload's fingerprint.** | 2 | 2 | 8 | 8 | 4, 4.1 | 24.2 | -| 43 | 0.1.0 | decision | **Give "record", "verdict" and "judge" one meaning each across loop-claude, larv-review and workflow-bench.** | 2 | 3 | 8 | 8 | 4, 4.1 | 24.0 | +| 47 | 0.1.0 | | **Archive the judge's evidence with each verdict, so a wrong finish shows what it rested on.** | 1 | 1 | 6 | 6 | 2, 4 | 21.4 | +| 56 | 0.1.0 | | **Have the judge rule a chunk finished only once every answer the human typed in it is recorded in `README.md`, `AGENTS.md` or `docs/decisions.md`.** | 3 | 3 | 7 | 8 | 4, 4.2 | 21.0 | +| 46 | 0.1.0 | question | **Let the judge read and quote `~/.claude/CLAUDE.md` beside the project's records.** | 4 | 3 | 7 | 8 | 4, 4.2 | 20.0 | +| 54 | 0.1.0 | | **Give each review pass a fixed name in larv-review ยง3's table, and count its rounds by that name.** | 2 | 1 | 6 | 6 | 4, 4.1 | 17.8 | +| 55 | 0.1.0 | | **Make larv-review's comprehension floor readable without opening the panel skill, its scoring-run file and `AGENTS.md` in turn.** | 2 | 3 | 5 | 6 | 4, 4.1 | 15.3 | +| 48 | 0.1.0 | | **Stamp each archived outcome with its UTC time.** | 1 | 1 | 4 | 4 | 2 | 13.9 | | 23 | 0.1.0 | | **Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers.** | 3 | 4 | 7 | 8 | 4.4 | 13.5 | | 21 | 0.1.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 6 | 7 | 4.3 | 12.9 | +| 49 | 0.1.0 | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 2 | 5 | 6 | 4.3 | 12.5 | +| 53 | 0.1.0 | | **Cut the comprehension-floor decision to its standing rule and each call to ship under the floor.** | 1 | 2 | 4 | 5 | 4.1 | 12.1 | | 12 | 0.1.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 4 | 6 | 4.1 | 11.7 | | 5 | 0.1.0 | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 5 | 6 | 4.1 | 10.5 | | 4 | 0.1.0 | | **Name each chunk's archive folder by the chunk's start time, so `/` lists chunks in the order they ran.** | 3 | 2 | 4 | 3 | 2 | 9.8 | +| 50 | 0.1.0 | principle | **Grant the bench's runs only the tools a review needs, in place of skipping every permission.** | 2 | 2 | 3 | 4 | 3 | 9.7 | | 29 | 0.1.0 | | **Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.** | 2 | 2 | 3 | 5 | 4.1, 4.4 | 9.1 | +| 52 | 0.1.0 | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 6 | 6 | 3 | 5 | 1 | 8.5 | | 6 | 0.1.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 4 | 5 | 4.1 | 7.4 | +| 51 | 0.1.0 | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 3 | 5 | 3 | 5 | 4.1 | 7.4 | ## Details @@ -44,17 +52,31 @@ It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost 2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest. -### 42. Give the judge's contract one home, so its prompt, reply schema, parser and `--help` cannot drift apart. +The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 2). -The 2026-10-03 scoring runs on PR #202 named it under Self-sufficiency and Locality: what a reply means is stated in `JUDGE_RULES`, the `Reply` field descriptions, `verdict_from`'s precedence, `transition`'s cap and the `--help` docstring, and the repeated-question rule lives only in the prompt. Derive each from one definition, or tie it to that definition with a test; the interrupt wording moves out of `transition` into `run.ask`. +### 47. Archive the judge's evidence with each verdict, so a wrong finish shows what it rested on. -### 44. Move the modules `rank_todo.py` shares out from under `loop_claude/`, keeping them inside reload's fingerprint. +The judge runs without session persistence, and `close` and `ask` archive only the verdict and the question. A wrong `finished` deletes the session, and nothing then shows the passage the judge quoted. -Named under Shape by the same runs: `failure.py`, `file_writes.py` and `markdown_sections.py` sit in loop-claude's package because `reload.fingerprint` hashes only `loop_claude/**/*.py`, and nothing at the package says a second tool depends on them. Widen the fingerprint to a named shared package. +### 56. Have the judge rule a chunk finished only once every answer the human typed in it is recorded in `README.md`, `AGENTS.md` or `docs/decisions.md`. -### 43. Give "record", "verdict" and "judge" one meaning each across loop-claude, larv-review and workflow-bench. +2026-10-03, the human, answering the principles audit on PR #208: a finished chunk's session is deleted, and its `[human]` answers with it, so an answer recorded nowhere is asked again in a later chunk (goal 4.2). -Named under Shape by the same runs: loop-claude's records are `AGENTS.md` and `docs/decisions.md`, larv-review's "record" is a decision-log entry or plan item older than the chunk; `Verdict` is the judge's ruling and `.verdict.md` also holds stop reasons; `cycle/judge.py` and `workflow-bench/judge.py` are different judges. +### 46. Let the judge read and quote `~/.claude/CLAUDE.md` beside the project's records. + +The architecture pass's principles audit against README.md's goals, on PR #208, rated the gap ๐Ÿ”ด against goals 4 and 4.2: the worker follows `CLAUDE.md`, but the judge sees only the premises, `AGENTS.md` and `docs/decisions.md`. A choice `CLAUDE.md` settles therefore reads to the judge as one nothing discriminates, and a question it answers goes to the human. The fix revises the decision "loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md` and `docs/decisions.md`", so the human decides it. + +### 54. Give each review pass a fixed name in larv-review ยง3's table, and count its rounds by that name. + +Named under Shape by the PR #208 scoring runs: "Count" keys on `Answer round :`, but the table's first column names the architecture pass with a whole sentence, so a run can spell one pass two ways and restart its count. + +### 55. Make larv-review's comprehension floor readable without opening the panel skill, its scoring-run file and `AGENTS.md` in turn. + +Named under Self-sufficiency by the PR #208 scoring runs, as the worst of the skills' leans on other documents. + +### 48. Stamp each archived outcome with its UTC time. + +After an overnight exit 1, `.outcomes.md` holds each outcome without saying when it happened. ### 23. Launch a principles auditor only for a principles file the project shows applies, and rerun only the reviewer whose finding a fix answers. @@ -66,6 +88,14 @@ Claude Code rewrites `"model"` in this tracked file whenever a model is picked, Every write Claude Code makes to the file rewrites `"model"`, `claude plugin install` included: Claude Code 2.1.288 turned `"opus"` into `"opus[1m]"`. Each write also puts the keys back in Claude Code's own order, so a sorted file stays sorted only until the next write. +### 49. Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`. + +DRY, in `principles/technical-principles.md`: the list is copied by hand, and sessions work from the copy. + +### 53. Cut the comprehension-floor decision to its standing rule and each call to ship under the floor. + +Its 2026-09-27 paragraph lists every scoring run's five scores, and buries among them the rule that no later scoring run may score below its best run on `rebuild`; the scores live in the PRs and git history. + ### 12. Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough. The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word. @@ -78,10 +108,22 @@ The key names the project's session, archive folder and models entry. `project_k Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. +### 50. Grant the bench's runs only the tools a review needs, in place of skipping every permission. + +"Always grant explicit access to data", in `principles/technical-principles.md`: `workflow-bench/bench.py` starts claude with `--dangerously-skip-permissions`, and no rule confines it to a sandbox, so a run on the host reaches the host's credentials and other checkouts. + ### 29. Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter. State that in `CLAUDE.md`'s goals-and-audience rule, and have larv-review's comprehension floor name the contributor as the reader it serves. The floor then gates every chunk while the contributor stands, and a project that drops them skips it. +### 52. Record why this checkout lives in Claude Code's own directory, or move it out and link it in. + +"One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory. + ### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay. Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. + +### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints. + +"Functional core, imperative shell", in `principles/technical-principles.md`: `archive`, `trust`, `retried`, the worker, `interrupt` and `model_choice` print to stderr themselves, and the tests swap the global stream. diff --git a/workflow-bench/bench.py b/workflow-bench/bench.py index 3c127b28..25ab0920 100755 --- a/workflow-bench/bench.py +++ b/workflow-bench/bench.py @@ -1,5 +1,18 @@ #!/usr/bin/env python3 -"""Run larv-review bench runs: BENCH_SOURCES=-main clones, their -main.md reports and comparison.md> bench.py -- ...""" +"""Run larv-review bench runs: BENCH_SOURCES= bench.py -- ... + +The 2026-09-30 bench ran two versions of larv-review, main and rebuild. Each reviewed four real chunks, +the cases, three times; compare.py then rules whether each version reviews at least as well as the +other. The bench's inputs are untracked: +- versions// beside this script: a copy of ~/.claude at that version, which each run reads + in place of ~/.claude (run-prompt.md). +- $BENCH_SOURCES/-main/: a clone of the case's project; CASES names the chunk's base and head + commits in it. +- $BENCH_SOURCES/-main.md: main's own review of the case, run on 2026-09-29. +- $BENCH_SOURCES/comparison.md: what each case's real review found, one table row per issue, its ID + led by the case's letter in compare.py's PREFIX. +Each run leaves its clone in /, its report in .md and its claude stream in logs/. +""" import concurrent.futures import json import os diff --git a/workflow-bench/judge-prompt.md b/workflow-bench/compare-prompt.md similarity index 83% rename from workflow-bench/judge-prompt.md rename to workflow-bench/compare-prompt.md index 5f2d83e8..2b015c2c 100644 --- a/workflow-bench/judge-prompt.md +++ b/workflow-bench/compare-prompt.md @@ -1,4 +1,4 @@ -You judge a bench of two code-review processes, A and B, on one real chunk of work. Each process reviewed the same chunk three times, independently: runs A1โ€“A3 and B1โ€“B3. Rule whether B reviews at least as well as A, and whether A reviews at least as well as B. +You compare two code-review processes, A and B, on one real chunk of work. Each process reviewed the same chunk three times, independently: runs A1โ€“A3 and B1โ€“B3. Rule whether B reviews at least as well as A, and whether A reviews at least as well as B. Everything is under `{dir}`; read nothing outside it: @@ -7,7 +7,7 @@ Everything is under `{dir}`; read nothing outside it: - `/report.md`: the run's own account of its passes, findings and outcomes. Its claims are not evidence. - `/fixes.diff`: what the run actually changed. This is the evidence. -Judge each run on: +Rate each run on: 1. **Truth coverage**: for each truth issue, caught and fixed โœ”, partly โ—, or missed โœ˜, checked against `fixes.diff`. A filed or declined issue with a sound reason counts โ—. 2. **Other real defects**: a finding the truth lacks that is a real defect in the chunk, fixed or filed. diff --git a/workflow-bench/judge.py b/workflow-bench/compare.py similarity index 79% rename from workflow-bench/judge.py rename to workflow-bench/compare.py index 847aa3fa..98435398 100755 --- a/workflow-bench/judge.py +++ b/workflow-bench/compare.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Blind-judge each case's six runs: BENCH_SOURCES= judge.py ...""" +"""Blind-compare each case's six runs: BENCH_SOURCES= compare.py ...""" import concurrent.futures import json import pathlib @@ -29,11 +29,12 @@ def runs(case, version): def blind(text): + """The report, with VERSION_DIR in place of every name that tells which version wrote it.""" return re.sub(r"\S*versions/(main|rebuild)\S*|\b(main|rebuild)\b(?=[`\s]*(process|version))", "VERSION_DIR", text) def prepare(case): - folder = BENCH / "judge" / case + folder = BENCH / "compare" / case if folder.exists(): shutil.rmtree(folder) folder.mkdir(parents=True) @@ -53,15 +54,15 @@ def prepare(case): (run / "report.md").write_text(blind(report.read_text())) (run / "fixes.diff").write_text(bench.git(clone, "diff", head, "chunk") + "\n") mapping[f"{label}{n}"] = str(report) - (BENCH / "judge" / f"{case}.mapping.json").write_text(json.dumps(mapping, indent="\t") + "\n") + (BENCH / "compare" / f"{case}.mapping.json").write_text(json.dumps(mapping, indent="\t") + "\n") return folder -def judge(case): +def compare(case): folder = prepare(case) - ruling = BENCH / "judge" / f"{case}.ruling.md" - prompt = (BENCH / "judge-prompt.md").read_text().format(dir=folder, ruling=ruling) - with (BENCH / "logs" / f"judge-{case}.jsonl").open("w") as out: + ruling = BENCH / "compare" / f"{case}.ruling.md" + prompt = (BENCH / "compare-prompt.md").read_text().format(dir=folder, ruling=ruling) + with (BENCH / "logs" / f"compare-{case}.jsonl").open("w") as out: subprocess.run( ["claude", "-p", prompt, "--model", "claude-opus-5-5", "--allowedTools", "Read,Grep,Glob,Write", "--output-format", "stream-json", "--verbose"], cwd=folder, stdout=out, stderr=subprocess.STDOUT) @@ -70,5 +71,5 @@ def judge(case): if __name__ == "__main__": with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: - for result in pool.map(judge, sys.argv[1:]): + for result in pool.map(compare, sys.argv[1:]): print(result, flush=True)