Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions pm-stack/opencode-claimant/claimant.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,63 @@ def read_mode() -> str:
return "shadow"


# Which code this fire is running (#12813): the primary clone's
# checked-out branch and commit, read once per process by
# read_code_source() and written into every fires.jsonl entry by
# log_fire(). The 2026-11-23 incident was the primary clone silently
# sitting on a stale branch: every fire aborted cap_unknown and the
# fire log named neither the branch nor the commit, so the cause had
# to be reconstructed from the clone's reflog after the fact.
# Recording both makes the next such incident name itself in the
# first fire that hits it.
_code_source: "Dict[str, Any] | None" = None


def read_code_source() -> "Dict[str, Any]":
"""Read the primary clone's checked-out branch and commit.

Fail-open by design: this is provenance for the fire log, never
a gate. Any git failure (no git binary, not a checkout, timeout)
yields state "unreadable" with branch/commit None rather than
raising - a fire must never abort because its own provenance
read failed. The result is cached per process: one fire is one
process, and the checkout does not change under a running fire.
"""
global _code_source
if _code_source is not None:
return _code_source
source: Dict[str, Any] = {
"path": str(PRIMARY_CLONE),
"state": "ok",
"branch": None,
"commit": None,
}
_code_source = source
try:
branch = subprocess.run(
["git", "-C", str(PRIMARY_CLONE), "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True,
text=True,
timeout=10,
)
commit = subprocess.run(
["git", "-C", str(PRIMARY_CLONE), "rev-parse", "HEAD"],
capture_output=True,
text=True,
timeout=10,
)
if branch.returncode != 0 or commit.returncode != 0:
source["state"] = "unreadable"
return source
source["branch"] = branch.stdout.strip() or None
source["commit"] = commit.stdout.strip() or None
if source["branch"] is None or source["commit"] is None:
source["state"] = "unreadable"
except Exception:
source["state"] = "unreadable"
return source


def ensure_state_dir() -> None:
"""Ensure the state directory exists."""
STATE_DIR.mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -306,6 +363,7 @@ def log_fire(
"timestamp": datetime.now(timezone.utc).isoformat(),
"mode": mode,
"mode_source": _mode_source,
"code_source": read_code_source(),
"candidates_seen": candidates,
"sessions_launched": launched,
"cap_room": cap_room,
Expand Down
85 changes: 85 additions & 0 deletions pm-stack/opencode-claimant/test_claimant.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@

import importlib.util
import json
import os
import subprocess
import tempfile
import time
import unittest
Expand Down Expand Up @@ -1578,3 +1580,86 @@ def test_no_launchable_candidate_no_handback(self):

if __name__ == "__main__":
unittest.main()


class TestCodeSourceFireLog(unittest.TestCase):
"""#12813: every fire log entry records the primary clone's
checked-out branch and commit (code_source), so a fire running
stale-branch code names itself. The read is fail-open: a clone
git cannot read yields state "unreadable", never an abort."""

def setUp(self):
claimant._code_source = None

def tearDown(self):
claimant._code_source = None

def _make_clone(self, tmp: str) -> Path:
clone = Path(tmp) / "clone"
clone.mkdir()
env = dict(os.environ)
env.update(
{
"GIT_AUTHOR_NAME": "test",
"GIT_AUTHOR_EMAIL": "test@example.invalid",
"GIT_COMMITTER_NAME": "test",
"GIT_COMMITTER_EMAIL": "test@example.invalid",
}
)
subprocess.run(
["git", "init", "-b", "main", str(clone)],
check=True,
capture_output=True,
env=env,
Comment on lines +1609 to +1613

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep Git subprocesses out of the hermetic test suite

Running the supported make test entry point now fails: run_hermetic_tests.py loads this test class after installing an audit hook that rejects every subprocess.Popen. Both tests using _make_clone() therefore raise before creating their repositories. The unreadable-clone test also attempts real Git subprocesses; although read_code_source() catches the exception, the harness records the violation and still exits unsuccessfully. Mock the Git calls in the hermetic suite, or separate real-repository integration coverage into an explicitly permitted runner.

Useful? React with 👍 / 👎.

)
(clone / "f.txt").write_text("x")
subprocess.run(
["git", "-C", str(clone), "add", "f.txt"],
check=True,
capture_output=True,
env=env,
)
subprocess.run(
["git", "-C", str(clone), "commit", "-m", "init"],
check=True,
capture_output=True,
env=env,
)
return clone

def test_reads_branch_and_commit(self):
with tempfile.TemporaryDirectory() as tmp:
clone = self._make_clone(tmp)
with patch.object(claimant, "PRIMARY_CLONE", clone):
source = claimant.read_code_source()
self.assertEqual(source["state"], "ok")
self.assertEqual(source["branch"], "main")
self.assertEqual(len(source["commit"]), 40)

def test_unreadable_clone_fails_open(self):
with tempfile.TemporaryDirectory() as tmp:
not_a_repo = Path(tmp) / "nope"
not_a_repo.mkdir()
with patch.object(claimant, "PRIMARY_CLONE", not_a_repo):
source = claimant.read_code_source()
self.assertEqual(source["state"], "unreadable")
self.assertIsNone(source["branch"])
self.assertIsNone(source["commit"])

def test_fire_entry_carries_code_source(self):
with tempfile.TemporaryDirectory() as tmp:
clone = self._make_clone(tmp)
state_dir = Path(tmp) / "state"
fires = state_dir / "fires.jsonl"
with (
patch.object(claimant, "PRIMARY_CLONE", clone),
patch.object(claimant, "STATE_DIR", state_dir),
patch.object(claimant, "FIRES_FILE", fires),
):
claimant.log_fire("live", [], [], 3, [])
entries = [
json.loads(line) for line in fires.read_text().splitlines() if line
]
self.assertEqual(len(entries), 1)
self.assertEqual(entries[0]["code_source"]["branch"], "main")
self.assertEqual(entries[0]["code_source"]["state"], "ok")