Name loop_claude's modules and words by what each holds, explain the reload, and tie each exit-1 clause of --help to its Stop
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Claude Code's files and JSON shapes, each beside a sample, as Claude Code 2.1.284 writes them."""
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
from loop_claude.claude_code.formats import models_in
|
||||
|
||||
|
||||
def offered_models(folder: pathlib.Path) -> list[tuple[str, object]]:
|
||||
def catalog_models(folder: pathlib.Path) -> list[tuple[str, object]]:
|
||||
files = []
|
||||
for path in folder.glob("*.json"):
|
||||
try:
|
||||
@@ -12,4 +10,17 @@ def offered_models(folder: pathlib.Path) -> list[tuple[str, object]]:
|
||||
files.append(json.load(handle))
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return models_in(files)
|
||||
return newest_catalog_models(files)
|
||||
|
||||
|
||||
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
|
||||
def newest_catalog_models(files: list[object]) -> list[tuple[str, object]]:
|
||||
"""The (id, name) of each model in the newest of the parsed catalog files."""
|
||||
newest: dict = {}
|
||||
for data in files:
|
||||
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
|
||||
newest = data
|
||||
models: object = newest
|
||||
for key in ("catalog", "config", "models"):
|
||||
models = models.get(key) if isinstance(models, dict) else None
|
||||
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
"""Claude Code's JSON shapes loop-claude handles, each under a sample of it, as Claude Code 2.1.284 writes it."""
|
||||
"""Entries of Claude Code's transcripts and of its stream-json and json output."""
|
||||
import json
|
||||
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
def parse(raw: str | bytes) -> dict | None:
|
||||
try:
|
||||
@@ -94,27 +92,3 @@ def ends_stream(event: dict) -> bool:
|
||||
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
|
||||
def structured_output(stdout: str) -> object:
|
||||
return (parse(stdout) or {}).get("structured_output")
|
||||
|
||||
|
||||
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
|
||||
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
|
||||
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
|
||||
return Failure('not an object whose "projects" is an object')
|
||||
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
|
||||
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
|
||||
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
|
||||
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
|
||||
return {**config, "projects": {**projects, **marked}}, untrusted
|
||||
|
||||
|
||||
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
|
||||
def models_in(files: list[object]) -> list[tuple[str, object]]:
|
||||
"""The (id, name) of each model in the newest of the parsed catalog files."""
|
||||
newest: dict = {}
|
||||
for data in files:
|
||||
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
|
||||
newest = data
|
||||
models: object = newest
|
||||
for key in ("catalog", "config", "models"):
|
||||
models = models.get(key) if isinstance(models, dict) else None
|
||||
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
|
||||
@@ -5,7 +5,7 @@ import pathlib
|
||||
import shutil
|
||||
import uuid
|
||||
|
||||
from loop_claude.outcome import Failure
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.paths import Paths
|
||||
|
||||
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
|
||||
@@ -19,9 +19,9 @@ class Session:
|
||||
name: str
|
||||
|
||||
|
||||
def session_for(project: str, paths: Paths) -> Session:
|
||||
def session_for(project_key: str, paths: Paths) -> Session:
|
||||
# "A " is the human's cue in the session picker that the session is the loop's.
|
||||
name = f"A {project} loop-claude"
|
||||
name = f"A {project_key} loop-claude"
|
||||
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import json
|
||||
|
||||
from loop_claude.claude_code.formats import assistant_parts, human_text, parse, part_text, tool_call
|
||||
from loop_claude.outcome import Failure
|
||||
from loop_claude.claude_code.entries import assistant_parts, human_text, parse, part_text, tool_call
|
||||
from loop_claude.failure import Failure
|
||||
|
||||
JUDGED_TOOL_INPUT = 400
|
||||
|
||||
|
||||
def read(path: str) -> list[dict] | Failure:
|
||||
@@ -19,16 +21,16 @@ def human_turns(entries: list[dict]) -> int:
|
||||
def render(entries: list[dict]) -> str:
|
||||
lines = []
|
||||
for entry in entries:
|
||||
lines += [line for part in assistant_parts(entry) if (line := part_line(part))]
|
||||
lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))]
|
||||
if (text := human_text(entry)) is not None:
|
||||
lines.append("[human] " + text)
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def part_line(part: object, limit: int = 400) -> str:
|
||||
def part_line(part: object, tool_input_chars: int) -> str:
|
||||
if (text := part_text(part)) and text.strip():
|
||||
return text
|
||||
if call := tool_call(part):
|
||||
name, arguments = call
|
||||
return f"[tool {name}] {json.dumps(arguments)[:limit]}"
|
||||
return f"[tool {name}] {json.dumps(arguments)[:tool_input_chars]}"
|
||||
return ""
|
||||
|
||||
@@ -2,9 +2,8 @@ import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from loop_claude.claude_code.formats import mark_trusted
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.file_writes import replace_json
|
||||
from loop_claude.outcome import Failure
|
||||
|
||||
|
||||
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
|
||||
@@ -26,3 +25,14 @@ def trust(config: pathlib.Path, roots: list[str]) -> None:
|
||||
print(f"could not write {config}: {unwritten.reason}", file=sys.stderr)
|
||||
return
|
||||
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
|
||||
|
||||
|
||||
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
|
||||
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
|
||||
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
|
||||
return Failure('not an object whose "projects" is an object')
|
||||
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
|
||||
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
|
||||
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
|
||||
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
|
||||
return {**config, "projects": {**projects, **marked}}, untrusted
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import hashlib
|
||||
import sys
|
||||
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.file_writes import make_private, replace_file
|
||||
from loop_claude.outcome import Failure
|
||||
from loop_claude.paths import Paths
|
||||
|
||||
|
||||
def archive(project: str, path: str, note: str, paths: Paths) -> Failure | None:
|
||||
folder = paths.archive / project
|
||||
def archive(project_key: str, path: str, note: str, paths: Paths) -> Failure | None:
|
||||
folder = paths.transcript_archive / project_key
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
raw = handle.read()
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from loop_claude import human_needed
|
||||
from loop_claude.claude_code.transcript import human_turns, read
|
||||
from loop_claude.claude_code.trust import trust
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.project.checkout import checkouts
|
||||
from loop_claude.stop import Stop, needs_human, needs_terminal
|
||||
|
||||
TO = "answer the question above"
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
|
||||
|
||||
def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question: str, paths: Paths, effects: Effects) -> Stop | None:
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if stop := human_needed.off_terminal(TO, effects.on_terminal()):
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
trust(paths.claude_json, checkouts(root, effects))
|
||||
entries = read(path)
|
||||
@@ -28,4 +28,4 @@ def interrupt(root: str, session_id: uuid.UUID, model: str, path: str, question:
|
||||
entries = read(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
return None if human_turns(entries) > before else human_needed.stop(TO, "the interrupt ended with nothing typed")
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
|
||||
@@ -2,11 +2,12 @@ import dataclasses
|
||||
import json
|
||||
import typing
|
||||
|
||||
from loop_claude.claude_code.formats import structured_output
|
||||
from loop_claude.claude_code.entries import structured_output
|
||||
from loop_claude.cycle.retry import retried
|
||||
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished, Verdict
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
JUDGE_RULES = (
|
||||
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
|
||||
@@ -45,7 +46,7 @@ JUDGE_SCHEMA = {
|
||||
}
|
||||
|
||||
|
||||
def judge(root: str, task: str, premises: str, transcript: str, model: str, effects: Effects) -> Verdict | Stop:
|
||||
def judge(root: str, task: str, premises: str, rendered_transcript: str, model: str, effects: Effects) -> Verdict | Stop:
|
||||
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
|
||||
args = [
|
||||
"-p",
|
||||
@@ -56,11 +57,11 @@ def judge(root: str, task: str, premises: str, transcript: str, model: str, effe
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--tools", "",
|
||||
]
|
||||
prompt = judge_prompt(task, premises, transcript)
|
||||
return retried("judge", lambda: run_judge(root, args, prompt, transcript, effects), effects)
|
||||
prompt = judge_prompt(task, premises, rendered_transcript)
|
||||
return retried("judge", lambda: run_judge(root, args, prompt, rendered_transcript, effects), effects)
|
||||
|
||||
|
||||
def run_judge(root: str, args: list[str], prompt: str, transcript: str, effects: Effects) -> Verdict | Failure:
|
||||
def run_judge(root: str, args: list[str], prompt: str, rendered_transcript: str, effects: Effects) -> Verdict | Failure:
|
||||
try:
|
||||
proc = effects.claude(args, root, prompt)
|
||||
except OSError as failure:
|
||||
@@ -70,27 +71,27 @@ def run_judge(root: str, args: list[str], prompt: str, transcript: str, effects:
|
||||
verdict = verdict_from(structured_output(proc.stdout))
|
||||
if isinstance(verdict, Failure):
|
||||
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
|
||||
if not grounded(verdict.evidence, transcript):
|
||||
if not grounded(verdict.evidence, rendered_transcript):
|
||||
return Failure(f"the judge quoted {verdict.evidence!r}, nothing in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt) else ""))
|
||||
return verdict
|
||||
|
||||
|
||||
def judge_prompt(task: str, premises: str, transcript: str) -> str:
|
||||
def judge_prompt(task: str, premises: str, rendered_transcript: str) -> str:
|
||||
return (
|
||||
f"From README.md:\n{premises}\n\n"
|
||||
f"The task an agent was given:\n{task}\n\n"
|
||||
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
||||
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n"
|
||||
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{rendered_transcript[-40000:]}\n\n"
|
||||
f"{JUDGE_RULES}"
|
||||
)
|
||||
|
||||
|
||||
def verdict_from(output: object) -> Verdict | Failure:
|
||||
if not isinstance(output, dict):
|
||||
return Failure("the judge returned no verdict")
|
||||
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 verdict has no {name} of type {JSON_TYPES[kind]}")
|
||||
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
|
||||
# An interrupt outranks finished: the human answers before the chunk can close.
|
||||
if output["interrupt"]:
|
||||
if not output["question"].strip():
|
||||
@@ -99,9 +100,9 @@ def verdict_from(output: object) -> Verdict | Failure:
|
||||
return Finished(output["evidence"]) if output["finished"] else Unfinished(output["evidence"])
|
||||
|
||||
|
||||
def grounded(evidence: str, transcript: str) -> bool:
|
||||
def grounded(evidence: str, rendered_transcript: str) -> bool:
|
||||
quoted = plain(evidence)
|
||||
return quoted != "" and quoted in plain(transcript)
|
||||
return quoted != "" and quoted in plain(rendered_transcript)
|
||||
|
||||
|
||||
def plain(text: str) -> str:
|
||||
|
||||
@@ -2,7 +2,8 @@ import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
T = typing.TypeVar("T")
|
||||
|
||||
|
||||
@@ -10,9 +10,10 @@ from loop_claude.cycle.retry import retried
|
||||
from loop_claude.cycle.states import Active, Answered, Archived, Ended, Event, Finishing, Interrupting, Judging, Ruled, State, WorkerRan, Working, transition
|
||||
from loop_claude.cycle.worker import run_worker, worker_args
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.project.models import Models
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -21,7 +22,7 @@ class Cycle:
|
||||
models: Models
|
||||
paths: Paths
|
||||
premises: str
|
||||
project: str
|
||||
project_key: str
|
||||
root: str
|
||||
session: Session
|
||||
task: str
|
||||
@@ -69,13 +70,13 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, question: str) -> Answered | Stop:
|
||||
# The interrupt appends to this transcript, so it is archived at each question.
|
||||
if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: interrupt\n\n{question}", cycle.paths):
|
||||
if failure := archive(cycle.project_key, transcript_path, f"Task: {cycle.task}\n\nVerdict: 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 Answered()
|
||||
|
||||
|
||||
def close(cycle: Cycle, transcript_path: str) -> Archived | Stop:
|
||||
if failure := archive(cycle.project, transcript_path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths):
|
||||
if failure := archive(cycle.project_key, transcript_path, f"Task: {cycle.task}\n\nVerdict: finished", cycle.paths):
|
||||
return Stop(1, failure.reason)
|
||||
if failure := delete_session(cycle.session):
|
||||
return Stop(1, failure.reason)
|
||||
@@ -1,8 +1,10 @@
|
||||
from loop_claude.claude_code.formats import assistant_parts, ends_stream, parse
|
||||
from loop_claude.claude_code.entries import assistant_parts, ends_stream, parse
|
||||
from loop_claude.claude_code.session import Session
|
||||
from loop_claude.claude_code.transcript import part_line
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.outcome import Failure
|
||||
from loop_claude.failure import Failure
|
||||
|
||||
PRINTED_TOOL_INPUT = 160
|
||||
|
||||
|
||||
def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None:
|
||||
@@ -15,7 +17,7 @@ def run_worker(root: str, args: list[str], effects: Effects) -> Failure | None:
|
||||
event = parse(raw) or {}
|
||||
done = done or ends_stream(event)
|
||||
for part in assistant_parts(event):
|
||||
if line := part_line(part, 160):
|
||||
if line := part_line(part, PRINTED_TOOL_INPUT):
|
||||
print(line, flush=True)
|
||||
code = proc.wait()
|
||||
if code < 0:
|
||||
|
||||
@@ -27,7 +27,7 @@ class Effects:
|
||||
stream_claude: typing.Callable[[list[str], str], Streaming]
|
||||
|
||||
|
||||
class Popened:
|
||||
class StreamingClaude:
|
||||
def __init__(self, args: list[str], cwd: str) -> None:
|
||||
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
|
||||
|
||||
@@ -49,5 +49,5 @@ def system_effects() -> Effects:
|
||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||
python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True),
|
||||
sleep=time.sleep,
|
||||
stream_claude=Popened,
|
||||
stream_claude=StreamingClaude,
|
||||
)
|
||||
|
||||
@@ -5,10 +5,3 @@ import dataclasses
|
||||
class Failure:
|
||||
"""A step failed, for reason; its caller decides what follows."""
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stop:
|
||||
"""loop-claude exits with code, printing reason."""
|
||||
code: int
|
||||
reason: str
|
||||
@@ -3,7 +3,7 @@ import os
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.outcome import Failure
|
||||
from loop_claude.failure import Failure
|
||||
|
||||
|
||||
def make_private(folder: pathlib.Path) -> None:
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def stop(to: str, but: str) -> Stop:
|
||||
return Stop(2, f"the human is needed to {to}, but {but}")
|
||||
|
||||
|
||||
def off_terminal(to: str, on_terminal: bool) -> Stop | None:
|
||||
if on_terminal:
|
||||
return None
|
||||
return stop(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
|
||||
@@ -10,13 +10,22 @@ on the terminal, every worktree first marked trusted in ~/.claude.json. An unfin
|
||||
its session next cycle; the next chunk starts a fresh session.
|
||||
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
Exit 1: no task, git cannot start or finds no checkout, no premises, a models file it cannot read or
|
||||
write, claude leaves no transcript or one it cannot read or archive, a finished chunk's session it
|
||||
cannot delete, claude cannot start for an interrupt, python cannot start for a reload, a reload whose
|
||||
loop run it cannot read, or the worker or the judge fails three times running, retried a minute apart
|
||||
within the cycle. A worker fails when claude cannot start, exits non-zero, is killed, or ends without
|
||||
a result event; a judge when claude cannot start or exits non-zero, or its verdict misses or mistypes
|
||||
a field, interrupts without a question, or quotes nothing in the transcript.
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
- git cannot start or finds no checkout
|
||||
- README.md holds no premises
|
||||
- the models file cannot be read or written
|
||||
- claude leaves no transcript
|
||||
- a transcript cannot be read or archived
|
||||
- a finished chunk's session cannot be deleted
|
||||
- claude cannot start for an interrupt
|
||||
- python cannot start for a reload
|
||||
- a reload cannot read the cycle number, checkout root and task the edited script was handed, as
|
||||
when the edit changed what one script hands the next
|
||||
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
||||
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
||||
a judge when claude cannot start or exits non-zero, or its reply misses or mistypes a field,
|
||||
interrupts without a question, or quotes nothing in the transcript.
|
||||
Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a
|
||||
terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any
|
||||
open session.
|
||||
@@ -40,14 +49,14 @@ import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.claude_code.session import session_for
|
||||
from loop_claude.cycle.steps import Cycle, run_cycle
|
||||
from loop_claude.cycle.run import Cycle, run_cycle
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.loop.reload import RELOAD_FLAG, LoopRun, decode_handed, exec_if_edited, fingerprint
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.project.checkout import checkout_root, project_name
|
||||
from loop_claude.project.models import project_models
|
||||
from loop_claude.project.checkout import checkout_root, project_key
|
||||
from loop_claude.project.models import models_for
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
||||
@@ -65,8 +74,8 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
if isinstance(loop_run, Stop):
|
||||
return loop_run
|
||||
baseline = fingerprint(launcher)
|
||||
project = project_name(loop_run.root, paths.code)
|
||||
session = session_for(project, paths)
|
||||
key = project_key(loop_run.root, paths.code)
|
||||
session = session_for(key, paths)
|
||||
while True:
|
||||
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
|
||||
return stop
|
||||
@@ -74,11 +83,11 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
premises = read_premises(loop_run.root)
|
||||
if isinstance(premises, Stop):
|
||||
return premises
|
||||
models = project_models(project, paths, env, effects)
|
||||
models = models_for(key, paths, env, effects)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
print(f"\n=== cycle {loop_run.cycle_number} ===", flush=True)
|
||||
if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project=project, root=loop_run.root, session=session, task=loop_run.task)):
|
||||
if stop := run_cycle(Cycle(effects=effects, models=models, paths=paths, premises=premises, project_key=key, root=loop_run.root, session=session, task=loop_run.task)):
|
||||
return stop
|
||||
|
||||
|
||||
@@ -91,5 +100,5 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR
|
||||
return root if isinstance(root, Stop) else LoopRun(0, root, task)
|
||||
loop_run = decode_handed(argv[1], LoopRun) if len(argv) == 2 else None
|
||||
if not (loop_run and loop_run.root and loop_run.task):
|
||||
return Stop(1, f"the reload cannot read the loop run from {argv[1:]}; rerun loop-claude <task>")
|
||||
return Stop(1, f"the reload cannot read the cycle number, checkout root and task the edited script was handed in {argv[1:]}, as when the edit changed what one script hands the next; rerun loop-claude <task>")
|
||||
return loop_run
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
"""A loop runs unattended for hours, often on its own checkout: a reload puts an edit to loop-claude to work at the next cycle without the human rerunning it."""
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
@@ -6,7 +7,7 @@ import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
RELOAD_FLAG = "--reloaded"
|
||||
T = typing.TypeVar("T")
|
||||
@@ -15,7 +16,7 @@ T = typing.TypeVar("T")
|
||||
# A field change stops a running loop at its next reload: the new script rejects the old fields.
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LoopRun:
|
||||
"""One loop-claude run; a reload hands it to the new script as JSON on argv."""
|
||||
"""What a reload hands the edited script, as JSON on argv: the cycle number, checkout root and task."""
|
||||
cycle_number: int
|
||||
root: str
|
||||
task: str
|
||||
|
||||
@@ -5,21 +5,21 @@ import typing
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Paths:
|
||||
archive: pathlib.Path
|
||||
claude_code_transcripts: pathlib.Path
|
||||
claude_json: pathlib.Path
|
||||
code: pathlib.Path
|
||||
model_catalog: pathlib.Path
|
||||
models_file: pathlib.Path
|
||||
transcript_archive: pathlib.Path
|
||||
|
||||
|
||||
def paths_from(home: pathlib.Path, env: typing.Mapping[str, str]) -> Paths:
|
||||
claude = home / ".claude"
|
||||
return Paths(
|
||||
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
|
||||
claude_code_transcripts=claude / "projects",
|
||||
claude_json=home / ".claude.json",
|
||||
code=home / "code",
|
||||
model_catalog=claude / "cache" / "model-catalog",
|
||||
models_file=claude / "loop-claude-models.json",
|
||||
transcript_archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
|
||||
)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pathlib
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop:
|
||||
@@ -25,5 +25,5 @@ def checkouts(root: str, effects: Effects) -> list[str]:
|
||||
return sorted(set(found))
|
||||
|
||||
|
||||
def project_name(root: str, code: pathlib.Path) -> str:
|
||||
def project_key(root: str, code: pathlib.Path) -> str:
|
||||
return root.removeprefix(f"{code}/").lstrip("/")
|
||||
|
||||
@@ -4,12 +4,12 @@ import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_claude import human_needed
|
||||
from loop_claude.claude_code.catalog import offered_models
|
||||
from loop_claude.claude_code.catalog import catalog_models
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.file_writes import replace_json
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.stop import Stop, needs_human, needs_terminal
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -18,37 +18,37 @@ class Models:
|
||||
worker: str
|
||||
|
||||
|
||||
def project_models(project: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop:
|
||||
def models_for(project_key: str, paths: Paths, env: typing.Mapping[str, str], effects: Effects) -> Models | Stop:
|
||||
judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL")
|
||||
if judge and worker:
|
||||
return Models(judge, worker)
|
||||
chosen = project_model(project, paths, effects)
|
||||
chosen = saved_model(project_key, paths, effects)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
return Models(judge or chosen, worker or chosen)
|
||||
|
||||
|
||||
def project_model(name: str, paths: Paths, effects: Effects) -> str | Stop:
|
||||
def saved_model(project_key: str, paths: Paths, effects: Effects) -> str | Stop:
|
||||
saved = paths.models_file
|
||||
models = read_models(saved)
|
||||
models = read_models_file(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if saved_model := models.get(name):
|
||||
return saved_model
|
||||
chosen = ask_model(name, saved, paths.model_catalog, effects)
|
||||
if kept := models.get(project_key):
|
||||
return kept
|
||||
chosen = ask_for_model(project_key, saved, paths.model_catalog, effects)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
# Reread: another loop may have saved its project while this one waited on the human.
|
||||
models = read_models(saved)
|
||||
models = read_models_file(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True):
|
||||
if failure := replace_json(saved, {**models, project_key: chosen}, indent="\t", sort_keys=True):
|
||||
return Stop(1, f"could not save the model in {saved}: {failure.reason}")
|
||||
print(f"{name} runs on {chosen}", file=sys.stderr)
|
||||
print(f"{project_key} runs on {chosen}", file=sys.stderr)
|
||||
return chosen
|
||||
|
||||
|
||||
def read_models(saved: pathlib.Path) -> dict[str, str] | Stop:
|
||||
def read_models_file(saved: pathlib.Path) -> dict[str, str] | Stop:
|
||||
try:
|
||||
with open(saved, encoding="utf-8") as handle:
|
||||
models = json.load(handle)
|
||||
@@ -61,11 +61,11 @@ def read_models(saved: pathlib.Path) -> dict[str, str] | Stop:
|
||||
return models
|
||||
|
||||
|
||||
def ask_model(name: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop:
|
||||
if stop := human_needed.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"<model>\"}} into {saved}", effects.on_terminal()):
|
||||
def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, effects: Effects) -> str | Stop:
|
||||
if stop := needs_terminal(f"pick {project_key}'s model, or merge {{\"{project_key}\": \"<model>\"}} into {saved}", effects.on_terminal()):
|
||||
return stop
|
||||
offered = offered_models(folder)
|
||||
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr)
|
||||
offered = catalog_models(folder)
|
||||
print(f"\nThe model to run {project_key} on, saved in {saved}:", file=sys.stderr)
|
||||
for number, (model_id, label) in enumerate(offered, 1):
|
||||
print(f" {number}. {label} ({model_id})", file=sys.stderr)
|
||||
if not offered:
|
||||
@@ -75,7 +75,7 @@ def ask_model(name: str, saved: pathlib.Path, folder: pathlib.Path, effects: Eff
|
||||
answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ")
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
return human_needed.stop(f"pick {name}'s model", "the input ended")
|
||||
return needs_human(f"pick {project_key}'s model", "the input ended")
|
||||
picked = model_picked(answer, offered)
|
||||
if isinstance(picked, Failure):
|
||||
print(picked.reason, file=sys.stderr)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import pathlib
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
def read_premises(root: str) -> str | Stop:
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import dataclasses
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stop:
|
||||
"""loop-claude exits with code, printing reason."""
|
||||
code: int
|
||||
reason: str
|
||||
|
||||
|
||||
def needs_human(need: str, blocker: str) -> Stop:
|
||||
return Stop(2, f"the human is needed to {need}, but {blocker}")
|
||||
|
||||
|
||||
def needs_terminal(need: str, on_terminal: bool) -> Stop | None:
|
||||
if on_terminal:
|
||||
return None
|
||||
return needs_human(need, "stdin or stdout is not a terminal; rerun loop-claude on a terminal")
|
||||
Reference in New Issue
Block a user