Run a first chunk in a newcomer's container against a mock Messages API
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
"""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 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"
|
||||
# The line the person's own CLAUDE.md holds. No request may hold it: nothing in `~/.claude` loads in the loop's home.
|
||||
OWN_INSTRUCTION = "Sign every reply as the newcomer's own claude."
|
||||
# A heading of the setup's CLAUDE.md, which the worker's request holds where the loop's home loaded.
|
||||
SETUP_INSTRUCTION = "## Working loop"
|
||||
# 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.
|
||||
"""
|
||||
|
||||
|
||||
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, and a remote it is pushed to."""
|
||||
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 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")
|
||||
if any(OWN_INSTRUCTION in text for text in texts):
|
||||
found.append("a request held the person's own CLAUDE.md, so `~/.claude` loaded 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:
|
||||
(HOME / ".claude" / "CLAUDE.md").write_text(OWN_INSTRUCTION + "\n", encoding="utf-8")
|
||||
before = snapshot(HOME / ".claude", HOME / ".claude.json")
|
||||
project_made()
|
||||
requests = mock_messages_api.Requests()
|
||||
server = mock_messages_api.serve(requests)
|
||||
# The token signs claude in, as docs/decisions.md → `Claude Code in a home of its own` found; 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)
|
||||
deadline = time.monotonic() + PATIENCE
|
||||
while started.returncode == 0 and not chunk_finished() and time.monotonic() < deadline:
|
||||
time.sleep(1)
|
||||
found = [f"build-release exited {started.returncode}"] if started.returncode else 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())
|
||||
Reference in New Issue
Block a user