"""Observe Git and Claude Code worktrees using a disposable repository."""
import argparse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import shutil
from subprocess import run
from tempfile import TemporaryDirectory
from threading import Thread
from lab_gateway import TOKEN, stream
PROMPT_NOTE = "Inspect the two released inventory formats and identify differences."
SYSTEM_MARKER = "Return a byte-level comparison before writing any recommendation."
def exercise(executable):
requests = []
class Fixture(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def do_POST(self):
if self.headers.get("Authorization") != "Bearer " + TOKEN or self.path.split("?", 1)[0] != "/v1/messages":
self.send_error(403)
return
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
requests.append({"custom_system_prompt": SYSTEM_MARKER in json.dumps(body.get("system", [])),
"prompt_matched": PROMPT_NOTE in json.dumps(body.get("messages", []))})
payload = stream(body["model"])
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
with TemporaryDirectory(prefix="mbsky-worktrees-") as tmp, ThreadingHTTPServer(("127.0.0.1",0),Fixture) as server:
root = Path(tmp)
repo = root / "warehouse"
repo.mkdir()
env = {k:os.environ[k] for k in ("SYSTEMROOT","WINDIR","PATH","TEMP","TMP","COMSPEC","PROGRAMFILES") if k in os.environ}
env.update(CLAUDE_CONFIG_DIR=str(root/"profile"), GIT_CONFIG_NOSYSTEM="1",
GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0",
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1", DISABLE_AUTOUPDATER="1",
DISABLE_TELEMETRY="1", DISABLE_ERROR_REPORTING="1",
CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL="1",
ANTHROPIC_BASE_URL=f"http://127.0.0.1:{server.server_port}",
ANTHROPIC_AUTH_TOKEN=TOKEN, ANTHROPIC_MODEL="sample-pro", API_TIMEOUT_MS="4500",
HTTP_PROXY="http://127.0.0.1:1", HTTPS_PROXY="http://127.0.0.1:1",
ALL_PROXY="http://127.0.0.1:1", NO_PROXY="127.0.0.1,localhost", NO_COLOR="1",
CLAUDE_CODE_GIT_BASH_PATH=str(Path(shutil.which("git")).resolve().parent.parent/"bin/bash.exe")
if os.name=="nt" else "")
def invoke(args, directory=repo, *, check=True):
return run(args,cwd=directory,env=env,capture_output=True,text=True,encoding="utf-8",timeout=26,check=check)
def git(*args, directory=repo):
return invoke(["git",*args],directory).stdout.strip()
server_thread = Thread(target=server.serve_forever, daemon=True)
server_thread.start()
try:
git("init","--initial-branch=main")
git("config","user.name","MBSKY Lab")
git("config","user.email","lab@example.test")
(repo/"inventory.txt").write_bytes(b"active inventory\n")
(repo/".gitignore").write_bytes(b".claude/worktrees/\n")
source_agent = Path(__file__).with_name("inventory-reviewer.md")
target_agent = repo / ".claude/agents" / source_agent.name
target_agent.parent.mkdir(parents=True)
target_agent.write_bytes(source_agent.read_bytes())
git("add",".")
git("commit","-m","Record inventory baseline")
base = git("rev-parse","HEAD")
units = (root/"warehouse-labels", root/"warehouse-audit")
for unit,branch in zip(units,("labels","audit"),strict=True):
git("worktree","add","-b",branch,str(unit),"main")
for unit,content in zip(units,(b"label schedule\n",b"audit counts\n"),strict=True):
(unit/"inventory.txt").write_bytes(content)
branches = [git("branch","--show-current",directory=unit) for unit in (repo,*units)]
values = [(unit/"inventory.txt").read_text(encoding="utf-8") for unit in (repo,*units)]
common_dirs = [git("rev-parse","--path-format=absolute","--git-common-dir",directory=unit)
for unit in (repo,*units)]
index_files = [git("rev-parse","--path-format=absolute","--git-path","index",directory=unit)
for unit in (repo,*units)]
git("add","inventory.txt",directory=units[0])
staged = [git("diff","--cached","--name-only",directory=unit) for unit in (repo,*units)]
git("commit","-m","Set shipping label schedule",directory=units[0])
new_tip = git("rev-parse","HEAD",directory=units[0])
visible_object = git("cat-file","-t",new_tip,directory=units[1])
main_stays = git("rev-parse","HEAD")==base
# Remove the clean worktree via Git. The uncommitted worktree stays for inspection.
git("worktree","remove",str(units[0]))
refused = invoke(["git","worktree","remove",str(units[1])],check=False)
dirty_retained = (units[1]/"inventory.txt").read_bytes()==b"audit counts\n"
same_branch = invoke(["git","worktree","add",str(root/"duplicate"),"audit"],check=False)
cli = invoke([str(executable),"--version"]).stdout.strip()
reply = invoke([str(executable),"-p","-w","inventory-review","--agent","inventory-reviewer",
"--tools","","--strict-mcp-config",PROMPT_NOTE])
worktree = repo/".claude/worktrees/inventory-review"
claude_branch = git("branch","--show-current",directory=worktree)
claude_baseline = (worktree/"inventory.txt").read_text(encoding="utf-8")
return {
"git": git("--version"), "claude": cli, "branches": branches, "files": values,
"same_git_objects": len(set(common_dirs))==1, "independent_indexes": len(set(index_files))==3,
"staged": staged, "visible_commit_object": visible_object, "main_head_retained": main_stays,
"clean_removed": not units[0].exists(), "dirty_remove_exit": refused.returncode,
"dirty_data_retained": dirty_retained, "duplicate_branch_exit": same_branch.returncode,
"claude_branch": claude_branch, "claude_root_file": claude_baseline,
"claude_reply": reply.stdout.strip(), "loopback_requests": requests,
}
finally:
server.shutdown()
server_thread.join(5)
if __name__=="__main__":
parser = argparse.ArgumentParser()
parser.add_argument("claude_path", type=Path)
print(json.dumps(exercise(parser.parse_args().claude_path.resolve(strict=True)), ensure_ascii=False))
本例需在 Windows、Claude Code 2.1.325、Git 2.54.0 和 Python 3.12。使用临时仓库与本机回环服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Claude Code 2.1.325、Git 2.54.0 和 Python 3.12。使用临时仓库与本机回环服务。
入口文件:projects/claude-code-parallel/exercise_worktrees.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
exercise_worktrees.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Claude Code 2.1.325、Git 2.54.0 和 Python 3.12。使用临时仓库与本机回环服务。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3117.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3137.zip