#!/usr/bin/env python3
"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.

usage: loop-claude <task>

Run it in a project checkout whose README.md has ## Goals and ## Audience, the premises. Each cycle
a worker runs the task; a judge then reads the transcript against them. A question only the human
can answer, or a release ready to cut, is an interrupt: `claude --resume` on the terminal. An
unfinished chunk resumes the same session next cycle; a finished one starts a fresh session. Cycles
continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md, "Vocabulary".

Exit 1: no task, no premises, claude leaves no transcript, or the worker or the judge fails three
times running, a verdict missing a field or quoting nothing in the transcript being a judge failure.
Exit 2: the human is needed and stdin or stdout is not a terminal, or the interrupt ended without
them typing anything. Rerunning resumes the session after either exit. Before an interrupt every
worktree is marked trusted in ~/.claude.json.

Each project has one session, "A ~/code/<path> auto-mode" (the absolute path outside ~/code),
deleted when the chunk finishes. Its transcript is archived under $AUTO_MODE_TRANSCRIPTS (default
~/.claude/auto-mode-transcripts/<path>/) whenever the human is asked and when the chunk finishes.
JUDGE_MODEL and WORKER_MODEL override the model the project's Claude Code settings pick. A change to
this file takes effect at the next cycle boundary, once the new file answers --help.

Claude Code internals this rests on, observed on 2.1.282:
- The transcript is ~/.claude/projects/*/<session-id>.jsonl, one JSON object per line. A <session-id>/
  folder and <session-id>.superseded-*/ and .orphaned-*.jsonl siblings belong to the same session.
- Claude Code writes "user" entries of its own: isMeta ones, tool_result lists, strings starting with
  "<" (<command-name> and its kind) and text parts starting with "[Request interrupted". A typed human
  turn is any other "user" entry.
- An "assistant" entry, in the transcript and in --output-format stream-json, carries message.content
  parts of type "text" (text) and "tool_use" (name, input); stream-json ends with a "result" event.
