diff --git a/bin/claude_code/transcript.py b/bin/claude_code/transcript.py index 572a5b7d..a6e05e69 100644 --- a/bin/claude_code/transcript.py +++ b/bin/claude_code/transcript.py @@ -60,6 +60,17 @@ def render(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | No return "\n\n".join(lines) +def human_answers(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | None]) -> list[str]: + """Each answer the human typed, whole, as render shows it on a [human] line, latest last.""" + found = [] + for entry in entries: + if isinstance(entry, HumanTurn): + found.append(entry.text) + elif isinstance(entry, LoopPrompt) and (typed := typed_answer(entry.text)): + found.append(typed.answer) + return found + + def assistant_lines(turn: AssistantTurn) -> list[str]: """The turn's text and tool calls as the judge reads them.""" return [line for part in turn.parts if (line := part_line(part, JUDGED_TOOL_INPUT))] diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index cbf1b954..e80fbef0 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -10,7 +10,7 @@ from claude_code.entries import Entry, structured_output from loop_claude import escalation_mark from failure import Failure from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict -from claude_code.transcript import plain, verbatim +from claude_code.transcript import human_answers, plain, verbatim from loop_claude.cycle.retry import retried from model_routing.ladder import Rung from loop_claude.stop import Stop @@ -78,8 +78,8 @@ class Reply: question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."}) # True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed. release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."}) - # Counts the human's reversals of the worker's own choices, the counter-signal of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…`, its entry of 2026-11-08; score-outcomes lists them per chunk. - reversed: str = dataclasses.field(metadata={"description": "The latest [human] line that overrides a choice the worker took itself on its own recommendation and recorded with its reason, quoted verbatim, without elisions. Empty where none does; a line that answers a question the worker left open doesn't override anything."}) + # Finds the answer that reverses a choice the worker took on its own recommendation. score-outcomes counts these answers per chunk: they are the counter-signal the 2026-11-08 entry of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…` stays valid by. + reversed: str = dataclasses.field(metadata={"description": "The latest [human] line that overrides a choice the worker took on its own recommendation and recorded with its reason, quoted verbatim, without elisions. Empty where none does; a line that answers a question the worker left open doesn't override anything."}) REPLY_TYPES = typing.get_type_hints(Reply) @@ -106,6 +106,8 @@ class Grounds(typing.NamedTuple): after_mark: str # README.md's premises and the records. quotable: str + # Each answer the human typed, whole, latest last (transcript.human_answers). + typed: tuple[str, ...] = () class Brief(typing.NamedTuple): @@ -176,13 +178,13 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects checked = quotes_checked(verdict, grounds) if isinstance(checked, Failure): return Rejected(checked.reason, replied, cost) - return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.shown))) + return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.typed))) -def reversal_of(output: object, shown: str) -> str: - """The reply's reversed quote where the transcript holds it verbatim; empty otherwise. verdict_from has checked the field is a str.""" +def reversal_of(output: object, typed: tuple[str, ...]) -> str: + """The latest answer the human typed that holds the reply's reversed quote, whole, so the same answer archives the same way however the judge quotes it; empty where none does. verdict_from has checked the field is a str.""" quote = output.get("reversed") if isinstance(output, dict) else None - return quote if isinstance(quote, str) and verbatim(quote, shown) else "" + return next((answer for answer in reversed(typed) if isinstance(quote, str) and verbatim(quote, answer)), "") def cost_of(reply: dict) -> float: @@ -201,6 +203,7 @@ def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict | Failure: | its left_open | answered_before and the question | the interrupt becomes an Unfinished that quotes answered_before back to the worker | re_ask_checked | | a quoted answer | grounds.quotable | the question goes to the human as an interrupt, which keeps the escalation the answer carried | answer_checked | | the escalation | grounds.shown and grounds.after_mark | the escalation is dropped, so the worker's rung holds | escalation_mark.checked | + | the reversal | one of grounds.typed | the reversal is dropped; run_judge, after this check | reversal_of | Only a misquoted evidence fails. A Failure for any other would exit an unattended loop, so each changes the verdict instead. """ @@ -262,5 +265,6 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]: shown=shown, after_mark=escalation_mark.after_mark(brief.entries, brief.escalated_at), quotable=f"{brief.premises}\n\n{brief.records}", + typed=tuple(human_answers(brief.entries, typed_answer)), ) return f"{head}{shown}\n\n{JUDGE_RULES}", grounds \ No newline at end of file diff --git a/bin/loop_claude/cycle/spend.py b/bin/loop_claude/cycle/spend.py index 349c42db..e1db335a 100644 --- a/bin/loop_claude/cycle/spend.py +++ b/bin/loop_claude/cycle/spend.py @@ -1,4 +1,4 @@ -"""What a stretch of the chunk's work spent, in raw tokens by model and kind, which the archive records beside each verdict, interrupt and quoted answer: docs/decisions.md → `loop-claude: each verdict records the setup, the spend and the reversals…`. +"""What a stretch of the chunk's work spent, in raw tokens by model and kind, which the archive records beside each verdict, interrupt and quoted answer: docs/decisions.md → `loop-claude: each verdict records the claude-config release and commit that ran it…`. A stretch runs from the previous outcome that recorded a spend, or from the chunk's start, to the ruling. It counts the worker's main thread, each subagent and the judge run that ruled, each message once. Dollars are left to be derived from the model and the tokens, at the prices recorded beside them. """ @@ -54,11 +54,12 @@ def moment(stamp: str) -> datetime.datetime: return datetime.datetime.fromisoformat(stamp) -# The outcome's stamp runs to the second, so a message written in the second it was stamped, before it, counts again; the judge runs for seconds after the worker exits, so none is. +# An outcome's stamp runs to the second, so a message written earlier in that second would count in both stretches. In practice none is, since the judge runs for seconds after the worker's last message. def later(timestamp: str, start: datetime.datetime) -> bool: + """Whether timestamp is after start; False where it is no time, or names no time zone to compare by.""" try: return moment(timestamp) > start - except ValueError: + except (TypeError, ValueError): return False diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index af7f7dba..1b791e09 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -431,7 +431,7 @@ Worker: {OFF_LADDER} new = {"type": "assistant", "timestamp": "2026-09-21T14:13:21Z", "message": {"id": "new", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 5}}} transcript.write_text("\n".join(json.dumps(entry) for entry in [{"type": "queue-operation", "timestamp": "2026-09-21T14:00:00Z"}, old, human("No, keep the old name."), new]) + "\n") with contextlib.redirect_stderr(io.StringIO()): - self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", record=outcomes.Record("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) + self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW)) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished", reversed="No, keep the old name.")]) run.run_cycle(self.cycle(fake)) latest = max(self.archived_outcomes(), key=len) @@ -1699,13 +1699,14 @@ List prices in dollars per million tokens of input, cache write 5m, cache write self.assertEqual(spend.spent_block("", {("judge", "unpriced"): Tokens(input=6)}), "Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:\n- judge, unpriced: 6, 0, 0, 0, 0") self.assertEqual(spend.spent_block("", {}), "") - def test_keeps_the_reversal_the_judge_quotes_verbatim_and_its_tokens(self): - shown = "[human] No, keep the old name.\nworking" - for quoted, kept in [("No, keep the old name.", "No, keep the old name."), ("No, keep the name.", "")]: + def test_keeps_the_whole_typed_answer_that_holds_the_judges_quote_and_its_tokens(self): + shown = "[human] Use A.\n[human] No, keep the old name. Use X.\nworking: keep the new name" + typed = ("Use A.", "No, keep the old name. Use X.") + for quoted, kept in [("No, keep the old name. Use X.", "No, keep the old name. Use X."), ("keep the old name", "No, keep the old name. Use X."), ("Use", "No, keep the old name. Use X."), ("keep the new name", ""), ("No, keep the name.", "")]: with self.subTest(quoted=quoted): answer = json.loads(judged("unfinished", reversed=quoted).stdout) fake = FakeEffects(claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 2, "output_tokens": 3}}))]) - self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds(shown, shown, ""), fake.effects()), Unfinished("working", judged=Judged(tokens=Tokens(input=2, output=3), reversed=kept))) + self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds(shown, shown, "", typed), fake.effects()), Unfinished("working", judged=Judged(tokens=Tokens(input=2, output=3), reversed=kept))) class SetupVersion(unittest.TestCase): @@ -1725,6 +1726,12 @@ class SetupVersion(unittest.TestCase): head = git("rev-parse", "HEAD", cwd=root).strip() self.assertEqual(main.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})") + def test_names_why_git_cannot_name_the_commit_on_one_line(self): + def fake_git(*args, cwd=None): + return Failure("fatal: bad HEAD\nhint: repair it") if args[0] == "rev-parse" else "v0.1.0\n" + + self.assertEqual(main.setup_version(pathlib.Path("/r"), fake_git), "unknown: fatal: bad HEAD hint: repair it") + class Grounded(unittest.TestCase): def test_every_verdict_must_quote_the_transcript(self): @@ -2032,10 +2039,10 @@ class ExitContract(unittest.TestCase): ("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read), ("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"), ("cycle/run.py", "rule", "1", "entries.reason", read), - ("cycle/run.py", "rule", "1", "record.reason", read), + ("cycle/run.py", "rule", "1", "annotation.reason", read), ("cycle/run.py", "rule", "1", "failure.reason", read), ("cycle/run.py", "keep_rejection", "1", "unkept.reason", read), - ("cycle/run.py", "close", "1", "record.reason", read), + ("cycle/run.py", "close", "1", "annotation.reason", read), ("cycle/run.py", "close", "1", "failure.reason", read), ("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"), ("loop/close.py", "closed_cycle", "1", "failure.reason", read),