Run a first chunk in a newcomer's container against a mock Messages API

This commit is contained in:
2026-12-04 06:41:30 +01:00
parent bd93c29295
commit 33fcca6a2e
4 changed files with 266 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
# A newcomer's machine: what README.md → Install asks for, and a stock Claude Code, with nothing of this repo.
# The python tag is ci.sh's. git and tmux come from Debian's current apt: the run needs no exact version.
FROM python:3.14.8
RUN apt-get update \
&& apt-get install --yes --no-install-recommends git tmux \
&& rm -rf /var/lib/apt/lists/*
# Claude Code refuses to skip permission prompts as root.
RUN useradd --create-home newcomer
USER newcomer
WORKDIR /home/newcomer
ENV PATH=/home/newcomer/.local/bin:$PATH
# The version the probes of docs/decisions.md → `Claude Code in a home of its own` ran on.
RUN curl --fail --silent --show-error --location https://claude.ai/install.sh | bash -s 2.1.336
+121
View File
@@ -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())
+119
View File
@@ -0,0 +1,119 @@
"""A mock of Anthropic's Messages API for claude to call at `ANTHROPIC_BASE_URL`: it keeps each request and answers as a worker that is done, or as a judge that rules the chunk finished.
It answers no other path of the API: claude runs a chunk without them.
"""
import http.server
import json
import threading
import typing
# What the worker says, whole. The judge quotes it as its evidence, which build-release checks against the transcript.
WORKER_REPLY = "The note is written, so the chunk is finished."
class Requests:
"""Every body posted to the Messages API so far, oldest first."""
def __init__(self) -> None:
self.lock = threading.Lock()
self.bodies: list[dict[str, typing.Any]] = []
def add(self, body: dict[str, typing.Any]) -> None:
with self.lock:
self.bodies.append(body)
def texts(self) -> list[str]:
"""Each request as JSON text, to search for what claude sent."""
with self.lock:
return [json.dumps(body, ensure_ascii=False) for body in self.bodies]
def verdict_tool(body: dict[str, typing.Any]) -> str | None:
"""The name of the tool claude offers for a reply that fits build-release's judge schema, which is how `--json-schema` asks for one; None in any other request."""
for tool in body.get("tools", []):
if {"finished", "interrupt", "evidence"} <= set(tool.get("input_schema", {}).get("properties", {})):
return tool["name"]
return None
def answered(body: dict[str, typing.Any]) -> bool:
"""Whether the request's last message returns a tool's result, so the verdict was already given."""
content = body["messages"][-1]["content"]
return isinstance(content, list) and any(block.get("type") == "tool_result" for block in content)
def verdict(schema: dict[str, typing.Any]) -> dict[str, typing.Any]:
"""A reply that fits schema and rules the chunk finished on the worker's reply: every other field is empty or false."""
empty = {name: "" if field["type"] == "string" else False if field["type"] == "boolean" else 0 for name, field in schema["properties"].items()}
return {**empty, "finished": True, "evidence": WORKER_REPLY}
def reply_block(body: dict[str, typing.Any]) -> dict[str, typing.Any]:
"""The one content block that answers body."""
tool = verdict_tool(body)
if tool is None or answered(body):
return {"type": "text", "text": WORKER_REPLY}
schema = next(each["input_schema"] for each in body["tools"] if each["name"] == tool)
return {"type": "tool_use", "id": "toolu_verdict", "name": tool, "input": verdict(schema)}
def message(body: dict[str, typing.Any], block: dict[str, typing.Any]) -> dict[str, typing.Any]:
return {
"id": "msg_mock",
"type": "message",
"role": "assistant",
"model": body.get("model", "mock"),
"content": [block],
"stop_reason": "tool_use" if block["type"] == "tool_use" else "end_turn",
"stop_sequence": None,
"usage": {"input_tokens": 1, "output_tokens": 1},
}
def stream(whole: dict[str, typing.Any]) -> bytes:
"""whole as the server-sent events of a streamed reply."""
block = whole["content"][0]
if block["type"] == "text":
start, delta = {"type": "text", "text": ""}, {"type": "text_delta", "text": block["text"]}
else:
start, delta = {**block, "input": {}}, {"type": "input_json_delta", "partial_json": json.dumps(block["input"])}
events = [
{"type": "message_start", "message": {**whole, "content": [], "stop_reason": None}},
{"type": "content_block_start", "index": 0, "content_block": start},
{"type": "content_block_delta", "index": 0, "delta": delta},
{"type": "content_block_stop", "index": 0},
{"type": "message_delta", "delta": {"stop_reason": whole["stop_reason"], "stop_sequence": None}, "usage": {"output_tokens": 1}},
{"type": "message_stop"},
]
return "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events).encode()
def serve(requests: Requests) -> http.server.ThreadingHTTPServer:
"""Starts the mock on a free port of this machine, and returns its server, whose `server_port` names the port."""
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self) -> None:
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if self.path.split("?")[0] != "/v1/messages":
self.answer(404, "application/json", b'{"type": "error", "error": {"type": "not_found_error", "message": "the mock answers only /v1/messages"}}')
return
requests.add(body)
whole = message(body, reply_block(body))
if body.get("stream"):
self.answer(200, "text/event-stream", stream(whole))
else:
self.answer(200, "application/json", json.dumps(whole).encode())
def answer(self, status: int, kind: str, content: bytes) -> None:
self.send_response(status)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content)
def log_message(self, format: str, *args: typing.Any) -> None:
"""Silent: the run's own output says what failed."""
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Runs a first chunk of the committed HEAD as a newcomer would: in a container that holds only what README.md → Install asks for and a stock Claude Code, from a clone, against a mock Messages API.
# first_chunk.py says what it checks. ci.sh runs this; run it yourself under run-heavy.
# The repo goes in as a git bundle, as in ci.sh.
set -eu
cd "$(dirname "$0")/.."
# An untagged image, which docker image prune removes, since a cancelled run skips any cleanup.
image=$(docker build --quiet --memory 2g --memory-swap 2g first-chunk-e2e)
git bundle create - HEAD | docker run --rm -i --init --memory 4g --memory-swap 4g "$image" sh -euc '
cat >/tmp/head.bundle
git -c init.defaultBranch=main -c advice.detachedHead=false clone --quiet /tmp/head.bundle ~/build-release
python3 ~/build-release/first-chunk-e2e/first_chunk.py
'