- `claude -p --output-format json --json-schema` returns the verdict under "structured_output".
- ~/.claude.json holds projects.<path>.hasTrustDialogAccepted per checkout.
"""
import glob
import json
import os
import shutil
import subprocess
import sys
import time
import uuid

ARCHIVE = os.path.expanduser(os.environ.get("AUTO_MODE_TRANSCRIPTS", "~/.claude/auto-mode-transcripts"))
RELOAD_BASELINE = open(__file__, encoding="utf-8").read()
RELOAD_CYCLE = "LOOP_CLAUDE_CYCLE"
RELOAD_FAILURES = "LOOP_CLAUDE_FAILURES"
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")

JUDGE_RULES = (
	"Decide whether the human must now be interrupted. ask=true when any of these appear:\n"
	"- the agent asks the human anything, seeks approval, or says a decision is the human's\n"
	"- it carried on under an assumption that decides the deliverable and that the human could "
	"reasonably reject; 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 release "
	"ready to cut, a choice outside the repo\n"
	"- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n"
	"- it chose between alternatives the README text does not discriminate between - it does not "
	"rule the rejected one out - and the choice materially changes the deliverable\n"
	"ask=false otherwise. A sensible preference is not a derivation. 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: judge only what is still open, "
	"never a question they already answered there.\n"
	"The question must be one the agent itself raised. Never construct a question from facts the agent "
	"stated. When ask=true, quote the agent's own wording where it already framed the question.\n"
	"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."
)

JUDGE_SCHEMA = {
	"properties": {
		"ask": {"type": "boolean"},
		"evidence": {"description": "A verbatim quote from the transcript of the line that raises the question. Empty when ask is false.", "type": "string"},
		"finished": {"description": "True when the chunk is complete: merged, or nothing remains that the agent could do on its own.", "type": "boolean"},
		"question": {"description": "The single question to put to the human. Empty when ask is false.", "type": "string"},
	},
	"required": ["ask", "evidence", "finished", "question"],
	"type": "object",
}


def sections(text):
	found, current, fenced = {}, None, False
	for line in text.splitlines():
		fenced ^= line.startswith("```")
		if not fenced and line.startswith("## "):
			current = line.strip()[3:]
			found[current] = []
		elif not fenced and line.startswith("# "):
			current = None
		elif current and line.strip():
			found[current].append(line)
	return {name: "\n".join(body) for name, body in found.items() if body}


def read_premises():
	try:
		found = sections(open("README.md", encoding="utf-8").read())
	except OSError:
		found = {}
	if not found.get("Goals") or not found.get("Audience"):
		sys.exit("README.md needs ## Goals and ## Audience - no premises.")
	return f"## Goals\n{found['Goals']}\n\n## Audience\n{found['Audience']}"


def project():
	root = os.path.expanduser("~/code")
	cwd = os.getcwd()
	if cwd == root or cwd.startswith(f"{root}/"):
		return "~/" + os.path.relpath(cwd, os.path.dirname(root))
	return cwd


def project_path():
	return project().removeprefix("~/code").lstrip("/") or "code"


def session_name():
	return f"A {project()} auto-mode"


def session_file(session_id):
	hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl"))
	return hit[0] if hit else ""


def end_session(path):
	for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"):
		try:
			shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
		except OSError as failure:
			print(f"could not remove {sibling}: {failure}", file=sys.stderr)


def session_open(session_id):
	return bool(session_file(session_id))


def parse(raw):
	try:
		entry = json.loads(raw)
	except ValueError:
		return None
	return entry if isinstance(entry, dict) else None


def entries(path):
	for raw in open(path, encoding="utf-8"):
		if entry := parse(raw):
			yield entry


def said(part, limit=400):
	kind = part.get("type") if isinstance(part, dict) else None
	if kind == "text" and part.get("text", "").strip():
		return part["text"]
	if kind == "tool_use":
		return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}"
	return ""


def render(entries):
	lines = []
	for entry in entries:
		if entry.get("type") == "assistant":
			lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))]
	return "\n\n".join(lines)


def typed(content):
	if isinstance(content, str):
		return not content.startswith("<")
	parts = content if isinstance(content, list) else []
	return bool(parts) and all(isinstance(part, dict) and part.get("type") == "text" and not part.get("text", "").startswith("[Request interrupted") for part in parts)


def human_turns(entries):
	return sum(1 for entry in entries if entry.get("type") == "user" and not entry.get("isMeta") and typed(entry.get("message", {}).get("content")))


def make_private(folder):
	mask = os.umask(0o077)
	try:
		os.makedirs(folder, exist_ok=True)
	finally:
		os.umask(mask)


def archive(path, note):
	folder = os.path.join(ARCHIVE, project_path())
	try:
		stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path)))
		make_private(folder)
		dest = os.path.join(folder, f"{stamp}.md")
		if not os.path.exists(dest):
			with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy:
				copy.write(f"# {stamp} {project_path()}\n\n{note}\n\n{render(entries(path))}\n")
		print(f"transcript: {dest}", file=sys.stderr)
	except OSError as failure:
		print(f"could not archive the transcript: {failure}", file=sys.stderr)


def checkouts():
	found = [os.getcwd()]
	listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, text=True)
	if listing.returncode == 0:
		found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")]
	return sorted(set(found))


def trust(paths):
	config = os.path.expanduser("~/.claude.json")
	try:
		data = json.load(open(config, encoding="utf-8"))
	except (OSError, ValueError):
		return
	projects = data.setdefault("projects", {})
	granted = [path for path in paths if not projects.setdefault(path, {}).get("hasTrustDialogAccepted")]
	if not granted:
		return
	for path in granted:
		projects[path]["hasTrustDialogAccepted"] = True
	staged = f"{config}.loop-claude"
	try:
		with open(staged, "w", encoding="utf-8") as handle:
			json.dump(data, handle, indent=2)
		os.replace(staged, config)
	except OSError as failure:
		print(f"could not record trust: {failure}", file=sys.stderr)
		return
	print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr)


def model(variable):
	return ["--model", os.environ[variable]] if os.environ.get(variable) else []


def worker_args(task, name, session_id, resuming):
	if resuming:
		start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)]
	else:
		start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", name, "--session-id", str(session_id)]
	return [
		*start,
		"--output-format", "stream-json",
		"--permission-mode", "bypassPermissions",
		"--verbose",
		*model("WORKER_MODEL"),
	]


def run_worker(args):
	proc = subprocess.Popen(["claude", *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
	done = {}
	for raw in proc.stdout:
		event = parse(raw) or {}
		if event.get("type") == "result":
			done = event
		elif event.get("type") == "assistant":
			for part in event.get("message", {}).get("content", []):
				if line := said(part, 160):
					print(line, flush=True)
	return done if proc.wait() == 0 else {}


def judge_prompt(task, premises, transcript):
	return (
		f"From README.md:\n{premises}\n\n"
		f"The task an agent was given:\n{task}\n\n"
		f"What the agent then did and said, latest last:\n{transcript[-40000:]}\n\n"
		f"{JUDGE_RULES}"
	)


def complete(verdict):
	return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys()


def grounded(verdict, transcript):
	return not verdict["ask"] or bool(verdict["evidence"]) and verdict["evidence"] in transcript


def judge(task, premises, transcript):
	args = [
		"-p",
		"--json-schema", json.dumps(JUDGE_SCHEMA),
		*model("JUDGE_MODEL"),
		"--no-session-persistence",
		"--output-format", "json",
		"--permission-mode", "bypassPermissions",
		"--tools", "",
	]
	prompt = judge_prompt(task, premises, transcript)
	for attempt in range(3):
		proc = subprocess.run(["claude", *args], capture_output=True, input=prompt, text=True)
		verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None
		if not complete(verdict):
			failure = proc.stderr.strip() or "the judge returned no verdict"
		elif not grounded(verdict, transcript):
			failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, asking: {verdict['question']}"
		else:
			return verdict
		if attempt == 2:
			sys.exit(f"the judge failed three times running: {failure}")
		print(f"retrying the judge in a minute: {failure}", file=sys.stderr)
		time.sleep(60)


def interrupt(session_id, path, question):
	print(f"\n{question}", file=sys.stderr)
	if not (sys.stdin.isatty() and sys.stdout.isatty()):
		return "stdin or stdout is not a terminal"
	trust(checkouts())
	before = human_turns(entries(path))
	subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(session_id)])
	return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything"


def run_cycle(task, premises, name, session_id):
	worked = run_worker(worker_args(task, name, session_id, resuming=session_open(session_id)))
	if not worked:
		return False
	path = session_file(session_id)
	if not path:
		sys.exit(f"claude left no transcript for session {session_id}")
	verdict = judge(task, premises, render(entries(path)))
	while verdict["ask"]:
		archive(path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}")
		if failure := interrupt(session_id, path, verdict["question"]):
			print(failure, file=sys.stderr)
			sys.exit(2)
		verdict = judge(task, premises, render(entries(path)))
	if verdict["finished"]:
		archive(path, f"Task: {task}\n\nVerdict: finished")
		end_session(path)
	return True


def reload_if_edited(cycle_number, failures):
	try:
		source = open(__file__, encoding="utf-8").read()
	except OSError as failure:
		print(f"keeping the running script: {failure}", file=sys.stderr)
		return
	if source == RELOAD_BASELINE:
		return
	trial = subprocess.run([sys.executable, __file__, "--help"], capture_output=True, text=True)
	if trial.returncode != 0:
		print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
		return
	os.environ[RELOAD_CYCLE] = str(cycle_number)
	os.environ[RELOAD_FAILURES] = str(failures)
	os.execv(sys.executable, [sys.executable, __file__, *sys.argv[1:]])


def main():
	task = " ".join(sys.argv[1:])
	if task in ("", "-h", "--help"):
		print(__doc__.strip())
		sys.exit(0 if task else 1)
	cycle_number = int(os.environ.pop(RELOAD_CYCLE, 0))
	failures = int(os.environ.pop(RELOAD_FAILURES, 0))
	while True:
		reload_if_edited(cycle_number, failures)
		cycle_number += 1
		premises = read_premises()
		name = session_name()
		print(f"\n=== cycle {cycle_number} ===", flush=True)
		if run_cycle(task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)):
			failures = 0
			continue
		failures += 1
		if failures == 3:
			sys.exit("the worker failed three times running")
		print("the worker failed - retrying in a minute", file=sys.stderr)
		time.sleep(60)


if __name__ == "__main__":
	try:
		main()
	except KeyboardInterrupt:
		sys.exit(130)
