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
13 changes: 13 additions & 0 deletions pm-stack/opencode-claimant/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -417,13 +417,26 @@ Logs written to `~/.local/state/opencode-claimant/fires.jsonl`:
{
"timestamp": "2026-11-06T23:35:00Z",
"mode": "shadow",
"mode_source": {
"path": "/home/user/.local/state/opencode-claimant/mode",
"state": "missing",
"file_mtime": null,
"dir_mtime": "2026-11-14T14:45:12+00:00",
"pid": 41234
},
"candidates_seen": [...],
"sessions_launched": [...],
"cap_room": 36,
"skips": [...]
}
```

`mode_source` (#10332) says where the fire's mode came from. `state` is
`ok`, `missing`, `unreadable` or `invalid`; every state but `ok` means the
fire fell back to shadow. A deletion changes the state directory's mtime,
so for a `missing` read `dir_mtime` bounds when the file went, and a
live-to-shadow flip can be dated from the log alone.

## Constants

- `CONCURRENCY_CAP = 36`
Expand Down
46 changes: 44 additions & 2 deletions pm-stack/opencode-claimant/claimant.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,20 @@ def _delete_session(session_id: str) -> bool:
LAUNCHED_BY_RECOVERY_GONE_SESSION = "opencode-claimant-recovery:gone-session"


# Where this process's mode came from (#10332): the file's path and
# state, and the mtimes that let a later reader date a flip. Set by
# read_mode(), written into every fires.jsonl entry by log_fire().
_mode_source: "Dict[str, Any] | None" = None


def _mtime(path: Path) -> "str | None":
"""An ISO UTC mtime for path, or None when it cannot be read."""
try:
return datetime.fromtimestamp(path.stat().st_mtime, timezone.utc).isoformat()
except OSError:
return None


def read_mode() -> str:
"""Read the execution mode from the mode file.

Expand All @@ -202,19 +216,40 @@ def read_mode() -> str:
every such read logs a loud CLAIMANT-MODE-WARNING line, and the
aggregator's host-health watchdog surfaces the same fact as a
needs-attention tier item.

Every read also records where the mode came from (#10332) in
_mode_source, which log_fire() writes into fires.jsonl: the path,
whether the file was ok, missing, unreadable or invalid, the
file's mtime when it exists, and the state directory's mtime. A
deletion changes the directory's mtime, so when a fire reads
"missing", the directory mtime bounds when the file went.
"""
global _mode_source
source: Dict[str, Any] = {
"path": str(MODE_FILE),
"state": "ok",
"file_mtime": None,
"dir_mtime": _mtime(MODE_FILE.parent),
"pid": os.getpid(),
}
_mode_source = source

if not MODE_FILE.exists():
source["state"] = "missing"
print(
f"CLAIMANT-MODE-WARNING (#10141): mode file {MODE_FILE} is MISSING "
"- defaulting to shadow; dispatch will return mode_not_live and "
"stall until the file is restored with the intended mode.",
"stall until the file is restored with the intended mode. "
f"State directory last changed {source['dir_mtime']}.",
file=sys.stderr,
)
return "shadow"

source["file_mtime"] = _mtime(MODE_FILE)
try:
raw = MODE_FILE.read_text()
except Exception as exc:
source["state"] = "unreadable"
print(
f"CLAIMANT-MODE-WARNING (#10141): mode file {MODE_FILE} is "
f"UNREADABLE ({exc}) - defaulting to shadow.",
Expand All @@ -224,6 +259,7 @@ def read_mode() -> str:
mode = raw.strip().lower()
if mode in ("shadow", "live"):
return mode
source["state"] = "invalid"
print(
f"CLAIMANT-MODE-WARNING (#10141): mode file {MODE_FILE} content "
f"{raw.strip()[:40]!r} is not live|shadow - defaulting to shadow.",
Expand Down Expand Up @@ -263,6 +299,7 @@ def log_fire(
fire_entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"mode": mode,
"mode_source": _mode_source,
"candidates_seen": candidates,
"sessions_launched": launched,
"cap_room": cap_room,
Expand Down Expand Up @@ -1449,7 +1486,12 @@ def main():

def _fire(mode: str):
"""One claimant fire, run under the single-instance lock."""
print(f"OpenCode claimant starting in {mode} mode")
source = _mode_source or {}
print(
f"OpenCode claimant starting in {mode} mode "
f"(mode file {source.get('path', MODE_FILE)}: {source.get('state', 'unknown')}, "
f"modified {source.get('file_mtime')})"
)

# Step 1: Supervision (always runs in live mode). Tasks it
# recovers are eligible on the NEXT fire, not this one (#8038
Expand Down
38 changes: 38 additions & 0 deletions pm-stack/opencode-claimant/test/test_claimant.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,44 @@ def test_valid_modes_are_returned_quietly(self):
self.assertEqual(result, want)
self.assertNotIn("CLAIMANT-MODE-WARNING", err)

def test_every_read_records_where_the_mode_came_from(self):
# #10332: a flip must be attributable from the fires log alone.
import tempfile

with tempfile.TemporaryDirectory() as td:
tmp = Path(td)
for content, state in (
("live\n", "ok"),
("banana", "invalid"),
(None, "missing"),
):
(tmp / "mode").unlink(missing_ok=True)
self._read_with_file(tmp, content)
source = claimant._mode_source
self.assertEqual(source["path"], str(tmp / "mode"))
self.assertEqual(source["state"], state)
self.assertIsNotNone(source["dir_mtime"])
if content is None:
self.assertIsNone(source["file_mtime"])
else:
self.assertIsNotNone(source["file_mtime"])

def test_fire_log_entries_carry_the_mode_source(self):
import tempfile

with tempfile.TemporaryDirectory() as td:
tmp = Path(td)
self._read_with_file(tmp, None)
fires = tmp / "fires.jsonl"
with patch.object(claimant, "STATE_DIR", tmp), patch.object(
claimant, "FIRES_FILE", fires
):
claimant.log_fire("shadow", [], [], None, [{"reason": "no_candidates"}])
entry = json.loads(fires.read_text().splitlines()[-1])
self.assertEqual(entry["mode"], "shadow")
self.assertEqual(entry["mode_source"]["state"], "missing")
self.assertEqual(entry["mode_source"]["path"], str(tmp / "mode"))


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