Files
claude-config/first-chunk-e2e/first_chunk.py
T

166 lines
7.6 KiB
Python

"""Runs a first chunk as a newcomer would, and checks that the person's own Claude home is left as it was.
It runs in the container of the Dockerfile beside it, from a clone of this repo: `first-chunk-e2e/run` starts it. The machine holds a stock Claude Code with its own `~/.claude`, to which this adds a `CLAUDE.md`. build-release then runs a task in a small project, with claude calling the mock Messages API. The run passes where the chunk finished on the setup's instructions, no request held the person's own, and `~/.claude` and `~/.claude.json` hold what they held before.
"""
import hashlib
import json
import os
import pathlib
import subprocess
import sys
import time
import mock_messages_api
CLONE = pathlib.Path(__file__).resolve().parent.parent
HOME = pathlib.Path.home()
# The project's key is its path under ~/code: README.md → Install → "Set up a project".
PROJECT = HOME / "code" / "first-project"
ARCHIVE = HOME / ".local/state/build-release/transcripts/first-project"
CONFIG = HOME / ".config/build-release/first-project/config.toml"
# What the person's own `~/.claude` holds beside the stock install's files. Nothing in it loads in the loop's home, so no request may hold either instruction, and the hook never runs.
OWN_INSTRUCTION = "Sign every reply as the newcomer's own claude."
OWN_RULE = "Open every reply with the newcomer's own greeting."
OWN_HOOK_RAN = HOME / "own-hook-ran"
OWN_FILES = {
"CLAUDE.md": OWN_INSTRUCTION + "\n",
# In two parts, since bin/repo_checks/test_citations.py reads a rule file's path written whole as one of the setup's.
os.path.join("rules", "greeting.md"): OWN_RULE + "\n",
"settings.json": json.dumps({"hooks": {"SessionStart": [{"hooks": [{"type": "command", "command": f"touch {OWN_HOOK_RAN}"}]}]}}) + "\n",
}
# A heading of the setup's CLAUDE.md, which the worker's request holds where the loop's home loaded.
SETUP_INSTRUCTION = "## Working loop"
# What build-release asks a project's first chunk, and the model the newcomer types: one on the shipped routing ladder.
MODEL_QUESTION = "name claude --model takes:"
MODEL = "claude-opus-5-5"
# How long the chunk may take. One on the mock takes under a minute.
PATIENCE = 300
README = """# first-project
## Goals
1. **Achieve:** Keep a note of what the project is for.
- Signal: the note exists.
- Counter-signal: the note says what the project isn't for.
- Why: a note that misleads is worse than none.
## Audience
Whoever runs the first chunk.
"""
# README.md → Install → "Set up a project" gives this config for a project of one's own.
CONFIG_TEXT = """checkout = "~/code/first-project"
plan = "checkout:todo.md"
working-rules = "checkout:AGENTS.md"
decisions = "checkout:docs/decisions.md"
score-anchors = "checkout:docs/score-anchors.md"
comprehension-history = "checkout:docs/comprehension-history.md"
reading-cost = "checkout:docs/reading-cost.md"
changelog = "checkout:CHANGELOG.md"
goals-and-audience = "checkout:README.md"
principles = "setup:principles"
standards = "setup:skills/larv-review/standards"
"""
def snapshot(*roots: pathlib.Path) -> dict[str, str]:
"""What each root holds: every path under it with its mode, and a file's content hash or a link's target."""
held = {}
for root in roots:
for path in [root, *sorted(root.rglob("*"))] if root.is_dir() else [root]:
status = path.lstat()
if path.is_symlink():
content = f"link to {os.readlink(path)}"
elif path.is_file():
content = hashlib.sha256(path.read_bytes()).hexdigest()
else:
content = "folder"
held[str(path)] = f"{status.st_mode:o} {content}"
return held
def git(*args: str) -> None:
subprocess.run(["git", "-c", "user.name=Newcomer", "-c", "user.email=newcomer@example.com", "-c", "init.defaultBranch=main", *args], check=True, cwd=PROJECT, stdout=subprocess.DEVNULL)
def project_made() -> None:
"""Makes the project: a checkout with the premises in its README, a remote it is pushed to, and its config."""
CONFIG.parent.mkdir(parents=True)
CONFIG.write_text(CONFIG_TEXT, encoding="utf-8")
PROJECT.mkdir(parents=True)
(PROJECT / "README.md").write_text(README, encoding="utf-8")
git("init", "--quiet")
git("add", "README.md")
git("commit", "--quiet", "-m", "State the goals and the audience")
git("init", "--quiet", "--bare", str(HOME / "first-project.git"))
git("remote", "add", "origin", str(HOME / "first-project.git"))
git("push", "--quiet", "--set-upstream", "origin", "main")
def chunk_finished() -> bool:
return any("Verdict: finished" in outcomes.read_text(encoding="utf-8") for outcomes in ARCHIVE.glob("*/*.outcomes.md"))
def windows() -> str:
"""What each tmux window of the loop shows, for a run that failed."""
listed = subprocess.run(["tmux", "list-panes", "-a", "-F", "#{pane_id}"], capture_output=True, text=True).stdout.split()
return "\n".join(subprocess.run(["tmux", "capture-pane", "-p", "-J", "-S", "-200", "-t", pane], capture_output=True, text=True).stdout.strip() for pane in listed)
def chunk_awaited() -> None:
"""Types the project's model into the chunk's window once build-release asks for it there, then waits until the chunk finishes or PATIENCE runs out."""
deadline = time.monotonic() + PATIENCE
while MODEL_QUESTION not in windows() and time.monotonic() < deadline:
time.sleep(1)
subprocess.run(["tmux", "send-keys", "-t", "loop-first-project:", MODEL, "Enter"], capture_output=True)
while not chunk_finished() and time.monotonic() < deadline:
time.sleep(1)
def failures(requests: mock_messages_api.Requests, before: dict[str, str]) -> list[str]:
"""Each way the run broke what it checks."""
found = []
texts = requests.texts()
if not chunk_finished():
found.append(f"no chunk finished within {PATIENCE} s; the loop's tmux windows show:\n{windows()}")
if not any(SETUP_INSTRUCTION in text for text in texts):
found.append(f"none of claude's {len(texts)} requests held the setup's CLAUDE.md, so the loop's home did not load")
for instruction in (OWN_INSTRUCTION, OWN_RULE):
if any(instruction in text for text in texts):
found.append(f"a request held the person's own instruction `{instruction}`, so `~/.claude` loaded in the loop")
if OWN_HOOK_RAN.exists():
found.append("the hook of the person's own `~/.claude/settings.json` ran in the loop")
after = snapshot(HOME / ".claude", HOME / ".claude.json")
for path in sorted(before.keys() | after.keys()):
if before.get(path) != after.get(path):
found.append(f"the run changed the person's own {path}: {before.get(path, 'absent')} before, {after.get(path, 'absent')} after")
return found
def main() -> int:
for name, text in OWN_FILES.items():
(HOME / ".claude" / name).parent.mkdir(exist_ok=True)
(HOME / ".claude" / name).write_text(text, encoding="utf-8")
before = snapshot(HOME / ".claude", HOME / ".claude.json")
project_made()
requests = mock_messages_api.Requests()
server = mock_messages_api.serve(requests)
# A made-up token, which grants access to nothing. It signs claude in, as docs/decisions.md → `Claude Code in a home of its own` found, and the mock doesn't check it.
env = {**os.environ, "ANTHROPIC_BASE_URL": f"http://127.0.0.1:{server.server_port}", "CLAUDE_CODE_OAUTH_TOKEN": "mock-token"}
started = subprocess.run([str(CLONE / "bin" / "build-release"), "Write a note of what the project is for."], cwd=PROJECT, env=env, stdin=subprocess.DEVNULL)
if started.returncode:
found = [f"build-release exited {started.returncode}"]
else:
chunk_awaited()
found = failures(requests, before)
subprocess.run(["tmux", "kill-server"], capture_output=True)
for failure in found:
print(f"FAILED: {failure}", file=sys.stderr)
if not found:
print("A first chunk finished in the loop's Claude home, and `~/.claude` is as it was.")
return 1 if found else 0
if __name__ == "__main__":
sys.exit(main())