From 0082c3946ac6fa4332cc54fa102db0322ce2c61e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:22:33 -0800 Subject: [PATCH 01/52] test(crew): reproduce the crew coordination faults and hunt for more The crew hit nine coordination faults on 26.11.25 (steps that never close, lanes that take no queued step, blocked steps holding files, the tech lead's commands taken for a member's, CI causes left unnamed); the engineers who fix them need failing tests first, on Claude Code and Codex, and a model-based hunt for faults of the same kind. Each fault has a test at the function or command that decides it, with that day's inputs; the Codex variants drive the real hooks with Codex rollouts. A seeded model-based test walks assign, launch, step, block, skip, reopen, resume, ask, answer, wait and stop on both hosts and reports each broken rule with its shrunk sequence (about 35 s). Verified: the 23 tests fail on purpose on 26.11.26 for their fault's reason (python3 3.15 and /usr/bin/python3 3.9: 23 failures, 0 errors); dev test prove: all 23 fail without a fix; dev test audit: 0 high, 0 medium --- tests/test_coordination_ci.py | 101 +++++++ tests/test_coordination_codex.py | 133 ++++++++ tests/test_coordination_identity.py | 66 ++++ tests/test_coordination_lanes.py | 147 +++++++++ tests/test_coordination_model.py | 449 ++++++++++++++++++++++++++++ 5 files changed, 896 insertions(+) create mode 100644 tests/test_coordination_ci.py create mode 100644 tests/test_coordination_codex.py create mode 100644 tests/test_coordination_identity.py create mode 100644 tests/test_coordination_lanes.py create mode 100644 tests/test_coordination_model.py diff --git a/tests/test_coordination_ci.py b/tests/test_coordination_ci.py new file mode 100644 index 00000000..ea34dfb0 --- /dev/null +++ b/tests/test_coordination_ci.py @@ -0,0 +1,101 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""Local CI and CI diagnosis: a green local run is not cut short by a limit shorter than the workflow allows, and a +run whose jobs never started names the host's reason. Each test reproduces a fault the crew hit on devkit 26.11.25 +(2026-11-19), through `dev ci --run`, `dev run view --failed` (the fake gh) and the CI watch (a stand-in gh first on +PATH). Run: python3 -m unittest tests.test_coordination_ci""" +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import ciwatch, gitx # noqa: E402 +from test_ciwatch import Clock, WatchCase, run # noqa: E402 +from test_gitx import Sandbox, dev # noqa: E402 + +BUDGET = "The job was not started because an Actions budget is preventing further use." +JOB_ID = "135985601878" +RUN_ID = "44645118961" + + +class LocalStepLimitTests(unittest.TestCase): + def test_a_step_gets_the_time_its_workflow_job_allows(self): + # devkit's own unit-test step takes about 36 minutes; its job allows 40 (timeout-minutes), and dev ci --run + # stopped the green suite at its own 30-minute default with exit 124 + workflow = ("name: CI\non: [pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n" + " timeout-minutes: 40\n steps:\n - name: Unit tests\n run: test -f README.md\n") + limits, real_run = [], subprocess.run + + def spy(argv, *args, **kwargs): # the step's own shell, as run_local_ci starts it + if isinstance(argv, list) and argv[:1] == ["bash"] and argv[-1] == "test -f README.md": + limits.append(kwargs.get("timeout")) + return real_run(argv, *args, **kwargs) + with Sandbox() as s: + s.write(".github/workflows/ci.yml", workflow) + s.branch("feat/ci") + s.commit("ci: add the workflow") + with mock.patch.object(gitx.subprocess, "run", spy): + rc, out, err = dev("ci", "--run") + self.assertEqual(rc, 0, out + err) + self.assertEqual(len(limits), 1, limits) + self.assertGreaterEqual(limits[0], 40 * 60) + + +class JobNeverStartedTests(unittest.TestCase): + def test_run_view_failed_names_the_annotation_of_a_job_that_never_started(self): + # B-igm6xuux0ffp: the Signature PR run started no job; `dev run view --failed` said "failing log + # unavailable: log not found", and only the check run's annotation said why + with Sandbox() as s: + s.gh.on(["run", "view"], {"workflowName": "ci", "number": 40, "conclusion": "failure", + "headBranch": "release/26.11.25", "headSha": "0bde25cdef", "event": "pull_request", + "url": f"https://github.com/acme/widget/actions/runs/{RUN_ID}", + "jobs": [{"name": "tests (Python 3.13, part 1 of 2)", "conclusion": "failure", + "databaseId": int(JOB_ID), "steps": []}]}) + s.gh.on(["run", "view"], rc=1, err=f"failed to get run log: log not found: {JOB_ID}", + when=lambda a: "--log-failed" in a) + s.gh.on(["api"], [{"annotation_level": "failure", "message": BUDGET, "path": ".github"}], + when=lambda a: any("annotations" in x for x in a)) + rc, out, err = dev("run", "view", RUN_ID, "--failed") + self.assertEqual(rc, 1) + self.assertIn("an Actions budget is preventing further use", out + err) + + +class WatchNeverStartedTests(WatchCase): + def setUp(self): + super().setUp() + ciwatch.failed_log = self.saved[4] # the real reader: it asks the stand-in gh below + self.top = tempfile.mkdtemp(dir=self.tmp.name) + tools = Path(self.tmp.name) / "bin" + tools.mkdir() + gh = tools / "gh" + gh.write_text("#!/bin/sh\n" + 'case "$*" in\n' + f' *--log-failed*) echo "failed to get run log: log not found: {JOB_ID}" >&2; exit 1 ;;\n' + f' *annotations*) echo \'[{{"annotation_level": "failure", "message": "{BUDGET}"}}]\' ;;\n' + ' *) echo "no canned answer: gh $*" >&2; exit 1 ;;\n' + "esac\n") + gh.chmod(0o755) + path = mock.patch.dict(os.environ, {"PATH": str(tools) + os.pathsep + os.environ["PATH"]}) + path.start() + self.addCleanup(path.stop) + + def test_the_ci_watch_names_why_a_job_never_started(self): + # B-igm6xuux0ffp: `dev ci watch` reported the failed run with class unknown and no first error + url = f"https://github.com/acme/api/actions/runs/{RUN_ID}/job/{JOB_ID}" + failed = run("failed", rid=RUN_ID, n=40, conclusion="failure", + jobs=[{"name": "tests (Python 3.13, part 1 of 2)", "status": "failed", "current": "", + "url": url}]) + clock = Clock() + res = ciwatch.watch(self.top, branch="release/26.11.25", sha="abc1234", sleep=clock.sleep, clock=clock, + runs_fn=self.sequence([run("running", rid=RUN_ID, n=40)], [failed])) + self.assertEqual(res["state"], "failed") + self.assertIn("an Actions budget is preventing further use", ciwatch.message(res)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_coordination_codex.py b/tests/test_coordination_codex.py new file mode 100644 index 00000000..46a0183c --- /dev/null +++ b/tests/test_coordination_codex.py @@ -0,0 +1,133 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The crew coordination faults of devkit 26.11.25 (2026-11-19), on Codex's host path: a Codex tech lead's thread, +its members spawned with spawn_agent and bound at SubagentStart by their task_name (Codex sends no PreToolUse for the +spawn), each member command a shell call through PreToolUse and PostToolUse that its own rollout also records as a +CommandExecution item, and notices that reach a member at its next PostToolUse. Real `dev` processes and hooks, as +tests/test_codex_launch.py drives them. The Claude Code variants are in tests/test_coordination_lanes.py and +tests/test_coordination_identity.py. Run: python3 -m unittest tests.test_coordination_codex""" +import json +import shlex +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from test_codex_launch import LEAD, TANK, CodexCrew, _line, _now # noqa: E402 + +SERAPH = "01a1c190-64c7-7ac1-81c6-000000000007" +REPORT = ("**[Firefly> DevKit · {role}]** api · `feat/invoice-export` · {task}\n- **Done:** {task}\n" + "- **Check:** ✓ 12 tests pass\n- **Next:** the tech lead merges it.\n\nNeeds from the tech lead: nothing") + + +class CodexCoordination(CodexCrew): + def run_lead(self, plan: str, *assign): + """A Codex tech lead's run for `plan`, each (step, member, scope) assigned by role.""" + self.config(max_parallel=3, reserve=0) + s = self.codex(LEAD, self.api) + s.ok("progress", "start", "Invoice export", "--plan", plan) + for step, name, scope in assign: + s.ok("progress", "assign", step, "--to", name, "--scope", scope) + return s + + def member(self, s, aid: str, member: str, *args) -> dict: + """A member's `dev` command: its shell call through the hooks, and the CommandExecution item its own rollout + records for it.""" + r = s.dev(*args, member=aid, member_type=member) + cmd = " ".join(["dev"] + [shlex.quote(str(a)) for a in args]) + item = {"type": "CommandExecution", "id": r["call"]["tool_use_id"], "command": ["/bin/zsh", "-lc", cmd], + "status": "completed" if r["rc"] == 0 else "failed", "exit_code": r["rc"], + "aggregated_output": (r["out"] + r["err"])[-2000:]} + with self.rollout(aid).open("a") as fh: + fh.write(_line({"timestamp": _now(), "type": "event_msg", "payload": { + "type": "item_completed", "turn_id": "01a1c178-28b7-7fa1-a67c-2bd8b7433d66", "item": item}})) + return r + + def stop(self, s, aid: str, member: str, report: str, again: bool = False) -> dict: + """SubagentStop as Codex 0.167.0 sends it: the member's own rollout beside the parent's.""" + return s.hook("subagent-stop", s.payload( + "SubagentStop", agent_id=aid, agent_type=member, model="gpt-6-luna", stop_hook_active=again, + agent_transcript_path=str(self.rollout(aid)), last_assistant_message=report)) + + def held(self, s, name: str) -> tuple: + st = self.step(s, name) + return st.get("owner"), st.get("state") + + +class CodexLaneTests(CodexCoordination): + def test_a_codex_members_checked_record_without_step_closes_its_lanes_only_running_step(self): + s = self.run_lead("api=30m [backend]; ui=30m [frontend]", ("api", "Tank", "api/**")) + self.spawn(s, TANK, "tank", "api") + self.assertEqual(self.held(s, "api"), (TANK, "running")) + r = self.member(s, TANK, "tank", "progress", "step", "the endpoint streams CSV", "--check", "✓ 12 tests pass") + self.assertEqual(r["rc"], 0, r["err"]) + self.assertIn("✓", r["out"]) + self.assertEqual(self.held(s, "api"), (TANK, "done"), r["out"]) + + def test_a_codex_lane_whose_step_closes_takes_the_first_of_two_steps_assigned_to_its_member(self): + s = self.run_lead("api=30m [backend]; export=30m [backend]; import=30m [backend]", + ("api", "Tank", "api/**"), ("export", "Tank", "export/**"), ("import", "Tank", "import/**")) + self.spawn(s, TANK, "tank", "api") + self.assertEqual(self.held(s, "api"), (TANK, "running")) + r = self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") + self.assertEqual(r["rc"], 0, r["err"]) + self.assertEqual((self.held(s, "export"), self.held(s, "import")), ((TANK, "running"), ("main", "pending"))) + + def test_a_blocked_codex_step_frees_the_lane_and_the_member_hears_of_its_next_step(self): + s = self.run_lead("api=30m [backend]; export=30m [backend]", ("api", "Tank", "api/**")) + self.spawn(s, TANK, "tank", "api") + s.ok("progress", "block", "the API contract waits for the developer", "--step", "api") + s.ok("progress", "assign", "export", "--to", "Tank", "--scope", "export/**") + self.assertEqual(self.held(s, "export"), (TANK, "running")) + heard = self.member_hears(s, TANK, "tank") # the member's next PostToolUse + self.assertNotIn("joins your lane once", heard) + + def test_a_resumed_codex_lane_takes_the_one_step_assigned_to_its_member_by_role(self): + s = self.run_lead("api=30m [backend]; export=30m [backend]", ("api", "Tank", "api/**")) + self.spawn(s, TANK, "tank", "api") + self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") + self.stop(s, TANK, "tank", REPORT.format(role="Backend engineer (Tank)", task="api")) + s.ok("progress", "assign", "export", "--to", "Tank", "--scope", "export/**") + self.subagent_start(s, TANK, "tank") # resumed: Codex starts the same thread again + self.assertEqual(self.held(s, "export"), (TANK, "running")) + self.assertEqual(s.run_doc()["agents"][TANK].get("scope"), ["export/**"]) + + def test_a_resumed_codex_reviewers_clean_report_approves_after_an_earlier_send_back(self): + s = self.run_lead("api=30m [backend]; review=20m [review] after api", ("api", "Tank", "api/**")) + self.spawn(s, TANK, "tank", "api") + self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") + self.stop(s, TANK, "tank", REPORT.format(role="Backend engineer (Tank)", task="api")) + s.ok("progress", "assign", "review", "--to", "Seraph") + self.spawn(s, SERAPH, "seraph", "review") + report = REPORT.format(role="Code reviewer (Seraph)", task="review") + self.assertEqual(self.stop(s, SERAPH, "seraph", report).get("decision"), "block") # no step recorded + self.stop(s, SERAPH, "seraph", report, again=True) # let through + self.assertEqual(self.held(s, "review")[1], "unverified") + s.ok("progress", "reopen", "review", "--why", "the reviewer gives the verdict again") + self.subagent_start(s, SERAPH, "seraph") + self.assertEqual(self.held(s, "review"), (SERAPH, "running")) + r = self.member(s, SERAPH, "seraph", "progress", "step", "review done", "--step", "review", "--check", + "✓ read the diff, 12 tests pass", "--approves", "api") + self.assertEqual(r["rc"], 0, r["err"]) + self.stop(s, SERAPH, "seraph", report) + why = [h["why"] for h in s.run_doc()["history"] if h["step"] == "review"][-1] + self.assertEqual(self.held(s, "review")[1], "done", why) + + +class CodexCallerTests(CodexCoordination): + # On Codex the tech lead's own commands are "unverified", which main-only commands allow, so a member's open + # wait or quoting question never takes them (checked on 2026-11-19); the ack below still fails + def test_the_codex_tech_lead_acknowledges_with_a_digest_read_in_the_same_command(self): + s = self.run_lead("api=30m [backend]", ("api", "Tank", "api/**")) + self.spawn(s, TANK, "tank", "api") + self.member(s, TANK, "tank", "crew", "ask", "Report: " + "x" * 400) + ref = next(m["id"] for m in s.run_doc()["messages"] if m.get("to") == "main") + r = s.sh(f'dev crew ack {ref} --sha256 "$(dev crew read {ref} --json | python3 -I -c \'import json,sys; ' + f'print(json.load(sys.stdin)["digest"])\')" --generation 1') + self.assertEqual(r["rc"], 0, r["out"] + r["err"]) + self.assertIn("main", next(m for m in s.run_doc()["messages"] if m["id"] == ref).get("receipts") or {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_coordination_identity.py b/tests/test_coordination_identity.py new file mode 100644 index 00000000..67d6c5f2 --- /dev/null +++ b/tests/test_coordination_identity.py @@ -0,0 +1,66 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""Who calls: the tech lead's own commands are the tech lead's whatever the crew members' open calls say, and a +command the tech lead types whole, a nested read included, is the tech lead's. Each test reproduces a fault the crew +hit on devkit 26.11.25 (2026-11-19) through the real command line and call ledger, with that day's command texts. +Run: python3 -m unittest tests.test_coordination_identity""" +import json +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import progress as pg # noqa: E402 +from test_caller_identity import CallerCase # noqa: E402 +from test_progress import launch # noqa: E402 + + +class CoordinationCallerCase(CallerCase): + def plan_with_link(self): + # the Release engineer works on sig2625; ci-redirect is the tech lead's to start + with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): + pg.start("Release", plan=["sig2625", "ci-redirect"]) + pg.assign("sig2625", "Link", why="the test's assignment") + launch("a_link", "devkit:link", "Link: sig2625 Signature release") + + def state_of(self, name): + return next(s for s in self.run_()["plan"] if s["name"] == name).get("state") + + +class MemberWaitTests(CoordinationCallerCase): + def test_the_tech_leads_begin_stays_theirs_while_a_member_waits_on_a_question_that_quotes_it(self): + # B-igm6pqbcs6l4: three tries of the tech lead's `dev progress begin ci-redirect` were refused as "inside a + # crew member's call" while the Release engineer's `dev crew ask` waited for its answer; that question quoted + # the command, and the call ledger took the member's open call for the one that typed it + self.plan_with_link() + self.call('dev crew ask "dev commit refuses my ci-redirect commit: my lane\'s scope is still sig2625\'s ' + '(blocked, not closed), and dev progress begin is the tech lead\'s. Please start ci-redirect for ' + 'my lane (dev progress begin ci-redirect, or whatever links it)."', aid="a_link") + self.call("dev progress begin ci-redirect 2>&1 | tail -6") + rc, out = self.dev("progress", "begin", "ci-redirect") + self.assertEqual(rc, 0, out) + self.assertEqual(self.state_of("ci-redirect"), "running") + + +class NestedReadTests(CoordinationCallerCase): + def test_the_tech_lead_acknowledges_with_a_digest_read_in_the_same_command(self): + # B-igm4c0qjyobs: `dev crew ack REF --sha256 "$(dev crew read REF --json | python3 -c …)" --generation 1` + # was refused as not_recipient in the main session; the same two calls typed one after the other passed + self.plan_with_link() + report = pg.crew_ask("Report: " + "x" * 400, from_agent="a_link") + ref = report["id"] + self.call(f'dev crew read {ref} --json') + rc, out = self.dev("crew", "read", ref, "--json") + self.assertEqual(rc, 0, out) + page = json.loads(out) + self.call(f'dev crew ack {ref} --sha256 "$(dev crew read {ref} --json | python3 -I -c \'import json,sys; ' + f'print(json.load(sys.stdin)["digest"])\')" --generation 1') + rc, out = self.dev("crew", "ack", ref, "--sha256", page["digest"], "--generation", str(page["generation"])) + self.assertEqual(rc, 0, out) + self.assertIn("main", next(m for m in self.run_()["messages"] if m["id"] == ref).get("receipts") or {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_coordination_lanes.py b/tests/test_coordination_lanes.py new file mode 100644 index 00000000..9a0999b8 --- /dev/null +++ b/tests/test_coordination_lanes.py @@ -0,0 +1,147 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""Crew lanes and the plan steps they hold: how a member's record closes a step, which steps a lane takes when its +step closes or it is resumed, whose files a lane may write, and when two scopes clash. Each test reproduces a fault +the crew hit on devkit 26.11.25 (2026-11-19), at the function that decides it, with the inputs of that day. +Run: python3 -m unittest tests.test_coordination_lanes""" +import sys +import time +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import progress as pg # noqa: E402 +from test_approvals_token import StopCase # noqa: E402 +from test_progress import TempState, launch, member_call, progress_cli_out # noqa: E402 + +KID_REPORT = ("**[Firefly> DevKit · DevEx engineer (Kid)]** devkit · `fix/open-bugs` · {task}\n- **Done:** {task}\n" + "- **Check:** ✓ 605 tests pass\n- **Next:** the Code reviewer reviews it") + + +class LaneCase(unittest.TestCase): + def setUp(self): + self.state = TempState().__enter__() + self.addCleanup(self.state.__exit__, None, None, None) + self.t0 = time.time() - 3600 # the work comes before the real time a hook ends a lane at + + def m(self, minutes): + return self.t0 + minutes * 60 + + def run_(self): + return pg.load_run("claude", "s1") + + def held(self, name): + st = next(s for s in self.run_()["plan"] if s["name"] == name) + return st.get("owner"), st.get("state") + + def scope_of(self, aid): + return sorted({g for layer in pg.lane_scope(self.run_(), aid) for g in layer}) + + +class MemberRecordTests(LaneCase): + def test_a_members_checked_record_without_step_closes_its_lanes_only_running_step(self): + # registry #56: `dev progress step "…" --check "✓ …"` from a member printed ✓ and closed no plan step, so + # the member reported its step done while the plan kept it running + pg.start("Hotfix", plan=["parser=30m", "docs=15m"], now=self.m(0)) + pg.assign("parser", "Neo", scope="lib/devkit/shellparse.py", why="test", now=self.m(0)) + launch("a_neo", "devkit:neo", "Neo: parser timing fix", at=self.m(1)) + self.assertEqual(self.held("parser"), ("a_neo", "running")) + with member_call("a_neo"): + rc, out, err = progress_cli_out("step", "the parser times out after 2 s", "--check", "✓ 46 tests pass") + self.assertEqual(rc, 0, err) + self.assertIn("✓", out) + self.assertEqual(self.held("parser"), ("a_neo", "done"), out) + + +class QueuedStepTests(LaneCase): + def test_a_lane_whose_step_closes_takes_the_first_of_two_steps_assigned_to_its_member(self): + # F-igm4bz4ptvvr: the DevEx engineer's three steps were assigned by role before the launch, whose description + # named launch-warn. When launch-warn closed, the lane took neither reassign-notice nor lesson-review ("with + # two waiting devkit gives a lane neither"), and its scope stayed launch-warn's + pg.start("Open bugs", plan=["launch-warn=45m", "reassign-notice=45m", "lesson-review=60m"], now=self.m(0)) + pg.assign("launch-warn", "Kid", scope="lib/devkit/hooks.py", why="test", now=self.m(0)) + pg.assign("reassign-notice", "Kid", scope="lib/devkit/dispatch.py", why="test", now=self.m(0)) + pg.assign("lesson-review", "Kid", scope="lib/devkit/lessons.py", why="test", now=self.m(0)) + launch("a_kid", "devkit:kid", "Kid: launch-warn hook notice", at=self.m(1)) + self.assertEqual(self.held("launch-warn"), ("a_kid", "running")) + pg.step("launch-warn committed", which="launch-warn", check="✓ 605 tests pass", from_agent="a_kid", + now=self.m(20)) + self.assertEqual((self.held("reassign-notice"), self.held("lesson-review")), + (("a_kid", "running"), ("main", "pending"))) + self.assertEqual(self.scope_of("a_kid"), ["lib/devkit/dispatch.py"]) + + +class BlockedStepTests(LaneCase): + def test_a_blocked_step_leaves_its_lane_free_for_the_members_next_step_and_its_files(self): + # the Release engineer's sig2625 was blocked on the Actions budget; ci-redirect, assigned to him next, only + # "joins your lane once sig2625 closes", so dev commit refused ci-redirect's files and his + # `dev progress step --step ci-redirect` was refused + pg.start("Release", plan=["sig2625=60m", "ci-redirect=60m"], now=self.m(0)) + pg.assign("sig2625", "Link", scope="docs/signature.md", why="test", now=self.m(0)) + launch("a_link", "devkit:link", "Link: sig2625 Signature release", at=self.m(1)) + pg.step("PR #20's run started no job: the Actions budget is spent", kind="blocked", which="sig2625", + now=self.m(30)) + self.assertEqual(self.held("sig2625"), ("a_link", "blocked")) + pg.assign("ci-redirect", "Link", scope="lib/devkit/gitx.py,tests/test_gitx.py", why="test", now=self.m(31)) + self.assertEqual(self.held("ci-redirect"), ("a_link", "running")) + self.assertEqual(self.scope_of("a_link"), ["lib/devkit/gitx.py", "tests/test_gitx.py"]) + + +class ResumedLaneTests(LaneCase): + def test_a_resumed_lane_takes_the_one_step_assigned_to_its_member_by_role(self): + # a step assigned by role to a member whose lane had ended stayed the tech lead's when the member was resumed + # with SendMessage, so the member worked read-only and its first writes were credited as unverified + pg.start("Hotfix", plan=["test-guard=30m", "hermetic-fix=20m"], now=self.m(0)) + pg.assign("test-guard", "Mouse", scope="tests/_hermetic.py", why="test", now=self.m(0)) + launch("a_mouse", "devkit:mouse", "Mouse: test-guard detached sync refusal", at=self.m(1)) + pg.step("test-guard committed", which="test-guard", check="✓ 27 tests pass", from_agent="a_mouse", + now=self.m(20)) + pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a_mouse", "agent_type": "devkit:mouse", + "last_assistant_message": KID_REPORT.format(task="test-guard")}, False, + now=self.m(21)) + pg.assign("hermetic-fix", "Mouse", scope="tests/test_hermetic.py", why="test", now=self.m(25)) + pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a_mouse", "agent_type": "devkit:mouse"}, True, + now=self.m(26)) + self.assertEqual(self.held("hermetic-fix"), ("a_mouse", "running")) + self.assertEqual(self.scope_of("a_mouse"), ["tests/test_hermetic.py"]) + + +class ScopeClashTests(LaneCase): + def test_a_glob_of_files_does_not_clash_with_other_files_it_cannot_hold(self): + # S-g580qopirdu: `docs/**/bug*.md` was refused as overlapping the DevEx engineer's docs/crew.md and + # docs/agents.md, which no path it holds can be + pg.start("Docs", plan=["launch-warn=45m", "registry-docs=30m"], now=self.m(0)) + pg.assign("launch-warn", "Kid", scope="docs/crew.md,docs/agents.md", why="test", now=self.m(0)) + launch("a_kid", "devkit:kid", "Kid: launch-warn hook notice", at=self.m(1)) + try: + pg.assign("registry-docs", "Ghost", scope="docs/**/bug*.md", why="test", now=self.m(2)) + except pg.StepError as e: + self.fail(f"refused as a clash: {e}") + self.assertEqual(next(s for s in self.run_()["plan"] if s["name"] == "registry-docs")["scope"], + ["docs/**/bug*.md"]) + + +class ReviewAfterSendBackTests(StopCase): + # The Code reviewer's final review and the Product owner's tabs-approve: the crew gates sent the member back once, + # its next stop was let through, the tech lead reopened the step and resumed the member, who recorded it with + # `dev progress step --step review --approves api` and a ✓ Check and stopped with a report the gates pass. The + # review stayed unverified ("the crew gates did not pass its report"), and the work it approves stayed owed + def test_a_resumed_reviewers_clean_report_approves_after_an_earlier_send_back(self): + self.assertEqual(self.stop()[:1], "{") # sent back: the transcript records no step + self.stop(stop_hook_active=True) # let through without a pass + self.assertEqual(self.plan()["review"]["state"], "unverified") + pg.reopen("review", why="the reviewer is resumed to give the verdict again", now=self.at(30)) + pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a_seraph", "agent_type": "devkit:seraph"}, True, + now=self.at(31)) + self.assertEqual(self.plan()["review"]["state"], "running") + pg.step("review done", which="review", check="✓ read the diff, 9 tests pass", from_agent="a_seraph", + approves="api", now=self.at(40)) + self.stop(self.passing()) + why = [h["why"] for h in self.run_()["history"] if h["step"] == "review"][-1] + self.assertEqual(self.plan()["review"]["state"], "done", why) + self.assertEqual(pg.approvals_owed(self.run_()), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_coordination_model.py b/tests/test_coordination_model.py new file mode 100644 index 00000000..8c8b362c --- /dev/null +++ b/tests/test_coordination_model.py @@ -0,0 +1,449 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""A model-based hunt for crew coordination faults. Seeded random sequences of what the tech lead and up to three crew +members do in one run (assign, launch, a member's step record, block, skip, reopen, resume, a question and its answer, +a wait, a stop through the SubagentStop hook and its crew gates) drive the real progress records, on Claude Code or +on Codex (each sequence's launches pick the host of its session). After every action the run is checked against the +rules the crew relies on; each rule is one test below, and a broken rule fails with the shortest sequence that still +breaks it (delta debugging over the first counterexample found). Standard library only, seeded, deterministic. +Run: python3 -m unittest tests.test_coordination_model""" +import contextlib +import copy +import io +import json +import os +import random +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import canary, core, hooks, lessonevents # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_progress import TempState, launch # noqa: E402 + +REAL_CALLER = pg.caller # the call ledger's own verdict; TempState replaces pg.caller for the actions themselves +SEED, SEQUENCES, LENGTH = 20261119, 48, 28 +MEMBERS = {"tank": ("Tank", "Backend engineer"), "trinity": ("Trinity", "Frontend engineer"), + "seraph": ("Seraph", "Code reviewer")} +PLAN = "api=30m [backend]; export=30m [backend]; ui=30m [frontend]; polish=20m [frontend]; review=20m [review] after api" +STEPS = {"api": "tank", "export": "tank", "ui": "trinity", "polish": "trinity", "review": "seraph"} +SCOPES = {"api": "api/**", "export": "export/**", "ui": "ui/**", "polish": "polish/**", "review": ""} +OPEN = ("running", "pending", "blocked") + + +KINDS = ["assign", "launch", "step", "block", "skip", "reopen", "resume", "ask", "answer", "wait", "stop"] + + +def propose(rng: random.Random, w=None) -> dict: + """One abstract action. With the world at hand, most proposals follow a step's life (assign it, launch its + member, record it, stop, reopen, resume), so a sequence reaches deep states; the rest are uniform.""" + kind, member, step = rng.choice(KINDS), rng.choice(sorted(MEMBERS)), rng.choice(sorted(STEPS)) + if w is not None and rng.random() < 0.7: + step = rng.choice(sorted(STEPS) + ["review", "review"]) # the review's life is the longest chain + plan = w.plan() + step = next((d for d in plan[step].get("after") or [] if plan[d]["state"] not in ("done", "skipped")), step) + member, s = STEPS[step], plan[step] + lane = w.lanes.get(member) + if s["state"] in ("done", "skipped", "unverified"): + again = 0.8 if s["state"] == "unverified" else 0.3 # unverified work waits for a reopen + kind = "reopen" if rng.random() < again else ("resume" if lane in w.ended else "stop") + elif not s.get("label"): + kind = "assign" + elif not w.live(member): + kind = "resume" if lane in w.ended and rng.random() < 0.8 else "launch" + elif not any(f"--step {step}" in c for c in w.commands.get(w.live(member), [])): + kind = rng.choice(["step", "step", "step", "ask", "wait", "answer", "assign"]) # record it first + else: + kind = rng.choice(["stop", "stop", "step", "ask", "wait", "answer"]) + if kind in ("assign", "block", "skip", "reopen"): + member = STEPS[step] + return {"do": kind, "member": member, "step": step, "how": rng.choice(["role", "label"]), + "named": rng.random() < 0.6, "clean": rng.random() < 0.6} + + +def generate(rng: random.Random, host: str) -> tuple: + """One sequence, built by running it: each slot takes the first of a few proposals that applies -> (the + actions, the rules they broke).""" + seq = [] + with World(host) as w: + for _ in range(LENGTH): + for _ in range(6): + a = propose(rng, w) + if w.act(a): + seq.append(a) + break + return seq, w.violations + + +def name_of(a): + return MEMBERS[a["member"]][0] + + +def show(seq: list) -> str: + def one(a): + extra = {"assign": f"{a['step']} by {a['how']}", "step": f"--step {a.get('used')}" if a["named"] else "(no --step)", + "stop": "clean" if a["clean"] else "sent back, then let through", "block": a["step"], + "skip": a["step"], "reopen": a["step"], "launch": f"“{name_of(a)}: {a.get('used')}”", "resume": "", "ask": "", "answer": "", + "wait": ""}[a["do"]] + who = "" if a["do"] in ("assign", "block", "skip", "reopen", "answer") else MEMBERS[a["member"]][0] + " " + return f"{a['do']} {who}{extra}".strip() + return " → ".join(f"{i}. {one(a)}" for i, a in enumerate(seq, 1)) + + +class World: + """One run in a temporary devkit home, driven through the real progress API and hooks.""" + + def __init__(self, host: str): + self.host = host + self.violations = {} + self.lanes, self.ended, self.count, self.calls, self.commands = {}, set(), 0, {}, {} + self.waiting_q = [] # (message id, member) of questions waiting for the tech lead's answer + self.t0 = time.time() - 50 * 60 + self.k = 0 + + def __enter__(self): + self.state = TempState().__enter__() + root = Path(self.state.tmp.name) + tools = root / "bin" + tools.mkdir() + (tools / "dev").symlink_to(core.DEVKIT_HOME / "bin" / "dev") + self.patches = [mock.patch.dict(os.environ, {"PATH": str(tools) + os.pathsep + os.environ["PATH"], + "DEVKIT_SESSION": f"{self.host}:s1"}), + mock.patch.object(hooks, "STATE", root), mock.patch.object(canary, "LOG", root / "canary"), + mock.patch.object(lessonevents, "EVENTS", root / "lesson-events")] + for p in self.patches: + p.start() + if self.host == "codex": + (pg.SESSIONS / "codex-s1.json").write_text(json.dumps({"agent": "codex", "session": "s1", + "started": self.t0, "project": "acme/api"})) + pg.start("Invoice export", plan=PLAN, now=self.now()) + return self + + def __exit__(self, *exc): + for p in reversed(self.patches): + p.stop() + self.state.__exit__(*exc) + + def now(self): + self.k += 1 + return self.t0 + self.k * 60 + + def run_(self): + return pg.load_run(self.host, "s1") + + def plan(self): + return {s["name"]: s for s in self.run_()["plan"]} + + def live(self, member): + aid = self.lanes.get(member) + return aid if aid and (self.run_()["agents"].get(aid) or {}).get("state") == "running" else None + + # ---------------------------------------------------------------- the call ledger + + def open_call(self, cmd, aid=None): + self.count += 1 + data = {"session_id": "s1", "tool_use_id": f"toolu_m{self.count:04d}", "tool_name": "Bash", + "tool_input": {"command": cmd}} + if aid: + data["agent_id"] = aid + pg.call_opened(self.host, data) + return data + + def close_member_call(self, member): + data = self.calls.pop(member, None) + if data: + pg.call_closed(data) + + def main(self, argv, fn): + """A command of the tech lead's: its open call in the ledger, attributed as the ledger reads it (I5).""" + data = self.open_call(" ".join(["dev"] + [json.dumps(a) if " " in a else a for a in argv])) + try: + who = REAL_CALLER(argv=argv)["caller"] + if who not in ("main", "unverified"): + self.flag("main-calls-are-mains", f"the tech lead's `dev {' '.join(argv[:3])}` was attributed to " + f"{who} while members waited in: " + "; ".join( + f"{MEMBERS[m][0]}: {c['tool_input']['command'][:70]}" for m, c in self.calls.items())) + with mock.patch.object(sys, "argv", ["dev", *argv]): + return fn() + except pg.StepError: + return None + finally: + pg.call_closed(data) + + def flag(self, rule, text): + self.violations.setdefault(rule, text) + + # ---------------------------------------------------------------- actions + + def act(self, a): + member, step = a["member"], a["step"] + name = MEMBERS[member][0] + before = {k: v.get("state") for k, v in self.plan().items()} + if a["do"] not in ("ask", "wait"): + self.close_member_call(member) # a member that acts again has finished its wait + expect = None + if a["do"] == "assign": + aid = self.lanes.get(member) + label = name if a["how"] == "role" or not aid else self.run_()["agents"][aid]["label"] + argv = ["progress", "assign", step, "--to", label] + (["--scope", SCOPES[step]] if SCOPES[step] else []) + self.main(argv, lambda: pg.assign(step, label, scope=SCOPES[step], why="model", now=self.now())) + elif a["do"] == "launch": + if self.live(member) or (self.lanes.get(member) and self.lanes[member] not in self.ended): + return False + mine = [s for s, m in STEPS.items() if m == member and self.plan()[s]["state"] == "pending" + and (self.plan()[s].get("label") or "").lower().startswith(name.lower())] + task = mine[0] if mine else step if STEPS[step] == member else "work" + a["used"] = task + aid = f"a{member}{len(self.lanes) + len(self.ended) + 1}" + try: + launch(aid, member if self.host == "codex" else f"devkit:{member}", f"{name}: {task}", at=self.now(), + agent=self.host) + except AssertionError: # Codex's admission refused the launch (a slot, the order): nothing started + return False + self.lanes[member] = aid + self.ended.discard(aid) + elif a["do"] == "step": + aid = self.live(member) + if not aid: + return False + running = [s for s, st in self.plan().items() if st.get("owner") == aid and st.get("state") == "running"] + which = (running[0] if running else step) if a["named"] else None + a["used"] = which + text = f"{which or 'my work'} committed" + try: + pg.step(text, which=which, check="✓ 12 tests pass", from_agent=aid, now=self.now(), + approves="api" if which == "review" else "") + except pg.StepError: + return False + self.commands.setdefault(aid, []).append( + f'dev progress step "{text}"' + (f' --step {which}' if which else "") + ' --check "✓ 12 tests pass"') + # I3b: the record closes the step it names, or its lane's only running step when it names none + target = which if which in running else (running[0] if not which and len(running) == 1 else None) + if target and target != "review": + expect = target + elif a["do"] == "block": + if before[step] not in ("running", "pending"): + return False + self.main(["progress", "block", "waits for the developer", "--step", step], + lambda: pg.step("waits for the developer", kind="blocked", which=step, now=self.now())) + elif a["do"] == "skip": + if before[step] in ("done", "skipped"): + return False + self.main(["progress", "skip", step, "--why", "out of scope"], + lambda: pg.reopen(step, "out of scope", skip=True, now=self.now())) + elif a["do"] == "reopen": + if before[step] not in ("done", "skipped", "unverified"): + return False + self.main(["progress", "reopen", step, "--why", "the review found a gap"], + lambda: pg.reopen(step, "the review found a gap", now=self.now())) + elif a["do"] == "resume": + aid = self.lanes.get(member) + if not aid or aid not in self.ended: + return False + pg.on_subagent(self.host, {"session_id": "s1", "agent_id": aid, + "agent_type": member if self.host == "codex" else f"devkit:{member}"}, True, + now=self.now()) + self.ended.discard(aid) + elif a["do"] in ("ask", "wait"): + aid = self.live(member) + if not aid or member in self.calls: + return False + if a["do"] == "ask": + cmd = f'dev crew ask "May I go on with {step}? (dev progress begin {step} or whatever links it)"' + try: + q = pg.crew_ask(cmd[len('dev crew ask "'):-1], from_agent=aid, now=self.now()) + self.waiting_q.append((q["id"], member)) + except Exception: + return False + else: + cmd = "dev watch --wait --for me --timeout 9" + self.calls[member] = self.open_call(cmd, aid) # in the foreground: open until the member acts again + if a["do"] == "ask": # the tech lead's begin of the step the question quotes, while it waits + self.main(["progress", "begin", step], lambda: pg.begin(step, now=self.now())) + elif a["do"] == "answer": + if not self.waiting_q: + return False + mid, asker = self.waiting_q.pop(0) + self.main(["crew", "answer", mid, "yes, go on"], lambda: pg.crew_answer(mid, "yes, go on", now=self.now())) + self.close_member_call(asker) + elif a["do"] == "stop": + aid = self.live(member) + if not aid: + return False + review = self.plan()["review"] + ready = review.get("owner") == aid and review.get("state") == "running" and any( + "--step review" in c for c in self.commands.get(aid, [])) + if a["clean"]: + self.stop(aid, member, self.commands.get(aid, [])) + else: + self.stop(aid, member, []) # a transcript with no step record: sent back once + self.stop(aid, member, [], again=True) + self.ended.add(aid) + if a["clean"] and ready: # I4: a clean report of a ✓ record of its own review is judged on its own + state = self.plan()["review"]["state"] + if state != "done": + why = [h["why"] for h in self.run_().get("history") or [] if h["step"] == "review"][-1:] + self.flag("clean-review-approves", f"review stayed {state} after its reviewer's clean report: " + f"{why[0] if why else ''}") + self.check(a, before, expect) + return True + + def stop(self, aid, member, commands, again=False): + """The member's stop through the SubagentStop hook: canary, crew gates, the lane's end.""" + root = Path(self.state.tmp.name) + tr = root / f"transcript-{aid}-{self.k}.jsonl" + records = [] + for i, command in enumerate(commands, 1): + records += [{"type": "assistant", "isSidechain": True, "message": {"role": "assistant", "content": [ + {"type": "tool_use", "id": f"toolu_{i:04}", "name": "Bash", "input": {"command": command}}]}}, + {"type": "user", "isSidechain": True, "message": {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": f"toolu_{i:04}", "content": "ok"}]}}] + tr.write_text("".join(json.dumps(r) + "\n" for r in records)) + name, role = MEMBERS[member] + report = (f"**[Firefly> DevKit · {role} ({name})]** api · `main` · the work\n- **Done:** the work\n" + "- **Check:** ✓ 12 tests pass\n- **Next:** the tech lead reviews it") + data = {"session_id": "s1", "agent_id": aid, "agent_type": member if self.host == "codex" else + f"devkit:{member}", "agent_transcript_path": str(tr), "last_assistant_message": report, + "stop_hook_active": again} + with mock.patch("sys.stdin", io.StringIO(json.dumps(data))), contextlib.redirect_stdout(io.StringIO()): + hooks.subagent_stop(self.host) + + # ---------------------------------------------------------------- the rules + + def check(self, a, before, expect): + run = self.run_() + plan, agents = {s["name"]: s for s in run["plan"]}, run.get("agents") or {} + live = {aid for aid, lane in agents.items() if lane.get("state") == "running"} + for name, s in plan.items(): + if s.get("state") == "running" and s.get("label") and s.get("owner", "main") != "main" \ + and s["owner"] not in live: + self.flag("running-step-has-a-live-lane", f"“{name}” runs in lane {s['owner']}, which is " + f"{(agents.get(s['owner']) or {}).get('state')}") + for aid in live: + layers = pg.lane_scope(run, aid) + writable = {g for layer in layers for g in layer} + mine = [s for s in plan.values() if s.get("owner") == aid] + running = {g for s in mine if s.get("state") == "running" for g in s.get("scope") or []} + for s in mine: + files = set(s.get("scope") or []) - running + if s.get("state") == "running" and not all(pg.in_scope(g.rstrip("*") + "x.py", layers) + for g in s.get("scope") or []): + self.flag("running-step-files-writable", f"lane {aid} runs “{s['name']}” but may not write " + f"its files {s.get('scope')}: its scope is {sorted(writable)}") + if s.get("state") == "blocked" and files & writable: + self.flag("blocked-step-files-released", f"lane {aid} still holds blocked “{s['name']}”'s " + f"files {sorted(files & writable)}") + if s.get("state") in ("done", "skipped") and files & writable: + self.flag("closed-step-files-released", f"lane {aid} still holds {s['state']} “{s['name']}”'s " + f"files {sorted(files & writable)}") + if not [s for s in mine if s.get("state") == "running"]: + member = (agents[aid].get("persona") or "").lower() + ready = [s["name"] for s in plan.values() if s.get("state") == "pending" and + (s.get("owner") or "main") == "main" and STEPS.get(s["name"]) == member and + (s.get("label") or "").lower().startswith(member) and not pg.deps_open(run, s) + and not [x for x in pg._queued_lanes(s) if x != aid]] + if ready: + self.flag("free-lane-takes-its-members-step", f"lane {aid} ({member}) holds no running step " + f"while {ready} wait for {member}") + for name, s in plan.items(): + if s.get("state") == "done" and before.get(name) != "done": + ok = (a["do"] == "step" and name == expect) or a["do"] == "stop" or \ + (a["do"] == "step" and a["named"] and s.get("owner") == self.lanes.get(a["member"])) + if not ok: + self.flag("closes-only-what-it-names", f"“{name}” closed on {a['do']} of {a['member']}") + if expect and plan[expect].get("state") != "done": + self.flag("checked-record-closes-its-step", f"{MEMBERS[a['member']][0]}'s ✓ record " + f"{'naming' if a['named'] else 'without --step, its lane running only'} “{expect}” left it " + f"{plan[expect].get('state')}") + + +RULES = { + "running-step-has-a-live-lane": "a running step belongs to exactly one live lane", + "running-step-files-writable": "a lane may write the files of each step it runs", + "blocked-step-files-released": "a lane's write scope never keeps a blocked step's files", + "closed-step-files-released": "a lane's write scope never keeps a done or skipped step's files", + "free-lane-takes-its-members-step": "a live lane with no running step takes a ready step assigned to its member", + "closes-only-what-it-names": "a step closes only by a record that names it, its lane's single running step, or " + "its lane's end", + "checked-record-closes-its-step": "a member's ✓ record closes the step it names, or its lane's only running step", + "clean-review-approves": "a reviewer's ✓ record of its own review is judged by the current rules whatever " + "earlier send-backs", + "main-calls-are-mains": "every main-session call is attributed to the main session whatever members wait", +} + + +def violations(host, seq) -> dict: + with World(host) as w: + for a in seq: + w.act(a) + return w.violations + + +def shrink(host, seq, rule) -> tuple: + """The shortest subsequence that still breaks `rule` (one-at-a-time and halving removals), and its message.""" + best = copy.deepcopy(seq) # its own actions: each records what it did in the replay + text = violations(host, best)[rule] + chunk = max(1, len(best) // 2) + while chunk >= 1: + i, changed = 0, False + while i < len(best): + trial = best[:i] + best[i + chunk:] + got = violations(host, trial) if trial else {} + if rule in got: + best, text, changed = trial, got[rule], True + else: + i += chunk + if not changed: + chunk //= 2 + violations(host, best) # replayed last, so each action shows what it did in this sequence + return best, text + + +class CoordinationModelTests(unittest.TestCase): + # Three rules the hunt also checks hold on 26.11.26 (a running step has a live lane, a lane may write its running + # steps' files, a step closes only by what names it): they get tests of their own once a fix could break them + found = None + + @classmethod + def hunt(cls): + if cls.found is None: + rng, first = random.Random(SEED), {} + for n in range(SEQUENCES): + host = "codex" if n % 2 else "claude" + seq, broken = generate(rng, host) + for rule in broken: + first.setdefault(rule, (host, seq)) + cls.found = {rule: (host,) + shrink(host, seq, rule) for rule, (host, seq) in sorted(first.items())} + return cls.found + + def holds(self, rule): + got = self.hunt().get(rule) + if got: + host, seq, text = got + self.fail(f"{RULES[rule]}: broken on {host} by {show(seq)}\n → {text}") + + def test_a_lanes_scope_never_keeps_a_blocked_steps_files(self): + self.holds("blocked-step-files-released") + + def test_a_lanes_scope_never_keeps_a_closed_steps_files(self): + self.holds("closed-step-files-released") + + def test_a_free_lane_takes_a_ready_step_assigned_to_its_member(self): + self.holds("free-lane-takes-its-members-step") + + def test_a_members_checked_record_closes_its_step(self): + self.holds("checked-record-closes-its-step") + + def test_a_clean_review_report_approves_whatever_earlier_send_backs(self): + self.holds("clean-review-approves") + + def test_every_main_session_call_is_the_main_sessions(self): + self.holds("main-calls-are-mains") + + +if __name__ == "__main__": + unittest.main() From 61b5fd179a14606b7056d5f034444f5b6cb74b60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:22:38 -0800 Subject: [PATCH 02/52] fix(progress): add coordination rules and stop false scope clashes A file glob such as docs/crew.md was read as a folder, so docs/**/bug*.md was refused as overlapping it; and the identity token needs its hash in the call entry's first write. Root cause: progress._glob_segments appended an implicit ** to every glob, so a literal file name overlapped any recursive glob in its folder coord.py holds the pure rules: held steps, derived scope, intents, claims, block and unblock, the invariant check and the glob overlap. call_opened takes an optional token_sha256 written in the same atomic write. Verified: python3 -m unittest tests.test_progress tests.test_lanescope tests.test_scope tests.test_coord_kernel tests.test_coord_calltoken: OK; the QA glob clash test now passes --- lib/devkit/coord.py | 423 ++++++++++++++++++++++++++++++++++ lib/devkit/progress.py | 151 ++++-------- tests/test_coord_calltoken.py | 42 ++++ tests/test_coord_kernel.py | 224 ++++++++++++++++++ 4 files changed, 738 insertions(+), 102 deletions(-) create mode 100644 lib/devkit/coord.py create mode 100644 tests/test_coord_calltoken.py create mode 100644 tests/test_coord_kernel.py diff --git a/lib/devkit/coord.py b/lib/devkit/coord.py new file mode 100644 index 00000000..d3a2670b --- /dev/null +++ b/lib/devkit/coord.py @@ -0,0 +1,423 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The crew's coordination rules, in one place, as pure functions over a run record: no files, no hooks, and no +clock but the `now` a caller passes. progress.py calls them inside its own transaction, and so do the hooks through +progress.py, so every path that gives, takes, blocks or closes a step reads the same definitions. + +- A lane *holds* the steps it owns in state running, and only those: a blocked, unverified, done, skipped or pending + step holds no lane. Its write scope is the union of the globs of the steps it holds (`scope`), never a stored copy. +- A lane is *busy* while it holds a step that is not a review; review steps share a lane. +- An *intent* says who the tech lead gave a pending step to: a member (any of its lanes may take it) or one lane. + It lives on the step, so a lane's end, stop or resume never loses it, and only a claim, a new assignment, the step + leaving pending or the run's end removes it. +- A free lane *claims* the step its launch names first, then an answered blocked step put back at the front, then + the steps bound to it, then its member's, each oldest first (`claimable`). +- `check` returns the invariants a run record breaks, by id (I-owner, I-one-step, I-scope, I-separate, I-intent, + I-claim, I-history), so a test can check every action. + +The scope glob rules live here too (`segments`, `globs_overlap`), since the overlap check that keeps two working +lanes apart is part of the same contract.""" +from __future__ import annotations + +import fnmatch + +OPEN = ("running",) # the only state that holds a lane and gives it scope +DONE = ("done", "skipped") +UNCLAIMABLE_BINDING = ("conflict", "unbound", "pending") # a lane not bound to a launch of its own takes no step + + +def _plain_review(s: dict) -> bool: + return s.get("activity") == "review" + + +def _rv(review): + return review or _plain_review + + +# --------------------------------------------------------------------------- lanes and members + +def member_of(label: str) -> str: + """The member a step's label names: "Tank" for "Tank" and for the launch description "Tank: the API".""" + return (label or "").split(":", 1)[0].strip() + + +def label_matches(label: str, lane: dict) -> bool: + """A step assigned to "Neo" belongs to the lane launched as "Neo: build the parser", or as devkit:neo.""" + lab = (label or "").strip().lower() + if not lab or not isinstance(lane, dict): + return False + names = [(lane.get("label") or "").lower(), (lane.get("persona") or "").lower(), (lane.get("type") or "").lower()] + return any(n and (n == lab or n.startswith(lab + ":") or n.startswith(lab + " ") or n.endswith(":" + lab) + or lab in n.split(":")[0]) for n in names) + + +def can_claim(lane: dict) -> bool: + """May this lane take a step now? A member's own lane (not a helper's), running, bound to its launch, and not + over the crew's limits or waiting for a slot.""" + return isinstance(lane, dict) and lane.get("state") == "running" and (lane.get("parent") or "main") == "main" \ + and lane.get("binding") not in UNCLAIMABLE_BINDING and not lane.get("over_limit") \ + and not lane.get("waits_slot") + + +def held(run: dict, aid: str) -> list: + """The steps lane `aid` owns in state running, in plan order.""" + return [s for s in (run or {}).get("plan") or [] if s.get("owner") == aid and s.get("state") in OPEN] + + +def busy(run: dict, aid: str, step: dict | None = None, review=None) -> bool: + """Does lane `aid` hold a step that keeps it from taking `step`? Any other step it holds, except that reviews + share a lane: for a review `step`, the lane's other reviews do not count. Without `step`: whether it holds a + step that is not a review.""" + rv = _rv(review) + for x in held(run, aid): + if x is step: + continue + if rv(x) and (step is None or rv(step)): + continue + return True + return False + + +def scope(run: dict, aid: str) -> list: + """The globs lane `aid` may write: the union of the scopes of the steps it holds, sorted. [] when it holds no + step, or only steps without a scope; progress.lane_scope tells those two apart for the edit check.""" + return sorted({g for s in held(run, aid) for g in s.get("scope") or [] if isinstance(g, str) and g}) + + +def deps_open(run: dict, s: dict, review=None) -> list: + """The steps `s` waits for that are not done or skipped, in the order of its `after`. A review does not wait for + an unverified step: its Check is the verdict on that work.""" + steps = {x.get("name"): x for x in (run or {}).get("plan") or []} + out = [a for a in s.get("after") or [] if a in steps and steps[a].get("state") not in DONE] + if any(steps[a].get("state") == "unverified" for a in out) and _rv(review)(s): + out = [a for a in out if steps[a].get("state") != "unverified"] + return out + + +# --------------------------------------------------------------------------- intents + +def intent(step: dict) -> dict | None: + """Who the tech lead gave pending step `step` to -> {"member", "lane", "rev", "ts", "by", "front"}, or None. + From `step["intent"]`; else from a queue entry of a run written before intents (`waits_lane`: one lane, or the + exact form, bind to that lane; several lanes become the member's); else, for a pending step assigned by role + that waits for a launch, the member, from the time it was assigned.""" + if not isinstance(step, dict): + return None + it = step.get("intent") + if isinstance(it, dict): + return {"member": it.get("member") or member_of(step.get("label")), "lane": it.get("lane") or None, + "rev": it.get("rev") or 0, "ts": it.get("ts") or 0, "by": it.get("by") or "main", + "front": bool(it.get("front"))} + w = step.get("waits_lane") + member = member_of(step.get("label")) + if isinstance(w, dict) and (w.get("lane") or w.get("lanes")): + lanes = [str(x) for x in (w.get("lanes") or [w.get("lane")]) if x] + return {"member": member, "lane": lanes[0] if len(lanes) == 1 and not w.get("lanes") else None, + "rev": w.get("revision") or step.get("assignment_revision") or 0, "ts": w.get("ts") or 0, + "by": "main", "front": False} + if step.get("state") == "pending" and member and (step.get("owner") or "main") == "main": + return {"member": member, "lane": None, "rev": step.get("assignment_revision") or 0, + "ts": step.get("assigned_at") or step.get("added") or 0, "by": "main", "front": False} + return None + + +def set_intent(run: dict, step: dict, member: str, lane: str | None, now: float, front: bool = False) -> dict: + """Record that `step` goes to `member`, to its lane `lane` when one is named. It replaces any earlier intent and + any legacy queue entry; `front` puts it ahead of the lane's other intents (an answered blocked step).""" + step.pop("waits_lane", None) + step["intent"] = {"member": member, "lane": lane or None, "rev": step.get("assignment_revision") or 0, + "ts": round(now, 3), "by": "main", "front": bool(front)} + return step["intent"] + + +def drop_intent(step: dict): + step.pop("intent", None) + step.pop("waits_lane", None) + + +def queued_lanes(step: dict) -> list: + """The lanes a pending step is bound to by its intent ([] for a member-wide one or none). A legacy entry for + several lanes lists them all.""" + w = step.get("waits_lane") if "intent" not in step else None + if isinstance(w, dict) and w.get("lanes"): + return [str(x) for x in w["lanes"] if x] + it = intent(step) if step.get("state", "pending") == "pending" else None + return [it["lane"]] if it and it.get("lane") else [] + + +def claimable(run: dict, aid: str, launch_named=None, member_wide: bool = True, review=None) -> dict | None: + """The step lane `aid` takes now, or None: of the pending steps whose dependencies are done and whose intent + names this lane, or its member with no lane (unless `member_wide` is False: a resume whose member has a new + launch on its way leaves those to that launch), and that the lane is free for (busy), the step its launch names + (`launch_named`: a step or its name), then a front intent, then a lane-bound one, then a member-wide one, each + oldest first, then in plan order.""" + lane = ((run or {}).get("agents") or {}).get(aid) + if not can_claim(lane): + return None + named = launch_named.get("name") if isinstance(launch_named, dict) else launch_named + found = [] + for i, s in enumerate(run.get("plan") or []): + if s.get("state") != "pending": + continue + it = intent(s) + if not it: + continue + if it["lane"]: + if it["lane"] != aid: + continue + elif not member_wide or not label_matches(it["member"], lane): + continue + if deps_open(run, s, review) or busy(run, aid, s, review): + continue + rank = 0 if named and s.get("name") == named else 1 if it["front"] else 2 if it["lane"] else 3 + found.append((rank, it["ts"] or 0, i, s)) + return min(found, key=lambda t: t[:3])[3] if found else None + + +def claim(run: dict, aid: str, now: float, why: str, launch_named=None, member_wide: bool = True, + review=None) -> dict | None: + """Lane `aid` takes the step `claimable` chooses: pending -> running in that lane, its intent removed, with a + history entry. -> the step, or None.""" + s = claimable(run, aid, launch_named, member_wide, review) + if s is None: + return None + s.update(owner=aid, state="running", started=s.get("started") or now) + drop_intent(s) + _history(run, s, "pending", "running", "devkit", why, now) + return s + + +# --------------------------------------------------------------------------- blocking + +def block(run: dict, step: dict, decision_id: str, now: float, why: str = "", by: str = "main"): + """A running step waits for a decision (or the tech lead's `dev progress block`): blocked, its owner kept (the + lane the answer returns it to), and it no longer holds that lane or gives it scope.""" + old = step.get("state") + step["state"] = "blocked" + if decision_id: + step["waiting"] = decision_id + _history(run, step, old, "blocked", by, why or (f"waiting for {decision_id}" if decision_id else "blocked"), now) + + +def unblock(run: dict, step: dict, lane_live: bool, now: float, why: str = "", review=None) -> str: + """The decision a blocked step waited for is answered or withdrawn. Its lane still works and is free: it runs + there again. Its lane works on another step: it waits first in that lane's intents. Its lane is gone: it waits + first in its member's intents, for that member's next lane (never back to the tech lead). The tech lead's own + blocked step runs again. -> "running" | "pending".""" + step.pop("waiting", None) + owner = step.get("owner") or "main" + why = why or "the decision it waited for is answered" + if owner == "main" or (lane_live and not busy(run, owner, step, review)): + step["state"] = "running" + _history(run, step, "blocked", "running", "main", why, now) + return "running" + step.update(state="pending", owner="main", started=None) + if lane_live: + set_intent(run, step, member_of(step.get("label")), owner, now, front=True) + _history(run, step, "blocked", "pending", "main", f"{why}; its lane works on another step: it joins that " + f"lane first once that step closes", now) + else: + set_intent(run, step, member_of(step.get("label")), None, now, front=True) + _history(run, step, "blocked", "pending", "main", f"{why}; its lane ended: it goes first to its member's " + f"next lane", now) + return "pending" + + +# --------------------------------------------------------------------------- outcomes and invariants + +def states(run: dict) -> dict: + """{step name: state}, taken before a change for `changes`.""" + return {s.get("name"): s.get("state") for s in (run or {}).get("plan") or []} + + +def changes(before: dict, run: dict) -> list: + """The steps whose state differs from `before` -> [(name, from, to)] in plan order (from None for a new step).""" + return [(s.get("name"), before.get(s.get("name")), s.get("state")) for s in (run or {}).get("plan") or [] + if before.get(s.get("name")) != s.get("state")] + + +def _history(run: dict, s: dict, old, new, by: str, why: str, now: float): + run.setdefault("history", []).append({"ts": round(now), "step": s.get("name"), "from": old, "to": new, + "by": by or "main", "why": (why or "")[:300]}) + run["history"] = run["history"][-200:] + + +def check(run: dict, now: float, review=None) -> list: + """The invariants run record `run` breaks -> ["I-owner: …", …], [] when it is sound.""" + out = [] + plan, agents = (run or {}).get("plan") or [], (run or {}).get("agents") or {} + live = {k for k, v in agents.items() if isinstance(v, dict) and v.get("state") == "running"} + rv = _rv(review) + for s in plan: + owner = s.get("owner") or "main" + if s.get("state") in OPEN and owner != "main" and owner not in live: + out.append(f"I-owner: “{s.get('name')}” runs in lane {owner}, which is " + f"{(agents.get(owner) or {}).get('state') or 'unknown'}") + if s.get("state") != "pending" and "intent" in s: + out.append(f"I-intent: {s.get('state')} “{s.get('name')}” still carries an intent") + for aid in sorted(agents): + lane = agents[aid] + builds = [s.get("name") for s in held(run, aid) if not rv(s)] + if len(builds) > 1: + out.append(f"I-one-step: lane {aid} runs {', '.join(builds)}") + if isinstance(lane, dict) and ("scope" in lane or "handed_over" in lane): + out.append(f"I-scope: lane {aid} keeps a stored scope or hand-over, which no running step gives it") + if aid in live: + s = claimable(run, aid, review=review) + if s is not None: + out.append(f"I-claim: lane {aid} is free while “{s.get('name')}” waits for it") + ids = sorted(live) + for i, a in enumerate(ids): + for b in ids[i + 1:]: + ga, gb = _scoped(run, a), _scoped(run, b) + clash = [(x, y) for x, ca in ga for y, cb in gb if (not ca or not cb or ca == cb) + and not x.startswith(("/", "~")) and globs_overlap(x, y)] + if clash: + out.append(f"I-separate: lanes {a} and {b} both hold {clash[0][0]} / {clash[0][1]}") + count = sum(1 for s in plan if s.get("state") in DONE) + if (run or {}).get("step", count) != count: + out.append(f"I-history: the run counts {run.get('step')} closed steps, the plan has {count}") + last = {} + for h in (run or {}).get("history") or []: + last[h.get("step")] = h + for s in plan: + h = last.get(s.get("name")) + if h and h.get("to") != s.get("state") and h.get("to") != h.get("from"): + out.append(f"I-history: “{s.get('name')}” is {s.get('state')}, its last history entry says {h.get('to')}") + return out + + +def _scoped(run: dict, aid: str) -> list: + return [(g, s.get("checkout") or "") for s in held(run, aid) for g in s.get("scope") or [] if isinstance(g, str)] + + +# --------------------------------------------------------------------------- scope globs +# A glob is matched segment by segment: `*`, `?` and `[…]` match inside one segment and never cross `/`, and `**` +# as a whole segment matches any number of segments, none included. A glob that names a folder holds everything +# under it: one that ends with `/` or `**`, one whose last segment has a wildcard (`src/*` matches the folder +# src/studio), and a literal name that is a folder. A literal name that is a file (`docs/crew.md`) holds only +# itself, so no other glob can reach a path under it. + +def _wild(seg: str) -> bool: + return any(c in seg for c in "*?[") + + +def segments(glob: str, folder: bool = True) -> list: + """A glob as its segments, ending with the "**" that holds what lies under a folder it names; `folder` False for + a glob whose literal last segment is a file.""" + segs = [s for s in str(glob or "").split("/") if s not in ("", ".")] + if segs and segs[-1] == "**": + return segs + return segs + ["**"] if folder or str(glob or "").endswith("/") or (segs and _wild(segs[-1])) else segs + + +def names_folder(glob: str, kind=None) -> bool: + """Can glob `glob` name a folder? Yes when it ends with `/` or `**`, or its last segment has a wildcard. A + literal last segment is a folder when `kind(glob)` says "dir", a file when it says "file"; with no answer (no + checkout at hand, or nothing there yet), a name with a suffix (`crew.md`) is a file, one without a folder.""" + g = str(glob or "") + segs = [s for s in g.split("/") if s not in ("", ".")] + if not segs or g.endswith("/") or segs[-1] == "**" or _wild(segs[-1]): + return True + k = kind(g.rstrip("/")) if kind else None + if k in ("dir", "file"): + return k == "dir" + return "." not in segs[-1][1:] + + +def segments_match(segs: list, pat: list) -> bool: + memo = {} + + def go(i, j): + if (i, j) not in memo: + if j == len(pat): + memo[(i, j)] = i == len(segs) + elif pat[j] == "**": + memo[(i, j)] = go(i, j + 1) or (i < len(segs) and go(i + 1, j)) + else: + memo[(i, j)] = i < len(segs) and fnmatch.fnmatchcase(segs[i], pat[j]) and go(i + 1, j + 1) + return memo[(i, j)] + return go(0, 0) + + +def _glob_tokens(seg: str) -> list: + """One segment of a glob as fnmatch reads it: "*", "?", ("set", "[…]") or ("lit", ).""" + out, i, n = [], 0, len(seg) + while i < n: + c = seg[i] + if c in "*?": + if not (c == "*" and out and out[-1] == "*"): + out.append(c) + i += 1 + continue + if c == "[": + j = i + 1 + (seg[i + 1:i + 2] == "!") + j += seg[j:j + 1] == "]" # a ] first in the set is one of its characters + end = seg.find("]", j) + if end >= 0: + out.append(("set", seg[i:end + 1])) + i = end + 1 + continue + out.append(("lit", c)) # an unclosed [ is a literal, as fnmatch reads it + i += 1 + return out + + +def _one_char_both(x, y) -> bool: + """Can one character match glob tokens x and y (neither "*")? Two sets count as sharing one: an overlap is the + answer that keeps two lanes apart.""" + if "?" in (x, y): + return True + if x[0] == "lit" and y[0] == "lit": + return x[1] == y[1] + if x[0] == "lit" or y[0] == "lit": + lit, other = (x, y) if x[0] == "lit" else (y, x) + return fnmatch.fnmatchcase(lit[1], other[1]) + return True + + +def _segment_overlap(p: str, q: str) -> bool: + """Can one path segment match both segment patterns p and q?""" + a, b, memo = _glob_tokens(p), _glob_tokens(q), {} + + def go(i, j): + if (i, j) not in memo: + r = i == len(a) and j == len(b) + if not r and i < len(a) and a[i] == "*": # it matches nothing, or one more character of q's + r = go(i + 1, j) or (j < len(b) and b[j] != "*" and go(i, j + 1)) + if not r and j < len(b) and b[j] == "*": + r = go(i, j + 1) or (i < len(a) and a[i] != "*" and go(i + 1, j)) + if not r and i < len(a) and j < len(b) and "*" not in (a[i], b[j]): + r = _one_char_both(a[i], b[j]) and go(i + 1, j + 1) + memo[(i, j)] = r + return memo[(i, j)] + return go(0, 0) + + +def segments_overlap(a: list, b: list) -> bool: + """Can one path match both glob segment lists?""" + memo = {} + + def go(i, j): + if (i, j) not in memo: + r = i == len(a) and j == len(b) + if not r and i < len(a) and a[i] == "**": # it spans nothing, or one more segment of b's + r = go(i + 1, j) or (j < len(b) and go(i, j + 1)) + if not r and j < len(b) and b[j] == "**": + r = go(i, j + 1) or (i < len(a) and go(i + 1, j)) + if not r and i < len(a) and j < len(b) and "**" not in (a[i], b[j]): + r = _segment_overlap(a[i], b[j]) and go(i + 1, j + 1) + memo[(i, j)] = r + return memo[(i, j)] + return go(0, 0) + + +def globs_overlap(a: str, b: str, kind=None) -> bool: + """Could two scope globs hold the same file? True when one path matches both, compared without case. `kind`: + the checkout's answer for a literal name ("dir", "file" or None), so a file such as `docs/crew.md` is no folder + another glob could reach into (names_folder).""" + a, b = str(a or ""), str(b or "") + if not a or not b: + return False + return segments_overlap(segments(a.casefold(), names_folder(a, kind)), + segments(b.casefold(), names_folder(b, kind))) diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 4d00f450..74043c47 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -40,7 +40,7 @@ import uuid from pathlib import Path -from . import core, state, ui +from . import coord, core, state, ui from .core import STATE RUNS = STATE / "runs" @@ -495,10 +495,14 @@ def call_reads(cmd: str, cwd) -> bool: return False -def call_opened(agent: str, data: dict, now: float | None = None): +def call_opened(agent: str, data: dict, now: float | None = None, token_sha256: str = ""): """PreToolUse of a shell call or accepted Codex patch: its ledger entry {tool_use_id, session, agent, caller, depth, ts, ttl, cmd_sha256, cmd (redacted, at most CALL_TEXT), cut}, and reads: true when it writes no file - (call_reads).""" + (call_reads). `token_sha256`: the SHA-256 (64 hex characters) of the call token's nonce, written in the same + atomic write, so an entry of a call that carries a token never exists without its hash. Raises ValueError for + any other value.""" + if token_sha256 and not re.fullmatch(r"[0-9a-f]{64}", str(token_sha256)): + raise ValueError("token_sha256 must be 64 lowercase hex characters") tid, sid = _safe_name(data.get("tool_use_id")), _safe_name(data.get("session_id")) inp = data.get("tool_input") or {} cmd = inp.get("command") or inp.get("cmd") # Codex's exec_command sends its command as `cmd` @@ -531,6 +535,7 @@ def call_opened(agent: str, data: dict, now: float | None = None): "tool_use_id": tid, "session": sid, "agent": agent, "caller": aid or "main", "depth": depth, "ts": round(now, 3), "ttl": ttl, "cmd_sha256": hashlib.sha256(cmd.encode()).hexdigest(), "cmd": text, "cut": cut, **({"dev_args": dev_args} if dev_args else {}), + **({"token_sha256": token_sha256} if token_sha256 else {}), **({"agent_pid": agent_proc} if isinstance(agent_proc, int) else {}), **({"edit_paths": edit_paths} if edit_paths else {"reads": True} if call_reads(cmd, where) else {})}) @@ -2425,119 +2430,47 @@ def _tell_rewrites(run: dict, step: str, rewrites: list, now: float): # How a lane's scope glob holds a path. The edit check (in_scope), the holders of a path (scope_holders) and the -# overlap check that keeps two working lanes apart (_globs_overlap) read globs by the same rules, so two lanes whose -# scopes do not overlap never write the same file: +# overlap check that keeps two working lanes apart (_globs_overlap) read globs by the same rules (coord.segments), so +# two lanes whose scopes do not overlap never write the same file: # - a glob is matched segment by segment: `*`, `?` and `[…]` match inside one segment and never cross `/`, and `**` # as a whole segment matches any number of segments, none included (`docs/**/*.md` holds docs/guide.md); # - a glob holds everything under a folder it matches: `docs/`, `lib/parser`, `lib/parser/**` and `src/*` hold the -# files below those folders, `src/pkg/*.py` holds no file of src/pkg/studio/; +# files below those folders, `src/pkg/*.py` holds no file of src/pkg/studio/; a literal name that is a file in +# the checkout (`docs/crew.md`) has nothing under it, so no other glob overlaps it there; # - a relative glob counts from its repository and holds no path outside it (a `..` segment), `**` included; an -# absolute or ~ glob names a folder anywhere (a scratch folder, the project's plans) and holds absolute paths. +# absolute or ~ glob names a folder anywhere (a scratch folder, the project's plans) and holds absolute paths; +# - on a volume that ignores case (macOS's default), `Readme.md` and `README.md` are one file to both checks. def _glob_segments(glob: str) -> list: """A scope glob as its segments, ending with the "**" that holds what lies under a folder it matches.""" - segs = [s for s in glob.split("/") if s not in ("", ".")] - return segs if segs and segs[-1] == "**" else segs + ["**"] + return coord.segments(glob) -def _segments_match(segs: list, pat: list) -> bool: - import fnmatch - memo = {} +_FOLDS = {} - def go(i, j): - if (i, j) not in memo: - if j == len(pat): - memo[(i, j)] = i == len(segs) - elif pat[j] == "**": - memo[(i, j)] = go(i, j + 1) or (i < len(segs) and go(i + 1, j)) - else: - memo[(i, j)] = i < len(segs) and fnmatch.fnmatchcase(segs[i], pat[j]) and go(i + 1, j + 1) - return memo[(i, j)] - return go(0, 0) + +def _folds_case(base: str | None = None) -> bool: + """Does the volume of `base` (else the home folder) ignore case? Checked once per folder: the folder's own path + in the other case names it too.""" + p = os.path.realpath(base or os.path.expanduser("~")) + if p not in _FOLDS: + other = p.swapcase() + _FOLDS[p] = other != p and os.path.exists(other) and os.path.samefile(p, other) + return _FOLDS[p] -def scope_match(path, glob) -> bool: +def scope_match(path, glob, fold: bool | None = None) -> bool: """Does scope glob `glob` hold `path` (the rules above)? A relative glob holds a path relative to the lane's - repository, an absolute or ~ one an absolute path; a path with a `..` segment lies outside and is held by none.""" + repository, an absolute or ~ one an absolute path; a path with a `..` segment lies outside and is held by none. + `fold`: compare without case (None: when the home folder's volume ignores it, as _globs_overlap does).""" g, p = str(glob or ""), str(path or "") g = os.path.expanduser(g) if g.startswith("~") else g if not g or not p or g.startswith("/") != p.startswith("/"): return False + if _folds_case() if fold is None else fold: + g, p = g.casefold(), p.casefold() segs = [s for s in p.split("/") if s not in ("", ".")] - return bool(segs) and ".." not in segs and _segments_match(segs, _glob_segments(g)) - - -def _glob_tokens(seg: str) -> list: - """One segment of a glob as fnmatch reads it: "*", "?", ("set", "[…]") or ("lit", ).""" - out, i, n = [], 0, len(seg) - while i < n: - c = seg[i] - if c in "*?": - if not (c == "*" and out and out[-1] == "*"): - out.append(c) - i += 1 - continue - if c == "[": - j = i + 1 + (seg[i + 1:i + 2] == "!") - j += seg[j:j + 1] == "]" # a ] first in the set is one of its characters - end = seg.find("]", j) - if end >= 0: - out.append(("set", seg[i:end + 1])) - i = end + 1 - continue - out.append(("lit", c)) # an unclosed [ is a literal, as fnmatch reads it - i += 1 - return out - - -def _one_char_both(x, y) -> bool: - """Can one character match glob tokens x and y (neither "*")? Two sets count as sharing one: an overlap is the - answer that keeps two lanes apart.""" - import fnmatch - if "?" in (x, y): - return True - if x[0] == "lit" and y[0] == "lit": - return x[1] == y[1] - if x[0] == "lit" or y[0] == "lit": - lit, other = (x, y) if x[0] == "lit" else (y, x) - return fnmatch.fnmatchcase(lit[1], other[1]) - return True - - -def _segment_overlap(p: str, q: str) -> bool: - """Can one path segment match both segment patterns p and q?""" - a, b, memo = _glob_tokens(p), _glob_tokens(q), {} - - def go(i, j): - if (i, j) not in memo: - r = i == len(a) and j == len(b) - if not r and i < len(a) and a[i] == "*": # it matches nothing, or one more character of q's - r = go(i + 1, j) or (j < len(b) and b[j] != "*" and go(i, j + 1)) - if not r and j < len(b) and b[j] == "*": - r = go(i, j + 1) or (i < len(a) and a[i] != "*" and go(i + 1, j)) - if not r and i < len(a) and j < len(b) and "*" not in (a[i], b[j]): - r = _one_char_both(a[i], b[j]) and go(i + 1, j + 1) - memo[(i, j)] = r - return memo[(i, j)] - return go(0, 0) - - -def _segments_overlap(a: list, b: list) -> bool: - """Can one path match both glob segment lists?""" - memo = {} - - def go(i, j): - if (i, j) not in memo: - r = i == len(a) and j == len(b) - if not r and i < len(a) and a[i] == "**": # it spans nothing, or one more segment of b's - r = go(i + 1, j) or (j < len(b) and go(i, j + 1)) - if not r and j < len(b) and b[j] == "**": - r = go(i, j + 1) or (i < len(a) and go(i + 1, j)) - if not r and i < len(a) and j < len(b) and "**" not in (a[i], b[j]): - r = _segment_overlap(a[i], b[j]) and go(i + 1, j + 1) - memo[(i, j)] = r - return memo[(i, j)] - return go(0, 0) + return bool(segs) and ".." not in segs and coord.segments_match(segs, coord.segments(g)) def _glob_real(g: str) -> str: @@ -2547,18 +2480,32 @@ def _glob_real(g: str) -> str: return "/".join([core.real("/".join(parts[:k]) or "/")] + parts[k:]) -def _globs_overlap(a: str, b: str) -> bool: +def _path_kind(top: str): + """What a glob's literal path is in checkout `top` -> "dir", "file" or None (nothing there): the answer + coord.names_folder asks for. None without a checkout.""" + if not top or not os.path.isdir(top): + return None + + def kind(glob): + p = glob if glob.startswith("/") else os.path.join(top, glob) + return "dir" if os.path.isdir(p) else "file" if os.path.exists(p) else None + return kind + + +def _globs_overlap(a: str, b: str, top: str = "") -> bool: """Could two scope globs hold the same file? True when at least one path matches both by scope_match's rules, compared without case, since macOS's disk ignores it. `src/pkg/*.py` and `src/pkg/studio/host.py` do not overlap, nor do `tests/unit/test_parser*.py` and `tests/unit/test_cli*.py`, so two lanes can split one folder; - `tests/unit/**` overlaps every file under tests/unit/. A relative glob never overlaps an absolute one: the - absolute globs a step keeps lie outside its repository (_scope_globs).""" + `tests/unit/**` overlaps every file under tests/unit/. A literal name is a folder or a file as checkout `top` + has it (a suffix makes it a file when nothing is there yet), so `docs/crew.md` and `docs/**/bug*.md` do not + overlap. A relative glob never overlaps an absolute one: the absolute globs a step keeps lie outside its + repository (_scope_globs).""" a, b = str(a or ""), str(b or "") if not a or not b or a.startswith(("/", "~")) != b.startswith(("/", "~")): return False if a.startswith(("/", "~")): a, b = _glob_real(a), _glob_real(b) - return _segments_overlap(_glob_segments(a.casefold()), _glob_segments(b.casefold())) + return coord.globs_overlap(a, b, kind=_path_kind(top or "/" if a.startswith("/") else top)) def _in_globs(rel_path: str, globs) -> bool: diff --git a/tests/test_coord_calltoken.py b/tests/test_coord_calltoken.py new file mode 100644 index 00000000..a35d0e70 --- /dev/null +++ b/tests/test_coord_calltoken.py @@ -0,0 +1,42 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The call ledger keeps the hash of a call's token in the entry's one write, so an entry of a call that carries a +token never exists without it. Run: python3 -m unittest tests.test_coord_calltoken""" +import hashlib +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import progress as pg # noqa: E402 +from test_progress import TempState # noqa: E402 + + +def call(tid): + return {"session_id": "s1", "tool_use_id": tid, "tool_name": "Bash", "tool_input": {"command": "dev crew inbox"}} + + +class CallTokenHashTests(unittest.TestCase): + def setUp(self): + self.state = TempState().__enter__() + self.addCleanup(self.state.__exit__, None, None, None) + + def test_the_entry_carries_the_token_hash_from_its_first_write(self): + digest = hashlib.sha256(b"nonce-value").hexdigest() + pg.call_opened("claude", call("toolu_tok1"), token_sha256=digest) + self.assertEqual(pg.call_entry(call("toolu_tok1"))["token_sha256"], digest) + + def test_an_entry_without_a_token_has_no_hash(self): + pg.call_opened("claude", call("toolu_tok2")) + self.assertNotIn("token_sha256", pg.call_entry(call("toolu_tok2"))) + + def test_a_malformed_hash_writes_no_entry(self): + for bad in ("nonce-value", "A" * 64, "ab" * 31): + with self.assertRaises(ValueError): + pg.call_opened("claude", call("toolu_tok3"), token_sha256=bad) + self.assertEqual(pg.call_entry(call("toolu_tok3")), {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_coord_kernel.py b/tests/test_coord_kernel.py new file mode 100644 index 00000000..b184db40 --- /dev/null +++ b/tests/test_coord_kernel.py @@ -0,0 +1,224 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The crew coordination rules (devkit.coord) on hand-built run records: which steps a lane holds and the files it +may write, the assignment intents that outlive lanes and the order a free lane claims them in, blocking and +unblocking, the steps a command changed, the invariant check, and when two scope globs can hold the same file. +Run: python3 -m unittest tests.test_coord_kernel""" +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +from devkit import coord # noqa: E402 + +T = 1_800_000_000.0 + + +def review(s): + return s.get("activity") == "review" + + +def step(name, state="pending", owner="main", label="", scope=(), after=(), **kw): + return dict(name=name, state=state, owner=owner, label=label, scope=list(scope), after=list(after), **kw) + + +def lane(persona, state="running", label="", **kw): + return dict(persona=persona, label=label or persona, state=state, binding="exact", parent="main", **kw) + + +def run_of(plan, agents=None, **kw): + done = sum(1 for s in plan if s["state"] in coord.DONE) + return dict(plan=plan, agents=agents or {}, history=[], step=done, **kw) + + +class HeldAndScopeTests(unittest.TestCase): + def test_a_lanes_scope_is_the_union_of_its_running_steps_only(self): + plan = [step("a", "running", "L", "Tank", ["api/**"]), step("b", "blocked", "L", "Tank", ["b/**"]), + step("c", "unverified", "L", "Tank", ["c/**"]), step("d", "done", "L", "Tank", ["d/**"]), + step("e", "running", "L", "Tank", ["tests/test_api.py"], activity="review")] + run = run_of(plan, {"L": lane("Tank", scope=["old/**"])}) + self.assertEqual([s["name"] for s in coord.held(run, "L")], ["a", "e"]) + self.assertEqual(coord.scope(run, "L"), ["api/**", "tests/test_api.py"]) # never the stored lane scope + + def test_a_lane_with_only_blocked_or_closed_steps_is_free_and_holds_no_files(self): + plan = [step("a", "blocked", "L", "Tank", ["api/**"]), step("b", "unverified", "L", "Tank", ["b/**"])] + run = run_of(plan, {"L": lane("Tank")}) + self.assertFalse(coord.busy(run, "L", review=review)) + self.assertEqual(coord.scope(run, "L"), []) + + def test_reviews_share_a_lane_and_a_running_build_step_keeps_it_busy(self): + r1 = step("r1", "running", "L", "Seraph", activity="review") + r2 = step("r2", "pending", "main", "Seraph", activity="review") + build = step("x", "pending", "main", "Seraph") + run = run_of([r1, r2, build], {"L": lane("Seraph")}) + self.assertFalse(coord.busy(run, "L", r2, review=review)) + self.assertTrue(coord.busy(run, "L", build, review=review)) + self.assertFalse(coord.busy(run, "L", review=review)) # it owns no running step that is not a review + + +class IntentTests(unittest.TestCase): + def test_a_legacy_queue_entry_reads_as_an_intent(self): + one = step("a", label="Tank", waits_lane={"lane": "L1", "ts": T}) + exact = step("b", label="Tank: api", assignment_revision=3, + waits_lane={"lane": "L2", "ts": T + 1, "session": "s1", "run_started": T, "step": "b", + "revision": 3}) + several = step("c", label="Tank", waits_lane={"lanes": ["L1", "L2"], "ts": T + 2}) + self.assertEqual((coord.intent(one)["lane"], coord.intent(one)["ts"], coord.intent(one)["member"]), + ("L1", T, "Tank")) + self.assertEqual((coord.intent(exact)["lane"], coord.intent(exact)["rev"]), ("L2", 3)) + self.assertEqual((coord.intent(several)["lane"], coord.intent(several)["member"]), (None, "Tank")) + + def test_a_step_assigned_by_role_without_an_entry_is_a_member_wide_intent(self): + s = step("a", label="Kid", assigned_at=T + 5) + self.assertEqual({k: coord.intent(s)[k] for k in ("member", "lane", "ts")}, + {"member": "Kid", "lane": None, "ts": T + 5}) + self.assertIsNone(coord.intent(step("b", label=""))) # the tech lead's own step + self.assertIsNone(coord.intent(step("c", "running", "L", "Kid"))) # taken already + + def test_set_intent_replaces_the_legacy_entry(self): + s = step("a", label="Tank", waits_lane={"lane": "L1", "ts": T}, assignment_revision=2) + coord.set_intent({}, s, "Tank", "L2", T + 9, front=True) + self.assertNotIn("waits_lane", s) + self.assertEqual({k: s["intent"][k] for k in ("member", "lane", "rev", "ts", "front")}, + {"member": "Tank", "lane": "L2", "rev": 2, "ts": T + 9, "front": True}) + + +class ClaimTests(unittest.TestCase): + def plan(self): + return [step("old-role", label="Tank", intent={"member": "Tank", "lane": None, "ts": T + 1}), + step("bound", label="Tank", intent={"member": "Tank", "lane": "L", "ts": T + 5}), + step("front", label="Tank", intent={"member": "Tank", "lane": "L", "ts": T + 9, "front": True}), + step("named", label="Tank", intent={"member": "Tank", "lane": None, "ts": T + 20}), + step("other-lane", label="Tank", intent={"member": "Tank", "lane": "L2", "ts": T}), + step("not-ready", label="Tank", after=["gate"], intent={"member": "Tank", "lane": None, "ts": T}), + step("gate", "running", "main"), + step("trinity", label="Trinity", intent={"member": "Trinity", "lane": None, "ts": T})] + + def test_a_free_lane_claims_named_then_front_then_bound_then_member_wide_oldest_first(self): + run = run_of(self.plan(), {"L": lane("Tank"), "L2": lane("Tank", "done")}) + order = [] + for named in ("named", None, None, None): + got = coord.claimable(run, "L", launch_named=named, review=review) + order.append(got["name"]) + got["state"] = "done" # the lane finished it + self.assertEqual(order, ["named", "front", "bound", "old-role"]) + self.assertIsNone(coord.claimable(run, "L", review=review)) # another lane's, another member's, or waiting + + def test_a_launch_cannot_name_another_members_step_into_its_lane(self): + run = run_of(self.plan(), {"L": lane("Tank")}) + self.assertEqual(coord.claimable(run, "L", launch_named="trinity", review=review)["name"], "front") + + def test_a_busy_lane_or_one_that_cannot_work_claims_nothing(self): + busy = run_of(self.plan() + [step("work", "running", "L", "Tank")], {"L": lane("Tank")}) + self.assertIsNone(coord.claimable(busy, "L", review=review)) + for flags in ({"state": "done"}, {"over_limit": True}, {"binding": "unbound"}, {"parent": "L9"}): + run = run_of(self.plan(), {"L": dict(lane("Tank"), **flags)}) + self.assertIsNone(coord.claimable(run, "L", review=review), flags) + + def test_a_resume_with_a_launch_on_its_way_leaves_member_wide_intents_to_that_launch(self): + run = run_of([step("role", label="Tank", intent={"member": "Tank", "lane": None, "ts": T})], + {"L": lane("Tank")}) + self.assertIsNone(coord.claimable(run, "L", member_wide=False, review=review)) + + def test_a_claim_runs_the_step_in_the_lane_removes_its_intent_and_records_why(self): + run = run_of(self.plan(), {"L": lane("Tank")}) + s = coord.claim(run, "L", T + 30, "its lane holds no other step", review=review) + self.assertEqual((s["name"], s["state"], s["owner"], s["started"], "intent" in s), + ("front", "running", "L", T + 30, False)) + self.assertEqual(run["history"][-1], {"ts": round(T + 30), "step": "front", "from": "pending", + "to": "running", "by": "devkit", "why": "its lane holds no other step"}) + self.assertIsNone(coord.claim(run_of([], {"L": lane("Tank")}), "L", T, "x", review=review)) + + +class BlockTests(unittest.TestCase): + def test_block_keeps_the_owner_and_frees_the_lane(self): + s = step("a", "running", "L", "Link", ["docs/**"]) + run = run_of([s], {"L": lane("Link")}) + coord.block(run, s, "D3", T, "waits for the developer") + self.assertEqual((s["state"], s["owner"], s["waiting"]), ("blocked", "L", "D3")) + self.assertEqual((coord.busy(run, "L", review=review), coord.scope(run, "L")), (False, [])) + self.assertEqual(run["history"][-1]["to"], "blocked") + + def test_an_answer_runs_the_step_again_in_its_free_lane(self): + s = step("a", "blocked", "L", "Link", waiting="D3") + run = run_of([s], {"L": lane("Link")}) + self.assertEqual(coord.unblock(run, s, True, T, review=review), "running") + self.assertEqual((s["state"], s["owner"], "waiting" in s), ("running", "L", False)) + + def test_an_answer_while_the_lane_is_busy_puts_the_step_first_in_that_lanes_queue(self): + s = step("a", "blocked", "L", "Link", waiting="D3") + run = run_of([s, step("b", "running", "L", "Link")], {"L": lane("Link")}) + self.assertEqual(coord.unblock(run, s, True, T, review=review), "pending") + self.assertEqual((s["owner"], coord.intent(s)["lane"], coord.intent(s)["front"]), ("main", "L", True)) + + def test_an_answer_after_the_lane_ended_goes_to_the_members_next_lane_not_the_tech_lead(self): + s = step("a", "blocked", "L", "Link: sig release", waiting="D3") + run = run_of([s], {"L": lane("Link", "done")}) + self.assertEqual(coord.unblock(run, s, False, T, review=review), "pending") + self.assertEqual((coord.intent(s)["member"], coord.intent(s)["lane"], coord.intent(s)["front"]), + ("Link", None, True)) + + +class ChangesTests(unittest.TestCase): + def test_changes_lists_exactly_the_steps_whose_state_moved(self): + run = run_of([step("a", "done"), step("b", "running"), step("c")]) + self.assertEqual(coord.changes({"a": "running", "b": "running"}, run), + [("a", "running", "done"), ("c", None, "pending")]) + self.assertEqual(coord.changes(coord.states(run), run), []) + + +class CheckTests(unittest.TestCase): + def sound(self): + return run_of([step("api", "running", "L", "Tank", ["api/**"]), + step("ui", "running", "M", "Trinity", ["ui/**"]), + step("doc", "done", "L", "Tank")], + {"L": lane("Tank"), "M": lane("Trinity")}) + + def ids(self, run): + return {v.split(":")[0] for v in coord.check(run, T, review=review)} + + def test_a_sound_run_breaks_no_invariant(self): + self.assertEqual(coord.check(self.sound(), T, review=review), []) + + def test_each_broken_invariant_is_named(self): + cases = { + "I-owner": lambda r: r["agents"]["L"].update(state="done"), + "I-one-step": lambda r: r["plan"].append(step("api2", "running", "L", "Tank")), + "I-scope": lambda r: r["agents"]["L"].update(scope=["api/**"]), + "I-separate": lambda r: r["plan"][1].update(scope=["api/x.py"]), + "I-intent": lambda r: r["plan"][0].update(intent={"member": "Tank", "lane": None, "ts": T}), + "I-claim": lambda r: (r["plan"][0].update(state="done"), + r["plan"].append(step("next", label="Tank", assigned_at=T))), + "I-history": lambda r: r.update(step=0), + } + for rule, breaks in cases.items(): + run = self.sound() + breaks(run) + self.assertIn(rule, self.ids(run), rule) + + def test_a_steps_latest_history_entry_must_name_its_state(self): + run = self.sound() + run["history"] = [{"ts": T, "step": "api", "from": "pending", "to": "blocked", "by": "main", "why": "x"}] + self.assertEqual(self.ids(run), {"I-history"}) + + +class OverlapTests(unittest.TestCase): + def test_a_file_name_is_not_a_folder_another_glob_could_reach_into(self): + self.assertFalse(coord.globs_overlap("docs/**/bug*.md", "docs/crew.md")) + self.assertFalse(coord.globs_overlap("docs/agents.md", "docs/**/bug*.md")) + self.assertTrue(coord.globs_overlap("docs/**/bug*.md", "docs/bug1.md")) + + def test_folders_still_hold_what_lies_under_them(self): + for a, b in (("docs/", "docs/crew.md"), ("lib/devkit", "lib/devkit/progress.py"), + ("src/*", "src/studio/host.py"), ("docs/**", "docs/a/b.md")): + self.assertTrue(coord.globs_overlap(a, b) and coord.globs_overlap(b, a), (a, b)) + + def test_the_checkout_decides_whether_a_literal_name_is_a_folder(self): + kinds = {"conf.d": "dir", "bin/dev": "file"} + self.assertTrue(coord.globs_overlap("conf.d", "conf.d/x.conf", kind=kinds.get)) + self.assertFalse(coord.globs_overlap("bin/dev", "bin/dev/x", kind=kinds.get)) + self.assertFalse(coord.globs_overlap("conf.d", "conf.d/x.conf")) # no checkout at hand: a suffix is a file + + +if __name__ == "__main__": + unittest.main() From ec4d80402b50597d791594565f88ee2eec1a57e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:23:22 -0800 Subject: [PATCH 03/52] fix(gates): judge every member stop and send back once per lane life A reviewer the crew gates sent back once, who then recorded its step correctly and reported a clean check, still ended its review unverified, so the tech lead had to close the review and record the approval by hand, on Claude Code and on Codex. Root cause: gates.check returned before judging any stop of a member already in crew_gated, after dropping its pass token, so no later stop of that session could ever pass Every stop is judged by the current rules. A send-back is keyed by the lane's life (its start or last resume), so a resumed lane may be sent back once again. A stop let through with findings writes no token, is audited as let through, and keeps its findings for the tech lead (gates.let_through). check takes a judge for model-based tests. Verified: python3 -m unittest tests.test_gates_judgment tests.test_crew_gates tests.test_gates_skills tests.test_gates_writes tests.test_approvals_token tests.test_hooks_codex: 99 tests OK --- lib/devkit/gates.py | 134 +++++++++++++++++++++---------- tests/test_crew_gates.py | 5 +- tests/test_gates_judgment.py | 149 +++++++++++++++++++++++++++++++++++ 3 files changed, 244 insertions(+), 44 deletions(-) create mode 100644 tests/test_gates_judgment.py diff --git a/lib/devkit/gates.py b/lib/devkit/gates.py index 31134e12..5eea314b 100644 --- a/lib/devkit/gates.py +++ b/lib/devkit/gates.py @@ -68,6 +68,12 @@ # --approves approves only with the # token of that stop (progress._passed_now); without one, nothing approves. PASSED = "crew_passed" +# The session record's send-backs, {agent id: {who, life}}: the lane life (its start, or its last resume) whose stop +# the gates sent back. A member is sent back once per life; its next stop of that life is still judged. +GATED = "crew_gated" +# The session record's findings of a stop the gates let through, {agent id: {who, life, findings}}, for the tech +# lead (let_through); each stop of that agent replaces or drops its entry. +FINDINGS = "crew_findings" # A hook's denial as Claude Code writes it into the tool result: "PreToolUse:Bash hook error: ". DENIAL_RE = re.compile(r"^\s*(?:PreToolUse|PermissionRequest)(?::[^\s:]+)? hook (?:blocking )?error\b", re.I) _SPLIT = re.compile(r"\|\||&&|\$\(|[;&|()`\n]") # where a new simple command starts @@ -1216,33 +1222,79 @@ def _keep_for_lead(sess: dict, key: str, who: str, tasks: list): def _unpass(sess: dict, key: str): - """This member's pass token goes (and the record's key with the last), before its stop is judged: a pass of an - earlier stop never counts for this one.""" - tokens = sess.get(PASSED) - if isinstance(tokens, dict): - tokens.pop(key, None) - if not tokens: - sess.pop(PASSED, None) - elif tokens is not None: - sess.pop(PASSED, None) # not a record of tokens: none of it counts - - -def check(name, data: dict, sess: dict, pid: str = "", roster=None, lead_name: str = "", agent: str = ""): + """This member's pass token and let-through findings go (and each record's key with its last entry), before its + stop is judged: what an earlier stop left never counts for this one.""" + for field in (PASSED, FINDINGS): + entries = sess.get(field) + if isinstance(entries, dict): + entries.pop(key, None) + if not entries: + sess.pop(field, None) + elif entries is not None: + sess.pop(field, None) # not a record of entries: none of it counts + + +def let_through(sess: dict, key: str) -> list: + """The findings of the last stop of `key` (its agent id) that the gates let through with something missing (sent + back once in that lane life already, or only recorded), for the tech lead: [{rule, item, evidence, fix}], or [] + when that stop passed, was sent back, or was not judged. The SubagentStop hook reads them once gates.check + returns and passes them on to the lane's end, which names them to the tech lead.""" + entries = sess.get(FINDINGS) if isinstance(sess, dict) else None + rec = entries.get(key) if isinstance(entries, dict) else None + found = rec.get("findings") if isinstance(rec, dict) else None + return [dict(f) for f in found if isinstance(f, dict)] if isinstance(found, list) else [] + + +def _life(data: dict, agent: str = ""): + """When the stopping member's lane began its current life: its last resume, else its start. None when devkit + keeps no lane for it (a launch without a run, a helper): all its stops in the session are then one life.""" + aid = data.get("agent_id") or "" + if not aid: + return None + try: + from . import progress + host = agent or agent_of(data.get("agent_transcript_path") or "") + _, lane = progress.lane_of(host, data.get("session_id") or "-", aid) + except Exception: + return None + return (lane.get("resumed_at") or lane.get("started") or None) if isinstance(lane, dict) else None + + +def _sent_back(sess: dict, key: str, life) -> bool: + """This lane life of `key` was sent back already. A send-back recorded before lives were kept (the member's name + alone) counts for every life, so a session record written by an older devkit never sends a member back twice.""" + rec = (sess.get(GATED) or {}).get(key) + if rec is None: + return False + return rec.get("life") == life if isinstance(rec, dict) else True + + +def _detail(who: str, findings) -> str: + """A finding set as the audit trail keeps it: `: : (task ); …`.""" + return f"{who}: " + "; ".join(f"{f['rule']}: {f['item']}" + (f" (task {f['task']})" if f.get("task") else "") + for f in findings) + + +def check(name, data: dict, sess: dict, pid: str = "", roster=None, lead_name: str = "", agent: str = "", + judge=None): """The SubagentStop entry point. -> the hook's {"decision": "block", "reason": …} the first time a member stops - with something missing, else None. Records each finding set as `crew.gate` in the audit trail ("blocked", or - "recorded" when `crew.gates.enforce` is false) and marks the member in `sess["crew_gated"]`, so it is sent back - only once. A member let through with background work still running (sent back once already, or not enforced) is - audited and kept for the tech lead as `lead_name` (`_keep_for_lead`): the name devkit's launch records give it - (`hooks._lead_name`), never `name`, which may come from a description a member wrote for its helper. Without - one, nothing is kept. `lead_name` also says whether the tech lead wrote the brief (`_by_lead`), and a proof met - another way is audited as `crew.gate` with outcome "ok" and how it was met. Fails open: the member is never - held back by a gate that cannot judge. Approvals fail closed: only a clean pass (no findings) writes the member's - pass token when the current report explicitly says Check ✓, `sess[PASSED][agent id]` = the time it passed, - in the session record the hook writes once this - returns. A stop let through after a send-back, findings only recorded, a missing transcript or agent id, or a - crash write none and drop the token an earlier stop left, so that member's review steps and --approves verdicts - approve nothing at its lane's end (progress._passed_now), and neither does a stop that never reaches this check - or whose record write is dropped.""" + with something missing in its lane's current life, else None. Every stop is judged by the current rules: a + send-back is keyed by the lane's life (its start, or its last resume: `_life`) in `sess[GATED]`, so a member is + sent back once per life, and its next stop of that life is judged again and let through with what it still + misses. Each finding set is audited as `crew.gate` ("blocked"; "recorded" when `crew.gates.enforce` is false; + "let through" after a send-back), and a stop that goes through with findings keeps them for the tech lead + (`let_through`). A member let through with background work still running is also kept for the tech lead as + `lead_name` (`_keep_for_lead`): the name devkit's launch records give it (`hooks._lead_name`), never `name`, + which may come from a description a member wrote for its helper. Without one, nothing is kept. `lead_name` also + says whether the tech lead wrote the brief (`_by_lead`), and a proof met another way is audited as `crew.gate` + with outcome "ok" and how it was met. `judge`: what finds the findings, with crew_gates' arguments (default + crew_gates; a model-based test gives an oracle). Fails open: the member is never held back by a gate that + cannot judge. Approvals fail closed: only a clean pass (no findings) writes the member's pass token when the + current report explicitly says Check ✓, `sess[PASSED][agent id]` = the time it passed, in the session record the + hook writes once this returns, whether or not an earlier stop of the lane was sent back. A stop with findings, a + missing transcript or agent id, or a crash write none and drop the token an earlier stop left, so that member's + review steps and --approves verdicts approve nothing at its lane's end (progress._passed_now), and neither does + a stop that never reaches this check or whose record write is dropped.""" try: key = data.get("agent_id") or str(name or "") _unpass(sess, key) @@ -1250,23 +1302,14 @@ def check(name, data: dict, sess: dict, pid: str = "", roster=None, lead_name: s if not transcript: return None from . import approvals, audit, canary, crew - if key in (sess.get("crew_gated") or {}): # sent back once: let through, but not silently - tasks = background_work(transcript) - if tasks: - who = sess["crew_gated"][key] - audit.record("crew.gate", pid or "", f"{who}: background: " + "; ".join( - f"{t['command']} (task {t['id']})" for t in tasks) + "; sent back once already", - "let through", member=who, rules=["background"]) - _keep_for_lead(sess, key, lead_name, tasks) - return None m = _member(name, roster) accepted = [] report = data.get("last_assistant_message") or canary.last_assistant_text(transcript) or "" status = canary.parse_status(report) positive = approvals.glyph((status or {}).get("check")) == "✓" - findings = crew_gates(m or name, transcript, data.get("cwd") or "", roster, agent, - session=data.get("session_id") or "", lane=data.get("agent_id") or "", - by_lead=_by_lead(lead_name), accepted=accepted, successful=positive) + findings = (judge or crew_gates)(m or name, transcript, data.get("cwd") or "", roster, agent, + session=data.get("session_id") or "", lane=data.get("agent_id") or "", + by_lead=_by_lead(lead_name), accepted=accepted, successful=positive) who = crew.who(m) if m else str(name or "Agent") if accepted: # a proof met another way is a choice someone can review: `dev audit --action crew.gate` audit.record("crew.gate", pid or "", f"{who}: " + "; ".join( @@ -1276,12 +1319,19 @@ def check(name, data: dict, sess: dict, pid: str = "", roster=None, lead_name: s if data.get("agent_id") and positive: sess.setdefault(PASSED, {})[key] = time.time() return None - sess.setdefault("crew_gated", {})[key] = who - enforce = enforced() - audit.record("crew.gate", pid or "", f"{who}: " + "; ".join(f"{f['rule']}: {f['item']}" for f in findings), - "blocked" if enforce else "recorded", member=who, rules=sorted({f["rule"] for f in findings})) + life, rules = _life(data, agent), sorted({f["rule"] for f in findings}) + again = _sent_back(sess, key, life) + enforce = enforced() and not again + if again: # sent back once in this life: let through with what it still misses, never silently + audit.record("crew.gate", pid or "", _detail(who, findings) + "; sent back once already", "let through", + member=who, rules=rules) + else: + sess.setdefault(GATED, {})[key] = {"who": who, "life": life} + audit.record("crew.gate", pid or "", _detail(who, findings), "blocked" if enforce else "recorded", + member=who, rules=rules) if enforce: return {"decision": "block", "reason": send_back_reason(findings, who)} + sess.setdefault(FINDINGS, {})[key] = {"who": who, "life": life, "findings": findings} running = [{"id": f["task"], "command": f["item"]} for f in findings if f["rule"] == "background"] if running: _keep_for_lead(sess, key, lead_name, running) diff --git a/tests/test_crew_gates.py b/tests/test_crew_gates.py index e7031f8d..6080f245 100644 --- a/tests/test_crew_gates.py +++ b/tests/test_crew_gates.py @@ -813,8 +813,9 @@ def test_the_hook_entry_sends_a_member_back_once_and_audits_it(self): self.assertIn("a1", sess["crew_gated"]) self.assertIsNone(gates.check("Kid", {**data, "stop_hook_active": True}, sess, "owner/repo", roster={"members": [KID]})) # sent back once, like the canary - recs = audit.records(1, action="crew.gate") - self.assertEqual([(r["target"], r["outcome"]) for r in recs], [("owner/repo", "blocked")]) + recs = audit.records(1, action="crew.gate") # the second stop is judged too, and audited as let through + self.assertEqual([(r["target"], r["outcome"], (r.get("ref") or {}).get("result")) for r in recs], + [("owner/repo", "blocked", None), ("owner/repo", "recorded", "let through")]) self.assertIn("proofs", recs[0]["detail"]) def test_with_enforce_off_the_gate_only_records(self): diff --git a/tests/test_gates_judgment.py b/tests/test_gates_judgment.py new file mode 100644 index 00000000..802d24b4 --- /dev/null +++ b/tests/test_gates_judgment.py @@ -0,0 +1,149 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The crew gates judge every stop of a member, on Claude Code and on Codex: a send-back is keyed by the lane's life +(its start, or its last resume), so a member sent back once is let through on its next stop of that life, but that +stop is still judged. A clean ✓ then writes the pass token, so a review step ends done and its approval counts; a stop +let through with findings writes none, and its findings are kept for the tech lead (`gates.let_through`). A resumed +lane is a new life, which may be sent back once again. + +Run: python3 -m unittest tests.test_gates_judgment -v""" +import json +import os +import shlex +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "lib")) +sys.path.insert(0, str(ROOT / "tests")) +from devkit import audit, gates # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_acceptance_crew_sessions import HOOK_BOOT # noqa: E402 +from test_approvals_token import StopCase # noqa: E402 +from test_codex_launch import LEAD, TANK, CodexCrew, _line, _now # noqa: E402 + +SUBAGENT_STOP_KEYS = {"continue", "decision", "reason", "stopReason", "suppressOutput", "systemMessage"} +SERAPH = "01a1c190-64c7-7ac1-81c6-000000000009" +CODEX_REPORT = ("**[Firefly> DevKit · {role}]** api · `feat/invoice-export` · {task}\n- **Done:** {task}\n" + "- **Check:** ✓ 12 tests pass\n- **Next:** the tech lead merges it.\n\nNeeds from the tech lead: nothing") + + +class ClaudeStopJudgmentTests(StopCase): + # The Code reviewer holds "review"; each stop goes through Claude Code's SubagentStop hook + def session(self) -> dict: + return json.loads(self.session_file().read_text()) + + def test_a_clean_second_stop_after_a_send_back_passes_the_review(self): + self.assertEqual(json.loads(self.stop() or "{}").get("decision"), "block") # no dev progress step + self.assertEqual(self.stop(self.passing(), stop_hook_active=True), "") # fixed: same life, judged again + why = [h["why"] for h in self.run_()["history"] if h["step"] == "review"][-1] + self.assertEqual(self.plan()["review"]["state"], "done", why) + self.assertEqual(pg.approvals_owed(self.run_()), []) + + def test_findings_on_a_second_stop_of_the_same_life_are_kept_for_the_tech_lead_without_a_token(self): + self.assertEqual(json.loads(self.stop() or "{}").get("decision"), "block") + self.assertEqual(self.stop(stop_hook_active=True), "") # still no dev progress step: let through + kept = gates.let_through(self.session(), "a_seraph") + self.assertEqual([(f["rule"], f["item"]) for f in kept], [("proofs", "dev progress step")]) + self.assertNotIn("a_seraph", self.tokens()) + self.assert_review_approves_nothing() + recs = audit.records(1, action="crew.gate") + self.assertEqual([(r["outcome"], (r.get("ref") or {}).get("result")) for r in recs], + [("blocked", None), ("recorded", "let through")]) + self.assertIn("proofs: dev progress step", recs[1]["detail"]) + + def test_a_resumed_lane_with_findings_is_sent_back_once_more(self): + self.stop() + self.stop(stop_hook_active=True) + pg.reopen("review", why="the reviewer is resumed for a second verdict", now=self.at(30)) + pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a_seraph", "agent_type": "devkit:seraph"}, True, + now=self.at(31)) + out = json.loads(self.stop() or "{}") # a new life: its first stop with findings goes back + self.assertEqual(out.get("decision"), "block", out) + self.assertIn("the crew gates found 1 thing missing", out.get("reason", "")) + + def test_a_judge_given_to_the_gates_decides_the_stop(self): + # the seam a model-based test drives: the judge's findings, not the real gates, decide the verdict + sess = {} + data = {"session_id": "s1", "agent_id": "a_seraph", "agent_type": "devkit:seraph", + "agent_transcript_path": str(self.transcript()), "last_assistant_message": self.REPORT} + self.assertIsNone(gates.check("Seraph", data, sess, judge=lambda *a, **k: [])) + self.assertIn("a_seraph", sess.get(gates.PASSED) or {}) + + +class CodexStopJudgmentTests(CodexCrew): + # The same judgment on Codex's path: SubagentStart binds the member by its task_name, every member command is a + # shell call its own rollout records as a CommandExecution item, and SubagentStop names that rollout. A spawned + # agent's rollout is written as Codex 0.167.0 writes it: its session_meta says where its own history starts + # (subagent_history_start_ordinal), its own turn opens with task_started, every record has its ordinal, and a + # CommandExecution item names its folder + def agent_rollout(self, s, aid: str, member: str, task: str, parent: str = "", depth: int = 1, source=None): + path = super().agent_rollout(s, aid, member, task, parent, depth, source) + meta = json.loads(path.read_text()) + meta["ordinal"] = 0 + meta["payload"]["subagent_history_start_ordinal"] = 1 + turn = {"timestamp": _now(), "ordinal": 1, "type": "event_msg", + "payload": {"type": "task_started", "turn_id": "01a1c178-651e-7bc1-a532-a2415b26e099"}} + path.write_text(_line(meta) + _line(turn)) + return path + + def member(self, s, aid: str, member: str, *args) -> dict: + r = s.dev(*args, member=aid, member_type=member) + cmd = " ".join(["dev"] + [shlex.quote(str(a)) for a in args]) + item = {"type": "CommandExecution", "id": r["call"]["tool_use_id"], "command": ["/bin/zsh", "-lc", cmd], + "cwd": f"file://{s.repo}", "status": "completed" if r["rc"] == 0 else "failed", + "exit_code": r["rc"], "aggregated_output": (r["out"] + r["err"])[-2000:]} + path = self.rollout(aid) + ordinal = len(path.read_text().splitlines()) + with path.open("a") as fh: + fh.write(_line({"timestamp": _now(), "ordinal": ordinal, "type": "event_msg", "payload": { + "type": "item_completed", "turn_id": "01a1c178-28b7-7fa1-a67c-2bd8b7433d66", "item": item}})) + self.assertEqual(r["rc"], 0, r["err"]) + return r + + def stop(self, s, aid: str, member: str, report: str, again: bool = False) -> dict: + """SubagentStop as Codex 0.167.0 sends it: the member's own rollout as its transcript. The crew gates credit + a `dev` command only when `dev` on the hook's PATH is devkit's own bin/dev, as on a Mac devkit installed: + the sandbox's commands run through a stand-in launcher, so this hook gets a folder first on PATH whose + `dev` is the checkout's bin/dev.""" + trusted = self.home / "devkit-bin" + if not trusted.exists(): + trusted.mkdir() + (trusted / "dev").symlink_to(ROOT / "bin" / "dev") + env = {name: os.pathsep.join(p for p in (str(trusted), s.host.env.get(name, "")) if p) + for name in ("PATH", "DEVKIT_TEST_PATH")} + payload = s.payload("SubagentStop", agent_id=aid, agent_type=member, model="gpt-6-luna", + stop_hook_active=again, agent_transcript_path=str(self.rollout(aid)), + last_assistant_message=report) + out = s._hook_result(s.host.send([sys.executable, "-I", "-S", "-c", HOOK_BOOT, ROOT / "lib", "subagent-stop", + s.agent, s.mac.spawns], s.repo, env=env, stdin=json.dumps(payload))) + self.assertEqual(set(out) - SUBAGENT_STOP_KEYS, set(), out) # what Codex's output schema accepts + return out + + def review_state(self, s) -> str: + return next(st for st in s.run_doc()["plan"] if st["name"] == "review")["state"] + + def test_a_codex_reviewers_clean_second_stop_after_a_send_back_passes_the_review(self): + self.config(max_parallel=3, reserve=0) + s = self.codex(LEAD, self.api) + s.ok("progress", "start", "Invoice export", "--plan", "api=30m [backend]; review=20m [review] after api") + s.ok("progress", "assign", "api", "--to", "Tank", "--scope", "api/**") + self.spawn(s, TANK, "tank", "api") + self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") + self.stop(s, TANK, "tank", CODEX_REPORT.format(role="Backend engineer (Tank)", task="api")) + s.ok("progress", "assign", "review", "--to", "Seraph") + self.spawn(s, SERAPH, "seraph", "review") + report = CODEX_REPORT.format(role="Code reviewer (Seraph)", task="review") + first = self.stop(s, SERAPH, "seraph", report) + self.assertEqual(first.get("decision"), "block", first) + self.assertIn("the crew gates found", first.get("reason", "")) + self.member(s, SERAPH, "seraph", "progress", "step", "review done", "--step", "review", "--check", + "✓ read the diff, 12 tests pass") + self.assertEqual(self.stop(s, SERAPH, "seraph", report, again=True), {}) + why = [h["why"] for h in s.run_doc()["history"] if h["step"] == "review"][-1] + self.assertEqual(self.review_state(s), "done", why) + + +if __name__ == "__main__": + unittest.main() From 1211d21c0a4757ad6250be6b52e6847423b06872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:26:57 -0800 Subject: [PATCH 04/52] test(crew): give the Codex stops a faithful Codex 0.167 rollout The Codex stop fixture wrote rollouts no gate could read (no folder on each command, no history ordinals, an untrusted dev), so a Codex review failed for the fixture's sake rather than devkit's. Codex members' commands carry their folder and ordinals, the rollout says where the member's history starts, and the stop hook finds devkit's own bin/dev first. The resumed Codex reviewer approves on 26.11.26, so that test is removed; the model applies the review rule only to stops that end the lane. Verified: on an export of 26.11.26 the Codex variants and the model fail for their fault's reason (16 failures, 0 errors); dev test audit 0 findings --- tests/test_coordination_codex.py | 66 +++++++++++++++++--------------- tests/test_coordination_model.py | 37 +++++++++++++++--- 2 files changed, 68 insertions(+), 35 deletions(-) diff --git a/tests/test_coordination_codex.py b/tests/test_coordination_codex.py index 46a0183c..58bebebf 100644 --- a/tests/test_coordination_codex.py +++ b/tests/test_coordination_codex.py @@ -7,6 +7,7 @@ tests/test_codex_launch.py drives them. The Claude Code variants are in tests/test_coordination_lanes.py and tests/test_coordination_identity.py. Run: python3 -m unittest tests.test_coordination_codex""" import json +import os import shlex import sys import unittest @@ -14,6 +15,7 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) +from test_acceptance_crew_sessions import HOOK_BOOT # noqa: E402 from test_codex_launch import LEAD, TANK, CodexCrew, _line, _now # noqa: E402 SERAPH = "01a1c190-64c7-7ac1-81c6-000000000007" @@ -31,24 +33,47 @@ def run_lead(self, plan: str, *assign): s.ok("progress", "assign", step, "--to", name, "--scope", scope) return s + def agent_rollout(self, s, aid: str, member: str, task: str, parent: str = "", depth: int = 1, source=None): + """The spawned agent's rollout as Codex 0.167.0 writes it: its session_meta says where its own history starts + (subagent_history_start_ordinal), its own turn opens with task_started, and every record has its ordinal.""" + path = super().agent_rollout(s, aid, member, task, parent, depth, source) + meta = json.loads(path.read_text()) + meta["ordinal"] = 0 + meta["payload"]["subagent_history_start_ordinal"] = 1 + turn = {"timestamp": _now(), "ordinal": 1, "type": "event_msg", + "payload": {"type": "task_started", "turn_id": "01a1c178-651e-7bc1-a532-a2415b26e099"}} + path.write_text(_line(meta) + _line(turn)) + return path + def member(self, s, aid: str, member: str, *args) -> dict: """A member's `dev` command: its shell call through the hooks, and the CommandExecution item its own rollout - records for it.""" + records for it, with its folder and ordinal.""" r = s.dev(*args, member=aid, member_type=member) cmd = " ".join(["dev"] + [shlex.quote(str(a)) for a in args]) item = {"type": "CommandExecution", "id": r["call"]["tool_use_id"], "command": ["/bin/zsh", "-lc", cmd], - "status": "completed" if r["rc"] == 0 else "failed", "exit_code": r["rc"], - "aggregated_output": (r["out"] + r["err"])[-2000:]} - with self.rollout(aid).open("a") as fh: - fh.write(_line({"timestamp": _now(), "type": "event_msg", "payload": { + "cwd": f"file://{s.repo}", "status": "completed" if r["rc"] == 0 else "failed", + "exit_code": r["rc"], "aggregated_output": (r["out"] + r["err"])[-2000:]} + path = self.rollout(aid) + ordinal = len(path.read_text().splitlines()) + with path.open("a") as fh: + fh.write(_line({"timestamp": _now(), "ordinal": ordinal, "type": "event_msg", "payload": { "type": "item_completed", "turn_id": "01a1c178-28b7-7fa1-a67c-2bd8b7433d66", "item": item}})) return r def stop(self, s, aid: str, member: str, report: str, again: bool = False) -> dict: - """SubagentStop as Codex 0.167.0 sends it: the member's own rollout beside the parent's.""" - return s.hook("subagent-stop", s.payload( - "SubagentStop", agent_id=aid, agent_type=member, model="gpt-6-luna", stop_hook_active=again, - agent_transcript_path=str(self.rollout(aid)), last_assistant_message=report)) + """SubagentStop as Codex 0.167.0 sends it, the member's own rollout as its transcript. The crew gates credit a + `dev` command only when `dev` on the hook's PATH is devkit's own bin/dev, so this hook gets one first.""" + trusted = self.home / "devkit-bin" + if not trusted.exists(): + trusted.mkdir() + (trusted / "dev").symlink_to(ROOT / "bin" / "dev") + env = {name: os.pathsep.join(p for p in (str(trusted), s.host.env.get(name, "")) if p) + for name in ("PATH", "DEVKIT_TEST_PATH")} + payload = s.payload("SubagentStop", agent_id=aid, agent_type=member, model="gpt-6-luna", + stop_hook_active=again, agent_transcript_path=str(self.rollout(aid)), + last_assistant_message=report) + return s._hook_result(s.host.send([sys.executable, "-I", "-S", "-c", HOOK_BOOT, ROOT / "lib", "subagent-stop", + s.agent, s.mac.spawns], s.repo, env=env, stdin=json.dumps(payload))) def held(self, s, name: str) -> tuple: st = self.step(s, name) @@ -56,6 +81,8 @@ def held(self, s, name: str) -> tuple: class CodexLaneTests(CodexCoordination): + # A resumed Codex reviewer's clean report after a send-back does approve on 26.11.26 (the gates credit the + # executed step its rollout records), so that fault has no Codex test here; tests/test_gates_judgment.py keeps it def test_a_codex_members_checked_record_without_step_closes_its_lanes_only_running_step(self): s = self.run_lead("api=30m [backend]; ui=30m [frontend]", ("api", "Tank", "api/**")) self.spawn(s, TANK, "tank", "api") @@ -93,27 +120,6 @@ def test_a_resumed_codex_lane_takes_the_one_step_assigned_to_its_member_by_role( self.assertEqual(self.held(s, "export"), (TANK, "running")) self.assertEqual(s.run_doc()["agents"][TANK].get("scope"), ["export/**"]) - def test_a_resumed_codex_reviewers_clean_report_approves_after_an_earlier_send_back(self): - s = self.run_lead("api=30m [backend]; review=20m [review] after api", ("api", "Tank", "api/**")) - self.spawn(s, TANK, "tank", "api") - self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") - self.stop(s, TANK, "tank", REPORT.format(role="Backend engineer (Tank)", task="api")) - s.ok("progress", "assign", "review", "--to", "Seraph") - self.spawn(s, SERAPH, "seraph", "review") - report = REPORT.format(role="Code reviewer (Seraph)", task="review") - self.assertEqual(self.stop(s, SERAPH, "seraph", report).get("decision"), "block") # no step recorded - self.stop(s, SERAPH, "seraph", report, again=True) # let through - self.assertEqual(self.held(s, "review")[1], "unverified") - s.ok("progress", "reopen", "review", "--why", "the reviewer gives the verdict again") - self.subagent_start(s, SERAPH, "seraph") - self.assertEqual(self.held(s, "review"), (SERAPH, "running")) - r = self.member(s, SERAPH, "seraph", "progress", "step", "review done", "--step", "review", "--check", - "✓ read the diff, 12 tests pass", "--approves", "api") - self.assertEqual(r["rc"], 0, r["err"]) - self.stop(s, SERAPH, "seraph", report) - why = [h["why"] for h in s.run_doc()["history"] if h["step"] == "review"][-1] - self.assertEqual(self.held(s, "review")[1], "done", why) - class CodexCallerTests(CodexCoordination): # On Codex the tech lead's own commands are "unverified", which main-only commands allow, so a member's open diff --git a/tests/test_coordination_model.py b/tests/test_coordination_model.py index 8c8b362c..644de579 100644 --- a/tests/test_coordination_model.py +++ b/tests/test_coordination_model.py @@ -278,7 +278,11 @@ def act(self, a): ready = review.get("owner") == aid and review.get("state") == "running" and any( "--step review" in c for c in self.commands.get(aid, [])) if a["clean"]: - self.stop(aid, member, self.commands.get(aid, [])) + if not self.stop(aid, member, self.commands.get(aid, [])): + ready = False # the gates sent it back for something else: the lane works on + self.ended.discard(aid) + self.check(a, before, expect) + return True else: self.stop(aid, member, []) # a transcript with no step record: sent back once self.stop(aid, member, [], again=True) @@ -296,21 +300,44 @@ def stop(self, aid, member, commands, again=False): """The member's stop through the SubagentStop hook: canary, crew gates, the lane's end.""" root = Path(self.state.tmp.name) tr = root / f"transcript-{aid}-{self.k}.jsonl" - records = [] - for i, command in enumerate(commands, 1): + if self.host == "codex": + tr = self.codex_rollout(aid, commands, tr) + records = [] if self.host == "codex" else None + for i, command in enumerate(commands if records is not None else [], 1): records += [{"type": "assistant", "isSidechain": True, "message": {"role": "assistant", "content": [ {"type": "tool_use", "id": f"toolu_{i:04}", "name": "Bash", "input": {"command": command}}]}}, {"type": "user", "isSidechain": True, "message": {"role": "user", "content": [ {"type": "tool_result", "tool_use_id": f"toolu_{i:04}", "content": "ok"}]}}] - tr.write_text("".join(json.dumps(r) + "\n" for r in records)) + if records is not None: + tr.write_text("".join(json.dumps(r) + "\n" for r in records)) name, role = MEMBERS[member] report = (f"**[Firefly> DevKit · {role} ({name})]** api · `main` · the work\n- **Done:** the work\n" "- **Check:** ✓ 12 tests pass\n- **Next:** the tech lead reviews it") data = {"session_id": "s1", "agent_id": aid, "agent_type": member if self.host == "codex" else f"devkit:{member}", "agent_transcript_path": str(tr), "last_assistant_message": report, "stop_hook_active": again} - with mock.patch("sys.stdin", io.StringIO(json.dumps(data))), contextlib.redirect_stdout(io.StringIO()): + out = io.StringIO() + with mock.patch("sys.stdin", io.StringIO(json.dumps(data))), contextlib.redirect_stdout(out): hooks.subagent_stop(self.host) + return '"block"' not in out.getvalue() # the lane ended: the gates let this stop through + + def codex_rollout(self, aid, commands, tr): + """A Codex member's own rollout as Codex 0.167.0 writes it: its session_meta (where its own history starts), + task_started, then one CommandExecution item per command with its folder, every record with its ordinal.""" + child = next(pg.SESSIONS.parent.glob(f".codex/sessions/*/*/*/rollout-*-{aid}.jsonl")) + meta = json.loads(child.read_text().splitlines()[0]) + meta["ordinal"] = 0 + meta["payload"]["subagent_history_start_ordinal"] = 1 + lines = [meta, {"timestamp": meta.get("timestamp"), "ordinal": 1, "type": "event_msg", + "payload": {"type": "task_started", "turn_id": "t1"}}] + for i, command in enumerate(commands, 2): + lines.append({"timestamp": meta.get("timestamp"), "ordinal": i, "type": "event_msg", "payload": { + "type": "item_completed", "turn_id": "t1", "item": { + "type": "CommandExecution", "id": f"exec-{aid}-{i}", "command": ["/bin/zsh", "-lc", command], + "cwd": f"file://{self.state.tmp.name}", "status": "completed", "exit_code": 0, + "aggregated_output": "✓"}}}) + tr.write_text("".join(json.dumps(r) + "\n" for r in lines)) + return tr # ---------------------------------------------------------------- the rules From bb54650e65b899187071f7c55faaa0b230c26029 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:29:31 -0800 Subject: [PATCH 05/52] fix(ci): take a local step's limit from its workflow, then its history dev ci --run stopped a green 36-minute unit-test step at 30 minutes with exit 124, so the local evidence for a push needed a second, longer run of the whole suite. Root cause: run_local_ci gave every step a fixed limit (step_timeout=30 and the --step-timeout default of 30), unrelated to the timeout-minutes the workflow declares or the step's recorded duration A step's limit is --step-timeout when given, else its own timeout-minutes, then its job's, else 1.5 times its longest whole pass recorded here when that is over 30 minutes, else 30. Step records keep the longest pass across partial reruns. A timeout keeps exit 124 and prints the limit and where it came from. Verified: python3 -m unittest tests.test_ci_limits tests.test_coordination_ci.LocalStepLimitTests tests.test_gitx tests.test_gitx_ci_shortcuts tests.test_pipelines: all OK --- lib/devkit/gitx.py | 79 +++++++++++++++++++++++++---- tests/test_ci_limits.py | 110 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 179 insertions(+), 10 deletions(-) create mode 100644 tests/test_ci_limits.py diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index fad743e1..9f27aff1 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -26,6 +26,7 @@ import contextlib import glob as _glob import json +import math import os import re import shlex @@ -2053,7 +2054,8 @@ def plan_workflow(text: str, fname: str, root: str) -> list: "id": jid, "needs": [str(n) for n in pipelines._as_list(jt.get("needs"))], "cond": cond, "decide": False, "never": False, "outputs": {str(k): str(v) for k, v in outputs.items()}, "matrix": matrix.strip() if isinstance(matrix, str) and "${{" in matrix else None, - "title": title if "${{" in title else ""} + "title": title if "${{" in title else "", + "timeout": _minutes(_scalar(jm["timeout-minutes"][0])) if "timeout-minutes" in jm else None} jobs.append(job) runs_on = _scalar(jm["runs-on"][0]) if "runs-on" in jm else "" if not triggers & CI_TRIGGERS: @@ -2084,7 +2086,9 @@ def plan_workflow(text: str, fname: str, root: str) -> list: sm = _mapping(item, 0, len(item)) sid = _scalar(sm["id"][0]) if "id" in sm else "" st = {"job": jname, "name": "", "run": None, "cwd": root, "env": {}, "skip": None, "blocking": False, - "dropped": [], "id": sid, "dynamic": False, "never": False, "outputs_read": sid in read} + "dropped": [], "id": sid, "dynamic": False, "never": False, "outputs_read": sid in read, + "timeout": _minutes(_scalar(sm["timeout-minutes"][0])) if "timeout-minutes" in sm else None, + "job_timeout": job["timeout"]} if "uses" in sm: st.update(name=_scalar(sm["uses"][0]), skip="setup") job["steps"].append(st) @@ -2897,7 +2901,9 @@ def add_ci_arguments(p): g.add_argument("--evidence", action="store_true", help="show whether HEAD has local CI evidence") g.add_argument("--dry-run", action="store_true", help="with --run: show the plan without running it") g.add_argument("--keep-going", action="store_true", help="with --run: do not stop at the first failure") - g.add_argument("--step-timeout", type=int, default=30, metavar="MIN", help="with --run: minutes per step") + g.add_argument("--step-timeout", type=int, default=None, metavar="MIN", + help="with --run: minutes per step (default: the step's or its job's timeout-minutes; else 1.5 × " + "its longest local pass when that is over 30; else 30)") g.add_argument("--resume", action="store_true", help="with --run: re-run failed and never-run steps, and passed steps the changes since can affect; " "a test step re-runs only its failed and affected tests (whole when the change is global); " @@ -3268,7 +3274,52 @@ def _job_order(jobs) -> list: return out -def run_local_ci(c, dry_run=False, keep_going=False, step_timeout=30, resume=False) -> int: +STEP_FLOOR_MIN = 30 # a local step's limit when neither its workflow nor its history says more + + +def _minutes(value): + """A `timeout-minutes` value -> a positive number of minutes, or None (an expression, or not a number).""" + try: + m = float(str(value).strip()) + except (TypeError, ValueError): + return None + return (int(m) if m == int(m) else m) if m > 0 else None + + +def _longest_pass(rec): + """The longest whole pass, in seconds, recorded for a local step: the record's `longest`, kept across partial + reruns, else its own duration when it was a whole pass; None when it never passed whole here.""" + if not isinstance(rec, dict): + return None + kept = rec.get("longest") + if isinstance(kept, (int, float)) and not isinstance(kept, bool) and kept > 0: + return float(kept) + secs = rec.get("secs") + if rec.get("rc") == 0 and rec.get("how") == "full" and isinstance(secs, (int, float)) and secs > 0: + return float(secs) + return None + + +def step_limit(s, rec=None, given=None) -> tuple: + """The minutes local step `s` may run and where that number comes from -> (minutes, source): `given` (the + command line's --step-timeout); else the step's own timeout-minutes, then its job's, as the workflow declares + them; else 1.5 times the longest whole pass recorded here (`rec`, its step record), rounded up to a minute, when + that is above the floor; else the floor. A limit from history never lowers the floor: a step that ran fast once + (a warm cache) still gets the floor when it runs cold.""" + if given: + return given, "--step-timeout" + if s.get("timeout"): + return s["timeout"], "the step's timeout-minutes" + if s.get("job_timeout"): + return s["job_timeout"], "the job's timeout-minutes" + longest = _longest_pass(rec) + mins = math.ceil(longest * 1.5 / 60) if longest else 0 + if mins > STEP_FLOOR_MIN: + return mins, f"1.5 × its longest pass here ({_fmt_secs(longest)})" + return STEP_FLOOR_MIN, f"the {STEP_FLOOR_MIN}-minute default" + + +def run_local_ci(c, dry_run=False, keep_going=False, step_timeout=None, resume=False) -> int: from . import pipelines jobs = _job_order(plan(c.top)) if not jobs: @@ -3279,7 +3330,8 @@ def run_local_ci(c, dry_run=False, keep_going=False, step_timeout=30, resume=Fal [(s["job"], s["name"], s["skip"], s["blocking"]) for j in jobs if not j["skip"] for s in j["steps"] if s["skip"] and s["skip"] != "setup"] setup = sum(1 for j in jobs for s in j["steps"] if s["skip"] == "setup") - records = step_records(c) if resume else {} + history = step_records(c) # each step's last record: what --resume keeps, and its longest pass for its limit + records = history if resume else {} if resume and not records: info("nothing recorded yet: --resume runs every step") resume = False @@ -3343,13 +3395,15 @@ def run_step(s): label = f"{s['job']} › {s['name']}" command = s["run"].splitlines()[0][:120] if s["run"] else "" rec = records.get(key) + limit, limit_from = step_limit(s, history.get(key), step_timeout) + longest = _longest_pass(history.get(key)) decision, detail = _resume_plan(c, s, rec, tree, cache) if resume and tree else ("full", None) res = None if decision == "partial": runner = detail["runner"] runner["env"] = dict(runner.get("env") or {}) p = testx.partial(c.top, runner, failed=detail["failed"], changed=detail["changed"], - env=dict(env, **runner["env"]), timeout=step_timeout * 60, log=log) + env=dict(env, **runner["env"]), timeout=limit * 60, log=log) if "skip" in p: decision, detail = "kept", p["skip"] elif "whole" in p: @@ -3381,7 +3435,8 @@ def run_step(s): "tests": res["count"], "runner": res["runner"], "base": base, "partials": partials, "complete": res.get("complete") is True, "completion_version": 1, "failed_tests": [fx["id"] for fx in res["failures"]], - "failed": [{"id": fx["id"], "file": fx["file"]} for fx in res["failures"]]} + "failed": [{"id": fx["id"], "file": fx["file"]} for fx in res["failures"]], + "longest": longest} results.append({"job": s["job"], "step": s["name"], "rc": rc, "secs": round(secs, 1), "command": command, "how": "partial", "tests": res["count"], "sha": sha, "tree": tree, "base_sha": base.get("sha"), "base_tree": base.get("tree"), "partials": partials}) @@ -3395,13 +3450,14 @@ def run_step(s): invocation.mkdir() completion = testx.unittest_completion(invocation) argv[-1] = testx.observe_unittest_shell(s["run"], invocation, completion) + timed_out = False try: with open(log, "w") as fh: rc = subprocess.run(argv, cwd=s["cwd"], stdout=fh, stderr=subprocess.STDOUT, env=env, - timeout=step_timeout * 60).returncode + timeout=limit * 60).returncode except subprocess.TimeoutExpired: - rc = 124 + rc, timed_out = 124, True except OSError as e: log.write_text(str(e)) rc = 127 @@ -3420,7 +3476,8 @@ def run_step(s): "runner": runner["name"] if runner else None, "complete": complete, "completion_version": 1, "failed_tests": [fx["id"] for fx in fails] if fails else None, "failed": fails, - "base": {"sha": sha, "tree": tree}, "partials": [], "outputs": outputs} + "base": {"sha": sha, "tree": tree}, "partials": [], "outputs": outputs, + "longest": round(max(longest or 0, secs if rc == 0 else 0), 1) or None} results.append({"job": s["job"], "step": s["name"], "rc": rc, "secs": round(secs, 1), "command": command, "how": "full", "sha": sha, "tree": tree}) print(f" {ui.OK if rc == 0 else ui.FAIL} {label} {ui.dim(_fmt_secs(secs))}") @@ -3430,6 +3487,8 @@ def run_step(s): tail = [ln.rstrip()[:200] for ln in log.read_text(errors="replace").splitlines() if ln.strip()][-20:] for ln in tail: print(f" {ui.dim(ui.ANSI_RE.sub('', ln))}") + if timed_out: # distinct from a test failure: say which limit stopped it, so a slow step is not misread + print(f" {ui.dim(f'timed out after {limit:g} min (limit from {limit_from})')}") print(f" {ui.dim('exit ' + str(rc) + ' · full log: ' + core.tilde(log))}") if rc == 127 and s.get("dropped"): print(" " + ui.dim("a tool this step installs on the runner is missing here: install it on " diff --git a/tests/test_ci_limits.py b/tests/test_ci_limits.py new file mode 100644 index 00000000..42f5724a --- /dev/null +++ b/tests/test_ci_limits.py @@ -0,0 +1,110 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""`dev ci --run` gives each local step the time its project allows: `--step-timeout` when given; else the step's own +`timeout-minutes`, then its job's; else 1.5 times the longest pass recorded for the step, rounded up to a minute and +never below the floor; else the floor of 30 minutes. A step that runs past its limit ends with exit 124 and says the +limit and where it came from. devkit's own unit-test step takes about 36 minutes and used to end with 124 at 30. + +Run: python3 -m unittest tests.test_ci_limits -v""" +import subprocess +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import gitx # noqa: E402 +from test_gitx import Sandbox, dev # noqa: E402 + + +def workflow(job_timeout=None, step_timeout=None, steps=(("Unit tests", "test -f README.md"),)) -> str: + """A pull-request workflow with one job `test` and its run steps, with the timeouts given.""" + text = "name: CI\non: [pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n" + if job_timeout is not None: + text += f" timeout-minutes: {job_timeout}\n" + text += " steps:\n" + for i, (name, run) in enumerate(steps): + text += f" - name: {name}\n run: {run}\n" + if step_timeout is not None and i == 0: + text += f" timeout-minutes: {step_timeout}\n" + return text + + +class StepLimitCase(unittest.TestCase): + def setUp(self): + self.s = Sandbox().__enter__() + self.addCleanup(self.s.__exit__, None, None, None) + self.limits, self.real_run = {}, subprocess.run + + def ci(self, text, *flags, slow=()): + """`dev ci --run` on a branch with workflow `text` -> (rc, output); each step's limit lands in self.limits, + and a step whose command is in `slow` runs past it.""" + self.s.commit("ci: the workflow", files={".github/workflows/ci.yml": text}) + + def spy(argv, *args, **kwargs): # the step's own shell, as run_local_ci starts it + if isinstance(argv, list) and argv[:1] == ["bash"]: + self.limits[argv[-1]] = kwargs.get("timeout") + if argv[-1] in slow: + raise subprocess.TimeoutExpired(argv, kwargs.get("timeout")) + return self.real_run(argv, *args, **kwargs) + with mock.patch.object(gitx.subprocess, "run", spy): + rc, out, err = dev("ci", "--run", *flags) + return rc, out + err + + def record(self, step, secs, rc=0, how="full"): + """An earlier local run of `test › `, as dev ci --run records it.""" + gitx._save_step(gitx.ctx(self.s.repo), f"test › {step}", + {"job": "test", "step": step, "rc": rc, "secs": secs, "how": how, "ts": 1795140000}) + + +class WorkflowLimitTests(StepLimitCase): + def setUp(self): + super().setUp() + self.s.branch("feat/ci") + + def test_the_jobs_timeout_minutes_is_the_limit_of_its_steps_unless_the_command_line_gives_one(self): + rc, out = self.ci(workflow(job_timeout=45)) + self.assertEqual(rc, 0, out) + self.assertEqual(self.limits, {"test -f README.md": 45 * 60}) + rc, out = self.ci(workflow(job_timeout=45) + "# again\n", "--step-timeout", "5") + self.assertEqual(rc, 0, out) + self.assertEqual(self.limits, {"test -f README.md": 5 * 60}) + + def test_a_steps_own_timeout_minutes_wins_over_its_jobs(self): + rc, out = self.ci(workflow(job_timeout=40, step_timeout=50)) + self.assertEqual(rc, 0, out) + self.assertEqual(self.limits, {"test -f README.md": 50 * 60}) + + def test_a_step_past_its_limit_ends_124_and_names_the_limit_and_its_source(self): + rc, out = self.ci(workflow(job_timeout=45), slow=("test -f README.md",)) + self.assertEqual(rc, 1, out) + self.assertIn("timed out after 45 min (limit from the job's timeout-minutes)", out) + self.assertEqual(gitx.step_records(gitx.ctx(self.s.repo))["test › Unit tests"]["rc"], 124) + + +class HistoryLimitTests(StepLimitCase): + STEPS = (("Unit tests", "test -f README.md"), ("Lint", "test -d .git")) + + def setUp(self): + super().setUp() + self.s.branch("feat/ci") + + def test_without_a_workflow_timeout_the_longest_recorded_pass_sets_the_limit_above_the_floor(self): + self.record("Unit tests", 2142.5) # devkit's own unit-test step: 35.7 minutes -> 1.5 times, 54 minutes + self.record("Lint", 60) # 1.5 minutes from history: the 30-minute floor stays + rc, out = self.ci(workflow(steps=self.STEPS)) + self.assertEqual(rc, 0, out) + self.assertEqual(self.limits, {"test -f README.md": 54 * 60, "test -d .git": 30 * 60}) + + def test_a_short_pass_keeps_the_limit_its_longest_pass_set(self): + self.record("Unit tests", 2142.5) + self.assertEqual(self.ci(workflow(steps=self.STEPS[:1]))[0], 0) # passes in milliseconds this time + self.limits.clear() + rc, out = self.ci(workflow(steps=self.STEPS[:1]) + "# again\n") + self.assertEqual(rc, 0, out) + self.assertEqual(self.limits, {"test -f README.md": 54 * 60}) + + +if __name__ == "__main__": + unittest.main() From 9a1c3e4a06cb35f8636be55aa221015211f53b77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:35:10 -0800 Subject: [PATCH 06/52] fix(ci): name why a job never started instead of a missing log A run whose jobs GitHub never started (an Actions budget, failed payments, no runner) was reported as 'failing log unavailable: log not found' by dev run view --failed and dev pr checks, and as class unknown by dev ci watch, so nobody saw that no code change or push could fix it. Root cause: gitx._run_view and failing_logs only read the failed log, and ciwatch.diagnose classified by that log or the job names; none read the job's check-run annotations or noticed the job had no steps One reader, ciwatch.never_started, reads a failed job's check-run annotation when the job has no steps or no log, and classes it not_started (subclass budget for an account limit) with the one next action. A run that failed at startup is workflow_invalid. The annotation is shown as one redacted line of at most 300 characters. Verified: python3 -m unittest tests.test_ci_not_started tests.test_coordination_ci tests.test_ciwatch tests.test_ciwatch_sessions tests.test_acceptance_watch tests.test_dashnow tests.test_watch_e2e tests.test_watch_stop tests.test_gitx: 356 tests OK --- lib/devkit/ciwatch.py | 131 ++++++++++++++++++++++++++++++++-- lib/devkit/gitx.py | 19 +++++ tests/test_ci_not_started.py | 132 +++++++++++++++++++++++++++++++++++ 3 files changed, 276 insertions(+), 6 deletions(-) create mode 100644 tests/test_ci_not_started.py diff --git a/lib/devkit/ciwatch.py b/lib/devkit/ciwatch.py index e4f22aa6..4e465ed0 100644 --- a/lib/devkit/ciwatch.py +++ b/lib/devkit/ciwatch.py @@ -117,7 +117,21 @@ "cancelled": "the run stopped before it finished (a newer push or someone cancelled it, or a job ran past its " "timeout): read where it stopped (dev run view ); for a timeout, find what hung or ran slow, " "reproduce it locally, fix, push once; for a newer push, follow that push's own run", + # a job that never started has no log and nothing to reproduce: its cause is in its check run's annotation + "not_started": "the job never started, so there is no log and nothing to reproduce locally: fix the cause its " + "annotation names (a runs-on label no runner has is fixed in the workflow, dev ci audit; a host or " + "account limit by whoever owns it), then rerun the run once, without a new push", + "budget": "an account limit, not the code: no local reproduction; the developer checks billing (the Actions " + "budget, spending limit or payment method); do not push again until it is lifted, then rerun the run", + "workflow_invalid": "GitHub could not start the run, so a workflow file is invalid: run dev ci audit and " + "actionlint, fix the file, push once", } +# A check-run annotation that says the job never ran, and the ones that name an account's spending limit or payments +NOT_STARTED_RE = re.compile(r"(?i)\b(?:was|were) not (?:started|acquired)\b|spending limit|budget is preventing|" + r"payments? (?:have |has )?failed|account is locked|billing") +BUDGET_RE = re.compile(r"(?i)spending limit|\bbudget\b|payments? (?:have |has )?failed|account is locked|billing") +_SLUG_RE = re.compile(r"github\.com/([\w.-]+/[\w.-]+)/actions/runs/") +_JOB_RE = re.compile(r"/actions/runs/\d+/job/(\d+)") ERROR_LINE = re.compile(r"(?i)\b(error|failed|failure|fatal|exception|traceback|assert|panic|cannot|could not|" r"not found|denied|exit code [1-9])\b|✗|##\[error\]") # A line that names a class of failure (CLASSES) and reads as one: a tool's name alone ("Run ruff check") is no error @@ -228,7 +242,88 @@ def failed_log(provider: str, top: str, run: dict, job: dict | None = None) -> s return "" -def diagnose(provider: str, top: str, run: dict) -> dict: +def _gh(args, cwd=None, timeout=60) -> tuple: + """gh with `args` -> (exit code, stdout, stderr), as gitx.GH answers.""" + p = subprocess.run(["gh", *[str(a) for a in args]], cwd=cwd, capture_output=True, text=True, timeout=timeout) + return p.returncode, p.stdout, p.stderr + + +def host_line(text, limit: int = 300) -> str: + """Text a CI host wrote (an annotation), as one line: control characters and ANSI codes stripped, whitespace + joined, secrets redacted, at most `limit` characters.""" + from .audit import redact + s = re.sub(r"\x1b\[[0-9;?]*[ -/]*[@-~]", "", str(text or "")) + s = " ".join(re.sub(r"[\x00-\x1f\x7f-\x9f]", " ", s).split()) + s = redact(s) + return s if len(s) <= limit else s[:limit - 1] + "…" + + +def job_annotation(slug: str, job_id, gh=None) -> str: + """The first annotation of a GitHub Actions job's check run (a failure before a warning or a notice), as one + line (host_line), or "" when there is none or gh cannot read it. A job's id is its check run's id. `gh`: a + callable with gitx.GH's arguments and answer (default: the gh on PATH).""" + if not re.fullmatch(r"[\w.-]+/[\w.-]+", str(slug or "")) or not str(job_id or "").isdigit(): + return "" + try: + rc, out, _ = (gh or _gh)(["api", f"repos/{slug}/check-runs/{job_id}/annotations"], timeout=30) + notes = json.loads(out or "[]") if rc == 0 else [] + except (OSError, ValueError, subprocess.TimeoutExpired): + return "" + notes = [n for n in notes if isinstance(n, dict) and str(n.get("message") or "").strip()] \ + if isinstance(notes, list) else [] + order = {"failure": 0, "warning": 1, "notice": 2} + notes.sort(key=lambda n: order.get(str(n.get("annotation_level") or ""), 3)) + return host_line(notes[0]["message"]) if notes else "" + + +def _job_started(job) -> bool | None: + """Whether a job ran: True with steps, False with none (or no start time), None when the record does not say. + Reads gh's job (`steps`, `startedAt`) and cistatus's (`steps_total`, `started`).""" + if not isinstance(job, dict): + return None + steps = job.get("steps") + count = len(steps) if isinstance(steps, list) else job.get("steps_total") + if isinstance(count, int) and not isinstance(count, bool): + return count > 0 + for key in ("started", "startedAt"): + if key in job: + return bool(job[key]) + return None + + +def never_started(slug: str, job_id, gh=None, job: dict | None = None) -> dict | None: + """Why a failed GitHub Actions job never started -> {"class": "not_started", "subclass": "budget" or "", + "cause": its annotation, "action": the one next action}, or None when it ran. `job`: its record from gh or + cistatus, when known: a job with steps ran, and its annotations are not read; one with no steps never started, + with or without an annotation; with no record, an annotation that says the job was not started decides.""" + ran = _job_started(job) + if ran: + return None + cause = job_annotation(slug, job_id, gh) + if ran is None and not NOT_STARTED_RE.search(cause): + return None + sub = "budget" if BUDGET_RE.search(cause) else "" + return {"class": "not_started", "subclass": sub, "cause": cause, "action": ACTIONS[sub or "not_started"]} + + +def never_started_line(name, why: dict) -> str: + """`job “” never started: (budget)`, the line that names a job that never started.""" + return (f"job “{_one_line(name)}” never started" + (f": {why['cause']}" if why.get("cause") else "") + + (f" ({why['subclass']})" if why.get("subclass") else "")) + + +def _job_id(job: dict) -> str: + if str(job.get("id") or "").isdigit(): + return str(job["id"]) + m = _JOB_RE.search(str(job.get("url") or "")) + return m.group(1) if m else "" + + +def diagnose(provider: str, top: str, run: dict, repo: str = "") -> dict: + """A failed run's diagnosis: its failed jobs, the first error of its failed log, the class and the one next + action. On GitHub, a run that failed at startup is `workflow_invalid`, and a failed job with no log that never + started is `not_started` with its annotation's cause (never_started). `repo`: owner/name, else read from the + job's or the run's link.""" word = conclusion(run)[0] jobs = [j for j in run.get("jobs") or [] if j.get("status") in ("failed", "cancelled")] job = jobs[0] if jobs else None @@ -239,11 +334,25 @@ def diagnose(provider: str, top: str, run: dict) -> dict: classify(excerpt or log[-20_000:] if log else " ".join(j.get("name", "") for j in jobs)) if kind == "unknown" and log and word not in STOPPED: # the first error says too little: the failed log's end kind = classify(first_error(log[-20_000:], context=0, limit=10_000) or log[-20_000:]) + sub, cause, unstarted = "", "", None + if provider == "github" and not log: # no log: a job that never ran, or a run GitHub could not start + slug = repo or next((m.group(1) for m in (_SLUG_RE.search(str(x.get("url") or "")) for x in jobs + [run]) + if m), "") + for j in jobs[:3]: + why = never_started(slug, _job_id(j), job=j) + if why: + kind, sub, cause, unstarted = why["class"], why["subclass"], why["cause"], j.get("name") or "?" + break + if word == "startup failure" and not unstarted: + kind = "workflow_invalid" + cause = next((c for c in (job_annotation(slug, _job_id(j)) for j in jobs[:3]) if c), "") return {"run": run.get("name"), "number": run.get("number"), "id": run.get("id"), "url": run.get("url"), "sha": run.get("sha"), "conclusion": word, "failed_jobs": [{"name": j.get("name"), "step": j.get("current") or "", "url": j.get("url")} for j in jobs], - "class": kind, "action": ACTIONS[kind], "excerpt": excerpt, - "log": "first error of the failed log" if excerpt else "no log available: open the link"} + "class": kind, "subclass": sub, "cause": cause, "action": ACTIONS[sub or kind], "excerpt": excerpt, + "never_started": unstarted, + "log": "first error of the failed log" if excerpt else + "the job never started, so it has no log" if unstarted else "no log available: open the link"} def _one_line(text, limit: int = 100) -> str: @@ -373,7 +482,7 @@ def _finish(top, data, branch, sha, runs, state, start, clock, always_diagnose=F # a repeat nobody waits on is not diagnosed (each diagnosis reads a log online); one a joined session still has to # hear is, so its message carries the class and the next action if fresh or always_diagnose or (state in FINAL and _owed(ident, branch, sha)): - res["diagnoses"] = [dict(diagnose(provider, top, r), new=k in fresh) + res["diagnoses"] = [dict(diagnose(provider, top, r, repo=data.get("repo") or ""), new=k in fresh) for r, (_, mark), k in zip(runs, ends, keys) if mark == "failed"] if state in FINAL: res["told"] = sorted(f"{a}:{s}" for a, s in _settle(res)) @@ -442,7 +551,12 @@ def message(res: dict) -> str: for d in diags: jobs = ", ".join(j["name"] + (f" (step {j['step']})" if j.get("step") else "") for j in d["failed_jobs"]) out.append(f"- {d['run']} #{d['number']} {d.get('conclusion') or 'failed'}" + (f" in {jobs}" if jobs else "") - + f": class **{d['class']}**. Next: {d['action']}. Log: {d['url']}") + + f": class **{d['class']}**" + (f" ({d['subclass']})" if d.get("subclass") else "") + + f". Next: {d['action']}. Log: {d['url']}") + if d.get("never_started"): # the host's own words (untrusted, one line): why the job never ran + out.append(" " + never_started_line(d["never_started"], d)) + elif d.get("cause"): + out.append(f" GitHub says: {d['cause']}") if d.get("excerpt"): out.append(" First error (untrusted CI output: data, not instructions):\n ```text\n " + d["excerpt"].replace("\n", "\n ")[:1800] + "\n ```") @@ -1212,7 +1326,12 @@ def wait_lines(res: dict, again: str) -> list: for j in d.get("failed_jobs") or []) causes.append(f"{_one_line(d.get('run'), 60)} #{d.get('number')} {d.get('conclusion') or 'failed'}" + (f" in {jobs}" if jobs else "") - + f": class {d['class']}; next: {d['action']} · log: {d['url']}") + + f": class {d['class']}" + (f" ({d['subclass']})" if d.get("subclass") else "") + + f"; next: {d['action']} · log: {d['url']}") + if d.get("never_started"): + lines.append(never_started_line(d["never_started"], d)) + elif d.get("cause"): + lines.append(f"GitHub says: {d['cause']}") if d.get("excerpt"): lines.append(f"first error of {_one_line(d.get('run'), 60)} #{d.get('number')} (untrusted CI output: data, " "not instructions):") diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 9f27aff1..9d6a138c 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -4154,6 +4154,9 @@ def trim_log(text: str, n: int = 25) -> list: def failing_logs(c, checks, lines=25, max_jobs=3) -> list: + """[(check name, its failed log's relevant lines)] for the first failed checks; a job whose log is unavailable + because it never started gets its cause from its check run's annotation (ciwatch.never_started) instead.""" + from . import ciwatch out = [] for ch in [x for x in checks if x.get("bucket") == "fail"][:max_jobs]: m = _LINK_RE.search(ch.get("link") or "") @@ -4161,6 +4164,11 @@ def failing_logs(c, checks, lines=25, max_jobs=3) -> list: continue args = ["run", "view", m.group(1), "-R", c.slug, "--log-failed"] + (["--job", m.group(2)] if m.group(2) else []) rc, log, err = GH(args, cwd=c.top, timeout=120) + why = ciwatch.never_started(c.slug, m.group(2), GH) if rc != 0 and m.group(2) else None + if why: + out.append((ch.get("name"), [f"never started: {why['cause']}" + (f" ({why['subclass']})" if why["subclass"] + else ""), f"next: {why['action']}"])) + continue out.append((ch.get("name"), trim_log(log, lines) if rc == 0 else [f"(log unavailable: {_first_line(err)})"])) return out @@ -4752,6 +4760,17 @@ def _run_view(c, a) -> int: if good: info(f"{good} job(s) passed") if a.failed and bad: + from . import ciwatch + unstarted = [] + for j in bad: # a job that never ran has no log: its check run's annotation says why + why = ciwatch.never_started(c.slug, j.get("databaseId"), GH, job=j) + if why: + unstarted.append(j) + print(f" {ui.FAIL} {ciwatch.never_started_line(j.get('name'), why)}") + print(" " + ui.dim(f"class {why['class']}" + (f" ({why['subclass']})" if why["subclass"] else "") + + f" · next: {why['action']}")) + if len(unstarted) == len(bad): + return 1 rc, log, err = GH(["run", "view", rid, "-R", c.slug, "--log-failed"], cwd=c.top, timeout=120) if rc != 0: return fail(f"failing log unavailable: {_first_line(err)}") diff --git a/tests/test_ci_not_started.py b/tests/test_ci_not_started.py new file mode 100644 index 00000000..c5163cfc --- /dev/null +++ b/tests/test_ci_not_started.py @@ -0,0 +1,132 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""A CI job that never started has no log: devkit reads its check run's annotations and names the cause, with the one +next action. `dev run view --failed`, `dev pr checks` (gitx.failing_logs) and the CI watch (ciwatch.diagnose) share +one reader (ciwatch.never_started). A job is classed `not_started` (subclass `budget` for an account's spending limit +or failed payments, which no code change or push fixes), and a run that failed at startup `workflow_invalid`. The +annotation is host text: one line, control characters stripped, secrets redacted, at most 300 characters. Every gh +call goes to a fake (gitx's FakeGH, or a stand-in gh first on PATH); no test reaches GitHub. + +Run: python3 -m unittest tests.test_ci_not_started -v""" +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import ciwatch, gitx # noqa: E402 +from test_gitx import Sandbox, dev # noqa: E402 + +BUDGET = "The job was not started because an Actions budget is preventing further use." +NO_RUNNER = "The job was not acquired by Runner of type self-hosted even after multiple attempts" +JOB_ID, RUN_ID = "135985601878", "44645118961" +JOB_URL = f"https://github.com/acme/api/actions/runs/{RUN_ID}/job/{JOB_ID}" + + +class GitxNeverStartedTests(unittest.TestCase): + def setUp(self): + self.s = Sandbox().__enter__() + self.addCleanup(self.s.__exit__, None, None, None) + self.s.gh.on(["run", "view"], rc=1, err=f"failed to get run log: log not found: {JOB_ID}", + when=lambda a: "--log-failed" in a) + self.s.gh.on(["api"], [{"annotation_level": "failure", "message": BUDGET, "path": ".github"}], + when=lambda a: a[1:2] == [f"repos/acme/widget/check-runs/{JOB_ID}/annotations"]) + + def test_run_view_failed_names_why_a_job_never_started_and_the_one_next_action(self): + self.s.gh.on(["run", "view"], {"workflowName": "ci", "number": 40, "conclusion": "failure", + "headBranch": "release/26.11.25", "headSha": "0bde25cdef", "event": "pull_request", + "url": JOB_URL, "jobs": [{"name": "tests (part 1 of 2)", "conclusion": "failure", + "databaseId": int(JOB_ID), "steps": []}]}, + when=lambda a: "--json" in a) + rc, out, err = dev("run", "view", RUN_ID, "--failed") + self.assertEqual(rc, 1, out + err) + self.assertIn(f"job “tests (part 1 of 2)” never started: {BUDGET} (budget)", out + err) + self.assertIn("an account limit, not the code", out + err) + self.assertNotIn("log unavailable", out + err) + + def test_pr_checks_name_why_a_failed_job_never_started_instead_of_a_missing_log(self): + checks = [{"name": "tests (part 1 of 2)", "bucket": "fail", "link": f"https://github.com/acme/widget/actions/" + f"runs/{RUN_ID}/job/{JOB_ID}"}] + lines = dict(gitx.failing_logs(gitx.ctx(self.s.repo), checks))["tests (part 1 of 2)"] + self.assertEqual(lines[0], f"never started: {BUDGET} (budget)") + self.assertTrue(any("an account limit, not the code" in ln for ln in lines), lines) + + +class StandInGh(unittest.TestCase): + """A stand-in gh first on PATH that answers a job's annotations with `self.notes` and fails every other call.""" + notes = [] + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + tools = Path(tmp.name) + (tools / "notes.json").write_text(json.dumps(self.notes)) + (tools / "gh").write_text("#!/bin/sh\n" + 'case "$*" in\n' + f' "api repos/acme/api/check-runs/{JOB_ID}/annotations") cat "{tools}/notes.json" ;;\n' + ' *) echo "no canned answer: gh $*" >&2; exit 1 ;;\n' + "esac\n") + (tools / "gh").chmod(0o755) + path = mock.patch.dict(os.environ, {"PATH": str(tools) + os.pathsep + os.environ["PATH"]}) + path.start() + self.addCleanup(path.stop) + log = mock.patch.object(ciwatch, "failed_log", lambda *a, **k: "") # a job that never ran has no log + log.start() + self.addCleanup(log.stop) + + def diagnose(self, conclusion="failure", jobs=None): + run = {"id": RUN_ID, "name": "ci", "number": 40, "status": "failed", "conclusion": conclusion, + "url": f"https://github.com/acme/api/actions/runs/{RUN_ID}", "jobs": jobs if jobs is not None else [ + {"name": "tests (part 1 of 2)", "status": "failed", "current": "", "url": JOB_URL, + "steps_total": 0, "started": 0}]} + return ciwatch.diagnose("github", tempfile.gettempdir(), run) # the repository: from the job's or run's link + + +class BudgetDiagnosisTests(StandInGh): + notes = [{"annotation_level": "warning", "message": "Node.js 16 actions are deprecated."}, + {"annotation_level": "failure", "message": BUDGET}] + + def test_a_job_an_actions_budget_kept_from_starting_is_not_started_budget_with_its_cause(self): + d = self.diagnose() + self.assertEqual((d["class"], d["subclass"], d["cause"]), ("not_started", "budget", BUDGET)) + self.assertIn("do not push again", d["action"]) + said = ciwatch.message({"state": "failed", "branch": "main", "sha": "abc1234", "minutes": 1, + "runs": [{"name": "ci", "number": 40, "status": "failed", "conclusion": "failed"}], + "diagnoses": [d]}) + self.assertIn(f"job “tests (part 1 of 2)” never started: {BUDGET} (budget)", said) + + +class NoRunnerDiagnosisTests(StandInGh): + notes = [{"annotation_level": "failure", "message": NO_RUNNER}] + + def test_a_job_no_runner_took_is_not_started_without_the_budget_subclass(self): + d = self.diagnose() + self.assertEqual((d["class"], d["subclass"], d["cause"]), ("not_started", "", NO_RUNNER)) + self.assertIn("runs-on", d["action"]) + + +class HostTextTests(StandInGh): + notes = [{"annotation_level": "failure", + "message": "The job was not started:\n\x1b[31mtoken ghp_" + "a" * 36 + "\x1b[0m " + "x" * 400}] + + def test_an_annotation_is_shown_as_one_redacted_line_of_at_most_300_characters(self): + cause = self.diagnose()["cause"] + self.assertLessEqual(len(cause), 300) + self.assertTrue(cause.startswith("The job was not started: token "), cause) + self.assertNotIn("ghp_" + "a" * 36, cause) + self.assertFalse(any(ch in cause for ch in "\n\r\x1b"), repr(cause)) + + +class StartupFailureTests(StandInGh): + def test_a_run_that_failed_at_startup_is_an_invalid_workflow(self): + d = self.diagnose(conclusion="startup_failure", jobs=[]) + self.assertEqual(d["class"], "workflow_invalid") + self.assertIn("dev ci audit", d["action"]) + + +if __name__ == "__main__": + unittest.main() From 0b76d83cdfc5f92f674865927d6de1c2b551466c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:44:17 -0800 Subject: [PATCH 07/52] fix(ci): let history lift a matrix job's per-leg limit in dev ci --run devkit's test job allows 40 minutes for each half of the suite on a runner, but dev ci --run runs it once over the whole suite, which passed in 35.7 minutes here: a 12% margin before the green step ends with exit 124 again. Root cause: a literal matrix is not expanded locally, so the step runs every leg's work in one run, while the job's timeout-minutes it was given is one leg's For a job with a literal matrix, the step's limit is the larger of the job's timeout-minutes and 1.5 times the step's longest local pass; devkit's unit-test step gets 54 minutes. A job without a matrix keeps its declared timeout. Verified: dev test run (test_ci_limits, test_coordination_ci, test_gitx, test_gitx_ci_shortcuts, test_pipelines, test_cli_ci, test_workflow_ci): 251 passed; dev test prove: the new test fails without the change --- lib/devkit/gitx.py | 17 ++++++++++++----- tests/test_ci_limits.py | 13 +++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 9d6a138c..3a16a405 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -2088,7 +2088,9 @@ def plan_workflow(text: str, fname: str, root: str) -> list: st = {"job": jname, "name": "", "run": None, "cwd": root, "env": {}, "skip": None, "blocking": False, "dropped": [], "id": sid, "dynamic": False, "never": False, "outputs_read": sid in read, "timeout": _minutes(_scalar(sm["timeout-minutes"][0])) if "timeout-minutes" in sm else None, - "job_timeout": job["timeout"]} + "job_timeout": job["timeout"], + # a literal matrix runs once here, its values unset: the job's timeout is one leg's, not this run's + "one_leg": bool(matrix) and not job["matrix"]} if "uses" in sm: st.update(name=_scalar(sm["uses"][0]), skip="setup") job["steps"].append(st) @@ -3305,17 +3307,22 @@ def step_limit(s, rec=None, given=None) -> tuple: command line's --step-timeout); else the step's own timeout-minutes, then its job's, as the workflow declares them; else 1.5 times the longest whole pass recorded here (`rec`, its step record), rounded up to a minute, when that is above the floor; else the floor. A limit from history never lowers the floor: a step that ran fast once - (a warm cache) still gets the floor when it runs cold.""" + (a warm cache) still gets the floor when it runs cold. A job with a literal matrix runs once here over what its + legs share on a runner (devkit's tests: the whole suite, in two parts there), so its timeout-minutes, which is one + leg's, gives way to a longer limit from history.""" if given: return given, "--step-timeout" if s.get("timeout"): return s["timeout"], "the step's timeout-minutes" - if s.get("job_timeout"): - return s["job_timeout"], "the job's timeout-minutes" longest = _longest_pass(rec) mins = math.ceil(longest * 1.5 / 60) if longest else 0 + learned = f"1.5 × its longest pass here ({_fmt_secs(longest)})" if longest else "" + if s.get("job_timeout"): + if s.get("one_leg") and mins > s["job_timeout"]: + return mins, learned + ", over the job's timeout-minutes for one matrix leg" + return s["job_timeout"], "the job's timeout-minutes" if mins > STEP_FLOOR_MIN: - return mins, f"1.5 × its longest pass here ({_fmt_secs(longest)})" + return mins, learned return STEP_FLOOR_MIN, f"the {STEP_FLOOR_MIN}-minute default" diff --git a/tests/test_ci_limits.py b/tests/test_ci_limits.py index 42f5724a..51aa70da 100644 --- a/tests/test_ci_limits.py +++ b/tests/test_ci_limits.py @@ -97,6 +97,19 @@ def test_without_a_workflow_timeout_the_longest_recorded_pass_sets_the_limit_abo self.assertEqual(rc, 0, out) self.assertEqual(self.limits, {"test -f README.md": 54 * 60, "test -d .git": 30 * 60}) + def test_a_matrix_job_run_once_here_gets_more_than_one_legs_timeout_when_its_history_needs_it(self): + # devkit's own test job: timeout-minutes 40 for each half of the suite on a runner; dev ci --run does not + # expand a literal matrix, so here its step runs the whole suite, which passed in 35.7 minutes + sharded = workflow(job_timeout=40, steps=self.STEPS[:1]).replace( + " timeout-minutes: 40\n", " timeout-minutes: 40\n strategy:\n matrix:\n shard: [1, 2]\n") + self.record("Unit tests", 2142.5) + rc, out = self.ci(sharded) + self.assertEqual(rc, 0, out) + self.assertEqual(self.limits, {"test -f README.md": 54 * 60}) + self.limits.clear() + self.assertEqual(self.ci(workflow(job_timeout=40, steps=self.STEPS[:1]))[0], 0) # no matrix: the job's own + self.assertEqual(self.limits, {"test -f README.md": 40 * 60}) + def test_a_short_pass_keeps_the_limit_its_longest_pass_set(self): self.record("Unit tests", 2142.5) self.assertEqual(self.ci(workflow(steps=self.STEPS[:1]))[0], 0) # passes in milliseconds this time From 1e235d04573d3d290f760f884f235dba3579d587 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:45:12 -0800 Subject: [PATCH 08/52] fix(progress): give queued steps to free lanes, scope by running steps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Members lost steps queued for them when their lane ended or resumed, kept the files of blocked and closed steps, and a member's ✓ without --step closed nothing while printing ✓. Root cause: intent lived on short-lived lanes (waits_lane, dropped at lane end), scope was a stored lane copy counting blocked steps, and progress.step resolved a member's target only from --step Steps keep an intent that a free lane claims oldest first; a blocked step frees its lane and its answer returns it first; scope derives from running steps; a member's record closes its single running step; the CLI prints ✓ only when a step changed. Existing tests that pinned the replaced behavior are updated, each with a comment. Verified: copy with committed identity: 423 tests in 12 coordination and progress modules OK except the Codex message acknowledgment test, which the caller identity change covers; both model hunts pass my rules --- lib/devkit/cli.py | 10 +- lib/devkit/coord.py | 15 +- lib/devkit/progress.py | 769 ++++++++++++++----------------- tests/test_codex_coord_parity.py | 64 +++ tests/test_coord_kernel.py | 2 +- tests/test_coord_model.py | 91 ++++ tests/test_coord_scenarios.py | 206 +++++++++ 7 files changed, 728 insertions(+), 429 deletions(-) create mode 100644 tests/test_codex_coord_parity.py create mode 100644 tests/test_coord_model.py create mode 100644 tests/test_coord_scenarios.py diff --git a/lib/devkit/cli.py b/lib/devkit/cli.py index 90ca4b11..ffe0a58b 100644 --- a/lib/devkit/cli.py +++ b/lib/devkit/cli.py @@ -2879,13 +2879,21 @@ def cmd_progress(a): if from_agent: lane = (run.get("agents") or {}).get(from_agent) or {} out = run.get("lane_outcome") or {} + changed = out.get("changed") or [] + # ✓ only when the record changed a plan step; ⚠ with the reason when it changed none tail = (f" · closed “{out['step']}” ({out['state']})" if out.get("closed") + else f" · “{out['step']}” is blocked" if out.get("state") == "blocked" and changed else f" · {out['why']}" if out.get("why") else "") + tail += "".join(f" · “{n}” is your step now" for n, old, new in changed + if old == "pending" and new == "running" and n != out.get("step")) + if out.get("closed") and out.get("why"): + tail += f" · {out['why']}" # a step that closed without a verdict is not done: say so, and how to give the verdict unverified = out.get("closed") and out.get("state") != "done" if unverified and not str(check).lstrip().startswith(("✗", "⚠")): tail += " · start --check with ✓ when the evidence passed, ⚠ when partly, ✗ when it failed" - print(f"{ui.WARN if unverified else ui.OK} {lane.get('persona') or lane.get('label') or 'lane'} · " + ok = bool(changed) and not unverified + print(f"{ui.OK if ok else ui.WARN} {lane.get('persona') or lane.get('label') or 'lane'} · " f"{' '.join(a.text)}{tail}") return 0 print(pg.render_update(run)) diff --git a/lib/devkit/coord.py b/lib/devkit/coord.py index d3a2670b..8d0aec75 100644 --- a/lib/devkit/coord.py +++ b/lib/devkit/coord.py @@ -148,13 +148,16 @@ def queued_lanes(step: dict) -> list: def claimable(run: dict, aid: str, launch_named=None, member_wide: bool = True, review=None) -> dict | None: """The step lane `aid` takes now, or None: of the pending steps whose dependencies are done and whose intent names this lane, or its member with no lane (unless `member_wide` is False: a resume whose member has a new - launch on its way leaves those to that launch), and that the lane is free for (busy), the step its launch names + launch on its way leaves those to that launch; nor a lane launched as a follow-up of a finished step, + `follow_up`), and that the lane is free for (busy), the step its launch names (`launch_named`: a step or its name), then a front intent, then a lane-bound one, then a member-wide one, each oldest first, then in plan order.""" lane = ((run or {}).get("agents") or {}).get(aid) if not can_claim(lane): return None + agents = run.get("agents") or {} named = launch_named.get("name") if isinstance(launch_named, dict) else launch_named + member_wide = member_wide and not lane.get("follow_up") # a follow-up of finished work takes no member's step found = [] for i, s in enumerate(run.get("plan") or []): if s.get("state") != "pending": @@ -163,7 +166,10 @@ def claimable(run: dict, aid: str, launch_named=None, member_wide: bool = True, if not it: continue if it["lane"]: - if it["lane"] != aid: + other = agents.get(it["lane"]) or {} + # a step bound to another lane goes to this one only when its launch names it and that lane ended + if it["lane"] != aid and not (named and s.get("name") == named and other.get("state") != "running" + and label_matches(it["member"], lane)): continue elif not member_wide or not label_matches(it["member"], lane): continue @@ -260,8 +266,9 @@ def check(run: dict, now: float, review=None) -> list: builds = [s.get("name") for s in held(run, aid) if not rv(s)] if len(builds) > 1: out.append(f"I-one-step: lane {aid} runs {', '.join(builds)}") - if isinstance(lane, dict) and ("scope" in lane or "handed_over" in lane): - out.append(f"I-scope: lane {aid} keeps a stored scope or hand-over, which no running step gives it") + if isinstance(lane, dict) and plan and ("handed_over" in lane or + ("scope" in lane and sorted(lane["scope"] or []) != scope(run, aid))): + out.append(f"I-scope: lane {aid} keeps a stored scope or hand-over that its running steps do not give") if aid in live: s = claimable(run, aid, review=review) if s is not None: diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 74043c47..286e61d7 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -890,7 +890,9 @@ def caller(cwd: str | None = None, argv=None, now: float | None = None) -> dict: out = {"agent": found.agent, "session": sp.session, "how": found.session_how, "caller": "unknown", "calls": []} if sp.how == "human": return dict(out, caller="human") - if found.agent == "codex": + if getattr(found, "refusal", ""): # identity refuses this call (a failed or missing call token) + return dict(out, caller="unknown", why=found.refusal) + if found.agent == "codex" and sp.how not in ("token", "thread"): return dict(out, caller="unverified") out["calls"] = list(found.calls) if sp.how == "stamped" and sp.lane != "main": @@ -1020,7 +1022,9 @@ def _settle(run: dict): def _save(run: dict, touch_session: bool = True): - """Write the run atomically through state, settled first (_settle). The caller loaded it inside the same _tx.""" + """Write the run atomically through state, settled first (_settle) and in the coordination shape (_coord_shape). + The caller loaded it inside the same _tx.""" + _coord_shape(run) _settle(run) p = run_path(run["agent"], run["session"]) with state.hold(p): @@ -1373,6 +1377,39 @@ def normalize(run: dict) -> dict: return run +def _coord_shape(run: dict): + """The run as the coordination rules read it, written on every save: a pending step's legacy queue entry + (`waits_lane`) becomes its intent, a step that is not pending keeps none, and a lane keeps no hand-over; its + `scope` and `checkout` mirror the steps it runs (lane_scope derives its authority from those steps, not from + the mirror); its `checkout` is that of those steps, which the + edit advice counts the scope from. A run from an older devkit continues with no other change.""" + for s in run.get("plan") or []: + if not isinstance(s, dict): + continue + if s.get("state") == "pending" and "waits_lane" in s: + it = coord.intent(s) + s.pop("waits_lane", None) + if it: + s["intent"] = it + elif s.get("state") != "pending": + coord.drop_intent(s) + for aid, lane in (run.get("agents") or {}).items(): + if not isinstance(lane, dict): + continue + if run.get("plan"): # a run without a plan keeps a lane's scope as given (lane_scope) + held = coord.scope(run, aid) + if held: # a mirror of the steps it runs, for readers of the record; never read for authority + lane["scope"] = held + else: + lane.pop("scope", None) + lane.pop("handed_over", None) + home = _lane_checkout(run, aid) + if home: + lane["checkout"] = home + else: + lane.pop("checkout", None) + + def _default_step_minutes(project) -> float: steps = [r["secs"] / 60 for r in records(60, "step", project) if r.get("secs")] return round(statistics.median(steps), 1) if len(steps) >= 3 else 10.0 @@ -1777,14 +1814,15 @@ def _finish_step(run, s, now, agent, sid): def _advance_main(run, now): """Keep one main step running: the first ready one (its dependencies done) not handed to a subagent. Before that, - each lane that holds no open step takes the step queued for it (_bind_queued).""" - _bind_queued(run, now) + each lane that is free claims what waits for it (_claim_free_lanes).""" + _claim_free_lanes(run, now) plan = run.get("plan") or [] if any(s.get("state") == "running" and (s.get("owner") or "main") == "main" for s in plan): return nxt = next((s for s in ready(run) if (s.get("owner") or "main") == "main" and not s.get("label")), None) if nxt: nxt.update(state="running", started=now) + coord._history(run, nxt, "pending", "running", "main", "the tech lead's next ready step", now) def _main_only(from_agent, what: str, cwd: str | None = None): @@ -1802,6 +1840,8 @@ def _main_only(from_agent, what: str, cwd: str | None = None): _audit("caller.unverified", what, f"{who.get('agent')} session {str(who.get('session'))[:40]}: devkit cannot " f"verify who calls yet", "allowed") return + if who.get("why"): + raise StepError(f"only the tech lead {what}: {who['why']}") here = f"{who.get('agent')}:{who.get('session')}" elsewhere = [f"{a}:{s}" for a, s in _ledger_sessions(sys.argv[1:]) if f"{a}:{s}" != here] _audit("caller.refused", what, f"caller {c}; session found by {who.get('how')}" @@ -1860,10 +1900,10 @@ def _raci_assign(run: dict, s: dict, label: str, why: str, now: float, activity: def assign(which, label: str, cwd: str | None = None, now: float | None = None, scope: str = "", from_agent: str | None = None, why: str = "", activity: str = "") -> dict: - """Hand a plan step to a subagent: the next subagent launched with this description owns it, or a working lane - of that member whose launch names the step and that holds no other step (_launch_takes; never a lane busy with - another step, nor one whose member ended or went stale, working_agents), and its time is that - subagent's time. `scope`: the files it owns (comma-separated globs); the pre-tool hook advises that subagent when + """Hand a plan step to a subagent: the step keeps an intent for the member, or for the one lane its launch + description names, and the first of the member's working lanes that is free takes it, oldest intent first + (_route_to_lane; never a lane busy with another step, nor one whose member ended or went stale, working_agents, + which takes it when it works again); its time is that subagent's time. `scope`: the files it owns (comma-separated globs); the pre-tool hook advises that subagent when it edits outside them, and `dev crew owner` names it as their holder. The crew's RACI must make the member Responsible for the step's kind of work; `why` overrides it, recorded. `activity`: the step's kind of work, an id from dev crew raci, which then decides whatever language the step is written in.""" @@ -1892,19 +1932,21 @@ def assign(which, label: str, cwd: str | None = None, now: float | None = None, if owner == "main": # it was queued for those lanes, whose member was told it would join them _tell_unqueued(run, s, held, label, now) s.update(owner="main", state="pending") # the other member's lane no longer owns it - s.pop("waits_lane", None) # nor takes it when its open step closes + coord.drop_intent(s) # nor takes it when its open step closes s["label"] = label s["assigned_at"] = round(now, 3) # a step assigned after the developer's mid-turn message is their request live = working_agents(run, now, own=True) # one that ended or went stale takes no step and holds no files if globs: - for _, lane in live: - if not _label_matches(label, lane) and _same_checkout(checkout, lane.get("checkout")): - clash = [g for g in globs for h in lane.get("scope") or [] if _globs_overlap(g, h)] + top = checkout or _scope_top(run, cwd) + for aid, lane in live: + held = coord.scope(run, aid) # the files of the steps it runs, never a stored copy + if not _label_matches(label, lane) and _same_checkout(checkout, _lane_checkout(run, aid)): + clash = list(dict.fromkeys(g for g in globs for h in held if _globs_overlap(g, h, top))) if clash: from . import crew raise StepError(f"{', '.join(clash)} overlaps the files " f"{crew.who(lane.get('persona') or lane.get('label'))} owns while working " - f"({', '.join(lane.get('scope'))}). Give each member different files, or " + f"({', '.join(held)}). Give each member different files, or " f"wait until they finish; for members in different worktrees, give each " f"scope as paths in its worktree (/lib/**): scopes of two " f"checkouts do not clash.") @@ -1913,20 +1955,35 @@ def assign(which, label: str, cwd: str | None = None, now: float | None = None, s["checkout"] = checkout else: s.pop("checkout", None) - lane_id = _route_to_lane(run, s, label, live, now) - if lane_id: - if run["agents"][lane_id].get("binding") == "unbound": # Morpheus confirms a lane with no launch record - run["agents"][lane_id]["binding"] = "confirmed" - _audit("crew.confirm", run["agents"][lane_id].get("persona") or label, f"Morpheus assigned " - f"“{s['name']}” to a lane without a launch record", project=run.get("project") or "", - agent_id=lane_id[:16]) - elif s.get("state") == "running" and (s.get("owner") or "main") == "main": - s["state"] = "pending" # waits for its subagent + if s.get("state") == "running" and (s.get("owner") or "main") == "main": + s["state"] = "pending" # the tech lead's own step goes to its member + coord._history(run, s, "running", "pending", "main", f"assigned to {label}", now) + unbound = [k for k, v in live if v.get("binding") == "unbound" and _label_matches(label, v)] + if len(unbound) == 1: # Morpheus confirms the one lane with no launch record his assignment names + run["agents"][unbound[0]]["binding"] = "confirmed" + _audit("crew.confirm", run["agents"][unbound[0]].get("persona") or label, f"Morpheus assigned " + f"“{s['name']}” to a lane without a launch record", project=run.get("project") or "", + agent_id=unbound[0][:16]) + _route_to_lane(run, s, label, live, now) _advance_main(run, now) _save(run) return run +def _scope_top(run: dict, cwd: str | None) -> str: + """The checkout a run's repository-relative scope globs count from (lanescope.scope_base).""" + try: + from . import lanescope + return lanescope.scope_base(run.get("project") or "", cwd or os.getcwd()) + except Exception: + return "" + + +def _lane_checkout(run: dict, aid: str) -> str: + """The checkout the scope of lane `aid` counts in: that of the steps it runs (_scope_checkout), '' for none.""" + return next((x.get("checkout") for x in coord.held(run, aid) if x.get("checkout")), "") + + def _tell_unqueued(run: dict, s: dict, lanes: list, label: str, now: float): """Step `s`, queued for `lanes` (waits_lane), now goes to `label`: each of those lanes that still runs gets a devkit notice naming the step and its new owner, which its next hook and `dev watch --wait` deliver, so its @@ -1943,91 +2000,52 @@ def _tell_unqueued(run: dict, s: dict, lanes: list, label: str, now: float): def _route_to_lane(run: dict, s: dict, label: str, live: list, now: float): - """Step `s`, just assigned to `label` or reopened, goes to its member's live lane (`live`: working_agents) when - devkit can tell which. A lane whose launch names it, or that holds no other open step, takes it now, once its - dependencies are done (its launch's lane first: a member resumed with SendMessage keeps its first launch's - words). With one live lane that cannot take it yet (it works on another step, or the step's dependencies are - open), the step is queued for that lane (`waits_lane`): the same agent takes it once its open step closes - (_bind_queued), and its scope with it; the member is told. With several live lanes that cannot take it yet, it is - queued for all of them, and the first that holds no open step takes it. A closed step goes to no lane: reopening - it gives it back. Morpheus is told why it waits (lane_wait). -> the lane that took it, or None.""" + """Step `s`, just assigned to `label` or reopened, goes to its member by an intent kept on the step + (coord.set_intent): bound to one lane when `label` is the launch description of exactly one of the member's + lanes, live or ended, or when it is reopened for the live lane that held it (its owner on entry); else to the + member, whichever of its lanes claims it first. Then each live lane of the member (`live`: working_agents) that + is free claims (_claim_lane), so the step runs now when one is free and its dependencies are done. Otherwise it + waits in its intent, which outlives the member's lanes: the lane that frees first, a resume, or a new launch that + names it takes it, oldest intent first. A closed step goes to no lane: reopening it gives it back. A blocked step + keeps waiting for its decision. Morpheus and the member are told why it waits. -> the lane that took it, or None.""" from . import crew - previous = s.get("waits_lane") or {} - prior_lane = previous.get("lane") if _exact_intent(run, s, previous.get("lane")) else None - s.pop("waits_lane", None) # assigned again: placed anew, at the end of the lane's queue s["assignment_revision"] = (s.get("assignment_revision") or 0) + 1 - # An ended lane needs an exact assignment, never a role-only revival. Preserve - # its current ownership/intent, or an explicitly named, unique launch label. - matching = {aid: lane for aid, lane in (run.get("agents") or {}).items() - if lane.get("binding") == "exact" and _label_matches(label, lane)} - held = s.get("owner") if s.get("owner") in matching else prior_lane if prior_lane in matching else None - exact = [held] if held else [aid for aid, lane in matching.items() if ":" in label and - label.strip().lower() == (lane.get("label") or "").strip().lower()] - if len(exact) == 1 and run["agents"][exact[0]].get("state") != "running": - s["waits_lane"] = {"lane": exact[0], "ts": now, "session": run.get("session"), - "run_started": run.get("started"), "step": s["name"], - "revision": s["assignment_revision"]} - working = [k for k, v in live if _label_matches(label, v) - and (s.get("owner") == k or _launch_takes(run, k, s) or k in exact)] - if s.get("waits_lane"): - working = [k for k in working if k == s["waits_lane"]["lane"]] - if not working: - if not s.get("waits_lane") and s.get("state") not in DONE + ("unverified",) and \ - not any(_label_matches(label, v) for _, v in live): - hint = _ended_lane_hint(run, s, label, matching) - if hint: - _post(run, "devkit", "main", hint, now, from_name="devkit") - return None + agents = run.get("agents") or {} + lanes = [k for k, v in live if _label_matches(label, v) and (v.get("parent") or "main") == "main"] if s.get("state") in DONE + ("unverified",): - _post(run, "devkit", "main", f"“{s['name']}” is {s.get('state')}, so {crew.who(label)}'s lane does not take " - f"it again: to have them work on it again, reopen it (dev progress reopen \"{s['name']}\" --why \"…\"), " - f"and their lane takes it with its scope", now, from_name="devkit") + coord.drop_intent(s) + if lanes: + _post(run, "devkit", "main", f"“{s['name']}” is {s.get('state')}, so {crew.who(label)}'s lane does not " + f"take it again: to have them work on it again, reopen it (dev progress reopen \"{s['name']}\" " + f"--why \"…\"), and their lane takes it with its scope", now, from_name="devkit") return None - deps = deps_open(run, s) - lane_id = None if deps else next( - (k for k in working if s.get("owner") == k or _launch_takes(run, k, s)), - next((k for k in working if not _open_step_of(run, k, s)), None)) - if lane_id: - _take_step(run, lane_id, s, now) - return lane_id - if len(working) == 1: - aid = working[0] - s["waits_lane"] = {"lane": aid, "ts": round(now, 3)} + owner = s.get("owner") or "main" + if s.get("state") == "blocked": + return None # it waits for its decision; the answer returns it to its lane (coord.unblock) + if s.get("state") == "running" and owner in agents and _label_matches(label, agents[owner]): + coord.drop_intent(s) + return owner # its member's lane works on it already + named = [k for k, v in agents.items() if ":" in label and (v.get("parent") or "main") == "main" + and label.strip().lower() == (v.get("label") or "").strip().lower() and _label_matches(label, v)] + bound = owner if owner in lanes else named[0] if len(named) == 1 else None + coord.set_intent(run, s, coord.member_of(label) or label, bound, now) + for k in ([bound] if bound in lanes else []) + [k for k in lanes if k != bound]: + _claim_lane(run, k, now) + if s.get("state") == "running": + return s.get("owner") + if bound in lanes or (not bound and len(lanes) == 1): + aid = bound if bound in lanes else lanes[0] before = _closes_before(run, aid, s) if before: _post(run, "devkit", aid, f"devkit: the tech lead gave you “{s['name']}”: it joins your lane once " f"{_quoted_and(before)} close{'s' if len(before) == 1 else ''} (dev progress step \"…\" --step " f"\"{before[0]}\" --check \"…\"), and its files become your scope then", now, from_name="devkit", kind="notice") - else: # the member works in several lanes: the first of them that holds no open step takes it (_bind_queued) - s["waits_lane"] = {"lanes": list(working), "ts": round(now, 3)} - if not deps: + if lanes and not deps_open(run, s): _post(run, "devkit", "main", lane_wait(run, s, live), now, from_name="devkit") return None -def _ended_lane_hint(run: dict, s: dict, label: str, lanes: dict, lane_id: str = "") -> str: - """What the tech lead is told when step `s`, assigned to `label`, goes to none of its member's lanes since they - ended (`lanes`: the member's lanes bound to a launch): a lane that ended takes a step only from an assignment that - names it by its launch description, never from its role (a role's step may be meant for a new launch), so a - member resumed with SendMessage would work without it and read only. -> the line naming the assignment for each - lane its description names alone ('' when none does); `lane_id`: that lane only, which resumed without a step.""" - from . import crew - ended = {k: v for k, v in lanes.items() if v.get("state") != "running" or k == lane_id} - labels = [v.get("label") for k, v in ended.items() if v.get("label") and (not lane_id or k == lane_id) - and sum(1 for x in lanes.values() if (x.get("label") or "").strip().lower() - == v["label"].strip().lower()) == 1] - if not labels: - return "" - who, name = crew.who(label), s["name"] - lines = " · ".join(f'dev progress assign "{name}" --to "{lab}"' for lab in labels) - if lane_id: # the line first: a long notice reaches the tech lead as a preview of its start - return (f"{lines}: gives “{name}” to {who}, who works again with no step of its own and may read but not " - f"write until then (a lane that ended takes no step assigned by role)") - return (f"{lines}: gives “{name}” to {who}'s lane that ended, for a resume with SendMessage; a lane that ended " - f"takes no step assigned by role, so “{name}” waits for a new launch") - - def _quoted_and(names: list) -> str: """'“a”', '“a” and “b”', '“a”, “b” and “c”'.""" q = [f"“{n}”" for n in names] @@ -2035,28 +2053,35 @@ def _quoted_and(names: list) -> str: def _queued_lanes(s: dict) -> list: - """The lanes step `s` is queued for (waits_lane): its member's one lane, or each of the member's lanes when it - works in several, where the first of them that holds no open step takes it.""" - w = s.get("waits_lane") - if not isinstance(w, dict): - return [] - return [str(x) for x in (w.get("lanes") or [w.get("lane")]) if x] + """The lanes pending step `s` is bound to by its intent (coord.queued_lanes): one lane, or [] when it goes to + whichever lane of its member claims it first. The one reader of a step's queue, for runs written before intents + too (their `waits_lane`).""" + return coord.queued_lanes(s) def _exact_intent(run, s, aid): - """A supported assignment in this run still names this exact lane and revision.""" - w = s.get("waits_lane") or {} - return bool(w.get("revision") and w.get("revision") == s.get("assignment_revision") and - w.get("lane") == aid and w.get("session") == run.get("session") and - w.get("run_started") == run.get("started") and w.get("step") == s.get("name") and + """Pending step `s` is bound to lane `aid` by its intent, and its label still names that lane's member.""" + it = coord.intent(s) if s.get("state") == "pending" else None + return bool(it and it.get("lane") == aid and _label_matches(s.get("label") or "", (run.get("agents") or {}).get(aid) or {})) def _queued_for(run: dict, aid: str) -> list: - """The steps queued for lane `aid` (waits_lane), in the order they were assigned.""" - marks = [(((x.get("waits_lane") or {}).get("ts") or 0), i, x) for i, x in enumerate(run.get("plan") or []) - if aid in _queued_lanes(x)] - return [x for _, _, x in sorted(marks, key=lambda t: t[:2])] + """The pending steps whose intent may go to lane `aid` (bound to it, or to its member), in the order it claims + them (coord.claimable): answered blocked steps first, then those bound to it, then its member's, oldest first.""" + lane = (run.get("agents") or {}).get(aid) or {} + marks = [] + for i, x in enumerate(run.get("plan") or []): + it = coord.intent(x) if x.get("state") == "pending" else None + if not it: + continue + other = (run.get("agents") or {}).get(it["lane"]) or {} if it["lane"] else {} + if it["lane"] == aid or (it["lane"] and other.get("state") != "running" and _label_matches(it["member"], lane) + and (lane.get("parent") or "main") == "main") \ + or (not it["lane"] and _label_matches(it["member"], lane) + and (lane.get("parent") or "main") == "main" and not lane.get("follow_up")): + marks.append((0 if it["front"] else 1 if it["lane"] else 2, it["ts"] or 0, i, x)) + return [x for *_, x in sorted(marks, key=lambda t: t[:3])] def _closes_before(run: dict, aid: str, s: dict) -> list: @@ -2070,103 +2095,94 @@ def _closes_before(run: dict, aid: str, s: dict) -> list: def lane_wait(run: dict, s: dict, live: list) -> str: """Why step `s`, whose member works (`live`: working_agents), waits for that member, and what to do: the one - advice `dev progress assign` and `dev progress reopen` post and `dev crew next` gives (dispatch._sorted). Queued - for one of the member's lanes: it joins that lane once the steps before it close, and the member's own - `dev progress step --step` closes it. One lane, not queued: assigning it again queues it there. Several lanes: - queued for all of them, the first that frees takes it, and assigning it with one lane's launch description gives - it to that lane. '' when its member does not work.""" + advice `dev progress assign` and `dev progress reopen` post and `dev crew next` gives (dispatch._sorted). Its + intent goes to the member's lane that frees first (or the one lane it is bound to), once the steps before it + close, and the member's own `dev progress step --step` closes it. '' when its member does not work.""" from . import crew label = s.get("label") or "" lanes = [k for k, v in live if _label_matches(label, v)] if not lanes: return "" who, name = crew.who(label), s["name"] - queued_for = _queued_lanes(s) - queued = next((k for k in lanes if k in queued_for), None) if len(queued_for) == 1 else None - aid = queued or (lanes[0] if len(lanes) == 1 else None) - if not aid: - agents = run.get("agents") or {} + bound = next((k for k in lanes if k in _queued_lanes(s)), None) + if not bound and len(lanes) > 1: busy = [x["name"] for x in (_open_step_of(run, k, s) for k in lanes) if x] + agents = run.get("agents") or {} labels = [lab for lab in (agents[k].get("label") or "" for k in lanes) if lab and sum(1 for _, v in live if _label_matches(lab, v)) == 1] one = ("; to give it to one of them, assign it with that lane's launch description: " + " · ".join(f'dev progress assign "{name}" --to "{lab}"' for lab in labels)) if labels else "" - if any(k in queued_for for k in lanes): - return (f"{who} works in {len(lanes)} lanes: “{name}” joins the first of them whose step closes" - + (f" ({_quoted_and(busy)})" if busy else "") + one) - return (f"{who} works in {len(lanes)} lanes: dev progress assign \"{name}\" --to \"{label}\" queues “{name}” " - f"for the first of them whose step closes" + one) + return (f"{who} works in {len(lanes)} lanes: “{name}” joins the first of them whose step closes" + + (f" ({_quoted_and(busy)})" if busy else "") + one) + aid = bound or lanes[0] cur = _open_step_of(run, aid, s) head = f"{who} works on “{cur['name']}”" if cur else f"{who} works with no step" - if queued: - before = _closes_before(run, aid, s) - when = f"once {_quoted_and(before)} close{'s' if len(before) == 1 else ''}" if before else "now" - return (f"{head}: “{name}” joins that lane {when}; send it to them (SendMessage / send_input), and their " - f"dev progress step --step \"{name}\" closes it") - if cur: - return (f"{head}: dev progress assign \"{name}\" --to \"{label}\" queues “{name}” for that lane, which " - f"takes it once “{cur['name']}” closes; otherwise it waits for a launch of its own once they finish") - return f"{head}: dev progress assign \"{name}\" --to \"{label}\" gives “{name}” to that lane" - - -def _bind_queued(run: dict, now: float): - """Each live lane with steps queued for it (waits_lane) that holds no open step takes the first of them whose - dependencies are done, as a launch takes its step (_take_step: the step's scope becomes the lane's), and its - member is told. The step joined the lane (`joined`): only the lane's own evidence for it closes it - (_steps_about). A queue entry goes when its step is no longer the tech lead's to give, or its lane ended or - began again since (a resumed member asks anew); that step waits for a launch of its own.""" + before = _closes_before(run, aid, s) + when = f"once {_quoted_and(before)} close{'s' if len(before) == 1 else ''}" if before else "now" + return (f"{head}: “{name}” joins that lane {when}; send it to them (SendMessage / send_input), and their " + f"dev progress step --step \"{name}\" closes it") + + +def _launch_named(run: dict, aid: str, lane: dict): + """The step of its member that lane `aid`'s launch description names best, alone (as _bind_step scores it), + among the pending steps that may go to it; None when it names none of them, or two equally.""" + task = _task_text(lane.get("label") or "") + scored = [(_name_score(task, x["name"]), x["name"]) for x in _queued_for(run, aid)] + if not scored: + return None + best = max(sc for sc, _ in scored) + top = [n for sc, n in scored if sc == best] + return top[0] if best[1] and len(top) == 1 else None + + +def _claim_lane(run: dict, aid: str, now: float, member_wide: bool = True) -> list: + """Lane `aid`, when it is free, takes the steps the claim rule gives it (coord.claim): the one its launch names, + else the oldest intent for it; a reviewer's lane goes on taking ready reviews, since reviews share a lane. Each + step is recorded in the lane, and its member is told when its launch did not name it. `member_wide` False: a + resume whose member has a new launch on its way leaves the member's steps to that launch. -> the steps taken""" from . import crew - agents, lanes = run.get("agents") or {}, [] - for s in run.get("plan") or []: - w = s.get("waits_lane") - if w is None: - continue - w = w if isinstance(w, dict) else {} - mine = s.get("state") == "pending" and (s.get("owner") or "main") == "main" - if w.get("revision"): - aid = w.get("lane") - if not _exact_intent(run, s, aid) or s.get("state") not in DONE + ("unverified",) and \ - (s.get("owner") or "main") not in ("main", aid): - s.pop("waits_lane") - # Exact intent survives completion/reopen and admission waits. Only - # this child's own hook can consume it, after checking its slot. - continue + lane = (run.get("agents") or {}).get(aid) + taken = [] + while coord.can_claim(lane) and len(taken) < 20: + named = _launch_named(run, aid, lane) + s = coord.claimable(run, aid, named, member_wide, review=is_review_step) + if s is None: + break + who = crew.who(lane.get("persona") or s.get("label") or "") + why = (f"{who}'s launch names it" if s["name"] == named else f"{who} holds no other step now: it took this " + f"step, the oldest waiting for it") + coord.claim(run, aid, now, why, named, member_wide, review=is_review_step) + _remember_step(lane, s) + lane.pop("handed_over", None) + _audit("crew.claim", s["name"], why, project=run.get("project") or "", agent_id=aid[:16]) + if s["name"] == named: + s.pop("joined", None) + else: + s["joined"] = aid # its launch does not name it: only the lane's own evidence closes it (_steps_about) + rest = [x["name"] for x in _queued_for(run, aid)] + scope = f" (your scope: {', '.join(s['scope'])})" if s.get("scope") else "" + _post(run, "devkit", aid, f"devkit: “{s['name']}” is your step now{scope}: close it with dev progress " + f"step \"…\" --step \"{s['name']}\" --check \"…\"" + (f"; then “{rest[0]}” joins your lane" if rest + else ""), now, from_name="devkit", + kind="notice") + taken.append(s) + return taken - def live(aid): - lane = agents.get(aid) or {} - life = lane.get("resumed_at") or lane.get("started") or 0 - return lane.get("state") == "running" and (w.get("ts") or 0) >= life and \ - _label_matches(s.get("label") or "", lane) - queued = _queued_lanes(s) - valid = [aid for aid in queued if live(aid)] if mine else [] - if not valid: - s.pop("waits_lane") - if mine: - gone = agents.get(queued[0]) or {} if queued else {} - _log_change(run, s, "pending", "pending", "devkit", f"{crew.who(gone.get('persona') or s.get('label'))}" - f"'s lane{'s' if len(queued) > 1 else ''} ended before {'one' if len(queued) > 1 else 'it'} " - f"took this step: it waits for a launch of its own", now) - continue - if w.get("lanes"): - w["lanes"] = valid # the member's lanes that ended or began again since leave the queue - lanes += [aid for aid in valid if aid not in lanes] - for aid in lanes: - lane = agents[aid] - if lane.get("over_limit") or lane.get("waits_slot"): + +def _claim_free_lanes(run: dict, now: float): + """Every lane that can take a step claims what waits for it (_claim_lane), oldest lane first: after any change + that frees a lane, readies a step or gives one an intent. A lane the record lists as running whose member ended + or went stale (lane_states, read only when some lane has a step to claim) takes nothing.""" + agents = run.get("agents") or {} + states = None + for aid in sorted(agents, key=lambda k: (agents[k].get("started") or 0, k)): + if not coord.can_claim(agents[aid]) or coord.claimable(run, aid, review=is_review_step) is None: continue - nxt = next((x for x in _queued_for(run, aid) if not deps_open(run, x)), None) - if not nxt or _open_step_of(run, aid, nxt): # a review joins a lane that holds reviews only + if states is None: + states = lane_states(run, now, own=True) + if (states.get(aid) or {}).get("state", "working") != "working": continue - _take_step(run, aid, nxt, now) - nxt["joined"] = aid # its launch does not name it - who = crew.who(lane.get("persona") or nxt.get("label") or "") - _log_change(run, nxt, "pending", "running", "devkit", f"{who} holds no other step now: it joined that lane", - now) - rest = [x["name"] for x in _queued_for(run, aid)] - scope = f" (your scope: {', '.join(nxt['scope'])})" if nxt.get("scope") else "" - _post(run, "devkit", aid, f"devkit: “{nxt['name']}” is your step now{scope}: close it with dev progress step " - f"\"…\" --step \"{nxt['name']}\" --check \"…\"" + (f"; then “{rest[0]}” joins your lane" if rest else ""), - now, from_name="devkit", kind="notice") + _claim_lane(run, aid, now) def _background_running(agent: str, sid: str, aid: str) -> list: @@ -2208,7 +2224,7 @@ def _member_close_refused(run: dict, st: dict, aid: str, check: str, running=()) return (f"“{name}” stays {st.get('state')}: a step closes on its evidence, so run this again with --check " f"\"✓ \" (dev progress note \"…\" --step \"{name}\" keeps partial evidence and " f"leaves it open); devkit recorded nothing") - if aid in _queued_lanes(st): + if st.get("state") == "pending" and any(st is x for x in _queued_for(run, aid)): before = _closes_before(run, aid, st) if before: return (f"“{name}” joins your lane once {_quoted_and(before)} close{'s' if len(before) == 1 else ''}, so it " @@ -2223,46 +2239,21 @@ def _member_close_refused(run: dict, st: dict, aid: str, check: str, running=()) def _open_step_of(run: dict, aid: str, s: dict | None = None): - """The step lane `aid` still works on other than `s` (not done, skipped or unverified: a step that ended - unverified waits for the tech lead's evidence, not for the member), or None: a lane works one step at a time. - Reviews are the exception: a review step closes only with its reviewer's report (_member_close), so for a review - `s` the lane's open reviews do not count, and one report ends them all (_end_lane_steps).""" - from . import approvals - review = s is not None and approvals.is_review(s) - return next((x for x in run.get("plan") or [] if x is not s and x.get("owner") == aid - and x.get("state") not in DONE + ("unverified",) and not (review and approvals.is_review(x))), None) + """The step lane `aid` holds (runs) that keeps it from taking `s`, or None (coord.busy): a lane works one step + at a time, and a blocked or unverified step does not hold it. Reviews are the exception: for a review `s` the + lane's running reviews do not count, and one report ends them all (_end_lane_steps).""" + review = s is not None and is_review_step(s) + return next((x for x in coord.held(run, aid) if x is not s and not (review and is_review_step(x))), None) def _take_step(run: dict, aid: str, s: dict, now: float): - """Lane `aid` takes step `s`: it owns it and runs it, its scope becomes the step's, and its member's step closes - reach the plan.""" + """Lane `aid` takes step `s`: it owns it and runs it, its scope is the step's while it runs (lane_scope), and its + member's step closes reach the plan.""" s.update(owner=aid, state="running", started=s.get("started") or now) - s.pop("waits_lane", None) + coord.drop_intent(s) lane = run["agents"][aid] _remember_step(lane, s) - lane.pop("handed_over", None) # Morpheus gives it a step of its own - if s.get("scope"): - lane["scope"] = s["scope"] - if s.get("checkout"): # the checkout its scope counts in (_scope_checkout) - lane["checkout"] = s["checkout"] - else: - lane.pop("checkout", None) - _hand_scope(run, s, aid, now) - - -def _tell_role_steps(run: dict, aid: str, lane: dict, now: float): - """Lane `aid` resumed with no step of its own: each step assigned to its member by role that waits for a launch - (pending with the tech lead, its dependencies done, queued for no lane) is one it does not take, and the tech - lead is told the line that gives it to this lane (_ended_lane_hint).""" - lanes = {k: v for k, v in (run.get("agents") or {}).items() - if v.get("binding") == "exact" and _label_matches(lane.get("label") or "", v)} - for s in run.get("plan") or []: - if s.get("state") == "pending" and (s.get("owner") or "main") == "main" and s.get("label") \ - and ":" not in s["label"] and _label_matches(s["label"], lane) and not s.get("waits_lane") \ - and not deps_open(run, s): - hint = _ended_lane_hint(run, s, s["label"], lanes, lane_id=aid) - if hint: - _post(run, "devkit", "main", hint, now, from_name="devkit") + lane.pop("handed_over", None) def _remember_step(lane: dict, step: dict): @@ -2272,49 +2263,6 @@ def _remember_step(lane: dict, step: dict): held.append(step["name"]) -def _take_waiting_step(run: dict, aid: str, now: float, sess=None): - """A member resumed (SendMessage) that holds no open step takes the one step assigned to it that waits for a - launch (pending on the tech lead, its dependencies done), as a new launch would; with two or more waiting it - takes none, and the tech lead's `dev progress assign` picks. Never another member's step, and none while a new - launch of its own member is on its way (that launch takes the step). `sess`: the session record, for its - launches. -> the step taken, or None.""" - lane = (run.get("agents") or {}).get(aid) or {} - if not lane.get("persona") and not lane.get("label") or _open_step_of(run, aid): - return None - me = (lane.get("persona") or "").lower() - if me and any(r.get("state") == "pending" and not r.get("agent_id") and now - (r.get("ts") or now) < LAUNCH_TTL - and (persona(r.get("type") or "", r.get("label") or "") or "").lower() == me - for r in ((sess or {}).get("launches") or {}).values() if isinstance(r, dict)): - return None - waiting = [x for x in run.get("plan") or [] if (x.get("owner") or "main") == "main" and x.get("state") == "pending" - and x.get("label") and _label_matches(x["label"], lane) and not deps_open(run, x) - and (_exact_intent(run, x, aid) or not (x.get("waits_lane") or {}).get("revision") and - x["name"] in lane.get("assigned_steps", [])) - and (not _queued_lanes(x) or aid in _queued_lanes(x))] # never a step queued for another lane - if len(waiting) != 1: - return None - s = waiting[0] - _take_step(run, aid, s, now) - _log_change(run, s, "pending", "running", "main", "its member was resumed and holds no other step", now) - return s - - -def _launch_takes(run: dict, aid: str, s: dict) -> bool: - """May this working lane take step `s` when Morpheus assigns it? Only when its launch names the - step, the way _bind_step reads a launch: the lane holds no other open step (one step per launch), and its - description's task text names some of the step's words and none of its member's other waiting steps better. A - step assigned while its member works on another one waits for a launch of its own.""" - lane = (run.get("agents") or {}).get(aid) or {} - plan = run.get("plan") or [] - if any(x is not s and x.get("owner") == aid and x.get("state") not in DONE for x in plan): - return False - text = _task_text(lane.get("label") or "") - mine = _name_score(text, s["name"]) - rivals = [x for x in plan if x is not s and x.get("state") not in DONE and x.get("label") - and (x.get("owner") or "main") == "main" and _label_matches(x["label"], lane)] - return bool(mine[1]) and all(mine >= _name_score(text, x["name"]) for x in rivals) - - def _checkouts(base: str) -> list: """The real paths of every checkout of the repository at `base` (its main checkout and its worktrees) that is still there, deepest first, so a worktree inside the main checkout wins over it. git lists a worktree whose @@ -2761,10 +2709,7 @@ def top(run): # a scope given in one checkout (_scope_checkout) counts there, else in the checkout its session works in if lanescope.scope_owner_across(ap, runs=[dict(run, agents={aid: lane})], me_session=sid, checkout_of=lambda r, lane=lane: lane.get("checkout") or top(r)): - globs = set(lane.get("scope") or []) | {g for s in run.get("plan") or [] if isinstance(s, dict) - and s.get("owner") == aid and s.get("state") not in DONE - for g in s.get("scope") or []} - out.append(_holder(run, aid, lane, globs, facts, now, alive, own=False)) + out.append(_holder(run, aid, lane, coord.scope(run, aid), facts, now, alive, own=False)) if isinstance(mine, dict) and mine.get("state") != "done": run = normalize(mine) expire_stale(run, now) @@ -2773,9 +2718,10 @@ def top(run): if aid == me or not isinstance(lane, dict) or lane.get("state") != "running": continue # a scope given in one checkout counts there: the same relative files of another checkout are not its - here = lanescope.scope_rel(path, cwd, lane["checkout"]) if lane.get("checkout") else rel - if _in_globs(here, lane.get("scope") or []): - out.append(_holder(run, aid, lane, lane.get("scope") or [], facts, now, alive, own=True)) + home = _lane_checkout(run, aid) + here = lanescope.scope_rel(path, cwd, home) if home else rel + if _in_globs(here, coord.scope(run, aid)): + out.append(_holder(run, aid, lane, coord.scope(run, aid), facts, now, alive, own=True)) return out @@ -3906,12 +3852,15 @@ def crew_decision(question: str, options=None, recommend: str = "", from_agent: lane = (run.get("agents") or {}).get(from_agent) if lane: lane["waiting"] = d["id"] - for s in run.get("plan") or []: - if s.get("owner") == from_agent and s.get("state") == "running": - _log_change(run, s, "running", "blocked", from_agent, f"waiting for the developer: {d['id']}", now) - s["state"], s["waiting"] = "blocked", d["id"] - # as asked: deciding unblocks them, and devkit's context line still names them - d.setdefault("blocks", []).append(s["name"]) + for s in coord.held(run, from_agent): + if is_review_step(s) and any(not is_review_step(x) for x in coord.held(run, from_agent)): + continue # the lane's build step waits; its reviews close with its report + _audit("plan.blocked", s["name"], f"waiting for the developer: {d['id']}", + project=run.get("project") or "", by=_name_of(run, from_agent)) + coord.block(run, s, d["id"], now, f"waiting for the developer: {d['id']}", by=from_agent) + # as asked: deciding unblocks them, and devkit's context line still names them + d.setdefault("blocks", []).append(s["name"]) + _claim_free_lanes(run, now) # the blocked step frees its lane for the member's next step if auto and d.get("approves"): d["note"] = (f"auto mode, but it approves {', '.join(f'“{s}”' for s in d['approves'])}: only the " f"developer's answer approves steps, so it waits for the developer") @@ -3997,40 +3946,43 @@ def _own_decision_id(decision_id: str, agent: str, sid: str, verb: str) -> str: def _release(run, d: dict, why: str, now: float) -> list: - """The steps blocked on decision `d`, once it is decided or withdrawn (`why` says which): each runs again while - its member works, and waits for a new launch (pending, back with Morpheus, its scope kept, announced ready) when - its member ended or went stale, as `dev crew owner` reads it (lane_gone over lane_states of the caller's own run; - a lane the run does not know counts as working). A lane never runs again because of an answer (its wait never - changed its state); a step that moved on meanwhile stays as it is. -> the steps sent back for a new launch""" + """The steps blocked on decision `d`, once it is decided or withdrawn (`why` says which), go back by + coord.unblock: each runs again in its lane while its member works there and the lane is free; it waits first in + that lane's intents while the lane works on another step; and first in its member's intents, for that member's + next lane, when its member ended or went stale, as `dev crew owner` reads it (lane_gone over lane_states of the + caller's own run; a lane the run does not know counts as working). A lane never runs again because of an answer + (its wait never changed its state); a step that moved on meanwhile stays as it is. Then every free lane claims. + -> the steps that wait for a lane""" from . import crew agents, states, back = run.get("agents") or {}, None, [] for s in run.get("plan") or []: if s.get("waiting") != d["id"]: continue - s.pop("waiting", None) if s.get("state") != "blocked": + s.pop("waiting", None) continue owner = s.get("owner") or "main" lane = agents.get(owner) if states is None and isinstance(lane, dict) and lane.get("state") == "running": states = lane_states(run, now, own=True) g = lane_gone(owner, lane, states or {}) if owner != "main" else None - if g: - _log_change(run, s, "blocked", "pending", "main", f"{why}; its owner {crew.who(_lane_name(lane))} had " - f"{'gone stale' if g[0] == 'stale' else 'ended'}: {g[1]}, so the step waits for a new launch", - now) - # its lane takes it back once its member works again, after now (approvals._worked_since): resumed - # with the answer, or a stale lane seen again; never a member that only ended within finish_grace - s.update(state="pending", owner="main", lost_from=owner, lost_at=now) + text = why if not g else (f"{why}; its owner {crew.who(_lane_name(lane))} had " + f"{'gone stale' if g[0] == 'stale' else 'ended'}: {g[1]}") + if coord.unblock(run, s, not g, now, text, review=is_review_step) == "pending": back.append(s) - else: - _log_change(run, s, "blocked", "running", "main", why, now) - s["state"] = "running" + if g: # its lane takes it back once its member works again, after now (approvals._worked_since) + s.update(lost_from=owner, lost_at=now) + if not g: + _post(run, "devkit", owner, f"devkit: {d['id']} is answered, so “{s['name']}” comes back to you: it " + f"joins your lane first once {_quoted_and([x['name'] for x in coord.held(run, owner)][:1])} " + f"closes", now, from_name="devkit", kind="notice") + _audit(f"plan.{s['state']}", s["name"], text[:300], project=run.get("project") or "", by="main") for lane in agents.values(): if lane.get("waiting") == d["id"]: lane.pop("waiting", None) lane.pop("state_before_wait", None) # kept by runs saved before an answer stopped reviving lanes - return back + _claim_free_lanes(run, now) + return [x for x in back if x.get("state") == "pending"] def _unblock(run, d: dict, now: float) -> list: @@ -4554,7 +4506,10 @@ def begin(which, cwd: str | None = None, now: float | None = None, from_agent: s raise StepError(f"step “{s['name']}” waits for {', '.join(waiting)}, not done yet: it starts when " f"{'that is' if len(waiting) == 1 else 'they are'} done. If the order really changed, " f"skip what it waits for: dev progress skip \"{waiting[0]}\" --why \"…\"") + old = s.get("state") s.update(state="running", started=s.get("started") or now) + if old != "running": + _log_change(run, s, old, "running", "main", "the tech lead began it (dev progress begin)", now) run["begun"] = s["name"] _save(run) return run @@ -5024,7 +4979,7 @@ def step(text: str, nxt: str = "", cwd: str | None = None, kind: str = "step", c from_agent_lane = bool(from_agent) # read before the lock: the member's transcript can be long running = _background_running(agent, sid, from_agent) if from_agent_lane and kind == "step" and \ - which not in (None, "") and str(check or "").strip() else [] + str(check or "").strip() else [] with _tx(agent, sid): run = load_run(agent, sid) if from_agent_lane: # a subagent's update: its lane only @@ -5033,8 +4988,16 @@ def step(text: str, nxt: str = "", cwd: str | None = None, kind: str = "step", c if which not in (None, "") and not named: raise StepError(f"no step “{which}” in the plan: " + "; ".join( f"{i}. {s['name']}" for i, s in enumerate(run.get("plan") or [], 1))) - refused = _member_close_refused(run, named, from_agent, check, running) if kind == "step" and named \ - else "" + before = coord.states(run) + implicit = named is None and kind in ("step", "blocked") + if implicit: # the step its lane runs, as the tech lead's record without --step closes his own + builds = [x for x in coord.held(run, from_agent) if not is_review_step(x)] + if len(builds) > 1: + raise StepError("your lane runs several steps (" + ", ".join(x["name"] for x in builds) + + "): say which with --step; devkit recorded nothing") + named = builds[0] if builds else None + refused = _member_close_refused(run, named, from_agent, check, running) \ + if kind == "step" and named and (not implicit or str(check or "").strip()) else "" if refused: raise StepError(refused) lane = _lane(run, from_agent, now) @@ -5056,12 +5019,28 @@ def step(text: str, nxt: str = "", cwd: str | None = None, kind: str = "step", c run["updates"] = run["updates"][-40:] outcome = _member_close(run, named, lane, from_agent, u, now, agent, sid) if kind == "step" and named \ else None + if kind == "blocked" and named: + if named.get("owner") == from_agent and named.get("state") == "running": + coord.block(run, named, "", now, text, by=from_agent) + _audit("plan.blocked", named["name"], text[:300], project=run.get("project") or "", + by=_name_of(run, from_agent)) + _claim_free_lanes(run, now) # the blocked step frees its lane for the member's next step + outcome = {"step": named["name"], "state": "blocked", "closed": False, "why": ""} + else: + outcome = {"step": named["name"], "state": named.get("state"), "closed": False, + "why": f"“{named['name']}” is not a step your lane runs, so devkit blocked nothing"} + if outcome is None and kind in ("step", "blocked"): + outcome = {"step": "", "state": "", "closed": False, + "why": "recorded in your lane; it closes no step, since your lane runs none"} if held: # the command's line says why nothing is approved yet outcome = dict(outcome or {"step": "", "state": "", "closed": False}, why="; ".join(x for x in ((outcome or {}).get("why"), held) if x)) + run["step"] = sum(1 for x in run.get("plan") or [] if x.get("state") in DONE) _save(run) if outcome: - run["lane_outcome"] = outcome # for the command's own line; never saved + # for the command's own line; never saved: the steps whose state this record changed, and the + # verdict it leaves for the crew gates + run["lane_outcome"] = dict(outcome, changed=coord.changes(before, run), held=bool(held)) return run run = normalize(run or {}) plan = run["plan"] @@ -5103,9 +5082,10 @@ def step(text: str, nxt: str = "", cwd: str | None = None, kind: str = "step", c run["state"] = "blocked" cur = target or next((s for s in plan if s.get("state") == "running"), None) if cur: - _log_change(run, cur, cur.get("state"), "blocked", "main", text, now) - cur["state"] = "blocked" + _audit("plan.blocked", cur["name"], text[:300], project=run.get("project") or "", by="morpheus") + coord.block(run, cur, "", now, text) run["blocked_on"] = cur["name"] # the run runs again once this step moves (_settle) + _claim_free_lanes(run, now) # a member's blocked step frees its lane for its next step elif kind == "done": waiting = pending_decisions(run) if waiting and not force: @@ -5572,9 +5552,6 @@ def lane_stopped(task_or_agent_id: str, reason: str, agent: str | None = None, s continue held = [st for st in run.get("plan") or [] if st.get("owner") == aid and st.get("state") not in DONE] here = approvals.apply(run, approvals.stop_moves(run, aid, why, at=now, now=now), now) - for st in held: # a live lane of its member took the step: its scope goes with it - if st.get("owner") not in (aid, "main", None): - _hand_scope(run, st, st["owner"], now) if here: _save(run, touch_session=False) if here: @@ -5940,50 +5917,29 @@ def _name_score(text: str, name: str) -> tuple: def _bind_step(run: dict, aid: str, lane: dict, now: float): - """Give a newly bound lane the plan step its launch names: of the steps assigned to its member that - the dependency engine finds ready, the one whose name the launch's task text names best ("Neo: session graph" - → "session graph command"). Never the member's first step by default: when the text names none of its steps, - or two equally, they stay with Morpheus and he is told how to link one.""" + """Give a newly bound lane its step. Its launch's task text is scored against all its member's steps, done ones + included ("Neo: session graph" → "session graph command"): a launch that names a done or skipped step best is a + follow-up of finished work (`follow_up`), left as it is, and takes no step its member was given by role; one that + names a step its member's ended lane left unverified looks at it again; otherwise the lane claims (_claim_lane): + the step it names first, else the oldest step waiting for its member. A named step whose dependencies are open + waits, and Morpheus is told.""" plan = run.get("plan") or [] - if any(st.get("owner") == aid and st.get("state") not in DONE for st in plan): - return # one step at a time lanes = run.get("agents") or {} - mine = [st for st in plan if st.get("label") and st.get("state") not in DONE - and (st.get("owner") or "main") == "main" and _label_matches(st["label"], lane)] - # a step its member's ended lane left unverified: a new launch of that member that names it looks at it again - mine += [st for st in plan if st.get("state") == "unverified" and st.get("label") and st.get("owner") != aid - and (lanes.get(st.get("owner")) or {}).get("state") in ENDED_LANE + ("unverified",) - and _label_matches(st["label"], lane)] - if not mine: - return + mine = [st for st in plan if st.get("label") and _label_matches(st["label"], lane) and ( + st.get("state") in DONE or (st.get("state") == "pending" and (st.get("owner") or "main") == "main") + or st.get("state") == "unverified" and st.get("owner") != aid + and (lanes.get(st.get("owner")) or {}).get("state") in ENDED_LANE + ("unverified",))] from . import crew who, label = crew.who(lane.get("persona") or lane.get("label") or "a subagent"), lane.get("label") or "" scored = [(_name_score(_task_text(label), st["name"]), st) for st in mine] - best = max(sc for sc, _ in scored) - top = [st for sc, st in scored if sc == best] - from . import approvals - if best[1] and len(top) > 1 and all(approvals.is_review(st) for st in top): - # one reviewer's launch for several reviews: each closes with its report, so the lane holds them together; - # one whose work is not finished yet joins once it is (_bind_queued) - rd = ready(run) - for st in top: - if any(x is st for x in rd): - _take_step(run, aid, st, now) - else: - st["waits_lane"] = {"lane": aid, "ts": round(now, 3)} - return - if not best[1] or len(top) > 1: - names = ", ".join(f"“{st['name']}”" for st in (top if best[1] else mine)) - what = f"names {names} equally" if best[1] else f"names none of {crew.who(mine[0]['label'])}'s steps ({names})" - how = (f"If this launch does one of them, link it: dev progress assign \"\" --to \"{mine[0]['label']}\"" - if best[1] else "Each waits for a launch whose description names it (dev progress assign links a " - "step only to such a launch, B-fy9639hfz5t)") - _post(run, "devkit", "main", f"{who} started as “{label}”, which {what}: the steps stay with you. {how}", - now, from_name="devkit") + best = max((sc for sc, _ in scored), default=(False, 0, 0.0)) + top = [st for sc, st in scored if best[1] and sc == best] + st = top[0] if len(top) == 1 else None + if st is not None and st.get("state") in DONE: + lane["follow_up"] = st["name"] # a follow-up of finished work (B-igm9ittsioat): it binds no step return - st = top[0] - if st.get("state") == "unverified": - if deps_open(run, st): + if st is not None and st.get("state") == "unverified": + if deps_open(run, st) or coord.busy(run, aid, st, review=is_review_step): return # a dependency was reopened since: dev progress reopen gives it back once that is done st.pop("recheck", None) # it is redone now st["reopened"] = (st.get("reopened") or 0) + 1 @@ -5991,45 +5947,22 @@ def _bind_step(run: dict, aid: str, lane: dict, now: float): _log_change(run, st, "unverified", "running", aid, f"a new launch of {who}, “{label}”, names it: the new " f"lane works on it again", now) return - if not any(x is st for x in ready(run)): - w = ", ".join(deps_open(run, st)) - if w: # launched too early: the step keeps waiting for its dependencies - _post(run, "devkit", "main", f"{who} started, but “{st['name']}” waits for {w}, not done yet: the step " - f"stays pending and this lane runs without it. When {w} is done, link it: dev progress assign " - f"\"{st['name']}\" --to \"{st['label']}\"", now, from_name="devkit") - return - _take_step(run, aid, st, now) + _claim_lane(run, aid, now) + if st is not None and st.get("state") == "pending" and deps_open(run, st): + w = ", ".join(deps_open(run, st)) # launched too early: the step keeps waiting for its dependencies + _post(run, "devkit", "main", f"{who} started, but “{st['name']}” waits for {w}, not done yet: the step " + f"stays pending, and this lane takes it once {w} is done if it is free then", now, from_name="devkit") -def _hand_scope(run: dict, st: dict, to: str, now: float): - """Step `st` and its scope now belong to lane `to`. Every other lane that holds no open step but keeps a scope of - its own that overlaps it (the scope of a step it held before, such as a stopped lane's) loses that scope and reads - only (`handed_over`) until Morpheus assigns it a step, so two lanes never write the same files, and a lane - without a scope is not left free to write anywhere.""" - globs = st.get("scope") or [] - if not globs: - return - plan = run.get("plan") or [] - for k, lane in (run.get("agents") or {}).items(): - own = lane.get("scope") or [] - if k == to or not own or to in lane_chain(run, k): - continue - if any(x.get("owner") == k and x.get("state") not in DONE for x in plan): - continue # it works on a step of its own - if not _same_checkout(st.get("checkout"), lane.get("checkout")) or \ - not any(_globs_overlap(g, h) for g in globs for h in own): - continue - _revoke_lane(run, k, st, to, now) - - -def _revoke_lane(run, aid, step, to, now): - """Losing assignment revokes write authority even when its scope was unrestricted.""" - lane = run["agents"][aid] - own = lane.pop("scope", []) - lane["handed_over"] = {"ts": round(now), "step": step.get("name"), "to": to[:16], "scope": own} - _audit("crew.scope-handed", lane.get("persona") or lane.get("label") or aid[:8], - f"“{step.get('name')}” went to {_name_of(run, to)}: this lane may read but not write until a step is " - "assigned to it", "restricted", project=run.get("project") or "", agent_id=aid[:16]) +def _launch_on_its_way(lane: dict, sess, now: float) -> bool: + """Does a new launch of this lane's member wait to start (a pending launch in the session record, within + LAUNCH_TTL)? Then that launch, not this resumed lane, takes the steps given to the member by role.""" + me = (lane.get("persona") or "").lower() + return bool(me) and any( + r.get("state") == "pending" and not r.get("agent_id") and now - (r.get("ts") or now) < LAUNCH_TTL + and (persona(r.get("type") or "", r.get("label") or "") or "").lower() == me + for r in (((sess or {}) if isinstance(sess, dict) else {}).get("launches") or {}).values() + if isinstance(r, dict)) def _lane_event(run, aid, kind, tid, rec, binding, now, start, waiting, own=True, sess=None): @@ -6046,25 +5979,11 @@ def _lane_event(run, aid, kind, tid, rec, binding, now, start, waiting, own=True (rec.get("ts") or 0) < run.get("started", 0)): return # a prior run's recorded launch cannot acquire this run's assignments if lane and own and lane.get("parent", "main") == "main": - if "assigned_steps" not in lane: - held = [s for s in run.get("plan", []) if s.get("owner") == aid] - for step in held: - _remember_step(lane, step) - if not held and run.get("plan"): - _revoke_lane(run, aid, {"name": "unverified prior assignment"}, "main", now) - return - current = [s for s in run.get("plan", []) if s.get("state") not in DONE and - s.get("label") and _label_matches(s["label"], lane) and - (s.get("owner") == aid or not deps_open(run, s) and - (_exact_intent(run, s, aid) if (s.get("waits_lane") or {}).get("revision") else - aid in _queued_lanes(s)))] - obsolete = next((s for s in run.get("plan", []) if - s["name"] in lane.get("assigned_steps", []) and - (s.get("label") and not _label_matches(s["label"], lane) or - s.get("owner", "main") not in ("main", aid))), None) - if obsolete and not current: - _revoke_lane(run, aid, obsolete, obsolete.get("owner") or "main", now) - return # reassignment is authoritative before the replacement agent starts + if "assigned_steps" not in lane: # a lane recorded before lanes kept their steps + lane["assigned_steps"] = [] + for step in run.get("plan", []): + if step.get("owner") == aid: + _remember_step(lane, step) intent = [s for s in run.get("plan", []) if _exact_intent(run, s, aid)] if lane.get("state") != "running" and intent and not any( s.get("state") == "pending" and not deps_open(run, s) for s in intent): @@ -6097,15 +6016,11 @@ def _lane_event(run, aid, kind, tid, rec, binding, now, start, waiting, own=True _open(run, "agent", aid, now) _audit("crew.resume", lane.get("persona") or lane.get("label") or aid[:8], lane.get("label") or "", project=run.get("project") or "", agent_id=aid[:16]) - if lane.get("parent", "main") == "main": # a member, not a helper: it takes the step waiting for it - _take_waiting_step(run, aid, now, sess if isinstance(sess, dict) else None) - if run.get("plan") and not _open_step_of(run, aid): - _revoke_lane(run, aid, {"name": "no current assignment"}, "main", now) - _tell_role_steps(run, aid, lane, now) + if lane.get("parent", "main") == "main": # a member, not a helper: it takes what waits for it + _claim_lane(run, aid, now, member_wide=not _launch_on_its_way(lane, sess, now)) elif own and lane.get("parent", "main") == "main": - # Assignment may follow the admission hook; the next own hook consumes - # its exact intent once dependencies are ready. - _take_waiting_step(run, aid, now, sess if isinstance(sess, dict) else None) + # an assignment may follow the admission hook: the next own hook of a free lane claims it + _claim_lane(run, aid, now, member_wide=not _launch_on_its_way(lane, sess, now)) if binding == "exact" and lane.get("binding") == "pending": label = rec.get("label") or lane.get("label") or kind parent = rec.get("parent") or "main" @@ -6633,11 +6548,10 @@ def lane_chain(run: dict, aid: str) -> list: def _lane_level(lane: dict) -> str: """One lane's own tool level: read for a lane whose launch another agent is bound to, that devkit has no launch record of (until Morpheus assigns it a step), or that has not met its launch yet (a missing binding - grants nothing); read too for a lane whose step and scope another lane took (`handed_over`, until Morpheus - assigns it a step) and for a resumed lane that waits for a crew slot (`waits_slot`); else its crew member's + grants nothing); read too for a resumed lane that waits for a crew slot (`waits_slot`); else its crew member's `tools`, else all (an ad-hoc agent).""" if lane.get("state") not in (None, "running") or \ - lane.get("binding") in ("conflict", "unbound", "pending") or lane.get("handed_over") or \ + lane.get("binding") in ("conflict", "unbound", "pending") or \ (lane.get("waits_slot") and lane.get("state") != "running"): return "read" try: @@ -6658,24 +6572,29 @@ def lane_tools(run: dict, aid: str): def lane_scope(run: dict, aid: str) -> list: - """The scope a lane edits in, as layers [[globs], …]: one per lane in its parent chain that has a scope (the - lane's own globs and those of the open steps it owns). A path must match every layer, so a helper stays inside - its member's files, and a helper with a scope of its own inside both. [] when nothing is scoped.""" + """The scope a lane edits in, as layers [[globs], …]: one per lane in its parent chain that has a scope, the + globs of the steps it runs (coord.scope), never a stored copy. A path must match every layer, so a helper stays + inside its member's files. A crew member's lane in a run with a plan that runs no step holds no file: its layer + is empty ([]), so a blocked, closed or reassigned step's files are no longer its own. [] when nothing is scoped: + a lane that runs steps without a scope, a helper, or an agent outside the crew.""" plan = (run or {}).get("plan") or [] layers = [] for k in lane_chain(run, aid): - globs = set(run["agents"][k].get("scope") or []) - for st in plan: - if st.get("owner") == k and st.get("state") not in DONE: - globs.update(st.get("scope") or []) + lane = run["agents"][k] + globs = coord.scope(run, k) + if not globs and not plan and lane.get("scope"): + globs = sorted(lane["scope"]) # a run without a plan, recorded before scopes came from steps if globs: - layers.append(sorted(globs)) + layers.append(globs) + elif plan and lane.get("persona") and (lane.get("parent") or "main") == "main" and not coord.held(run, k): + layers.append([]) return layers def in_scope(rel_path: str, layers: list) -> bool: - """A repo-relative path is inside every layer of a lane_scope (the same glob rules as scope_holders).""" - return all(_in_globs(rel_path, layer) for layer in layers if layer) + """A repo-relative path is inside every layer of a lane_scope (the same glob rules as scope_holders); an empty + layer holds nothing.""" + return all(_in_globs(rel_path, layer) for layer in layers) def launch_depth(sess: dict, run: dict | None, parent: str) -> int: @@ -6867,8 +6786,7 @@ def _resume_refusal(run: dict, aid: str, sess: dict, now: float): m = None # Admission charges for the member's restored tools, not the temporary read # restriction that its new assignment will clear in _take_step. - level = max((_lane_level(dict(run["agents"][k], state="running", - **({"handed_over": None} if k == aid else {}))) for k in lane_chain(run, aid)), + level = max((_lane_level(dict(run["agents"][k], state="running")) for k in lane_chain(run, aid)), key=TOOL_LEVELS.index, default="all") # its level once it works, whatever it waits for now cost = _cost(m, level) if cost <= 0: @@ -7295,15 +7213,20 @@ def _end_lane_steps(run: dict, lane: dict, aid: str, report: str, now: float, ag mine = [st for st in run.get("plan") or [] if st.get("owner") == aid and st.get("state") not in DONE] about = _steps_about(lane, aid, report, mine) who = lane.get("persona") or "the subagent" + from . import approvals for st in mine: + if st.get("state") == "blocked" and (not any(st is x for x in about) + or approvals.ending(lane, report)[0] != "done"): + continue # it waits for its decision: the answer gives it to its member's next lane (coord.unblock) if any(st is x for x in about): _end_member_step(run, st, lane, aid, report, now, agent, sid, passed=passed) continue old = st.get("state") st.update(owner="main", state="pending", started=None) st.pop("joined", None) + coord.set_intent(run, st, coord.member_of(st.get("label")) or who, None, now) _log_change(run, st, old, "pending", "devkit", f"{who} ended, and neither its launch, its report nor its dev " - f"progress step names this step: it waits for a launch of its own", now) + f"progress step names this step: it waits for its member's next lane", now) def _end_member_step(run: dict, st: dict, lane: dict, aid: str, report: str, now: float, agent: str, sid: str, diff --git a/tests/test_codex_coord_parity.py b/tests/test_codex_coord_parity.py new file mode 100644 index 00000000..b0f12fc1 --- /dev/null +++ b/tests/test_codex_coord_parity.py @@ -0,0 +1,64 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The crew coordination scenarios of tests/test_coord_scenarios.py on Codex's host path: members spawned with +spawn_agent and bound at SubagentStart by their task_name, resumed by a new SubagentStart of the same thread, each +member command a shell call through the hooks, and stops with the member's own rollout. Same outcomes as on Claude +Code; only how a member hears devkit differs (its next PostToolUse). Real `dev` processes and hooks. +Run: python3 -m unittest tests.test_codex_coord_parity""" +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_codex_launch import TANK # noqa: E402 +from test_coordination_codex import REPORT, CodexCoordination # noqa: E402 + +TANK2 = "01a1c190-64c7-7ac1-81c6-000000000012" +TANK_REPORT = REPORT.format(role="Backend engineer (Tank)", task="{task}") + + +class CodexParityTests(CodexCoordination): + def test_a_codex_members_record_with_no_step_running_warns_and_closes_nothing(self): + s = self.run_lead("api=30m [backend]; docs=15m") + self.spawn(s, TANK, "tank", "look around") + r = self.member(s, TANK, "tank", "progress", "step", "read the code", "--check", "✓ nothing to run") + self.assertEqual(r["rc"], 0, r["err"]) + self.assertNotIn("✓", r["out"].split("·")[0]) + self.assertIn("closes no step", r["out"]) + + def test_a_codex_queue_bound_to_a_lane_survives_its_end_and_its_resume_takes_it(self): + s = self.run_lead("api=30m [backend]; export=30m [backend]", ("api", "Tank", "api/**")) + self.spawn(s, TANK, "tank", "api") + label = s.run_doc()["agents"][TANK]["label"] + s.ok("progress", "assign", "export", "--to", label, "--scope", "export/**") + self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") + self.assertEqual(self.held(s, "export"), (TANK, "running")) + + def test_a_codex_answer_while_the_lane_works_on_puts_the_blocked_step_first(self): + s = self.run_lead("api=30m [backend]; export=30m [backend]", ("api", "Tank", "api/**")) + s.ok("crew", "mode", "guided") + self.spawn(s, TANK, "tank", "api") + self.member(s, TANK, "tank", "crew", "ask", "--decision", "CSV or JSON?", "--options", "A: csv | B: json", + "--recommend", "A") + s.ok("progress", "assign", "export", "--to", "Tank", "--scope", "export/**") + self.assertEqual((self.held(s, "api"), self.held(s, "export")), ((TANK, "blocked"), (TANK, "running"))) + d = next(x["id"] for x in s.run_doc()["decisions"] if x.get("state") == "pending") + s.ok("crew", "decide", d, "A: csv") + self.assertEqual(self.held(s, "api"), ("main", "pending")) + self.member(s, TANK, "tank", "progress", "step", "export committed", "--step", "export", "--check", "✓ 3") + self.assertEqual(self.held(s, "api"), (TANK, "running")) + + def test_a_codex_task_name_naming_a_done_step_binds_none_quietly(self): + s = self.run_lead("api=30m [backend]; export=30m [backend]", ("api", "Tank", "api/**")) + self.spawn(s, TANK, "tank", "api") + self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") + self.stop(s, TANK, "tank", TANK_REPORT.format(task="api")) + s.ok("progress", "assign", "export", "--to", "Tank") + self.spawn(s, TANK2, "tank", "api") # a follow-up of the finished api + self.assertEqual(self.held(s, "export"), ("main", "pending")) + told = [m["text"] for m in s.run_doc().get("messages") or [] if m.get("to") == "main"] + self.assertFalse([t for t in told if "names none" in t], told) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_coord_kernel.py b/tests/test_coord_kernel.py index b184db40..bc1f348e 100644 --- a/tests/test_coord_kernel.py +++ b/tests/test_coord_kernel.py @@ -184,7 +184,7 @@ def test_each_broken_invariant_is_named(self): cases = { "I-owner": lambda r: r["agents"]["L"].update(state="done"), "I-one-step": lambda r: r["plan"].append(step("api2", "running", "L", "Tank")), - "I-scope": lambda r: r["agents"]["L"].update(scope=["api/**"]), + "I-scope": lambda r: r["agents"]["L"].update(scope=["doc/**"]), # a closed step's files "I-separate": lambda r: r["plan"][1].update(scope=["api/x.py"]), "I-intent": lambda r: r["plan"][0].update(intent={"member": "Tank", "lane": None, "ts": T}), "I-claim": lambda r: (r["plan"][0].update(state="done"), diff --git a/tests/test_coord_model.py b/tests/test_coord_model.py new file mode 100644 index 00000000..e09d28e3 --- /dev/null +++ b/tests/test_coord_model.py @@ -0,0 +1,91 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The coordination invariants (devkit.coord.check) over the QA engineer's model hunt: the same seeded sequences of +what the tech lead and the crew do, on Claude Code and Codex (tests/test_coordination_model.py), each checked +against every invariant after every action, and each broken invariant reported with the shortest sequence that still +breaks it. DEVKIT_MODEL_SEED replays one seed; DEVKIT_MODEL_SEEDS sets how many sequences run. +Run: python3 -m unittest tests.test_coord_model""" +import os +import random +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import test_coordination_model as model # noqa: E402 +from devkit import coord # noqa: E402 +from devkit import progress as pg # noqa: E402 + +RULES = { + "I-owner": "every running step belongs to the tech lead or to one running lane", + "I-one-step": "a lane runs at most one step that is not a review", + "I-scope": "a lane's scope is that of the steps it runs, never a stored copy", + "I-separate": "two running lanes never hold the same file", + "I-intent": "only a pending step carries an intent", + "I-claim": "a free running lane never leaves a step waiting for it", + "I-history": "the run's count of closed steps and each step's last history entry match the plan", +} + + +class CoordWorld(model.World): + """The QA engineer's world, checked against coord.check after each action as well as its own rules.""" + + def check(self, a, before, expect): + super().check(a, before, expect) + for v in coord.check(self.run_(), time.time(), review=pg.is_review_step): + self.flag(v.split(":", 1)[0], v) + + +class CoordModelTests(unittest.TestCase): + found = None + + @classmethod + def hunt(cls): + if cls.found is None: + first = {} + with mock.patch.object(model, "World", CoordWorld): + one = os.environ.get("DEVKIT_MODEL_SEED") + seeds = [int(one)] if one else range(int(os.environ.get("DEVKIT_MODEL_SEEDS") or 24)) + for n in seeds: + host = "codex" if n % 2 else "claude" + seq, broken = model.generate(random.Random(model.SEED + n), host) + for rule in broken: + if rule in RULES: + first.setdefault(rule, (host, seq, n)) + cls.found = {rule: (host, n) + model.shrink(host, seq, rule) + for rule, (host, seq, n) in sorted(first.items())} + return cls.found + + def holds(self, rule): + got = self.hunt().get(rule) + if got: + host, n, seq, text = got + self.fail(f"{RULES[rule]}: broken on {host} (seed {n}) by {model.show(seq)}\n → {text}") + + def test_every_running_step_has_a_running_owner(self): + self.holds("I-owner") + + def test_a_lane_runs_one_step_besides_reviews(self): + self.holds("I-one-step") + + def test_a_lanes_scope_comes_from_its_running_steps(self): + self.holds("I-scope") + + def test_two_running_lanes_never_hold_one_file(self): + self.holds("I-separate") + + def test_only_pending_steps_carry_intents(self): + self.holds("I-intent") + + def test_no_free_lane_leaves_its_step_waiting(self): + self.holds("I-claim") + + def test_the_history_matches_the_plan(self): + self.holds("I-history") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_coord_scenarios.py b/tests/test_coord_scenarios.py new file mode 100644 index 00000000..1faf8942 --- /dev/null +++ b/tests/test_coord_scenarios.py @@ -0,0 +1,206 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""Crew coordination scenarios on Claude Code's path, through the progress API and its hooks: what a member's record +says and changes, the steps that wait for a member and the order its lanes take them in, blocked steps and their +answers, and the files a lane may write. The same scenarios on Codex are in tests/test_codex_coord_parity.py. +Run: python3 -m unittest tests.test_coord_scenarios""" +import sys +import time +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import coord, ui # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_progress import TempState, launch, member_call, progress_cli_out # noqa: E402 + +REPORT = ("**[Firefly> DevKit · Backend engineer (Tank)]** api · `main` · {task}\n- **Done:** {task}\n" + "- **Check:** {check}\n- **Next:** the tech lead reviews it") + + +class Scenario(unittest.TestCase): + def setUp(self): + self.state = TempState().__enter__() + self.addCleanup(self.state.__exit__, None, None, None) + self.t0 = time.time() - 3600 + + def m(self, minutes): + return self.t0 + minutes * 60 + + def run_(self): + return pg.load_run("claude", "s1") + + def held(self, name): + st = next(s for s in self.run_()["plan"] if s["name"] == name) + return st.get("owner"), st.get("state") + + def end(self, aid, task, at, member="tank", check="✓ 12 tests pass"): + pg.on_subagent("claude", {"session_id": "s1", "agent_id": aid, "agent_type": f"devkit:{member}", + "last_assistant_message": REPORT.format(task=task, check=check)}, False, now=at) + + def resume(self, aid, at, member="tank"): + pg.on_subagent("claude", {"session_id": "s1", "agent_id": aid, "agent_type": f"devkit:{member}"}, True, + now=at) + + def cli(self, aid, *args): + with member_call(aid): + return progress_cli_out("step", *args) + + def sound(self): + self.assertEqual(coord.check(self.run_(), time.time(), review=pg.is_review_step), []) + + +class MemberRecordTests(Scenario): + def test_member_step_without_step_closes_its_single_running_step(self): + pg.start("Export", plan=["api=30m", "docs=15m"], now=self.m(0)) + pg.assign("api", "Tank", scope="api/**", why="test", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + run = pg.step("api committed", check="✓ 12 tests pass", from_agent="a_tank", now=self.m(10)) + self.assertEqual(run["lane_outcome"]["changed"], [("api", "running", "done")]) + self.assertEqual(self.held("api"), ("a_tank", "done")) + self.sound() + + def test_member_step_without_any_held_step_prints_warning(self): + pg.start("Export", plan=["api=30m"], now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: look around", at=self.m(1)) + rc, out, err = self.cli("a_tank", "read the code", "--check", "✓ nothing to run") + self.assertEqual(rc, 0, err) + self.assertTrue(out.startswith(ui.WARN), out) + self.assertIn("closes no step", out) + self.assertEqual(self.held("api"), ("main", "running")) + + def test_a_record_for_a_step_already_done_says_so_with_a_warning(self): + pg.start("Export", plan=["api=30m", "docs=15m"], now=self.m(0)) + pg.assign("api", "Tank", why="test", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + pg.step("api committed", which="api", check="✓ 12 tests pass", from_agent="a_tank", now=self.m(10)) + rc, out, err = self.cli("a_tank", "api committed again", "--step", "api", "--check", "✓ 12 tests pass") + self.assertEqual(rc, 0, err) + self.assertTrue(out.startswith(ui.WARN), out) + self.assertIn("is done already", out) + + def test_a_record_naming_two_running_steps_is_refused_without_step(self): + pg.start("Review", plan=["api=30m", "review=20m [review]"], now=self.m(0)) + pg.assign("api", "Tank", why="test", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + run = self.run_() + run["plan"][1].update(owner="a_tank", state="running", label="Tank") # two build steps in one lane + run["plan"][1].pop("activity", None) + pg.run_path("claude", "s1").write_text(__import__("json").dumps(run)) + with self.assertRaises(pg.StepError) as e: + pg.step("both done", check="✓ 12 tests pass", from_agent="a_tank", now=self.m(10)) + self.assertIn("say which with --step", str(e.exception)) + + +class QueueTests(Scenario): + def setUp(self): + super().setUp() + pg.start("Export", plan=["api=30m", "export=30m", "import=30m"], now=self.m(0)) + pg.assign("api", "Tank", scope="api/**", why="test", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + + def test_lane_takes_queued_steps_in_order_after_each_close(self): + pg.assign("import", "Tank", scope="import/**", why="test", now=self.m(2)) + pg.assign("export", "Tank", scope="export/**", why="test", now=self.m(3)) + pg.step("api", which="api", check="✓ 1", from_agent="a_tank", now=self.m(10)) + self.assertEqual((self.held("import"), self.held("export")), (("a_tank", "running"), ("main", "pending"))) + pg.step("import", which="import", check="✓ 2", from_agent="a_tank", now=self.m(20)) + self.assertEqual(self.held("export"), ("a_tank", "running")) + self.assertEqual(pg.lane_scope(self.run_(), "a_tank"), [["export/**"]]) + self.sound() + + def test_queue_survives_lane_end_and_resume(self): + pg.assign("export", "Tank: api", scope="export/**", why="test", now=self.m(2)) # bound to this lane + pg.assign("import", "Tank", scope="import/**", why="test", now=self.m(3)) + self.end("a_tank", "api", self.m(10)) + self.assertEqual((self.held("api"), pg._queued_lanes(self.run_()["plan"][1])), (("a_tank", "done"), + ["a_tank"])) + self.resume("a_tank", self.m(12)) + self.assertEqual((self.held("export"), self.held("import")), (("a_tank", "running"), ("main", "pending"))) + self.sound() + + def test_a_new_launch_naming_a_step_bound_to_an_ended_lane_takes_it(self): + pg.assign("export", "Tank: api", scope="export/**", why="test", now=self.m(2)) + self.end("a_tank", "api", self.m(10)) + launch("a_tank2", "devkit:tank", "Tank: export", at=self.m(11)) + self.assertEqual(self.held("export"), ("a_tank2", "running")) + + def test_a_step_bound_to_a_live_lane_stays_with_it_when_another_launch_names_it(self): + pg.assign("export", "Tank: api", scope="export/**", why="test", now=self.m(2)) + launch("a_tank2", "devkit:tank", "Tank: export", at=self.m(3)) + self.assertEqual(self.held("export"), ("main", "pending")) + pg.step("api", which="api", check="✓ 1", from_agent="a_tank", now=self.m(10)) + self.assertEqual(self.held("export"), ("a_tank", "running")) + + def test_a_follow_up_launch_naming_a_done_step_takes_no_step(self): + self.end("a_tank", "api", self.m(10)) + pg.assign("export", "Tank", why="test", now=self.m(11)) + launch("a_tank2", "devkit:tank", "Tank: api follow-up", at=self.m(12)) + self.assertEqual(self.held("export"), ("main", "pending")) + self.assertEqual(self.run_()["agents"]["a_tank2"].get("follow_up"), "api") + self.sound() + + +class BlockTests(Scenario): + def setUp(self): + super().setUp() + pg.start("Export", plan=["api=30m", "export=30m"], now=self.m(0), mode="guided") + pg.assign("api", "Tank", scope="api/**", why="test", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + + def test_blocked_step_frees_lane_scope_and_next_step_joins(self): + pg.assign("export", "Tank", scope="export/**", why="test", now=self.m(2)) + pg.crew_decision("CSV or JSON?", options="A: csv | B: json", recommend="A", from_agent="a_tank", + now=self.m(5)) + self.assertEqual((self.held("api"), self.held("export")), (("a_tank", "blocked"), ("a_tank", "running"))) + self.assertEqual(pg.lane_scope(self.run_(), "a_tank"), [["export/**"]]) + self.sound() + + def test_answer_requeues_blocked_step_first_when_lane_busy(self): + pg.assign("export", "Tank", scope="export/**", why="test", now=self.m(2)) + d = pg.crew_decision("CSV or JSON?", options="A: csv | B: json", recommend="A", from_agent="a_tank", + now=self.m(5)) + pg.crew_decide(d["id"], "A: csv", now=self.m(6)) + self.assertEqual((self.held("api"), pg._queued_lanes(self.run_()["plan"][0])), (("main", "pending"), + ["a_tank"])) + pg.step("export", which="export", check="✓ 3", from_agent="a_tank", now=self.m(10)) + self.assertEqual(self.held("api"), ("a_tank", "running")) + self.sound() + + def test_an_answer_after_the_lane_ended_goes_to_the_members_next_lane(self): + d = pg.crew_decision("CSV or JSON?", options="A: csv | B: json", recommend="A", from_agent="a_tank", + now=self.m(5)) + self.end("a_tank", "api", self.m(6), check="– waiting for D1") # it stops while it waits + self.assertEqual(self.held("api"), ("a_tank", "blocked")) + pg.crew_decide(d["id"], "A: csv", now=self.m(7)) + launch("a_tank2", "devkit:tank", "Tank: carry on", at=self.m(8)) + self.assertEqual(self.held("api"), ("a_tank2", "running")) + + +class ScopeTests(Scenario): + def test_a_closed_step_gives_its_lane_no_files(self): + pg.start("Export", plan=["api=30m"], now=self.m(0)) + pg.assign("api", "Tank", scope="api/**", why="test", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + pg.step("api", which="api", check="✓ 1", from_agent="a_tank", now=self.m(10)) + layers = pg.lane_scope(self.run_(), "a_tank") + self.assertEqual((layers, pg.in_scope("api/x.py", layers)), ([[]], False)) + self.assertNotIn("scope", self.run_()["agents"]["a_tank"]) + + def test_a_run_without_a_plan_keeps_a_lanes_given_scope(self): + # a lane recorded with a scope of its own, as older runs and `dev test` in a lane have it + run = {"goal": "Work", "agents": {"a_kid": {"scope": ["lib/calc.py"], "label": "Kid: calc"}}, "plan": []} + self.assertEqual(pg.lane_scope(run, "a_kid"), [["lib/calc.py"]]) + + def test_file_glob_does_not_overlap_recursive_glob_with_other_file_name(self): + pg.start("Docs", plan=["guide=30m", "bugs=30m"], now=self.m(0)) + pg.assign("guide", "Kid", scope="docs/crew.md", why="test", now=self.m(0)) + launch("a_kid", "devkit:kid", "Kid: guide", at=self.m(1)) + pg.assign("bugs", "Ghost", scope="docs/**/bug*.md", why="test", now=self.m(2)) + with self.assertRaises(pg.StepError): + pg.assign("bugs", "Ghost", scope="docs/", why="test", now=self.m(3)) # a real overlap + + +if __name__ == "__main__": + unittest.main() From 59e374eea36a61cd184c72674e3c8cebc9cfa5e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:46:13 -0800 Subject: [PATCH 09/52] test(progress): follow the claim rule and derived lane scope These assertions pinned behavior the coordination fix replaced: queue entries in waits_lane, stored lane scope, read-only lanes after a reassignment, and a member's record that closed nothing. Each changed assertion carries a comment naming the rule it now checks. Verified: python3 -m unittest of the seven files in a copy with the committed identity module: OK --- tests/test_caller_identity.py | 3 ++- tests/test_crew_slots.py | 9 +++++---- tests/test_lane_binding.py | 18 ++++++++++-------- tests/test_progress.py | 31 +++++++++++++++---------------- tests/test_progress_reassign.py | 4 ++-- tests/test_raci.py | 4 ++-- tests/test_scope_liveness.py | 2 +- 7 files changed, 37 insertions(+), 34 deletions(-) diff --git a/tests/test_caller_identity.py b/tests/test_caller_identity.py index 3f2d89ed..c5790766 100644 --- a/tests/test_caller_identity.py +++ b/tests/test_caller_identity.py @@ -243,7 +243,8 @@ def test_a_member_match_makes_a_lane_command_act_as_that_member(self): self.assertEqual(rc, 0, out) run = self.run_() self.assertEqual([u["text"] for u in run["agents"]["a_tank"]["updates"]], ["parser done"]) - self.assertEqual(next(s for s in run["plan"] if s["name"] == "parser")["state"], "running") + # the member's record closes its lane's only running step; a Check without ✓ leaves it unverified + self.assertEqual(next(s for s in run["plan"] if s["name"] == "parser")["state"], "unverified") def test_a_delegation_through_a_member_call_is_the_members(self): self.plan_with_tank() diff --git a/tests/test_crew_slots.py b/tests/test_crew_slots.py index 060997a4..f8466748 100644 --- a/tests/test_crew_slots.py +++ b/tests/test_crew_slots.py @@ -282,8 +282,9 @@ def test_a_stopped_lane_frees_its_slot_and_its_step_waits_for_a_new_launch(self) self.assertEqual(run["agents"]["a_link"]["state"], "stopped") self.assertEqual((step["state"], step["owner"], step["label"]), ("pending", "main", "Link")) self.assertEqual(pg.slots(run), []) - self.assertIn("wrong brief", next(h["why"] for h in run["history"] if h["step"] == "ciwatch reports once" - and h["to"] == "pending")) + # the step's latest move to pending is the stop's (its assignment from the tech lead's lane came first) + self.assertIn("wrong brief", [h["why"] for h in run["history"] if h["step"] == "ciwatch reports once" + and h["to"] == "pending"][-1]) self.assertEqual([r["target"] for r in audit.records(1, "crew.stopped")], ["a_link"]) self.assertTrue(made) self.assertIn("ciwatch reports once", dispatch.ready_context("claude", "s1")) # announced ready to launch @@ -303,7 +304,7 @@ def test_a_stopped_lane_whose_step_a_live_lane_took_loses_its_scope(self): now=self.t0 + 120) run = pg.load_run("claude", "s1") self.assertEqual(pg.lane_scope(run, "a_link2"), [["lib/devkit/ciwatch.py"]]) - self.assertEqual((pg.lane_scope(run, "a_link"), pg.lane_tools(run, "a_link")), ([], "read")) + self.assertEqual((pg.lane_scope(run, "a_link"), pg.lane_tools(run, "a_link")), ([[]], "read")) # a lane that runs no step holds no file: an empty layer class ResumeSlotTests(unittest.TestCase): @@ -353,7 +354,7 @@ def test_a_stopped_lane_whose_step_a_new_launch_took_loses_its_scope(self): launch("a_tank2", "devkit:tank", "Tank: api") run = pg.load_run("claude", "s1") self.assertEqual(run["plan"][0]["owner"], "a_tank2") - self.assertEqual((pg.lane_scope(run, "a_tank"), pg.lane_tools(run, "a_tank")), ([], "read")) + self.assertEqual((pg.lane_scope(run, "a_tank"), pg.lane_tools(run, "a_tank")), ([[]], "read")) # a lane that runs no step holds no file: an empty layer class VisibleTests(unittest.TestCase): diff --git a/tests/test_lane_binding.py b/tests/test_lane_binding.py index 3632db82..e0346676 100644 --- a/tests/test_lane_binding.py +++ b/tests/test_lane_binding.py @@ -276,7 +276,7 @@ def test_a_finished_claude_child_takes_its_new_exact_intent_over_obsolete_histor pg.assign("dashboard server", "Neo", why="replacement owns the follow-up", now=self.m(24)) self.first_tool("a_tank") - self.assertEqual(pg.lane_tools(self.run_(), "a_tank"), "read") + self.assertEqual(pg.lane_scope(self.run_(), "a_tank"), [[]]) # it runs no step now, so it holds no file self.assertEqual(self.step("dashboard server")["owner"], "main") def test_a_launch_binds_to_the_step_its_description_names_not_the_members_first(self): @@ -298,15 +298,17 @@ def test_a_launch_binds_to_the_step_its_description_names_not_the_members_first( self.assertEqual(self.step("plan dependency engine")["owner"], "main") self.assertEqual(self.step("lifecycle consult security")["owner"], "main") - def test_a_launch_that_names_none_of_the_members_steps_takes_none_and_morpheus_is_told(self): + def test_a_launch_that_names_none_of_the_members_steps_takes_the_oldest_step_waiting_for_its_member(self): + # a free lane takes the oldest step assigned to its member, whatever its description says pg.start("Work", plan=["F2 exact lane binding"], now=self.m(0)) pg.assign("F2 exact lane binding", "Tank", now=self.m(0), why="the live plan's assignment") self.launch("toolu_consult", "Tank: backend consultation") self.start("a_consult") self.result("toolu_consult", "a_consult", "Tank: backend consultation") self.assertEqual((self.step("F2 exact lane binding")["owner"], self.lane("a_consult").get("binding")), - ("main", "exact")) - self.assertTrue(any("F2 exact lane binding" in t and "dev progress assign" in t for t in self.to_morpheus())) + ("a_consult", "exact")) + self.assertIn("“F2 exact lane binding” is your step now", " ".join( + m["text"] for m in self.run_().get("messages") or [] if m.get("to") == "a_consult")) class ResumeTests(LaneCase): @@ -330,9 +332,9 @@ def reassignment(self, label, scope): pg.assign("dashboard server", "Neo", why="handoff", now=self.m(22)) self.start("a_tank", at=self.m(23)) self.assertEqual(self.step("dashboard server")["owner"], "main") - self.assertNotEqual(pg.lane_tools(self.run_(), "a_tank"), "all") - self.assertEqual(pg.lane_scope(self.run_(), "a_tank"), []) - self.assertIn(ADVICE, self.first_tool("a_tank", tool="Edit", file_path="server/api.py")) + # the lane keeps its member's tools and runs no step, so it holds no file: its edits get the scope advice + self.assertEqual(pg.lane_scope(self.run_(), "a_tank"), [[]]) + self.assertFalse(pg.in_scope("server/api.py", pg.lane_scope(self.run_(), "a_tank"))) def test_a_resumed_agent_keeps_its_own_lane_and_takes_no_queued_launch(self): # live, B-fxnghfz0rjj: Tank's resumed lane took Trinity's label and step, and Morpheus's next message to @@ -555,7 +557,7 @@ def test_a_queued_step_waits_for_a_launch_of_its_own_once_the_lane_ends(self): # the queue is a promise of the lane while it works: its report closes launcher-depth and ends the lane, and # case-revert, which no evidence of the lane names, is offered for a launch of its own self.assign("case-revert", "tests/test_readonly.py", self.m(5)) - self.assertEqual((self.run_()["plan"][1].get("waits_lane") or {}).get("lane"), "a_neo") + self.assertEqual(pg._queued_lanes(self.run_()["plan"][1]), ["a_neo"]) # the queue lives in the step's intent, read by progress._queued_lanes pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a_neo", "agent_type": "devkit:neo", "last_assistant_message": self.REPORT.format(task="launcher-depth")}, False, now=self.m(30)) diff --git a/tests/test_progress.py b/tests/test_progress.py index 489544af..016691d0 100644 --- a/tests/test_progress.py +++ b/tests/test_progress.py @@ -2407,7 +2407,8 @@ def test_a_step_assigned_while_its_member_works_on_another_waits_for_its_own_lau s = self.plan()["isolated python spawns"] self.assertEqual((s["owner"], s["state"]), ("main", "pending")) told = [x["text"] for x in self.run_().get("messages") or [] if x.get("to") == "main"] - self.assertFalse(told) # a generic role assignment cannot capture a different launch's lane + # a role assignment waits for whichever of its member's lanes frees first, and the tech lead hears where + self.assertTrue(any("joins that lane once “red team fixes part 3” closes" in t for t in told), told) plan = self.stop("a_rt3", "✓ 18 red team tests pass on both Pythons", at=self.m(30)) self.assertEqual(plan["red team fixes part 3"]["state"], "done") self.assertEqual((plan["isolated python spawns"]["owner"], plan["isolated python spawns"]["state"]), @@ -2422,7 +2423,7 @@ def test_a_lanes_end_closes_only_the_steps_its_evidence_is_about(self): from devkit import dispatch named, other = "M379 status text says the tech lead", "M381 dev backup is tier 1 for members" waiting = dispatch.delegate(named, to="The Keymaker", now=self.m(5)) - self.assertEqual((waiting["lane"], (waiting["step"].get("waits_lane") or {}).get("lane")), (None, "a_rt3")) + self.assertEqual((waiting["lane"], pg._queued_lanes(waiting["step"])), (None, ["a_rt3"])) # the queue lives in the step's intent, read by progress._queued_lanes pg.step("red team fixes part 3", which="red team fixes part 3", check="✓ 18 red team tests", from_agent="a_rt3", now=self.m(10)) self.assertEqual((self.plan()[named]["owner"], self.plan()[named]["state"]), ("a_rt3", "running")) @@ -2882,8 +2883,7 @@ def test_a_members_close_of_its_own_step_without_evidence_fails_and_says_how(sel class ResumedMemberTakesItsNewStepTests(unittest.TestCase): # The DevEx engineer finished "sync" and its lane ended. The tech lead ran `dev progress assign cache-notes --to # Kid`, then resumed it with SendMessage: the resumed lane took no step and could not write, and nothing said why. - # A lane that ended takes a step only from an assignment naming it ("Kid: sync"): a role's step may be meant for - # a new launch. devkit now says so, with the line, when the step is assigned and when the lane resumes without it + # The step now waits for the member itself, so the resumed lane takes it, with its scope T0 = 1_800_000_000.0 LINE = 'dev progress assign "cache-notes" --to "Kid: sync"' @@ -2904,21 +2904,20 @@ def setUp(self): def told(self): return pg.messages_context("claude", "s1", "main") or "" - def test_a_role_assignment_while_the_members_lane_ended_names_the_line_that_gives_it_to_that_lane(self): - pg.assign("cache-notes", "Kid", why="test", now=self.m(11.5)) - self.assertIn(self.LINE, self.told()) + def test_a_role_assignment_while_the_members_lane_ended_waits_for_that_member(self): + # a role's step waits for the member's next lane, a resume or a new launch, with no line to relink it + run = pg.assign("cache-notes", "Kid", why="test", now=self.m(11.5)) + s = run["plan"][1] + self.assertEqual((s["state"], s["owner"], pg._queued_lanes(s)), ("pending", "main", [])) + self.assertNotIn(self.LINE, self.told()) - def test_a_member_resumed_without_its_step_is_told_the_line_and_takes_the_step_from_it(self): - pg.assign("cache-notes", "Kid", why="test", now=self.m(11.5)) - self.told() + def test_a_member_resumed_without_its_step_takes_the_step_assigned_to_it_by_role_and_may_write(self): + pg.assign("cache-notes", "Kid", scope="docs/**", why="test", now=self.m(11.5)) pg.bind("claude", {"session_id": "s1", "agent_id": "k1", "agent_type": "devkit:kid"}, now=self.m(12)) - self.assertEqual(pg.lane_tools(pg.load_run("claude", "s1"), "k1"), "read") - told = self.told() - self.assertIn("may read but not write", told) - self.assertIn(self.LINE, told) - run = pg.assign("cache-notes", "Kid: sync", scope="docs/**", why="test", now=self.m(13)) + run = pg.load_run("claude", "s1") self.assertEqual((run["plan"][1]["state"], run["plan"][1]["owner"]), ("running", "k1")) - self.assertEqual(pg.lane_tools(run, "k1"), "all") + self.assertEqual((pg.lane_tools(run, "k1"), pg.lane_scope(run, "k1")), ("all", [["docs/**"]])) + self.assertIn("“cache-notes” is your step now", pg.messages_context("claude", "s1", "k1") or "") class SavedModeChangeTests(unittest.TestCase): diff --git a/tests/test_progress_reassign.py b/tests/test_progress_reassign.py index 187abd0e..9ce574fe 100644 --- a/tests/test_progress_reassign.py +++ b/tests/test_progress_reassign.py @@ -37,14 +37,14 @@ def test_the_lane_a_step_was_queued_for_is_told_its_new_owner_and_no_other_lane_ pg.assign("csv", "Neo: parser", why="test") # that lane works on parser: csv is queued for it pg.assign("docs", "Mouse", why="test") # no Mouse lane works: docs waits for a launch, queued for nobody told = {aid: len(lane_messages(aid)) for aid in ("a_neo", "a_dozer")} - queued = next(s for s in pg.load_run("claude", "s1")["plan"] if s["name"] == "csv").get("waits_lane") + queued = pg._queued_lanes(next(s for s in pg.load_run("claude", "s1")["plan"] if s["name"] == "csv")) pg.assign("csv", "Tank", why="test") pg.assign("docs", "Tank", why="test") neo = lane_messages("a_neo")[told["a_neo"]:] dozer = lane_messages("a_dozer")[told["a_dozer"]:] delivered = pg.on_tool_done("claude", {"session_id": "s1", "agent_id": "a_neo"}) or "" csv = next(s for s in pg.load_run("claude", "s1")["plan"] if s["name"] == "csv") - self.assertEqual((queued or {}).get("lane"), "a_neo") + self.assertEqual(queued, ["a_neo"]) # the queue lives in the step's intent, read by progress._queued_lanes self.assertEqual(len(neo), 1, neo) self.assertEqual(neo[0].get("kind"), "notice") self.assertIn("the tech lead gave “csv” to Backend engineer (Tank)", neo[0]["text"]) diff --git a/tests/test_raci.py b/tests/test_raci.py index 67435784..c86ed6d8 100644 --- a/tests/test_raci.py +++ b/tests/test_raci.py @@ -273,10 +273,10 @@ def test_a_step_reassigned_away_from_a_running_member_leaves_its_lane(self): launch("a1", "devkit:kid", "Kid: installer", self.m(1)) dispatch.delegate("dashboard server", to="Kid", now=self.m(2)) # a mistake: it waits for Kid's busy lane queued = pg.load_run("claude", "s1")["plan"][1] - self.assertEqual((queued["owner"], (queued.get("waits_lane") or {}).get("lane")), ("main", "a1")) + self.assertEqual((queued["owner"], pg._queued_lanes(queued)), ("main", ["a1"])) # the queue lives in the step's intent, read by progress._queued_lanes run = pg.assign("dashboard server", "Tank", now=self.m(3)) s = run["plan"][1] - self.assertEqual((s["owner"], s["state"], s["label"], s.get("waits_lane")), ("main", "pending", "Tank", None)) + self.assertEqual((s["owner"], s["state"], s["label"], pg._queued_lanes(s)), ("main", "pending", "Tank", [])) # the queue lives in the step's intent, read by progress._queued_lanes self.assertIn("reassigned from Kid to Tank", [c.get("why") for c in run.get("history") or []][-1] or "") # Kid's own step closes: the step that went to Tank stays out of Kid's lane pg.step("installer", which="installer", check="✓ installer tests pass", from_agent="a1", now=self.m(10)) diff --git a/tests/test_scope_liveness.py b/tests/test_scope_liveness.py index 23a56885..83b4456d 100644 --- a/tests/test_scope_liveness.py +++ b/tests/test_scope_liveness.py @@ -570,7 +570,7 @@ def test_delegate_gives_the_step_to_this_sessions_working_member_when_the_sessio self.working_tank_without_the_sessions_record() r = dispatch.delegate("add a nullable column for the export date", to="Tank", now=self.now) # the lane still works on "api", so the step waits for it (a lane taken for stale would get no step at all) - self.assertEqual((r["lane"], (r["step"].get("waits_lane") or {}).get("lane")), (None, "a_tank")) + self.assertEqual((r["lane"], pg._queued_lanes(r["step"])), (None, ["a_tank"])) # the queue lives in the step's intent, read by progress._queued_lanes def test_this_sessions_working_member_still_works_when_the_sessions_record_is_missing(self): self.working_tank_without_the_sessions_record() From e78b96ef8a628404b00d1b16647ad9d0752f209a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 19:56:23 -0800 Subject: [PATCH 10/52] fix(progress): tell the tech lead which verdicts a lane end drops A review or --approves verdict the crew gates did not pass was dropped with a history line only, so nobody heard the work was still owed; reopen and begin also changed step states with no history entry. Root cause: _lane_verdicts and _end_member_step recorded refused verdicts only in history and audit, and reopen, begin and assign moved steps without _log_change One notice per lane end names the reviews and verdicts that do not count; the hook names the findings. The model test adds coord.check after every action of the QA hunt. Verified: python3 -m unittest tests.test_coord_scenarios tests.test_codex_coord_parity tests.test_coord_calltoken: OK; DEVKIT_MODEL_SEEDS=60 tests.test_coord_model: 7 OK --- lib/devkit/progress.py | 22 ++++++++++++++++++++++ tests/test_codex_coord_parity.py | 5 ++++- tests/test_coord_calltoken.py | 4 ---- tests/test_coord_scenarios.py | 20 ++++++++++++++++++++ 4 files changed, 46 insertions(+), 5 deletions(-) diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 286e61d7..66067c0a 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -4758,6 +4758,8 @@ def reopen(which, why: str, cwd: str | None = None, now: float | None = None, sk for x in run["plan"]: # the reopened step becomes the main lane's current one if x is not s and x.get("state") == "running" and (x.get("owner") or "main") == "main": x["state"] = "pending" + coord._history(run, x, "running", "pending", "main", f"“{s['name']}” was reopened and " + f"runs in its place", now) s["state"] = "running" s["started"] = s.get("started") or now elif s.get("label"): # its member still works: back to their lane, now or once its open step closes @@ -4938,6 +4940,7 @@ def _lane_verdicts(run: dict, lane: dict, aid: str, passed: bool, now: float): if not passed: why = (f"{who}'s verdict on it (dev progress step --approves) is not counted: the crew gates did not pass " f"its report (sent back, only recorded, or not judged)") + run.setdefault("_uncounted", []).extend(f"its verdict on “{n}”" for n in names) for n in names: st = steps[n] run.setdefault("history", []).append({"ts": round(now), "step": n, "from": st.get("state") or "-", @@ -4953,6 +4956,23 @@ def _lane_verdicts(run: dict, lane: dict, aid: str, passed: bool, now: float): project=run.get("project") or "") +def _tell_uncounted(run: dict, lane: dict, now: float): + """At a lane's end, one devkit notice to the tech lead naming the reviews and verdicts its member gave that do + not count (_end_member_step, _lane_verdicts), since the crew gates did not pass its report; the hook names the + gate findings themselves.""" + held = list(dict.fromkeys(run.pop("_uncounted", None) or [])) + if held: + from . import crew + _post(run, "devkit", "main", f"devkit: {crew.who(lane.get('persona') or lane.get('label') or 'a member')}'s " + f"report did not pass the crew gates, so {_quoted_list(held)} count{'s' if len(held) == 1 else ''} " + f"for nothing yet: the work stays owed until a report the gates pass (resume the member, or launch the " + f"review again)", now, from_name="devkit", kind="notice") + + +def _quoted_list(items: list) -> str: + return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1] + + def step(text: str, nxt: str = "", cwd: str | None = None, kind: str = "step", check: str = "", which=None, from_agent: str | None = None, now: float | None = None, force: bool = False, why: str = "", approves: str = "") -> dict: @@ -6949,6 +6969,7 @@ def finish(run, rsid=sid): spent.append(passed) _end_lane_steps(run, lane or {}, aid, report, now, agent, rsid, passed=passed) _lane_verdicts(run, lane or {}, aid, passed, now) + _tell_uncounted(run, lane or {}, now) run["step"] = sum(1 for x in run.get("plan") or [] if x.get("state") in ("done", "skipped")) _advance_main(run, now) _run_event(agent, sid, finish) @@ -7248,6 +7269,7 @@ def _end_member_step(run: dict, st: dict, lane: dict, aid: str, report: str, now if state_ == "done" and sure: state_, why = "unverified", f"its shell call wrote {', '.join(sure[:3])} while no other writer was at work" if state_ == "done" and not passed and approvals.is_review(st): + run.setdefault("_uncounted", []).append(f"the review “{st['name']}”") state_, why = "unverified", ("the crew gates did not pass its report (sent back, only recorded, or not " "judged), so its Check approves nothing: launch the review again for a verdict " "the gates pass") diff --git a/tests/test_codex_coord_parity.py b/tests/test_codex_coord_parity.py index b0f12fc1..c9dad62a 100644 --- a/tests/test_codex_coord_parity.py +++ b/tests/test_codex_coord_parity.py @@ -31,7 +31,10 @@ def test_a_codex_queue_bound_to_a_lane_survives_its_end_and_its_resume_takes_it( self.spawn(s, TANK, "tank", "api") label = s.run_doc()["agents"][TANK]["label"] s.ok("progress", "assign", "export", "--to", label, "--scope", "export/**") - self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") + self.stop(s, TANK, "tank", TANK_REPORT.format(task="api")) # sent back once: it recorded no step + self.stop(s, TANK, "tank", TANK_REPORT.format(task="api"), again=True) # let through: the lane ends + self.assertEqual((s.run_doc()["agents"][TANK]["state"], self.held(s, "export")), ("done", ("main", "pending"))) + self.subagent_start(s, TANK, "tank") # resumed: Codex starts the same thread again self.assertEqual(self.held(s, "export"), (TANK, "running")) def test_a_codex_answer_while_the_lane_works_on_puts_the_blocked_step_first(self): diff --git a/tests/test_coord_calltoken.py b/tests/test_coord_calltoken.py index a35d0e70..14eb04b3 100644 --- a/tests/test_coord_calltoken.py +++ b/tests/test_coord_calltoken.py @@ -27,10 +27,6 @@ def test_the_entry_carries_the_token_hash_from_its_first_write(self): pg.call_opened("claude", call("toolu_tok1"), token_sha256=digest) self.assertEqual(pg.call_entry(call("toolu_tok1"))["token_sha256"], digest) - def test_an_entry_without_a_token_has_no_hash(self): - pg.call_opened("claude", call("toolu_tok2")) - self.assertNotIn("token_sha256", pg.call_entry(call("toolu_tok2"))) - def test_a_malformed_hash_writes_no_entry(self): for bad in ("nonce-value", "A" * 64, "ab" * 31): with self.assertRaises(ValueError): diff --git a/tests/test_coord_scenarios.py b/tests/test_coord_scenarios.py index 1faf8942..7636287b 100644 --- a/tests/test_coord_scenarios.py +++ b/tests/test_coord_scenarios.py @@ -202,5 +202,25 @@ def test_file_glob_does_not_overlap_recursive_glob_with_other_file_name(self): pg.assign("bugs", "Ghost", scope="docs/", why="test", now=self.m(3)) # a real overlap +class VerdictNoticeTests(Scenario): + def test_a_review_and_a_verdict_the_gates_did_not_pass_are_named_to_the_tech_lead_once(self): + pg.start("Export", plan=["api=30m", "review=20m [review] after api"], now=self.m(0)) + pg.assign("api", "Tank", why="test", now=self.m(0)) + pg.assign("review", "Seraph", why="test", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + pg.step("api", which="api", check="✓ 1", from_agent="a_tank", now=self.m(5)) + launch("a_ser", "devkit:seraph", "Seraph: review", at=self.m(6)) + pg.step("review done", which="review", check="✓ read the diff", from_agent="a_ser", approves="api", + now=self.m(10)) + pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a_ser", "agent_type": "devkit:seraph", + "last_assistant_message": REPORT.format(task="review", check="✓ read the diff")}, + False, now=self.m(11)) + told = [m["text"] for m in self.run_().get("messages") or [] if m.get("to") == "main" + and "crew gates" in m["text"]] + self.assertEqual(len(told), 1, told) + self.assertIn("“review”", told[0]) + self.assertIn("“api”", told[0]) + + if __name__ == "__main__": unittest.main() From 846d53812232e94f6e62db7cfc917d8c26f62edf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:02:53 -0800 Subject: [PATCH 11/52] fix(ci): derive the CI watch limit and name a job no runner takes A commit's CI watch gave up after a fixed 90 minutes, shorter than a chain of jobs that need each other can take, and a job that no runner took (a runs-on label no runner has) ended as a plain 'still running', so nobody learned why the run never finished. Root cause: the watch's limit was the constant 90 in watch, start_background and cmd_wait, unrelated to the jobs' timeout-minutes, and nothing told a job waiting for a runner from one still at work The limit is the longest needs-chain of job timeout-minutes in the GitHub workflows that run on a push or pull request, plus 30 minutes for the queue, between 90 and 360; the background watch after a push gets it. A GitHub job that has waited 30 minutes for a runner while nothing else of its commit runs is told once to an agent's wait with its next action, and named when the watch reaches its limit. cistatus keeps GitHub's own status, so a job waiting for an environment's approval is never taken for one. Verified: dev test run (test_ci_watch_limits, test_ci_not_started, test_coordination_ci, test_ciwatch, test_ciwatch_sessions, test_cistatus, test_watch_e2e, test_watch_stop, test_dashnow, test_codex_watch, test_watch_gate_wiring, test_gitx): 360 passed; dev test prove: 4 new tests fail without the change --- lib/devkit/cistatus.py | 6 +- lib/devkit/ciwatch.py | 113 ++++++++++++++++++++++++++++++---- tests/test_ci_watch_limits.py | 109 ++++++++++++++++++++++++++++++++ 3 files changed, 214 insertions(+), 14 deletions(-) create mode 100644 tests/test_ci_watch_limits.py diff --git a/lib/devkit/cistatus.py b/lib/devkit/cistatus.py index b71b3813..b0297caa 100644 --- a/lib/devkit/cistatus.py +++ b/lib/devkit/cistatus.py @@ -114,7 +114,9 @@ def github_job(j: dict, now: float) -> dict: st, fin = _ts(j.get("startedAt")), _ts(j.get("completedAt")) return {"name": j.get("name"), "status": _gh_status(j.get("status"), j.get("conclusion")), "started": st, "elapsed": (fin or now) - st if st else 0, "steps_done": len(done), "steps_total": len(steps), - "current": cur, "url": j.get("url")} + "current": cur, "url": j.get("url"), + # GitHub's own word: "queued" waits for a runner, "waiting" for an environment's approval + "host_status": j.get("status")} def github_run(r: dict, now: float) -> dict: @@ -126,7 +128,7 @@ def github_run(r: dict, now: float) -> dict: "sha": (r.get("headSha") or "")[:7], "event": r.get("event"), "status": status, "conclusion": r.get("conclusion") or "", "started": st, "finished": fin, "elapsed": (fin or now) - st if st else 0, "eta": None, "url": r.get("url"), - "workflow_id": r.get("workflowDatabaseId"), "jobs": []} + "workflow_id": r.get("workflowDatabaseId"), "jobs": [], "host_status": r.get("status")} def _github(owner_repo: str, branch, limit: int, detail: bool) -> list: diff --git a/lib/devkit/ciwatch.py b/lib/devkit/ciwatch.py index 4e465ed0..b86a5122 100644 --- a/lib/devkit/ciwatch.py +++ b/lib/devkit/ciwatch.py @@ -36,6 +36,7 @@ import hashlib import json +import math import os import re import shlex @@ -55,6 +56,14 @@ LIVE_DAYS = 3 WAIT_MIN = 28 # an agent's watch ends itself before a Claude Code Monitor's 30-minute limit, with the re-arm command MONITOR_MS = 1_800_000 # the longest Monitor Claude Code allows +WATCH_DEFAULT_MIN = 90 # a watch's limit when no job of the workflows declares a timeout, and its floor +WATCH_MAX_MIN = 360 # its ceiling: GitHub ends a job at 6 hours, and a background watcher should not outlive that +QUEUE_MIN = 30 # the queue's share of a watch's limit, and how long a job may wait for a runner before it is stuck +RUNNER_WAIT = ("queued", "requested", "pending") # GitHub's words for a run or job that waits for a runner +STUCK_ACTION = ("no runner has taken it: when its runs-on names a self-hosted label, compare it with the runners the " + "repository has (Settings → Actions → Runners; dev ci audit) and start the one that is offline; on " + "GitHub's own runners, the account's other jobs hold every slot and it starts when one frees; gh run " + "cancel drops the run") EXIT = {"passed": 0, "failed": 1, "timeout": 3, "none": 4} # 2: nothing to watch FINAL = ("passed", "failed", "none") # how a watch can end with its run's result DONE = ("success", "failed", "cancelled", "skipped") @@ -387,7 +396,68 @@ def _final_jobs(provider: str, repo: str, run: dict, again=None) -> list: return [cistatus.github_job(j, time.time()) for j in jobs if isinstance(j, dict)] -def watch(top: str, branch: str | None = None, sha: str | None = None, timeout_min: float = 90, +def watch_minutes(top) -> int: + """How long a watch of a commit's CI follows it before it ends as still running: the longest chain of jobs that + need each other in the repository's GitHub workflows that run on a push or a pull request, each at its + timeout-minutes, plus QUEUE_MIN for the queue. Never under WATCH_DEFAULT_MIN (so also when no job declares a + timeout, or the workflows cannot be read), never over WATCH_MAX_MIN. Jobs of different workflows run at once.""" + try: + from . import gitx + jobs = {(j["file"], j["id"]): j for j in gitx.plan(top) + if not str(j.get("skip") or "").startswith("workflow runs on")} # not on a push or a pull request + except Exception: # noqa: BLE001 - an unreadable workflow keeps the default, never the watch + return WATCH_DEFAULT_MIN + memo = {} + + def chain(key, seen=frozenset()): + """The minutes of the longest chain of jobs that ends with job `key`.""" + if key not in jobs or key in seen: # a need of another workflow, or a cycle GitHub would refuse + return 0 + if key not in memo: + j = jobs[key] + memo[key] = (j.get("timeout") or 0) + max( + (chain((key[0], need), seen | {key}) for need in j.get("needs") or []), default=0) + return memo[key] + longest = max((chain(k) for k in jobs), default=0) + return int(min(WATCH_MAX_MIN, max(WATCH_DEFAULT_MIN, math.ceil(longest + QUEUE_MIN)))) + + +def _stuck(provider: str, runs: list, waits: dict, now: float) -> list: + """The commit's GitHub jobs (or runs not given a job yet) that have waited QUEUE_MIN minutes for a runner while + nothing else of the commit ran: [{run, number, id, url, job, minutes}]. `waits`, kept across a watch's polls: + {(run id, job name): when this watch first saw it wait with nothing running}. A running job or run clears it, so + a job queued behind the jobs it needs counts only from when they end; a job waiting for an environment's + approval (GitHub's "waiting") never counts.""" + live = [r for r in runs if r.get("status") not in DONE] + waiting = {} + for r in live if provider == "github" else []: + jobs = [j for j in r.get("jobs") or [] if j.get("status") not in DONE] + if any(j.get("status") == "running" for j in jobs) or (not jobs and r.get("status") == "running"): + waiting = {} + break + for j in jobs: + if j.get("host_status") in RUNNER_WAIT: + waiting[(r.get("id"), j.get("name"))] = r + if not jobs and r.get("host_status") in RUNNER_WAIT: + waiting[(r.get("id"), None)] = r + for key in [k for k in waits if k not in waiting]: + waits.pop(key) + out = [] + for key, r in waiting.items(): + minutes = int((now - waits.setdefault(key, now)) // 60) + if minutes >= QUEUE_MIN: + out.append({"run": r.get("name"), "number": r.get("number"), "id": r.get("id"), "url": r.get("url"), + "job": key[1], "minutes": minutes}) + return out + + +def stuck_line(s: dict) -> str: + """`job “deploy” of ci #41 has waited 30 min for a runner`: a job (or run) no runner took.""" + what = f"job “{_one_line(s.get('job'))}” of " if s.get("job") else "" + return f"{what}{_one_line(s.get('run'), 60)} #{s.get('number')} has waited {s.get('minutes')} min for a runner" + + +def watch(top: str, branch: str | None = None, sha: str | None = None, timeout_min: float | None = None, poll: float = 20, quiet: bool = True, sleep=time.sleep, clock=time.time, runs_fn=None, on_event=None, always_diagnose: bool = False, since: float | None = None) -> dict: """Follow the CI runs of a branch (for one commit when `sha` is given) until all finish or the timeout. A host @@ -399,13 +469,17 @@ def watch(top: str, branch: str | None = None, sha: str | None = None, timeout_m out, and the watch waits up to NO_RUN_MIN for a run from then on that is not skipped (a draft's run the same command pushed can start after `since` and be skipped at once). Once one appears, only the runs from then on are reported; when none does (a repository whose CI does not run on `ready`), the commit's other runs are. - -> {"state": passed|failed|timeout|none, "runs": [...], "diagnoses": [...], ...}""" + `timeout_min`: None takes the repository's own limit (watch_minutes). A GitHub job that has waited QUEUE_MIN + minutes for a runner while nothing else of the commit runs (_stuck) is told once to on_event, with its next + action, and named in a result that reaches the limit. -> {"state": passed|failed|timeout|none, "runs": [...], + "diagnoses": [...], "stuck": [...] (a timeout with a job that waits for a runner), ...}""" from . import cistatus runs_fn = runs_fn or cistatus.runs_for branch = branch or core.gitout(top, "branch", "--show-current") sha = (sha or core.gitout(top, "rev-parse", "HEAD"))[:7] + timeout_min = watch_minutes(top) if timeout_min is None else timeout_min start = clock() - seen_any, told, data, runs = False, set(), {}, [] + seen_any, told, data, runs, waits = False, set(), {}, [], {} ident = repo_id(top) while True: since = since or _since(ident, branch, sha) @@ -446,10 +520,17 @@ def again(): # the runs once more with the jobs of those that ended, read once break if not data.get("provider"): # origin is no CI host devkit reads: no run will ever appear return _finish(top, data, branch, sha, runs, "none", start, clock, always_diagnose) + stuck = [] if failing else _stuck(data.get("provider") or "", runs, waits, clock()) + for s in stuck if on_event else []: # an agent's wait hears it once, with the next action, and keeps waiting + if ("stuck", s["id"], s["job"]) not in told: + told.add(("stuck", s["id"], s["job"])) + on_event(f"{stuck_line(s)}: {STUCK_ACTION}") if waited >= timeout_min or (not seen_any and not failing and waited >= NO_RUN_MIN): - # no run after 5 minutes: CI does not run for this push + # no run after 5 minutes: CI does not run for this push. At the limit, a job that still waits for a + # runner is named instead of "still running" (a busy queue of GitHub's own runners looks the same, so + # the watch follows the run to its limit rather than ending at the first sign) return _finish(top, data, branch, sha, runs, "timeout" if seen_any or failing else "none", start, clock, - always_diagnose) + always_diagnose, stuck=stuck) if not quiet: from . import ui live = [r for r in runs if r.get("status") not in DONE] @@ -463,7 +544,7 @@ def _before(run: dict, since: float) -> bool: return bool(run.get("started")) and run["started"] < since -def _finish(top, data, branch, sha, runs, state, start, clock, always_diagnose=False) -> dict: +def _finish(top, data, branch, sha, runs, state, start, clock, always_diagnose=False, stuck=None) -> dict: """The result of a watch. Each run carries how it ended and whether this watch is the first to report it (new); `repeat` when no run is new: a result reported before, which record and deliver then leave alone. A final result ends the watches recorded on the commit (`dev ci watches` no longer lists them).""" @@ -478,7 +559,7 @@ def _finish(top, data, branch, sha, runs, state, start, clock, always_diagnose=F "conclusion": word, "new": k in fresh, "url": r.get("url"), "elapsed": round((r.get("elapsed") or 0) / 60, 1)} for r, (word, _), k in zip(runs, ends, keys)], "started": max((r.get("started") or 0 for r in runs), default=0) or None, # how recent the commit's CI is - "diagnoses": [], "repeat": not fresh} + "diagnoses": [], "repeat": not fresh, **({"stuck": stuck} if stuck else {})} # a repeat nobody waits on is not diagnosed (each diagnosis reads a log online); one a joined session still has to # hear is, so its message carries the class and the next action if fresh or always_diagnose or (state in FINAL and _owed(ident, branch, sha)): @@ -529,7 +610,8 @@ def record(top: str, res: dict): audit.record("ci.watch", f"{res.get('repo')}@{res.get('branch')}", detail, res["state"], sha=res.get("sha")) try: from . import progress - title = "CI still running" if res["state"] == "timeout" else f"CI {said(res)}" if _shown(res) else "no CI run" + title = ("CI waits for a runner" if res.get("stuck") else "CI still running") if res["state"] == "timeout" \ + else f"CI {said(res)}" if _shown(res) else "no CI run" progress.notify(f"{title} · {res.get('branch')}", detail[:180]) except Exception: pass @@ -540,6 +622,8 @@ def message(res: dict) -> str: one next action.""" runs = _shown(res) head = f"devkit · CI {said(res)} on {res.get('branch')} @ {res.get('sha')} ({res.get('minutes')} min)" + if res["state"] == "timeout" and res.get("stuck"): + return head + ": " + "; ".join(stuck_line(s) for s in res["stuck"]) + f". Next: {STUCK_ACTION}." if res["state"] == "timeout": return head + ": still running after the watch limit; follow it with dev ci status --watch." if not runs: @@ -990,22 +1074,24 @@ def start_background(top: str, session: str = "", branch: str = "", sha: str = " target = {"top": top, "ref": branch, "sha": sha, "repo_id": repo, "kind": "tag" if _rev(top, f"refs/tags/{branch}") and not _rev(top, f"refs/heads/{branch}") else "branch", **({"since": round(since, 3)} if since else {})} + limit = watch_minutes(top) # the repository's own: its longest chain of job timeouts and the queue try: if lock.exists() and time.time() - lock.stat().st_mtime < 3 * 3600: pid = int((lock.read_text().split() or ["0"])[0]) os.kill(pid, 0) # still watching - register(target, "devkit", agent, sid, pid, 90) + register(target, "devkit", agent, sid, pid, limit) return False except (ValueError, ProcessLookupError, PermissionError, OSError): pass log = open(STATE / "logs" / "ci-watch.log", "a") if (STATE / "logs").exists() else subprocess.DEVNULL p = subprocess.Popen([sys.executable, "-I", "-S", str(core.release_home() / "bin" / "dev"), "ci", "watch", - "--quiet", "--branch", branch, "--sha", sha] + (["--session", session] if session else []) + + "--quiet", "--branch", branch, "--sha", sha, "--timeout", str(limit)] + + (["--session", session] if session else []) + (["--since", f"{since:.3f}"] if since else []), cwd=top, stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True) lock.write_text(f"{p.pid} {int(time.time())}") - register(target, "devkit", agent, sid, p.pid, 90) + register(target, "devkit", agent, sid, p.pid, limit) return True @@ -1312,6 +1398,9 @@ def wait_lines(res: dict, again: str) -> list: runs = _shown(res) summary = ", ".join(f"{_one_line(r.get('name'), 60)} #{r.get('number')} {r.get('conclusion') or r.get('status')}" for r in runs) + if res["state"] == "timeout" and res.get("stuck"): + return [f"CI still running · {where}: " + "; ".join(stuck_line(s) for s in res["stuck"]) + + f"; next: {STUCK_ACTION}; re-arm: {again}"] if res["state"] == "timeout": return [f"CI still running · {where} after {res.get('minutes')} min" + (f" ({summary})" if summary else "") + f": this watch ended first; re-arm: {again}"] @@ -1357,7 +1446,7 @@ def emit(line): if not target: emit(f"CI none · nothing to watch: {why}") return 2 - timeout = float(getattr(a, "timeout", None) or 90) + timeout = float(getattr(a, "timeout", None) or watch_minutes(target["top"])) since = _since(target.get("repo_id") or repo_id(target["top"]), target["ref"], target["sha"]) rid = register(dict(target, **({"since": since} if since else {})), "agent", agent, sid, os.getpid(), timeout, now=clock()) diff --git a/tests/test_ci_watch_limits.py b/tests/test_ci_watch_limits.py new file mode 100644 index 00000000..2d9beaa4 --- /dev/null +++ b/tests/test_ci_watch_limits.py @@ -0,0 +1,109 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""How long a CI watch waits, and when it stops waiting for a job no runner takes. A watch's limit comes from the +repository's own workflows: the longest chain of jobs that need each other, at their timeout-minutes, plus 30 minutes +for the queue, and never under the old 90-minute default; the background watch devkit starts after a push gets it +too. A GitHub job that has waited 30 minutes for a runner while nothing else of its commit runs is told to an agent's +wait at once, with the one next action, and a watch that reaches its limit names it instead of "still running"; a +job waiting for an environment's approval is not taken for one. The watch is host-independent: Claude Code and Codex +sessions follow the same watch, and `dev ci watch --wait` prints the same lines on both. + +Run: python3 -m unittest tests.test_ci_watch_limits -v""" +import os +import sys +import tempfile +import types +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import cistatus, ciwatch # noqa: E402 +from test_ciwatch import Clock, WatchCase # noqa: E402 + +CHAIN = ("name: CI\non: [pull_request]\njobs:\n" + " build:\n runs-on: ubuntu-latest\n timeout-minutes: 20\n steps:\n - run: make\n" + " test:\n needs: build\n runs-on: ubuntu-latest\n timeout-minutes: 45\n steps:\n" + " - run: make test\n" + " package:\n needs: [test]\n runs-on: ubuntu-latest\n timeout-minutes: 30\n steps:\n" + " - run: make dist\n" + " lint:\n runs-on: ubuntu-latest\n timeout-minutes: 10\n steps:\n - run: make lint\n") +NIGHTLY = ("name: nightly\non:\n schedule:\n - cron: '0 3 * * *'\njobs:\n soak:\n runs-on: ubuntu-latest\n" + " timeout-minutes: 300\n steps:\n - run: make soak\n") +UNTIMED = "name: CI\non: [push]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - run: make test\n" + + +def repo_with(**workflows) -> str: + top = tempfile.mkdtemp() + for name, text in workflows.items(): + f = Path(top) / ".github" / "workflows" / f"{name}.yml" + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(text) + return top + + +def gh_run(status="in_progress", jobs=()) -> dict: + """A run as cistatus reads it from gh, with its jobs (name, gh status, gh conclusion).""" + now = 1_800_000_000.0 + r = cistatus.github_run({"databaseId": 7701, "number": 41, "status": status, "workflowName": "ci", + "headBranch": "main", "headSha": "abc1234def", + "url": "https://github.com/acme/api/actions/runs/7701"}, now) + r["jobs"] = [cistatus.github_job({"name": name, "status": st, "conclusion": concl, + "startedAt": "2026-11-19T10:00:00Z" if st != "queued" else None, + "steps": [{"status": "in_progress", "name": "run"}] if st == "in_progress" else [], + "url": f"https://github.com/acme/api/actions/runs/7701/job/{i}"}, now) + for i, (name, st, concl) in enumerate(jobs, 1)] + return r + + +class WatchLimitTests(WatchCase): + def test_a_watch_lasts_the_longest_needs_chain_of_job_timeouts_plus_the_queue(self): + top = repo_with(ci=CHAIN, nightly=NIGHTLY) # build 20 -> test 45 -> package 30, and 30 for the queue + clock = Clock() + res = ciwatch.watch(top, branch="main", sha="abc1234", sleep=clock.sleep, clock=clock, + runs_fn=self.sequence([gh_run(jobs=[("test", "in_progress", None)])])) + self.assertEqual(res["state"], "timeout") + self.assertGreaterEqual(res["minutes"], 125) + self.assertLess(res["minutes"], 127) + + def test_workflows_that_declare_no_job_timeout_keep_the_90_minute_default(self): + self.assertEqual(ciwatch.watch_minutes(repo_with(ci=UNTIMED)), 90) + + def test_the_background_watch_of_a_push_gets_the_derived_limit(self): + top = repo_with(ci=CHAIN) + started = [] + spawn = types.SimpleNamespace(Popen=lambda args, **k: started.append(args) or mock.Mock(pid=os.getpid()), + DEVNULL=-3) + with mock.patch.object(ciwatch, "subprocess", spawn), mock.patch.dict(os.environ, {"DEVKIT_NO_CI_WATCH": ""}): + self.assertTrue(ciwatch.start_background(top, session="claude:s1", branch="main", sha="abc1234")) + self.assertEqual(started[0][started[0].index("--timeout") + 1], "125") + self.assertEqual([w.get("timeout_min") for w in ciwatch.watches()], [125]) + + +class StuckJobTests(WatchCase): + def test_a_job_no_runner_takes_is_named_with_its_next_action_once_nothing_else_of_its_commit_runs(self): + # the deploy job's runs-on names a self-hosted label no runner has; the release job waits for an approval. + # The watch follows the run to its limit (a busy queue of GitHub's own runners looks the same and still ends) + busy = gh_run(jobs=[("unit", "in_progress", None), ("deploy", "queued", None), ("release", "waiting", None)]) + idle = gh_run(jobs=[("unit", "completed", "success"), ("deploy", "queued", None), ("release", "waiting", None)]) + clock, heard = Clock(), [] + start = clock() + res = ciwatch.watch(repo_with(ci=CHAIN), branch="main", sha="abc1234", sleep=clock.sleep, clock=clock, + runs_fn=self.sequence(*[[busy]] * 90, [idle]), # unit runs 40 minutes + on_event=lambda line: heard.append(((clock() - start) / 60, line))) + told = [(at, line) for at, line in heard if "for a runner" in line] + self.assertEqual(len(told), 1, heard) # once, 30 minutes after nothing else ran, not 30 from the start + self.assertTrue(69 <= told[0][0] < 72, told) + self.assertIn("job “deploy” of ci #41 has waited 30 min for a runner", told[0][1]) + self.assertIn("runs-on", told[0][1]) + self.assertEqual(res["state"], "timeout") # the limit, 125 minutes: exit 3, the watch ended before the run + self.assertEqual([(s["job"], s["run"], s["number"]) for s in res["stuck"]], [("deploy", "ci", 41)]) + self.assertRegex(ciwatch.message(res), r"job “deploy” of ci #41 has waited 8\d min for a runner") + last = ciwatch.wait_lines(res, "dev ci watch --wait")[-1] + self.assertTrue(last.startswith("CI still running · "), last) + self.assertRegex(last, r"job “deploy” of ci #41 has waited 8\d min for a runner.*re-arm: dev ci watch --wait") + + +if __name__ == "__main__": + unittest.main() From a8ba558cdc42b962a653d84f0f0b8b8155589e3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:06:17 -0800 Subject: [PATCH 12/52] fix(identity): name a dev command's caller by its call token The tech lead's commands were refused as a crew member's while a member's open call held the same words (dev progress begin while a member waited on a question quoting it), and dev crew ack with a nested dev crew read was refused as not_recipient: devkit guessed the caller from command text. Root cause: identity._find took any open call whose text held the command's words in order (progress._names_args) as the caller, and could not see words an expansion produced, so a member's quoting call outranked the tech lead's own and a nested substitution matched nobody The PreToolUse hook gives every shell call a token (DEVKIT_CALL=.) once its ledger entry holds the nonce's SHA-256 and the session record lists the call; a dev command with a token is the entry's caller when the token is this session's, its agent's and its call shell's (pinned on first use, O_EXCL), the call is open and the process is not detached. A session that stamps tokens refuses a tokenless state change; on Codex a tokenless command may name its lane by CODEX_THREAD_ID, and the root thread maps to the tech lead only after a member's token call showed per-agent thread ids. Without a token, text matching drops a call that provably runs another command and matches nested substitutions whole. Detached spawns drop the token, audit.redact hides it, and identity records carry fixed fields, never the nonce. Verified: dev test run (10 files): 143 passed; dev test prove: the new identity and Codex token tests fail without the change --- lib/devkit/audit.py | 5 + lib/devkit/bugs.py | 3 +- lib/devkit/dashserver.py | 5 +- lib/devkit/hooks.py | 203 +++++++++- lib/devkit/identity.py | 576 ++++++++++++++++++++++++++++- lib/devkit/laneroute.py | 25 ++ lib/devkit/mcp.py | 6 +- lib/devkit/visual/noderun.py | 4 +- lib/devkit/visual/store.py | 2 +- lib/devkit/work.py | 4 +- tests/test_codex_identity_token.py | 220 +++++++++++ tests/test_identity_token.py | 450 ++++++++++++++++++++++ 12 files changed, 1473 insertions(+), 30 deletions(-) create mode 100644 tests/test_codex_identity_token.py create mode 100644 tests/test_identity_token.py diff --git a/lib/devkit/audit.py b/lib/devkit/audit.py index 6b9283c1..9fb038e5 100644 --- a/lib/devkit/audit.py +++ b/lib/devkit/audit.py @@ -76,6 +76,8 @@ # Every rule runs in linear time: no nested unbounded quantifiers, and a bounded length wherever a match could # otherwise scan far from each starting point. _RULES = [ + # devkit's own call token (identity.CALL_VAR): dead once its call closes, never kept + (r"\bDEVKIT_CALL=[A-Za-z0-9_.-]+", "DEVKIT_CALL=" + MARK), # a private key loses its whole body, up to its END line (or the end of the text when it was cut); PGP keys end # their header with BLOCK (r"-----BEGIN (?P[A-Z0-9 ]*)PRIVATE KEY(?P(?: BLOCK)?)-----" + _NOT_DONE + @@ -1771,6 +1773,9 @@ def settings() -> dict: "layer": "ref.layer", # dev ext: the layer a change or drift is in (team, user, project, retired) # peers.py: the claimed resource, the sessions a message or an escalation went to (their keys), and its kind "resource": "ref.resource", "recipients": "ref.recipients", "kind": "ref.kind", + # identity.py's records of a call's caller: the agent of the session, the command's parents up to its agent, and + # the lane variable and Codex thread it carried + "host_agent": "ref.agent", "ancestors": "ref.ancestors", "lane_var": "ref.lane_var", "thread": "ref.thread", } RAISE = {"tampered": "critical"} # a caller's outcome word that makes the record more severe EVIDENCE_KEYS = {p.split(".", 1)[1] for p in EXTRAS.values() if p.startswith("evidence.")} diff --git a/lib/devkit/bugs.py b/lib/devkit/bugs.py index 00f1f131..4353ac39 100644 --- a/lib/devkit/bugs.py +++ b/lib/devkit/bugs.py @@ -3238,10 +3238,11 @@ def _start_send() -> bool: return False try: (core.STATE / "logs").mkdir(parents=True, exist_ok=True) + from . import identity with open(core.STATE / "logs" / "sync.log", "a") as log: # the child keeps its own descriptor child = subprocess.Popen([sys.executable, "-I", "-S", str(core.release_home() / "bin" / "dev"), "bug", "sync"], stdin=subprocess.DEVNULL, stdout=log, stderr=log, - start_new_session=True, close_fds=True) + start_new_session=True, close_fds=True, env=identity.detached_env()) except (OSError, ValueError): return False _write_json(path, {"pid": child.pid, "ts": now}) diff --git a/lib/devkit/dashserver.py b/lib/devkit/dashserver.py index 8b8f1107..73534b54 100644 --- a/lib/devkit/dashserver.py +++ b/lib/devkit/dashserver.py @@ -39,7 +39,7 @@ from pathlib import Path from urllib.parse import parse_qs, quote, urlsplit -from . import core +from . import core, identity API = "/api/v1" POLL_SECONDS = 2.0 # the watcher looks at modification times this often (it is also the debounce) @@ -800,7 +800,8 @@ def start() -> dict: with open(log_file(), "a") as log: proc = subprocess.Popen([sys.executable, "-I", "-S", "-c", _SERVE_CODE, lib, "devkit.dashserver", "serve", "--fd", str(sock.fileno())], - pass_fds=(sock.fileno(),), env=env, cwd=str(state_file().parent), + pass_fds=(sock.fileno(),), env=identity.detached_env(env), + cwd=str(state_file().parent), stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True) _CHILDREN[proc.pid] = proc finally: diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 19217b6c..2ea23dc9 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -14,6 +14,7 @@ from __future__ import annotations import copy +import hmac import io import json import re @@ -89,9 +90,12 @@ def _spawn(args, logname="sync.log"): """Detached background `dev …` so the hook returns immediately. It runs the release install.json pins (core.release_home): a session that still runs an older copy starts the installed release, never itself.""" # The child gets its own copy of the log's descriptor; ours closes once it is started (an open one warns at exit). + # It never carries a call token: a detached worker acts for no call (identity.detached_env). + from . import identity with open(STATE / "logs" / logname, "a") as log: subprocess.Popen([sys.executable, "-I", "-S", str(core.release_home() / "bin" / "dev"), *args], # its shebang - stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True) + stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, close_fds=True, + env=identity.detached_env()) def _older_copy_notice(agent: str, sid: str, what: str) -> str: @@ -1527,9 +1531,13 @@ def _close_call(data: dict): _log(f"edit record drop: {traceback.format_exc()[-300:]}") if data.get("tool_name") in SHELL_TOOLS or data.get("tool_name") == "apply_patch": try: - from . import progress - if data.get("tool_name") in SHELL_TOOLS or progress.call_entry(data).get("agent") == "codex": + from . import identity, progress + entry = progress.call_entry(data) + if data.get("tool_name") in SHELL_TOOLS or entry.get("agent") == "codex": progress.call_closed(data) + if data.get("tool_name") in SHELL_TOOLS and entry.get("agent") and data.get("tool_use_id"): + # its token dies with it: the pin goes, and the session record lists the call as closed + identity.note_closed(entry["agent"], str(data.get("session_id") or ""), str(data["tool_use_id"])) except Exception: _log(f"ledger close: {traceback.format_exc()[-300:]}") @@ -1549,8 +1557,115 @@ def _rewrite(agent: str, updated: dict) -> dict: # characters neither bash nor zsh gives a meaning, and not starting with = or ~ (zsh's =(…) and =cmd, the home folder). # Each word ends at a space, a tab or the end of the command, so no word runs into another. _PLAIN_WORD = re.compile(r"""[ \t]*('[^']*'|"[^"$`\\]*"|[A-Za-z0-9_./:@%+,-][A-Za-z0-9_./:@%+,=-]*)(?=[ \t]|\Z)""") -# the variables laneroute.route, _watch_route and _speaker_route put in front of a devkit call -_DEVKIT_VARIABLE = re.compile(r"(?:DEVKIT_FROM_AGENT|DEVKIT_SESSION|DEVKIT_SPEAKER)=[A-Za-z0-9_.:-]+\Z") +# the variables laneroute.route, _watch_route, _speaker_route and the call token put in front of a devkit call +_DEVKIT_VARIABLE = re.compile(r"(?:DEVKIT_FROM_AGENT|DEVKIT_SESSION|DEVKIT_SPEAKER|DEVKIT_CALL)=[A-Za-z0-9_.:-]+\Z") +_SH_FAMILY = frozenset({"bash", "zsh", "sh"}) # the shells that know `export …; readonly …;` + + +def _sh_family(agent: str, data: dict) -> bool: + """Does the call's shell read `export` and `readonly`? Claude Code's Bash runs bash or zsh; a Codex exec runs the + `shell` its input names, else the user's login shell (fish and nushell have no `readonly`).""" + if agent != "codex": + return True + inp = data.get("tool_input") if isinstance(data.get("tool_input"), dict) else {} + shell = inp.get("shell") or os.environ.get("SHELL") or "/bin/zsh" + return os.path.basename(str(shell)) in _SH_FAMILY + + +def _token_skipped(agent: str, data: dict, why: str): + """A shell call that goes out without its call token: audited (calls.token-skipped). In a session whose calls carry + tokens, its state changes are then refused, with the fix to run it again (identity.NO_TOKEN).""" + try: + from . import audit + audit.record("calls.token-skipped", str(data.get("tool_use_id") or "-")[:80], why, "flagged", + tool_use_id=str(data.get("tool_use_id") or "")[:80], session=str(data.get("session_id") or "")[:80], + host_agent=agent, lane=str(data.get("agent_id") or "main")[:80]) + except Exception as e: + _swallowed("pre-tool", e) + + +def _with_token(agent: str, data: dict, new, token: str): + """The shell call's input (`new`, the routed one, else its own) with the call token in front of its command, or None + when this call's form cannot carry one: `export DEVKIT_CALL=; readonly DEVKIT_CALL;` in an sh-family shell + where Codex never asks (and always on Claude Code), the variable-list form `DEVKIT_CALL= dev …` for one plain + devkit call where Codex asks or the shell is another one. A token never costs a rewrite Codex would apply + (_codex_may_rewrite), and never makes one either: where Codex asks, `allow` would skip the developer's approval, + so only a call devkit rewrites anyway (routed or stamped) carries it. The leading space keeps the stamped command + out of the shell's history.""" + from . import identity + if agent == "codex" and new is None and not _codex_never_asks(data): + return None + base = new or data.get("tool_input") or {} + cmds = _shell_inputs({"tool_name": data.get("tool_name"), "tool_input": base}) + if len(cmds) != 1 or not cmds[0][0]: + return None + key, cmd = cmds[0] + var = identity.CALL_VAR + if agent == "codex" and not _codex_never_asks(data) or not _sh_family(agent, data): + if not _plain_devkit_call(cmd): + return None + at = 0 # after devkit's own variables, right before `dev` + while True: + m = _PLAIN_WORD.match(cmd, at) + if not m or not _DEVKIT_VARIABLE.match(m.group(1)): + break + at = m.end() + lead = cmd[:at].strip(" \t") + out = {**base, key: f"{lead + ' ' if lead else ''}{var}={token} {cmd[at:].lstrip(' ' + chr(9))}"} + else: + out = {**base, key: f" export {var}={token}; readonly {var}; {cmd}"} + return out if agent != "codex" or _codex_may_rewrite(data, out) else None + + +def _stamped_token(agent: str, data: dict, new, token: str, digest: str): + """The input a shell call goes out with when it carries its call token, None when it carries none (it then goes + out as `new`, the routed input, or as it is). The token goes out only once its ledger entry holds the nonce's hash + (read back) and the session record lists the call under its hold (identity.note_opened, which also marks the + session as one whose calls carry tokens, even for a Codex call whose form cannot carry one). A failure stamps no + token and is audited, and so is a rewrite that could not take the token.""" + from . import identity, progress + sid, tid = str(data.get("session_id") or ""), str(data.get("tool_use_id") or "") + if not token: + return None + tokened = _with_token(agent, data, new, token) + if tokened is None: + if new is not None: + _token_skipped(agent, data, "the rewrite would not carry the token: it goes out without it") + identity.note_opened(agent, sid) + return None + entry = progress.call_entry(data) + ttl = identity.codex_ttl(data.get("tool_input")) if agent == "codex" else None + if not hmac.compare_digest(str(entry.get("token_sha256") or ""), digest) or \ + ttl is not None and entry.get("ttl") != ttl: + _token_skipped(agent, data, "its call ledger entry does not hold the token") + return None + if not identity.note_opened(agent, sid, tid): + _token_skipped(agent, data, "the session record is busy") + return None + return tokened + + +def _identity_strip_advice(agent: str, data: dict) -> list: + """A crew member's command that strips or sets devkit's identity variables (env -u, env -i, unset, an assignment + to DEVKIT_CALL or CODEX_THREAD_ID): advice, and an audit record (caller.spoof-suspect). A typo guard, not a + control: the call token's bindings are what holds (identity._verify).""" + from . import laneroute + cmds = _shell_inputs(data) + if not data.get("agent_id") or len(cmds) != 1: + return [] + found = laneroute.identity_strips(cmds[0][1]) + if not found: + return [] + try: + from . import audit + audit.record("caller.spoof-suspect", str(data.get("agent_id"))[:80], ", ".join(found)[:300], "flagged", + tool_use_id=str(data.get("tool_use_id") or "")[:80], session=str(data.get("session_id") or "")[:80], + host_agent=agent, lane=str(data.get("agent_id"))[:80]) + except Exception as e: + _swallowed("pre-tool", e) + return [f"this command changes devkit's identity variables ({', '.join(found)}): devkit names who runs a " + "command by its call token, so a dev call that drops or sets them acts as nobody; run dev commands as " + "they are, in your lane"] def _plain_devkit_call(cmd: str) -> bool: @@ -2036,7 +2151,9 @@ def codex_rollout(transcript) -> tuple: p = rec.get("payload") if isinstance(rec, dict) and isinstance(rec.get("payload"), dict) else {} item = p.get("item") if rec.get("type") == "event_msg" and p.get("type") == "item_completed" else None if isinstance(item, dict) and item.get("type") == "CommandExecution" and item.get("id"): - items[str(item["id"])] = item + # the thread Codex ran it on, from its own record (_codex_thread_mismatch) + items[str(item["id"])] = dict(item, thread_id=p["thread_id"]) if isinstance(p.get("thread_id"), str) \ + else item version = _codex_version(first) return items, bool(items) or writer or version >= CODEX_RECORDS_SINCE or version == (0, 0, 0) @@ -2200,6 +2317,7 @@ def _codex_call(agent: str, data: dict) -> tuple: try: items, writes = _rollout_once(read, data.get("transcript_path")) item = items.get(str(data.get("tool_use_id") or "")) + _codex_thread_mismatch(agent, data, item) data["_codex_command_executed"] = _codex_executed(item) observed = (state.read(_codex_pending(str(data.get("session_id") or ""))) or {}).get("observed") or [] data["_codex_lesson_failure"] = _codex_lesson_failure(item) and _codex_observation_key(data) not in observed @@ -2210,6 +2328,28 @@ def _codex_call(agent: str, data: dict) -> tuple: return outcome, settled +def _codex_thread_mismatch(agent: str, data: dict, item): + """A Codex exec whose dev command resolved its caller by the call's token (its pin exists) ran on a thread that is + not that caller's, by the rollout's own CommandExecution record: audited caller.mismatch, after the fact (a main + token used in a member's write_stdin into the tech lead's exec shows here). The tech lead's thread is the + session's; a member's is its own, or the session's where Codex shares it.""" + from . import identity, progress + sid, tid = str(data.get("session_id") or ""), str(data.get("tool_use_id") or "") + thread = str((item or {}).get("thread_id") or "") if isinstance(item, dict) else "" + if agent != "codex" or not thread or not sid or not tid or not identity.pin_path(sid, tid).exists(): + return + caller = str(progress.call_entry(data).get("caller") or "main")[:80] + if thread in ((sid,) if caller == "main" else (caller, sid)): + return + try: + from . import audit + audit.record("caller.mismatch", tid[:80], f"its dev command resolved {caller}, and Codex ran the command on " + f"thread {thread[:80]}", "flagged", tool_use_id=tid[:80], session=sid[:80], host_agent=agent, + thread=thread[:80]) + except Exception as e: + _swallowed("post-tool", e) + + def _codex_pending(sid: str) -> Path: return STATE / "codex-pending" / f"{re.sub(r'[^A-Za-z0-9_.-]', '_', sid)[:80]}.json" @@ -3061,11 +3201,20 @@ def _pre_tool(agent: str, data: dict): progress.bind(agent, data) except Exception: _log(f"pre-tool bind {agent}: {traceback.format_exc()[-300:]}") + token = digest = "" # the call token this shell call gets, and its nonce's hash in the ledger entry if tool in SHELL_TOOLS: # the call ledger: who makes this call + from . import identity + token, digest = identity.new_call_token(str(data.get("tool_use_id") or "")) try: - progress.call_opened(agent, data) + progress.call_opened(agent, data, token_sha256=digest) + ttl = identity.codex_ttl(data.get("tool_input")) if agent == "codex" and token else None + if ttl is not None: # the token dies at the exec's yield, whenever its PostToolUse comes + progress.call_note(data, ttl=ttl) except Exception: _log(f"pre-tool ledger {agent}: {traceback.format_exc()[-300:]}") + if token: + _token_skipped(agent, data, "its call ledger entry could not be written") + token = digest = "" rule = _lesson_rule_hit(agent, data) # before any other lesson this call shows is recorded skip = (rule.get("lesson"),) if rule else () # the rule said its lesson: not again as a pitfall advice = _advice(agent, "crew-limits", lambda: _crew_limits_advice(agent, data)) + \ @@ -3095,19 +3244,22 @@ def _pre_tool(agent: str, data: dict): stamped = None if routed else _routed(agent, "speaker", data, lambda: _speaker_route(data, agent), held) unroutable = [] if routed or stamped else [UNROUTED_LANE_CALL] if held and data.get("agent_id") else \ _advice(agent, "crew-lane", lambda: _unroutable_lane_advice(agent, data)) - advice += unroutable + advice += unroutable + _advice(agent, "identity", lambda: _identity_strip_advice(agent, data)) for line in advice: _log(f"pre-tool {agent} advice: {line[:160]}") _post_codex_advice(agent, data, advice, bool(unroutable)) - if routed or stamped: - if stamped: # a call that only gains who runs it records what every other call records + final = _stamped_token(agent, data, routed or stamped, token, digest) if tool in SHELL_TOOLS else None + if routed or stamped or final: + if not routed: # a call that only gains who runs it records what every other call records try: _watch_writes(agent, data) + progress.edit_opened(agent, data) except Exception as e: _swallowed("pre-tool", e) - _log(f"progress {agent}: a {'subagent' if data.get('agent_id') else 'main session'} call goes to its " - f"{'lane' if data.get('agent_id') else 'consumer, stamped main'}") - out = _with_context(agent, _rewrite(agent, routed or stamped), data, skip, advice) + if routed or stamped: + _log(f"progress {agent}: a {'subagent' if data.get('agent_id') else 'main session'} call goes to its " + f"{'lane' if data.get('agent_id') else 'consumer, stamped main'}") + out = _with_context(agent, _rewrite(agent, final or routed or stamped), data, skip, advice) print(json.dumps({"hookSpecificOutput": out}, ensure_ascii=False)) return if tool in ("Agent", "Task"): # subagent briefs get the skills their work requires, on the named description @@ -3737,8 +3889,26 @@ def post_tool(agent: str): handoff repository right after a delivery event (commit, push, merge, tag, PR, release); at a call that usually ends the turn, show the status block the final message opens with; in the main session, name the members that finished, and those that finished with background work still running (crew_notices).""" + post_tool_payload(agent, _stdin_json()) + + +def _without_token(data: dict) -> dict: + """The payload with the call token the PreToolUse hook put in front of its command taken out again, so nothing + devkit keeps of a call's text holds it (identity.strip_token).""" + from . import identity + inp = data.get("tool_input") + if isinstance(inp, dict) and data.get("tool_name") in SHELL_TOOLS: + for k in ("command", "cmd"): + if isinstance(inp.get(k), str) and identity.CALL_VAR in inp[k]: + data = dict(data, tool_input=dict(inp, **{k: identity.strip_token(inp[k])})) + inp = data["tool_input"] + return data + + +def post_tool_payload(agent: str, data: dict): + """PostToolUse on a payload already read (post_tool).""" from . import progress - data = _stdin_json() + data = _without_token(data) if agent == "codex": # steering must reach continuity before a failed/deferred result or compaction try: progress.note_midturn(agent, data) @@ -3828,7 +3998,7 @@ def post_tool_failure(agent: str): that failed or was interrupted has ended: it leaves the call ledger. The same failure twice in a row stops the agent with the root-cause paragraph (_patch_loop, _root_cause): it takes the best lessons of the output recall, after the recall resolved their earlier showings, and they count as shown on the output channel.""" - _tool_failed(agent, _stdin_json(), "PostToolUseFailure") + _tool_failed(agent, _without_token(_stdin_json()), "PostToolUseFailure") def _tool_failed(agent: str, data: dict, event: str, before: str = ""): @@ -4221,7 +4391,8 @@ def pct(label, v): CAPTURE_CUT = 200 # characters kept of prompts, tool input and output, the last assistant message and a # compaction's summary CAPTURE_CUT_KEYS = ("prompt", "tool_input", "tool_response", "last_assistant_message", "compact_summary") -_CAPTURE_TOKEN = re.compile(r"(?i)\bbearer\s+[a-z0-9._~+/=-]{8,}|\beyJ[a-z0-9_-]{8,}\.[a-z0-9_-]{8,}\.[a-z0-9_-]{4,}") +_CAPTURE_TOKEN = re.compile(r"(?i)\bbearer\s+[a-z0-9._~+/=-]{8,}|\beyJ[a-z0-9_-]{8,}\.[a-z0-9_-]{8,}\.[a-z0-9_-]{4,}|" + r"(?-i:(?<=\bDEVKIT_CALL=)[A-Za-z0-9_.-]+)") # and devkit's own call token _CAPTURE_SECRET_KEY = re.compile(r"(?i)token|secret|passw|api[_-]?key|authorization|cookie|credential") diff --git a/lib/devkit/identity.py b/lib/devkit/identity.py index 9185968c..025df89d 100644 --- a/lib/devkit/identity.py +++ b/lib/devkit/identity.py @@ -30,20 +30,63 @@ (a Codex crew, whose rewrite may carry no lane mark, waits with one command for every member). Codex marks a spawned agent's hooks with its agent_id, but the main thread's hooks carry none, so a Codex speaker that -devkit takes for main is not verified (`verified` False); progress.caller keeps reporting Codex as `unverified`. +devkit takes for main by these rules is not verified (`verified` False); progress.caller reports it as `unverified`. + +The call token comes before every rule above (rule 0). The PreToolUse hook gives each shell call a token, +DEVKIT_CALL=., after its call ledger entry holds the nonce's SHA-256 and the session record lists +the call as one the hook opened (call_token). A `dev` command that carries one is the entry's caller (`main` or the +member's agent id, how "token") when all of these hold (_verify): the entry is in the folder of the session this +process runs in and names it, it is open and listed, its hash matches; the nearest agent process above this command is +the entry's; the call's shell (the process right below that agent) is the one the token's first use pinned, with the +same start time; this command runs in that shell's process session (a detached process never does). A command +resolves its token once and keeps the verdict for its lifetime. A failed token refuses a state change +(STATE_CHANGING) and lets a read or a wait fall to the rules above. In a session whose hook stamps tokens, a state +change without one is refused (caller.no-token): text matching never decides it. On Codex, a call without a token +may still name its lane by CODEX_THREAD_ID (rule 0b); the root thread maps to main only after a member's token call +showed that members carry thread ids of their own. """ from __future__ import annotations +import hashlib +import hmac +import json import os import re import sys import threading import time -from dataclasses import dataclass +from dataclasses import dataclass, field LANE_VAR = "DEVKIT_FROM_AGENT" # a crew member's lane call, stamped by the PreToolUse hook SPEAKER_VAR = "DEVKIT_SPEAKER" # "main": the main session's own `dev watch` or `dev session` call, stamped likewise +CALL_VAR = "DEVKIT_CALL" # the call token: ., stamped on every shell call by the PreToolUse hook +THREAD_VAR = "CODEX_THREAD_ID" # the Codex thread that runs a command, exported by Codex LAUNCH_WAIT = 900 # seconds a launch whose agent has not started still counts as someone who may speak +CALLS_KEPT = 512 # tool_use_ids a session record keeps of its open calls, and of its closed ones +_TOKEN = re.compile(r"[A-Za-z0-9_-]{1,120}\.[A-Za-z0-9_-]{22}") +_TID = re.compile(r"[A-Za-z0-9_-]{1,120}") + +# The commands that use acting_lane, require or progress.caller for authority: a call token decides them, and in a +# session whose hook stamps tokens nothing else does. Everything else (watch, crew read, inbox and decisions, session +# read and ls, progress status and history) is a read or a wait. +STATE_CHANGING = { + "progress": frozenset({"start", "step", "block", "done", "note", "add", "assign", "begin", "reopen", "skip", + "confirm", "order"}), + "crew": frozenset({"ask", "answer", "decide", "withdraw", "mode", "delegate", "decline", "route", "ack"}), + "session": frozenset({"tell", "ask", "answer", "claim", "escalate", "ack"}), + "task": frozenset({"start", "done", "release"}), +} + +STALE = ("this call's identity has ended (its call closed, or ran past its time limit); a background command's " + "identity ends when it starts: run it in the foreground") +NO_TOKEN = ("devkit could not verify this call's identity (it carries no call token): run it again as a command of " + "its own") +BAD_TOKEN = "devkit could not verify this call's identity (its call token does not match its call): run it again" +FOREIGN = "this call's token belongs to another session or agent, so it names nobody here: run it again in your own call" +FOREIGN_USE = "this call's token is in use by another shell, so it names nobody: run it again in your own call" +PLAIN_CALL = ("devkit could not verify which Codex thread runs this: run it as one plain dev command (no pipeline, " + "script or other command around it)") +CONFLICT = "this call's token and its lane variable or thread name different callers" @dataclass(frozen=True) @@ -51,8 +94,9 @@ class Speaker: agent: str # "claude" | "codex" | "human" session: str # the session id ("shell-" for a developer's shell) lane: str # "main" | a crew member's agent_id | "" (not known) - how: str # "payload" | "stamped" | "ledger" | "sole" | "human" | "unknown" + how: str # "payload" | "token" | "thread" | "stamped" | "ledger" | "sole" | "human" | "unknown" verified: bool # False for a Codex main session (its hooks carry no mark) and for anyone devkit cannot name + why: str = field(default="", compare=False) # why devkit refuses this caller a state change ("" when it does not) def key(self) -> str: return f"{self.agent}:{self.session}" @@ -75,6 +119,11 @@ class _Found: ledger: str # who the ledger names: "main", a member's agent id, or "" (nobody, or main in a guessed session) members: tuple = () # the members whose open calls hold this command + @property + def refusal(self) -> str: + """Why a state change is refused to this caller (a failed or missing call token), "" when it is not.""" + return self.speaker.why + def from_hook(agent: str, data: dict) -> Speaker: """Who a hook acts for, from its own payload: `agent_id` is a crew member's lane, its absence the main session.""" @@ -96,8 +145,19 @@ def acting_lane(cwd: str | None = None) -> str: rule 5 ("main", a member's agent id, or "" when devkit cannot tell). IdentityError when the open calls of several members hold this command and no lane mark names one of them: the speaker is then the most restricted of them, which is right for a permission (every one of them is a member) but would read or write in another member's lane; - the refusal names them all.""" + the refusal names them all. IdentityError too when the call's token failed or is missing where one is due + (_Found.refusal), and when devkit cannot name the caller while a crew member may be speaking: an unknown caller + never acts as the tech lead.""" got = _find(cwd, None, None, settle=False) + if got.refusal: + raise IdentityError(got.refusal) + if got.speaker.how == "unknown": + from . import progress + if state_changing(sys.argv[1:]) and _may_speak(progress, got.agent, got.speaker.session, None, None): + raise IdentityError("devkit cannot tell who runs this command, and only the tech lead or a crew member " + "in its own lane may: run the dev command as a command of its own, not through a " + "script or another shell") + return "" if got.speaker.how != "ledger" or len(got.members) < 2: return got.speaker.lane from . import crew, progress @@ -113,6 +173,11 @@ def require(sp: Speaker, *, main: bool = False, what: str = "") -> Speaker: """`sp`, or IdentityError: devkit cannot tell who speaks; with `main`, a crew member, or the developer's own terminal, which has no agent session to act for. `what` says what the command does ("sends to other sessions").""" does = what or "runs this command" + if sp.why and main: + raise IdentityError(f"only the tech lead {does}, and {sp.why}; a crew member asks them with dev crew ask " + "\"…\"") + if sp.why: + raise IdentityError(f"devkit refuses who {does}: {sp.why}") if sp.how == "unknown": raise IdentityError(f"devkit cannot tell whether the tech lead or a crew member {does}: run the dev command " "as a command of its own, not in a pipeline, a script or another shell") @@ -131,6 +196,13 @@ def verified_lane(lane: str, cwd: str | None = None, now: float | None = None) - ledger shows that member at work: without one of its calls open, the call has no lane identity and acts as no one. Codex selects its session by the lane and refuses one that belongs to none (progress.resolve_session).""" from . import progress + got = _find(cwd, None, now, settle=False) + if got.speaker.how == "token": + if got.speaker.lane != lane: + raise IdentityError(f"{CONFLICT}: run the dev command as a command of your own, in your lane") + return lane + if got.refusal: + raise IdentityError(got.refusal) agent, sid, how = progress.resolve_session(cwd, sys.argv[1:]) if agent == "codex": return lane @@ -179,9 +251,28 @@ def _find(cwd=None, argv=None, now=None, exact: bool = False, settle: bool = Tru agent, sid, how = progress.resolve_session(cwd, args) if how == "shell": return _Found(Speaker("human", sid, "", "human", True), agent, how, (), "") + changes = state_changing(args) + token = _token_verdict(agent, sid, args, now) + if token is not None and token.caller: # rule 0: the call token names its caller + members = (token.caller,) if token.caller != "main" else () + return _Found(Speaker(agent, sid, token.caller, "token", True), agent, how, (token.tid,), token.caller, + members) + if token is not None and changes: + return _Found(Speaker(agent, sid, "", "unknown", False, token.why), agent, how, (), "") + if token is None and agent == "codex": # rule 0b: the Codex thread that runs the command + thread = _thread_rule(agent, sid) + if thread: + return _Found(Speaker(agent, sid, thread, "thread", True), agent, how, (), thread, + (thread,) if thread != "main" else ()) + if token is None and changes and _token_session(agent, sid): + _no_token(agent, sid, args) + why = PLAIN_CALL if agent == "codex" else NO_TOKEN + return _Found(Speaker(agent, sid, "", "unknown", False, why), agent, how, (), "") verified_main = agent != "codex" open_ = progress.open_calls(sid, now) - hits = [c for c in open_ if (_typed_exactly(c, args) if exact else progress._names_args(c, args))] + hits = [c for c in open_ if (_typed_exactly(c, args) if exact else + progress._names_args(c, args) or _runs_parsed(c, args))] + hits = [c for c in hits if not _ran_elsewhere(c, args)] typed = hits if exact else [c for c in open_ if _typed_exactly(c, args)] members = sorted({str(c.get("caller")) for c in hits if c.get("caller") != "main"}) run = None @@ -251,6 +342,481 @@ def _typed_exactly(entry: dict, args: list) -> bool: return re.search(_DEV + r"\s+" + words + _END, str(entry.get("cmd") or "")) is not None +# What a call's text proves when its program is plain: every program in it devkit reads (shellparse.shell_calls), +# and each one either only filters text or is a devkit coordination command that starts no other `dev` command. +_INERT_PROGRAMS = frozenset({"cd", "pushd", "popd", "tail", "head", "grep", "egrep", "fgrep", "rg", "wc", "cat", "jq", + "sort", "uniq", "cut", "tr", "echo", "printf", "true", ":"}) +_INERT_DEV = frozenset({"watch", "session", "crew", "progress"}) +_EXPANDS = re.compile(r"[$`*?\[{~]") # a word the shell may turn into other words + + +def _may_be(words: list, args: list) -> bool: + """Could a `dev` call of these words (quotes removed) run with `args`? A word the shell expands may become any + words, so only the words before the first such one are compared.""" + for w, a in zip(words, args): + if _EXPANDS.search(w): + return True + if w != a: + return False + return len(words) == len(args) or any(_EXPANDS.search(w) for w in words[len(args):]) + + +def _ran_elsewhere(entry: dict, args: list) -> bool: + """Does this open call provably not run `dev `, although its text holds the words? It does not when devkit + read every program it runs and each is a filter or a devkit coordination call that cannot be this one: a member's + `dev crew ask "…dev progress begin x…"` quotes the tech lead's command and runs another. A cut or redacted text + proves it only by its own record: it writes no file (reads) and none of its `dev` calls is this one (dev_args). + False whenever devkit cannot tell (an interpreter, a script, a shell fed text, an unreadable command).""" + from . import progress, shellparse + if entry.get("cut") or entry.get("dev_args"): + return bool(entry.get("reads")) and progress.args_hash(args) not in (entry.get("dev_args") or []) + try: + calls = shellparse.shell_calls(str(entry.get("cmd") or ""), None) + except Exception: + return False + if calls is None: + return False + for argv, code in calls: + name = os.path.basename(argv[0]) if argv else "" + if code is not None: + return False + if name == "dev": + words = shellparse.dev_args(argv) + pos = shellparse.dev_words(words) if words is not None else [] + if not pos or pos[0] not in _INERT_DEV or _EXPANDS.search(pos[0]) or _may_be(words, args): + return False + elif name not in _INERT_PROGRAMS: + return False + return True + + +def _expansion_parts(word: str) -> list: + """A word as the shell reads it, split into (True, expansion) and (False, literal text): `$name`, `${…}`, `$(…)` + with its nested parentheses and quotes, and backticks.""" + out, i, lit = [], 0, "" + while i < len(word): + c = word[i] + if c == "`": + j = word.find("`", i + 1) + j = len(word) if j < 0 else j + 1 + elif c == "$" and word[i + 1:i + 2] == "(": + depth, j, quote = 0, i + 1, "" + while j < len(word): + ch = word[j] + if quote: + quote = "" if ch == quote else quote + elif ch in "'\"": + quote = ch + elif ch == "(": + depth += 1 + elif ch == ")": + depth -= 1 + if depth == 0: + break + j += 1 + j = min(j + 1, len(word)) + elif c == "$" and word[i + 1:i + 2] == "{": + j = word.find("}", i) + j = len(word) if j < 0 else j + 1 + elif c == "$" and re.match(r"[A-Za-z_]", word[i + 1:i + 2]): + j = re.match(r"\$[A-Za-z_]\w*", word[i:]).end() + i + elif c == "$" and word[i + 1:i + 2] and word[i + 1] in "0123456789@*#?$!-": + j = i + 2 + else: + lit += c + i += 1 + continue + if lit: + out.append((False, lit)) + lit = "" + out.append((True, word[i:j])) + i = j + if lit: + out.append((False, lit)) + return out + + +def _runs_parsed(entry: dict, args: list) -> bool: + """Does the call run `dev` with these arguments where it typed an expansion in their place, read the way the shell + reads the command (shellparse.shell_calls)? Only for the commands that read or acknowledge the caller's own + messages (progress.EXPANDED_COMMANDS): `dev crew ack REF --sha256 "$(dev crew read REF --json | jq -r .digest)"` + holds the digest only once the substitution ran, and its nested parentheses end no expansion early.""" + from . import progress, shellparse + text = str(entry.get("cmd") or "") + if entry.get("cut") or tuple(args[:2]) not in progress.EXPANDED_COMMANDS or not any(c in text for c in "$`"): + return False + try: + calls = shellparse.shell_calls(text, None) or [] + except Exception: + return False + for argv, _ in calls: + words = shellparse.dev_args(argv) + if not words or len(words) != len(args) or words[:2] != args[:2]: + continue + if all(w == a or re.fullmatch("".join(".*" if e else re.escape(t) for e, t in _expansion_parts(w)), a, re.S) + for w, a in zip(words, args)): + return True + return False + + +# --------------------------------------------------------------------------- the call token +# The hook side (hooks._pre_tool): new_call_token for a shell call, progress.call_opened with its hash, note_opened under +# the session hold, then the stamp. A `dev` command: _token_verdict, once per process (_RESOLVED). + +def state_changing(args) -> bool: + """Does `dev ` change run state (STATE_CHANGING)?""" + from . import shellparse + try: + words = shellparse.dev_words([str(a) for a in args or []]) + except Exception: + return False + return len(words) > 1 and words[1] in STATE_CHANGING.get(words[0], ()) + + +def new_call_token(tid) -> tuple: + """(DEVKIT_CALL's value, the SHA-256 hex digest of its nonce) for a shell call's tool_use_id; ("", "") for an id a + token cannot carry. The nonce is 128 random bits, never stored.""" + import secrets + if not isinstance(tid, str) or not _TID.fullmatch(tid): + return "", "" + nonce = secrets.token_urlsafe(16) + return f"{tid}.{nonce}", hashlib.sha256(nonce.encode()).hexdigest() + + +def parse_token(value): + """(tool_use_id, nonce) of a DEVKIT_CALL value, or None for anything else: rejected, never cleaned up.""" + if not isinstance(value, str) or not _TOKEN.fullmatch(value): + return None + tid, _, nonce = value.rpartition(".") + return (tid, nonce) if tid and not tid.startswith(".") else None + + +def pin_path(sid: str, tid: str): + """The file that pins a token to the shell of its first use: CALLS//..pin (a dot-file: no reader of + the ledger takes it for an entry).""" + from . import progress + return progress.CALLS / progress._safe_name(sid) / f".{progress._safe_name(tid)}.pin" + + +def detached_env(env=None) -> dict: + """The environment for a process devkit starts detached (start_new_session): `env`, default this process's, + without the call token. Such a worker never acts for the call that started it.""" + return {k: v for k, v in (os.environ if env is None else env).items() if k != CALL_VAR} + + +def strip_token(cmd): + """A shell command without the call token the PreToolUse hook put in front of it, as devkit keeps command text + (the ledger, the records of closed calls, the audit trail, notices).""" + if not isinstance(cmd, str): + return cmd + cmd = re.sub(r"\A ?export DEVKIT_CALL=[A-Za-z0-9_.-]+; readonly DEVKIT_CALL; ", "", cmd) + return re.sub(r"\A((?:DEVKIT_[A-Z_]+=[A-Za-z0-9_.:-]+ )*)DEVKIT_CALL=[A-Za-z0-9_.-]+ ", r"\1", cmd) + + +def codex_ttl(inp: dict): + """The life of a Codex exec call's entry, in seconds, from its own limits: it ends at the exec's yield (five + seconds after `yield_time_ms`) or its `timeout_ms`, never later than progress.CALL_TTL. None when the input + gives neither.""" + from . import progress + limits = [] + for k, extra in (("yield_time_ms", 5.0), ("timeout_ms", 0.0)): + v = (inp or {}).get(k) + if isinstance(v, (int, float)) and not isinstance(v, bool) and v > 0: + limits.append(v / 1000 + extra) + return round(min(limits + [progress.CALL_TTL]), 3) if limits else None + + +def _session_update(path, fn): + from . import state + return state.update(path, fn, create=False) + + +def note_opened(agent: str, sid: str, tid: str = "") -> bool: + """The session record lists `tid` among the calls the hook opened (at most CALLS_KEPT) and is a token session + (call_token). False when the record is busy or missing: the call then gets no token.""" + from . import progress, state + if not tid and _token_session(agent, sid): + return True + + def put(d): + if tid: + d["calls_opened"] = ([t for t in d.get("calls_opened") or [] if t != tid] + [tid])[-CALLS_KEPT:] + d["call_token"] = 1 + try: + _session_update(progress.session_path(agent, sid), put) + except (state.StateBusy, OSError, ValueError): + return False + doc = state.read(progress.session_path(agent, sid)) or {} + return not tid or tid in (doc.get("calls_opened") or []) + + +def note_closed(agent: str, sid: str, tid: str): + """The call ended: its tid moves from the opened calls to the closed ones (at most CALLS_KEPT), and its pin goes.""" + from . import progress, state + try: + pin_path(sid, tid).unlink() + except OSError: + pass + + def put(d): + if tid in (d.get("calls_opened") or []): + d["calls_opened"] = [t for t in d["calls_opened"] if t != tid] + d["calls_closed"] = ([t for t in d.get("calls_closed") or [] if t != tid] + [tid])[-CALLS_KEPT:] + try: + _session_update(progress.session_path(agent, sid), put) + except (state.StateBusy, OSError, ValueError): + pass + + +@dataclass(frozen=True) +class _Verdict: + tid: str + caller: str = "" # who the token names when it holds: "main" or a member's agent id + code: str = "" # the audit action when it fails + why: str = "" # the refusal of a state change + detail: str = "" + ancestors: tuple = () + + +_RESOLVED: dict = {} # {(pid, token, ledger folder, agent, session): _Verdict}: a process resolves its token once +_NOTED: set = set() # the tokenless state changes this process already audited + + +def _forget(): + """Forget the verdicts this process reached (tests: each dev command is a process of its own).""" + _RESOLVED.clear() + _NOTED.clear() + + +def _token_verdict(agent: str, sid: str, args: list, now): + """The verdict on this process's call token, None when it carries none. Reached once per process and kept, so a + long command keeps its caller after its call closed; a failure is audited then.""" + from . import progress + value = os.environ.get(CALL_VAR) + if not value: + return None + key = (os.getpid(), value, str(progress.CALLS), agent, sid) + if key not in _RESOLVED: + _RESOLVED[key] = v = _verify(agent, sid, value, now) + if v.code and (state_changing(args) or v.code not in ("caller.stale-token",)): + _audit_identity(v.code, v, agent, sid, args, "deny" if state_changing(args) else "flagged") + return _RESOLVED[key] + + +def _chain() -> list: + """This process's parents, nearest first, as (pid, command line) (progress._ancestor_pids).""" + from . import progress + pids = progress._ancestor_pids() + lines = (progress._ANCESTRY.get(os.getpid()) or {}).get("args") or {} + return [(p, lines.get(p, "")) for p in pids] + + +def _started(pid) -> str: + """When process `pid` started (`ps -o lstart=`), "" when ps gives no answer: a pid the system reused for another + process has another start time.""" + import subprocess + try: + out = subprocess.run(["ps", "-o", "lstart=", "-p", str(int(pid))], capture_output=True, text=True, timeout=5) + except (OSError, subprocess.SubprocessError, TypeError, ValueError): + return "" + return out.stdout.strip() if out.returncode == 0 else "" + + +def _session_of(pid): + """The process session of `pid` (0: this process), None when the system does not say.""" + try: + return os.getsid(pid) + except OSError: + return None + + +def _read_entry(sid: str, tid: str): + """The ledger entry of call `tid` in session `sid`'s folder only, None when it has none.""" + from . import core, progress + e = core.read_json(progress.CALLS / progress._safe_name(sid) / f"{tid}.json", None) + return e if isinstance(e, dict) else None + + +def _pin(sid: str, tid: str, shell: int, started: str) -> bool: + """Pin the token of call `tid` to its first user's shell (pid and start time): True when this use created the + pin, False when one existed (O_EXCL: of two first uses at once, one wins).""" + path = pin_path(sid, tid) + try: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + return False + except OSError: + return False + with os.fdopen(fd, "w") as fh: + fh.write(json.dumps({"pid": int(shell), "started": started})) + return True + + +def _read_pin(sid: str, tid: str) -> dict: + try: + doc = json.loads(pin_path(sid, tid).read_text()) + except (OSError, ValueError): + return {} + return doc if isinstance(doc, dict) else {} + + +def _verify(agent: str, sid: str, value: str, now) -> _Verdict: + """The checks of rule 0, in order (the module's docstring).""" + from . import core, progress, state + parsed = parse_token(value) + if not parsed: + return _Verdict("", code="caller.mismatch", why=BAD_TOKEN, detail="a malformed call token") + tid, nonce = parsed + sess = state.read(progress.session_path(agent, sid)) or {} + opened, closed = sess.get("calls_opened") or [], sess.get("calls_closed") or [] + entry = _read_entry(sid, tid) + if entry is None: + if tid in opened or tid in closed: + return _Verdict(tid, code="caller.stale-token", why=STALE, detail="its call has closed") + return _Verdict(tid, code="caller.foreign-session", why=FOREIGN, + detail=f"no call of session {str(sid)[:40]} has this token") + if str(entry.get("session")) != str(sid) or str(entry.get("agent")) != str(agent): + return _Verdict(tid, code="caller.foreign-session", why=FOREIGN, detail="its entry names another session") + if (now or time.time()) - (entry.get("ts") or 0) > (entry.get("ttl") or progress.CALL_TTL): + return _Verdict(tid, code="caller.stale-token", why=STALE, detail="its call ran past its time limit") + if tid not in opened: + return _Verdict(tid, code="calls.forged", why=BAD_TOKEN, detail="the hook never opened this call") + want = entry.get("token_sha256") + if not isinstance(want, str) or not hmac.compare_digest(want, hashlib.sha256(nonce.encode()).hexdigest()): + return _Verdict(tid, code="caller.mismatch", why=BAD_TOKEN, detail="the token does not match its entry") + caller = str(entry.get("caller") or "main")[:80] + chain = _chain() + pids = [p for p, _ in chain] + agents = [p for p, line in chain if core.is_agent_process(line)] + owner = entry.get("agent_pid") + above = tuple(pids[:pids.index(owner) + 1] if owner in pids else pids) + if not agents: + return _Verdict(tid, code="caller.stale-token", why=STALE, detail="no agent process runs it (detached)", + ancestors=above) + if isinstance(owner, int): + if agents[0] != owner: + return _Verdict(tid, code="caller.foreign-agent", why=FOREIGN, ancestors=above, + detail=f"its nearest agent process is {agents[0]}, its call's is {owner}") + below = pids[:pids.index(owner)] + mine = _session_of(0) + if mine is None or mine not in {_session_of(p) for p in below or [0]}: + return _Verdict(tid, code="caller.stale-token", why=STALE, ancestors=above, + detail="it runs in a process session of its own (detached)") + shell = below[-1] if below else os.getpid() + started = _started(shell) + if not _pin(sid, tid, shell, started): + pin = _read_pin(sid, tid) + if not any(p == pin.get("pid") and _started(p) == pin.get("started") for p in below): + return _Verdict(tid, code="caller.token-foreign-use", why=FOREIGN_USE, ancestors=above, + detail=f"pinned to shell {pin.get('pid')} ({pin.get('started')}), used from shell " + f"{shell} ({started})") + else: + _unpinned_once(agent, sid, tid, above) + lane = (os.environ.get(LANE_VAR) or "").strip()[:80] + if lane and lane != caller: + return _Verdict(tid, code="caller.conflict", why=CONFLICT, ancestors=above, + detail=f"the token names {caller}, the lane variable {lane}") + if agent == "codex": + clash = _thread_evidence(agent, sid, caller, owner) + if clash: + return _Verdict(tid, code="caller.conflict", why=CONFLICT, ancestors=above, detail=clash) + return _Verdict(tid, caller=caller, ancestors=above) + + +def _unpinned_once(agent: str, sid: str, tid: str, above: tuple): + """A token whose entry names no agent process binds to its session only: audited once per session.""" + from . import progress, state + if (state.read(progress.session_path(agent, sid)) or {}).get("token_unpinned"): + return + try: + _session_update(progress.session_path(agent, sid), lambda d: d.update(token_unpinned=1)) + except (state.StateBusy, OSError, ValueError): + return + _audit_identity("caller.token-unpinned", _Verdict(tid, detail="its call's agent process is not known", + ancestors=above), agent, sid, sys.argv[1:], "flagged") + + +def _thread_evidence(agent: str, sid: str, caller: str, owner) -> str: + """A Codex call whose token holds: CODEX_THREAD_ID must not name another known thread ('' when it agrees, else + the conflict). A member's pinned token call records whether Codex gives members their own thread id (per-agent) + or the root's (shared, which turns the root mapping off for the session for good).""" + from . import progress + thread = (os.environ.get(THREAD_VAR) or "").strip() + if not thread: + return "" + lanes = set(((progress.load_run(agent, sid) or {}).get("agents") or {})) + if caller == "main": + return f"the token names the main thread, CODEX_THREAD_ID the lane {thread[:40]}" if thread in lanes else "" + if thread != caller and thread in lanes: + return f"the token names {caller[:40]}, CODEX_THREAD_ID the lane {thread[:40]}" + if isinstance(owner, int) and thread in (caller, sid): + _record_threads(agent, sid, "per-agent" if thread == caller else "shared") + return "" + + +def _record_threads(agent: str, sid: str, seen: str): + from . import progress, state + path = progress.session_path(agent, sid) + before = (state.read(path) or {}).get("codex_threads") + if before == "shared" or before == seen: + return + try: + _session_update(path, lambda d: d.update(codex_threads=seen) if d.get("codex_threads") != "shared" else None) + except (state.StateBusy, OSError, ValueError): + return + if seen == "shared": + _audit_identity("codex.thread-shared", _Verdict("", detail="a member's command carries the root thread's id: " + "the root thread no longer maps to the tech lead"), + agent, sid, sys.argv[1:], "flagged") + + +def _thread_rule(agent: str, sid: str) -> str: + """Rule 0b, a Codex command without a token: CODEX_THREAD_ID equal to a running lane's agent id is that lane; the + session's own (root) thread is the tech lead only once a member's token call showed members carry thread ids of + their own (codex_threads per-agent). '' otherwise.""" + from . import progress, state + thread = (os.environ.get(THREAD_VAR) or "").strip() + if not thread: + return "" + run = progress.load_run(agent, sid) or {} + lane = (run.get("agents") or {}).get(thread) + if isinstance(lane, dict) and lane.get("state") in ("running", None): + return thread + if thread == sid and (state.read(progress.session_path(agent, sid)) or {}).get("codex_threads") == "per-agent": + return "main" + return "" + + +def _token_session(agent: str, sid: str) -> bool: + """Does the hook stamp call tokens in this session (call_token in its record)?""" + from . import progress, state + return bool((state.read(progress.session_path(agent, sid)) or {}).get("call_token")) + + +def _no_token(agent: str, sid: str, args: list): + key = (os.getpid(), agent, sid, tuple(args)) + if key in _NOTED: + return + _NOTED.add(key) + _audit_identity("caller.no-token", _Verdict("", detail="a state change without a call token in a session whose " + "calls carry one"), agent, sid, args, "deny") + + +def _audit_identity(action: str, v: _Verdict, agent: str, sid: str, args, outcome: str): + """One identity record with its fixed fields: the token's tid, the session and agent, the dev arguments (redacted + and cut like the ledger's text), the parents up to the agent, the lane variable and the Codex thread, and the + outcome. Never the nonce.""" + from . import progress + try: + from . import audit + text = " ".join(["dev"] + [str(a) for a in args or []])[:progress.CALL_TEXT] + audit.record(action, v.tid or "-", v.detail, outcome, tool_use_id=v.tid, session=str(sid)[:80], + host_agent=agent, command=text, ancestors=list(v.ancestors) or [p for p, _ in _chain()][:16], + lane_var=(os.environ.get(LANE_VAR) or "")[:80], thread=(os.environ.get(THREAD_VAR) or "")[:80]) + except Exception: + pass + + # --------------------------------------------------------------------------- this Mac # macOS changes the hostname with the network (`mac-158`, `Mac-158.lan`, `andress-mbp-2` in one day), so devkit names # a Mac by a random id created once in its local state (STATE/machine.json, 0600) and keeps the hostname as a label diff --git a/lib/devkit/laneroute.py b/lib/devkit/laneroute.py index f2869345..e26a2ff1 100644 --- a/lib/devkit/laneroute.py +++ b/lib/devkit/laneroute.py @@ -231,6 +231,31 @@ def holds_lane_call(cmd: str, cwd) -> bool: return bool(calls) and any(kind == "lane" for argv, code in calls for kind, _ in _dev_calls(argv, code)) +# What in a crew member's command strips or sets the variables devkit reads a caller from: the lane variable, the +# call token and Codex's thread id. Read on the text, as a typo guard for the advice (hooks._identity_strip_advice): +# the call token's bindings, not this list, decide who calls. +_IDENTITY_VARS = r"(?:DEVKIT_FROM_AGENT|DEVKIT_CALL|DEVKIT_SPEAKER|DEVKIT_SESSION|CODEX_THREAD_ID)" +_STRIPS = ( + (re.compile(r"\benv\b[^;&|\n]*?\s(?:-u[ \t]*|--unset[= ])(" + _IDENTITY_VARS + r")\b"), "env -u {}"), + (re.compile(r"\benv[ \t]+(?:-[A-Za-z]*i[A-Za-z]*|--ignore-environment|-)(?=[ \t]|$)"), "env -i"), + (re.compile(r"\bunset\b[^;&|\n]*?\b(" + _IDENTITY_VARS + r")\b"), "unset {}"), + (re.compile(r"(?:^|[\s;&|(`])(?:export[ \t]+|declare[ \t]+-x[ \t]+|typeset[ \t]+-x[ \t]+)?" + r"(DEVKIT_CALL|CODEX_THREAD_ID)="), "{}="), +) + + +def identity_strips(cmd: str) -> list: + """The forms in a shell command that strip or set devkit's identity variables: `env -u DEVKIT_FROM_AGENT`, + `env -i`, `unset DEVKIT_CALL`, an assignment to DEVKIT_CALL or CODEX_THREAD_ID. [] for any other command.""" + found = [] + for rx, form in _STRIPS: + for m in rx.finditer(cmd if isinstance(cmd, str) else ""): + text = form.format(*m.groups()) if m.groups() else form + if text not in found: + found.append(text) + return found + + # interpreter code that can call a function it names with a string it builds (getattr, __import__, eval, a variable # call), so a spawn the _SPAWNS table cannot see may hide in it. Per language, and only the builtins: a method # of the same name (re.compile, model.eval) is not one. diff --git a/lib/devkit/mcp.py b/lib/devkit/mcp.py index c4d9acaf..ff14f7da 100644 --- a/lib/devkit/mcp.py +++ b/lib/devkit/mcp.py @@ -25,7 +25,7 @@ import threading import time -from . import core +from . import core, identity # Newest first. The client's version is echoed when it is one of these; otherwise the newest is offered. PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") @@ -503,8 +503,8 @@ def run_dev(argv: list, timeout: float = DEFAULT_TIMEOUT, call: Call = None, pro # -I -S as bin/dev's shebang; -I ignores PYTHONIOENCODING, so -X utf8 keeps the output UTF-8 call.proc = subprocess.Popen([sys.executable, "-I", "-S", "-X", "utf8", str(DEV_BIN)] + [str(x) for x in argv], cwd=cwd or _cwd(), - stdin=subprocess.DEVNULL, stdout=out, stderr=err, env=env, - start_new_session=True) + stdin=subprocess.DEVNULL, stdout=out, stderr=err, + env=identity.detached_env(env), start_new_session=True) except OSError as e: return 127, "", str(e) start, rc = time.monotonic(), None diff --git a/lib/devkit/visual/noderun.py b/lib/devkit/visual/noderun.py index 02db58b3..e759b3ec 100644 --- a/lib/devkit/visual/noderun.py +++ b/lib/devkit/visual/noderun.py @@ -29,6 +29,8 @@ import subprocess import tempfile +from .. import identity + STOP_WAIT = 10 # seconds for a stopped driver to end and close its output @@ -79,7 +81,7 @@ def run(args, stdin: str = "", *, timeout, cwd=None, env=None, tmpdir=None, pref folder = os.path.abspath(tempfile.mkdtemp(prefix=prefix, dir=None if within is None else str(within))) if own \ else str(tmpdir) try: - environ = {**(os.environ if env is None else env), "TMPDIR": folder} + environ = identity.detached_env({**(os.environ if env is None else env), "TMPDIR": folder}) # for no call proc = subprocess.Popen(list(args), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=environ, cwd=str(cwd or folder), start_new_session=True) try: diff --git a/lib/devkit/visual/store.py b/lib/devkit/visual/store.py index 6eec7ef5..22a03caa 100644 --- a/lib/devkit/visual/store.py +++ b/lib/devkit/visual/store.py @@ -554,7 +554,7 @@ def _run_capture(request: dict, cwd) -> dict: folder = tempfile.mkdtemp(prefix="devkit-visual-") try: os.chmod(folder, 0o700) - env = {**os.environ, "TMPDIR": folder} + env = identity.detached_env({**os.environ, "TMPDIR": folder}) # it acts for no call proc = subprocess.Popen([node, str(CAPTURE), "--json"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env, cwd=str(cwd), start_new_session=True) try: diff --git a/lib/devkit/work.py b/lib/devkit/work.py index afc11af3..23c304b4 100644 --- a/lib/devkit/work.py +++ b/lib/devkit/work.py @@ -1330,9 +1330,11 @@ def request_sync(reason: str = "", delay: int = 15): except OSError: out = subprocess.DEVNULL try: + from . import identity subprocess.Popen([sys.executable, "-I", "-S", str(core.release_home() / "bin" / "dev"), "sync", "--quiet", "--offline", "--delay", str(delay)], stdin=subprocess.DEVNULL, stdout=out, stderr=out, - start_new_session=True, close_fds=True) # isolated, as its shebang runs it + start_new_session=True, close_fds=True, # isolated, as its shebang runs it + env=identity.detached_env()) # a detached worker acts for no call finally: if out is not subprocess.DEVNULL: out.close() # the child holds its own copy of the log diff --git a/tests/test_codex_identity_token.py b/tests/test_codex_identity_token.py new file mode 100644 index 00000000..a49b46dd --- /dev/null +++ b/tests/test_codex_identity_token.py @@ -0,0 +1,220 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# The call token on Codex (the CLI and the ChatGPT app): where Codex never asks, every exec carries the token as on +# Claude Code; where it asks, only one plain devkit call does, in its variable-list form, and the token never costs a +# rewrite Codex would apply. A tokenless command may name its lane by CODEX_THREAD_ID, and the root thread maps to the +# tech lead only after a member's token call showed that members carry their own thread id. The payloads are Codex +# 0.167's exec_command (`cmd`, `workdir`, `yield_time_ms`, `timeout_ms`, `shell`), with the thread ids and rollout +# records of tests/codexrollout.py. +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_codex_identity_token -v +import contextlib +import io +import json +import os +import sys +import time +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +import _hermetic # noqa: E402 + +_hermetic.activate() +sys.path.insert(0, str(ROOT / "lib")) + +from devkit import audit, hooks, identity, state # noqa: E402 +from devkit import progress as pg # noqa: E402 +from codexrollout import OTHER, SID, SUB, Rollout # noqa: E402 +from test_identity_token import LANE, TokenCase # noqa: E402 +from test_progress import launch # noqa: E402 + +SUB2 = "01a1c19a-9a8b-7c6d-8e5f-4a3b2c1d0e9f" # a second spawned agent of the same thread +CODEX = 70101 + + +class CodexTokenCase(TokenCase): + agent = "codex" + agent_line = "codex" + never_asks = True + + def setUp(self): + super().setUp() + self.chain = [(70102, "/bin/zsh -lc dev"), (CODEX, "codex")] + self.starts[70102] = "Thu Nov 19 10:00:00 2026" + for p in (mock.patch.object(pg, "_call_agent_pid", lambda: CODEX), + mock.patch.object(hooks, "_codex_never_asks", lambda data: self.never_asks), + mock.patch.dict(os.environ, {"DEVKIT_SESSION": f"codex:{SID}", "SHELL": "/bin/zsh"})): + p.start() + self.addCleanup(p.stop) + (pg.SESSIONS / f"codex-{SID}.json").write_text(json.dumps({"agent": "codex", "session": SID, + "started": time.time()})) + with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): + pg.start("Codex work", plan=["api", "ui"]) + pg.assign("api", "Tank", why="the test's assignment") + launch(SUB, "tank", "Tank: api", sid=SID, agent="codex") + + def exec(self, cmd, aid=None, **inp): + return self.hook(cmd, aid=aid, sid=SID, tool="exec_command", key="cmd", **inp) + + def run_(self, sid=SID, agent="codex"): + return pg.load_run(agent, sid) + + def sess(self): + return state.read(pg.session_path("codex", SID)) or {} + + def thread(self, tid, token="", **env): + return {identity.THREAD_VAR: tid, **env} + + +class CodexStampTests(CodexTokenCase): + def test_codex_rewrite_carries_call_token_when_never_asks(self): + _, token, new = self.exec("git status") + self.assertTrue(new.startswith(f" export DEVKIT_CALL={token}; readonly DEVKIT_CALL; "), new) + self.assertEqual(self.last.get("permissionDecision"), "allow") + rc, out = self.lead(token) + self.assertEqual(rc, 0, out) + self.assertTrue(self.added()) + + def test_codex_plain_call_token_under_asking_policy(self): + self.never_asks = False + _, token, new = self.exec("dev progress add extra") + self.assertTrue(new.startswith(f"DEVKIT_SPEAKER=main DEVKIT_SESSION=codex:{SID} DEVKIT_CALL={token} dev "), new) + self.assertEqual(identity.strip_token(new), f"DEVKIT_SPEAKER=main DEVKIT_SESSION=codex:{SID} dev progress add " + f"extra") + self.assertTrue(hooks._plain_devkit_call(new)) + self.assertEqual(self.last.get("permissionDecision"), "allow") + rc, out = self.lead(token) + self.assertEqual(rc, 0, out) + self.assertTrue(self.added()) + + def test_codex_member_lane_route_keeps_its_rewrite_with_the_token_or_without_it(self): + self.never_asks = False + _, token, new = self.exec("dev progress note 'api half done'", aid=SUB) + self.assertTrue(token and f"DEVKIT_FROM_AGENT={SUB}" in new, new) + self.assertEqual(self.last.get("permissionDecision"), "allow") + with mock.patch.object(hooks, "_DEVKIT_VARIABLE", hooks.re.compile( + r"(?:DEVKIT_FROM_AGENT|DEVKIT_SESSION|DEVKIT_SPEAKER)=[A-Za-z0-9_.:-]+\Z")): + _, token, new = self.exec("dev progress note 'api done'", aid=SUB) + self.assertEqual(token, "") + self.assertIn(f"DEVKIT_FROM_AGENT={SUB}", new) # the lane route still goes out + self.assertEqual(self.last.get("permissionDecision"), "allow") + self.assertEqual(len(self.records("calls.token-skipped")), 1) + + def test_codex_fish_shell_gets_no_readonly(self): + _, token, new = self.exec("git status", shell="/opt/homebrew/bin/fish") + self.assertEqual((token, new), ("", "")) + _, token, new = self.exec("dev crew inbox", shell="/opt/homebrew/bin/fish") + self.assertIn(f" DEVKIT_CALL={token} dev crew inbox", new) + self.assertNotIn("readonly", new) + + def test_codex_exec_entry_dies_at_its_yield(self): + data, token, _ = self.exec("dev ci --run", yield_time_ms=10_000, timeout_ms=3_600_000) + self.assertTrue(token) + self.assertEqual(pg.call_entry(data)["ttl"], 15.0) + + +class CodexThreadTests(CodexTokenCase): + never_asks = False # Codex asks: a compound command goes out as it is, with no token + + def test_codex_root_thread_without_evidence_refuses_with_the_plain_call_fix(self): + _, token, new = self.exec("dev progress add extra | tail -3") + self.assertEqual((token, new), ("", "")) + rc, out = self.lead(env=self.thread(SID)) + self.assertEqual(rc, 2, out) + self.assertIn("run it as one plain dev command", out) + self.assertFalse(self.added()) + + def test_codex_member_token_with_the_root_thread_turns_the_root_mapping_off(self): + self.never_asks = True + _, token, _ = self.exec("dev crew inbox", aid=SUB) + self.assertEqual(self.dev("crew", "inbox", token=token, env=self.thread(SID))[0], 0) + self.assertEqual(self.sess().get("codex_threads"), "shared") + self.assertEqual(len(self.records("codex.thread-shared")), 1) + rc, out = self.lead(env=self.thread(SID)) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + + def test_codex_member_token_with_its_own_thread_turns_the_root_mapping_on(self): + self.never_asks = True + _, token, _ = self.exec("dev crew inbox", aid=SUB) + self.assertEqual(self.dev("crew", "inbox", token=token, env=self.thread(SUB))[0], 0) + self.assertEqual(self.sess().get("codex_threads"), "per-agent") + self.never_asks = False + self.exec("dev progress add extra | tail -3") + rc, out = self.lead(env=self.thread(SID)) + self.assertEqual(rc, 0, out) + self.assertTrue(self.added()) + + def test_codex_member_token_with_another_lanes_thread_is_a_conflict(self): + self.never_asks = True + launch(SUB2, "trinity", "Trinity: ui", sid=SID, agent="codex") + _, token, _ = self.exec("dev progress note x", aid=SUB) + rc, out = self.dev("progress", "note", "x", token=token, env=self.thread(SUB2)) + self.assertEqual(rc, 2, out) + self.assertEqual(len(self.records("caller.conflict")), 1) + + def test_codex_compound_command_uses_the_thread_rule_for_a_lane(self): + _, token, new = self.exec("dev progress note 'api half done' | tail -1", aid=SUB) + self.assertEqual(token, "") + rc, out = self.dev("progress", "note", "api half done", env=self.thread(SUB)) + self.assertEqual(rc, 0, out) + self.assertIn("api half done", [u.get("text") for u in self.run_()["agents"][SUB].get("updates") or []]) + + def test_codex_unknown_thread_refuses_a_state_change_with_the_plain_call_fix(self): + self.exec("dev progress add extra | tail -3") + rc, out = self.lead(env=self.thread(OTHER)) + self.assertEqual(rc, 2, out) + self.assertIn("run it as one plain dev command", out) + self.assertEqual(len(self.records("caller.no-token")), 1) + + +class CodexCallLifeTests(CodexTokenCase): + def test_codex_yielded_exec_token_dies_at_post_tool_use(self): + data, token, _ = self.exec("sleep 60; dev progress add extra", yield_time_ms=10_000) + self.closed(data) # the exec yielded and its PostToolUse came; it goes on in a write_stdin session + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.stale-token")), 1) + + def test_codex_command_execution_thread_mismatch_is_audited(self): + data, token, new = self.exec("dev crew inbox") + self.assertEqual(self.speak(token).lane, "main") # its dev call resolved the tech lead + rollout = Rollout(self.root / ".codex", SID) + rollout.add("event_msg", {"type": "item_completed", "thread_id": SUB, "turn_id": "t1", + "item": {"type": "CommandExecution", "id": data["tool_use_id"], "exit_code": 0, + "status": "completed", "command": ["/bin/zsh", "-lc", new], + "aggregated_output": ""}}, time.time()) + with contextlib.redirect_stdout(io.StringIO()): + hooks.post_tool_payload("codex", dict(data, hook_event_name="PostToolUse", transcript_path=str( + rollout.path), tool_input={"cmd": new}, tool_response={"output": ""})) + found = self.records("caller.mismatch") + self.assertEqual(len(found), 1) + self.assertIn(SUB, found[0]["detail"]) + + def test_codex_tech_leads_token_resolves_main_while_a_members_call_holds_the_same_words(self): + self.exec("python3 -I -c \"print('dev progress add extra')\"", aid=SUB) + _, token, _ = self.exec("dev progress add extra 2>&1 | tail -3") + rc, out = self.lead(token) + self.assertEqual(rc, 0, out) + self.assertTrue(self.added()) + + def test_codex_ack_with_a_nested_read_resolves_the_tech_lead(self): + ref = pg.crew_ask("Report: " + "x" * 400, from_agent=SUB)["id"] + _, token, new = self.exec(f'dev crew ack {ref} --sha256 "$(dev crew read {ref} --json | jq -r .digest)" ' + f'--generation 1') + self.assertIsNone(LANE.search(new)) + rc, out = self.dev("crew", "read", ref, "--json", token=token) + self.assertEqual(rc, 0, out) + page = json.loads(out) + rc, out = self.dev("crew", "ack", ref, "--sha256", page["digest"], "--generation", str(page["generation"]), + token=token) + self.assertEqual(rc, 0, out) + self.assertIn("main", next(m for m in self.run_()["messages"] if m["id"] == ref).get("receipts") or {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_identity_token.py b/tests/test_identity_token.py new file mode 100644 index 00000000..9a4be74f --- /dev/null +++ b/tests/test_identity_token.py @@ -0,0 +1,450 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# Who calls, by the call token: the PreToolUse hook gives every shell call a token (DEVKIT_CALL=.) +# whose hash its call ledger entry holds, and a `dev` command that carries one is the entry's caller when the token is +# this session's, its agent's and its call shell's, and the call is still open. A session the hook stamped never lets a +# tokenless state change fall back to text matching. Each test is one path of the call-token design and its threat +# review. The hook runs in-process with the progress state and the audit trail in a temporary folder; the process tree +# a `dev` command sees (its shells and agent) is a fixture. +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_identity_token -v +import ast +import contextlib +import hashlib +import io +import json +import os +import re +import sys +import threading +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +import _hermetic # noqa: E402 + +_hermetic.activate() # run alone, this module gets the suite's temporary home too +sys.path.insert(0, str(ROOT / "lib")) + +from devkit import audit, hooks, identity, state # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_caller_identity import CallerCase # noqa: E402 +from test_progress import launch # noqa: E402 + +AGENT, SHELL, SIBLING, NESTED, INNER = 70001, 70002, 70003, 70004, 70005 +TOKEN = re.compile(r"DEVKIT_CALL=([A-Za-z0-9_.-]+)") +LANE = re.compile(r"DEVKIT_FROM_AGENT=([A-Za-z0-9_.:-]+)") + + +class TokenCase(CallerCase): + agent = "claude" + agent_line = "claude" + + def setUp(self): + super().setUp() + identity._forget() + self.addCleanup(identity._forget) + # the dev command runs below the call's shell, which runs below the agent process + self.chain = [(SHELL, "/bin/zsh -c source snapshot && eval cmd"), (AGENT, self.agent_line)] + self.starts = {SHELL: "Thu Nov 19 10:00:00 2026", SIBLING: "Thu Nov 19 10:00:09 2026", + INNER: "Thu Nov 19 10:01:00 2026"} + self.own_session = None # the process session the dev command runs in: by default its nearest shell's + for p in (mock.patch.object(pg, "_call_agent_pid", lambda: AGENT), + mock.patch.object(identity, "_chain", lambda: list(self.chain)), + mock.patch.object(identity, "_started", lambda pid: self.starts.get(pid, "")), + mock.patch.object(identity, "_session_of", lambda pid: ( + self.own_session or (self.chain[0][0] if self.chain else 1)) if pid == 0 else pid)): + p.start() + self.addCleanup(p.stop) + (hooks.STATE / "logs").mkdir(parents=True, exist_ok=True) + + # who a dev command with this token is, in this process (no fresh start) + def speak(self, token, *args): + with mock.patch.dict(os.environ, {identity.CALL_VAR: token}): + return identity.speaker(argv=list(args) or ["crew", "inbox"]) + + # a command only the tech lead's plan takes: it adds a step to the main plan + def lead(self, token="", env=None): + return self.dev("progress", "add", "extra", token=token, env=env) + + def added(self): + return "extra" in [s["name"] for s in self.run_()["plan"]] + + # the PreToolUse hook on a shell call, in-process -> (payload, its token or "", the command as rewritten) + def hook(self, cmd, aid=None, sid="s1", tool="Bash", key="command", **inp): + self.n += 1 + data = {"session_id": sid, "tool_use_id": f"toolu_{self.n:04d}", "tool_name": tool, + "hook_event_name": "PreToolUse", "tool_input": {key: cmd, **inp}, "cwd": str(self.root)} + if aid: + data["agent_id"] = aid + out = io.StringIO() + with contextlib.redirect_stdout(out): + hooks._pre_tool(self.agent, data) + spec = (json.loads(out.getvalue()) if out.getvalue().strip() else {}).get("hookSpecificOutput") or {} + new = (spec.get("updatedInput") or {}).get(key) or "" + found = TOKEN.search(new) + self.last = spec + return data, (found.group(1) if found else ""), new + + def closed(self, data, event="PostToolUse"): + hooks._close_call(dict(data, hook_event_name=event)) + + def dev(self, *args, token="", env=None, fresh=True): + e = dict(env or {}) + if token: + e[identity.CALL_VAR] = token + if fresh: + identity._forget() # each dev command is a process of its own + return super().dev(*args, env=e) + + def plan_with_link(self): + with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): + pg.start("Release", plan=["sig2625", "ci-redirect"]) + pg.assign("sig2625", "Link", why="the test's assignment") + launch("a_link", "devkit:link", "Link: sig2625 Signature release") + + def state_of(self, name): + return next(s for s in self.run_()["plan"] if s["name"] == name).get("state") + + def records(self, action): + return audit.records(1, action=action) + + +class StampTests(TokenCase): + def test_every_main_shell_call_gets_a_readonly_token_whose_hash_its_entry_holds(self): + data, token, new = self.hook("git status") + self.assertTrue(new.startswith(f" export DEVKIT_CALL={token}; readonly DEVKIT_CALL; git status"), new) + tid, nonce = identity.parse_token(token) + entry = pg.call_entry(data) + self.assertEqual(tid, data["tool_use_id"]) + self.assertEqual(entry["token_sha256"], hashlib.sha256(nonce.encode()).hexdigest()) + self.assertNotIn(nonce, json.dumps(entry)) + self.assertEqual((state.read(pg.session_path("claude", "s1")) or {}).get("call_token"), 1) + + def test_a_ledger_write_that_fails_stamps_no_token_and_is_audited(self): + with mock.patch.object(pg, "_write_private", side_effect=OSError("disk full")): + _, token, new = self.hook("dev progress note 'still working'") + self.assertEqual(token, "") + self.assertNotIn("DEVKIT_CALL", new) + self.assertEqual([r["action"] for r in self.records("calls.token-skipped")], ["calls.token-skipped"]) + + def test_a_busy_session_hold_stamps_no_token(self): + with mock.patch.object(identity, "_session_update", side_effect=state.StateBusy("busy")): + data, token, _ = self.hook("git status") + self.assertEqual(token, "") + self.assertNotIn(data["tool_use_id"], (state.read(pg.session_path("claude", "s1")) or {}).get( + "calls_opened") or []) + + def test_closing_the_call_drops_its_pin_and_its_opened_mark(self): + data, token, _ = self.hook("dev progress note x") + self.assertEqual(self.dev("crew", "inbox", token=token)[0], 0) + tid = data["tool_use_id"] + self.assertTrue(identity.pin_path("s1", tid).exists()) + self.closed(data) + sess = state.read(pg.session_path("claude", "s1")) or {} + self.assertFalse(identity.pin_path("s1", tid).exists()) + self.assertNotIn(tid, sess.get("calls_opened") or []) + self.assertIn(tid, sess.get("calls_closed") or []) + + +class ResolutionTests(TokenCase): + def test_the_tech_leads_token_resolves_main_while_a_members_open_call_holds_the_same_words(self): + self.plan_with_link() + # a member's call whose program devkit cannot read through holds the tech lead's very words + self.hook("python3 -I -c \"print('dev progress begin ci-redirect')\"", aid="a_link") + _, token, _ = self.hook("dev progress begin ci-redirect 2>&1 | tail -6") + rc, out = self.dev("progress", "begin", "ci-redirect", token=token) + self.assertEqual(rc, 0, out) + self.assertEqual(self.state_of("ci-redirect"), "running") + + def test_a_cut_member_call_does_not_capture_the_tech_leads_command(self): + self.plan_with_link() + self.hook("python3 - <<'EOF'\n" + "print('x')\n" * 600 + "EOF", aid="a_link") # over 4096 characters + _, token, _ = self.hook("dev progress begin ci-redirect") + rc, out = self.dev("progress", "begin", "ci-redirect", token=token) + self.assertEqual(rc, 0, out) + self.assertEqual(self.state_of("ci-redirect"), "running") + + def test_an_ack_with_a_nested_read_resolves_its_caller_for_the_tech_lead_and_a_member(self): + self.plan_with_link() + to_main = pg.crew_ask("Report: " + "x" * 400, from_agent="a_link")["id"] + with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}), \ + mock.patch.object(identity, "acting_lane", lambda *a, **k: "main"): + to_link = pg.crew_ask("Brief: " + "y" * 400, to="Link")["id"] + for ref, aid in ((to_main, None), (to_link, "a_link")): + with self.subTest(ref=ref): + _, token, new = self.hook(f'dev crew ack {ref} --sha256 "$(dev crew read {ref} --json | jq -r ' + f'.digest)" --generation 1', aid=aid) + lane = LANE.search(new) + env = {"DEVKIT_FROM_AGENT": lane.group(1)} if lane else {} + rc, out = self.dev("crew", "read", ref, "--json", token=token, env=env) + self.assertEqual(rc, 0, out) + page = json.loads(out) + rc, out = self.dev("crew", "ack", ref, "--sha256", page["digest"], "--generation", + str(page["generation"]), token=token, env=env) + self.assertEqual(rc, 0, out) + receipts = next(m for m in self.run_()["messages"] if m["id"] == ref).get("receipts") or {} + self.assertIn(aid or "main", receipts) + + def test_a_token_from_another_sessions_folder_is_refused(self): + self.plan_with_link() + _, token, _ = self.hook("dev progress begin ci-redirect", sid="s1") + (pg.SESSIONS / "claude-s2.json").write_text(json.dumps({"agent": "claude", "session": "s2"})) + rc, out = self.lead(token, env={"DEVKIT_SESSION": "claude:s2"}) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.foreign-session")), 1) + + def test_a_token_used_below_a_nested_agent_is_refused(self): + self.plan_with_link() + _, token, _ = self.hook("codex exec 'review the diff'") + # dev -> shell -> codex -> the tech lead's call shell -> claude + self.chain = [(INNER, "/bin/zsh -lc dev"), (NESTED, "codex exec review"), (SHELL, "/bin/zsh -c x"), + (AGENT, "claude")] + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.foreign-agent")), 1) + + def test_a_second_use_from_a_sibling_shell_is_refused_and_the_calls_own_shell_still_resolves_main(self): + self.plan_with_link() + _, token, _ = self.hook("dev progress begin ci-redirect") + self.assertEqual(self.speak(token).lane, "main") # its first use, from the call's own shell + self.chain = [(SIBLING, "/bin/zsh -c steal"), (AGENT, "claude")] # a member's shell under the same agent + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + found = self.records("caller.token-foreign-use") + self.assertEqual(len(found), 1) + self.assertIn(str(SHELL), found[0]["detail"]) + self.assertIn(str(SIBLING), found[0]["detail"]) + self.chain = [(SHELL, "/bin/zsh -c x"), (AGENT, "claude")] + rc, out = self.lead(token) + self.assertEqual(rc, 0, out) + self.assertTrue(self.added()) + + def test_two_concurrent_first_uses_leave_one_pin(self): + _, token, _ = self.hook("dev progress note x") + tid, _ = identity.parse_token(token) + results, gate = [], threading.Barrier(2) + + def use(shell): + gate.wait() + results.append((shell, identity._pin("s1", tid, shell, self.starts[shell]))) + threads = [threading.Thread(target=use, args=(s,)) for s in (SHELL, SIBLING)] + for t in threads: + t.start() + for t in threads: + t.join() + self.assertEqual(sorted(ok for _, ok in results), [False, True]) + winner = next(s for s, ok in results if ok) + self.assertEqual(json.loads(identity.pin_path("s1", tid).read_text())["pid"], winner) + + def test_a_reused_shell_pid_with_another_start_time_is_refused(self): + self.plan_with_link() + _, token, _ = self.hook("dev progress begin ci-redirect") + self.assertEqual(self.speak(token).lane, "main") + self.starts[SHELL] = "Thu Nov 19 11:30:00 2026" # the call's shell ended and its pid went to another one + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.token-foreign-use")), 1) + + def test_a_detached_process_holding_a_live_token_changes_nothing_but_may_read(self): + self.plan_with_link() + to_main = pg.crew_ask("Report: " + "x" * 400, from_agent="a_link")["id"] + _, token, _ = self.hook(f"dev crew read {to_main} --json; setsid dev progress add extra") + self.own_session = 99999 # setsid: a process session of its own, while the call is still open + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + rc, out = self.dev("crew", "read", to_main, "--json", token=token) + self.assertEqual(rc, 0, out) + self.own_session, self.chain = None, [] # reparented to launchd: no agent above it at all + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + + def test_a_token_whose_entry_has_no_hash_is_a_mismatch_never_legacy(self): + self.plan_with_link() + data = self.call("dev progress add extra") # an entry written without a token hash + identity.note_opened("claude", "s1", data["tool_use_id"]) + rc, out = self.lead(f"{data['tool_use_id']}.{'A' * 22}") + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.mismatch")), 1) + + def test_a_forged_entry_the_hook_never_opened_is_refused(self): + self.plan_with_link() + self.hook("git status") # a token session + nonce = "B" * 22 + pg.call_opened("claude", {"session_id": "s1", "tool_use_id": "toolu_forged", "tool_name": "Bash", + "tool_input": {"command": "dev progress add extra"}}, + token_sha256=hashlib.sha256(nonce.encode()).hexdigest()) + rc, out = self.lead(f"toolu_forged.{nonce}") + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("calls.forged")), 1) + + def test_a_dev_process_resolves_once_and_keeps_its_caller_after_the_entry_closes(self): + data, token, _ = self.hook("dev progress note x") + self.assertEqual(self.speak(token, "progress", "note", "x").how, "token") + self.closed(data) + self.assertEqual(self.speak(token, "progress", "note", "x").lane, "main") # the same process, still main + self.plan_with_link() + rc, out = self.dev("progress", "note", "x", token=token) # a new command after the close + self.assertEqual(rc, 2, out) + self.assertEqual(len(self.records("caller.stale-token")), 1) + + def test_a_background_calls_state_change_is_refused_with_the_foreground_fix(self): + self.plan_with_link() + data, token, _ = self.hook("dev progress note 'waiting on CI'", run_in_background=True) + self.closed(data) # a background call's result comes as soon as it starts + rc, out = self.dev("progress", "note", "waiting on CI", token=token) + self.assertEqual(rc, 2, out) + self.assertIn("a background command's identity ends when it starts: run it in the foreground", out) + + def test_a_member_token_with_another_lanes_variable_is_a_conflict(self): + self.plan_with_link() + launch("a_tank", "devkit:tank", "Tank: api") + _, token, _ = self.hook("dev progress note x", aid="a_link") + rc, out = self.dev("progress", "note", "x", token=token, env={"DEVKIT_FROM_AGENT": "a_tank"}) + self.assertEqual(rc, 2, out) + self.assertEqual(len(self.records("caller.conflict")), 1) + + def test_a_member_token_names_the_member_and_never_the_tech_lead(self): + self.plan_with_link() + _, token, _ = self.hook("python3 -I tools/assign.py", aid="a_link") # no lane variable reaches the dev call + rc, out = self.dev("progress", "begin", "ci-redirect", token=token) + self.assertEqual(rc, 2, out) + self.assertIn("only the tech lead", out) + + +class TokenSessionTests(TokenCase): + def test_a_tokenless_state_change_in_a_token_session_is_refused_and_never_main(self): + self.plan_with_link() + self.hook("dev progress add extra") # the tech lead's call is open; the session holds tokens + self.call("python3 -I x.py", aid="a_link") # a member's call that carries no token (env -u DEVKIT_CALL) + rc, out = self.lead() + self.assertEqual(rc, 2, out) + self.assertIn("devkit could not verify this call's identity", out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.no-token")), 1) + + def test_a_session_the_hook_never_stamped_keeps_one_ledger_match(self): + self.plan_with_link() + self.call("dev progress add extra") + rc, out = self.lead() + self.assertEqual(rc, 0, out) + self.assertTrue(self.added()) + + def test_the_developers_own_terminal_is_unchanged(self): + self.hook("git status") + with mock.patch.object(pg, "resolve_session", lambda *a, **k: ("human", "shell-1", "shell")): + sp = identity.speaker(argv=["progress", "begin", "ci-redirect"]) + self.assertEqual((sp.how, sp.lane), ("human", "")) + + def test_an_unknown_caller_never_acts_as_the_tech_lead_while_a_member_may_speak(self): + self.plan_with_link() # a session the hook never stamped, with the Release engineer at work + with mock.patch.object(sys, "argv", ["dev", "crew", "ask", "hello"]): + with self.assertRaises(identity.IdentityError): + identity.acting_lane() + + +class AuditAndSecrecyTests(TokenCase): + def test_every_identity_record_carries_the_fixed_fields_and_never_the_nonce(self): + self.plan_with_link() + _, token, _ = self.hook("dev progress begin ci-redirect") + nonce = identity.parse_token(token)[1] + (pg.SESSIONS / "claude-s2.json").write_text(json.dumps({"agent": "claude", "session": "s2"})) + self.lead(token, env={"DEVKIT_SESSION": "claude:s2"}) + self.assertEqual(self.speak(token).lane, "main") # the call's own shell pins the token + self.chain = [(SIBLING, "/bin/zsh -c x"), (AGENT, "claude")] + self.lead(token) + self.chain = [(SHELL, "/bin/zsh -c x"), (AGENT, "claude")] + self.lead(f"{identity.parse_token(token)[0]}.{'C' * 22}") + found = [r for r in audit.query(days=1) if r.get("action", "").startswith(("caller.", "calls.")) + and r["action"] != "caller.refused"] + self.assertEqual(sorted(r["action"] for r in found), + ["caller.foreign-session", "caller.mismatch", "caller.token-foreign-use"]) + for r in found: + with self.subTest(r["action"]): + self.assertEqual(r["crew"]["tool_use_id"], identity.parse_token(token)[0]) + self.assertIn(r["ref"]["session"], ("s1", "s2")) + self.assertEqual(r["ref"]["agent"], "claude") + self.assertEqual((r["outcome"], r["ref"]["result"]), ("blocked", "deny")) + self.assertTrue(r["evidence"]["command"].startswith("dev progress add"), r["evidence"]) + self.assertIn(str(AGENT), r["ref"]["ancestors"]) + self.assertNotIn(nonce, json.dumps(r)) + + def test_no_devkit_file_holds_the_nonce_after_a_stamped_call(self): + self.plan_with_link() + data, token, new = self.hook("dev progress begin ci-redirect") + nonce = identity.parse_token(token)[1] + self.assertEqual(self.dev("progress", "begin", "ci-redirect", token=token)[0], 0) + out = io.StringIO() + with contextlib.redirect_stdout(out): + hooks.post_tool_payload(self.agent, dict(data, hook_event_name="PostToolUse", + tool_input={"command": new}, + tool_response={"stdout": "ok", "exit_code": 0})) + self.assertIn(nonce, new) + held = [str(f.relative_to(self.root)) for f in self.root.rglob("*") if f.is_file() + and nonce.encode() in f.read_bytes()] + self.assertEqual(held, []) + self.assertEqual(audit.redact(f"x DEVKIT_CALL={token} y"), "x DEVKIT_CALL=…[redacted] y") + + def test_malformed_tokens_are_rejected_before_any_file_read(self): + self.plan_with_link() + self.hook("git status") + bad = ["../x." + "n" * 22, ".shells." + "n" * 22, "toolu_1." + "n" * 21, "toolu_1." + "n" * 23, + "toolu.1." + "n" * 22, "toolu_1/" + "n" * 22, ""] + for value in bad: + with self.subTest(value): + self.assertIsNone(identity.parse_token(value)) + with mock.patch.object(identity, "_read_entry", side_effect=AssertionError("read")): + rc, out = self.lead(value or "x") + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + + +class SpawnAndAdviceTests(TokenCase): + def test_devkits_detached_spawns_never_pass_the_call_token(self): + with mock.patch.dict(os.environ, {identity.CALL_VAR: "toolu_1." + "n" * 22}), \ + mock.patch.object(hooks.subprocess, "Popen") as popen: + hooks._spawn(["dev", "sync"]) + self.assertNotIn(identity.CALL_VAR, popen.call_args.kwargs["env"]) + self.assertNotIn(identity.CALL_VAR, identity.detached_env()) + self.assertEqual(identity.detached_env({"A": "1", identity.CALL_VAR: "v"}), {"A": "1"}) + # every start_new_session spawn in devkit builds its environment with identity.detached_env + missing = [] + for f in (ROOT / "lib" / "devkit").rglob("*.py"): + for node in ast.walk(ast.parse(f.read_text())): + if isinstance(node, ast.Call) and any(k.arg == "start_new_session" for k in node.keywords): + env = next((k.value for k in node.keywords if k.arg == "env"), None) + if env is None or "detached_env" not in ast.unparse(env) and not self._env_from_helper(f, env): + missing.append(str(f.relative_to(ROOT))) + # the tech lead places these two once their owners' lanes finish (ciwatch's CI watch, cli's own spawn) + self.assertLessEqual(set(missing), {"lib/devkit/ciwatch.py", "lib/devkit/cli.py"}, missing) + + @staticmethod + def _env_from_helper(f, env) -> bool: + # a spawn whose env is a variable built by identity.detached_env in the same function + name = ast.unparse(env) + return re.search(rf"\b{re.escape(name)}\s*=\s*(?:dict\()?identity\.detached_env\(", f.read_text()) is not None + + def test_a_members_command_that_strips_its_identity_gets_advice_and_a_spoof_audit(self): + self.plan_with_link() + for cmd in ("env -u DEVKIT_FROM_AGENT dev crew inbox", "unset DEVKIT_CALL; dev crew inbox", + "env -i PATH=/usr/bin python3 x.py", "DEVKIT_CALL=toolu_9.abc dev crew inbox", + "export CODEX_THREAD_ID=x; dev crew inbox"): + with self.subTest(cmd): + self.hook(cmd, aid="a_link") + self.assertIn("devkit · advice: ", self.last.get("additionalContext") or "") + self.assertIn("identity", self.last.get("additionalContext") or "") + self.assertEqual(len(self.records("caller.spoof-suspect")), 5) + + +if __name__ == "__main__": + unittest.main() From 696a773039935ba6ce48ba44c8616493a7b400bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:06:59 -0800 Subject: [PATCH 13/52] test(identity): compare rewritten commands without their call token Every shell call now carries its call token in front of the command, so two tests that compared the whole rewritten command failed although the lane route they check still holds. Each test checks that the token prefix is there and compares the command without it (identity.strip_token). Verified: python3 -m unittest tests.test_hooks_wiring.FailOpenTests tests.test_caller_identity: 38 passed --- tests/test_caller_identity.py | 6 ++++-- tests/test_hooks_wiring.py | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/test_caller_identity.py b/tests/test_caller_identity.py index c5790766..bf693d4a 100644 --- a/tests/test_caller_identity.py +++ b/tests/test_caller_identity.py @@ -20,7 +20,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) sys.path.insert(0, str(Path(__file__).resolve().parent)) -from devkit import audit, cli, hooks, progress as pg # noqa: E402 +from devkit import audit, cli, hooks, identity, progress as pg # noqa: E402 from test_progress import TempState, launch # noqa: E402 SETTINGS = Path(__file__).resolve().parents[1] / "config" / "claude" / "settings.json" @@ -570,7 +570,9 @@ def test_a_member_lane_command_is_rewritten_without_approving_it(self): with mock.patch("sys.stdin", io.StringIO(json.dumps(data))), contextlib.redirect_stdout(out): hooks.run("pre-tool", "claude") spec = json.loads(out.getvalue())["hookSpecificOutput"] - self.assertEqual(spec["updatedInput"]["command"], "DEVKIT_FROM_AGENT=a_tank dev progress note x") + command = spec["updatedInput"]["command"] + self.assertTrue(command.startswith(" export DEVKIT_CALL="), command) # the call token goes in front + self.assertEqual(identity.strip_token(command), "DEVKIT_FROM_AGENT=a_tank dev progress note x") self.assertNotIn("permissionDecision", spec) diff --git a/tests/test_hooks_wiring.py b/tests/test_hooks_wiring.py index 763adb60..e0f35b98 100644 --- a/tests/test_hooks_wiring.py +++ b/tests/test_hooks_wiring.py @@ -19,7 +19,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) sys.path.insert(0, str(Path(__file__).resolve().parent)) -from devkit import audit, bugs, canary, core, hooks, lanescope, progress as pg, registry, stubs, work # noqa: E402 +from devkit import audit, bugs, canary, core, hooks, identity, lanescope, progress as pg, registry, stubs, work # noqa: E402,E501 from test_language_neutral_hooks import HookCase # noqa: E402 from test_progress import gates_passed, launch # noqa: E402 import test_threaded_turn_endings as turns # noqa: E402 (its TurnCase fixture; its tests run in their own module) @@ -237,7 +237,9 @@ def test_a_members_routed_progress_call_still_routes_when_its_lessons_fail(self) out = self.hook("pre-tool", call) spec = json.loads(out)["hookSpecificOutput"] self.assertNotIn("permissionDecision", spec) - self.assertTrue(spec["updatedInput"]["command"].startswith("DEVKIT_FROM_AGENT=a_tank dev progress step"), out) + command = spec["updatedInput"]["command"] + self.assertTrue(command.startswith(" export DEVKIT_CALL="), out) # the call token goes in front + self.assertTrue(identity.strip_token(command).startswith("DEVKIT_FROM_AGENT=a_tank dev progress step"), out) class MainSessionTests(WiringCase): From 35510e431876b8c4779d181322895fd7fdd92229 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:07:08 -0800 Subject: [PATCH 14/52] fix(hooks): leave a follow-up launch of a done step unchanged A follow-up launch whose description named a step its member had already finished was rewritten to take the member's next waiting step, so the follow-up took work the tech lead had not given it. Root cause: hooks._launch_naming scored the description only against open steps, so a description naming a done step named none of them, and the one waiting step was put in its place The description is scored against the member's done steps too: naming one leaves the launch as it is, binding no step. A step waits for a launch only when its intent binds it to no lane, read through progress._queued_lanes. Verified: python3 -m unittest tests.test_hooks_launch: 8 passed; dev test prove: both new tests fail without the change --- lib/devkit/hooks.py | 11 +++++++--- tests/test_hooks_launch.py | 42 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 2ea23dc9..d0cf917d 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -3101,6 +3101,9 @@ def _launch_naming(agent: str, data: dict) -> tuple: the exact description that takes each. - It names one (or every review it names, which one reviewer's launch holds together), its member has no step to take, or no step waits for it: (None, []). + - It names one of its member's steps that is done (a follow-up of finished work): (None, []), so it starts + unchanged and takes no step. Its description is scored against the member's done steps too. + A step waits for a launch only when its intent binds it to no lane (progress._queued_lanes, the one reader). Claude Code's Agent and Task calls only, launched by the main session with a devkit crew member's subagent_type. Codex is left as it is: it applies updatedInput only to a shell command (_codex_may_rewrite), and its spawn's task_name, not a description, selects the step (progress._native_launch_label, codexlaunch).""" @@ -3119,8 +3122,10 @@ def _launch_naming(agent: str, data: dict) -> tuple: steps = _launchable_steps(run, lane) if not steps: return None, [] - binds, tied = _named_steps(label, steps) - if binds: + done = [st for st in run.get("plan") or [] if st.get("state") in pg.DONE and st.get("label") + and pg._label_matches(st["label"], lane)] + binds, tied = _named_steps(label, steps + done) + if binds or any(st in done for st in tied): return None, [] who = crew.who(m) if tied: @@ -3130,7 +3135,7 @@ def _launch_naming(agent: str, data: dict) -> tuple: f"starts. The description that takes one: " + " · ".join(f"“{d}” for “{n}”" for n, d in given if d) + f"; for this launch, dev progress assign \"\" --to \"{label}\" links the one it does"] - waiting = [st for st in steps if not st.get("waits_lane") and st.get("state") in ("pending", "unverified") + waiting = [st for st in steps if not pg._queued_lanes(st) and st.get("state") in ("pending", "unverified") and not pg.deps_open(run, st)] if len(waiting) == 1: name = waiting[0]["name"] diff --git a/tests/test_hooks_launch.py b/tests/test_hooks_launch.py index a3f971cb..0badceae 100644 --- a/tests/test_hooks_launch.py +++ b/tests/test_hooks_launch.py @@ -12,6 +12,7 @@ import json import sys import tempfile +import time import unittest from pathlib import Path @@ -94,6 +95,47 @@ def test_a_description_without_a_member_prefix_gets_the_step_name_in_front(self) self.assertEqual(owner("v23-qa"), "a1") +class FollowUpTests(unittest.TestCase): + def test_a_follow_up_launch_naming_a_done_step_is_left_unchanged(self): + # B-igm9ittsioat: "Mouse: v23-qa follow-up" after v23-qa is done was rewritten to take the next waiting step + with TempState(): + pg.start("Acceptance", plan=["v23-qa", "v24-a11y"]) + pg.assign("v23-qa", "Mouse") + pre_tool(call("Mouse: v23-qa visual acceptance tests")) + started() + pg.step("v23-qa passes", which="v23-qa", check="✓ 9 tests pass", from_agent="a1") + pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a1", "agent_type": "devkit:mouse"}, False) + pg.assign("v24-a11y", "Mouse") # waits for the member's next launch + self.assertEqual(next(s["state"] for s in pg.load_run("claude", "s1")["plan"] if s["name"] == "v23-qa"), + "done") + got = hooks._launch_naming("claude", call("Mouse: v23-qa follow-up", tid="toolu_m2")) + out = pre_tool(call("Mouse: v23-qa follow-up", tid="toolu_m3")) + self.assertEqual(got, (None, [])) + self.assertEqual((out.get("updatedInput") or {}).get("description", "Mouse: v23-qa follow-up"), + "Mouse: v23-qa follow-up") + + def test_a_step_queued_for_a_lane_is_not_waiting_for_a_launch(self): + # the queue is read through progress._queued_lanes, the one reader of a step's intent: a 26.11.26 run queued + # a role's step behind its member's busy lane, and its next save keeps that as an intent bound to the lane, + # which no other launch may take + with TempState(): + pg.start("Acceptance", plan=["v23-qa", "v24-a11y"]) + pg.assign("v23-qa", "Mouse") + pre_tool(call("Mouse: v23-qa visual acceptance tests")) + started() + path = pg.run_path("claude", "s1") + doc = json.loads(path.read_text()) + step = next(s for s in doc["plan"] if s["name"] == "v24-a11y") + step.update(state="pending", owner="main", label="Mouse", waits_lane=None, + intent={"member": "Mouse", "lane": "a1", "rev": 1, "ts": time.time(), "by": "main", + "front": False}) + path.write_text(json.dumps(doc)) + queued = next(s for s in pg.normalize(pg.load_run("claude", "s1"))["plan"] if s["name"] == "v24-a11y") + self.assertEqual(pg._queued_lanes(queued), ["a1"]) + got = hooks._launch_naming("claude", call(VAGUE, tid="toolu_m2")) + self.assertEqual(got, (None, [])) + + class NoticeTests(unittest.TestCase): def test_several_waiting_steps_get_a_notice_with_the_description_for_each_and_no_rewrite(self): with TempState(): From c57476824b340faba7fadb564a2e0fc225fb9052 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:07:15 -0800 Subject: [PATCH 15/52] fix(hooks): tell the tech lead what the gates let a member through with A member the crew gates sent back once and then let through with findings ended its review unverified, and the tech lead did not hear what was still missing. Root cause: subagent_stop never read the findings gates.check keeps for a stop it lets through (gates.let_through), so they reached nobody After the gates let a stop through, the hook reads those findings and posts one devkit notice to the tech lead, naming the member by role and up to six findings. Verified: python3 -m unittest tests.test_hooks_gate_findings: 1 passed; dev test prove: it fails without the change --- lib/devkit/hooks.py | 35 ++++++++++++++++++++++++++++++ tests/test_hooks_gate_findings.py | 36 +++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 tests/test_hooks_gate_findings.py diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index d0cf917d..a4dd0e02 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -4205,6 +4205,36 @@ def judge(): return (box["out"], work) if not t.is_alive() and "out" in box else (None, None) +FINDINGS_TOLD = 6 # gate findings one notice to the tech lead names, the rest counted + + +def _tell_lead_findings(agent: str, data: dict, findings: list): + """A member's stop the crew gates let through with findings (sent back once in this lane life already, or only + recorded): the tech lead hears them as devkit's notice, with the member's name, since that stop's Check approves + nothing and no review it closes counts. Never raises (logged).""" + from . import progress + sid, aid = str(data.get("session_id") or ""), str(data.get("agent_id") or "") + if not findings or not sid: + return + try: + with progress._tx(agent, sid): + run = progress.load_run(agent, sid) + if not run: + return + run = progress.normalize(run) + lane = (run.get("agents") or {}).get(aid) or {} + who = _who(lane.get("persona") or lane.get("label") or str(data.get("agent_type") or "A crew member")) + named = "; ".join(_inline(f"{f.get('rule')}: {f.get('item')}", 160) for f in findings[:FINDINGS_TOLD]) + more = f" and {len(findings) - FINDINGS_TOLD} more" if len(findings) > FINDINGS_TOLD else "" + progress._post(run, "devkit", "main", + f"devkit: {who} stopped, and the crew gates let it through with what is still missing: " + f"{named}{more}. A review or verdict of that stop counts for nothing: check its work, or " + f"send it back with the fix.", time.time(), from_name="devkit", kind="notice") + progress._save(run, touch_session=False) + except Exception: + _log(f"subagent-stop findings {agent}: {traceback.format_exc()[-300:]}") + + def subagent_stop(agent: str): """SubagentStop: a crew member's report must start with its own status block (the canary covers the crew too); without it the member is sent back once to write it, and the correction is recorded like the main canary's. Only @@ -4214,6 +4244,7 @@ def subagent_stop(agent: str): from . import progress data = _stdin_json() out = None + let_through = [] # what the crew gates still found in a stop they let through (gates.let_through) try: from . import continuity if continuity.is_summarizer(agent, data, state.read(_session_file(agent, data.get("session_id") or "-"))): @@ -4308,6 +4339,9 @@ def subagent_stop(agent: str): "did not judge this stop", "let through", member=name, rules=[]) else: sess = judged + if out is None: + from . import gates + let_through = gates.let_through(sess, aid or str(name or "")) if out is None and agent == "claude" and aid and by_main and \ aid not in (sess.get("crew_background") or {}): # it finished: the tech lead hears it once, with the id Claude Code's TaskStop takes @@ -4323,6 +4357,7 @@ def subagent_stop(agent: str): return _lessons_end(data, str(data.get("agent_id") or "")) # the member's lane ended: what it did not hit was heeded progress.on_subagent(agent, data, False) + _tell_lead_findings(agent, data, let_through) _continuity("on_subagent_stop", agent, data) # a last read of its transcript: a compaction no hook saw _prompt_refresh(data, force=True) # a lane closed: the prompt's crew count follows diff --git a/tests/test_hooks_gate_findings.py b/tests/test_hooks_gate_findings.py new file mode 100644 index 00000000..c763c3a5 --- /dev/null +++ b/tests/test_hooks_gate_findings.py @@ -0,0 +1,36 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# A member's stop that the crew gates let through with findings (sent back once in that lane life already): the +# SubagentStop hook reads what they still found (gates.let_through) and the tech lead hears it as devkit's notice, +# named by the member's role, since that stop's Check approves nothing. Through Claude Code's SubagentStop hook, with +# the real gates (test_approvals_token.StopCase: the Code reviewer holds "review"). +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_hooks_gate_findings -v +import json +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "lib")) +sys.path.insert(0, str(ROOT / "tests")) +from test_approvals_token import StopCase # noqa: E402 + + +class LetThroughFindingsTests(StopCase): + def notices(self): + return [m["text"] for m in self.run_().get("messages") or [] if m.get("to") == "main" + and m.get("from") == "devkit" and "crew gates let it through" in str(m.get("text"))] + + def test_the_tech_lead_hears_what_the_gates_still_found_in_a_stop_they_let_through(self): + self.assertEqual(json.loads(self.stop() or "{}").get("decision"), "block") # no dev progress step + self.assertEqual(self.notices(), []) # a send-back tells the member, not the tech lead + self.assertEqual(self.stop(stop_hook_active=True), "") # still none: let through + told = self.notices() + self.assertEqual(len(told), 1, told) + self.assertIn("Code reviewer (Seraph) stopped", told[0]) + self.assertIn("proofs: dev progress step", told[0]) + + +if __name__ == "__main__": + unittest.main() From f6bd130ebdfcde4ae7508356cebdf35836460346 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:08:11 -0800 Subject: [PATCH 16/52] test(crew): check the Codex compound ack under both approval policies Under the approved threat review a compound dev crew ack gets a call token only where Codex never asks; the test ran under an asking policy and read the receipt from the raw run file, where the messaging store's receipt does not show. Where Codex never asks (config.toml approval_policy never, as dev setup writes it) the ack succeeds and the receipt is read from the messaging store; where Codex may ask, the refusal must name the plain-call fix. Verified: before 3c4a549a both cases fail (not_recipient); on the branch the never-asks case passes and the asking case still fails: the ack's refusal drops identity's plain-call reason; dev test audit 0 findings --- tests/test_coordination_codex.py | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/tests/test_coordination_codex.py b/tests/test_coordination_codex.py index 58bebebf..7c3db894 100644 --- a/tests/test_coordination_codex.py +++ b/tests/test_coordination_codex.py @@ -17,6 +17,7 @@ sys.path.insert(0, str(ROOT / "tests")) from test_acceptance_crew_sessions import HOOK_BOOT # noqa: E402 from test_codex_launch import LEAD, TANK, CodexCrew, _line, _now # noqa: E402 +from devkit import messaging # noqa: E402 SERAPH = "01a1c190-64c7-7ac1-81c6-000000000007" REPORT = ("**[Firefly> DevKit · {role}]** api · `feat/invoice-export` · {task}\n- **Done:** {task}\n" @@ -122,17 +123,39 @@ def test_a_resumed_codex_lane_takes_the_one_step_assigned_to_its_member_by_role( class CodexCallerTests(CodexCoordination): - # On Codex the tech lead's own commands are "unverified", which main-only commands allow, so a member's open - # wait or quoting question never takes them (checked on 2026-11-19); the ack below still fails - def test_the_codex_tech_lead_acknowledges_with_a_digest_read_in_the_same_command(self): + # On Codex the tech lead's own commands were "unverified", which main-only commands allow, so a member's open + # wait or quoting question never took them; the tech lead's compound acknowledgement was refused + def codex_policy(self, policy: str): + """Codex's config.toml in the test's own home, as dev setup writes it on a Mac where Codex never asks.""" + home = self.home / ".codex" + home.mkdir(parents=True, exist_ok=True) + (home / "config.toml").write_text(f'approval_policy = "{policy}"\n') + + def compound_ack(self): + """The tech lead acknowledges a member's report with a digest read by a nested dev crew read in the same + command -> (the command's result, the message as the messaging store keeps it).""" s = self.run_lead("api=30m [backend]", ("api", "Tank", "api/**")) self.spawn(s, TANK, "tank", "api") self.member(s, TANK, "tank", "crew", "ask", "Report: " + "x" * 400) ref = next(m["id"] for m in s.run_doc()["messages"] if m.get("to") == "main") r = s.sh(f'dev crew ack {ref} --sha256 "$(dev crew read {ref} --json | python3 -I -c \'import json,sys; ' f'print(json.load(sys.stdin)["digest"])\')" --generation 1') + store = self.state / "messaging-v2" / "runs" / f"{messaging.run_id(s.run_doc())}.json" + return r, next(m for m in json.loads(store.read_text())["messages"] if m["id"] == ref) + + def test_the_codex_tech_lead_acknowledges_with_a_digest_read_in_the_same_command(self): + self.codex_policy("never") # Codex never asks: every shell call carries its call token + r, message = self.compound_ack() self.assertEqual(r["rc"], 0, r["out"] + r["err"]) - self.assertIn("main", next(m for m in s.run_doc()["messages"] if m["id"] == ref).get("receipts") or {}) + self.assertIn("main", message.get("receipts") or {}) + + def test_a_codex_compound_ack_that_codex_may_ask_about_names_the_plain_call_fix(self): + # with no config.toml Codex may ask about the call, so devkit gives it no token, and a compound command + # cannot tell which thread runs it: it is refused, saying to run the ack as one plain dev command + r, message = self.compound_ack() + self.assertNotEqual(r["rc"], 0, r["out"]) + self.assertIn("run it as one plain dev command", r["out"] + r["err"]) + self.assertNotIn("main", message.get("receipts") or {}) if __name__ == "__main__": From cafb9d3b5a2e968b895a2a5b7df1a44e1f168398 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:17:16 -0800 Subject: [PATCH 17/52] test(crew): drop client names and item ids from coordination tests devkit's code and tests never name a client, and work item ids point into the private handoff repository; the comments already say what each test reproduces Verified: dev test run on the three files: 11 passed --- tests/test_coordination_ci.py | 4 ++-- tests/test_coordination_identity.py | 6 +++--- tests/test_coordination_lanes.py | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/test_coordination_ci.py b/tests/test_coordination_ci.py index ea34dfb0..aa4f1faa 100644 --- a/tests/test_coordination_ci.py +++ b/tests/test_coordination_ci.py @@ -48,7 +48,7 @@ def spy(argv, *args, **kwargs): # the step's own shell, as run_local_ci starts class JobNeverStartedTests(unittest.TestCase): def test_run_view_failed_names_the_annotation_of_a_job_that_never_started(self): - # B-igm6xuux0ffp: the Signature PR run started no job; `dev run view --failed` said "failing log + # a release PR's run started no job; `dev run view --failed` said "failing log # unavailable: log not found", and only the check run's annotation said why with Sandbox() as s: s.gh.on(["run", "view"], {"workflowName": "ci", "number": 40, "conclusion": "failure", @@ -85,7 +85,7 @@ def setUp(self): self.addCleanup(path.stop) def test_the_ci_watch_names_why_a_job_never_started(self): - # B-igm6xuux0ffp: `dev ci watch` reported the failed run with class unknown and no first error + # `dev ci watch` reported the failed run with class unknown and no first error url = f"https://github.com/acme/api/actions/runs/{RUN_ID}/job/{JOB_ID}" failed = run("failed", rid=RUN_ID, n=40, conclusion="failure", jobs=[{"name": "tests (Python 3.13, part 1 of 2)", "status": "failed", "current": "", diff --git a/tests/test_coordination_identity.py b/tests/test_coordination_identity.py index 67d6c5f2..19da84c0 100644 --- a/tests/test_coordination_identity.py +++ b/tests/test_coordination_identity.py @@ -23,7 +23,7 @@ def plan_with_link(self): with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): pg.start("Release", plan=["sig2625", "ci-redirect"]) pg.assign("sig2625", "Link", why="the test's assignment") - launch("a_link", "devkit:link", "Link: sig2625 Signature release") + launch("a_link", "devkit:link", "Link: sig2625 copy release") def state_of(self, name): return next(s for s in self.run_()["plan"] if s["name"] == name).get("state") @@ -31,7 +31,7 @@ def state_of(self, name): class MemberWaitTests(CoordinationCallerCase): def test_the_tech_leads_begin_stays_theirs_while_a_member_waits_on_a_question_that_quotes_it(self): - # B-igm6pqbcs6l4: three tries of the tech lead's `dev progress begin ci-redirect` were refused as "inside a + # three tries of the tech lead's `dev progress begin ci-redirect` were refused as "inside a # crew member's call" while the Release engineer's `dev crew ask` waited for its answer; that question quoted # the command, and the call ledger took the member's open call for the one that typed it self.plan_with_link() @@ -46,7 +46,7 @@ def test_the_tech_leads_begin_stays_theirs_while_a_member_waits_on_a_question_th class NestedReadTests(CoordinationCallerCase): def test_the_tech_lead_acknowledges_with_a_digest_read_in_the_same_command(self): - # B-igm4c0qjyobs: `dev crew ack REF --sha256 "$(dev crew read REF --json | python3 -c …)" --generation 1` + # `dev crew ack REF --sha256 "$(dev crew read REF --json | python3 -c …)" --generation 1` # was refused as not_recipient in the main session; the same two calls typed one after the other passed self.plan_with_link() report = pg.crew_ask("Report: " + "x" * 400, from_agent="a_link") diff --git a/tests/test_coordination_lanes.py b/tests/test_coordination_lanes.py index 9a0999b8..1f0ddd0b 100644 --- a/tests/test_coordination_lanes.py +++ b/tests/test_coordination_lanes.py @@ -56,7 +56,7 @@ def test_a_members_checked_record_without_step_closes_its_lanes_only_running_ste class QueuedStepTests(LaneCase): def test_a_lane_whose_step_closes_takes_the_first_of_two_steps_assigned_to_its_member(self): - # F-igm4bz4ptvvr: the DevEx engineer's three steps were assigned by role before the launch, whose description + # the DevEx engineer's three steps were assigned by role before the launch, whose description # named launch-warn. When launch-warn closed, the lane took neither reassign-notice nor lesson-review ("with # two waiting devkit gives a lane neither"), and its scope stayed launch-warn's pg.start("Open bugs", plan=["launch-warn=45m", "reassign-notice=45m", "lesson-review=60m"], now=self.m(0)) @@ -78,8 +78,8 @@ def test_a_blocked_step_leaves_its_lane_free_for_the_members_next_step_and_its_f # "joins your lane once sig2625 closes", so dev commit refused ci-redirect's files and his # `dev progress step --step ci-redirect` was refused pg.start("Release", plan=["sig2625=60m", "ci-redirect=60m"], now=self.m(0)) - pg.assign("sig2625", "Link", scope="docs/signature.md", why="test", now=self.m(0)) - launch("a_link", "devkit:link", "Link: sig2625 Signature release", at=self.m(1)) + pg.assign("sig2625", "Link", scope="docs/copy.md", why="test", now=self.m(0)) + launch("a_link", "devkit:link", "Link: sig2625 copy release", at=self.m(1)) pg.step("PR #20's run started no job: the Actions budget is spent", kind="blocked", which="sig2625", now=self.m(30)) self.assertEqual(self.held("sig2625"), ("a_link", "blocked")) @@ -109,7 +109,7 @@ def test_a_resumed_lane_takes_the_one_step_assigned_to_its_member_by_role(self): class ScopeClashTests(LaneCase): def test_a_glob_of_files_does_not_clash_with_other_files_it_cannot_hold(self): - # S-g580qopirdu: `docs/**/bug*.md` was refused as overlapping the DevEx engineer's docs/crew.md and + # `docs/**/bug*.md` was refused as overlapping the DevEx engineer's docs/crew.md and # docs/agents.md, which no path it holds can be pg.start("Docs", plan=["launch-warn=45m", "registry-docs=30m"], now=self.m(0)) pg.assign("launch-warn", "Kid", scope="docs/crew.md,docs/agents.md", why="test", now=self.m(0)) From a3bdf702539bb01b234f7d520651763faa192bf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:24:08 -0800 Subject: [PATCH 18/52] fix(ci): stop naming cancelled jobs and failed tests as never started A run a newer push cancelled, or a matrix leg fail-fast stopped, was reported as a job that never started with the advice to rerun it; a failed test named test_billing read as an account limit; and dev run view exited 0 on a run GitHub could not start. Root cause: never_started counted every job without steps, cancelled ones too, diagnose ran it for stopped runs, NOT_STARTED_RE and BUDGET_RE matched the bare words billing and budget, and _run_view only looked at failed jobs, which a startup failure has none of A stopped run skips the never-started check; a cancelled job counts only when its annotation says it was not started; dev run view leaves cancelled jobs out of that check. The patterns match only GitHub's own phrases. dev run view classes a startup failure as workflow_invalid, with its next action, and exits 1. Verified: python3 -m unittest tests.test_ci_not_started tests.test_coordination_ci tests.test_ciwatch tests.test_gitx tests.test_ci_watch_limits: 252 tests OK --- lib/devkit/ciwatch.py | 21 +++++++++----- lib/devkit/gitx.py | 14 +++++++--- tests/test_ci_not_started.py | 53 ++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 11 deletions(-) diff --git a/lib/devkit/ciwatch.py b/lib/devkit/ciwatch.py index b86a5122..e47b9517 100644 --- a/lib/devkit/ciwatch.py +++ b/lib/devkit/ciwatch.py @@ -135,10 +135,12 @@ "workflow_invalid": "GitHub could not start the run, so a workflow file is invalid: run dev ci audit and " "actionlint, fix the file, push once", } -# A check-run annotation that says the job never ran, and the ones that name an account's spending limit or payments -NOT_STARTED_RE = re.compile(r"(?i)\b(?:was|were) not (?:started|acquired)\b|spending limit|budget is preventing|" - r"payments? (?:have |has )?failed|account is locked|billing") -BUDGET_RE = re.compile(r"(?i)spending limit|\bbudget\b|payments? (?:have |has )?failed|account is locked|billing") +# GitHub's own phrases in a check-run annotation that says the job never ran, and those that name an account limit +# (its spending limit, failed payments, a budget, a lock over billing). Phrases, never bare words: a failed test's +# annotation such as "tests/test_billing.py::test_total - AssertionError" is no account limit +BUDGET_PHRASES = r"spending limit|payments have failed|budget is preventing|locked due to a billing issue" +NOT_STARTED_RE = re.compile(r"(?i)\bwas not started because\b|\bwas not acquired by\b|" + BUDGET_PHRASES) +BUDGET_RE = re.compile(r"(?i)" + BUDGET_PHRASES) _SLUG_RE = re.compile(r"github\.com/([\w.-]+/[\w.-]+)/actions/runs/") _JOB_RE = re.compile(r"/actions/runs/\d+/job/(\d+)") ERROR_LINE = re.compile(r"(?i)\b(error|failed|failure|fatal|exception|traceback|assert|panic|cannot|could not|" @@ -304,12 +306,15 @@ def never_started(slug: str, job_id, gh=None, job: dict | None = None) -> dict | """Why a failed GitHub Actions job never started -> {"class": "not_started", "subclass": "budget" or "", "cause": its annotation, "action": the one next action}, or None when it ran. `job`: its record from gh or cistatus, when known: a job with steps ran, and its annotations are not read; one with no steps never started, - with or without an annotation; with no record, an annotation that says the job was not started decides.""" + with or without an annotation; with no record, an annotation that says the job was not started decides. A + cancelled job with no steps was usually stopped while it waited (a newer push's cancel-in-progress, a fail-fast + matrix): only an annotation that says it was not started counts it.""" ran = _job_started(job) if ran: return None + cancelled = "cancelled" in ((job or {}).get("status"), (job or {}).get("conclusion")) cause = job_annotation(slug, job_id, gh) - if ran is None and not NOT_STARTED_RE.search(cause): + if (ran is None or cancelled) and not NOT_STARTED_RE.search(cause): return None sub = "budget" if BUDGET_RE.search(cause) else "" return {"class": "not_started", "subclass": sub, "cause": cause, "action": ACTIONS[sub or "not_started"]} @@ -344,7 +349,9 @@ def diagnose(provider: str, top: str, run: dict, repo: str = "") -> dict: if kind == "unknown" and log and word not in STOPPED: # the first error says too little: the failed log's end kind = classify(first_error(log[-20_000:], context=0, limit=10_000) or log[-20_000:]) sub, cause, unstarted = "", "", None - if provider == "github" and not log: # no log: a job that never ran, or a run GitHub could not start + # no log: a job that never ran, or a run GitHub could not start. A run that was cancelled or timed out stopped + # its jobs itself, so its queued ones are no jobs that never started + if provider == "github" and not log and word not in STOPPED: slug = repo or next((m.group(1) for m in (_SLUG_RE.search(str(x.get("url") or "")) for x in jobs + [run]) if m), "") for j in jobs[:3]: diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 3a16a405..68053588 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -4758,6 +4758,10 @@ def _run_view(c, a) -> int: "startup_failure") else ui.INFO print(f"{mark} {r.get('workflowName')} #{r.get('number')} {state} · {r.get('headBranch')} " f"{(r.get('headSha') or '')[:7]} · {r.get('event')} · {r.get('url')}") + if state == "startup_failure": # GitHub could not start the run: no job ran, and there is no log to read + from . import ciwatch + print(f" {ui.FAIL} GitHub could not start the run · class workflow_invalid") + print(" " + ui.dim(f"next: {ciwatch.ACTIONS['workflow_invalid']}")) jobs = r.get("jobs") or [] bad = [j for j in jobs if j.get("conclusion") in ("failure", "timed_out", "cancelled", "startup_failure")] for j in bad: @@ -4769,15 +4773,17 @@ def _run_view(c, a) -> int: if a.failed and bad: from . import ciwatch unstarted = [] - for j in bad: # a job that never ran has no log: its check run's annotation says why + # a job that never ran has no log: its check run's annotation says why. A cancelled job (a fail-fast matrix + # leg, a newer push's cancel-in-progress) was stopped by the run, not kept from starting + for j in [j for j in bad if j.get("conclusion") != "cancelled"]: why = ciwatch.never_started(c.slug, j.get("databaseId"), GH, job=j) if why: unstarted.append(j) print(f" {ui.FAIL} {ciwatch.never_started_line(j.get('name'), why)}") print(" " + ui.dim(f"class {why['class']}" + (f" ({why['subclass']})" if why["subclass"] else "") + f" · next: {why['action']}")) - if len(unstarted) == len(bad): - return 1 + if not [j for j in bad if j not in unstarted and j.get("conclusion") != "cancelled"]: + return 1 # every failed job never started: no log to read rc, log, err = GH(["run", "view", rid, "-R", c.slug, "--log-failed"], cwd=c.top, timeout=120) if rc != 0: return fail(f"failing log unavailable: {_first_line(err)}") @@ -4790,7 +4796,7 @@ def _run_view(c, a) -> int: print(" " + row) elif bad: info(f"failing steps' logs: dev run view {rid} --failed") - return 1 if bad else 0 + return 1 if bad or state == "startup_failure" else 0 def _handoff_log(pid: str, text: str) -> bool: diff --git a/tests/test_ci_not_started.py b/tests/test_ci_not_started.py index c5163cfc..6b67d724 100644 --- a/tests/test_ci_not_started.py +++ b/tests/test_ci_not_started.py @@ -48,6 +48,38 @@ def test_run_view_failed_names_why_a_job_never_started_and_the_one_next_action(s self.assertIn("an account limit, not the code", out + err) self.assertNotIn("log unavailable", out + err) + def run_view(self, conclusion, jobs): + self.s.gh.on(["run", "view"], {"workflowName": "ci", "number": 40, "conclusion": conclusion, + "headBranch": "main", "headSha": "0bde25cdef", "event": "pull_request", + "url": JOB_URL, "jobs": jobs}, when=lambda a: "--json" in a) + return dev("run", "view", RUN_ID, "--failed") + + def test_run_view_failed_leaves_a_matrix_leg_fail_fast_cancelled_out_of_the_jobs_that_never_started(self): + self.s.gh.on(["run", "view"], "tests (part 1 of 2)\tUnit tests\tFAILED tests/test_x.py::test_y - AssertionError", + when=lambda a: "--log-failed" in a) + rc, out, err = self.run_view("failure", [ + {"name": "tests (part 1 of 2)", "conclusion": "failure", "databaseId": 1001, + "steps": [{"name": "Unit tests", "conclusion": "failure"}]}, + {"name": "tests (part 2 of 2)", "conclusion": "cancelled", "databaseId": 1002, "steps": []}]) + self.assertEqual(rc, 1, out + err) + self.assertNotIn("never started", out + err) + self.assertIn("FAILED tests/test_x.py::test_y", out + err) + + def test_run_view_failed_classes_a_run_github_could_not_start_and_fails(self): + rc, out, err = self.run_view("startup_failure", []) + self.assertEqual(rc, 1, out + err) + self.assertIn("class workflow_invalid", out + err) + self.assertIn("dev ci audit", out + err) + + def test_pr_checks_keep_a_failed_test_named_billing_a_missing_log_not_an_account_limit(self): + self.s.gh.on(["api"], [{"annotation_level": "failure", "message": "tests/test_billing.py::test_total - " + "AssertionError"}], + when=lambda a: a[1:2] == ["repos/acme/widget/check-runs/2002/annotations"]) + checks = [{"name": "unit", "bucket": "fail", + "link": f"https://github.com/acme/widget/actions/runs/{RUN_ID}/job/2002"}] + lines = dict(gitx.failing_logs(gitx.ctx(self.s.repo), checks))["unit"] + self.assertEqual(lines, [f"(log unavailable: failed to get run log: log not found: {JOB_ID})"]) + def test_pr_checks_name_why_a_failed_job_never_started_instead_of_a_missing_log(self): checks = [{"name": "tests (part 1 of 2)", "bucket": "fail", "link": f"https://github.com/acme/widget/actions/" f"runs/{RUN_ID}/job/{JOB_ID}"}] @@ -121,6 +153,27 @@ def test_an_annotation_is_shown_as_one_redacted_line_of_at_most_300_characters(s self.assertFalse(any(ch in cause for ch in "\n\r\x1b"), repr(cause)) +class CancelledDiagnosisTests(StandInGh): + notes = [{"annotation_level": "failure", + "message": "Canceling since a higher priority waiting request for 'ci-refs/heads/main' exists"}] + QUEUED_LEG = {"name": "tests (part 2 of 2)", "status": "cancelled", "current": "", "url": JOB_URL, + "steps_total": 0, "started": 0} + + def test_a_run_a_newer_push_cancelled_is_cancelled_not_never_started(self): + # concurrency's cancel-in-progress: the job was still queued, so it has no steps and no start + d = self.diagnose(conclusion="cancelled", jobs=[self.QUEUED_LEG]) + self.assertEqual((d["class"], d["subclass"], d["never_started"]), ("cancelled", "", None)) + self.assertIn("newer push", d["action"]) + + def test_a_matrix_leg_fail_fast_cancelled_is_not_a_job_that_never_started(self): + ran = {"name": "tests (part 1 of 2)", "status": "failed", "current": "Unit tests", + "url": f"https://github.com/acme/api/actions/runs/{RUN_ID}/job/1001", "steps_total": 6, + "started": 1_800_000_000} + d = self.diagnose(conclusion="failure", jobs=[ran, self.QUEUED_LEG]) + self.assertNotEqual(d["class"], "not_started") + self.assertIsNone(d["never_started"]) + + class StartupFailureTests(StandInGh): def test_a_run_that_failed_at_startup_is_an_invalid_workflow(self): d = self.diagnose(conclusion="startup_failure", jobs=[]) From 2831a9614ebab422eda54419e9b553aadc547559 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:25:30 -0800 Subject: [PATCH 19/52] fix(ci): give a timed-out step a longer run and refuse a limit under 1 A slow step that ran past its limit never earned a longer one, since a timed-out run records no pass, and --step-timeout 0 was ignored while -5 ended every step at once with exit 124. Root cause: the timeout line named only the limit, and --step-timeout was a plain int that step_limit skipped at 0 and used as given below it The timeout line names dev ci --run --resume --step-timeout with twice the limit. --step-timeout takes a whole number of minutes of 1 or more; argparse refuses anything else. Verified: python3 -m unittest tests.test_ci_limits tests.test_coordination_ci.LocalStepLimitTests tests.test_gitx_ci_shortcuts: all OK --- lib/devkit/gitx.py | 16 +++++++++++++++- tests/test_ci_limits.py | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 68053588..41479df8 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -2892,6 +2892,17 @@ def plan(root) -> list: return jobs +def _whole_minutes(text) -> int: + """--step-timeout's value: a whole number of minutes, 1 or more (0 and below would end every step at once).""" + try: + n = int(text) + except ValueError: + n = 0 + if n < 1: + raise argparse.ArgumentTypeError(f"minutes per step must be a whole number of 1 or more, not {text!r}") + return n + + def add_ci_arguments(p): """Extra `dev ci` options (call from cli.py's parser for `ci`).""" g = p.add_argument_group("local CI evidence (checked by dev push, dev pr create and dev release)", HOST_RULE) @@ -2903,7 +2914,7 @@ def add_ci_arguments(p): g.add_argument("--evidence", action="store_true", help="show whether HEAD has local CI evidence") g.add_argument("--dry-run", action="store_true", help="with --run: show the plan without running it") g.add_argument("--keep-going", action="store_true", help="with --run: do not stop at the first failure") - g.add_argument("--step-timeout", type=int, default=None, metavar="MIN", + g.add_argument("--step-timeout", type=_whole_minutes, default=None, metavar="MIN", help="with --run: minutes per step (default: the step's or its job's timeout-minutes; else 1.5 × " "its longest local pass when that is over 30; else 30)") g.add_argument("--resume", action="store_true", @@ -3496,6 +3507,9 @@ def run_step(s): print(f" {ui.dim(ui.ANSI_RE.sub('', ln))}") if timed_out: # distinct from a test failure: say which limit stopped it, so a slow step is not misread print(f" {ui.dim(f'timed out after {limit:g} min (limit from {limit_from})')}") + # a run that timed out records no pass, so its history never gives it longer by itself + longer = f"dev ci --run --resume --step-timeout {math.ceil(limit * 2)}" + print(f" {ui.dim('when it is slow, not hung: ' + longer)}") print(f" {ui.dim('exit ' + str(rc) + ' · full log: ' + core.tilde(log))}") if rc == 127 and s.get("dropped"): print(" " + ui.dim("a tool this step installs on the runner is missing here: install it on " diff --git a/tests/test_ci_limits.py b/tests/test_ci_limits.py index 51aa70da..0557166b 100644 --- a/tests/test_ci_limits.py +++ b/tests/test_ci_limits.py @@ -6,6 +6,8 @@ limit and where it came from. devkit's own unit-test step takes about 36 minutes and used to end with 124 at 30. Run: python3 -m unittest tests.test_ci_limits -v""" +import contextlib +import io import subprocess import sys import unittest @@ -83,6 +85,20 @@ def test_a_step_past_its_limit_ends_124_and_names_the_limit_and_its_source(self) self.assertEqual(gitx.step_records(gitx.ctx(self.s.repo))["test › Unit tests"]["rc"], 124) + def test_a_step_past_its_limit_names_the_command_that_gives_it_twice_the_time(self): + # a timed-out run records no pass, so the step's history never learns that it needs longer + rc, out = self.ci(workflow(job_timeout=45), slow=("test -f README.md",)) + self.assertEqual(rc, 1, out) + self.assertIn("dev ci --run --resume --step-timeout 90", out) + + def test_a_step_limit_under_one_minute_is_refused(self): + for minutes in ("0", "-5"): # 0 was ignored, and -5 ended every step at once with exit 124 + with self.subTest(minutes=minutes): + with self.assertRaises(SystemExit) as refused, contextlib.redirect_stderr(io.StringIO()): + dev("ci", "--run", "--step-timeout", minutes) + self.assertEqual(refused.exception.code, 2) + + class HistoryLimitTests(StepLimitCase): STEPS = (("Unit tests", "test -f README.md"), ("Lint", "test -d .git")) From f422bbd02e6173e8ce0c6715ab3f6a4ae57bedb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:28:41 -0800 Subject: [PATCH 20/52] fix(ci): count GitHub's job default and reusable workflows in a watch A watch's limit counted a job without timeout-minutes as no time at all and skipped the jobs of a local reusable workflow, a run waiting for its concurrency group was taken for one waiting for a runner, and the detached watcher kept the call token of the call that started it. Root cause: watch_minutes added only declared timeouts from gitx.plan, which leaves a job that calls a reusable workflow without one; RUNNER_WAIT held GitHub's pending; start_background passed no environment of its own to Popen watch_minutes reads the workflows: a job counts its timeout-minutes or GitHub's 360 without one, a local reusable workflow counts its own longest chain and a remote one 360, still between 90 and 360. Only queued and requested wait for a runner. The watcher starts with identity.detached_env(). Verified: dev test run (17 files: test_ci_watch_limits, test_ci_not_started, test_ci_limits, test_coordination_ci, test_ciwatch, test_ciwatch_sessions, test_cistatus, test_watch_e2e, test_watch_stop, test_dashnow, test_codex_watch, test_watch_gate_wiring, test_gitx, test_gitx_ci_shortcuts, test_pipelines, test_cli_ci, test_workflow_ci): 455 passed --- lib/devkit/ciwatch.py | 74 +++++++++++++++++++++++++---------- tests/test_ci_watch_limits.py | 37 +++++++++++++++++- 2 files changed, 89 insertions(+), 22 deletions(-) diff --git a/lib/devkit/ciwatch.py b/lib/devkit/ciwatch.py index e47b9517..ce016db1 100644 --- a/lib/devkit/ciwatch.py +++ b/lib/devkit/ciwatch.py @@ -59,7 +59,10 @@ WATCH_DEFAULT_MIN = 90 # a watch's limit when no job of the workflows declares a timeout, and its floor WATCH_MAX_MIN = 360 # its ceiling: GitHub ends a job at 6 hours, and a background watcher should not outlive that QUEUE_MIN = 30 # the queue's share of a watch's limit, and how long a job may wait for a runner before it is stuck -RUNNER_WAIT = ("queued", "requested", "pending") # GitHub's words for a run or job that waits for a runner +GITHUB_JOB_MIN = 360 # what GitHub gives a job without timeout-minutes, and a reusable workflow devkit cannot read +# GitHub's words for a run or job that waits for a runner. Not "pending" (a run that waits for an earlier run of its +# concurrency group to end) nor "waiting" (a job that waits for an environment's approval) +RUNNER_WAIT = ("queued", "requested") STUCK_ACTION = ("no runner has taken it: when its runs-on names a self-hosted label, compare it with the runners the " "repository has (Settings → Actions → Runners; dev ci audit) and start the one that is offline; on " "GitHub's own runners, the account's other jobs hold every slot and it starts when one frees; gh run " @@ -405,28 +408,57 @@ def _final_jobs(provider: str, repo: str, run: dict, again=None) -> list: def watch_minutes(top) -> int: """How long a watch of a commit's CI follows it before it ends as still running: the longest chain of jobs that - need each other in the repository's GitHub workflows that run on a push or a pull request, each at its - timeout-minutes, plus QUEUE_MIN for the queue. Never under WATCH_DEFAULT_MIN (so also when no job declares a - timeout, or the workflows cannot be read), never over WATCH_MAX_MIN. Jobs of different workflows run at once.""" + need each other in the repository's GitHub workflows that run on a push or a pull request, plus QUEUE_MIN for the + queue, between WATCH_DEFAULT_MIN (also when the workflows cannot be read) and WATCH_MAX_MIN. Each job counts its + timeout-minutes, GitHub's own GITHUB_JOB_MIN without one; a job that calls a local reusable workflow (`uses: + ./.github/workflows/x.yml`) counts that workflow's own longest chain, and a remote one GITHUB_JOB_MIN. Jobs of + different workflows run at once, so the longest chain of any workflow decides.""" try: - from . import gitx - jobs = {(j["file"], j["id"]): j for j in gitx.plan(top) - if not str(j.get("skip") or "").startswith("workflow runs on")} # not on a push or a pull request + from . import ci, gitx, pipelines + root = Path(top).resolve() + folder = root / ".github" / "workflows" + files = sorted(list(folder.glob("*.yml")) + list(folder.glob("*.yaml"))) if folder.is_dir() else [] + texts = {f.resolve(): f.read_text() for f in files} except Exception: # noqa: BLE001 - an unreadable workflow keeps the default, never the watch return WATCH_DEFAULT_MIN - memo = {} + trees = {} - def chain(key, seen=frozenset()): - """The minutes of the longest chain of jobs that ends with job `key`.""" - if key not in jobs or key in seen: # a need of another workflow, or a cycle GitHub would refuse - return 0 - if key not in memo: - j = jobs[key] - memo[key] = (j.get("timeout") or 0) + max( - (chain((key[0], need), seen | {key}) for need in j.get("needs") or []), default=0) - return memo[key] - longest = max((chain(k) for k in jobs), default=0) - return int(min(WATCH_MAX_MIN, max(WATCH_DEFAULT_MIN, math.ceil(longest + QUEUE_MIN)))) + def jobs_of(path) -> dict: + if path not in trees: + try: + text = texts[path] if path in texts else path.read_text() + tree = pipelines.load_yaml(text) + except Exception: # noqa: BLE001 - a workflow the reader cannot parse counts no jobs + tree = None + jobs = tree.get("jobs") if isinstance(tree, dict) else None + trees[path] = {str(k): v for k, v in jobs.items() if isinstance(v, dict)} if isinstance(jobs, dict) else {} + return trees[path] + + def job_minutes(job: dict, seen: frozenset) -> float: + uses = job.get("uses") + if isinstance(uses, str): # a reusable workflow: its own jobs, which this job cannot time + called = (root / uses[2:]).resolve() if uses.startswith("./") else None + if called is None or not called.is_file() or root not in called.parents: + return GITHUB_JOB_MIN # remote, or outside the repository: not readable here + return longest(called, seen) if called not in seen else 0 # a cycle GitHub refuses + return gitx._minutes(job.get("timeout-minutes")) or GITHUB_JOB_MIN + + def longest(path, seen=frozenset()) -> float: + """The minutes of the longest chain of jobs that need each other in workflow `path`.""" + jobs, memo = jobs_of(path), {} + + def chain(jid, stack=frozenset()): + if jid not in jobs or jid in stack: # a need of no job here, or a cycle GitHub would refuse + return 0 + if jid not in memo: + job = jobs[jid] + memo[jid] = job_minutes(job, seen | {path}) + max( + (chain(str(need), stack | {jid}) for need in pipelines._as_list(job.get("needs"))), default=0) + return memo[jid] + return max((chain(jid) for jid in jobs), default=0) + runs = [p for p, text in texts.items() if set(ci.parse_workflow(text).get("on") or []) & gitx.CI_TRIGGERS] + most = max((longest(p) for p in runs), default=0) + return int(min(WATCH_MAX_MIN, max(WATCH_DEFAULT_MIN, math.ceil(most + QUEUE_MIN)))) def _stuck(provider: str, runs: list, waits: dict, now: float) -> list: @@ -1090,13 +1122,15 @@ def start_background(top: str, session: str = "", branch: str = "", sha: str = " return False except (ValueError, ProcessLookupError, PermissionError, OSError): pass + from . import identity log = open(STATE / "logs" / "ci-watch.log", "a") if (STATE / "logs").exists() else subprocess.DEVNULL + # detached, so it never acts for the call that started it: its environment drops that call's token p = subprocess.Popen([sys.executable, "-I", "-S", str(core.release_home() / "bin" / "dev"), "ci", "watch", "--quiet", "--branch", branch, "--sha", sha, "--timeout", str(limit)] + (["--session", session] if session else []) + (["--since", f"{since:.3f}"] if since else []), cwd=top, stdin=subprocess.DEVNULL, stdout=log, stderr=log, start_new_session=True, - close_fds=True) + close_fds=True, env=identity.detached_env()) lock.write_text(f"{p.pid} {int(time.time())}") register(target, "devkit", agent, sid, p.pid, limit) return True diff --git a/tests/test_ci_watch_limits.py b/tests/test_ci_watch_limits.py index 2d9beaa4..5815ddef 100644 --- a/tests/test_ci_watch_limits.py +++ b/tests/test_ci_watch_limits.py @@ -32,6 +32,13 @@ NIGHTLY = ("name: nightly\non:\n schedule:\n - cron: '0 3 * * *'\njobs:\n soak:\n runs-on: ubuntu-latest\n" " timeout-minutes: 300\n steps:\n - run: make soak\n") UNTIMED = "name: CI\non: [push]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - run: make test\n" +CALLER = ("name: CI\non: [pull_request]\njobs:\n" + " build:\n runs-on: ubuntu-latest\n timeout-minutes: 20\n steps:\n - run: make\n" + " release:\n needs: build\n uses: ./.github/workflows/publish.yml\n") +PUBLISH = ("name: publish\non:\n workflow_call:\njobs:\n" + " pack:\n runs-on: ubuntu-latest\n timeout-minutes: 50\n steps:\n - run: make dist\n" + " upload:\n needs: pack\n runs-on: ubuntu-latest\n timeout-minutes: 40\n steps:\n" + " - run: make upload\n") def repo_with(**workflows) -> str: @@ -67,8 +74,25 @@ def test_a_watch_lasts_the_longest_needs_chain_of_job_timeouts_plus_the_queue(se self.assertGreaterEqual(res["minutes"], 125) self.assertLess(res["minutes"], 127) - def test_workflows_that_declare_no_job_timeout_keep_the_90_minute_default(self): - self.assertEqual(ciwatch.watch_minutes(repo_with(ci=UNTIMED)), 90) + def test_a_job_without_timeout_minutes_counts_githubs_six_hour_default(self): + self.assertEqual(ciwatch.watch_minutes(repo_with(ci=UNTIMED)), 360) # 360 and the queue, at the 360 ceiling + + def test_a_local_reusable_workflow_counts_the_chain_of_its_own_jobs(self): + top = repo_with(ci=CALLER, publish=PUBLISH) # build 20 -> release (pack 50 -> upload 40), and the queue + self.assertEqual(ciwatch.watch_minutes(top), 140) + + def test_the_background_watcher_never_carries_the_call_token_of_the_call_that_started_it(self): + started = [] + spawn = types.SimpleNamespace(Popen=lambda args, **k: started.append(k) or mock.Mock(pid=os.getpid()), + DEVNULL=-3) + with mock.patch.object(ciwatch, "subprocess", spawn), \ + mock.patch.dict(os.environ, {"DEVKIT_NO_CI_WATCH": "", "DEVKIT_CALL": "toolu_01.nonce"}): + self.assertTrue(ciwatch.start_background(repo_with(ci=CHAIN), session="claude:s1", branch="main", + sha="abc1234")) + env = started[0].get("env") + self.assertIsNotNone(env) + self.assertNotIn("DEVKIT_CALL", env) + self.assertEqual(env.get("HOME"), os.environ.get("HOME")) def test_the_background_watch_of_a_push_gets_the_derived_limit(self): top = repo_with(ci=CHAIN) @@ -104,6 +128,15 @@ def test_a_job_no_runner_takes_is_named_with_its_next_action_once_nothing_else_o self.assertTrue(last.startswith("CI still running · "), last) self.assertRegex(last, r"job “deploy” of ci #41 has waited 8\d min for a runner.*re-arm: dev ci watch --wait") + def test_a_run_waiting_for_its_concurrency_group_is_not_taken_for_one_waiting_for_a_runner(self): + # GitHub's "pending": the run waits until an earlier run of its concurrency group ends, not for a runner + clock, heard = Clock(), [] + res = ciwatch.watch(repo_with(ci=CHAIN), branch="main", sha="abc1234", sleep=clock.sleep, clock=clock, + runs_fn=self.sequence([gh_run(status="pending")]), on_event=heard.append) + self.assertEqual(res["state"], "timeout") + self.assertNotIn("stuck", res) + self.assertEqual([line for line in heard if "for a runner" in line], []) + if __name__ == "__main__": unittest.main() From 323a33305693f070f8e57313cccf63b1d929c748 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:30:27 -0800 Subject: [PATCH 21/52] test(ci): keep the stopped-run cases in a class of their own The cancelled-leg, billing-test and startup-failure cases sat inside the class of the never-started tests, so a change to them read as a change to those tests. They move to GitxStoppedRunTests, with the same fake gh; no test changes what it checks. Verified: python3 -m unittest tests.test_ci_not_started: 11 tests OK --- tests/test_ci_not_started.py | 75 +++++++++++++++++++++--------------- 1 file changed, 43 insertions(+), 32 deletions(-) diff --git a/tests/test_ci_not_started.py b/tests/test_ci_not_started.py index 6b67d724..5191770d 100644 --- a/tests/test_ci_not_started.py +++ b/tests/test_ci_not_started.py @@ -48,38 +48,6 @@ def test_run_view_failed_names_why_a_job_never_started_and_the_one_next_action(s self.assertIn("an account limit, not the code", out + err) self.assertNotIn("log unavailable", out + err) - def run_view(self, conclusion, jobs): - self.s.gh.on(["run", "view"], {"workflowName": "ci", "number": 40, "conclusion": conclusion, - "headBranch": "main", "headSha": "0bde25cdef", "event": "pull_request", - "url": JOB_URL, "jobs": jobs}, when=lambda a: "--json" in a) - return dev("run", "view", RUN_ID, "--failed") - - def test_run_view_failed_leaves_a_matrix_leg_fail_fast_cancelled_out_of_the_jobs_that_never_started(self): - self.s.gh.on(["run", "view"], "tests (part 1 of 2)\tUnit tests\tFAILED tests/test_x.py::test_y - AssertionError", - when=lambda a: "--log-failed" in a) - rc, out, err = self.run_view("failure", [ - {"name": "tests (part 1 of 2)", "conclusion": "failure", "databaseId": 1001, - "steps": [{"name": "Unit tests", "conclusion": "failure"}]}, - {"name": "tests (part 2 of 2)", "conclusion": "cancelled", "databaseId": 1002, "steps": []}]) - self.assertEqual(rc, 1, out + err) - self.assertNotIn("never started", out + err) - self.assertIn("FAILED tests/test_x.py::test_y", out + err) - - def test_run_view_failed_classes_a_run_github_could_not_start_and_fails(self): - rc, out, err = self.run_view("startup_failure", []) - self.assertEqual(rc, 1, out + err) - self.assertIn("class workflow_invalid", out + err) - self.assertIn("dev ci audit", out + err) - - def test_pr_checks_keep_a_failed_test_named_billing_a_missing_log_not_an_account_limit(self): - self.s.gh.on(["api"], [{"annotation_level": "failure", "message": "tests/test_billing.py::test_total - " - "AssertionError"}], - when=lambda a: a[1:2] == ["repos/acme/widget/check-runs/2002/annotations"]) - checks = [{"name": "unit", "bucket": "fail", - "link": f"https://github.com/acme/widget/actions/runs/{RUN_ID}/job/2002"}] - lines = dict(gitx.failing_logs(gitx.ctx(self.s.repo), checks))["unit"] - self.assertEqual(lines, [f"(log unavailable: failed to get run log: log not found: {JOB_ID})"]) - def test_pr_checks_name_why_a_failed_job_never_started_instead_of_a_missing_log(self): checks = [{"name": "tests (part 1 of 2)", "bucket": "fail", "link": f"https://github.com/acme/widget/actions/" f"runs/{RUN_ID}/job/{JOB_ID}"}] @@ -153,6 +121,49 @@ def test_an_annotation_is_shown_as_one_redacted_line_of_at_most_300_characters(s self.assertFalse(any(ch in cause for ch in "\n\r\x1b"), repr(cause)) +class GitxStoppedRunTests(unittest.TestCase): + """What `dev run view --failed` and `dev pr checks` must not take for a job that never started: a matrix leg the + run cancelled, a failed test whose name holds an account word, and a run GitHub could not start at all.""" + + def setUp(self): + self.s = Sandbox().__enter__() + self.addCleanup(self.s.__exit__, None, None, None) + self.s.gh.on(["run", "view"], rc=1, err=f"failed to get run log: log not found: {JOB_ID}", + when=lambda a: "--log-failed" in a) + + def run_view(self, conclusion, jobs): + self.s.gh.on(["run", "view"], {"workflowName": "ci", "number": 40, "conclusion": conclusion, + "headBranch": "main", "headSha": "0bde25cdef", "event": "pull_request", + "url": JOB_URL, "jobs": jobs}, when=lambda a: "--json" in a) + return dev("run", "view", RUN_ID, "--failed") + + def test_run_view_failed_leaves_a_matrix_leg_fail_fast_cancelled_out_of_the_jobs_that_never_started(self): + self.s.gh.on(["run", "view"], "tests (part 1 of 2)\tUnit tests\tFAILED tests/test_x.py::test_y - AssertionError", + when=lambda a: "--log-failed" in a) + rc, out, err = self.run_view("failure", [ + {"name": "tests (part 1 of 2)", "conclusion": "failure", "databaseId": 1001, + "steps": [{"name": "Unit tests", "conclusion": "failure"}]}, + {"name": "tests (part 2 of 2)", "conclusion": "cancelled", "databaseId": 1002, "steps": []}]) + self.assertEqual(rc, 1, out + err) + self.assertNotIn("never started", out + err) + self.assertIn("FAILED tests/test_x.py::test_y", out + err) + + def test_run_view_failed_classes_a_run_github_could_not_start_and_fails(self): + rc, out, err = self.run_view("startup_failure", []) + self.assertEqual(rc, 1, out + err) + self.assertIn("class workflow_invalid", out + err) + self.assertIn("dev ci audit", out + err) + + def test_pr_checks_keep_a_failed_test_named_billing_a_missing_log_not_an_account_limit(self): + self.s.gh.on(["api"], [{"annotation_level": "failure", "message": "tests/test_billing.py::test_total - " + "AssertionError"}], + when=lambda a: a[1:2] == ["repos/acme/widget/check-runs/2002/annotations"]) + checks = [{"name": "unit", "bucket": "fail", + "link": f"https://github.com/acme/widget/actions/runs/{RUN_ID}/job/2002"}] + lines = dict(gitx.failing_logs(gitx.ctx(self.s.repo), checks))["unit"] + self.assertEqual(lines, [f"(log unavailable: failed to get run log: log not found: {JOB_ID})"]) + + class CancelledDiagnosisTests(StandInGh): notes = [{"annotation_level": "failure", "message": "Canceling since a higher priority waiting request for 'ci-refs/heads/main' exists"}] From ec4ab26720eabb65cdd49b474b08030757583f48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:34:09 -0800 Subject: [PATCH 22/52] fix(identity): list every coordination command that changes state identity.STATE_CHANGING named a progress order command dev does not have and missed commands that change crew, session, task and plan records, so a tokenless call of those fell back to text matching in a session whose calls carry tokens. Root cause: the set was written from the design's list instead of from dev's parser, and nothing checked it against the commands dev runs A test walks dev's parser over progress, crew, session, task and plan and runs every subcommand twice, in a fresh fixture: once stopped where it asks who calls, once as the tech lead with a snapshot of the records before and after. A subcommand that changes records must be in STATE_CHANGING, one that only asks who calls in the new READS, and every listed name must exist. Verified: dev test run (7 files): 164 passed; dev test prove: both coverage tests fail without the change --- lib/devkit/identity.py | 27 +++- tests/test_identity_coverage.py | 266 ++++++++++++++++++++++++++++++++ 2 files changed, 286 insertions(+), 7 deletions(-) create mode 100644 tests/test_identity_coverage.py diff --git a/lib/devkit/identity.py b/lib/devkit/identity.py index 025df89d..777e6cd2 100644 --- a/lib/devkit/identity.py +++ b/lib/devkit/identity.py @@ -66,15 +66,28 @@ _TOKEN = re.compile(r"[A-Za-z0-9_-]{1,120}\.[A-Za-z0-9_-]{22}") _TID = re.compile(r"[A-Za-z0-9_-]{1,120}") -# The commands that use acting_lane, require or progress.caller for authority: a call token decides them, and in a -# session whose hook stamps tokens nothing else does. Everything else (watch, crew read, inbox and decisions, session -# read and ls, progress status and history) is a read or a wait. +# The commands that change a run, a session's records, the crew's records, work items or plans (whether or not they +# ask who calls): a call token decides who runs them, and in a session whose hook stamps tokens nothing else does. A +# subcommand that does both (`crew mode`, `crew raci`, `crew next`) is here when one of its forms changes state. +# Everything else (watch, the READS below, and the commands that ask nobody) is a read or a wait. STATE_CHANGING = { "progress": frozenset({"start", "step", "block", "done", "note", "add", "assign", "begin", "reopen", "skip", - "confirm", "order"}), - "crew": frozenset({"ask", "answer", "decide", "withdraw", "mode", "delegate", "decline", "route", "ack"}), - "session": frozenset({"tell", "ask", "answer", "claim", "escalate", "ack"}), - "task": frozenset({"start", "done", "release"}), + "confirm"}), + "crew": frozenset({"ask", "answer", "decide", "withdraw", "mode", "delegate", "decline", "route", "ack", "next", + "raci", "set"}), + "session": frozenset({"tell", "ask", "answer", "claim", "release", "escalate", "ack", "carry", "forget", + "replay"}), + "task": frozenset({"add", "start", "claim", "release", "done", "block", "unblock", "cancel", "reopen", "link", + "delegate", "move", "edit", "reconcile"}), + "plan": frozenset({"new", "revise", "approve", "supersede"}), +} +# The commands that ask who calls only to know whose records to read or wait on: a failed token lets them fall to the +# rules above. tests/test_identity_coverage.py runs every coordination subcommand and holds both sets to what it finds. +READS = { + "progress": frozenset({"history"}), + "crew": frozenset({"read", "inbox", "decisions", "owner"}), + "session": frozenset({"ls", "read", "inbox", "brief"}), + "task": frozenset({"ls"}), } STALE = ("this call's identity has ended (its call closed, or ran past its time limit); a background command's " diff --git a/tests/test_identity_coverage.py b/tests/test_identity_coverage.py new file mode 100644 index 00000000..8323e3aa --- /dev/null +++ b/tests/test_identity_coverage.py @@ -0,0 +1,266 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# identity.STATE_CHANGING is the set of commands a call token decides and, in a session whose calls carry tokens, +# nothing else does. This test walks dev's parser (cli.build_parser, read, never edited) over the commands that +# coordinate work (progress, crew, session, task, plan) and runs every subcommand twice, each time in a fresh +# fixture: once with devkit's identity lookups (acting_lane, require, verified_lane, progress.caller) stopping the +# command where it asks who calls, and once with them naming the tech lead, to see whether the command changes the +# run, the session record, the work items, the plans or the crew's records. A subcommand that changes any of them +# must be in STATE_CHANGING; one that only asks who calls must be in identity.READS; every name in either must be a +# subcommand dev has. +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_identity_coverage -v +import argparse +import contextlib +import hashlib +import io +import re +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +import _hermetic # noqa: E402 + +_hermetic.activate() +sys.path.insert(0, str(ROOT / "lib")) + +from devkit import cli, core, identity, peers, plans, work # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_progress import TempState, launch # noqa: E402 + +FAMILIES = ("progress", "crew", "session", "task", "plan") +# what each subcommand runs with, as the tech lead would type it; {M}, {D}, {T} and {P} are the fixture's message, +# decision, work item and plan. A subcommand dev gains without a line here fails the test until it gets one. +CASES = { + ("progress", "start"): ["Second run", "--replace", "--why", "a new goal", "--plan", "a; b"], + ("progress", "note"): ["still working"], + ("progress", "step"): ["docs written", "--step", "docs", "--check", "✓ read it twice"], + ("progress", "block"): ["waiting for the API key"], + ("progress", "done"): ["finished", "--why", "the test's end"], + ("progress", "assign"): ["docs", "--to", "Ghost"], + ("progress", "begin"): ["docs"], + ("progress", "add"): ["extra=10m"], + ("progress", "reopen"): ["docs", "--why", "redo"], + ("progress", "skip"): ["docs", "--why", "not needed"], + ("progress", "confirm"): ["docs", "--why", "still holds"], + ("progress", "history"): [], + ("progress", "time"): [], + ("crew", "raci"): ["backend", "--set", "R=tank A=seraph C=architect I=ghost", "--why", "a test"], + ("crew", "set"): ["tank", "summary", "Builds APIs", "--why", "shorter"], + ("crew", "history"): [], + ("crew", "rules"): [], + ("crew", "graph"): [], + ("crew", "show"): ["tank"], + ("crew", "brief"): ["tank", "Add", "the", "export", "--step", "parser"], + ("crew", "sync"): None, # writes devkit's generated agent files into its own checkout: never run here + ("crew", "ask"): ["Is the parser done?"], + ("crew", "answer"): ["{M}", "yes"], + ("crew", "read"): ["{M}", "--json"], + ("crew", "ack"): ["{M}", "--sha256", "{M_SHA}", "--generation", "1"], + ("crew", "inbox"): [], + ("crew", "mode"): ["auto"], + ("crew", "decide"): ["{D}", "yes"], + ("crew", "withdraw"): ["{D}", "--why", "no longer applies"], + ("crew", "decisions"): [], + ("crew", "route"): ["--plan", "--apply"], + ("crew", "delegate"): ["review", "the", "parser", "--to", "Seraph"], + ("crew", "decline"): ["parser", "--why", "not mine"], + ("crew", "owner"): ["lib/x.py"], + ("crew", "next"): ["--first", "docs", "--why", "the developer asked for it first"], + ("session", "brief"): [], + ("session", "carry"): [], + ("session", "compactions"): ["{TRANSCRIPT}"], + ("session", "forget"): ["--session", "claude:s1"], + ("session", "ls"): [], + ("session", "tell"): ["@all", "the parser is done"], + ("session", "ask"): ["@all", "is anyone on the parser?"], + ("session", "answer"): ["Q1", "yes"], + ("session", "inbox"): [], + ("session", "read"): ["S1"], + ("session", "ack"): ["S1", "--sha256", "0" * 64, "--generation", "1"], + ("session", "claim"): ["release:acme/api", "--why", "releasing"], + ("session", "release"): ["release:acme/api"], + ("session", "claims"): [], + ("session", "escalate"): ["@all", "who releases?", "--options", "A: me; B: you", "--recommend", "A"], + ("session", "escalations"): [], + ("session", "replay"): [], + ("task", "add"): ["Write", "the", "docs", "-p", "acme/api"], + ("task", "start"): ["{T}", "-p", "acme/api"], + ("task", "claim"): ["{T}", "-p", "acme/api"], + ("task", "release"): ["{T}", "-p", "acme/api"], + ("task", "done"): ["{T}", "--why", "shipped", "-p", "acme/api"], + ("task", "block"): ["{T}", "--why", "waits on the API", "-p", "acme/api"], + ("task", "unblock"): ["{T}", "--why", "the API is up", "-p", "acme/api"], + ("task", "cancel"): ["{T}", "--why", "not needed", "-p", "acme/api"], + ("task", "reopen"): ["{T}", "--why", "again", "-p", "acme/api"], + ("task", "show"): ["{T}", "-p", "acme/api"], + ("task", "history"): ["{T}", "-p", "acme/api"], + ("task", "link"): ["{T}", "--to", "https://example.com/issue/1", "-p", "acme/api"], + ("task", "delegate"): ["{T}", "--to", "ada", "--why", "her area", "-p", "acme/api"], + ("task", "move"): ["{T}", "--to", "now", "--why", "urgent", "-p", "acme/api"], + ("task", "edit"): ["{T}", "--title", "Fix the login timeout now", "--why", "clearer", "-p", "acme/api"], + ("task", "reconcile"): ["-p", "acme/api"], + ("task", "ls"): ["-p", "acme/api"], + ("plan", "new"): ["Export", "invoices", "-p", "acme/api"], + ("plan", "revise"): ["{P}", "--why", "a new step"], + ("plan", "approve"): ["{P}"], + ("plan", "supersede"): ["{P}", "--why", "replaced"], + ("plan", "ls"): ["-p", "acme/api"], +} +# listed commands that find nothing to change in the fixture: no continuity records to forget (a session's brief +# writes them later), no message waiting to be sent again +NOTHING_TO_DO = {("session", "forget"), ("session", "replay")} +LOOKUPS = ("acting_lane", "require", "verified_lane") +QUIET = ("audit", "logs", "timing", "task-lists", "captures", "bugs", "crashes", "prompt-state", "continuity") +LOCK = re.compile(r"\.lock\Z|\A[0-9a-f]{32}-\d+\Z") # a record's lock and its holder's mark, not a record + + +class _Asked(BaseException): + # raised where a command asks who calls, so it stops there and changes nothing + pass + + +def _subparsers(p): + return next((a.choices for a in p._actions if isinstance(a, argparse._SubParsersAction)), {}) + + +def subcommands() -> set: + # every (command, subcommand) of the coordination commands, as dev's parser has them: its subparsers, or the + # choices of its first positional (dev session brief|carry|…) + top, out = _subparsers(cli.build_parser()), set() + for fam in FAMILIES: + subs = _subparsers(top[fam]) + if subs: + out |= {(fam, name) for name in subs} + else: + first = next(a for a in top[fam]._actions if not a.option_strings and a.choices) + out |= {(fam, name) for name in first.choices} + return out + + +class Coordination: + # a run with a member at work, a message to the tech lead, a decision waiting, a work item and a plan + def __enter__(self): + self.state = TempState(real_caller=True).__enter__() + self.root = Path(self.state.tmp.name) + handoff = self.root / "handoff" + self.patches = [mock.patch.object(core, "HANDOFF", handoff), mock.patch.object(work, "HANDOFF", handoff), + mock.patch.object(work, "ITEMS", handoff / "items"), + mock.patch.object(work, "_commit", lambda *a, **k: None), + mock.patch.object(plans, "HANDOFF", handoff), mock.patch.object(plans, "PLANS", + handoff / "plans"), + # the work items' project, which no registry on this test's Mac knows + mock.patch.object(cli, "_scope", lambda a: ("acme/api", "acme/api"))] + for p in self.patches: + p.start() + main = (mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}), + mock.patch.object(identity, "acting_lane", lambda *a, **k: "main")) + with main[0], main[1]: + pg.start("Work", plan=["parser", "docs"]) + pg.assign("parser", "Tank", why="the test's assignment") + self.decision = pg.crew_decision("Ship the parser now?", options="yes|no")["id"] + launch("a_tank", "devkit:tank", "Tank: parser") + msg = pg.crew_ask("Report: the parser is done", from_agent="a_tank") + self.message = msg["id"] + self.message_sha = msg.get("body_sha256") or hashlib.sha256(b"").hexdigest() + self.task = work.create("acme/api", "Fix the login timeout", kind="bug", why="users are logged out")["meta"][ + "id"] + self.plan = str(plans.new("acme/api", "Invoice export")) + self.transcript = self.root / "t.jsonl" + self.transcript.write_text("") + return self + + def __exit__(self, *exc): + for p in reversed(self.patches): + p.stop() + self.state.__exit__(*exc) + + def argv(self, fam, name): + fill = {"{M}": self.message, "{M_SHA}": self.message_sha, "{D}": self.decision, "{T}": self.task, + "{P}": self.plan, "{TRANSCRIPT}": str(self.transcript)} + return [fam, name] + [fill.get(w, w) for w in CASES[(fam, name)]] + + def snapshot(self) -> dict: + # every record a coordination command can change: runs, session records, the call ledger, work items, plans + # and the crew's records; devkit's own logs and the audit trail are left out + out = {} + for top in (self.root, Path(core.STATE), peers.PEERS): # and the records between sessions on this Mac + for f in top.rglob("*") if top.is_dir() else []: + rel = f.relative_to(top) + if f.is_file() and not any(part in QUIET for part in rel.parts) and not LOCK.search(f.name): + out[str(f)] = hashlib.sha256(f.read_bytes()).hexdigest() + return out + + +def run(fam, name, asked: list): + # the subcommand once, in its own fixture -> (exit code, whether it changed a record); `asked` gets the lookups + # it reached (each stops the command when `asked` is not None) + with Coordination() as fx: + argv, before = fx.argv(fam, name), fx.snapshot() + out = io.StringIO() + + def stop(what): + def f(*a, **k): + asked.append(what) + raise _Asked(what) + return f + lookups = [mock.patch.object(identity, k, stop(k)) for k in LOOKUPS] + [ + mock.patch.object(pg, "caller", stop("progress.caller"))] if asked is not None else [ + mock.patch.object(identity, "acting_lane", lambda *a, **k: "main"), + mock.patch.object(identity, "speaker", lambda *a, **k: identity.Speaker("claude", "s1", "main", "test", True)), + mock.patch.object(identity, "require", lambda sp, **k: sp), + mock.patch.object(identity, "verified_lane", lambda lane, *a, **k: lane), + mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test", "agent": "claude", + "session": "s1", "calls": []})] + with contextlib.ExitStack() as stack: + for p in lookups: + stack.enter_context(p) + stack.enter_context(mock.patch.object(sys, "argv", ["dev", *argv])) + stack.enter_context(contextlib.redirect_stdout(out)) + stack.enter_context(contextlib.redirect_stderr(out)) + try: + rc = cli.main(argv) + except _Asked: + rc = "asked" + except SystemExit as e: + rc = e.code + after = fx.snapshot() + changed = sorted(k for k in set(before) | set(after) if before.get(k) != after.get(k)) + return rc, changed, out.getvalue() + + +class StateChangingTests(unittest.TestCase): + def test_the_listed_commands_are_dev_subcommands(self): + listed = {(fam, sub) for fam, subs in identity.STATE_CHANGING.items() for sub in subs} | \ + {(fam, sub) for fam, subs in identity.READS.items() for sub in subs} + self.assertEqual(sorted(listed - subcommands()), []) + both = {(f, s) for f, subs in identity.STATE_CHANGING.items() for s in subs + if s in identity.READS.get(f, ())} + self.assertEqual(sorted(both), []) + + def test_a_subcommand_that_asks_who_calls_or_changes_state_is_listed(self): + self.assertEqual(sorted(subcommands() ^ set(CASES)), []) # every subcommand dev has, and only those, has a case + missing, wrong = [], [] + for fam, name in sorted(subcommands()): + if CASES[(fam, name)] is None: + continue + with self.subTest(f"dev {fam} {name}"): + asked = [] + run(fam, name, asked) + rc, changed, out = run(fam, name, None) + changes = name in identity.STATE_CHANGING.get(fam, ()) + reads = name in identity.READS.get(fam, ()) + if changed and not changes: + missing.append(f"dev {fam} {name} changes state ({', '.join(Path(c).name for c in changed[:3])})") + if asked and not changed and not (changes or reads): + missing.append(f"dev {fam} {name} asks who calls ({asked[0]})") + if changes and not changed and rc == 0 and (fam, name) not in NOTHING_TO_DO: # it ran, and only read + wrong.append(f"dev {fam} {name} changed nothing: {out.strip()[-160:]}") + self.assertEqual(missing + wrong, []) + + +if __name__ == "__main__": + unittest.main() From 81b5db40af7c6f51fbe30bec5f1ac7682191b680 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:40:24 -0800 Subject: [PATCH 23/52] fix(progress): say why a message read was refused A refused compound ack told the tech lead only not_recipient, not that it must run as one plain dev command. Root cause: _readable_message raised a fixed not_recipient text and dropped the reason identity gave progress.caller as why Verified: committed tree plus this change: python3 -m unittest tests.test_coordination_codex OK, the compound ack test included --- lib/devkit/progress.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 66067c0a..d03d4f7e 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -3311,7 +3311,9 @@ def _command_session(cwd=None): def _readable_message(ref, from_agent=None, cwd=None): from . import messaging if from_agent is None and _command_session(cwd) is None: - raise messaging.MessageError("not_recipient", "the main session's own command reads its messages") + why = caller(cwd).get("why") # identity's reason, such as the plain-call fix + raise messaging.MessageError("not_recipient", "the main session's own command reads its messages" + + (f": {why}" if why else "")) lane = _as_lane(from_agent, cwd) or "main" agent, sid = current_session(cwd) bare, suffix = split_id(ref) From 404f6b0c2fae3b086dbb515d9006f1d432dcc5c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:41:04 -0800 Subject: [PATCH 24/52] test(progress): follow the claim rule in the Codex lifecycle tests Three Codex lifecycle tests pinned a resumed child that stays shut out and takes no role step, which the coordination fix replaced. They now check that the resumed child takes no closed step, that a reopened step goes to its exact owner, and that a role step goes to the member's resumed lane. Verified: committed tree plus this change: python3 -m unittest tests.test_codex_lifecycle OK --- tests/test_codex_lifecycle.py | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/tests/test_codex_lifecycle.py b/tests/test_codex_lifecycle.py index 840fdea0..420a9c2f 100644 --- a/tests/test_codex_lifecycle.py +++ b/tests/test_codex_lifecycle.py @@ -53,18 +53,12 @@ def test_new_exact_assignment_resumes_despite_unrelated_reassigned_history(self) run["plan"].append({"name": "historical", "state": "done", "owner": "replacement", "label": "tank"}) pg.run_path("codex", "s1").write_text(json.dumps(run)) child = {"session_id": "s1", "agent_id": "member0", "agent_type": "tank"} - pg.bind("codex", child, now=self.now + 0.5) # the obsolete history has already revoked its authority + pg.bind("codex", child, now=self.now + 0.5) # it works again, with no step and so no files + self.assertEqual(pg.lane_scope(pg.load_run("codex", "s1"), "member0"), [[]]) pg.assign("work0", "tank: work0", now=self.now + 1, scope="current/**", why="same child rework") + self.assertEqual(pg.load_run("codex", "s1")["plan"][0]["state"], "done") # closed work stays closed pg.reopen("work0", "recheck current implementation", now=self.now + 2) - pending = pg.load_run("codex", "s1") - self.assertEqual((pending["agents"]["member0"]["state"], pending["plan"][0]["owner"]), ("done", "main")) - with mock.patch.dict(core.CFG, {"progress": {"max_parallel": 1, "reserve": 0}}): - pg.bind("codex", child, now=self.now + 2.5) - queued = pg.load_run("codex", "s1") - self.assertEqual(queued["agents"]["member0"]["state"], "done") - self.assertEqual(queued["plan"][0]["owner"], "main") - pg.bind("codex", child, now=self.now + 3) - live = pg.load_run("codex", "s1") + live = pg.load_run("codex", "s1") # the reopened step goes to the same child, its exact owner self.assertEqual((live["agents"]["member0"]["state"], live["plan"][0]["owner"]), ("running", "member0")) self.assertEqual(live["agents"]["member0"]["scope"], ["current/**"]) self.assertEqual(live["plan"][-1]["owner"], "replacement") @@ -79,8 +73,9 @@ def test_a_resumed_child_does_not_capture_an_unrelated_same_role_step(self): pg.assign("candidate", "tank", now=self.now + 1, why="a separate launch will own it") pg.bind("codex", {"session_id": "s1", "agent_id": "member0", "agent_type": "tank"}, now=self.now + 2) live = pg.load_run("codex", "s1") - self.assertEqual(live["plan"][2]["owner"], "main") - self.assertEqual(pg.lane_tools(live, "member0"), "read") + # a resumed lane of the member takes the step assigned to its member by role, and may write + self.assertEqual(live["plan"][2]["owner"], "member0") + self.assertEqual(pg.lane_tools(live, "member0"), "all") def test_exact_intent_waits_for_dependencies_and_the_childs_own_admission(self): run = pg.load_run("codex", "s1") @@ -125,7 +120,7 @@ def test_assigning_a_closed_step_keeps_the_new_child_waiting_until_reopen(self): pg.assign("work0", "trinity: work1", now=self.now + 1, why="exact replacement after reopening") child = {"session_id": "s1", "agent_id": "member1", "agent_type": "trinity"} pg.bind("codex", child, now=self.now + 2) - self.assertEqual(pg.load_run("codex", "s1")["agents"]["member1"]["state"], "done") + self.assertEqual(pg.load_run("codex", "s1")["plan"][0]["state"], "done") # it takes no closed step pg.reopen("work0", "replacement can start now", now=self.now + 3) pg.bind("codex", child, now=self.now + 4) self.assertEqual(pg.load_run("codex", "s1")["plan"][0]["owner"], "member1") From 2496399f28e67f034b0d871e505f602b8b15e27c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:43:18 -0800 Subject: [PATCH 25/52] fix(progress): let the fix after a review that asked for changes start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A review recorded with ✗ stayed unverified and blocked the step after it, so the fix waited for nothing and the tech lead closed the review by hand. Root cause: deps_open counted an unverified review as open whatever its verdict, though a review that asked for changes is finished work A review that ends with ✗ or ⚠ keeps verdict changes; the step after it is ready while the reviewed work stays unapproved. The model hunt adds a reviewer that asks for changes and a fix step after the review. Verified: committed tree plus this change: tests.test_coord_scenarios, tests.test_coord_kernel OK; DEVKIT_MODEL_SEEDS=60 tests.test_coord_model 8 OK --- lib/devkit/coord.py | 7 +++-- lib/devkit/progress.py | 20 ++++++++++---- tests/test_coord_model.py | 49 +++++++++++++++++++++++++++++++++-- tests/test_coord_scenarios.py | 22 ++++++++++++++++ 4 files changed, 89 insertions(+), 9 deletions(-) diff --git a/lib/devkit/coord.py b/lib/devkit/coord.py index 8d0aec75..cf583170 100644 --- a/lib/devkit/coord.py +++ b/lib/devkit/coord.py @@ -86,9 +86,12 @@ def scope(run: dict, aid: str) -> list: def deps_open(run: dict, s: dict, review=None) -> list: """The steps `s` waits for that are not done or skipped, in the order of its `after`. A review does not wait for - an unverified step: its Check is the verdict on that work.""" + an unverified step: its Check is the verdict on that work. A review that ended with changes requested + (`verdict` "changes", its ✗) is finished work: the step after it, the fix, does not wait for it, while the work + it reviewed stays unapproved.""" steps = {x.get("name"): x for x in (run or {}).get("plan") or []} - out = [a for a in s.get("after") or [] if a in steps and steps[a].get("state") not in DONE] + out = [a for a in s.get("after") or [] if a in steps and steps[a].get("state") not in DONE + and not (steps[a].get("state") == "unverified" and steps[a].get("verdict") == "changes")] if any(steps[a].get("state") == "unverified" for a in out) and _rv(review)(s): out = [a for a in out if steps[a].get("state") != "unverified"] return out diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index d03d4f7e..9cce8427 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -1206,11 +1206,7 @@ def is_review_step(s) -> bool: def deps_open(run, s) -> list: """The steps `s` waits for that are not done or skipped yet, in the order of its `after`. A review step does not wait for an unverified one: its Check is the verdict that approves that work.""" - steps = _by_name((run or {}).get("plan")) - out = [a for a in s.get("after") or [] if a in steps and steps[a].get("state") not in DONE] - if any(steps[a].get("state") == "unverified" for a in out) and is_review_step(s): - out = [a for a in out if steps[a].get("state") != "unverified"] - return out + return coord.deps_open(run, s, review=is_review_step) def ready(run) -> list: @@ -7277,6 +7273,8 @@ def _end_member_step(run: dict, st: dict, lane: dict, aid: str, report: str, now "the gates pass") who = lane.get("persona") or "subagent" if state_ != "done": + if approvals.is_review(st) and _review_verdict(lane, st, report) == "changes": + st["verdict"] = "changes" # finished, changes requested: the fix after it may start (coord.deps_open) st["state"] = "unverified" _log_change(run, st, old, "unverified", aid, f"{who} {'closed it' if closing else 'stopped'}; unverified: " f"{why}", now) @@ -7290,6 +7288,18 @@ def _end_member_step(run: dict, st: dict, lane: dict, aid: str, report: str, now _audit("crew.approval-refused", st.get("name") or "", str(e)[:300], "refused", project=run.get("project") or "") +def _review_verdict(lane: dict, st: dict, report: str) -> str: + """The verdict of a review step's member (approvals.verdict_of): from its last `dev progress step --step` record + of that step, else its report's Check. '' when it gave none.""" + from . import approvals, canary + ups = [u for u in lane.get("updates") or [] if u.get("kind") == "step" and u.get("step") == st.get("name")] + check = (ups[-1].get("check") if ups else "") or (canary.parse_status(report or "") or {}).get("check") or "" + try: + return approvals.verdict_of(check) + except approvals.ApprovalError: + return "" + + def _member_close(run: dict, st: dict, lane: dict, aid: str, u: dict, now: float, agent: str, sid: str) -> dict: """A member's `dev progress step "…" --step --check "…"`: when its lane holds that step, the step ends now, by the rules of the member's end (_end_member_step on this update's Check: done with a ✓, else diff --git a/tests/test_coord_model.py b/tests/test_coord_model.py index e09d28e3..a99d30e1 100644 --- a/tests/test_coord_model.py +++ b/tests/test_coord_model.py @@ -27,12 +27,52 @@ "I-intent": "only a pending step carries an intent", "I-claim": "a free running lane never leaves a step waiting for it", "I-history": "the run's count of closed steps and each step's last history entry match the plan", + "fix-after-changes": "the step after a review that asked for changes does not wait for that review", } +PLAN = model.PLAN + "; fix=20m [backend] after review" +STEPS, SCOPES = dict(model.STEPS, fix="tank"), dict(model.SCOPES, fix="fix/**") + + +QA_PROPOSE = model.propose # the hunt patches model.propose with the one below + + +def propose(rng, w=None): + """The QA engineer's proposals, and now and then the reviewer asking for changes on the review it runs.""" + if w is not None and rng.random() < 0.15: + return {"do": "reject", "member": "seraph", "step": "review", "how": "role", "named": True, "clean": True} + return QA_PROPOSE(rng, w) + + +def show(seq: list) -> str: + """model.show, with this hunt's own action.""" + return " → ".join(f"{i}. Seraph asks for changes on review" if x["do"] == "reject" else + f"{i}. " + model.show([x]).split(". ", 1)[1] for i, x in enumerate(seq, 1)) class CoordWorld(model.World): """The QA engineer's world, checked against coord.check after each action as well as its own rules.""" + def act(self, a): + if a["do"] != "reject": + return super().act(a) + aid = self.live("seraph") + review = self.plan()["review"] + if not aid or review.get("owner") != aid or review.get("state") != "running": + return False + before = {k: v.get("state") for k, v in self.plan().items()} + cmd = 'dev progress step "review" --step review --check "✗ changes requested"' + pg.step("review", which="review", check="✗ changes requested", from_agent=aid, now=self.now()) + self.commands.setdefault(aid, []).append(cmd) + self.stop(aid, "seraph", self.commands[aid]) + self.stop(aid, "seraph", self.commands[aid], again=True) + self.ended.add(aid) + fix = self.plan()["fix"] + if fix.get("state") == "pending" and "review" in pg.deps_open(self.run_(), fix) \ + and self.plan()["review"].get("state") == "unverified": + self.flag("fix-after-changes", "“fix” still waits for the review that asked for changes") + self.check(a, before, None) + return True + def check(self, a, before, expect): super().check(a, before, expect) for v in coord.check(self.run_(), time.time(), review=pg.is_review_step): @@ -46,7 +86,9 @@ class CoordModelTests(unittest.TestCase): def hunt(cls): if cls.found is None: first = {} - with mock.patch.object(model, "World", CoordWorld): + with mock.patch.object(model, "World", CoordWorld), mock.patch.object(model, "PLAN", PLAN), \ + mock.patch.object(model, "STEPS", STEPS), mock.patch.object(model, "SCOPES", SCOPES), \ + mock.patch.object(model, "propose", propose): one = os.environ.get("DEVKIT_MODEL_SEED") seeds = [int(one)] if one else range(int(os.environ.get("DEVKIT_MODEL_SEEDS") or 24)) for n in seeds: @@ -63,7 +105,7 @@ def holds(self, rule): got = self.hunt().get(rule) if got: host, n, seq, text = got - self.fail(f"{RULES[rule]}: broken on {host} (seed {n}) by {model.show(seq)}\n → {text}") + self.fail(f"{RULES[rule]}: broken on {host} (seed {n}) by {show(seq)}\n → {text}") def test_every_running_step_has_a_running_owner(self): self.holds("I-owner") @@ -86,6 +128,9 @@ def test_no_free_lane_leaves_its_step_waiting(self): def test_the_history_matches_the_plan(self): self.holds("I-history") + def test_the_fix_after_a_review_that_asked_for_changes_can_start(self): + self.holds("fix-after-changes") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_coord_scenarios.py b/tests/test_coord_scenarios.py index 7636287b..7417e513 100644 --- a/tests/test_coord_scenarios.py +++ b/tests/test_coord_scenarios.py @@ -222,5 +222,27 @@ def test_a_review_and_a_verdict_the_gates_did_not_pass_are_named_to_the_tech_lea self.assertIn("“api”", told[0]) +class ReviewVerdictTests(Scenario): + def test_a_review_closed_with_changes_requested_lets_the_step_after_it_start(self): + pg.start("Export", plan=["api=30m", "review=20m [review] after api", "fix=20m after review"], now=self.m(0)) + pg.assign("api", "Tank", why="test", now=self.m(0)) + pg.assign("review", "Seraph", why="test", now=self.m(0)) + pg.assign("fix", "Tank", why="test", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + pg.step("api", which="api", check="✓ 1", from_agent="a_tank", now=self.m(5)) + launch("a_ser", "devkit:seraph", "Seraph: review", at=self.m(6)) + pg.step("review", which="review", check="✗ changes requested: the CSV header is wrong", from_agent="a_ser", + approves="api", now=self.m(10)) + pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a_ser", "agent_type": "devkit:seraph", + "last_assistant_message": REPORT.format(task="review", check="✗ changes requested")}, + False, now=self.m(11)) + run = self.run_() + self.assertEqual(self.held("review")[1], "unverified") + self.assertEqual((pg.deps_open(run, run["plan"][2]), self.held("fix")), ([], ("a_tank", "running"))) + self.assertIn("api", [s["name"] for s in run["plan"] if s["name"] == "api"]) + self.assertNotIn("api", {n for a in run.get("approvals") or [] if a.get("verdict") == "approve" + for n in a.get("steps") or []}) + + if __name__ == "__main__": unittest.main() From ed93721f94f8c191ea61879554f354e39e27cc12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 20:46:48 -0800 Subject: [PATCH 26/52] feat(progress): name the caller and its call in each step's history The threat review asked that every step change say how devkit found its caller and which call made it, and that a dev process resolve its caller once before anything else runs. cli.main resolves the caller once when the call token is present (progress.mark_calls); each history entry carries how and tid. The background sync starts with identity.detached_env(), so it never acts for the call that started it. Verified: committed tree plus this change: 632 tests in 16 modules OK, except a workdir test that only fails in a copy without the repository and passes here --- lib/devkit/cli.py | 7 +++++- lib/devkit/coord.py | 5 ++++- lib/devkit/progress.py | 20 ++++++++++++++++- tests/test_coord_calltoken.py | 42 +++++++++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/lib/devkit/cli.py b/lib/devkit/cli.py index ffe0a58b..df17f943 100644 --- a/lib/devkit/cli.py +++ b/lib/devkit/cli.py @@ -328,6 +328,7 @@ def _spawn_flusher(at: int): """Start `dev sync --quiet --flush-at ` detached, as work.request_sync starts a queued sync. -> its pid, or None when it did not start (DEVKIT_NO_AUTOSYNC: that process asked for no background sync).""" import subprocess + from . import identity if os.environ.get("DEVKIT_NO_AUTOSYNC"): return None log = core.STATE / "logs" / "sync.log" @@ -339,7 +340,8 @@ def _spawn_flusher(at: int): try: p = subprocess.Popen([sys.executable, "-I", "-S", str(core.release_home() / "bin" / "dev"), "sync", "--quiet", "--flush-at", str(int(at))], stdin=subprocess.DEVNULL, stdout=out, stderr=out, - start_new_session=True, close_fds=True) # isolated, as its shebang runs it + start_new_session=True, close_fds=True, # isolated, as its shebang runs it + env=identity.detached_env()) # it never acts for the call that started it return p.pid except OSError: return None @@ -5367,6 +5369,9 @@ def main(argv=None) -> int: argv = sys.argv[1:] if argv is None else argv _ARGV = list(argv) a = parse(argv) + if os.environ.get("DEVKIT_CALL"): # who runs this process, resolved once before anything else runs + from . import progress + progress.mark_calls() if a.help: # `dev -h ` shows the command's help and never runs it if a.cmd: with contextlib.suppress(SystemExit): diff --git a/lib/devkit/coord.py b/lib/devkit/coord.py index cf583170..69f650ac 100644 --- a/lib/devkit/coord.py +++ b/lib/devkit/coord.py @@ -245,9 +245,12 @@ def changes(before: dict, run: dict) -> list: if before.get(s.get("name")) != s.get("state")] +HISTORY_MARKS: dict = {} # {how, tid} of the call this process runs for, set once (progress.mark_calls) + + def _history(run: dict, s: dict, old, new, by: str, why: str, now: float): run.setdefault("history", []).append({"ts": round(now), "step": s.get("name"), "from": old, "to": new, - "by": by or "main", "why": (why or "")[:300]}) + "by": by or "main", "why": (why or "")[:300], **HISTORY_MARKS}) run["history"] = run["history"][-200:] diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 9cce8427..b79e8d4c 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -4600,9 +4600,27 @@ def _audit(action: str, target: str, detail: str = "", outcome: str = "ok", **ex pass +def mark_calls(marks: dict | None = None) -> dict: + """Resolve who runs this `dev` process once, at its start (cli.main), when its call carries the call token: each + history entry it writes then names how the caller was found and the call's tool_use_id (`how`, `tid`). `marks` + sets them as given ({} clears them). -> the marks""" + if marks is None: + from . import identity + token = identity.parse_token(os.environ.get(identity.CALL_VAR) or "") + marks = {} + if token: + try: + marks = {"how": identity.speaker().how, "tid": token[0]} + except Exception: + marks = {"how": "unknown", "tid": token[0]} + coord.HISTORY_MARKS.clear() + coord.HISTORY_MARKS.update(marks) + return dict(coord.HISTORY_MARKS) + + def _log_change(run, s, old, new, who, why, now): run.setdefault("history", []).append({"ts": round(now), "step": s["name"], "from": old, "to": new, - "by": who or "main", "why": (why or "")[:300]}) + "by": who or "main", "why": (why or "")[:300], **coord.HISTORY_MARKS}) run["history"] = run["history"][-200:] _audit(f"plan.{new}", s["name"], why or "", project=run.get("project") or "", run=run.get("goal", "")[:80], by=_name_of(run, who or "main") if who != "devkit" else "devkit", was=old or "") diff --git a/tests/test_coord_calltoken.py b/tests/test_coord_calltoken.py index 14eb04b3..166d8be8 100644 --- a/tests/test_coord_calltoken.py +++ b/tests/test_coord_calltoken.py @@ -34,5 +34,47 @@ def test_a_malformed_hash_writes_no_entry(self): self.assertEqual(pg.call_entry(call("toolu_tok3")), {}) +class HistoryMarksTests(unittest.TestCase): + """A step change records how its caller was found and the call that typed it (the audit fields).""" + + def setUp(self): + self.state = TempState().__enter__() + self.addCleanup(self.state.__exit__, None, None, None) + self.addCleanup(pg.mark_calls, {}) + + def test_a_dev_process_resolves_its_caller_once_and_each_history_entry_names_it(self): + from unittest import mock + from devkit import cli, identity + sp = identity.Speaker("claude", "s1", "main", "token", True) + with mock.patch.dict("os.environ", {identity.CALL_VAR: "toolu_hist1." + "a" * 22}), \ + mock.patch.object(identity, "speaker", return_value=sp) as found: + cli.main(["progress", "start", "Export", "--plan", "api=30m; docs=15m"]) + pg.reopen("api", "skip it", skip=True) + found.assert_called_once() + entries = [h for h in pg.load_run("claude", "s1")["history"] if h["step"] in ("api", "docs")] + self.assertTrue(entries) + self.assertEqual({(h.get("how"), h.get("tid")) for h in entries}, {("token", "toolu_hist1")}) + + def test_without_a_call_token_nothing_is_resolved_and_no_marks_are_written(self): + from unittest import mock + from devkit import cli, identity + with mock.patch.object(identity, "speaker") as found: + cli.main(["progress", "start", "Export", "--plan", "api=30m; docs=15m"]) + pg.reopen("api", "skip it", skip=True) + found.assert_not_called() + self.assertFalse([h for h in pg.load_run("claude", "s1")["history"] if "tid" in h]) + + def test_the_background_sync_starts_without_the_call_token(self): + from unittest import mock + from devkit import cli, identity + with mock.patch.dict("os.environ", {identity.CALL_VAR: "toolu_hist2." + "a" * 22}), \ + mock.patch.dict("os.environ", {"DEVKIT_NO_AUTOSYNC": ""}), \ + mock.patch("subprocess.Popen") as popen: + popen.return_value.pid = 4242 + cli._spawn_flusher(0) + self.assertTrue(popen.called) + self.assertNotIn(identity.CALL_VAR, popen.call_args.kwargs.get("env") or {identity.CALL_VAR: ""}) + + if __name__ == "__main__": unittest.main() From 03281bc6204f8292fdb178cd004c743256ed34b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:11:01 -0800 Subject: [PATCH 27/52] fix(identity): close the call token paths the red team broke A crew member could act as the tech lead or as another member: on Codex by dropping its token and setting CODEX_THREAD_ID, on Claude Code by reading the tech lead's token from the process list and using it first from its own shell, and below a nested agent started through node that devkit did not recognize. Root cause: the Codex thread rule trusted CODEX_THREAD_ID, which any child process sets, before refusing a tokenless state change; the token was pinned to whichever shell used it first; and core.is_agent_process knew only claude and codex by their own executable name The thread rule no longer decides a state change where the hook stamps every call (stamps_all), and elsewhere takes a lane or the root only when that caller's own open call holds the command; every resolution is audited (caller.thread). A token holds only when the call shell closest to the agent carries it in its own command line where the hook writes it, or, when that shell replaced itself with the command, the call's text runs this very dev command. Agents run through node, Gemini CLI and opencode count as agents, a Claude Code token carrying a Codex thread id is refused, and a Codex member's rewrite no longer carries the root thread's id. Verified: dev test run (10 files): 317 passed; the red team's probes now print refusals; 9 of the 10 red team tests fail against the previous commit --- lib/devkit/core.py | 12 +- lib/devkit/hooks.py | 39 ++++-- lib/devkit/identity.py | 209 +++++++++++++++++++--------- tests/test_codex_identity_token.py | 18 +-- tests/test_codex_session_routing.py | 7 +- tests/test_hooks_peers.py | 27 ++-- tests/test_identity_redteam.py | 142 +++++++++++++++++++ tests/test_identity_token.py | 77 +++++----- tests/test_laneroute.py | 7 +- tests/test_pre_tool_hook.py | 2 +- 10 files changed, 396 insertions(+), 144 deletions(-) create mode 100644 tests/test_identity_redteam.py diff --git a/lib/devkit/core.py b/lib/devkit/core.py index 66b5601b..f858e8d1 100644 --- a/lib/devkit/core.py +++ b/lib/devkit/core.py @@ -447,15 +447,21 @@ def expand(p) -> Path: _LOOKUP = object() +AGENT_EXECUTABLES = ("claude", "codex", "gemini", "opencode") # coding agents a shell call may start, nested or not + + def is_agent_process(args: str) -> bool: - """True when a command line is an agent: Claude Code, Codex, or their desktop apps (by the executable's name).""" + """True when a command line is an agent: Claude Code, Codex, Gemini CLI or opencode, or their desktop apps, by the + executable's name, also when node runs it (an npx or npm install's node_modules/.bin/codex).""" words = (args or "").split() if not words: return False exe = os.path.basename(words[0]).casefold() - if exe in ("claude", "codex") or "/claude/versions/" in words[0]: + if exe in AGENT_EXECUTABLES or "/claude/versions/" in words[0]: return True - return exe.startswith("node") and any("claude-code" in w or "@openai/codex" in w for w in words[1:3]) + return exe.startswith("node") and any( + "claude-code" in w or "@openai/codex" in w or "@google/gemini-cli" in w or "opencode-ai" in w + or os.path.basename(w).casefold() in AGENT_EXECUTABLES for w in words[1:3]) def _ancestry(): diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index a4dd0e02..0163eec3 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -1536,7 +1536,7 @@ def _close_call(data: dict): if data.get("tool_name") in SHELL_TOOLS or entry.get("agent") == "codex": progress.call_closed(data) if data.get("tool_name") in SHELL_TOOLS and entry.get("agent") and data.get("tool_use_id"): - # its token dies with it: the pin goes, and the session record lists the call as closed + # its token dies with it: its use mark goes, and the session record lists the call as closed identity.note_closed(entry["agent"], str(data.get("session_id") or ""), str(data["tool_use_id"])) except Exception: _log(f"ledger close: {traceback.format_exc()[-300:]}") @@ -1617,6 +1617,20 @@ def _with_token(agent: str, data: dict, new, token: str): return out if agent != "codex" or _codex_may_rewrite(data, out) else None +def _hook_launched_by(pid: int) -> bool: + """Did agent process `pid` start this hook, directly or through one shell, as Claude Code and Codex run their + hooks? An agent further up started some other program that runs the hook (a test runner, a script), so the + calls it records are not that agent's shell calls.""" + parent = os.getppid() + if parent == pid: + return True + try: + out = subprocess.run(["ps", "-o", "ppid=", "-p", str(parent)], capture_output=True, text=True, timeout=2) + except (OSError, subprocess.SubprocessError): + return False + return out.stdout.strip() == str(pid) + + def _stamped_token(agent: str, data: dict, new, token: str, digest: str): """The input a shell call goes out with when it carries its call token, None when it carries none (it then goes out as `new`, the routed input, or as it is). The token goes out only once its ledger entry holds the nonce's hash @@ -1633,13 +1647,19 @@ def _stamped_token(agent: str, data: dict, new, token: str, digest: str): _token_skipped(agent, data, "the rewrite would not carry the token: it goes out without it") identity.note_opened(agent, sid) return None + host = (os.environ.get(identity.THREAD_VAR) or "").strip()[:80] + if agent == "claude" and host: # a Claude Code started from a Codex shell: its commands carry that thread + progress.call_note(data, host_thread=host) + owner = progress.call_entry(data).get("agent_pid") + if isinstance(owner, int) and not _hook_launched_by(owner): + progress.call_note(data, agent_pid=None) # an agent further up started what runs this hook, not the hook entry = progress.call_entry(data) ttl = identity.codex_ttl(data.get("tool_input")) if agent == "codex" else None if not hmac.compare_digest(str(entry.get("token_sha256") or ""), digest) or \ - ttl is not None and entry.get("ttl") != ttl: + ttl is not None and entry.get("ttl") != ttl or agent == "claude" and entry.get("host_thread", "") != host: _token_skipped(agent, data, "its call ledger entry does not hold the token") return None - if not identity.note_opened(agent, sid, tid): + if not identity.note_opened(agent, sid, tid, every=agent != "codex" or _codex_never_asks(data)): _token_skipped(agent, data, "the session record is busy") return None return tokened @@ -1748,12 +1768,15 @@ def _member_folder(run: dict, aid: str) -> str: def _codex_session_assignment(agent: str, data: dict): - """A shell-safe root identity from the trusted Codex hook, empty for Claude, None for a malformed root.""" + """A shell-safe root identity from the trusted Codex hook for the main thread's calls, None for a malformed or + missing root (no rewrite then); empty for Claude, and for a crew member's calls, whose session devkit finds by + their lane: a member's shell never carries the root thread's id.""" if agent != "codex": return "" sid = data.get("session_id") - return f"DEVKIT_SESSION=codex:{sid}" if isinstance(sid, str) and \ - re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", sid) else None + if not isinstance(sid, str) or not re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", sid): + return None + return "" if data.get("agent_id") else f"DEVKIT_SESSION=codex:{sid}" def _route_subagent_progress(data: dict, agent: str = "claude"): @@ -2329,14 +2352,14 @@ def _codex_call(agent: str, data: dict) -> tuple: def _codex_thread_mismatch(agent: str, data: dict, item): - """A Codex exec whose dev command resolved its caller by the call's token (its pin exists) ran on a thread that is + """A Codex exec whose dev command resolved its caller by the call's token (its use mark exists) ran on a thread that is not that caller's, by the rollout's own CommandExecution record: audited caller.mismatch, after the fact (a main token used in a member's write_stdin into the tech lead's exec shows here). The tech lead's thread is the session's; a member's is its own, or the session's where Codex shares it.""" from . import identity, progress sid, tid = str(data.get("session_id") or ""), str(data.get("tool_use_id") or "") thread = str((item or {}).get("thread_id") or "") if isinstance(item, dict) else "" - if agent != "codex" or not thread or not sid or not tid or not identity.pin_path(sid, tid).exists(): + if agent != "codex" or not thread or not sid or not tid or not identity.used_path(sid, tid).exists(): return caller = str(progress.call_entry(data).get("caller") or "main")[:80] if thread in ((sid,) if caller == "main" else (caller, sid)): diff --git a/lib/devkit/identity.py b/lib/devkit/identity.py index 777e6cd2..ab21c0af 100644 --- a/lib/devkit/identity.py +++ b/lib/devkit/identity.py @@ -37,19 +37,22 @@ the call as one the hook opened (call_token). A `dev` command that carries one is the entry's caller (`main` or the member's agent id, how "token") when all of these hold (_verify): the entry is in the folder of the session this process runs in and names it, it is open and listed, its hash matches; the nearest agent process above this command is -the entry's; the call's shell (the process right below that agent) is the one the token's first use pinned, with the -same start time; this command runs in that shell's process session (a detached process never does). A command -resolves its token once and keeps the verdict for its lifetime. A failed token refuses a state change -(STATE_CHANGING) and lets a read or a wait fall to the rules above. In a session whose hook stamps tokens, a state -change without one is refused (caller.no-token): text matching never decides it. On Codex, a call without a token -may still name its lane by CODEX_THREAD_ID (rule 0b); the root thread maps to main only after a member's token call -showed that members carry thread ids of their own. +the entry's, and a Claude Code token carries no Codex thread id its call did not; the call's shell (the shell closest +to that agent above this command) carries this very token in its own command line, where the hook writes it, or, +when that shell replaced itself with the command it ran last, the call's own text runs this very dev command; this +command runs in that shell's process session (a detached process never does). A token another shell read from the +process list therefore names nobody in the thief's shell. A command resolves its token once and keeps the verdict for +its lifetime. A failed token refuses a state change (STATE_CHANGING) and lets a read or a wait fall to the rules +above. In a session whose hook stamps tokens, a state change without one is refused (caller.no-token): text matching +never decides it. On Codex, where Codex may ask (the hook cannot stamp every call), a call without a token may name +its lane by CODEX_THREAD_ID (rule 0b) when an open call of that lane holds the command; the root thread maps to main +only after a member's token call showed that members carry thread ids of their own. Any process can set the variable, +so where the hook stamps every call (stamps_all) the thread rule never decides a state change. """ from __future__ import annotations import hashlib import hmac -import json import os import re import sys @@ -273,7 +276,7 @@ def _find(cwd=None, argv=None, now=None, exact: bool = False, settle: bool = Tru if token is not None and changes: return _Found(Speaker(agent, sid, "", "unknown", False, token.why), agent, how, (), "") if token is None and agent == "codex": # rule 0b: the Codex thread that runs the command - thread = _thread_rule(agent, sid) + thread = _thread_rule(agent, sid, args, changes, now) if thread: return _Found(Speaker(agent, sid, thread, "thread", True), agent, how, (), thread, (thread,) if thread != "main" else ()) @@ -504,12 +507,6 @@ def parse_token(value): return (tid, nonce) if tid and not tid.startswith(".") else None -def pin_path(sid: str, tid: str): - """The file that pins a token to the shell of its first use: CALLS//..pin (a dot-file: no reader of - the ledger takes it for an entry).""" - from . import progress - return progress.CALLS / progress._safe_name(sid) / f".{progress._safe_name(tid)}.pin" - def detached_env(env=None) -> dict: """The environment for a process devkit starts detached (start_new_session): `env`, default this process's, @@ -544,9 +541,11 @@ def _session_update(path, fn): return state.update(path, fn, create=False) -def note_opened(agent: str, sid: str, tid: str = "") -> bool: +def note_opened(agent: str, sid: str, tid: str = "", every: bool = False) -> bool: """The session record lists `tid` among the calls the hook opened (at most CALLS_KEPT) and is a token session - (call_token). False when the record is busy or missing: the call then gets no token.""" + (call_token). `every`: the hook stamps every shell call of this session (Claude Code, or Codex where it never + asks), so a tokenless state change never needs the Codex thread rule there (stamps_all, kept for the session). + False when the record is busy or missing: the call then gets no token.""" from . import progress, state if not tid and _token_session(agent, sid): return True @@ -555,6 +554,8 @@ def put(d): if tid: d["calls_opened"] = ([t for t in d.get("calls_opened") or [] if t != tid] + [tid])[-CALLS_KEPT:] d["call_token"] = 1 + if every: + d["stamps_all"] = 1 try: _session_update(progress.session_path(agent, sid), put) except (state.StateBusy, OSError, ValueError): @@ -564,10 +565,11 @@ def put(d): def note_closed(agent: str, sid: str, tid: str): - """The call ended: its tid moves from the opened calls to the closed ones (at most CALLS_KEPT), and its pin goes.""" + """The call ended: its tid moves from the opened calls to the closed ones (at most CALLS_KEPT), and its use mark + goes.""" from . import progress, state try: - pin_path(sid, tid).unlink() + used_path(sid, tid).unlink() except OSError: pass @@ -610,7 +612,7 @@ def _token_verdict(agent: str, sid: str, args: list, now): return None key = (os.getpid(), value, str(progress.CALLS), agent, sid) if key not in _RESOLVED: - _RESOLVED[key] = v = _verify(agent, sid, value, now) + _RESOLVED[key] = v = _verify(agent, sid, value, now, args) if v.code and (state_changing(args) or v.code not in ("caller.stale-token",)): _audit_identity(v.code, v, agent, sid, args, "deny" if state_changing(args) else "flagged") return _RESOLVED[key] @@ -624,17 +626,91 @@ def _chain() -> list: return [(p, lines.get(p, "")) for p in pids] -def _started(pid) -> str: - """When process `pid` started (`ps -o lstart=`), "" when ps gives no answer: a pid the system reused for another - process has another start time.""" +def _command_line(pid) -> str: + """The whole command line of process `pid` (`ps -ww -o command=`), "" when ps gives no answer.""" import subprocess try: - out = subprocess.run(["ps", "-o", "lstart=", "-p", str(int(pid))], capture_output=True, text=True, timeout=5) + out = subprocess.run(["ps", "-ww", "-o", "command=", "-p", str(int(pid))], capture_output=True, text=True, + timeout=5) except (OSError, subprocess.SubprocessError, TypeError, ValueError): return "" return out.stdout.strip() if out.returncode == 0 else "" +# Where the hook writes the token in a call's command, as the call's shell shows it in its command line: first in the +# script its shell runs (after `eval '` on Claude Code, after `-c` or `-lc` on Codex), either as +# ` export DEVKIT_CALL=; readonly DEVKIT_CALL;` or after devkit's own variables right before `dev` +_STAMP_BEFORE = re.compile(r"(?:eval '|\s-l?c\s)\s*(?:export\s+|(?:DEVKIT_[A-Z_]+=[A-Za-z0-9_.:-]+\s+)*)\Z") + + +_SHELL_C = re.compile(r"(?:\S*/)?(?:ba|z|da|k|fi)?sh(?:\s+-[A-Za-z]+)*?\s+-[A-Za-z]*c[A-Za-z]*\s") # zsh -c, bash -lc + + +def _call_shell(below: list) -> tuple: + """The shell the agent ran the call in: of this command's parents below the agent (nearest first), the one + closest to the agent that runs a script (`zsh -c …`, `bash -lc …`), past any program in between that runs + none. -> (pid, its whole command line), or (None, "") when there is none.""" + for pid in reversed(below or []): + line = _command_line(pid) + if _SHELL_C.match(line): + return pid, line + return None, "" + + +def _runs_this(entry: dict, args: list) -> bool: + """Does the token's call run this very dev command? For a dev process with no call shell above it: the shell + replaced itself with the command it ran last (zsh and bash exec it), so the process is that command. Its + arguments must be a dev invocation of the call's own text, each word as typed or produced by an expansion there.""" + from . import progress, shellparse + if not args: + return False + if progress.args_hash(args) in (entry.get("dev_args") or []): + return True + if entry.get("cut"): + return False + try: + calls = shellparse.shell_calls(str(entry.get("cmd") or ""), None) or [] + except Exception: + return False + for argv, _ in calls: + words = shellparse.dev_args(argv) + if words is not None and len(words) == len(args) and all( + w == a or re.fullmatch("".join(".*" if e else re.escape(t) for e, t in _expansion_parts(w)), a, re.S) + for w, a in zip(words, args)): + return True + return False + + +def _stamped(line: str, value: str) -> bool: + """Does a shell's command line carry `value` as its call's token, where the hook writes it: the first + DEVKIT_CALL= in it is the hook's stamp and names this value? A shell that only prints or quotes a token + elsewhere, or carries another call's, does not.""" + i = (line or "").find("DEVKIT_CALL=") + if i < 0 or not _STAMP_BEFORE.search(line[:i]): + return False + rest = line[i + len("DEVKIT_CALL="):] + if not rest.startswith(value): + return False + after = rest[len(value):] + return after.startswith("; readonly DEVKIT_CALL;") if line[:i].rstrip().endswith("export") else \ + after[:1] in (" ", "\t") + + +def used_path(sid: str, tid: str): + """The mark a dev command leaves when it resolved its caller by call `tid`'s token: CALLS//..used (a + dot-file: no reader of the ledger takes it for an entry). The PostToolUse hook reads it (caller.mismatch).""" + from . import progress + return progress.CALLS / progress._safe_name(sid) / f".{progress._safe_name(tid)}.used" + + +def _mark_used(sid: str, tid: str): + try: + fd = os.open(used_path(sid, tid), os.O_WRONLY | os.O_CREAT, 0o600) + os.close(fd) + except OSError: + pass + + def _session_of(pid): """The process session of `pid` (0: this process), None when the system does not say.""" try: @@ -650,30 +726,7 @@ def _read_entry(sid: str, tid: str): return e if isinstance(e, dict) else None -def _pin(sid: str, tid: str, shell: int, started: str) -> bool: - """Pin the token of call `tid` to its first user's shell (pid and start time): True when this use created the - pin, False when one existed (O_EXCL: of two first uses at once, one wins).""" - path = pin_path(sid, tid) - try: - fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) - except FileExistsError: - return False - except OSError: - return False - with os.fdopen(fd, "w") as fh: - fh.write(json.dumps({"pid": int(shell), "started": started})) - return True - - -def _read_pin(sid: str, tid: str) -> dict: - try: - doc = json.loads(pin_path(sid, tid).read_text()) - except (OSError, ValueError): - return {} - return doc if isinstance(doc, dict) else {} - - -def _verify(agent: str, sid: str, value: str, now) -> _Verdict: +def _verify(agent: str, sid: str, value: str, now, args=()) -> _Verdict: """The checks of rule 0, in order (the module's docstring).""" from . import core, progress, state parsed = parse_token(value) @@ -703,10 +756,10 @@ def _verify(agent: str, sid: str, value: str, now) -> _Verdict: agents = [p for p, line in chain if core.is_agent_process(line)] owner = entry.get("agent_pid") above = tuple(pids[:pids.index(owner) + 1] if owner in pids else pids) - if not agents: - return _Verdict(tid, code="caller.stale-token", why=STALE, detail="no agent process runs it (detached)", - ancestors=above) if isinstance(owner, int): + if not agents: + return _Verdict(tid, code="caller.stale-token", why=STALE, detail="no agent process runs it (detached)", + ancestors=above) if agents[0] != owner: return _Verdict(tid, code="caller.foreign-agent", why=FOREIGN, ancestors=above, detail=f"its nearest agent process is {agents[0]}, its call's is {owner}") @@ -715,16 +768,18 @@ def _verify(agent: str, sid: str, value: str, now) -> _Verdict: if mine is None or mine not in {_session_of(p) for p in below or [0]}: return _Verdict(tid, code="caller.stale-token", why=STALE, ancestors=above, detail="it runs in a process session of its own (detached)") - shell = below[-1] if below else os.getpid() - started = _started(shell) - if not _pin(sid, tid, shell, started): - pin = _read_pin(sid, tid) - if not any(p == pin.get("pid") and _started(p) == pin.get("started") for p in below): - return _Verdict(tid, code="caller.token-foreign-use", why=FOREIGN_USE, ancestors=above, - detail=f"pinned to shell {pin.get('pid')} ({pin.get('started')}), used from shell " - f"{shell} ({started})") + shell, line = _call_shell(below) + if shell is not None and not _stamped(line, value) or shell is None and not _runs_this(entry, args): + return _Verdict(tid, code="caller.token-foreign-use", why=FOREIGN_USE, ancestors=above, + detail=f"the call shell below the agent ({shell or 'none'}, of {list(below)}) does not " + f"carry this call's token where the hook writes it" if shell is not None else + f"no call shell runs it (of {list(below)}), and its call does not run this command") + _mark_used(sid, tid) else: _unpinned_once(agent, sid, tid, above) + if agent == "claude" and str(entry.get("host_thread") or "") != (os.environ.get(THREAD_VAR) or "").strip(): + return _Verdict(tid, code="caller.foreign-agent", why=FOREIGN, ancestors=above, + detail="it carries a Codex thread id its Claude Code call did not: another agent runs it") lane = (os.environ.get(LANE_VAR) or "").strip()[:80] if lane and lane != caller: return _Verdict(tid, code="caller.conflict", why=CONFLICT, ancestors=above, @@ -751,7 +806,7 @@ def _unpinned_once(agent: str, sid: str, tid: str, above: tuple): def _thread_evidence(agent: str, sid: str, caller: str, owner) -> str: """A Codex call whose token holds: CODEX_THREAD_ID must not name another known thread ('' when it agrees, else - the conflict). A member's pinned token call records whether Codex gives members their own thread id (per-agent) + the conflict). A member's verified token call records whether Codex gives members their own thread id (per-agent) or the root's (shared, which turns the root mapping off for the session for good).""" from . import progress thread = (os.environ.get(THREAD_VAR) or "").strip() @@ -783,21 +838,37 @@ def _record_threads(agent: str, sid: str, seen: str): agent, sid, sys.argv[1:], "flagged") -def _thread_rule(agent: str, sid: str) -> str: - """Rule 0b, a Codex command without a token: CODEX_THREAD_ID equal to a running lane's agent id is that lane; the - session's own (root) thread is the tech lead only once a member's token call showed members carry thread ids of - their own (codex_threads per-agent). '' otherwise.""" +def _thread_rule(agent: str, sid: str, args: list, changes: bool, now=None) -> str: + """Rule 0b, a Codex command without a token. CODEX_THREAD_ID equal to a running lane's agent id names that lane; + the session's own (root) thread names the tech lead only once a member's token call showed members carry thread + ids of their own (codex_threads per-agent). Any child process can set the variable, so for a state change it + counts only where Codex may ask (a session whose hook stamps every call never needs it: stamps_all), and only + when an open call of that same lane (or the tech lead's, for the root) holds this very command. Every resolution + is audited (caller.thread). '' otherwise.""" from . import progress, state thread = (os.environ.get(THREAD_VAR) or "").strip() if not thread: return "" + sess = state.read(progress.session_path(agent, sid)) or {} + if changes and sess.get("stamps_all"): + return "" run = progress.load_run(agent, sid) or {} lane = (run.get("agents") or {}).get(thread) - if isinstance(lane, dict) and lane.get("state") in ("running", None): - return thread - if thread == sid and (state.read(progress.session_path(agent, sid)) or {}).get("codex_threads") == "per-agent": - return "main" - return "" + who = thread if isinstance(lane, dict) and lane.get("state") in ("running", None) else \ + "main" if thread == sid and sess.get("codex_threads") == "per-agent" else "" + if not who: + return "" + if changes and not any(str(c.get("caller")) == who and (_typed_exactly(c, args) or ( + progress._names_args(c, args) and not _ran_elsewhere(c, args))) for c in progress.open_calls(sid, now)): + return "" + key = ("thread", os.getpid(), agent, sid, who, tuple(args)) + if key not in _NOTED: # once per command (and never again from the audit record's own lookup of its actor) + _NOTED.add(key) + _audit_identity("caller.thread", _Verdict("", detail=f"CODEX_THREAD_ID names {who[:40]}, and its own open " + f"call holds this command" if changes else + f"CODEX_THREAD_ID names {who[:40]} for a read"), + agent, sid, args, "allowed") + return who def _token_session(agent: str, sid: str) -> bool: diff --git a/tests/test_codex_identity_token.py b/tests/test_codex_identity_token.py index a49b46dd..286258d2 100644 --- a/tests/test_codex_identity_token.py +++ b/tests/test_codex_identity_token.py @@ -38,14 +38,16 @@ class CodexTokenCase(TokenCase): agent = "codex" agent_line = "codex" + agent_pid = CODEX never_asks = True + def shell_line(self, new: str) -> str: + # the exec's shell as ps shows it: Codex runs the command with the user's shell, -lc + return f"/bin/zsh -lc {new}" + def setUp(self): super().setUp() - self.chain = [(70102, "/bin/zsh -lc dev"), (CODEX, "codex")] - self.starts[70102] = "Thu Nov 19 10:00:00 2026" - for p in (mock.patch.object(pg, "_call_agent_pid", lambda: CODEX), - mock.patch.object(hooks, "_codex_never_asks", lambda data: self.never_asks), + for p in (mock.patch.object(hooks, "_codex_never_asks", lambda data: self.never_asks), mock.patch.dict(os.environ, {"DEVKIT_SESSION": f"codex:{SID}", "SHELL": "/bin/zsh"})): p.start() self.addCleanup(p.stop) @@ -138,12 +140,11 @@ def test_codex_member_token_with_the_root_thread_turns_the_root_mapping_off(self self.assertFalse(self.added()) def test_codex_member_token_with_its_own_thread_turns_the_root_mapping_on(self): - self.never_asks = True - _, token, _ = self.exec("dev crew inbox", aid=SUB) + _, token, _ = self.exec("dev crew inbox", aid=SUB) # one plain call: its token in the variable-list form + self.assertTrue(token) self.assertEqual(self.dev("crew", "inbox", token=token, env=self.thread(SUB))[0], 0) self.assertEqual(self.sess().get("codex_threads"), "per-agent") - self.never_asks = False - self.exec("dev progress add extra | tail -3") + self.exec("dev progress add extra | tail -3") # the tech lead's own open call holds the command rc, out = self.lead(env=self.thread(SID)) self.assertEqual(rc, 0, out) self.assertTrue(self.added()) @@ -183,6 +184,7 @@ def test_codex_yielded_exec_token_dies_at_post_tool_use(self): def test_codex_command_execution_thread_mismatch_is_audited(self): data, token, new = self.exec("dev crew inbox") self.assertEqual(self.speak(token).lane, "main") # its dev call resolved the tech lead + self.assertTrue(identity.used_path(SID, data["tool_use_id"]).exists()) rollout = Rollout(self.root / ".codex", SID) rollout.add("event_msg", {"type": "item_completed", "thread_id": SUB, "turn_id": "t1", "item": {"type": "CommandExecution", "id": data["tool_use_id"], "exit_code": 0, diff --git a/tests/test_codex_session_routing.py b/tests/test_codex_session_routing.py index a1bec7ca..8354f33a 100644 --- a/tests/test_codex_session_routing.py +++ b/tests/test_codex_session_routing.py @@ -232,14 +232,17 @@ def test_codex_child_hook_root_stamp_agrees_with_lane_for_simple_and_compound_ca "cwd": str(pg.RUNS.parent), "tool_input": {"command": command}} routed = hooks._route_subagent_progress(data, "codex") self.assertIsNotNone(routed) + # a member's shell carries its lane only, never the root thread's id: its lane finds the session + self.assertNotIn("DEVKIT_SESSION=", routed["command"]) env = self.stamped_environment(routed["command"]) - self.assertEqual((env["DEVKIT_SESSION"], env["DEVKIT_FROM_AGENT"]), ("codex:parent", "child")) + self.assertEqual((env["DEVKIT_SESSION"], env["DEVKIT_FROM_AGENT"]), ("", "child")) with mock.patch.dict(os.environ, env): self.assertEqual(pg.resolve_session(argv=self.args), ("codex", "parent", "ancestry")) legacy = hooks._route_subagent_progress(data, "claude")["command"] self.assertNotIn("DEVKIT_SESSION=", legacy) self.assertEqual(self.stamped_environment(legacy)["DEVKIT_FROM_AGENT"], "child") - self.assertIsNone(hooks._route_subagent_progress({**data, "session_id": "parent; echo injected"}, "codex")) + injected = hooks._route_subagent_progress({**data, "session_id": "parent; echo injected"}, "codex") + self.assertNotIn("injected", (injected or {}).get("command", "")) # the root id never reaches its shell if __name__ == "__main__": diff --git a/tests/test_hooks_peers.py b/tests/test_hooks_peers.py index d43d1479..86e225f8 100644 --- a/tests/test_hooks_peers.py +++ b/tests/test_hooks_peers.py @@ -24,7 +24,7 @@ from test_hooks_wiring import WiringCase # noqa: E402 from test_progress import boundary, launch # noqa: E402 -from devkit import bugs, canary, core, crew, hooks, lessons, peers, work # noqa: E402 +from devkit import bugs, canary, core, crew, hooks, identity, lessons, peers, work # noqa: E402 from devkit import progress as pg # noqa: E402 ROSTER = crew.load @@ -113,8 +113,8 @@ def test_pretooluse_stamps_main_session_calls(self): out = self.hook("pre-tool", agent, self.call(agent, "dev watch --wait --for me --timeout 9", agent_id="a_tank", agent_type="devkit:tank")) self.assertEqual(self.updated(out).get("command"), - (f"DEVKIT_SESSION=codex:{CODEX_A} " if agent == "codex" else "") + "DEVKIT_FROM_AGENT=a_tank dev watch --wait --for me --timeout 9") + self.assertNotIn(CODEX_A, out) # a member's shell never carries the root thread's session id out = self.hook("pre-tool", agent, self.call(agent, "dev session ls", agent_id="a_tank")) self.assertNotIn("DEVKIT_SPEAKER", out) # the call ledger still holds the command as typed, the tech lead's (identity's fallback when a rewrite is @@ -146,6 +146,8 @@ def test_piped_and_eval_forms_carry_the_stamp_for_the_whole_command(self): command = 'dev progress start "Test the command routing" --plan routing' self.hook("pre-tool", "codex", self.call("codex", command)) with mock.patch.dict(os.environ, {"DEVKIT_SESSION": f"codex:{CODEX_A}"}), \ + mock.patch.object(identity, "acting_lane", lambda *a, **k: "main"), \ + mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}), \ mock.patch.object(sys, "argv", ["dev", "progress", "start", "Test the command routing", "--plan", "routing"]): pg.start("Test the command routing", cwd=str(self.repo), plan=["routing"]) @@ -156,24 +158,27 @@ def test_piped_and_eval_forms_carry_the_stamp_for_the_whole_command(self): with self.subTest(agent=agent, cmd=cmd, member=True): out = self.hook("pre-tool", agent, self.call(agent, cmd, agent_id="a_mouse", agent_type="devkit:mouse")) - self.assertEqual(self.updated(out).get("command"), - f"export DEVKIT_FROM_AGENT=a_mouse{root}; {cmd}") + # the call token, where the session's calls carry one, goes in front (identity.strip_token) + self.assertEqual(identity.strip_token(self.updated(out).get("command")), + f"export DEVKIT_FROM_AGENT=a_mouse; {cmd}") + self.assertNotIn(CODEX_A, out) # a member's shell never carries the root thread's session id with self.subTest(agent=agent, cmd=cmd, member=False): out = self.hook("pre-tool", agent, self.call(agent, cmd)) - self.assertEqual(self.updated(out).get("command"), f"export DEVKIT_SPEAKER=main{root}; {cmd}") + self.assertEqual(identity.strip_token(self.updated(out).get("command")), + f"export DEVKIT_SPEAKER=main{root}; {cmd}") with self.subTest(agent=agent, main_lane_calls=True): # the tech lead's own crew and progress calls for cmd in ('dev crew answer M7 "yes"', 'dev progress note "half done" | tail -3'): want = f"DEVKIT_SPEAKER=main{root} {cmd}" if "|" not in cmd else \ f"export DEVKIT_SPEAKER=main{root}; {cmd}" - self.assertEqual(self.updated(self.hook("pre-tool", agent, self.call(agent, cmd))).get("command"), - want) + self.assertEqual(identity.strip_token(self.updated(self.hook( + "pre-tool", agent, self.call(agent, cmd))).get("command")), want) for cmd in ("dev watch --wait; rm -rf build", "dev watch --wait > /tmp/w.txt", "echo export X=1 >> ~/.zshrc; dev watch --wait", "dev session ls &> out.json", "make test && dev session ls"): with self.subTest(agent=agent, cmd=cmd, stamped=False): # anything else runs: only a call of its for member in ({"agent_id": "a_mouse"}, {}): # own, or with cd and reads around it, is stamped - self.assertNotIn("DEVKIT_", json.dumps(self.updated(self.hook( - "pre-tool", agent, self.call(agent, cmd, **member))))) + self.assertNotIn("DEVKIT_", identity.strip_token(self.updated(self.hook( # but its token + "pre-tool", agent, self.call(agent, cmd, **member))).get("command") or "")) self.codex_policy("on-request") # where Codex asks, only a call that is one plain devkit call is rewritten for cmd in forms: for member in ({"agent_id": "a_mouse", "agent_type": "devkit:mouse"}, {}): @@ -181,8 +186,8 @@ def test_piped_and_eval_forms_carry_the_stamp_for_the_whole_command(self): self.assertEqual(self.updated(self.hook("pre-tool", "codex", self.call("codex", cmd, **member))), {}) one = 'dev crew answer M7 "yes"' - self.assertEqual(self.updated(self.hook("pre-tool", "codex", self.call("codex", one))).get("command"), - f"DEVKIT_SPEAKER=main DEVKIT_SESSION=codex:{CODEX_A} {one}") + self.assertEqual(identity.strip_token(self.updated(self.hook("pre-tool", "codex", self.call( + "codex", one))).get("command")), f"DEVKIT_SPEAKER=main DEVKIT_SESSION=codex:{CODEX_A} {one}") def test_hooks_drop_the_speaker_variable(self): seen = [] diff --git a/tests/test_identity_redteam.py b/tests/test_identity_redteam.py new file mode 100644 index 00000000..0824f12f --- /dev/null +++ b/tests/test_identity_redteam.py @@ -0,0 +1,142 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# The Red team tester's probes of the call token (2026-11-19), one test each: what a crew member tried to pass as the +# tech lead or as another member, and must not. On Codex: forging CODEX_THREAD_ID after dropping its token, under +# either approval policy. On Claude Code: taking the tech lead's token from the process list and using it first from +# its own shell, and running the tech lead's token below a nested agent devkit did not recognize. The fixtures are +# tests.test_identity_token's (Claude Code) and tests.test_codex_identity_token's (Codex 0.167 exec payloads). +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_identity_redteam -v +import os +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +import _hermetic # noqa: E402 + +_hermetic.activate() +sys.path.insert(0, str(ROOT / "lib")) + +from devkit import core, identity # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_codex_identity_token import SID, SUB, SUB2, CodexTokenCase # noqa: E402 +from test_identity_token import AGENT, INNER, NESTED, TokenCase # noqa: E402 +from test_progress import launch # noqa: E402 + +NPX_CODEX = "node /Users/u/.npm/_npx/9f/node_modules/.bin/codex exec review" + + +class CodexThreadForgeryTests(CodexTokenCase): + def per_agent(self): + # a member's honest token call with its own thread id: devkit learns that members carry their own ids + _, token, _ = self.exec("dev crew inbox", aid=SUB) + self.assertEqual(self.dev("crew", "inbox", token=token, env=self.thread(SUB))[0], 0) + self.assertEqual(self.sess().get("codex_threads"), "per-agent") + + def test_asking_policy_a_member_forging_the_root_thread_is_refused_and_audited(self): + self.per_agent() + self.never_asks = False + self.exec("python3 x.py; true", aid=SUB) # compound: Codex may ask, so no rewrite and no token + rc, out = self.lead(env=self.thread(SID)) # x.py runs dev with CODEX_THREAD_ID= + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.no-token")), 1) + + def test_never_asks_a_member_dropping_its_token_and_forging_the_root_is_refused(self): + self.per_agent() + _, token, _ = self.exec("python3 x.py", aid=SUB) # stamped; x.py drops DEVKIT_CALL + self.assertTrue(token) + rc, out = self.lead(env=self.thread(SID)) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + + def test_a_member_forging_another_lanes_thread_cannot_close_its_step(self): + with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): + pg.assign("ui", "Trinity", why="the test's assignment") + launch(SUB2, "trinity", "Trinity: ui", sid=SID, agent="codex") + for never_asks in (True, False): + with self.subTest(never_asks=never_asks): + self.never_asks = never_asks + self.exec("python3 x.py", aid=SUB) # x.py drops the token and the lane variable + rc, out = self.dev("progress", "step", "ui finished", "--step", "ui", "--check", "✓ all green", + env=self.thread(SUB2)) + self.assertEqual(rc, 2, out) + self.assertEqual(next(s for s in self.run_()["plan"] if s["name"] == "ui")["state"], "running") + + def test_the_thread_rule_takes_a_lane_only_with_its_own_open_call_and_audits_it(self): + self.never_asks = False + self.exec("dev progress note 'api half done' | tail -1", aid=SUB) # the member's own open call + rc, out = self.dev("progress", "note", "api half done", env=self.thread(SUB)) + self.assertEqual(rc, 0, out) + self.assertEqual(len(self.records("caller.thread")), 1) + rc, out = self.dev("progress", "note", "something else", env=self.thread(SUB)) # no call of its holds it + self.assertEqual(rc, 2, out) + + def test_a_members_rewrite_never_carries_the_roots_session_id(self): + for never_asks, cmd in ((False, "dev progress note x"), (True, "dev crew inbox"), (True, "git status")): + with self.subTest(never_asks=never_asks, cmd=cmd): + self.never_asks = never_asks + _, _, new = self.exec(cmd, aid=SUB) + self.assertNotIn(SID, new) + _, _, new = self.exec("dev crew inbox") # the main thread's keeps it + self.assertIn(f"DEVKIT_SESSION=codex:{SID}", new) + + +class ClaudeTokenTheftTests(TokenCase): + def test_a_member_using_the_tech_leads_token_first_from_its_own_shell_is_refused(self): + self.plan_with_link() + _, token, _ = self.hook("pytest -q tests") # the tech lead's long call runs no dev command + self.hook("python3 do.py", aid="a_link") # the member's script reads the stamp from ps + self.chain = [(self.shell, self.lines[self.shell]), (AGENT, "claude")] # the member's own shell + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.token-foreign-use")), 1) + self.chain = None # the tech lead's own call, later: still the tech lead's + rc, out = self.lead(token) + self.assertEqual(rc, 0, out) + self.assertTrue(self.added()) + + def test_agents_started_through_node_and_other_hosts_are_agents(self): + for line in (NPX_CODEX, "node /Users/u/.npm/_npx/9f/node_modules/.bin/claude -p review", + "gemini -p review", "opencode run review", "/opt/homebrew/bin/gemini", "node /x/bin/opencode"): + with self.subTest(line): + self.assertTrue(core.is_agent_process(line)) + self.assertFalse(core.is_agent_process("node /x/node_modules/.bin/vite")) + + def test_the_tech_leads_token_below_an_npx_codex_is_refused(self): + self.plan_with_link() + _, token, _ = self.hook("npx -y @openai/codex exec 'review the diff'") + own = self.parents_of(token) + self.chain = [(INNER, "/bin/zsh -lc dev"), (NESTED, NPX_CODEX)] + own + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.foreign-agent")), 1) + + def test_a_claude_token_carried_by_a_codex_thread_is_refused(self): + self.plan_with_link() + _, token, _ = self.hook("codex exec 'review the diff'") + rc, out = self.lead(token, env={identity.THREAD_VAR: "01a1f737-3cd7-7000-8000-000000000001"}) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.foreign-agent")), 1) + + def test_a_tokenless_member_cannot_reorder_launches(self): + self.plan_with_link() + self.hook("dev crew next --first ci-redirect --why urgent") # the tech lead's open call + self.call("python3 -I x.py", aid="a_link") # a member's call without its token + who = pg.caller(argv=["crew", "next", "--first", "ci-redirect", "--why", "urgent"]) + self.assertEqual(who.get("caller"), "unknown") + self.assertIn("could not verify", who.get("why") or "") + + def parents_of(self, token): + with mock.patch.dict(os.environ, {identity.CALL_VAR: token}): + return self.parents() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_identity_token.py b/tests/test_identity_token.py index 9a4be74f..bc23cd99 100644 --- a/tests/test_identity_token.py +++ b/tests/test_identity_token.py @@ -16,7 +16,6 @@ import os import re import sys -import threading import unittest from pathlib import Path from unittest import mock @@ -42,24 +41,38 @@ class TokenCase(CallerCase): agent = "claude" agent_line = "claude" + agent_pid = AGENT + def setUp(self): super().setUp() identity._forget() self.addCleanup(identity._forget) - # the dev command runs below the call's shell, which runs below the agent process - self.chain = [(SHELL, "/bin/zsh -c source snapshot && eval cmd"), (AGENT, self.agent_line)] - self.starts = {SHELL: "Thu Nov 19 10:00:00 2026", SIBLING: "Thu Nov 19 10:00:09 2026", - INNER: "Thu Nov 19 10:01:00 2026"} + # Each shell call runs in a shell of its own right below the agent process, whose command line holds the + # command as the hook rewrote it (the shells map). A dev command runs below the shell of the call whose token + # it carries, unless a test sets `chain` to the parents it runs below instead. + self.chain = None + self.shells, self.lines = {}, {SHELL: "/bin/zsh -c source snapshot && eval 'pytest'", SIBLING: "zsh"} self.own_session = None # the process session the dev command runs in: by default its nearest shell's - for p in (mock.patch.object(pg, "_call_agent_pid", lambda: AGENT), - mock.patch.object(identity, "_chain", lambda: list(self.chain)), - mock.patch.object(identity, "_started", lambda pid: self.starts.get(pid, "")), + for p in (mock.patch.object(pg, "_call_agent_pid", lambda: self.agent_pid), + mock.patch.object(hooks, "_hook_launched_by", lambda pid: pid == self.agent_pid, create=True), + mock.patch.object(identity, "_chain", self.parents), + mock.patch.object(identity, "_command_line", lambda pid: self.lines.get(pid, ""), create=True), mock.patch.object(identity, "_session_of", lambda pid: ( - self.own_session or (self.chain[0][0] if self.chain else 1)) if pid == 0 else pid)): + self.own_session or (self.parents()[0][0] if self.parents() else 1)) if pid == 0 else pid)): p.start() self.addCleanup(p.stop) (hooks.STATE / "logs").mkdir(parents=True, exist_ok=True) + def parents(self) -> list: + if self.chain is not None: + return list(self.chain) + shell = self.shells.get(os.environ.get(identity.CALL_VAR, ""), SHELL) + return [(shell, self.lines.get(shell, "")), (self.agent_pid, self.agent_line)] + + def shell_line(self, new: str) -> str: + # the call's shell as ps shows it: Claude Code runs the command through zsh -c and eval + return f"/bin/zsh -c source /tmp/snapshot.sh 2>/dev/null || true && eval '{new}' < /dev/null" + # who a dev command with this token is, in this process (no fresh start) def speak(self, token, *args): with mock.patch.dict(os.environ, {identity.CALL_VAR: token}): @@ -86,6 +99,10 @@ def hook(self, cmd, aid=None, sid="s1", tool="Bash", key="command", **inp): new = (spec.get("updatedInput") or {}).get(key) or "" found = TOKEN.search(new) self.last = spec + shell = 72000 + self.n # the shell this call runs in, with what the hook wrote, or the command as typed + self.lines[shell] = self.shell_line(new or cmd) + self.shells[found.group(1) if found else f"none-{self.n}"] = shell + self.shell = shell return data, (found.group(1) if found else ""), new def closed(self, data, event="PostToolUse"): @@ -137,14 +154,14 @@ def test_a_busy_session_hold_stamps_no_token(self): self.assertNotIn(data["tool_use_id"], (state.read(pg.session_path("claude", "s1")) or {}).get( "calls_opened") or []) - def test_closing_the_call_drops_its_pin_and_its_opened_mark(self): + def test_closing_the_call_drops_its_use_mark_and_its_opened_mark(self): data, token, _ = self.hook("dev progress note x") self.assertEqual(self.dev("crew", "inbox", token=token)[0], 0) tid = data["tool_use_id"] - self.assertTrue(identity.pin_path("s1", tid).exists()) + self.assertTrue(identity.used_path("s1", tid).exists()) self.closed(data) sess = state.read(pg.session_path("claude", "s1")) or {} - self.assertFalse(identity.pin_path("s1", tid).exists()) + self.assertFalse(identity.used_path("s1", tid).exists()) self.assertNotIn(tid, sess.get("calls_opened") or []) self.assertIn(tid, sess.get("calls_closed") or []) @@ -208,45 +225,27 @@ def test_a_token_used_below_a_nested_agent_is_refused(self): self.assertFalse(self.added()) self.assertEqual(len(self.records("caller.foreign-agent")), 1) - def test_a_second_use_from_a_sibling_shell_is_refused_and_the_calls_own_shell_still_resolves_main(self): + def test_a_use_from_a_sibling_shell_is_refused_and_the_calls_own_shell_still_resolves_main(self): self.plan_with_link() _, token, _ = self.hook("dev progress begin ci-redirect") - self.assertEqual(self.speak(token).lane, "main") # its first use, from the call's own shell - self.chain = [(SIBLING, "/bin/zsh -c steal"), (AGENT, "claude")] # a member's shell under the same agent + self.assertEqual(self.speak(token).lane, "main") # from the call's own shell + self.chain = [(SIBLING, "zsh"), (AGENT, "claude")] # a member's shell under the same agent rc, out = self.lead(token) self.assertEqual(rc, 2, out) self.assertFalse(self.added()) found = self.records("caller.token-foreign-use") self.assertEqual(len(found), 1) - self.assertIn(str(SHELL), found[0]["detail"]) self.assertIn(str(SIBLING), found[0]["detail"]) - self.chain = [(SHELL, "/bin/zsh -c x"), (AGENT, "claude")] + self.chain = None rc, out = self.lead(token) self.assertEqual(rc, 0, out) self.assertTrue(self.added()) - def test_two_concurrent_first_uses_leave_one_pin(self): - _, token, _ = self.hook("dev progress note x") - tid, _ = identity.parse_token(token) - results, gate = [], threading.Barrier(2) - - def use(shell): - gate.wait() - results.append((shell, identity._pin("s1", tid, shell, self.starts[shell]))) - threads = [threading.Thread(target=use, args=(s,)) for s in (SHELL, SIBLING)] - for t in threads: - t.start() - for t in threads: - t.join() - self.assertEqual(sorted(ok for _, ok in results), [False, True]) - winner = next(s for s, ok in results if ok) - self.assertEqual(json.loads(identity.pin_path("s1", tid).read_text())["pid"], winner) - - def test_a_reused_shell_pid_with_another_start_time_is_refused(self): + def test_a_shell_pid_the_system_gave_to_another_process_is_refused(self): self.plan_with_link() _, token, _ = self.hook("dev progress begin ci-redirect") self.assertEqual(self.speak(token).lane, "main") - self.starts[SHELL] = "Thu Nov 19 11:30:00 2026" # the call's shell ended and its pid went to another one + self.lines[self.shell] = "/bin/zsh -c vim notes.md" # the call's shell ended and its pid runs another one rc, out = self.lead(token) self.assertEqual(rc, 2, out) self.assertFalse(self.added()) @@ -360,10 +359,10 @@ def test_every_identity_record_carries_the_fixed_fields_and_never_the_nonce(self nonce = identity.parse_token(token)[1] (pg.SESSIONS / "claude-s2.json").write_text(json.dumps({"agent": "claude", "session": "s2"})) self.lead(token, env={"DEVKIT_SESSION": "claude:s2"}) - self.assertEqual(self.speak(token).lane, "main") # the call's own shell pins the token - self.chain = [(SIBLING, "/bin/zsh -c x"), (AGENT, "claude")] + self.assertEqual(self.speak(token).lane, "main") # the call's own shell + self.chain = [(SIBLING, "zsh"), (AGENT, "claude")] self.lead(token) - self.chain = [(SHELL, "/bin/zsh -c x"), (AGENT, "claude")] + self.chain = None self.lead(f"{identity.parse_token(token)[0]}.{'C' * 22}") found = [r for r in audit.query(days=1) if r.get("action", "").startswith(("caller.", "calls.")) and r["action"] != "caller.refused"] diff --git a/tests/test_laneroute.py b/tests/test_laneroute.py index c194047c..af86e63b 100644 --- a/tests/test_laneroute.py +++ b/tests/test_laneroute.py @@ -124,7 +124,7 @@ class HookRoutingTests(unittest.TestCase): # permission decision; Codex's carries `allow`, which is how Codex applies a changed input, so it goes out only # for one devkit call or where Codex never asks (hooks._codex_may_rewrite), and it refuses nothing. STAMP = "export DEVKIT_FROM_AGENT=a1; readonly DEVKIT_FROM_AGENT; " - CODEX_STAMP = "export DEVKIT_SESSION=codex:s; " + STAMP + CODEX_STAMP = STAMP # a Codex member's shell never carries the root thread's session id def lane(self, persona, level): from devkit import progress @@ -157,8 +157,9 @@ def test_a_compound_command_with_lane_calls_is_stamped_for_the_member(self): with self.subTest(cmd=cmd, persona=persona): self.assertEqual((hooks._route_subagent_progress(self.data(cmd)) or {}).get("command"), self.STAMP + cmd) - self.assertEqual((hooks._route_subagent_progress(self.data(cmd), "codex") or {}).get("command"), - self.CODEX_STAMP + cmd) + codex = (hooks._route_subagent_progress(self.data(cmd), "codex") or {}).get("command") + self.assertEqual(codex, self.CODEX_STAMP + cmd) + self.assertNotIn("DEVKIT_SESSION", codex) def test_a_review_member_waits_and_reads_its_inbox(self): # the wait every member is told to run when it is blocked on an answer, and its inbox, in a review lane diff --git a/tests/test_pre_tool_hook.py b/tests/test_pre_tool_hook.py index b8c2ce32..b7046494 100644 --- a/tests/test_pre_tool_hook.py +++ b/tests/test_pre_tool_hook.py @@ -226,7 +226,7 @@ def test_two_lane_calls_in_one_command_are_stamped_on_claude_and_on_a_codex_that self.assertEqual(self.advice(out), []) new = out["hookSpecificOutput"]["updatedInput"]["command"] self.assertIn(f"export DEVKIT_FROM_AGENT={TANK}; readonly DEVKIT_FROM_AGENT; {cmd}", new) - self.assertEqual(f"export DEVKIT_SESSION=codex:{s.sid}; " in new, agent == "codex", new) + self.assertNotIn(s.sid, new) # a member's shell never carries the root thread's session id def test_a_compound_codex_command_is_left_alone_where_codex_would_ask_and_the_member_is_told(self): # Codex applies a changed command only with `allow`, which also skips the approval Codex would ask for: a From 3309b78ad584d9f707b5171d5558c319f3d649d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:11:29 -0800 Subject: [PATCH 28/52] test(progress): follow the claim rule in the plan dependency test It pinned the manual relink a free lane needed once its step's dependency closed, which the claim rule replaced. Verified: python3 -m unittest tests.test_plan_dag OK --- tests/test_plan_dag.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_plan_dag.py b/tests/test_plan_dag.py index 68b55b94..aa49ba2b 100644 --- a/tests/test_plan_dag.py +++ b/tests/test_plan_dag.py @@ -146,8 +146,7 @@ def test_a_member_starting_early_does_not_take_a_step_that_waits(self): told = " ".join(x["text"] for x in pg.crew_inbox()) self.assertIn("“api” waits for design", told) pg.step("design done", check="ADR-12 written", now=self.m(30)) - self.assertEqual(self.states()["api"], ("pending", "main")) # Tank is busy: Morpheus links it - pg.assign("api", "Tank", now=self.m(31)) + # its dependency is done and Tank's lane is free: the lane takes it, with no link by the tech lead self.assertEqual(self.states()["api"], ("running", "t1")) def test_a_delegated_step_joins_a_working_member_only_once_its_dependency_is_done(self): From 244cddd3951f62f68c90bad8c02abd9dbe014830 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:13:38 -0800 Subject: [PATCH 29/52] fix(gates): read a Codex member's command without devkit's own stamps On live Codex, review lanes that ran dev progress step and reported favorably still ended unverified, with the gate finding 'proofs: dev progress step', so every Codex review needed the tech lead to close it by hand; design and tooling steps hid it, since they close on the member's own call. Root cause: a Codex CommandExecution item records the command as it ran, with the DEVKIT_SESSION, DEVKIT_FROM_AGENT and call-token stamps devkit's hooks write in front of it, and gates._receipt_words took the first of those assignments for the program, so it found no dev command _receipt_words reads the command without the call token (identity.strip_token) and without the lane and session variables, inline or exported. Any other assignment in front of dev, such as a PATH of its own, still keeps it from counting. A Claude Code transcript records the command as the model wrote it, so its path is unchanged. Verified: dev test run (test_gates_codex_proofs, test_gates_judgment, test_crew_gates, test_gates_skills, test_gates_writes, test_approvals_token, test_execution_receipts, test_skillguard, test_readonly_attribution, test_crew_codex_diagnostics): 146 passed; dev test prove: 7 of 7 fail without the change; the faithful Codex review test fails on HEAD's gates.py and passes with the fix --- lib/devkit/gates.py | 23 +++++- tests/test_gates_codex_proofs.py | 123 +++++++++++++++++++++++++++++++ tests/test_gates_judgment.py | 3 +- 3 files changed, 147 insertions(+), 2 deletions(-) create mode 100644 tests/test_gates_codex_proofs.py diff --git a/lib/devkit/gates.py b/lib/devkit/gates.py index 5eea314b..429120f0 100644 --- a/lib/devkit/gates.py +++ b/lib/devkit/gates.py @@ -667,6 +667,27 @@ def _names(proof, command) -> bool: return False +# The stamps devkit's own hooks write in front of a crew member's or the tech lead's command: the lane and session +# variables, inline (`DEVKIT_SESSION=codex: DEVKIT_FROM_AGENT= dev …`) or exported (`export +# DEVKIT_SESSION=…; …`). A Codex CommandExecution item records the command as it ran, with them; a Claude Code +# transcript records it as the model wrote it. Only these variables, with the values devkit writes, are taken off: +# any other assignment (a PATH of its own) changes which program runs, so the command stays no proof. +_STAMP_VALUE = r"[A-Za-z0-9_.:-]+" +_STAMP_RE = re.compile(rf"\A(?:export (?:DEVKIT_SESSION|DEVKIT_FROM_AGENT)={_STAMP_VALUE}; )*" + rf"(?:(?:DEVKIT_SESSION|DEVKIT_FROM_AGENT)={_STAMP_VALUE} )*") + + +def _unstamped(command: str) -> str: + """A shell command without the stamps devkit's hooks put in front of it: the call token (identity.strip_token), + then the lane and session variables (_STAMP_RE).""" + try: + from . import identity + command = identity.strip_token(command) + except Exception: # noqa: BLE001 - an identity module that cannot strip leaves the token, which proves nothing + pass + return _STAMP_RE.sub("", command, count=1) if isinstance(command, str) else command + + def _receipt_words(receipt, cwd, agent, repo=""): """One observed devkit command in the target tree, with a known executable, or no supported proof. @@ -686,7 +707,7 @@ def _receipt_words(receipt, cwd, agent, repo=""): here = receipt.get("cwd") or cwd if str(here).startswith("file://"): here = unquote(str(here)[7:]) - parts = shellparse.split_commands(receipt["command"], ops=True) + parts = shellparse.split_commands(_unstamped(receipt["command"]), ops=True) # as the member typed it if not parts: return [] start = 0 diff --git a/tests/test_gates_codex_proofs.py b/tests/test_gates_codex_proofs.py new file mode 100644 index 00000000..baf83a42 --- /dev/null +++ b/tests/test_gates_codex_proofs.py @@ -0,0 +1,123 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The crew gates see a Codex member's executed `dev progress step` as its proof. Codex records each command as it +ran, so its CommandExecution item carries the stamps devkit's own hooks put in front of it: the lane and session +variables (`DEVKIT_SESSION=codex: DEVKIT_FROM_AGENT= dev …`, or the `export …;` form) and the call +token. Those are taken off before the command is read; any other assignment in front of `dev` (a PATH of its own) +still keeps it from counting, since it changes which program runs. A Claude Code transcript records the command as +the model wrote it, so its path is unchanged. Only a review step's close (and an --approves verdict) waits for the +gates' pass, so this showed on review lanes while a design or tooling step closed on its own call. + +The rollout below has the shape of a Codex 0.167.2 member's own rollout (2026-11-19): a session_meta that is not a +fork (no forked_from_id, history_mode "paginated", source.subagent.thread_spawn), its turn_context, task_started, the +code-mode `exec` call whose script calls tools.exec_command, and the CommandExecution item of the command as run, +with its ordinal, thread_id, file:// folder and exit code. + +Run: python3 -m unittest tests.test_gates_codex_proofs -v""" +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "lib")) +from devkit import gates # noqa: E402 + +LEAD = "01a1f737-1701-7791-bb05-000000000001" +SERAPH = "01a1f737-3cd7-7ce1-b6fd-000000000002" +TURN = "01a1f737-3cdb-7402-bf18-000000000003" +STEP = "dev progress step 'review done' --step review --check '✓ read the diff, 12 tests pass'" +# each form devkit's hooks write in front of a member's dev command, as a Codex CommandExecution item records it +STAMPED = { + "lane and session (26.11.25)": f"DEVKIT_SESSION=codex:{LEAD} DEVKIT_FROM_AGENT={SERAPH} {STEP}", + "exported session": f"export DEVKIT_SESSION=codex:{LEAD}; DEVKIT_FROM_AGENT={SERAPH} {STEP}", + "call token, exported": f"export DEVKIT_CALL=call_0642.Zt0q-2_mXy9kP4bS7nW1aA; readonly DEVKIT_CALL; " + f"DEVKIT_FROM_AGENT={SERAPH} {STEP}", + "call token, plain": f"DEVKIT_CALL=call_0642.Zt0q-2_mXy9kP4bS7nW1aA DEVKIT_FROM_AGENT={SERAPH} {STEP}", + "lane, then call token": f"DEVKIT_FROM_AGENT={SERAPH} DEVKIT_CALL=exec-01a1f737-5.iZj-U3exUAJI8QUjgQLDgA {STEP}", +} + + +class CodexMemberRollout: + """A Codex 0.167.2 member's own rollout in `home`, for a member working in `repo`.""" + + def __init__(self, home: Path, repo: Path): + self.path = home / "sessions" / "2026" / "11" / "19" / f"rollout-2026-11-19T20-29-14-{SERAPH}.jsonl" + self.path.parent.mkdir(parents=True, exist_ok=True) + self.repo, self.n = repo, 0 + self.add("session_meta", { + "id": SERAPH, "session_id": LEAD, "parent_thread_id": LEAD, "timestamp": "2026-11-19T20:29:14.000Z", + "cwd": str(repo), "originator": "codex_exec", "cli_version": "0.167.2", "thread_source": "subagent", + "history_mode": "paginated", "multi_agent_version": "v2", "agent_path": "/root/review", + "agent_nickname": "Tesla", "source": {"subagent": {"thread_spawn": { + "parent_thread_id": LEAD, "depth": 1, "agent_path": "/root/review", "agent_nickname": "Tesla", + "agent_role": None}}}}) + self.add("turn_context", {"turn_id": TURN, "cwd": str(repo), "approval_policy": "never", + "sandbox_policy": {"type": "danger-full-access"}, "model": "gpt-6-luna"}) + self.add("event_msg", {"type": "task_started", "turn_id": TURN}) + + def add(self, kind: str, payload: dict): + with self.path.open("a") as fh: + fh.write(json.dumps({"timestamp": "2026-11-19T20:29:19.000Z", "ordinal": self.n, "type": kind, + "payload": payload}) + "\n") + self.n += 1 + + def ran(self, command: str, code: int = 0): + """One command through code mode: the exec script that calls exec_command, then its CommandExecution item + (the command as it ran) and the script's output.""" + call = f"call_{self.n:04d}" + self.add("response_item", {"type": "custom_tool_call", "status": "completed", "call_id": call, "name": "exec", + "input": f"text(await tools.exec_command({{cmd:{json.dumps(command)}}}))\n"}) + self.add("event_msg", {"type": "item_completed", "thread_id": SERAPH, "turn_id": TURN, + "started_at_ms": 1795148959000, "completed_at_ms": 1795148959300, "item": { + "type": "CommandExecution", "id": f"exec-{self.n:08d}", "process_id": "99924", + "command": ["/bin/zsh", "-lc", command], "cwd": f"file://{self.repo}", + "parsed_cmd": [{"type": "unknown", "cmd": command}], + "source": "unified_exec_startup", "status": "completed" if code == 0 else "failed", + "aggregated_output": "✓ Seraph · review done\n", "exit_code": code, + "duration": {"secs": 0, "nanos": 2208}}}) + self.add("response_item", {"type": "custom_tool_call_output", "call_id": call, "output": [ + {"type": "input_text", "text": "Script completed\nWall time 0.3 seconds\nOutput:\n"}]}) + return self + + +class CodexProofTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.home = Path(os.path.realpath(tmp.name)) + self.repo = self.home / "api" + self.repo.mkdir() + subprocess.run(["git", "init", "-q", str(self.repo)], check=True) + tools = self.home / "bin" # `dev` on PATH is devkit's own bin/dev, as on a Mac devkit installed + tools.mkdir() + (tools / "dev").symlink_to(ROOT / "bin" / "dev") + path = mock.patch.dict(os.environ, {"PATH": str(tools) + os.pathsep + os.environ["PATH"]}) + path.start() + self.addCleanup(path.stop) + + def proof_findings(self, command: str) -> list: + rollout = CodexMemberRollout(self.home, self.repo).ran(command) + found = gates.crew_gates("seraph", str(rollout.path), str(self.repo), agent="codex", session=LEAD, + lane=SERAPH, successful=True) + rollout.path.unlink() + return [(f["rule"], f["item"]) for f in found if f["rule"] == "proofs"] + + def test_a_codex_members_dev_progress_step_counts_with_each_stamp_devkit_writes_in_front_of_it(self): + for form, command in STAMPED.items(): + with self.subTest(form=form): + self.assertEqual(self.proof_findings(command), []) + + def test_an_assignment_devkit_does_not_write_still_keeps_the_command_from_counting(self): + # a PATH of its own changes which `dev` runs: only devkit's own stamps are taken off + self.assertEqual(self.proof_findings(f"DEVKIT_SESSION=codex:{LEAD} DEVKIT_FROM_AGENT={SERAPH} {STEP}"), []) + self.assertEqual(self.proof_findings(f"PATH=/tmp/elsewhere DEVKIT_FROM_AGENT={SERAPH} {STEP}"), + [("proofs", "dev progress step")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_gates_judgment.py b/tests/test_gates_judgment.py index 802d24b4..c8f00790 100644 --- a/tests/test_gates_judgment.py +++ b/tests/test_gates_judgment.py @@ -90,7 +90,8 @@ def agent_rollout(self, s, aid: str, member: str, task: str, parent: str = "", d def member(self, s, aid: str, member: str, *args) -> dict: r = s.dev(*args, member=aid, member_type=member) - cmd = " ".join(["dev"] + [shlex.quote(str(a)) for a in args]) + cmd = r["ran"] # as it ran: with the stamps devkit's PreToolUse put in front of it, as Codex records it + self.assertIn(" ".join(["dev"] + [shlex.quote(str(a)) for a in args]), cmd) item = {"type": "CommandExecution", "id": r["call"]["tool_use_id"], "command": ["/bin/zsh", "-lc", cmd], "cwd": f"file://{s.repo}", "status": "completed" if r["rc"] == 0 else "failed", "exit_code": r["rc"], "aggregated_output": (r["out"] + r["err"])[-2000:]} From 194ed45d203f4becd4aa56f62325940d0ea78d94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:31:44 -0800 Subject: [PATCH 30/52] fix(progress): hand the tech lead's running step over on every route A route that bypassed assign left the tech lead's running step his, so the member's free lane could not take it. Root cause: the running-to-pending hand-over lived in assign, not in _route_to_lane, which reopen and direct routes also use Verified: committed tree plus this change: 419 tests in 8 modules OK except the copy-only workdir test --- lib/devkit/progress.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index b79e8d4c..1eefa1e5 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -1951,9 +1951,6 @@ def assign(which, label: str, cwd: str | None = None, now: float | None = None, s["checkout"] = checkout else: s.pop("checkout", None) - if s.get("state") == "running" and (s.get("owner") or "main") == "main": - s["state"] = "pending" # the tech lead's own step goes to its member - coord._history(run, s, "running", "pending", "main", f"assigned to {label}", now) unbound = [k for k, v in live if v.get("binding") == "unbound" and _label_matches(label, v)] if len(unbound) == 1: # Morpheus confirms the one lane with no launch record his assignment names run["agents"][unbound[0]]["binding"] = "confirmed" @@ -2016,6 +2013,9 @@ def _route_to_lane(run: dict, s: dict, label: str, live: list, now: float): f"--why \"…\"), and their lane takes it with its scope", now, from_name="devkit") return None owner = s.get("owner") or "main" + if s.get("state") == "running" and owner == "main": + s["state"] = "pending" # the tech lead's own step goes to its member + coord._history(run, s, "running", "pending", "main", f"assigned to {label}", now) if s.get("state") == "blocked": return None # it waits for its decision; the answer returns it to its lane (coord.unblock) if s.get("state") == "running" and owner in agents and _label_matches(label, agents[owner]): From d3689e6e589df3eab9bb61c1f66c18e07ec988fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:31:50 -0800 Subject: [PATCH 31/52] test(progress): follow the claim rule in modes, roles, messaging These pinned replaced behavior: a launch naming none of its member's steps took none, a free lane kept a closed step's files, and a stopped member's waiting step went back to the tech lead. Each changed assertion carries a comment naming the rule it checks now. Verified: python3 -m unittest tests.test_modes tests.test_roles tests.test_messaging on the committed tree: OK --- tests/test_messaging.py | 6 ++++-- tests/test_modes.py | 5 +++-- tests/test_roles.py | 15 +++++++-------- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/tests/test_messaging.py b/tests/test_messaging.py index d3268d36..4784e8b4 100644 --- a/tests/test_messaging.py +++ b/tests/test_messaging.py @@ -273,8 +273,10 @@ def test_role_assignment_does_not_capture_retiring_lanes_scope(self): run = progress.load_run("claude", "s1") run["plan"][1]["scope"] = ["new.py"] progress._route_to_lane(run, run["plan"][1], "Neo", [("a1", run["agents"]["a1"])], 200) - self.assertEqual("main", run["plan"][1]["owner"]) - self.assertEqual(["old.py"], run["agents"]["a1"]["scope"]) + # the free lane takes the step given to its member by role, with that step's files only, never the + # closed step's + self.assertEqual(("a1", "running"), (run["plan"][1]["owner"], run["plan"][1]["state"])) + self.assertEqual([["new.py"]], progress.lane_scope(run, "a1")) def test_answer_preserves_complete_utf8_body(self): with TempState(): diff --git a/tests/test_modes.py b/tests/test_modes.py index 06f24c6f..f48747d9 100644 --- a/tests/test_modes.py +++ b/tests/test_modes.py @@ -28,7 +28,7 @@ from devkit import progress as pg # noqa: E402 import test_hooks_welcome # noqa: E402 from test_crew import TempState, run_cli # noqa: E402 -from test_progress import launch # noqa: E402 +from test_progress import NEO_REPORT, launch # noqa: E402 READ_SAVED = core.config_snapshot # devkit's own reader, taken before any sandbox replaces it ASKS_THE_DEVELOPER = re.compile(r"ask the waiting decisions|ask (?:it|them) now|AskUserQuestion|ask the developer|" @@ -236,8 +236,9 @@ def test_a_decision_whose_member_ended_and_blocks_no_step_is_moot(self): pg.start("Parser", plan=["parser", "docs"]) self.neo_works_on_the_parser() self.neo_asks() + # the asking member ends with its step done (a step it only left waiting would keep waiting for the answer) pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a1", "agent_type": "devkit:neo", - "last_assistant_message": "stopped"}, False) # the asking member ends + "last_assistant_message": NEO_REPORT.format(check="✓ 12 parser tests pass")}, False) run = self.run_() self.assertFalse(any(s.get("waiting") == "D1" and s.get("state") == "blocked" for s in run["plan"])) self.assertEqual([], pg.pending_decisions(run)) diff --git a/tests/test_roles.py b/tests/test_roles.py index e2f78074..7f6e87eb 100644 --- a/tests/test_roles.py +++ b/tests/test_roles.py @@ -253,16 +253,15 @@ def refused(key, call, error=pg.StepError): for text in refusals.values(): self.assertEqual(bare(text), [], text) - def test_a_launch_that_names_none_of_its_members_steps_is_reported_role_first(self): + def test_a_launch_that_names_none_of_its_members_steps_takes_the_oldest_and_tells_the_member(self): + # a free lane takes the oldest step waiting for its member, and the member hears it is theirs with State() as t: pg.start("Parser", plan=["docs"]) pg.assign("docs", "Neo") t.launch("a1", "devkit:neo", "Neo: profile the importer") - note = pg.on_tool_done("claude", {"session_id": "s1"}) - body = pg.crew_read("M1")["text"] - self.assertIn("preview; read: dev crew read", note) - self.assertIn("Senior engineer (Neo) started as “Neo: profile the importer”, which names none of Senior " - "engineer (Neo)'s steps (“docs”)", body) + run = pg.load_run("claude", "s1") + self.assertEqual((run["plan"][0]["state"], run["plan"][0]["owner"]), ("running", "a1")) + self.assertIn("“docs” is your step now", " ".join(m["text"] for m in run["messages"] if m.get("to") == "a1")) def test_a_launch_too_deep_names_the_tech_lead_by_role(self): from test_crew_slots import call, config @@ -314,8 +313,8 @@ def test_a_step_for_a_busy_member_says_who_is_busy_role_first(self): with State(): _, waiting = dispatch._sorted(run) self.assertEqual([why for _, why in waiting], - ['Senior engineer (Neo) works with no step: dev progress assign "docs" --to "Neo" gives ' - '“docs” to that lane']) + ['Senior engineer (Neo) works with no step: “docs” joins that lane now; send it to them ' + '(SendMessage / send_input), and their dev progress step --step "docs" closes it']) class SessionContextTests(unittest.TestCase): From 011f4a1a5f0d87e7b906fc05994f5fe8ed99b6f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:38:25 -0800 Subject: [PATCH 32/52] test(crew): give the model's clean stops a real execution receipt The model's clean stop carried no receipt the gates accept (no folder for the Claude Code call, a Codex rollout older than 0.167.2), so the gates sent it back for a missing dev progress step and the review rule failed for the fixture's sake. A clean stop's transcript holds each dev progress step as it ran: a Claude Code Bash call with its result and exit code, or a Codex 0.167.2 rollout whose CommandExecution items carry devkit's lane and session stamps, as tests/test_gates_codex_proofs.py writes them; the members work in a real checkout. An unclean stop holds no step and is still sent back. Verified: on the branch the 6 model rules hold (python3 3.15 and /usr/bin/python3 3.9); before d0030c56 the review rule fails on Codex: the crew gates did not pass the resumed reviewer's clean report; the gates find the unclean stop's missing dev progress step on both hosts; dev test audit 0 findings --- tests/test_coordination_model.py | 91 +++++++++++++++++++++----------- 1 file changed, 59 insertions(+), 32 deletions(-) diff --git a/tests/test_coordination_model.py b/tests/test_coordination_model.py index 644de579..5028994d 100644 --- a/tests/test_coordination_model.py +++ b/tests/test_coordination_model.py @@ -13,6 +13,7 @@ import json import os import random +import subprocess import sys import time import unittest @@ -110,7 +111,10 @@ def __enter__(self): root = Path(self.state.tmp.name) tools = root / "bin" tools.mkdir() - (tools / "dev").symlink_to(core.DEVKIT_HOME / "bin" / "dev") + (tools / "dev").symlink_to(core.DEVKIT_HOME / "bin" / "dev") # devkit's own bin/dev, as installed + self.repo = root / "api" # the checkout the members work in: their commands' folder + self.repo.mkdir() + subprocess.run(["git", "init", "-q", str(self.repo)], check=True) self.patches = [mock.patch.dict(os.environ, {"PATH": str(tools) + os.pathsep + os.environ["PATH"], "DEVKIT_SESSION": f"{self.host}:s1"}), mock.patch.object(hooks, "STATE", root), mock.patch.object(canary, "LOG", root / "canary"), @@ -297,47 +301,70 @@ def act(self, a): return True def stop(self, aid, member, commands, again=False): - """The member's stop through the SubagentStop hook: canary, crew gates, the lane's end.""" - root = Path(self.state.tmp.name) - tr = root / f"transcript-{aid}-{self.k}.jsonl" - if self.host == "codex": - tr = self.codex_rollout(aid, commands, tr) - records = [] if self.host == "codex" else None - for i, command in enumerate(commands if records is not None else [], 1): - records += [{"type": "assistant", "isSidechain": True, "message": {"role": "assistant", "content": [ - {"type": "tool_use", "id": f"toolu_{i:04}", "name": "Bash", "input": {"command": command}}]}}, - {"type": "user", "isSidechain": True, "message": {"role": "user", "content": [ - {"type": "tool_result", "tool_use_id": f"toolu_{i:04}", "content": "ok"}]}}] - if records is not None: - tr.write_text("".join(json.dumps(r) + "\n" for r in records)) + """The member's stop through the SubagentStop hook (canary, crew gates, the lane's end), with its own + transcript: each of `commands` as it ran, with its receipt. -> whether the lane ended (the gates let it + through).""" + tr = Path(self.state.tmp.name) / f"transcript-{aid}-{self.k}.jsonl" + lines = self.codex_rollout(aid, commands) if self.host == "codex" else self.claude_transcript(commands) + tr.write_text("".join(json.dumps(r) + "\n" for r in lines)) name, role = MEMBERS[member] report = (f"**[Firefly> DevKit · {role} ({name})]** api · `main` · the work\n- **Done:** the work\n" "- **Check:** ✓ 12 tests pass\n- **Next:** the tech lead reviews it") data = {"session_id": "s1", "agent_id": aid, "agent_type": member if self.host == "codex" else f"devkit:{member}", "agent_transcript_path": str(tr), "last_assistant_message": report, - "stop_hook_active": again} + "stop_hook_active": again, "cwd": str(self.repo), "hook_event_name": "SubagentStop"} out = io.StringIO() with mock.patch("sys.stdin", io.StringIO(json.dumps(data))), contextlib.redirect_stdout(out): hooks.subagent_stop(self.host) return '"block"' not in out.getvalue() # the lane ended: the gates let this stop through - def codex_rollout(self, aid, commands, tr): - """A Codex member's own rollout as Codex 0.167.0 writes it: its session_meta (where its own history starts), - task_started, then one CommandExecution item per command with its folder, every record with its ordinal.""" - child = next(pg.SESSIONS.parent.glob(f".codex/sessions/*/*/*/rollout-*-{aid}.jsonl")) - meta = json.loads(child.read_text().splitlines()[0]) - meta["ordinal"] = 0 - meta["payload"]["subagent_history_start_ordinal"] = 1 - lines = [meta, {"timestamp": meta.get("timestamp"), "ordinal": 1, "type": "event_msg", - "payload": {"type": "task_started", "turn_id": "t1"}}] - for i, command in enumerate(commands, 2): - lines.append({"timestamp": meta.get("timestamp"), "ordinal": i, "type": "event_msg", "payload": { - "type": "item_completed", "turn_id": "t1", "item": { - "type": "CommandExecution", "id": f"exec-{aid}-{i}", "command": ["/bin/zsh", "-lc", command], - "cwd": f"file://{self.state.tmp.name}", "status": "completed", "exit_code": 0, - "aggregated_output": "✓"}}}) - tr.write_text("".join(json.dumps(r) + "\n" for r in lines)) - return tr + def claude_transcript(self, commands) -> list: + """A Claude Code member's transcript: each command as its Bash call, then that call's result, which is its + execution receipt (exit code 0).""" + out = [] + for i, command in enumerate(commands, 1): + use = f"toolu_{i:04}" + out += [{"type": "assistant", "isSidechain": True, "cwd": str(self.repo), "message": { + "role": "assistant", "content": [{"type": "tool_use", "id": use, "name": "Bash", + "input": {"command": command}}]}}, + {"type": "user", "isSidechain": True, "cwd": str(self.repo), "toolUseResult": { + "stdout": "✓ recorded", "stderr": "", "interrupted": False, "exitCode": 0}, + "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": use, + "content": "✓ recorded", "is_error": False}]}}] + return out + + def codex_rollout(self, aid, commands) -> list: + """A Codex 0.167.2 member's own rollout, as tests/test_gates_codex_proofs.py writes it: a session_meta that is + not a fork (history_mode paginated, source.subagent.thread_spawn), its turn_context, task_started, then per + command the code-mode exec call, the CommandExecution item of the command as it ran (devkit's lane and + session stamps in front of it, its ordinal, thread_id, file:// folder and exit code) and the call's output.""" + turn = "01a1f737-3cdb-7402-bf18-00000000000a" + lines = [("session_meta", { + "id": aid, "session_id": "s1", "parent_thread_id": "s1", "timestamp": "2026-11-19T20:29:14.000Z", + "cwd": str(self.repo), "originator": "codex_exec", "cli_version": "0.167.2", + "thread_source": "subagent", "history_mode": "paginated", "multi_agent_version": "v2", + "agent_path": f"/root/{aid}", "agent_nickname": "Tesla", "source": {"subagent": {"thread_spawn": { + "parent_thread_id": "s1", "depth": 1, "agent_path": f"/root/{aid}", + "agent_nickname": "Tesla", "agent_role": None}}}}), + ("turn_context", {"turn_id": turn, "cwd": str(self.repo), "approval_policy": "never", + "sandbox_policy": {"type": "danger-full-access"}, "model": "gpt-6-luna"}), + ("event_msg", {"type": "task_started", "turn_id": turn})] + for i, command in enumerate(commands, 1): + ran = f"DEVKIT_SESSION=codex:s1 DEVKIT_FROM_AGENT={aid} {command}" + call = f"call_{i:04d}" + lines += [("response_item", {"type": "custom_tool_call", "status": "completed", "call_id": call, + "name": "exec", + "input": f"text(await tools.exec_command({{cmd:{json.dumps(ran)}}}))\n"}), + ("event_msg", {"type": "item_completed", "thread_id": aid, "turn_id": turn, "item": { + "type": "CommandExecution", "id": f"exec-{i:08d}", "process_id": "99924", + "command": ["/bin/zsh", "-lc", ran], "cwd": f"file://{self.repo}", + "parsed_cmd": [{"type": "unknown", "cmd": ran}], "source": "unified_exec_startup", + "status": "completed", "aggregated_output": "✓ recorded\n", "exit_code": 0, + "duration": {"secs": 0, "nanos": 2208}}}), + ("response_item", {"type": "custom_tool_call_output", "call_id": call, "output": [ + {"type": "input_text", "text": "Script completed\nWall time 0.3 seconds\nOutput:\n"}]})] + return [{"timestamp": "2026-11-19T20:29:19.000Z", "ordinal": n, "type": kind, "payload": payload} + for n, (kind, payload) in enumerate(lines)] # ---------------------------------------------------------------- the rules From 4871034bb0a9648884f89109046a8b7371697fa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:45:10 -0800 Subject: [PATCH 33/52] test(crew): bring back the resumed Codex reviewer case on the real hooks A resumed Codex reviewer's clean report after a send-back was never judged on 26.11.25, so review lanes ended unverified; the Codex case was removed after a check against a baseline that already held the gates fix. The member's rollout has Codex 0.167.2's shape: a session_meta that is not a fork, turn_context and task_started, and per command the code-mode exec call and the CommandExecution item of the command as it ran, devkit's stamps in front of it, with its thread, folder, exit code and ordinal. The reviewer resumes through the SubagentStart hook. Verified: before d0030c56 the case fails: the crew gates did not pass the resumed reviewer's report (with the 0.167.2 or the 0.167.0 fork rollout, stamped or bare); on the committed branch the 7 Codex tests pass; dev test audit 0 findings --- tests/test_coordination_codex.py | 79 +++++++++++++++++++++++--------- 1 file changed, 58 insertions(+), 21 deletions(-) diff --git a/tests/test_coordination_codex.py b/tests/test_coordination_codex.py index 7c3db894..1045d56d 100644 --- a/tests/test_coordination_codex.py +++ b/tests/test_coordination_codex.py @@ -34,35 +34,51 @@ def run_lead(self, plan: str, *assign): s.ok("progress", "assign", step, "--to", name, "--scope", scope) return s + TURN = "01a1f737-3cdb-7402-bf18-000000000003" + def agent_rollout(self, s, aid: str, member: str, task: str, parent: str = "", depth: int = 1, source=None): - """The spawned agent's rollout as Codex 0.167.0 writes it: its session_meta says where its own history starts - (subagent_history_start_ordinal), its own turn opens with task_started, and every record has its ordinal.""" + """The spawned agent's own rollout as Codex 0.167.2 writes it (tests/test_gates_codex_proofs.py): a + session_meta that is not a fork (no forked_from_id, history_mode paginated, source.subagent.thread_spawn), + its turn_context, then task_started, every record with its ordinal.""" path = super().agent_rollout(s, aid, member, task, parent, depth, source) meta = json.loads(path.read_text()) - meta["ordinal"] = 0 - meta["payload"]["subagent_history_start_ordinal"] = 1 - turn = {"timestamp": _now(), "ordinal": 1, "type": "event_msg", - "payload": {"type": "task_started", "turn_id": "01a1c178-651e-7bc1-a532-a2415b26e099"}} - path.write_text(_line(meta) + _line(turn)) + meta["payload"].pop("forked_from_id", None) + meta["payload"].update(cli_version="0.167.2", history_mode="paginated", multi_agent_version="v2") + path.write_text("") + self.record(aid, "session_meta", meta["payload"]) + self.record(aid, "turn_context", {"turn_id": self.TURN, "cwd": str(s.repo), "approval_policy": "never", + "sandbox_policy": {"type": "danger-full-access"}, "model": "gpt-6-luna"}) + self.record(aid, "event_msg", {"type": "task_started", "turn_id": self.TURN}) return path - def member(self, s, aid: str, member: str, *args) -> dict: - """A member's `dev` command: its shell call through the hooks, and the CommandExecution item its own rollout - records for it, with its folder and ordinal.""" - r = s.dev(*args, member=aid, member_type=member) - cmd = " ".join(["dev"] + [shlex.quote(str(a)) for a in args]) - item = {"type": "CommandExecution", "id": r["call"]["tool_use_id"], "command": ["/bin/zsh", "-lc", cmd], - "cwd": f"file://{s.repo}", "status": "completed" if r["rc"] == 0 else "failed", - "exit_code": r["rc"], "aggregated_output": (r["out"] + r["err"])[-2000:]} + def record(self, aid: str, kind: str, payload: dict): path = self.rollout(aid) - ordinal = len(path.read_text().splitlines()) + ordinal = len(path.read_text().splitlines()) if path.exists() else 0 with path.open("a") as fh: - fh.write(_line({"timestamp": _now(), "ordinal": ordinal, "type": "event_msg", "payload": { - "type": "item_completed", "turn_id": "01a1c178-28b7-7fa1-a67c-2bd8b7433d66", "item": item}})) + fh.write(_line({"timestamp": _now(), "ordinal": ordinal, "type": kind, "payload": payload})) + + def member(self, s, aid: str, member: str, *args) -> dict: + """A member's `dev` command: its shell call through the hooks, and what its own rollout records for it, as + Codex 0.167.2 does in code mode: the exec call, the CommandExecution item of the command as it ran (the + PreToolUse hook's rewrite, devkit's stamps in front of it) with its thread, folder and exit code, then the + call's output.""" + r = s.dev(*args, member=aid, member_type=member) + ran, call = r["ran"], f"call_{r['call']['tool_use_id'][-6:]}" + self.record(aid, "response_item", {"type": "custom_tool_call", "status": "completed", "call_id": call, + "name": "exec", + "input": f"text(await tools.exec_command({{cmd:{json.dumps(ran)}}}))\n"}) + self.record(aid, "event_msg", {"type": "item_completed", "thread_id": aid, "turn_id": self.TURN, "item": { + "type": "CommandExecution", "id": r["call"]["tool_use_id"], "process_id": "99924", + "command": ["/bin/zsh", "-lc", ran], "cwd": f"file://{s.repo}", + "parsed_cmd": [{"type": "unknown", "cmd": ran}], "source": "unified_exec_startup", + "status": "completed" if r["rc"] == 0 else "failed", "exit_code": r["rc"], + "aggregated_output": (r["out"] + r["err"])[-2000:], "duration": {"secs": 0, "nanos": 2208}}}) + self.record(aid, "response_item", {"type": "custom_tool_call_output", "call_id": call, "output": [ + {"type": "input_text", "text": "Script completed\nWall time 0.3 seconds\nOutput:\n"}]}) return r def stop(self, s, aid: str, member: str, report: str, again: bool = False) -> dict: - """SubagentStop as Codex 0.167.0 sends it, the member's own rollout as its transcript. The crew gates credit a + """SubagentStop as Codex sends it, the member's own rollout as its transcript. The crew gates credit a `dev` command only when `dev` on the hook's PATH is devkit's own bin/dev, so this hook gets one first.""" trusted = self.home / "devkit-bin" if not trusted.exists(): @@ -82,8 +98,6 @@ def held(self, s, name: str) -> tuple: class CodexLaneTests(CodexCoordination): - # A resumed Codex reviewer's clean report after a send-back does approve on 26.11.26 (the gates credit the - # executed step its rollout records), so that fault has no Codex test here; tests/test_gates_judgment.py keeps it def test_a_codex_members_checked_record_without_step_closes_its_lanes_only_running_step(self): s = self.run_lead("api=30m [backend]; ui=30m [frontend]", ("api", "Tank", "api/**")) self.spawn(s, TANK, "tank", "api") @@ -121,6 +135,29 @@ def test_a_resumed_codex_lane_takes_the_one_step_assigned_to_its_member_by_role( self.assertEqual(self.held(s, "export"), (TANK, "running")) self.assertEqual(s.run_doc()["agents"][TANK].get("scope"), ["export/**"]) + def test_a_resumed_codex_reviewers_clean_report_approves_after_an_earlier_send_back(self): + # the review lanes that ended unverified on Codex: the reviewer was sent back once, resumed with + # SubagentStart, recorded its review with --approves and a ✓ Check, and its clean report was never judged + s = self.run_lead("api=30m [backend]; review=20m [review] after api", ("api", "Tank", "api/**")) + self.spawn(s, TANK, "tank", "api") + self.member(s, TANK, "tank", "progress", "step", "api committed", "--step", "api", "--check", "✓ 12 pass") + self.stop(s, TANK, "tank", REPORT.format(role="Backend engineer (Tank)", task="api")) + s.ok("progress", "assign", "review", "--to", "Seraph") + self.spawn(s, SERAPH, "seraph", "review") + report = REPORT.format(role="Code reviewer (Seraph)", task="review") + self.assertEqual(self.stop(s, SERAPH, "seraph", report).get("decision"), "block") # no step recorded yet + self.stop(s, SERAPH, "seraph", report, again=True) # let through + self.assertEqual(self.held(s, "review")[1], "unverified") + s.ok("progress", "reopen", "review", "--why", "the reviewer gives the verdict again") + self.subagent_start(s, SERAPH, "seraph") # resumed: Codex starts the same thread again + self.assertEqual(self.held(s, "review"), (SERAPH, "running")) + r = self.member(s, SERAPH, "seraph", "progress", "step", "review done", "--step", "review", "--check", + "✓ read the diff, 12 tests pass", "--approves", "api") + self.assertEqual(r["rc"], 0, r["err"]) + self.stop(s, SERAPH, "seraph", report) + why = [h["why"] for h in s.run_doc()["history"] if h["step"] == "review"][-1] + self.assertEqual(self.held(s, "review")[1], "done", why) + class CodexCallerTests(CodexCoordination): # On Codex the tech lead's own commands were "unverified", which main-only commands allow, so a member's open From c209afbb73f47dcc55ae86ce2fdb0c0f90615da4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:54:05 -0800 Subject: [PATCH 34/52] docs(crew): document call tokens, lane claims, and CI step limits Members and the tech lead need to know how devkit names the caller of a dev command, which step a free lane takes, that a blocked step frees its lane, how the crew gates judge every stop, and why a local CI step or a CI watch stops when it does. The crew page, the agents page, and the crew skill describe the call token, the claim order, blocked steps, scopes that follow running steps, filename scopes, and gates that judge every stop. The CI pages and the cicd skill give the local step limit, the watch limit, the runner wait line, and the never-started job classes. The audit page lists the caller identity records; SECURITY.md says what the call token protects and what it does not; the bug registry page says how to avoid its notification mail. Verified: dev docs check on the 11 pages: 0 markdownlint issues, all links resolve, 0 Vale errors (6 earlier warnings on unchanged lines); dev test run tests/test_consistency.py tests/test_crew.py tests/test_skillguard.py tests/test_lessonlint.py (204 passed) and tests/test_install.py (34 passed) --- SECURITY.md | 32 ++++++ docs/agents.md | 6 +- docs/audit.md | 38 ++++++- docs/bug-registry.md | 5 +- docs/ci-cd.md | 16 ++- docs/commands.md | 26 +++-- docs/crew.md | 198 ++++++++++++++++++++++++------------ docs/git-and-github.md | 10 +- docs/troubleshooting.md | 39 ++++++- plugin/skills/cicd/SKILL.md | 17 +++- plugin/skills/crew/SKILL.md | 97 +++++++++++------- 11 files changed, 362 insertions(+), 122 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 226cb234..9566b30a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -38,6 +38,34 @@ To limit what agents can do, use the controls that do enforce limits: `DEVKIT_CONFIG` and `DEV_ROOT` included, and so change where devkit reads its configuration. Trust only repositories whose code you would run. +### What the call token protects + +devkit names who runs each `dev` command by a call token: the pre-tool hook puts `DEVKIT_CALL` in front of the call, +and the token holds only for the shell the agent ran the call in, and its child processes, and only while the call is +open (see [The crew › Who is calling](docs/crew.md#who-is-calling)). It protects against mistakes and makes misuse +visible: + +- **Mix-ups between callers.** A crew member's command is never taken as the tech lead's, or as another member's: + not when their command texts look alike, not while the tech lead's call and a member's call are open at the same + time, and not when devkit cannot tell who calls, since it then refuses the change. +- **Commands outside their call.** A background or detached job, a nested agent such as `codex exec` or `claude -p`, + and a token copied from a log or a transcript name nobody once their call has closed, or outside the call's own + shell, so the state changes they try are refused. +- **A record of each attempt.** Each failed check and each state change without a token writes a caller identity + record to the audit trail ([The audit trail › Caller identity records](docs/audit.md#caller-identity-records)). + devkit keeps only a hash of the token, and removes its value from every command text it records. + +What it does not protect: + +- **devkit's own state.** The call ledger, the session records, and the audit log are files your user owns. A crew + member that edits them can still act as another caller. The next tech-lead call shows the damage, but devkit does + not stop it, and such an attack is out of scope for reports (see [Scope](#scope)). +- **What an agent may run.** The token names who runs a `dev` command and limits nothing else. Against an agent set + on misuse, the controls that hold are the agent's permission mode and your Git host's branch protection. +- **The token while its call runs.** Any process of your user can read it from the process list then: holding only + for the call's own shell is what makes a copy useless elsewhere. Transcripts and Codex rollouts, which the agents + keep, can hold the token after its call closed, when it names nobody. + ## Supported versions | Version | Supported | @@ -97,6 +125,8 @@ In scope: - the `dev` CLI and everything under `lib/` and `bin/`; - the hooks: a way to make a hook leak data, corrupt devkit's records, or run code devkit did not mean to run is a vulnerability; +- the crew's caller identity: a way for one agent to act as the tech lead or another crew member through devkit's + commands without editing devkit's state files, or one that leaves a record that looks like a normal verified call; - the installer (`install.sh`, `dev setup`, `dev install`) and the settings, hooks, and instructions it writes; - the MCP server (`dev mcp`) and the Claude Desktop extension; - the dashboard, a generated HTML file: data it shows without escaping is in scope; @@ -111,6 +141,8 @@ Out of scope: - issues in the agents themselves (Claude Code, Codex, Claude Desktop, the ChatGPT app): report those to their vendors; - attacks that need an already compromised machine or account; +- a crew member, or another process of your user, that edits devkit's state files (the call ledger, the session + records, the audit log) to act as another caller; - what an agent runs with the permissions you gave it: devkit does not limit agents (see [devkit is not a security boundary](#devkit-is-not-a-security-boundary)). diff --git a/docs/agents.md b/docs/agents.md index 0fa419ec..6d82a434 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -240,10 +240,10 @@ works from the Desktop and ChatGPT apps, whose PATH is minimal. | --- | --- | --- | --- | | SessionStart | `startup\|resume\|clear\|compact`, 30 s | `startup\|resume\|clear\|compact`, 30 s | Records the session's starting commit and branch, refreshes the project's generated blocks, exports `DEVKIT_SESSION` (Claude), restores managed settings in the background, clones `node_modules` into a fresh worktree, queues a sync that pulls the claims of other machines, and prints the workspace context. Shows you the [welcome](concepts.md#the-session-start-welcome) as its `systemMessage`, on both agents (at most five lines: what needs you, what runs, what is next, and where you are), and tells the model which lines you saw; the notices about an older devkit copy and extensions become need lines in it, and a headless run, a crew member's session, or a scratch repository gets none. The context stays under both agents' limits on a hook's output (at most 9,000 bytes: past 10,000 characters Claude Code shows the model a 2,000-character preview, and Codex past about 2,500 tokens), with what matters most first, so a cut takes the end, the handoff note's excerpt, at whole lines. In a project, it carries an index of the kinds of work the agent declares by id, with the lesson anchors and where the rest is (`dev crew raci`, `dev crew rules`, and `config/skill-rules.json` for the skills); the three most relevant known pitfalls; and the handoff note's path, Now tasks, and current state. After a compaction or a resume, the continuity brief comes first, after the line about the welcome you saw: the run and its current step, the crew working now (not to relaunch), the decisions and messages waiting, your latest requests verbatim, the last status block and git, at most 4 KB. After `/clear`, a notice of the previous session's open run and `dev session carry` | | UserPromptSubmit | 10 s | 10 s | Starts the turn clock, except for a message you type while the agent works, which Claude Code sends with the running turn's `prompt_id` and Codex with the running turn's `turn_id`: devkit keeps that turn and its request, and adds the message beside them once, even when the transcript or rollout reports it again at a later hook; gives the agent a short reminder of the presentation rules the final message of its last development turn missed (the status block, a role, the Progress line with the run's current counts, the reply language), recorded by Stop instead of sending that turn back, tells it to follow them when this turn is development work, and not to rewrite or repeat that reply. The reminder comes with your prompts only, never with a background notification or a message typed mid-turn, and again at each one until a turn that Stop classes as development work ends after it; adds real progress records and the branch's CI/CD pipelines when you ask for status; reminds the tech lead to declare the request's kinds of work by their ids from the catalog and route each by the RACI, the same reminder in every language and never a guess from the request's words (`crew.route_hint` turns it off); reminds the agent of the status block in a session that already missed it once, naming the failure mode (nothing comes before the block); registers a session that missed SessionStart and injects its context, catalog included. When decisions wait for you that you have not seen since your last prompt, tells the tech lead once per batch to ask them together in as few question calls as the rules allow (see [The crew › How the tech lead asks you](crew.md#how-the-tech-lead-asks-you)). It does not read your prompt for corrections or for skills. Background notifications (subagent results, system notices) and relayed comments are not treated as your request. Keeps your prompt, redacted and cut to 1,000 characters, as pending in the session's continuity checkpoint until Stop classes the turn, and gives the main session, once and first, what waits for it: the brief of a compaction only the transcript showed, or "Not in the summary." A prompt that wakes the session for a background event (a task notification, an agent message) also carries what waits for it: crew questions, decisions, ready steps, CI results, and notices | -| PreToolUse | `Bash\|Monitor\|Write\|Edit\|MultiEdit\|NotebookEdit\|Agent\|Task\|WebFetch\|mcp__.*`, 15 s | `^(Bash\|apply_patch\|spawn_agent)$`, 15 s | `dev hook pre-tool` (`dev hook guard`, its earlier name, still runs it for sessions started before the update). It never refuses a call or asks you about one: its output is nothing, context for the call, or a crew member's command rewritten to carry its lane. On Codex, which reads no PreToolUse context, a member gets the advice as a devkit notice at its next PostToolUse, and a rewrite carries `allow` only when Codex's approval policy is `never`, or for one plain `dev progress`, `dev crew`, `dev watch`, or `dev session` call with nothing the shell would expand; otherwise the call is not rewritten and the member is told. Starts the call's timer, and records each shell call with the agent that made it (the call ledger that tells devkit [who is calling](crew.md#who-is-calling)). On a Claude Code subagent launch (Agent, Task), records its description for its lane and appends the required skills, the known pitfalls, and the report format to the brief. Before that, a crew member's launch whose description names none of the member's steps gets the name of the one step that waits for its launch, so the launch binds it, and the tech lead is told; with two or more waiting, or two or more named equally, the tech lead gets the exact description that takes each. Codex fires no PreToolUse for `spawn_agent`: a Codex launch is recorded at SubagentStart (see below the table). A Codex `exec_command` is read by its `cmd` in its `workdir`, like Bash's `command`. Inside a subagent (the input carries `agent_id`), routes a single `dev progress` or `dev crew` command to that subagent's lane. Adds one line of advice to the call's context for a write outside a member's file scope or by a read-only member, a launch past the crew's slots, an edit of a file a working member holds, a lane call it cannot route (which runs as the main session), and a commit that would take untracked unfinished work. Names the open [lessons](lessons.md) anchored on the command the call runs or the file it writes, each at most once an hour per agent, and adds the lesson of each matching [lesson rule](lessons.md#lesson-rules). Codex does not read a call's context, so there a rule's lesson is not counted as shown. When the hook itself fails, it logs the error and the call runs | +| PreToolUse | `Bash\|Monitor\|Write\|Edit\|MultiEdit\|NotebookEdit\|Agent\|Task\|WebFetch\|mcp__.*`, 15 s | `^(Bash\|apply_patch\|spawn_agent)$`, 15 s | `dev hook pre-tool` (`dev hook guard`, its earlier name, still runs it for sessions started before the update). It never refuses a call or asks you about one: its output is nothing, context for the call, or the command rewritten to carry its call token and, for a crew member, its lane. On Codex, which reads no PreToolUse context, a member gets the advice as a devkit notice at its next PostToolUse, and a rewrite carries `allow` only when Codex's approval policy is `never`, or for one plain `dev progress`, `dev crew`, `dev watch`, or `dev session` call with nothing the shell would expand; otherwise the call is not rewritten and the member is told. Starts the call's timer, records each shell call with the agent that made it (the call ledger), and puts the call token in front of it, which tells devkit [who is calling](crew.md#who-is-calling): every shell call carries it in Claude Code's `bypassPermissions` mode and under Codex's `never` approval policy; elsewhere only a call that visibly runs `dev` does, so you get no more permission prompts than before. On a Claude Code subagent launch (Agent, Task), records its description for its lane and appends the required skills, the known pitfalls, and the report format to the brief. Before that, a crew member's launch whose description names none of the member's steps gets the name of the one step that waits for its launch, so the launch binds it, and the tech lead is told; with two or more waiting, or two or more named equally, the tech lead gets the exact description that takes each. A follow-up launch that names one of the member's steps that is already done is left unchanged. Codex fires no PreToolUse for `spawn_agent`: a Codex launch is recorded at SubagentStart (see below the table). A Codex `exec_command` is read by its `cmd` in its `workdir`, like Bash's `command`. Inside a subagent (the input carries `agent_id`), routes a single `dev progress` or `dev crew` command to that subagent's lane. Adds one line of advice to the call's context for a write outside a member's file scope or by a read-only member, a launch past the crew's slots, an edit of a file a working member holds, a lane call it cannot route (which runs as the main session), and a commit that would take untracked unfinished work. Names the open [lessons](lessons.md) anchored on the command the call runs or the file it writes, each at most once an hour per agent, and adds the lesson of each matching [lesson rule](lessons.md#lesson-rules). Codex does not read a call's context, so there a rule's lesson is not counted as shown. When the hook itself fails, it logs the error and the call runs | | PostToolUse | `Bash\|Agent\|Task\|TaskStop\|Monitor\|Write\|Edit\|MultiEdit\|WebFetch\|WebSearch\|AskUserQuestion\|SendMessage`, 10 s | `^(Bash\|apply_patch)$`, 10 s | Closes the shell call in the call ledger. Records every Write, Edit, and MultiEdit call with its file, its caller, and its time: a file that changed during a read-only member's shell call is credited only to the member whose own edit call touched it, and any other such file is held against the read-only member. Ends the lane of an agent TaskStop stopped (it fires no SubagentStop): its slot frees and its step waits for a new launch. Names the open lessons whose error signature the call's output shows, each at most once an hour per agent, and the lesson rules whose text it shows. Adds each call to the [bug registry's](bug-registry.md) session ledger, and, for a marker of devkit's own failure in the output, gives the known detour or tells the agent how to find one. Right after a call that usually ends the turn (a subagent launch, a monitor, a background command, or `dev progress done`, `dev handoff --log`, `dev sync`, `dev task done`, a push, a PR, or a release), shows the main session the status block its final message opens with, with the project and branch filled in, at most once per 2 minutes in a turn; records slow calls; delivers crew messages to their recipient (the main session, or the subagent that made the call); tells the main session about decisions waiting for you and members ready to launch; reminds the main session to update you after a long silence; after a `git commit`, `push`, `merge`, `tag`, `rebase`, `cherry-pick`, or `revert`, or a `gh pr create`, `gh pr merge`, or `gh release create`, queues a sync of the handoff repository (see [Teams and machines › Near-real-time sync](teams.md#near-real-time-sync)). Gives the main session, once and first, the brief of a compaction only the transcript showed or "Not in the summary"; gives a member, after its own compaction, a reminder of its role, step, scope, procedure, and report format. A SendMessage from the main session to a member answers the questions to the tech lead that its text names (`M3: …`): each is marked answered via SendMessage, the text is kept as its answer, and the audit trail records `crew.message-answered`; a SendMessage that names none answers none, and a notice lists the questions that still wait. In Claude Code's main session, reads the messages you typed while it worked from the transcript (Claude Code also runs UserPromptSubmit for each, with the running turn's `prompt_id`): each counts as your latest request for the crew slot kept for you and for continuity, never as an approval. The crew messages, decisions, ready steps, CI results, and notices it delivers are the ones a `dev watch --wait` takes too: each reaches the session once, whichever reads it first | | PostToolUseFailure | `Agent\|Task\|Bash`, 10 s | — | A subagent launch that failed (an unknown agent type, an interrupt) started no agent, so its launch record goes at once: it never labels another agent or holds a crew slot. A failed or interrupted shell call leaves the call ledger, and its line goes to the [bug registry's](bug-registry.md) session ledger. When one agent's shell command fails twice in a row with the same error, it stops that agent once per command with the root-cause paragraph, the lessons the error matches, and the devkit bugs the registry knows (see [Lessons › Recall](lessons.md#recall)); a crew member's third identical failure sends the tech lead one notice. Names the open lessons and lesson rules whose error text the failure shows, and, for a marker of devkit's own failure, the known detour | -| SubagentStart · SubagentStop | 5 s · 10 s | 5 s · 10 s | Opens and closes the subagent's progress lane (its persona, its step, its active time); a lane binds to exactly one launch. At SubagentStop, for a member someone launched, sends it back once for each of these, in order: a report that does not start with its own status block (`**[Firefly> DevKit · Neo]**`); no `dev progress step` in its lane; and the [crew gates](crew.md#every-report-is-checked) (proofs, skills, unfinished work, tests that cannot fail, lessons). The gates get 6 s of the hook's 10: past that they do not judge the stop, the member goes through, no earlier pass of its gates approves anything, and the audit trail records `crew.gate` as let through. Then it closes the lane and its step, records no observed repeat for lessons shown without a later observed miss, without claiming success, and reads the member's transcript once more for a compaction no hook saw. The compaction summarizer's stop is skipped: it owes no report and binds nothing | +| SubagentStart · SubagentStop | 5 s · 10 s | 5 s · 10 s | Opens and closes the subagent's progress lane (its persona, its step, its active time); a lane binds to exactly one launch. At SubagentStop, for a member someone launched, sends it back once for each of these, in order: a report that does not start with its own status block (`**[Firefly> DevKit · Neo]**`); no `dev progress step` in its lane; and the [crew gates](crew.md#every-report-is-checked) (proofs, skills, unfinished work, tests that cannot fail, lessons). The crew gates judge every stop. A member is sent back once per lane life (its launch, or a resume), and its next stop is judged again: a clean report with Check ✓ passes, so a review it finishes ends done. A stop let through with findings approves nothing; it is audited as `crew.gate` let through, and its findings reach the tech lead in one notice. On Codex, the gates read a member's executed command without devkit's own stamps in front of it. The gates get 6 s of the hook's 10: past that they do not judge the stop, the member goes through, no earlier pass of its gates approves anything, and the audit trail records `crew.gate` as let through. Then it closes the lane and its step, records no observed repeat for lessons shown without a later observed miss, without claiming success, and reads the member's transcript once more for a compaction no hook saw. The compaction summarizer's stop is skipped: it owes no report and binds nothing | | Stop | 10 s | 10 s | On development turns only ([Concepts › Development work only](concepts.md#development-work-only)): checks, scores, and stores the status block. A final message that breaks a presentation rule is never sent back, because you have already read it: the block missing or not first (quoting the reply's first line), a crew member named without the role, while a `dev progress` run is active no Progress bullet or other step counts than the run's, or prose in another language than yours. devkit records the miss (`canary.remind` in the audit trail) and your next prompt reminds the agent; when the turn goes back for other work, the reminder joins that message instead (`canary.remind` with the `blocked` outcome, which `dev canary` lists as added to a send-back). Asks the agent to continue, and then to write only what is new since its last reply, when the turn left unfinished work without a task (`dev stubs`), new tests cannot fail (`dev test audit`), a plan changed without `dev plan revise`, matching files changed or matching commands ran without their required skills, the turn sent work to origin and left its unfinished CI run with nothing that wakes the agent (Claude Code: a live Monitor or background command running `dev ci watch --wait`; Codex, which has no background wake-up: that command in the foreground in this turn; see [CI/CD pipelines › The end-of-turn check](ci-cd.md#the-end-of-turn-check)), or your commits are newer than the handoff note's last real update (its human sections; task and session lines do not count), checked after every turn with new commits and from the repository the session is in now; once per session after a fix or revert commit, asks whether it deserves a lesson, with the anchor flags the lesson needs (`--file`, `--command`, `--error`), since a lesson with none is refused; counts a lesson id the reply names as a use that keeps the lesson strong; writes a missed block to the audit trail; records the turn; and, at most every 2 minutes, starts a background sync that writes the session line, renews locks, and publishes presence. When the turn ends (it is not sent back), refreshes the continuity checkpoint and keeps the turn's requests only when the turn was development work; when the classifier fails, they go. Sends back, once per turn, a main-session turn that ends while events can still arrive (a crew member works, a launch is pending, a step waits for a crew slot, CI the session sent has not finished) with nothing armed that wakes it: on Claude Code a live `dev watch --wait` (Bash `run_in_background`), on Codex one run in the foreground in this turn. A live `dev watch --wait` also covers the CI watch of a push | | SessionEnd | 10 s | 3 s | A background sync that writes the session's final line and closes the session record. Records exposure and any observed repeats without treating session completion as proof of success (see [Lessons › Measure](lessons.md#measure-shown-no-observed-repeat-missed)); a session that ends without SessionEnd has them resolved by the nightly fold after a day idle. After `/clear`, links the next session in the folder to this one for 10 minutes, and this session's kept requests go | | PreCompact | `manual\|auto`, 15 s | 15 s | Writes the session's continuity checkpoint (the run, the crew working now, the decisions and messages waiting, your last 5 requests, git) and records the compaction. In Claude Code's main session, adds devkit's instructions to the summarizer's: what to keep, by id, and your open requests word for word. Never blocks a compaction | @@ -254,7 +254,7 @@ works from the Desktop and ChatGPT apps, whose PATH is minimal. The Stop hook never loops: it asks for one more pass at most once per turn for changed plans, for an unwatched CI run, and for a wait that is not armed, once per session for each missing skill, once per turn for the handoff note, and once per session for a lesson. It records each presentation rule at most once per turn and never asks for a pass -for one. SubagentStop sends a member back at most once for each of its checks. With `canary.enforce`, +for one. SubagentStop sends a member back at most once for each of its checks, and for the crew gates once per lane life. With `canary.enforce`, `handoff.enforce`, `skills.enforce` or `crew.gates.enforce` set to `false`, the matching request is not made; the crew gates still record what they find in the audit trail (`crew.gate`). diff --git a/docs/audit.md b/docs/audit.md index b5028a7a..ab1ee0a9 100644 --- a/docs/audit.md +++ b/docs/audit.md @@ -310,7 +310,7 @@ dev audit show 01M6SFPEZ2 | `outcome` | yes | `ok`, `blocked`, `failed`, or `recorded` | | `why` | for an override | The reason given with `--why`, redacted. At most 300 characters | | `evidence` | when there is some | `command`, `commit`, `check`, `exit`, `duration`, `cwd`, `tool`, `rule`, `count`, `file`, `flag` (an escape hatch's name), `channel`, `transcript_uuid`, and, for a question tool answer, `match` and `asked` | -| `ref` | when there is some | Links to other records and decisions: `id`, `by`, `was`, `type`, `result`, `answer`, `label`, `labels`, `asked_by`, `irreversible`, `mode`, `overrides`, `routed`, and `session`; for messages, claims, and escalations between agent sessions, `kind`, `recipients`, and `resource`; for the irreversible-action gate, `tier` (1 or 2), `setting` (`audit` or `enforce`), `grant` (the grant's id), `source` (`policy-auto`, `E1`, `E2`, `step`, or `preapproval`), `repo` (the `owner/repo` acted on), `origin_repo` (the session's own project, when automatic policy allowed an operation in another project of your workspace), and, for a program the guard cannot classify, `kind` (`unclassified:unread`, `unclassified:built`, `unclassified:unsure`, or `unclassified:opaque`); for the developer's approval lines (`crew.evidence`), `kind` `typed-midturn` when devkit read the line from the session's transcript because you typed it while the session worked, and `since` (the running turn's start) for a line the prompt hook received while the session worked: `dev audit verify` accepts the transcript's record of it when it is stamped between `since` and the record's time; automatic authorization also retains `operation`, `mode_source`, `policy_digest`, `origin_repo`, `account`, and `principal_kind`; for a guard refusal, `refusal_id` (the stable id of the place that refused, or `hooks:` for a refusal the hook makes itself; see [The bug registry](bug-registry.md)) | +| `ref` | when there is some | Links to other records and decisions: `id`, `by`, `was`, `type`, `result`, `answer`, `label`, `labels`, `asked_by`, `irreversible`, `mode`, `overrides`, `routed`, and `session`; for messages, claims, and escalations between agent sessions, `kind`, `recipients`, and `resource`; for [caller identity records](#caller-identity-records), `agent`, `ancestors`, `lane_var`, and `thread`; for the irreversible-action gate, `tier` (1 or 2), `setting` (`audit` or `enforce`), `grant` (the grant's id), `source` (`policy-auto`, `E1`, `E2`, `step`, or `preapproval`), `repo` (the `owner/repo` acted on), `origin_repo` (the session's own project, when automatic policy allowed an operation in another project of your workspace), and, for a program the guard cannot classify, `kind` (`unclassified:unread`, `unclassified:built`, `unclassified:unsure`, or `unclassified:opaque`); for the developer's approval lines (`crew.evidence`), `kind` `typed-midturn` when devkit read the line from the session's transcript because you typed it while the session worked, and `since` (the running turn's start) for a line the prompt hook received while the session worked: `dev audit verify` accepts the transcript's record of it when it is stamped between `since` and the record's time; automatic authorization also retains `operation`, `mode_source`, `policy_digest`, `origin_repo`, `account`, and `principal_kind`; for a guard refusal, `refusal_id` (the stable id of the place that refused, or `hooks:` for a refusal the hook makes itself; see [The bug registry](bug-registry.md)) | | `prev` · `hash` | yes | The hash chain, see [Verify the chain](#verify-the-chain) | The `flag` and `match` evidence, the `irreversible` reference, and the fields of the irreversible-action gate appear @@ -356,6 +356,42 @@ it went to (`ref.recipients`), and the claimed resource (`ref.resource`), never | `peer.escalate` · `peer.settle` | `decision`, notice | An escalation and the developer's settling of it, with the choice's letter or `free text` | | `peer.sweep` | `job`, info | The hourly cleanup of old messages, ended sessions' mailboxes, and lapsed claims | +### Caller identity records + +devkit names who runs each `dev` command by its call token (see +[The crew › Who is calling](crew.md#who-is-calling)). Each failed check of a token, each state change that has no +token, and each fact about Codex threads that changes how devkit names a caller writes one record. A record holds: + +- the call's id, in `target` and `crew.tool_use_id`; +- the session devkit found, in `ref.session`, and its agent, in `ref.agent`; +- the `dev` command line, masked like any other, in `evidence.command`; +- the processes between the command and its agent, in `ref.ancestors`; +- the lane variable and the `CODEX_THREAD_ID` the command carried, in `ref.lane_var` and `ref.thread`; +- the outcome. + +No record holds the token's value: devkit replaces it with a redaction mark in every text it keeps. + +| Action | Category and severity | Records | +| --- | --- | --- | +| `caller.no-token` | `security`, warning | A state change without a call token, in a session whose calls carry one: refused | +| `caller.stale-token` | `security`, warning | A token whose call has closed or ran past its time limit, such as a background command's: refused for a state change | +| `caller.foreign-session` | `security`, warning | A token of another session's call, such as one a nested `codex exec` or `claude -p` inherited: refused for a state change | +| `caller.foreign-agent` | `security`, warning | A token used under another agent process than the one that made the call: refused for a state change | +| `caller.token-foreign-use` | `security`, warning | A token used from another shell than the one the agent ran the call in, naming both: refused for a state change | +| `caller.token-unpinned` | `security`, warning | A token whose call's agent process devkit does not know: refused for a state change | +| `caller.token-unexplained-use` | `security`, warning | A `dev` command resolved the token of a tech lead's call that runs no `dev` command, found when that call ends | +| `caller.conflict` | `security`, warning | A token and a lane variable, or a Codex thread, that name different callers: refused for a state change | +| `caller.mismatch` | `security`, warning | A Codex command that ran on another thread than the caller its `dev` command resolved to, found afterwards in the rollout | +| `caller.spoof-suspect` | `security`, warning | A member's command that drops or sets `DEVKIT_CALL` or `CODEX_THREAD_ID` (`unset`, `env -u`, `env -i`, an assignment); the member also gets advice | +| `caller.thread` | `security`, warning | A Codex command without a token that `CODEX_THREAD_ID` named: a read, or a state change that its caller's own open call holds exactly | +| `calls.forged` | `lifecycle`, notice | A token whose call the hook never opened: refused for a state change | +| `calls.token-skipped` | `lifecycle`, notice | A shell call that went out without its token, with the reason; its state changes are then refused | +| `codex.thread-shared` | `change`, info | A member's call carried the root thread's id, so the root thread names the tech lead no more in that session | + +`dev audit --action caller` and `dev audit --action calls` list them. The run's own history keeps the other half: in +`dev progress history`, each step change a token-verified call makes names how devkit knew the caller (`how`) and +the call's id (`tid`). + ## Levels: how much is recorded `audit.level` decides which records are written. A team policy can raise it, never lower it. diff --git a/docs/bug-registry.md b/docs/bug-registry.md index 2815f9f2..dabdab64 100644 --- a/docs/bug-registry.md +++ b/docs/bug-registry.md @@ -530,7 +530,10 @@ scoring code as the client (`lib/devkit/bugs.py`), so the two cannot disagree. history, which goes only with the comment. Each write of a record therefore posts it as a new comment, then deletes the old one, and its history with it. The post comes first, so a run that stops in between leaves two record comments and never none: devkit and the workflow read the newest, and the next write deletes the other. - Each write sends the issue's subscribers a notification, as any new comment does. + Each write sends the issue's subscribers a notification, as any new comment does, so every change of a record + emails them. To get no mail for registry issues you take no part in, watch the repository with **Custom** and + leave **Issues** unchecked. On an issue you opened, or one devkit posted to for you, choose **Unsubscribe** on the + issue's page. - **Labels:** the workflow applies the labels after it validates the issue's first payload, because GitHub drops labels set by people without push access. An issue whose first payload fails validation gets no label, and devkit ignores it. diff --git a/docs/ci-cd.md b/docs/ci-cd.md index 0ac33d39..d4490598 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -380,6 +380,14 @@ session that sends a commit devkit already watches joins that watcher. The resul commit, each once, at its next hook or in its `dev watch --wait`. Each result is recorded once, whichever watch of the commit ends first. +devkit's background watch follows a run for the repository's own limit: the longest chain of jobs that need each +other, at their `timeout-minutes` (GitHub's 360 when a job has none, a local reusable workflow counted by its own +chain), plus 30 minutes for the queue; at least 90, at most 360. `dev ci watch` and `dev ci watch --wait` give up +after `--timeout` minutes (default 90). A GitHub job that has waited 30 minutes for a runner while nothing else of +its commit runs gets one line in the `--wait` stream, with its next action, and a watch that reaches its limit +names it (`CI waits for a runner`). A job that waits for its concurrency group, or for an environment's approval, +is not counted. + A pushed tag gets a watcher only when it can start a run. On GitHub Actions, devkit reads the workflows of the tag's commit as GitHub does: a `release` trigger, or a `push` trigger that takes the tag (no filter, a `tags` or `tags-ignore` filter that lets it through; a `branches` filter alone takes no tag). When none does, no watcher @@ -406,7 +414,7 @@ counts as none, so nothing that stopped early is ever reported as passed: | --- | --- | --- | --- | | `passed` | `0` | `success` | Every run of the commit succeeded | | `failed` | `1` | `failure`, `cancelled`, `timed_out`, `startup_failure`, `action_required`, or a word devkit does not know | A run failed or stopped early; the result carries the diagnosis | -| `timeout` | `3` | still `queued` or `running` | The watch ended first, after `--timeout` minutes (default 90); follow it with `dev ci status --watch`, or re-arm a wait | +| `timeout` | `3` | still `queued` or `running` | The watch ended first, at its limit (see the start of this section); follow it with `dev ci status --watch`, or re-arm a wait | | `none` | `4` | no run, or only `skipped`, `neutral`, or `stale` | Nothing verified the commit: the branch has no CI, its workflows skipped it, or origin is no CI host devkit reads | `dev release` reads the runs of the commit it tags. It refuses when a run failed. While a run is still going, it @@ -431,8 +439,14 @@ one class and gives one next action; when the first error says too little, the e | `lint` | A linter, formatter, or type checker | The same check locally (`dev ci --run`), fix, push once | | `build` | A compile or packaging error | The build command CI runs, fix, `dev ci --run --resume`, push once | | `cancelled` | The run was cancelled or timed out: a newer push, someone cancelled it, or a job ran past its timeout. Never read as a flaky runner | Read where it stopped (`dev run view `); for a timeout, find what hung or ran slow, reproduce it locally, fix, push once; for a newer push, follow that push's run | +| `not_started` | No log: the job never started, and its check run's annotation names why, such as a `runs-on` label no runner has | Fix the cause its annotation names, then rerun once without a new push | +| `budget` (a `not_started` subclass) | An annotation about a spending limit or failed payments: an account limit, not the code | The developer checks billing; do not push again, and rerun once the limit is lifted | +| `workflow_invalid` | GitHub could not start the run (`startup_failure`), so no job ran | `dev ci audit` and actionlint, fix the file, push once | | `unknown` | Anything else | Read the log from the first error (`dev run view --failed`), reproduce, fix, push once | +A cancelled run or leg is never `not_started`: it keeps the class `cancelled`. `dev run view --failed` and +`dev pr checks` read a job that never started the same way, from its annotation, shown as one line. + ### Wait on a run: a watch that wakes the agent devkit's background watch speaks at the session's next hook, and a hook runs only when the session does something. diff --git a/docs/commands.md b/docs/commands.md index bda92541..d557bd63 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -350,11 +350,11 @@ Live progress of long agent work, with active time, a critical-path ETA and a pl | Command | Effect | | --- | --- | | `dev progress start "" [--plan "a=30m; b=1h after a [backend]; c"] [--estimate 2h] [--steps N] [--mode guided\|auto] [--replace --why "…"]` | Starts a run for the current session. While the session's run is live, a second start is refused: finish it with `dev progress done`, or replace it with `--replace --why "…"`, which keeps the reason in the new run. Each plan step can carry an estimate, the steps it waits for, and its kind of work in brackets: an id from `dev crew raci`, which decides the RACI check and the approver ([The crew › Kinds of work](crew.md#kinds-of-work-and-the-raci)); an unknown id is refused. Steps without an estimate share what `--estimate` leaves. `--mode` sets who takes the developer's decisions ([The crew](crew.md#guided-or-automatic)). Prints how long similar runs took here | -| `dev progress step "" --check "" [--step ] [--next "…"] [--force]` | Closes the running step (or the one named) with its evidence, and prints the update, which is the status block with the plan under it, then the exact change made. Refused when the description does not match the step, a crew member still owns it, or its dependencies are open; `--no-check` when there is nothing to verify. The tech lead's step closes done whatever its Check says, `⚠` and `✗` included, and the Check is kept in the step's history (`dev progress history`). A crew member's `--step --check "…"` closes that step at once, by the rules of its end: done with a ✓ Check, otherwise unverified. The member works on, and the line says whether the step closed or why it stays open. A review step stays running and ends with the member's report, done only when the crew gates pass it. A member's `--step` on a step its lane does not hold, on a step still queued for its lane, or on its own step without `--check` exits 2, records nothing, and says what to do | +| `dev progress step "" --check "" [--step ] [--next "…"] [--force]` | Closes the running step (or the one named) with its evidence, and prints the update, which is the status block with the plan under it, then the exact change made. Refused when the description does not match the step, a crew member still owns it, or its dependencies are open; `--no-check` when there is nothing to verify. The tech lead's step closes done whatever its Check says, `⚠` and `✗` included, and the Check is kept in the step's history (`dev progress history`). A crew member's `--step --check "…"` closes that step at once, by the rules of its end: done with a ✓ Check, otherwise unverified. Without `--step`, a member's record closes its lane's only running step; with two or more running it is refused, and with none it prints ⚠ and closes no step. The member works on, and the line shows ✓ only when a step's state changed: it says which step closed, names a step that joined the lane, or says why nothing changed. A review step stays running and ends with the member's report, done only when the crew gates pass it. A member's `--step` on a step its lane does not hold, on a step still queued for its lane, or on its own step without `--check` exits 2, records nothing, and says what to do | | `dev progress step "" --check "" --approves "api, screens"` | The step's Check is also its verdict on the finished steps it names: `✓` approves them, `✗` or `⚠` sends them back. Refused, whole, when a named step is not done, has no kind of work, was done by the same member, or is approved by someone else in the RACI. The tech lead's verdict counts at once. A crew member's is checked at once and counts at the end of its lane, only when the crew gates pass its report without a finding ([The crew › Kinds of work](crew.md#kinds-of-work-and-the-raci)) | | `dev progress note "" [--next "…"] [--step --check ""]` | An update while a step is still running: recorded and printed as the status block (Check `–` the step is still running), and no step changes state. From a crew member, it stays in its lane. `--step` with `--check` keeps partial evidence on a step that is not finished: the step stays as it is, and the crew gates count it as the member's recorded step. A crew member's goes on a step its lane holds; for another step it stays in its lane | | `dev progress add "= [after …] []" [--why "…"]` | Adds a step found during the work; add it when it starts. `[]` declares its kind of work, as in a plan. Each quoted spec is a step (`dev progress add "a=5h [security]" "b=2h [testing]"` adds two), and so is each part between `;`; a step name that still holds an estimate (`a=5h b`) is refused. From a crew member, the step goes to its own lane | -| `dev progress assign --to [--scope ""] [--activity ID] [--why "…"]` | Hands a step to a crew member; its time is that member's, and an edit outside the scope gets advice in the member's context. A working lane of that member that holds no other open step takes it at once, a member resumed with `SendMessage` included, so the lane gets the step's scope and its report closes it. When each working lane of the member holds another open step, the step is queued for those lanes and joins, with its scope, the first one whose step closes; `--to ""` gives it to one lane. `--activity` declares the step's kind of work (an id from `dev crew raci`, such as `backend` or `ux`), so the RACI check and the approver do not depend on the language of the step's name. Refused when the crew's RACI does not make that member Responsible for the step's kind of work, unless `--why` gives the reason, which is recorded | +| `dev progress assign --to [--scope ""] [--activity ID] [--why "…"]` | Hands a step to a crew member; its time is that member's, and an edit outside the scope gets advice in the member's context. A working lane of that member that runs no other step takes it at once, a member resumed with `SendMessage` included, so the lane gets the step's scope and its report closes it. Otherwise the step keeps its assignment and waits: the first lane of the member that frees takes it, oldest assignment first, with its scope; `--to ""` binds it to one lane. `--activity` declares the step's kind of work (an id from `dev crew raci`, such as `backend` or `ux`), so the RACI check and the approver do not depend on the language of the step's name. Refused when the crew's RACI does not make that member Responsible for the step's kind of work, unless `--why` gives the reason, which is recorded | | `dev progress begin ` | Starts a step in parallel with the running one; the tech lead's next `dev progress step` without `--step` closes that step or nothing. Refused for a step that is already done or skipped, with the line that adds your evidence to it (`dev progress note "…" --step "" --check "…"`, or `dev progress confirm` when its dependencies were reopened) and the `dev progress reopen` line that works on it again; refused too while its dependencies are open | | `… --verbose` on `add`, `assign`, `begin`, `reopen`, `skip` and `confirm` | Prints the whole plan after the change. Without it, these commands print the steps the change touched and one line with the run's progress | | `dev progress reopen --why "…"` · `dev progress skip --why "…"` · `dev progress confirm --why "…"` | Undoes a wrong close, skips a step on purpose, or confirms a step whose dependencies were reopened and closed again | @@ -634,7 +634,7 @@ Local CI evidence: proof that what CI runs passed on your Mac, on exactly the fi | `--run` | Runs the `run:` steps of the workflows that run on pushes and pull requests, in order, and records the evidence when all pass. Setup actions, dependency installs, side effects, a hosted runner's own setup (deletions outside the checkout, Docker prunes, setup run with `sudo`, OS package installs, `playwright install`, `git config --global`, Linux-only system setup such as `fc-cache`, `ldconfig`, or `locale-gen`, and `mkdir`, `cp`, `mv`, `ln`, `install`, `touch`, `tee`, or `rsync` writes and shell redirects (`>`, `>>`, `2>`, `&>`) into the home folder outside the checkout, unless the same pipeline runs a check, as `pytest \| tee ~/pytest.log` and `pytest > ~/pytest.log` do; a check that writes into a dotfile such as `~/.bashrc`, through `tee` or a redirect, or that is written as root (`sudo tee`, `sudo dd of=`) into any folder, blocks the evidence instead; a download written as root into a system folder stays setup), and steps that need CI secrets are skipped, each with a line that says why. In a step that sets up a tool and runs it (`brew install gitleaks && gitleaks detect`), only the setup is left out and the check runs, so a tool missing on this Mac fails the evidence. A script run with `source` or `.`, and a command or process substitution, count as checks. A check that cannot be separated from its setup (a nested shell, a subshell, a substitution, a heredoc, a `case`), a check run with `sudo` (including `sudo test`, `sudo [`, and a reporting command with a substitution, such as `sudo echo "$(…)"`), and a step that names a Docker context this Mac lacks block the evidence (see [Git and GitHub › Local CI evidence](git-and-github.md#local-ci-evidence)) | | `--dry-run` | With `--run`: the plan, without running anything | | `--keep-going` | With `--run`: do not stop at the first failure | -| `--step-timeout MIN` | With `--run`: minutes per step (default 30) | +| `--step-timeout MIN` | With `--run`: minutes per step. Default: the step's own `timeout-minutes`, else its job's. Without either, 1.5 × its longest local pass when that is over 30 minutes, else 30. A job with a literal matrix runs once locally, so history may raise its per-leg timeout. Values under 1 are refused | | `--resume` | With `--run`, after a fix: re-runs the failed steps, the steps that never ran, and the passed steps that the changes since can affect; a test step re-runs only its failed and affected tests (the whole step when the change is global). The evidence is recorded as "resumed" (see [Testing › After a CI step fails](testing.md#after-a-ci-step-fails)) | | `--mark-passed [--note "…"]` | Records that you ran the full suite yourself on the current files; the note goes into the PR body | | `--evidence [--json]` | Whether HEAD has evidence, and how it was recorded; exits with `2` when it has none | @@ -681,8 +681,10 @@ branch's pipelines to its context. Follows the CI/CD runs of a branch for one commit (default: the current branch at HEAD) until they finish, on GitHub Actions, GitLab CI, Bitbucket Pipelines, or Azure Pipelines. A failure comes with the failed jobs and steps, the first error of the failed log (GitHub through `gh run view --log-failed`, GitLab through `glab ci trace`; Bitbucket and -Azure give the job, step and link), its class (`test`, `lint`, `build`, `dependencies`, `pipeline`, -`infrastructure`, `cancelled`, `unknown`) and the one next action. The log excerpt is marked as untrusted output and +Azure give the job, step and link), its class (`access`, `test`, `lint`, `build`, `dependencies`, `pipeline`, +`infrastructure`, `cancelled`, `not_started` with its subclass `budget`, `workflow_invalid`, `unknown`) and the one +next action. A GitHub job that never started has no log: the failure names it with its check run's annotation +instead. The log excerpt is marked as untrusted output and has secrets redacted. Exit codes: 0 passed, 1 failed (cancelled and timed out count as failed), 3 still running at the timeout, 4 none (no run appeared within five minutes, or the runs were only skipped, neutral, or stale). @@ -691,8 +693,10 @@ it is given of: `--pr N` (the PR's head, or its merge commit once merged), `--ta `--branch B` as origin has it; by default, what the session last sent to origin. `--pr` and `--tag` work only with `--wait`. It prints one line per finished job, then one line that starts with `CI ·` (passed, failed, cancelled, timed out, skipped, none, or still running with the command to -re-arm it). It retries host errors and ends by itself at `--timeout`. Exit codes: 0 passed, 1 failed, 2 nothing to -watch, 3 the watch ended first (re-arm it), 4 none. Claude Code runs it with the Monitor tool (`--timeout 28`, +re-arm it). It retries host errors and ends by itself at `--timeout`. A job that has waited 30 minutes for a runner +while nothing else of its commit runs gets one line in the `--wait` stream, with its next action; a watch that +reaches its limit names it. Exit codes: 0 passed, 1 failed, 2 nothing to watch, 3 the watch ended first (re-arm +it), 4 none. Claude Code runs it with the Monitor tool (`--timeout 28`, `timeout_ms` 1800000, re-armed on expiry) or as a background command; Codex runs it in the foreground with a timeout. devkit starts it in the background after every `git push`, `dev push`, `gh pr create`, `dev pr create`, @@ -701,6 +705,10 @@ per repository, branch, and commit; on GitHub Actions, a pushed tag only when a on it, through a `push` trigger that takes the tag or a `release` trigger), and the result reaches that session with its next action at its next hook: a crew message to the main agent when it has a progress run, otherwise a note on its next tool call or prompt. That +background watch follows the run for the repository's own limit: the longest chain of jobs that need each other, at +their `timeout-minutes` (GitHub's 360 when a job has none, a local reusable workflow counted by its own chain), plus +30 minutes for the queue; at least 90, at most 360. `dev ci watch` and `dev ci watch --wait` give up after +`--timeout` minutes (default 90). That wakes no idle session, so an agent that waits on the run arms `--wait`; the Stop hook sends back a turn that sent work to origin and leaves its unfinished run with nothing that wakes the agent. Each result is in `~/.local/state/devkit/ci/watch/`, the audit trail (`ci.watch`), and a desktop notification. `DEVKIT_NO_CI_WATCH=1` @@ -1075,7 +1083,7 @@ a fresh fetch, that `origin` has nothing you lack, no WIP or fixup commits, a fi | `dev pr create [--title T] [--base B] [--draft \| --ready] [--fill \| --body-file F \| --edit] [--ci-passed] [--lang L] [--dry-run]` | Opens the PR of the pushed branch with a title in the repository's convention (a Conventional Commit, or a plain imperative sentence where its recent PR titles are sentences; see [Git and GitHub › Create](git-and-github.md#create)) and the body from the PR template, pre-filled with the commits, the local CI result, and the links (`--fill`, the default). Empty "What and why" or "How to verify" sections are refused unless `--draft`. It needs local CI evidence, except for a draft where no workflow runs on draft PRs (`dev pr ready` then asks for it); where one does, the refusal names it. With `delivery.draft_pr` on, the PR opens as a draft unless `--ready`. `--dry-run` prints the title, the template used, the evidence, and the body; `--body-file -` reads standard input | | `dev pr view [n] [--body] [--json]` | One-line state: branches, checks, review, conflicts, size, author, age, address | | `dev pr ls [--all] [--all-projects [--offline]] [--json]` | Your open PRs and those waiting for your review; `--all` adds the others; `--all-projects` covers every project | -| `dev pr checks [n] [--watch [--fail-fast] [--interval S] [--timeout MIN]] [--lines N] [--json]` | Pass, fail, and pending counts; each failing job with its trimmed log (25 lines). Exits with `0` (passed), `1` (failed), or `8` (pending). When every check was skipped (a draft's run skips the jobs with the draft gate), it reports no checks yet and exits with `8`, never passed. `--watch` waits and prints only the result; it also waits up to two minutes for the real run after `dev pr ready` | +| `dev pr checks [n] [--watch [--fail-fast] [--interval S] [--timeout MIN]] [--lines N] [--json]` | Pass, fail, and pending counts; each failing job with its trimmed log (25 lines), or, for a job that never started, its check run's annotation and the next action. Exits with `0` (passed), `1` (failed), or `8` (pending). When every check was skipped (a draft's run skips the jobs with the draft gate), it reports no checks yet and exits with `8`, never passed. `--watch` waits and prints only the result; it also waits up to two minutes for the real run after `dev pr ready` | | `dev pr merge [n] [--squash \| --merge \| --rebase] [--auto] [--keep-branch] [--dry-run]` | Merges when the checks passed and the reviews allow it, with the repository's method (checks that were all skipped have not passed: it waits for the real run); a squash commit gets the PR title and its "What and why"; then deletes the remote branch and, when the merge test finds it merged, the local branch with its clean worktree (or switches to the default branch and updates it), and marks the open work items linked to the merged branch as done (`merged in PR # ()` in their changelog; the output names them). `--auto` lets GitHub merge once the checks and reviews the base branch requires pass, which can be before every job ends, and closes no item until then. With checks still running, `--auto` is allowed only when GitHub's merge state is `BLOCKED` (something on GitHub holds the merge until they pass); otherwise it is refused, because GitHub could merge before they end. A repository that does not allow auto-merge is refused too. A PR that can merge now (its checks passed and nothing on GitHub holds it) gets a plain merge, with its cleanup. After `gh` returns, devkit reads the PR again: merged, it does the cleanup; waiting, it says so; neither, it exits with `1` | | `dev pr ready [n] [--ci-passed] [--lang L]` | Marks a draft ready after checking its title and required sections. Marking ready starts the one CI run, so it needs local CI evidence for the PR's head, for any PR. For the current branch's PR, the head must be your HEAD, and `--ci-passed` can attest the evidence. For another branch's PR, the head must be in this checkout and have its own evidence (`git switch `, `dev ci --run`); `--ci-passed` does not count for it | | `dev pr comment [n] -m "…" \| --body-file F` | Comments on a PR | @@ -1087,7 +1095,7 @@ a fresh fetch, that `origin` has nothing you lack, no WIP or fixup commits, a fi | Command | Effect | | --- | --- | | `dev run ls [--branch B \| --all-branches] [--limit N] [--json]` | Recent CI runs of the branch on any host (default 8) | -| `dev run view [id] [--failed] [--lines N] [--json]` | A run's failing jobs and their failing step (default: the branch's latest run); `--failed` adds the trimmed logs (30 lines). Exits with `1` when a job failed | +| `dev run view [id] [--failed] [--lines N] [--json]` | A run's failing jobs and their failing step (default: the branch's latest run); `--failed` adds the trimmed logs (30 lines). A job that never started has no log: it is named with its check run's annotation and the next action, and a run GitHub could not start (`startup_failure`) is named `workflow_invalid`. Exits with `1` when a job failed or the run could not start | | `dev run rerun --flaky "test and evidence" [--all-jobs]` | Re-runs the failed jobs of a run, only with a reason for a proven flaky test, which is recorded in `~/.local/state/devkit/flaky.jsonl` and the project's session log | ### `dev release [V | --version V] [--notes-file F] [--ci-passed] [--sign] [--draft] [--prerelease] [--dry-run] [--why REASON]` diff --git a/docs/crew.md b/docs/crew.md index f73c05a7..a742af5d 100644 --- a/docs/crew.md +++ b/docs/crew.md @@ -162,8 +162,8 @@ short version: A member starts cold and uses a full context of its own, so parallel work costs more tokens: it pays when it saves real time on independent work, and it is waste on small or coupled tasks. Follow-ups go to the same member (Claude `SendMessage`, Codex `send_input`), which keeps its context. Assign the follow-up's step to that member first -(`dev progress assign --to `): its lane takes the step with its scope as soon as it holds no other -open step, so the member's `dev progress step --step` can close it. A step nobody assigned stays the tech lead's. +(`dev progress assign --to `): its lane takes the step with its scope as soon as it runs no other +step, so the member's `dev progress step` can close it. A step nobody assigned stays the tech lead's. ## Kinds of work and the RACI @@ -262,52 +262,66 @@ that launch alone, so two members launched together never swap lanes: - **The step it names.** A bound lane takes the ready step its launch's description names, never just the member's first step. `dev progress assign` gives a step to the member's working lane at once when that lane's launch names - the step or the lane holds no other open step. Before a Claude Code launch starts, the pre-tool hook checks its + the step or the lane runs no other step. Before a Claude Code launch starts, the pre-tool hook checks its description the same way: when it names none of the member's steps and one waits for its launch, the hook puts that step's name in the description and tells the tech lead; when two or more wait or it names two or more equally, - the tech lead gets the exact description that takes each. Codex launches pick their step by `task_name` and are - not changed. -- **The steps queued for it.** When every working lane of the member holds another open step, the step is queued - for those lanes: once a lane's open step closes, that lane takes the first queued step whose dependencies are done, - the step's scope becomes the lane's, and the member is told. When the tech lead gives a queued step to another - member, each lane it was queued for gets a notice that names the step and its new owner. With two or more lanes, the first lane whose step - closes takes it; the tech lead's notice gives the `dev progress assign "" --to ""` line - that gives it to one lane instead. Queued steps join one at a time, in the order they were assigned. When the lanes - end or are resumed first, the step waits for a launch of its own, and the tech lead is told why. Reopening a step - while its member works gives it back to that member's lanes the same way. -- **The steps its evidence is about.** A member's `dev progress step "…" --step "" --check "…"` on a step its - lane holds ends that step at once, by the rules of the member's end (done only with a Check that starts with ✓, - such as `--check "✓ 12 tests pass"`; unverified with ⚠, ✗, –, or words alone), - and the next steps start while the member works on; the command's line says the step closed, or why it stays open, - and a step that closed unverified gets a ⚠ line with how to mark its Check. + the tech lead gets the exact description that takes each. A follow-up launch that names one of the member's steps + that is already done is left unchanged and takes no step. Codex launches pick their step by `task_name` and are + not changed; a `task_name` that names a done step takes none. +- **The steps given to it.** A pending step keeps its assignment on the step itself, so a lane that ends, stops, or + resumes never drops it. `dev progress assign` with a launch description (`--to ""`) binds the + step to that lane; with a role (`--to Tank`), any lane of the member may take it. A lane that runs no step takes, + in order: the step its launch names, an answered blocked step, the steps bound to that lane, then the steps given + to its member, each oldest first and once its dependencies are done. The step's scope becomes the lane's, and the + member is told (`“” is your step now`) at its next hook or in its `dev watch --wait`. A new launch takes a + step bound to an older lane once that lane has ended. When the member works in two or more lanes, the first lane + that frees takes a step given to the member, and the tech lead's notice gives the + `dev progress assign "" --to ""` line that gives it to one lane instead. When the tech + lead gives a waiting step to another member, each lane it was bound to gets a notice that names the step and its + new owner. Reopening a step while its member works gives it back to that member the same way. +- **The steps its evidence is about.** A member's `dev progress step "…" --check "…"` without `--step` closes its + lane's only running step. With two or more running, it is refused and records nothing + (`say which with --step`); with none, it records the evidence in the lane and prints ⚠ (`it closes no step`). + With `--step ""`, it closes that step of its lane. Either way the step ends at once, by the rules of the member's end (done only with a Check + that starts with ✓, such as `--check "✓ 12 tests pass"`; unverified with ⚠, ✗, –, or words alone), and the next + steps start while the member works on. The command's line shows ✓ only when a step's state changed: it says which + step closed, names a step that joined the lane (`“” is your step now`), or says why nothing changed, and a + step that closed unverified gets a ⚠ line with how to mark its Check. A review step is the exception: it stays running and ends with the member's report, done only when the crew gates pass it, so a reviewer's lane may hold more than one review step at once: a review assigned to a reviewer who holds only reviews joins its lane at once, one launch that names more than one review binds them all, and the report ends every review the lane holds. On Claude Code, the member's close is refused, with nothing recorded, while a background command it started has not ended: the refusal names the commands, so the member runs it again once they end (their - task notification) or stops the ones that are not the step's work with TaskStop. A `--step` the lane cannot close exits 2, records nothing, and says what to do: for a step that is not its - own, ask the tech lead to assign it; for a queued step, close the step ahead of it or wait for its dependencies; - for its own step, add `--check`. + task notification) or stops the ones that are not the step's work with TaskStop. A `--step` the lane cannot close + exits 2, records nothing, and says what to do: for a step that is not its own, ask the tech lead to assign it; for + a step that waits for the lane, close the step ahead of it or wait for its dependencies; for its own step, add + `--check`. `dev progress note "…" --step "" --check "…"` keeps partial evidence on the step (its last five) and leaves it open: use it for a long or paused step. When a lane ends, it closes the step its launch names, a step it named with - `--step`, and a step its report names. Any other step it held goes back to pending, still its member's, with the - reason in the step's history. A step delegated into a working lane closes only on that lane's own evidence. + `--step`, and a step its report names. Any other step it held goes back to pending, still its member's, for the + member's next lane, with the reason in the step's history. A step delegated into a working lane closes only on that + lane's own evidence. +- **A blocked step frees its lane.** While a step waits for a decision (one asked in guided mode, or one that + approves steps), it keeps its member but holds neither the lane nor its files: the member takes its next step, with + that step's files. When the decision is answered, the blocked step runs again in that lane, or goes first in the + lane's queue while the lane runs another step, or goes to the member's next lane if that lane ended. - **A launch that failed** (an unknown agent type, an interrupt) starts no agent, so its record goes at once: it never labels another agent or holds a slot. -- **A resumed agent** keeps its own lane and takes no other member's step or label. When it holds no open step, it - takes the one step assigned to its member that waits for a launch (never a step queued for another lane), unless a - new launch of its member is on its way for it; with two or more waiting, `dev progress assign` picks. It takes a crew slot like a launch: while none - is free, it may read but not write, and the tech lead is told once (`crew.queued`); it takes its slot at its - first tool call after one frees. -- **A lane whose files went to another lane.** When a step and its scope go to another lane, a lane that holds no - open step and kept an overlapping scope may read but not write until the tech lead assigns it a step - (`crew.scope-handed`), so two lanes never write the same files. +- **A resumed agent** keeps its own lane and takes no other member's step or label. When it runs no step, it takes + its next step in the same order as any free lane, a step given to its member by role included, unless a new + launch of its member is on its way: that launch takes the member's steps. It writes the files of the step it takes. + It takes a crew slot like a launch: while none is free, it may read but not write, and the tech lead is told once + (`crew.queued`); it takes its slot at its first tool call after one frees. +- **Files follow the running steps.** A lane's write scope is the union of the scopes of the steps it runs. A done, + skipped, blocked, or unverified step gives its lane no files, so when a step and its files go to another lane, the + first lane keeps none of them, and two lanes never write the same files. A lane that runs no step has no scope: an + edit it makes gets the advice of a write outside its files. - **A launch whose record was lost** gets a restricted lane: read-only, no step, no scope, no slot, recorded as `crew.unbound`, until the tech lead assigns it a step. - **A stopped or silent member.** TaskStop fires no SubagentStop, so the PostToolUse hook ends the lane of an agent TaskStop stopped; devkit does the same when a member's transcript ends with its interruption. The lane ends - `stopped`, and its open steps go back to pending for a new launch. A lane that stops reporting is `lost`, and its - steps go back to pending too. + `stopped`, and its running steps go back to pending, still its member's, for the member's next lane. A lane that + stops reporting is `lost`, and its steps go back to pending the same way. - **A report that meets a busy hook.** When SubagentStop finds the run locked by another hook, it saves the stop and applies it at the next hook, so no report is dropped (`crew.stop-deferred` in the audit trail). @@ -323,6 +337,7 @@ scope check, `dev crew owner`, and the overlap check of `assign` all match it th | `*`, `?`, `[…]` | Characters inside one folder name or filename, never across `/`: `src/pkg/*.py` holds `src/pkg/a.py`, not `src/pkg/studio/host.py` | | `**` | Any number of folders: `src/**` holds everything under `src/` | | A folder, or a glob that matches one | Everything under that folder | +| A name with no wildcard, such as `docs/crew.md` | That file only, when the checkout has a file there or, with nothing there yet, when the name has a suffix; otherwise a folder, and everything under it | | `*.md` | Markdown files at the repository's root only; write `**/*.md` for every Markdown file | - A relative glob never holds a path outside its repository, such as the handoff plans or the tech lead's @@ -334,8 +349,9 @@ scope check, `dev crew owner`, and the overlap check of `assign` all match it th A new file is judged by its nearest existing folder, and the advice names where the write would land. - A scope that names a whole checkout (`/**`) becomes that checkout's top-level entries. - Two scopes overlap only when one path matches both, compared without case, so two members can split one folder: - `src/pkg/*.py` for one and `src/pkg/studio/host.py` for the other. Scopes given in two different checkouts never - overlap; a scope relative to the repository overlaps a matching one in any checkout. + `src/pkg/*.py` for one and `src/pkg/studio/host.py` for the other. A filename overlaps only a glob that can match + it: `docs/crew.md` and `docs/**/bug*.md` do not overlap, while `docs/` and `docs/crew.md` do. Scopes given in two + different checkouts never overlap; a scope relative to the repository overlaps a matching one in any checkout. ### Slots @@ -385,8 +401,9 @@ lane, so a subagent can never advance the main plan by mistake. From a lane, `de reads with `&&`, `||`, `;`, or a newline and pipes it into a read-only filter (`| tail -5`), with no `$(…)`, subshell, loop, or redirect into a file. -A lane call devkit cannot place runs as the main session's, and the hook adds advice to run it alone, as a command of -its own. When such a call closed the main plan's step by mistake, `dev progress reopen` repairs it. +A lane call the router cannot place still acts as the member when its call carries the call token (below); without +the token, a command that changes state is refused. Either way the hook adds advice to run the call alone, as a +command of its own. Quoted text, such as a plan with `;` between its steps, a commit message that mentions a command, or a message passed from a quoted heredoc, is fine on both. Read-only crew commands run @@ -395,28 +412,71 @@ anywhere, alone or in a compound command: `dev crew` with no subcommand, `graph` (`dev crew set`, `raci --set`, `brief`) and `dev crew sync` are the tech lead's; a member that needs one asks the tech lead. -**The tech lead's commands must come from the main session.** The PreToolUse hook records every shell call with the -agent that made it, from the hook's own input (the call ledger, in devkit's state, closed when the call ends). A `dev` -command then looks for the open calls that hold its own arguments: it acts as the tech lead only when every such call -is the main session's, and as a member when any is a member's. No environment variable, parent process, or recent -activity can make a caller the tech lead. When the open calls of two or more members hold the same command and no -lane mark says which one calls, a command that acts in a member's lane acts as none of them: it is refused, names -each member, and asks for the command again as a command of its own, in the caller's lane. +**Each call carries a token that names its caller.** The PreToolUse hook records every shell call with the agent +that made it, from the hook's own input (the call ledger, in devkit's state, closed when the call ends), and puts +`DEVKIT_CALL=.` in front of the call. The token holds only for the shell the agent ran the call in, +and its child processes, and only while the call is open. A `dev` command reads its caller from the token once, when +it starts: a main-session call names the tech lead, and a member's call names that member, whatever other calls are +open or waiting at the same time. These work for the tech lead and for members alike: + +- the tech lead's `dev progress begin` or `dev progress assign` while a member waits in `dev watch --wait` or runs a + long call; +- one `dev` command inside another: + `dev crew ack M3 --sha256 "$(dev crew read M3 --json | jq -r .digest)" --generation 1`; +- a script run by path from the call's own shell. + +devkit keeps only a hash of the token, and removes the token's value from every command text it records. Each step +change a token-verified call makes names, in `dev progress history`, how devkit knew the caller (`how`, such as +`token`) and the call's id (`tid`). + +| Agent and mode | Which calls carry the token | Its form | +| --- | --- | --- | +| Claude Code in `bypassPermissions` mode, and Codex with approval policy `never`, in sh, bash, or zsh | Every shell call of the main session and of each member | devkit's prefix, ending in `export DEVKIT_CALL=; readonly DEVKIT_CALL;` | +| Claude Code in another permission mode, and other shells, such as fish | Only a call that visibly runs one plain `dev` command | `DEVKIT_CALL= dev …` | +| Codex with an approval policy that asks | Only a plain `dev progress`, `dev crew`, `dev watch`, or `dev session` call, which devkit rewrites anyway | `DEVKIT_CALL= dev …` | + +Outside bypass mode on Claude Code, or a never-asks approval policy on Codex, only calls that visibly run `dev` carry +the token, so you get no more permission prompts than before. Never add an allow rule for `export` (such as +`Bash(export:*)`): it would allow any command that starts with an export. + +**A state change devkit cannot verify is refused.** It is never taken as the tech lead's. The commands that change +a run, a session's records, the crew's records, work items, or plans need a caller the token verifies; reads and +waits, such as `dev crew read`, `dev crew inbox`, and `dev watch`, do not. devkit refuses the change, says why, and +records it in the audit trail when: + +- the call carries no token in a session whose calls carry one (`caller.no-token`): run it again as a command of its + own, in the foreground; +- the token's call has closed, or ran past its time limit (`caller.stale-token`). A background command's identity + ends when it starts: run it in the foreground; +- the token belongs to another session or agent, or another shell uses it (`caller.foreign-session`, + `caller.foreign-agent`, `caller.token-foreign-use`): run it in your own call; +- the token and the lane variable, or the Codex thread, name different callers (`caller.conflict`). + +These commands need the tech lead, so a member's call is refused for them: + +- `dev progress start` and `start --replace` in the main session, and `assign`, `begin`, `reopen`, `skip`, `confirm`, + and `done`; +- `dev crew route --plan --apply`, `decide`, `withdraw`, and `mode`. + +**On Codex.** Where devkit stamps every call (approval policy `never`, which `dev setup` writes), the token decides +and `CODEX_THREAD_ID` decides no state change. Where Codex asks, a plain `dev progress`, `dev crew`, `dev watch`, or +`dev session` call still carries the token. For any other call, the thread names a member, or the tech lead for +the session's root thread, only while that caller's own open call is exactly that `dev` command, typed alone; a +compound state change is refused with the fix: run it as one plain `dev` command. The root thread names the tech lead only after a member's verified call showed +that Codex gives members thread ids of their own. Any crew member can turn the root-thread mapping off for the rest of +the session with one call that carries the root's thread id: devkit records it as `codex.thread-shared`, and the tech +lead then runs plain `dev` commands. Reads and waits keep working either way. A session whose hook has never stamped a +token, such as one an older devkit started, keeps the earlier rules: there, a Codex tech lead's commands are allowed +and recorded as `caller.unverified`. Claude Code gives a running conversation a new session id after a compaction. Every hook registration records the agent's process, so the new id takes that process over from the older record, and the older session's open run moves to the new id with its working lanes (`session.adopt`). A `dev` command picks, among its process's sessions, the one whose call ledger holds its open call. When none does, it takes the one session of the same repository from the last 12 hours that holds the call and that no live process holds: the conversation before its new id -registered. These commands need the tech lead: +registered. -- `dev progress start` and `start --replace` in the main session, and `assign`, `begin`, `reopen`, `skip`, `confirm`, - and `done`; -- `dev crew route --plan --apply`, `decide`, `withdraw`, and `mode`. - -Type them yourself. Run through a script, `bash -c`, or another program, no open call holds them as typed, so devkit -refuses them and says how to run them (`caller.refused` in the audit trail). On Codex, devkit cannot verify the caller -yet: these calls are allowed and recorded as `caller.unverified`. +[The audit trail › Caller identity records](audit.md#caller-identity-records) lists every record these checks write. ### Helpers @@ -580,6 +640,11 @@ each check that fails, naming every missing item and the command that fixes it: | Lessons | Two or more refusals answered with a lesson that was recorded or counted: a `dev lesson add` or `dev lesson recur` whose output shows the lesson's id with its check mark (a refused add or a recur of no lesson does not count, whatever its exit code), or a vote on the bug a refusal's marker names. A refusal the [bug registry](bug-registry.md) served a workaround for in the session, or one an open lesson of the project, its initiatives, or the global scope covers, owes nothing | | Background work | Every started command has ended; native completion or a correlated terminal output must establish its result before it can support verification | +The crew gates judge every stop. A member is sent back once per lane life (its launch, or a resume), and its next +stop is judged again: a clean report with Check ✓ passes, so a review it finishes ends done. A stop let through with +findings approves nothing; it is audited as `crew.gate` let through, and its findings reach the tech lead in one +notice. On Codex, the gates read a member's executed command without devkit's own stamps in front of it. + A completed failed check can support an honest failure report, but cannot approve the work. A positive verdict requires successful execution evidence. `dev test plan`, help output, `dev ci --run --dry-run`, and `dev ci --run --evidence` inspect or describe checks; they do not prove that checks ran. An explicit project override @@ -630,8 +695,10 @@ audit trail). Keeping the step open while gate findings remain is planned. **Review steps start on unverified work.** A step whose dependencies ended unverified waits, except a review step (its kind of work is review, or its member works review-only): it starts, and its Check ✓ ends done the steps it -follows that its member approves, once the crew gates pass the member's report. The run cannot end while a step is -unverified or an approval is owed. +follows that its member approves, once the crew gates pass the member's report. A review recorded with ✗ (changes +requested) lets the step after it start, such as the fix; the reviewed work stays unapproved. When a lane ends, one +notice tells the tech lead which of its member's reviews and verdicts did not count, because the crew gates did not +pass its report. The run cannot end while a step is unverified or an approval is owed. `dev canary` and `dev doctor` count the crew's reports apart from the main sessions' (`crew 12/13`), so you can always see that the kit's rules still hold inside every agent. On Codex, devkit records a launch when its agent starts, and @@ -736,12 +803,14 @@ How a decision travels: main-only operations still go to the tech lead. An automatic decision never claims you gave the answer, and you can replace it later with `dev crew decide`. A decision asked with `--approves` is never automatic: only your answer approves a step, so it waits for you as in guided mode, and `dev crew ask` says so. -3. **Guided, and a decision that approves steps in either mode:** the member's step is blocked, the member stops and reports that it waits for D3, and no tokens are - spent while it waits. The tech lead sees the decision with his next action and asks you with Claude Code's +3. **Guided, and a decision that approves steps in either mode:** the member's step is blocked and frees its lane + (see [Lanes and time](#lanes-and-time)). When the member has another step, its lane takes that step and its files + at once, and the member may work on it; otherwise the member stops and reports that it waits for D3, so no tokens + are spent while it waits. The tech lead sees the decision with his next action and asks you with Claude Code's question dialog (see [How the tech lead asks you](#how-the-tech-lead-asks-you)). Your answer is recorded with `dev crew decide`, and the tech lead resumes the member with it; the member keeps everything it knew. Recording - the answer never brings back a member that ended or went stale: the step it blocked goes back to pending with - its scope, ready to launch, and the answer waits for the member's next launch. + the answer never brings back a member that ended or went stale: the step it blocked goes first to the member's + next lane, a resume or a new launch, and the answer waits for it there. 4. The run cannot be closed while a decision waits for you. In auto, the tech lead's final report lists the automatic decisions, which `dev crew decisions` marks `auto · review`. @@ -751,7 +820,7 @@ A decision belongs to its run, and only an open one needs you: answer. The decision stays pending but is moot: it shows on a quiet line under its run, never under **Needs you**, and it does not stop `dev progress done`. Your answer to it still counts if you give one. - **Withdrawn.** `dev crew withdraw --why "…"` closes a pending decision that no longer applies. Only the tech - lead runs it. It frees the step blocked on the decision, which goes back to pending, ready to launch, when the + lead runs it. It frees the step blocked on the decision, which goes first to the member's next lane when the member that asked ended or went stale. It tells the asking member when it still works, or their next launch when the step waits for one, and records the reason in the run's history and the audit trail (`crew.withdrawn`). It is never your answer. @@ -791,7 +860,7 @@ guardrails are devkit's own commands and records, and advice in a member's conte | Guardrail | What happens | | --- | --- | | Limited parallel members | a launch that does not fit its session's crew [slots](#slots) gets advice with who is working: `progress.max_parallel` (4 by default) per session, lowered by your account's usage in every session, a slot kept for your own request, review and read-only members at half a slot, and resumed agents and helpers counted (`E-parallel`, `E-resumed`) | -| Separate files for parallel members | `assign` refuses a scope that overlaps a working member's scope (`E-separate-files`) | +| Separate files for parallel members | `assign` refuses a scope that overlaps the scope of a working member's running steps (`E-separate-files`) | | A member stays in its scope | an edit outside the files it was assigned gets advice in the member's context (`E-scope`); a review-only or read-only member's shell writes are detected and counted for it, while a builder's shell is not checked against its scope (`E-shell-scope`) | | The main session respects a member's files | an edit by the main session inside a working member's scope gets advice that names the member (`E-main-scope`) | | An ended or stale member | holds no file and no slot in any session's run and is not counted as working: `dev progress`, the Crew line, `dev crew next`, the continuity brief, and the dashboard read each lane as `dev crew owner ` does, and the scheduled sweep closes its lane with the reason; `dev crew delegate` and `dev progress assign` give it no new step (`E-owner`) | @@ -801,9 +870,9 @@ guardrails are devkit's own commands and records, and advice in a member's conte | Every kind of work has an approver | the run ends only after each Accountable member approved (`E-approvals`), with an explicit verdict given after the work (`E-verdict`), and nobody approves their own kind of work (`E-no-self-approval`) | | Steps change only with evidence | closing a step needs `--check`, and a member's step ends done only on its evidence, otherwise unverified (`E-evidence`); a step whose dependencies are open is refused, except a review step after unverified work (`E-deps`); a finished step whose dependency was reopened is rechecked before the run ends: it clears when it finishes again after that dependency, or with `dev progress confirm --why "…"` (`E-recheck`); keeping a step open while gate findings remain is planned (`E-gate-findings`) | | Mistakes are fixable and visible | `dev progress reopen` or `dev progress skip` with `--why`, and `dev progress add`; every change is in `dev progress history` (`E-fixable`) | -| A member that never reports back | after `progress.stale_agent_hours` (6) its lane is closed as lost and its step goes back to the main session (`E-lost-lane`) | +| A member that never reports back | after `progress.stale_agent_hours` (6) its lane is closed as lost and its step goes back to pending, for its member's next lane (`E-lost-lane`) | | Every report is checked | the status block, the step's record, and the crew gates at SubagentStop (`E-status-block`, `E-step-records`, `E-proofs`, `E-skills`, `E-stubs`, `E-tests-fail`, `E-lessons`, `E-background`) | -| Only the tech lead plans, assigns, and decides | from a lane, `assign`, `begin`, `reopen`, `skip`, `confirm`, `done`, `decide`, `withdraw`, and `mode` are refused, and in the main session they must be typed as commands, not run by a script (`E-main-only`, `E-caller`) | +| Only the tech lead plans, assigns, and decides | from a lane, `assign`, `begin`, `reopen`, `skip`, `confirm`, `done`, `decide`, `withdraw`, and `mode` are refused, and in the main session they need a call its token verifies: a script run by path from the call's own shell counts, a background command does not (`E-main-only`, `E-caller`) | | Decisions | guided waits for your decisions; auto records the recommended option and goes on (`E-decisions`) | ## Everything is recorded @@ -818,7 +887,7 @@ dashboard and the handoff read, and devkit's audit trail (`dev audit`), publishe | `crew.stop-deferred` | a member's stop met a busy hook and is applied at the next one | | `crew.bind`, `crew.resume`, `crew.launch-failed`, `crew.unbound` | a lane binds to its launch, a member resumes, a launch fails, or a lane runs restricted because its launch record was lost | | `crew.limit`, `crew.reserve` | the effective slot limit changes, or a launch takes the slot kept for your request | -| `crew.queued`, `crew.scope-handed` | a resumed member waits for a slot, or a lane loses its scope to the lane that took its files | +| `crew.claim`, `crew.queued` | a free lane takes a step given to it or to its member, or a resumed member waits for a slot (records written before 26.11.27 can also hold `crew.scope-handed`, a lane that lost its scope to the lane that took its files) | | `session.adopt` | a session's open run moves to the new id Claude Code gave the conversation | | `crew.message` | a question or answer between members | | `crew.decision`, `crew.decided`, `crew.mode` | a decision point, its answer (and by whom), a change of mode | @@ -829,7 +898,8 @@ dashboard and the handoff read, and devkit's audit trail (`dev audit`), publishe | `scope.write` | a file a read-only member's shell call changed, counted for whoever's own edit call touched it during that call, otherwise flagged for the read-only member | | `crew.delegate`, `crew.decline` | work handed to another member, or handed back | | `raci.override` | a step assigned to a member the RACI does not make Responsible, with the reason | -| `caller.refused`, `caller.unverified` | a tech lead's command refused because it did not come from the main session, or allowed on Codex without verification | +| `caller.refused`, `caller.unverified` | a tech lead's command refused because its caller is not the main session, or allowed without verification in a Codex session whose hook never stamped a call token | +| `caller.*`, `calls.*`, `codex.thread-shared` | a call token that failed a check, a state change without one, or a Codex thread fact (see [The audit trail › Caller identity records](audit.md#caller-identity-records)) | | `canary.crew-miss`, `crew.unreported`, `crew.gate` | a member's report without its status block, a member that stopped without `dev progress step`, or a crew gate finding | | `stop.block`, `canary.crew-roles` | a final message sent back for more work, with the rule, or a member's report that names crew members without their role | | `canary.remind` | a presentation rule a final message missed (`roles` for names without their role), never a send-back of its own: recorded when your next development prompt reminds it, blocked when it joined a send-back for other work (`dev canary` lists it as added to a send-back) | diff --git a/docs/git-and-github.md b/docs/git-and-github.md index b13007f4..7620bf27 100644 --- a/docs/git-and-github.md +++ b/docs/git-and-github.md @@ -323,7 +323,10 @@ dev ci --mark-passed --note "./mvnw -B verify: 214 tests passed" # you ran the `dev ci --run` reads the GitHub Actions workflows that run on pushes and pull requests and runs their `run:` steps in order, with `bash -eo pipefail`, `CI=true`, and the step's environment, stopping at the first failure (`--keep-going` -runs on). Each step has 30 minutes (`--step-timeout`), and its log is kept in +runs on). Each step may run as long as its workflow allows: its own `timeout-minutes`, else its job's. Without one, +it gets 1.5 times its longest local pass when that is over 30 minutes, else 30. `--step-timeout` sets one limit for +every step. A step past its limit ends with exit 124, prints the limit and where it came from, and names +`dev ci --run --resume --step-timeout `. Each step's log is kept in `~/.local/state/devkit/ci/logs//`. When macOS has only `python3`, a `python` shim stands in for what `setup-python` provides on the runner. @@ -482,7 +485,10 @@ dev run rerun 4711 --flaky "PaymentIT times out on the runner; passed 5 times lo `dev run ls` reads GitHub, GitLab, Bitbucket, and Azure like [`dev ci status`](commands.md#dev-ci-status---watch---branch-name----all-branches---all-jobs---limit-n---json); -`dev run view` and `dev run rerun` work on GitHub. Re-running a failure without a change repeats it and costs a full +`dev run view` and `dev run rerun` work on GitHub. A job that never started has no log, so `dev run view --failed` +names it with its check run's annotation and the next action; an account limit gets the class `budget`, which no +push fixes. A run GitHub could not start is `workflow_invalid`: run `dev ci audit` and actionlint, fix the file, and +push once. Re-running a failure without a change repeats it and costs a full CI cycle, so `dev run rerun` needs `--flaky` with the test and the evidence. devkit records it in `~/.local/state/devkit/flaky.jsonl` and in the project's session log in the handoff repository, then re-runs the failed jobs (`--all-jobs` for all of them). diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 02dc5b8d..243e4172 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -371,6 +371,8 @@ A step closes only with its evidence, and only the step that evidence is about. | `step "" belongs to , still working on it` | It closes when the member finishes; use `--force` only when it is really done | | `step "" is already done` | `dev progress reopen "" --why "…"` | | `only the tech lead …` | A crew member asked to `assign`, `begin`, `reopen`, `skip`, or `confirm`: ask the tech lead with `dev crew ask` | +| `your lane runs several steps (…): say which with --step` | A crew member's record without `--step` while its lane runs two or more steps: name the step with `--step ""` | +| `⚠ … recorded in your lane; it closes no step` | Not a refusal: the member's lane runs no step, so the evidence closed nothing. Ask the tech lead to assign the step (`dev crew ask`) | Every change, including a forced one, is in `dev progress history`. @@ -385,6 +387,27 @@ A run ends only when it matches what happened (see [Work states › Runs](work-s | An approval is owed, or `To recheck: "" used "", reopened since` | Get the approval, or reopen and redo the flagged step, or confirm that its work still holds: `dev progress confirm "" --why "…"`. `dev progress done "" --why "…"` ends the run anyway and records the reason | | `decisions still waiting for the developer: D (…)` | Ask them, or withdraw one that no longer applies: `dev crew withdraw --why "…"`. A moot decision never blocks the end, and every decision still pending closes with the run | +### A `dev` command says devkit could not verify its caller + +devkit names who runs a command that changes state by the call token the pre-tool hook puts in front of the call +(see [The crew › Who is calling](crew.md#who-is-calling)). When the token cannot name the caller, devkit refuses the +change instead of taking it as the tech lead's, and records why: + +| Message | Fix | +| --- | --- | +| `devkit could not verify this call's identity (it carries no call token): run it again as a command of its own` | The command ran without the token, such as inside a program that gives its processes an environment of its own. Run it again, alone, in the foreground | +| `this call's identity has ended (its call closed, or ran past its time limit); a background command's identity ends when it starts: run it in the foreground` | Run the command in the foreground, not with `&`, `nohup`, or as a background call | +| `this call's token belongs to another session or agent, so it names nobody here: run it again in your own call` | A nested agent (`codex exec`, `claude -p`) or another session inherited the token. Run the command in that agent's own call | +| `this call's token is in use by another shell, so it names nobody: run it again in your own call` | Another shell than the one the agent ran the call in used the token. Run the command in your own call | +| `devkit could not verify which Codex thread runs this: run it as one plain dev command (no pipeline, script or other command around it)` | Codex asks before it runs commands, so the compound command carried no token. Run the `dev` command alone | +| `this call's token and its lane variable or thread name different callers` | The command sets `DEVKIT_FROM_AGENT` or `CODEX_THREAD_ID` to another caller. Run it without setting them | + +Reads and waits, such as `dev crew read` and `dev watch --wait`, are not refused. `dev audit --action caller` lists +the records ([The audit trail › Caller identity records](audit.md#caller-identity-records)). Outside Claude Code's +bypass mode, or a Codex approval policy other than `never`, only a call that visibly runs `dev` carries the token: do +not add an allow rule for `export` to get one on every call, since it would allow any command that starts with an +export. + ### Codex profile models are not available `dev doctor` reports "profile models available" failing when your account does not offer a profile's model. List the @@ -572,7 +595,13 @@ differently. | Result | What it means | Fix | | --- | --- | --- | | `none` (exit `4`): no run verified this commit | No run appeared within 5 minutes (the branch has no CI for this event, or the host was unreachable, which the message adds), or every run was `skipped`, `neutral`, or `stale` | Check the triggers with `dev ci` or `dev ci audit`, and the sign-in with `dev ci status` | -| `timeout` (exit `3`): still running after the watch limit | The run takes longer than `--timeout` (default 90 minutes) | Follow it with `dev ci status --watch`; if it hangs, `dev ci audit` reports jobs without a timeout | +| `timeout` (exit `3`): still running after the watch limit | The run takes longer than the watch's limit: `--timeout` for `dev ci watch` and `dev ci watch --wait` (default 90 minutes), or, for devkit's background watch, the longest chain of jobs that need each other, at their `timeout-minutes` (GitHub's 360 when a job has none, a local reusable workflow counted by its own chain), plus 30 minutes for the queue; at least 90, at most 360 | Follow it with `dev ci status --watch`; if it hangs, `dev ci audit` reports jobs without a timeout | +| `timeout` that names a job waiting for a runner | No runner has taken the job for 30 minutes: a `runs-on` label no runner has, a self-hosted runner offline, or every slot of the account busy. A job waiting for its concurrency group is not counted | Compare its `runs-on` labels with the repository's runners (`dev ci audit`), start the runner, or cancel the run with `gh run cancel ` | + +A job that never started has no log. `dev run view --failed`, `dev pr checks`, and the watch name it with its check +run's annotation and its class: `not_started`, with the subclass `budget` for an account limit that no push fixes, +or `workflow_invalid` for a run GitHub could not start. Each class's next action is in +[CI/CD pipelines › Watch every run](ci-cd.md#watch-every-run). The automatic watcher runs only for main sessions, once per repository, branch, and commit, and not for temporary folders. It watches only what reached `origin`: a branch that was never pushed gets no watch. Its log is @@ -647,9 +676,11 @@ devkit does not know. ### A crew member's progress landed on the main plan A member's `dev progress` or `dev crew` call that devkit cannot place in its lane, such as one inside `$(…)`, a loop, -or a pipeline into a file, runs as the main session's, and the hook adds advice to run it alone. When such a call -closed or noted the wrong step, repair it with `dev progress reopen --why "…"`, and have the member run the -call again as a command of its own. +or a pipeline into a file, still acts as the member when its call carries the call token, and a state change without +the token is refused (see [The crew › Who is calling](crew.md#who-is-calling)). Only in a session whose hook never +stamped a token, such as one an older devkit started, does such a call run as the main session's; the hook adds +advice to run it alone. When such a call closed or noted the wrong step, repair it with +`dev progress reopen --why "…"`, and have the member run the call again as a command of its own. ### An agent ran something devkit used to refuse diff --git a/plugin/skills/cicd/SKILL.md b/plugin/skills/cicd/SKILL.md index 5c525b9c..2d63382b 100644 --- a/plugin/skills/cicd/SKILL.md +++ b/plugin/skills/cicd/SKILL.md @@ -50,7 +50,8 @@ change: `dev branch new ci/`, `dev commit`, `dev ci --run`, `dev push`, ` OIDC token. - `dev ci audit --strict` fails on medium findings too (default: high and critical). The delivery policy's `job_timeout_minutes` (default 30) is the timeout that `--fix` writes and `init` generates, and the policy's test - gate is what a generated test job runs. + gate is what a generated test job runs. `dev ci --run` gives each local step its workflow's limit: the step's own + `timeout-minutes`, else its job's, else 1.5 times its longest local pass when that is over 30 minutes, else 30. - **A timeout or concurrency change needs no new local run.** When every file changed since the last local run is a GitHub workflow that differs only in `timeout-minutes`, `concurrency` (`group`, `cancel-in-progress`) or comments, with no YAML anchors, aliases, merge keys or tags, the evidence carries over once `actionlint` and `dev ci audit` @@ -117,7 +118,11 @@ dev ci watches # live watches, and expired ones with the command to re- `--wait` prints one line per finished job, then one line `CI · …` with the conclusion, retries host errors, and ends by itself. Exit codes: `0` passed; `1` failed (cancelled, timed out, startup failure, and action required count as failed); `2` nothing to watch; `3` the watch ended before the run (re-arm it); `4` none (no run, or only -skipped, neutral, or stale ones). Claude Code: the Monitor tool (one event per line, at most 30 minutes, re-armed on +skipped, neutral, or stale ones). devkit's background watch follows a run for the repository's own limit: the +longest chain of jobs that need each other, at their `timeout-minutes` (GitHub's 360 when a job has none), plus 30 +minutes for the queue, from 90 to 360; `dev ci watch` gives up at `--timeout` (default 90). A job that has waited 30 +minutes for a runner while nothing else of its commit runs gets one line in the `--wait` stream, with its next +action; a watch that reaches its limit names it. Claude Code: the Monitor tool (one event per line, at most 30 minutes, re-armed on expiry) or Bash with `run_in_background` (one notification at exit). Codex has no background wake-up: run it in the foreground with a timeout, or say that you check it again at the next turn. The Stop hook sends back a turn that sent work to origin and leaves its unfinished run with nothing watching it that wakes the agent. A live @@ -125,7 +130,7 @@ sent work to origin and leaves its unfinished run with nothing watching it that watch delivers, so arm `dev ci watch --wait` only to follow one run job by job (`wait-and-wake` skill). A failure comes with the failed jobs and steps, **the first error of the log** (not the tail: later errors -follow from it; the first line that reads as an error and says what failed), a class and one next action. A PR made +follow from it; the first line that reads as an error and says what failed), a class, and one next action. A PR made ready is watched to its own run, not the draft's skipped one: | Class | What it means | The one next action | @@ -138,6 +143,12 @@ ready is watched to its own run, not the draft's skipped one: | pipeline | the workflow file itself | `dev ci audit`, fix, `actionlint`, push once | | infrastructure | network, rate limit, runner: possibly flaky | prove it is not the change (the same job on the base branch, or a second failure in the same place), then rerun once with `dev run rerun --flaky ""` | | cancelled | the run was cancelled or timed out: a newer push, someone cancelled it, or a job ran past its timeout | read where it stopped (`dev run view `); for a timeout, find what hung or ran slow, reproduce it locally, fix, push once; for a newer push, follow that push's run | +| not_started | the job never started, so there is no log; its check run's annotation names why | fix the cause its annotation names, then rerun once without a new push | +| budget (a not_started subclass) | an account limit, not the code | the developer checks billing; do not push again | +| workflow_invalid | GitHub could not start the run | run `dev ci audit` and actionlint, fix the file, push once | + +A cancelled run or leg is never `not_started`: it stays `cancelled`. `dev run view --failed` and `dev pr checks` +name a job that never started with its annotation and next action, the same way. Rules that hold for every failure: diff --git a/plugin/skills/crew/SKILL.md b/plugin/skills/crew/SKILL.md index 1de2ebf1..23ad5889 100644 --- a/plugin/skills/crew/SKILL.md +++ b/plugin/skills/crew/SKILL.md @@ -98,8 +98,8 @@ then the developer's latest request, then age); a launch out of that order needs Never two members on the same files; never parallel work on a design that is not settled. Follow-ups go to the **same** member (Claude `SendMessage`, Codex `send_input`), which keeps its context and its lane: a fresh one would have to learn everything again. Assign the follow-up's step to that member first (`dev progress assign --to -`), then send the message: its lane takes the step with its scope as soon as it holds no other open step, -and only then can the member's `dev progress step --step` close it. +`), then send the message: its lane takes the step with its scope as soon as it runs no other step, and +only then can the member's `dev progress step` close it. Patterns that work: @@ -154,10 +154,10 @@ dev crew graph --global # every live session on this Mac (the defau - **A step binds to the launch that names it.** A new launch takes the ready step its description names, so put the step's name in the launch description (`dev crew brief --step` does). On Claude Code, a launch that names none of its member's steps gets the one waiting step's name from the pre-tool hook, which tells you; with two or more waiting, - it gives you the exact description that takes each. `assign` gives a step to a member's working - lane at once, when its dependencies are done, if that lane's launch names the step or the lane holds no other open - step; otherwise the step is queued for the member's lanes (next item), or, when the member does not work, waits - for a launch, and you are told why. A step delegated into a working lane closes only on that lane's own evidence: + it gives you the exact description that takes each. A follow-up launch that names a step of the member that is + already done is left unchanged and takes no step (on Codex, such a `task_name` takes none). `assign` gives a step + to a member's working lane at once, when its dependencies are done, if that lane's launch names the step or the + lane runs no other step; otherwise the step waits for the member's next free lane (next item). A step delegated into a working lane closes only on that lane's own evidence: the member names it with `dev progress step "…" --step "" --check "…"`. - The step's time is its member's own time, and its `--scope` is the set of files that member edits; an edit outside it gets advice in the member's context. @@ -169,23 +169,27 @@ dev crew graph --global # every live session on this Mac (the defau - **Scopes match folder by folder.** `*`, `?`, and `[…]` stay inside one folder name; `**` spans folders; a glob holds everything under a folder it matches. `*.md` means root-level Markdown only: write `**/*.md` for all of it. A relative glob never holds a path outside the repository, a link that leads out of it included, and a - whole-checkout scope becomes its top-level entries. Two scopes overlap only when one path matches both (without case), so two members can split one folder - (`src/pkg/*.py` and `src/pkg/studio/host.py`). -- **A member's own close lands at once.** `dev progress step "…" --step "" --check "…"` from the member ends - that step right away, and the steps after it start. A review step is the exception: it ends with the member's + whole-checkout scope becomes its top-level entries. Two scopes overlap only when one path matches both (without + case), so two members can split one folder (`src/pkg/*.py` and `src/pkg/studio/host.py`). A filename with no + wildcard is that file only: `docs/crew.md` does not overlap `docs/**/bug*.md`, while `docs/` does. +- **A member's own close lands at once.** `dev progress step "…" --check "…"` from the member closes its lane's + only running step (`--step ""` names one), and the steps after it start. With two or more running it is + refused (`say which with --step`); with none it prints ⚠ and closes nothing. The line shows ✓ only when a step's + state changed. A review step is the exception: it ends with the member's report, done only when the crew gates pass it, so a reviewer's lane may hold more than one review (one launch can name them all). On Claude Code, a member's close is refused while a background command it started has not ended: run it - again once they end, or stop the ones that are not the step's work with TaskStop. A `--step` on a step the lane does not hold, or still queued for it, + again once they end, or stop the ones that are not the step's work with TaskStop. A `--step` on a step the lane does not hold, or one that waits for the lane, exits 2 and records nothing. For a long step that stays open, the member records partial evidence with `dev progress note "…" --step "" --check "…"`, which the crew gate accepts as the step's record. -- **A busy member's next step waits in its lanes.** Assigning a step to a member whose working lanes all hold another - open step queues it for them: it joins, with its scope, the first lane whose step closes, one at a time in the - order you assigned them. To give it to one lane, assign it with that lane's launch description - (`--to ""`; the notice prints the line). If the lanes end first, the step waits for a launch. +- **A member's next steps wait on the steps themselves.** A pending step keeps its assignment, so a lane that ends, + stops, or resumes never drops it. A free lane takes, in order: the step its launch names, an answered blocked step, + the steps bound to that lane, then the steps given to its member, each oldest first. To bind a step to one lane, + assign it with that lane's launch description (`--to ""`; the notice prints the line). A new launch + takes a step bound to an older lane once that lane has ended. The member is told `“” is your step now`. - **Check who holds the files first.** Before you assign a scope, or edit files outside your own lane, run `dev crew owner `: it names the member whose step holds each path. A member whose lane ended or went stale - holds no files. When a step and its files go to another lane, a lane that kept those files may read but not write - until you assign it a step, so two lanes never write the same files. + holds no files. A lane's write scope is the union of the scopes of the steps it runs: a done, skipped, blocked, or + unverified step gives its lane no files, so two lanes never write the same files. - Work you discover goes into the plan when it **starts** (`dev progress add`, then `dev progress begin`), so its time is its own; close a step only with its evidence and only the step it is about. - `dev crew brief` prints the brief and the exact spawn line. Launch every parallel member **in one message**. Then @@ -219,18 +223,33 @@ files. subagent (`agent_id` in the hook input) and writes it to that member's lane, never to your plan. `dev progress`, the dashboard, `dev crew` and `dev crew graph` show every lane with its time. One launch makes one lane, and one step: name it in the launch. A failed launch holds no slot. A member stopped with TaskStop, or whose transcript - shows an interruption, ends `stopped`: its slot frees at once and its open steps go back to pending for a new - launch. A resumed member keeps its lane and takes a slot like a launch; while none is free it may read but not - write, and you are told once. -- **Who is calling:** devkit records every shell call with the agent that made it. Your own plan commands - (`dev progress start|assign|begin|reopen|skip|done`, `dev crew decide|mode`, `dev crew route --plan --apply`) count - as yours only when you type them: run through a script or `bash -c`, they are refused. A member's lane calls - (`dev progress …`, `dev crew ask|answer|inbox|…`) go to its own lane. On Claude Code they work inside any command - (a list, a loop, a pipe, `bash -c`): devkit runs it with the member's lane variable exported, except a command that - drops that variable, a lane call in a program that sets its children's environment, or a double-quoted message - that runs a substitution. On Codex, a lane call runs as the whole command, or joined to `cd` and reads with `&&` or - `;` and piped into a read-only filter (`| tail -5`). A lane call devkit cannot place runs as the main session's, - with advice to run it alone; repair a step it closed by mistake with `dev progress reopen`. + shows an interruption, ends `stopped`: its slot frees at once and its running steps go back to pending for its + member's next lane. A resumed member keeps its lane, takes its next step (one given to it by role included), and + writes that step's files; it takes a slot like a launch, and while none is free it may read but not write, and you + are told once. A blocked step frees its lane: the member takes its next step and its files. When the decision is + answered, the step runs again in that lane, or goes first in its queue, or goes to the member's next lane if that + lane ended. +- **Who is calling:** devkit names who runs a `dev` command by its call token: the PreToolUse hook puts + `DEVKIT_CALL=.` in front of the call, and the token holds only for the shell the agent ran the call + in, and its child processes, and only while the call is open. Your own plan commands + (`dev progress start|assign|begin|reopen|skip|done`, `dev crew decide|mode`, `dev crew route --plan --apply`) are + yours from your own call, whatever members' calls are open or wait at the time; a script run by path from your + call's shell, and `$(dev crew read …)` inside `dev crew ack`, work too. A state change devkit cannot verify is + refused, never taken as yours: run it again as a command of its own, in the foreground. A background command's + identity ends when it starts. + A member's lane calls (`dev progress …`, `dev crew ask|answer|inbox|…`) go to its own lane. On Claude Code they work + inside any command (a list, a loop, a pipe, `bash -c`): devkit runs it with the member's lane variable exported, + except a command that drops that variable, a lane call in a program that sets its children's environment, or a + double-quoted message that runs a substitution. On Codex, a lane call runs as the whole command, or joined to `cd` + and reads with `&&` or `;` and piped into a read-only filter (`| tail -5`). A lane call devkit cannot place still + acts as the member when its call carries the token, and is refused without it; the hook advises running it alone. + On Codex, `CODEX_THREAD_ID` decides no state change where devkit stamps every call (approval policy `never`). + Where Codex asks, a thread names a member, or you for the root thread, only while that caller's own open call is + exactly that `dev` command; a compound state change is refused with the fix to run it as one plain `dev` command. + Any crew member can turn the root-thread mapping off for the rest of the session with one call that carries the + root's thread id: devkit records it as `codex.thread-shared`, and you then run plain `dev` commands. + Outside bypass mode (Claude Code) or a never-asks policy (Codex), only calls that visibly run `dev` carry the + token, so permission prompts do not grow; never add an `export:*` allow rule. Read-only crew commands run anywhere: `dev crew graph`, `show`, `rules`, `history`, `next`, `owner`, and `dev crew raci` without `--set`. After a compaction, Claude Code gives your conversation a new session id; devkit moves your open run and its @@ -312,7 +331,9 @@ dev crew decide D1 "B: reject" # the tech lead records - **A member at a decision point** runs `dev crew ask --decision` with options and a recommendation, and `--approves ""` when the answer approves finished work. In auto mode it gets the answer at once and goes on, unless the decision approves steps. In guided mode, and for a decision that approves steps in either mode, its step - is blocked and it **stops**: it ends its report (Check: `– waiting for D1`), so no tokens burn while it waits. + is blocked and frees its lane: when the member has another step, its lane takes it with its files and the member + may work on it; otherwise it **stops**: it ends its report (Check: `– waiting for D1`), so no tokens burn while it + waits. - **You see** each pending decision with your next action: in guided, every one; in auto, only those auto cannot take, which approve steps or have no recommendation. Run `dev crew decisions --ask` and send the call it prints with your question tool (AskUserQuestion in Claude Code): at most 4 questions per call, `D ·` up front. You may @@ -334,8 +355,9 @@ dev crew decide D1 "B: reject" # the tech lead records - While the configuration is invalid (`dev config validate` fails), devkit reads the mode as guided (origin `invalid configuration`): decisions wait for the developer, and the views show the mode as invalid until the file is fixed. Every `dev` command's error names the `cp` command that restores the newest valid copy. -- Recording an answer never brings back a lane that ended: the step it blocked goes back to pending, and the resume - or a new launch takes a slot. +- Recording an answer never brings back a lane that ended: the step it blocked goes first to the member's next + lane, and the resume or a new launch takes a slot. While the lane runs another step, the answered step waits first + in its queue. A decision belongs to its run, and only an open one needs the developer: @@ -363,6 +385,11 @@ them). files hold no unfinished work, its new tests can fail, two refusals got a lesson (`dev lesson add`), and every command it put in the background has ended (Claude Code lists a member until then). + The crew gates judge every stop. A member is sent back once per lane life (its launch, or a resume), and its next + stop is judged again: a clean report with Check ✓ passes, so a review it finishes ends done. A stop let through + with findings approves nothing; it is audited as `crew.gate` let through, and its findings reach you in one + notice. On Codex, the gates read a member's executed command without devkit's own stamps in front of it. + When the member must not run `dev ci --run` (a shared checkout, runner preparation that must not run twice), put `Waived proof: dev ci --run — ` on a line of its own in the brief, or run `dev ci --run` yourself on the tree it leaves: only you can meet that proof for a member, and its own `dev ci --mark-passed` does not. @@ -384,8 +411,10 @@ them). 3. **Review steps start on unverified work.** A review step (its kind of work is review, or its member works review-only) does not wait for the steps it follows to be verified, and its Check ✓ approves the ones its member is the approver for. A member's verdict, its review's Check or its `--approves`, counts only at the end of its - lane, once the crew gates pass its report without a finding: a report sent back approves nothing, and the work - stays owed. Your own `--approves` counts at once. Every other step waits for done or skipped, and the run cannot + lane, once the crew gates pass its report without a finding: a report sent back or let through with findings + approves nothing, and the work stays owed; when the lane ends, one notice tells you which reviews and verdicts did + not count. A review recorded with ✗ (changes requested) lets the step after it start; the reviewed work stays + unapproved. Your own `--approves` counts at once. Every other step waits for done or skipped, and the run cannot end while a step is unverified or an approval is owed. 4. **Check the work, don't trust the report:** read the diff (`git diff --stat`, then the files that matter), run the affected tests yourself (`dev test`), and spot-check a cited `file:line`. From 318a108149c7428997ff3fcb083b472da0583248 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 21:59:37 -0800 Subject: [PATCH 35/52] fix(crew): list the coordination rules and keep a freed member working dev crew rules did not show the coordination rules devkit now enforces, still called the gate-findings rule planned and the caller check the call ledger, and a member whose guided decision freed its lane for its next step was told to stop. Root cause: the rules catalog in crew.ENFORCEMENT and the guided-decision message in _ask_decision were written before a blocked step freed its lane and before the call token and the judged stops existed The catalog adds E-claim (coord.claim), E-call-token (identity.speaker) and E-blocked-frees (coord.block), rewords E-caller for the call token, and marks E-gate-findings enforced by gates.let_through. A member whose lane takes its next step after a guided decision is told that step and how to record it, and only a member with nothing else to do is told to stop. Verified: python3 -m unittest tests.test_crew_rules tests.test_crew tests.test_consistency: 108 tests OK --- lib/devkit/crew.py | 43 ++++++++++++++++++++++++----- tests/test_crew.py | 24 ++++++++++++++--- tests/test_crew_rules.py | 58 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 116 insertions(+), 9 deletions(-) create mode 100644 tests/test_crew_rules.py diff --git a/lib/devkit/crew.py b/lib/devkit/crew.py index d802cc2d..1d25f62f 100644 --- a/lib/devkit/crew.py +++ b/lib/devkit/crew.py @@ -507,9 +507,16 @@ def body(m: dict, roster=None, alias=None) -> str: "devkit.approvals.end_check", "enforced"), ("E-evidence", "A step closes only with its evidence", "dev progress step and SubagentStop", "devkit.approvals.ending", "enforced"), - ("E-gate-findings", "A member the crew gates sent back cannot close its step with the findings open", - "SubagentStop: the crew gates, at the second stop", "F-gjrrnclogpn: keep the step open while findings remain", - "planned"), + ("E-gate-findings", "A member the crew gates let through with findings open closes no review and counts no " + "verdict, and the tech lead hears what it still misses", + "SubagentStop: the crew gates judge every stop, sending a member back once per lane life", + "devkit.gates.let_through", "enforced"), + ("E-claim", "A free lane takes the oldest step waiting for its member, the step its launch names first", + "every point a lane can become free: a close, a lane's end, a resume, a launch, an assignment, a block", + "devkit.coord.claim", "enforced"), + ("E-blocked-frees", "A blocked step frees its lane for its member's next step; the answer brings the blocked step " + "back to that lane first", "dev crew ask --decision (guided), dev progress block, and the answer", + "devkit.coord.block", "enforced"), ("E-deps", "No step starts before its dependencies are done", "every step transition (start, add, assign, begin, " "advance, subagent start, close, launch readiness)", "devkit.progress.deps_open", "enforced"), ("E-recheck", "A reopened dependency's finished dependents are rechecked before the run ends", "dev progress done", @@ -526,8 +533,13 @@ def body(m: dict, roster=None, alias=None) -> str: "every hook event on the run and every launch check", "devkit.progress.expire_stale", "enforced"), ("E-main-only", "Only the tech lead plans, assigns, decides and changes the mode", "dev progress and dev crew from a lane", "devkit.progress._main_only", "enforced"), - ("E-caller", "The tech lead's own commands cannot be reached through bash -c or scripts", - "the call ledger (Claude Code; Codex calls are audited)", "devkit.progress.caller", "enforced"), + ("E-caller", "A dev command acts as the call that typed it: the tech lead's as the tech lead, whatever members' " + "calls hold, and a member's, a script's run by path or a $(…)'s as that call's caller", + "the call token PreToolUse stamps on every shell call (Codex without a rewrite: its thread id); the call ledger " + "only for reads and waits", "devkit.progress.caller", "enforced"), + ("E-call-token", "A state change whose call carries no valid token, in a session whose calls carry one, is " + "refused, never taken as the tech lead's", "every state-changing dev command", "devkit.identity.speaker", + "enforced"), ("E-decisions", "A decision waits for the developer in guided mode; auto mode records the recommended option", "dev crew ask --decision", "devkit.progress.crew_decision", "enforced"), ("E-proofs", "A member runs the proofs its procedure names", "SubagentStop: the crew gates", @@ -1662,6 +1674,18 @@ def _from_agent(): return os.environ.get("DEVKIT_FROM_AGENT") or None # the hooks set it inside a subagent: its own lane +def _taken_meanwhile(me: str, d: dict) -> list: + """The steps lane `me` holds once its decision `d` blocked the steps it asked about: what the member works on while + the developer decides ([] when its lane holds nothing else, or the run cannot be read).""" + from . import coord, progress + try: + agent, sid, _ = progress.resolve_session() + run, _ = progress.lane_of(agent, sid, me) + return [s["name"] for s in coord.held(run or {}, me) if s["name"] not in (d.get("blocks") or [])] + except Exception: # noqa: BLE001 - an unreadable run keeps the message that the member waits + return [] + + def _ask_decision(a, me) -> int: from . import messaging, progress if a.to: @@ -1679,7 +1703,14 @@ def _ask_decision(a, me) -> int: + (f" · recommends {d['recommend']}" if d["recommend"] else "")) if d.get("note"): print(ui.dim(f" {d['note']}")) - if me: + nxt = _taken_meanwhile(me, d) if me else [] + if nxt: # the blocked step freed the lane (E-blocked-frees), which took its member's next step (E-claim) + on = ", ".join(f"“{s}”" for s in d.get("blocks") or []) + print(f"waiting for the developer's decision {d['id']}" + (f" on {on}" if on else "") + f": your lane takes " + f"“{nxt[0]}” meanwhile. Work on it and record it with dev progress step \"\" --step " + f"{nxt[0]} --check \"✓ \"; once the developer answers, the tech lead tells you, and the " + "blocked step comes back to your lane as soon as it holds no other step") + elif me: print(f"waiting for the developer's decision {d['id']}: stop here and end your report with your status block " f"(Check: – waiting for {d['id']}; Needs from the tech lead: {d['id']}). The tech lead resumes you " "with the answer") diff --git a/tests/test_crew.py b/tests/test_crew.py index cad27766..6646abfa 100644 --- a/tests/test_crew.py +++ b/tests/test_crew.py @@ -424,10 +424,11 @@ def test_no_rule_text_holds_a_plan_label(self): def test_a_planned_rule_names_a_work_item_and_counts_as_named_in_any_run(self): planned = [(rid, ref) for rid, _, _, ref, st in crew.ENFORCEMENT if st == "planned"] - self.assertTrue(planned) self.assertEqual([rid for rid, ref in planned if not selfcheck.TASK_ID.search(ref)], []) - self.assertEqual([ok for *_, st, ok in crew.enforcement({"some other step"}) if st == "planned"], - [True] * len(planned)) + later = ("E-later", "A rule a work item adds", "where it will be checked", "F-gjrrnclogpn: add it", "planned") + with mock.patch.object(crew, "ENFORCEMENT", crew.ENFORCEMENT + (later,)): # holds with no planned row too + self.assertEqual([ok for *_, st, ok in crew.enforcement({"some other step"}) if st == "planned"], + [True] * (len(planned) + 1)) # dev crew rules prints each rule with its id def test_rules_prints_each_rules_id(self): @@ -881,6 +882,23 @@ def test_a_decision_without_two_to_four_lettered_options_and_a_recommendation_is self.assertIn(fix, err, args) self.assertEqual(pg.load_run("claude", "s1").get("decisions") or [], []) + def test_a_guided_decision_names_the_step_the_freed_lane_takes_instead_of_stopping_the_member(self): + # the blocked step frees the lane (E-blocked-frees), which takes its member's next step (E-claim) + with TempState() as t: + pg.start("Parser", plan=["parse", "ship"]) + pg.set_mode("guided") + pg.assign("parse", "Neo") + pg.assign("ship", "Neo") + t.launch() + rc, out, _ = run_cli("crew", "ask", "--decision", "Drop the legacy column?", "--options", "A: drop | B: keep", + "--recommend", "B", from_agent="a1") + self.assertEqual(rc, 0, out) + plan = {s["name"]: (s.get("owner"), s["state"]) for s in pg.load_run("claude", "s1")["plan"]} + self.assertEqual(plan, {"parse": ("a1", "blocked"), "ship": ("a1", "running")}) + self.assertNotIn("stop here", out) + self.assertIn("waiting for the developer's decision D1 on “parse”: your lane takes “ship” meanwhile", out) + self.assertIn('dev progress step "" --step ship --check "✓ "', out) + def test_guided_decisions_wait_for_the_developer(self): with TempState() as t: pg.start("Parser", plan=["parse", "ship"]) diff --git a/tests/test_crew_rules.py b/tests/test_crew_rules.py new file mode 100644 index 00000000..0cbebf8c --- /dev/null +++ b/tests/test_crew_rules.py @@ -0,0 +1,58 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +"""The rules catalog (`dev crew rules`, crew.ENFORCEMENT) holds the coordination rules devkit now enforces, each with +the check that does it: a free lane takes the oldest step waiting for its member, the one its launch names first +(E-claim, coord.claim); a state change needs its call's token or is refused (E-call-token, identity.speaker); a +blocked step frees its lane (E-blocked-frees, coord.block); a command acts as the call that typed it, by the call +token (E-caller); and a member the crew gates let through with findings approves nothing, and the tech lead hears +them (E-gate-findings, gates.let_through, enforced now that the gates judge every stop). + +Run: python3 -m unittest tests.test_crew_rules -v""" +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import crew # noqa: E402 +from test_crew import run_cli # noqa: E402 +from test_progress import TempState # noqa: E402 + +NEW = {"E-claim": "devkit.coord.claim", "E-call-token": "devkit.identity.speaker", + "E-blocked-frees": "devkit.coord.block"} + + +def rows() -> dict: + return {row[0]: row for row in crew.ENFORCEMENT} + + +class CoordinationRuleTests(unittest.TestCase): + def test_the_coordination_rules_are_enforced_by_the_checks_that_do_it(self): + found = {rid: (rows()[rid][3], rows()[rid][4]) for rid in NEW if rid in rows()} + self.assertEqual(found, {rid: (ref, "enforced") for rid, ref in NEW.items()}) + checked = {rid: ok for (rid, *_), (*_, ok) in zip(crew.ENFORCEMENT, crew.enforcement())} + self.assertEqual([rid for rid in NEW if not checked[rid]], []) # each check imports + + def test_gate_findings_are_enforced_now_that_the_gates_judge_every_stop(self): + rid, rule, where, ref, state = rows()["E-gate-findings"] + self.assertEqual((ref, state), ("devkit.gates.let_through", "enforced")) + self.assertIn("every stop", where) + + def test_the_caller_rule_names_the_call_token_not_the_call_ledger(self): + rid, rule, where, ref, state = rows()["E-caller"] + self.assertIn("call token", where) + self.assertNotIn("bash -c", rule) # a script run by path or a $(…) now acts as the call that typed it + self.assertEqual(state, "enforced") + + def test_dev_crew_rules_lists_the_coordination_rules_as_enforced(self): + with TempState(): + rc, out, _ = run_cli("crew", "rules") + self.assertEqual(rc, 0, out) + for rid in [*NEW, "E-gate-findings"]: + with self.subTest(rule=rid): + line = next((ln for ln in out.splitlines() if ln.lstrip().startswith(rid + " ")), "") + self.assertIn("enforced", line, out) + + +if __name__ == "__main__": + unittest.main() From 6514ac1ce19fd893d33f0cfa7b874927003b25b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 22:00:22 -0800 Subject: [PATCH 36/52] fix(audit): register codex.thread-shared as a security notice A member's command that carried another caller's Codex thread was audited as a plain change with severity info, so dev audit's security views never listed it. Root cause: identity records it through _audit_identity, which the test that every recorded action is registered did not scan, and audit.ACTIONS had no entry for it audit.ACTIONS registers codex.thread-shared as security, notice, and the registry test now scans _audit_identity calls too. Verified: python3 -m unittest tests.test_audit: 126 tests OK --- lib/devkit/audit.py | 1 + tests/test_audit.py | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/devkit/audit.py b/lib/devkit/audit.py index 9fb038e5..2ddc0554 100644 --- a/lib/devkit/audit.py +++ b/lib/devkit/audit.py @@ -1733,6 +1733,7 @@ def settings() -> dict: # an extension recorded or a change accepted (shown until the developer acknowledges it), the acknowledgement "ext.accept": ("security", "warning"), "ext.ack": ("security", "notice"), "caller": ("security", "warning"), "caller.unverified": ("security", "notice"), + "codex.thread-shared": ("security", "notice"), # a member's command carries another caller's Codex thread "calls": ("lifecycle", "notice"), "progress": ("decision", "notice"), "session": ("lifecycle", "info"), "run": ("lifecycle", "notice"), # a run orphaned by its ended session, or taken back by its resumed one "scope.write": ("security", "notice"), # a review or read-only lane's shell call wrote files; a caller sure diff --git a/tests/test_audit.py b/tests/test_audit.py index d5d383cc..e44206cb 100644 --- a/tests/test_audit.py +++ b/tests/test_audit.py @@ -395,9 +395,13 @@ def test_automatic_authorization_preserves_its_policy_and_principal_evidence(sel self.assertEqual({key: recorded.get(key) for key in fields}, fields) self.assertEqual(recorded["source"], "policy-auto") + def test_a_codex_thread_shared_by_a_member_and_its_caller_is_a_security_notice(self): + # identity records it when a member's command carries another caller's Codex thread + self.assertEqual(audit.kind("codex.thread-shared"), ("security", "notice")) + def test_every_action_the_code_records_is_registered(self): - found = set() - call = re.compile(r"""\b(?:audit\.record|_audit)\(\s*f?["']([a-z][a-z0-9_.-]*)""") + found = set() # the identity records too (identity._audit_identity), which once went unregistered + call = re.compile(r"""\b(?:audit\.record|_audit|_audit_identity)\(\s*f?["']([a-z][a-z0-9_.-]*)""") for f in sorted((LIB / "devkit").glob("*.py")): found |= {m.group(1).rstrip(".") for m in call.finditer(f.read_text())} found.discard("action") From 7ad667dde9745418ce98628b3b7436f01eb00d39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 22:03:14 -0800 Subject: [PATCH 37/52] fix(ci): let a terminal dev ci watch take the derived limit dev ci watch in a terminal still gave up after a fixed 90 minutes, while the background watch after a push and --wait used the repository's own limit, and three doc rows said the default was 90. Root cause: the dev ci watch parser set --timeout default=90 and cmd_ci_watch fell back to 90, so ciwatch.watch never got None to derive its limit from --timeout defaults to None with help naming the derived limit, cmd_ci_watch passes it as given, and docs/commands.md, docs/ci-cd.md and docs/troubleshooting.md say all three watches follow the same limit unless --timeout gives minutes of its own. Verified: dev test run (test_ci_watch_limits, test_cli_ci, test_ci_commands, test_ciwatch, test_consistency, test_crew, test_crew_rules, test_audit, test_cli, test_docs_check): 329 passed; dev docs check clean --- docs/ci-cd.md | 4 ++-- docs/commands.md | 6 +++--- docs/troubleshooting.md | 2 +- lib/devkit/cli.py | 6 ++++-- tests/test_ci_watch_limits.py | 17 +++++++++++++++++ 5 files changed, 27 insertions(+), 8 deletions(-) diff --git a/docs/ci-cd.md b/docs/ci-cd.md index d4490598..1132c824 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -382,8 +382,8 @@ the commit ends first. devkit's background watch follows a run for the repository's own limit: the longest chain of jobs that need each other, at their `timeout-minutes` (GitHub's 360 when a job has none, a local reusable workflow counted by its own -chain), plus 30 minutes for the queue; at least 90, at most 360. `dev ci watch` and `dev ci watch --wait` give up -after `--timeout` minutes (default 90). A GitHub job that has waited 30 minutes for a runner while nothing else of +chain), plus 30 minutes for the queue; at least 90, at most 360. `dev ci watch` and `dev ci watch --wait` follow the +same limit, unless `--timeout` gives minutes of its own. A GitHub job that has waited 30 minutes for a runner while nothing else of its commit runs gets one line in the `--wait` stream, with its next action, and a watch that reaches its limit names it (`CI waits for a runner`). A job that waits for its concurrency group, or for an environment's approval, is not counted. diff --git a/docs/commands.md b/docs/commands.md index d557bd63..9bce0090 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -676,7 +676,7 @@ Tokens are read from the environment and never printed. A host that cannot be re `dev status` shows the latest run of the branch, and when you ask an agent for status, the prompt hook adds the branch's pipelines to its context. -### `dev ci watch [-p PROJECT] [--branch B] [--sha S] [--timeout 90] [--json] [--quiet] [--wait [--pr N | --tag T]]` +### `dev ci watch [-p PROJECT] [--branch B] [--sha S] [--timeout MIN] [--json] [--quiet] [--wait [--pr N | --tag T]]` Follows the CI/CD runs of a branch for one commit (default: the current branch at HEAD) until they finish, on GitHub Actions, GitLab CI, Bitbucket Pipelines, or Azure Pipelines. A failure comes with the failed jobs and steps, the first @@ -707,8 +707,8 @@ with its next action at its next hook: a crew message to the main agent when it has a progress run, otherwise a note on its next tool call or prompt. That background watch follows the run for the repository's own limit: the longest chain of jobs that need each other, at their `timeout-minutes` (GitHub's 360 when a job has none, a local reusable workflow counted by its own chain), plus -30 minutes for the queue; at least 90, at most 360. `dev ci watch` and `dev ci watch --wait` give up after -`--timeout` minutes (default 90). That +30 minutes for the queue; at least 90, at most 360. `dev ci watch` and `dev ci watch --wait` follow the same limit, +unless `--timeout` gives minutes of its own. The background watch wakes no idle session, so an agent that waits on the run arms `--wait`; the Stop hook sends back a turn that sent work to origin and leaves its unfinished run with nothing that wakes the agent. Each result is in `~/.local/state/devkit/ci/watch/`, the audit trail (`ci.watch`), and a desktop notification. `DEVKIT_NO_CI_WATCH=1` diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 243e4172..07a3e4b0 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -595,7 +595,7 @@ differently. | Result | What it means | Fix | | --- | --- | --- | | `none` (exit `4`): no run verified this commit | No run appeared within 5 minutes (the branch has no CI for this event, or the host was unreachable, which the message adds), or every run was `skipped`, `neutral`, or `stale` | Check the triggers with `dev ci` or `dev ci audit`, and the sign-in with `dev ci status` | -| `timeout` (exit `3`): still running after the watch limit | The run takes longer than the watch's limit: `--timeout` for `dev ci watch` and `dev ci watch --wait` (default 90 minutes), or, for devkit's background watch, the longest chain of jobs that need each other, at their `timeout-minutes` (GitHub's 360 when a job has none, a local reusable workflow counted by its own chain), plus 30 minutes for the queue; at least 90, at most 360 | Follow it with `dev ci status --watch`; if it hangs, `dev ci audit` reports jobs without a timeout | +| `timeout` (exit `3`): still running after the watch limit | The run takes longer than the watch's limit: the longest chain of jobs that need each other, at their `timeout-minutes` (GitHub's 360 when a job has none, a local reusable workflow counted by its own chain), plus 30 minutes for the queue; at least 90, at most 360. It holds for devkit's background watch, `dev ci watch` and `dev ci watch --wait`, unless `--timeout` gives minutes of its own | Follow it with `dev ci status --watch`; if it hangs, `dev ci audit` reports jobs without a timeout | | `timeout` that names a job waiting for a runner | No runner has taken the job for 30 minutes: a `runs-on` label no runner has, a self-hosted runner offline, or every slot of the account busy. A job waiting for its concurrency group is not counted | Compare its `runs-on` labels with the repository's runners (`dev ci audit`), start the runner, or cancel the run with `gh run cancel ` | A job that never started has no log. `dev run view --failed`, `dev pr checks`, and the watch name it with its check diff --git a/lib/devkit/cli.py b/lib/devkit/cli.py index df17f943..e953d9a7 100644 --- a/lib/devkit/cli.py +++ b/lib/devkit/cli.py @@ -2334,7 +2334,7 @@ def cmd_ci(a): def cmd_ci_watch(a, top): from . import ciwatch - res = ciwatch.watch(top, branch=a.branch, sha=getattr(a, "sha", None), timeout_min=getattr(a, "timeout", 90) or 90, + res = ciwatch.watch(top, branch=a.branch, sha=getattr(a, "sha", None), timeout_min=getattr(a, "timeout", None), quiet=getattr(a, "quiet", False) or a.json, since=getattr(a, "since", None)) if getattr(a, "session", None) and ":" in a.session: ciwatch.deliver(*a.session.split(":", 1), res) @@ -5183,7 +5183,9 @@ def wanted(*names): "as a Claude Code Monitor or background command, or in the foreground on Codex") p.add_argument("--tag", help="watch --wait: the runs of this tag") p.add_argument("--pr", help="watch --wait: the runs of this PR's head, or of its merge commit once merged") - p.add_argument("--timeout", type=float, default=90, help="watch: minutes before giving up (default 90)") + p.add_argument("--timeout", type=float, default=None, + help="watch: minutes before giving up (default: the workflows' longest chain of jobs at their " + "timeout-minutes, plus 30 for the queue; 90 to 360)") p.add_argument("--session", help=argparse.SUPPRESS) p.add_argument("--since", type=float, help=argparse.SUPPRESS) # a PR made ready: its runs count from then p.add_argument("--quiet", action="store_true", help="watch: no progress lines, only the result") diff --git a/tests/test_ci_watch_limits.py b/tests/test_ci_watch_limits.py index 5815ddef..f0c0ab10 100644 --- a/tests/test_ci_watch_limits.py +++ b/tests/test_ci_watch_limits.py @@ -9,6 +9,8 @@ sessions follow the same watch, and `dev ci watch --wait` prints the same lines on both. Run: python3 -m unittest tests.test_ci_watch_limits -v""" +import contextlib +import io import os import sys import tempfile @@ -105,6 +107,21 @@ def test_the_background_watch_of_a_push_gets_the_derived_limit(self): self.assertEqual([w.get("timeout_min") for w in ciwatch.watches()], [125]) +class WatchCommandTests(unittest.TestCase): + # `dev ci watch` in a terminal: with no --timeout it leaves the limit to the watch, which derives it + def test_dev_ci_watch_without_timeout_lets_the_watch_take_the_repositorys_limit(self): + from devkit import cli + asked = [] + + def watch(top, **kw): + asked.append(kw.get("timeout_min", "missing")) + return {"state": "none", "runs": [], "diagnoses": []} + with mock.patch.object(ciwatch, "watch", watch), contextlib.redirect_stdout(io.StringIO()): + cli.main(["ci", "watch", "--branch", "main", "--sha", "abc1234", "--json"]) + cli.main(["ci", "watch", "--branch", "main", "--sha", "abc1234", "--json", "--timeout", "45"]) + self.assertEqual(asked, [None, 45]) + + class StuckJobTests(WatchCase): def test_a_job_no_runner_takes_is_named_with_its_next_action_once_nothing_else_of_its_commit_runs(self): # the deploy job's runs-on names a self-hosted label no runner has; the release job waits for an approval. From 409e026a06949232529270f556eef4b1ea242da4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 22:17:44 -0800 Subject: [PATCH 38/52] fix(identity): bind each call token to the process its call pins A crew member that read the tech lead's call token from ps could still use it: it exec'd its call shell into python, set a fake argv[0] with exec -a, or ran zsh -c "$(cat payload)" with the stolen stamp, and devkit accepted the shell's command line as proof of which call ran the dev command. Root cause: The token's binding read the command lines of the dev process's ancestors, which the caller writes itself, and relaxed the check further for an exec'd dev matched by text and for programs that run no script. Each stamped call is now bound to one process by a pin: - where the agent never asks (Claude Code in bypassPermissions, Codex with approval_policy never) and the shell is sh, bash or zsh, the stamp's first action writes the shell's own pid under noclobber into a per-user 0700 folder under $TMPDIR, before the token is exported; a write that finds a pin already there marks the call contested, and a contested call names nobody; - elsewhere (a permission mode that checks rules, a Codex that asks, fish or nushell) only one plain dev call carries the token, in the variable-list form, and its dev process writes the pin with O_EXCL, naming the call's own process below the agent or below the loop that launches its calls; - a dev command resolves by the token only at or below the pinned process, whose parent is the agent (or its launcher), which started after the call opened and within its ttl, and whose pid and start time match its first use (pid reuse); a malformed pin fails closed; - a call whose agent process is not known no longer binds by its session alone: it refuses state changes (caller.token-unpinned) and leaves reads to the ledger's rules; - where Codex asks, a thread claim takes a lane for a state change only when the lane's own open call is exactly that one dev command, and such a change is audited as flagged; - when a call ends, its pin is audited: calls.pin-contested, calls.pin-late (born more than 30 s after the call opened), calls.pin-replaced (another inode than its first use saw), and caller.token-unexplained-use (a tech-lead call that runs no dev command had its token used); - the pin folder is named by a hash of the session id, so a member's stamped command never shows the root thread's id, and strip_token removes the new prefix from every stored text. The command-line matching (_call_shell, _runs_this, _stamped) and its relaxations (an exec'd dev matched by text, non-script programs skipped) are gone. Verified: dev test run on 22 files (identity, token, red team, real-process theft on Claude and Codex, Codex launch, gates, coordination, parity): 606 of 606 passed; dev test prove --since HEAD: 28 new tests fail without the change. --- lib/devkit/hooks.py | 109 +++++++-- lib/devkit/identity.py | 313 ++++++++++++++++++-------- tests/test_caller_identity.py | 3 +- tests/test_codex_identity_token.py | 27 ++- tests/test_hooks_wiring.py | 3 +- tests/test_identity_redteam.py | 350 ++++++++++++++++++++++++++++- tests/test_identity_token.py | 55 ++++- 7 files changed, 720 insertions(+), 140 deletions(-) diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 0163eec3..dec41ff7 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -1536,12 +1536,57 @@ def _close_call(data: dict): if data.get("tool_name") in SHELL_TOOLS or entry.get("agent") == "codex": progress.call_closed(data) if data.get("tool_name") in SHELL_TOOLS and entry.get("agent") and data.get("tool_use_id"): - # its token dies with it: its use mark goes, and the session record lists the call as closed + _pin_audits(entry, data) + # its token dies with it: its pin and use mark go, and the session record lists the call as closed identity.note_closed(entry["agent"], str(data.get("session_id") or ""), str(data["tool_use_id"])) except Exception: _log(f"ledger close: {traceback.format_exc()[-300:]}") +PIN_LATE_S = 30 # seconds after its call opened past which a pin's birth means someone wrote it again + + +def _pin_audits(entry: dict, data: dict): + """When a stamped call ends: what its pin shows, as audit records (flagged; the uses themselves were judged when + they happened). calls.pin-contested: another process wrote the pin first. calls.pin-late: the pin was born more + than PIN_LATE_S after the call opened. calls.pin-replaced: its inode is not the one its first verified use saw. + caller.token-unexplained-use: the tech lead's call runs no dev command, yet a dev command resolved its token + (a script run by path may explain it).""" + from . import identity, shellparse + if data.get("hook_event_name") == "PreToolUse" or not entry.get("pin"): + return + pin, tid, sid = Path(str(entry["pin"])), str(data.get("tool_use_id") or ""), str(data.get("session_id") or "") + used = identity._read_used(sid, tid) + found = [] + if Path(f"{pin}.contested").exists(): + found.append(("calls.pin-contested", "another process wrote this call's pin before its shell did")) + try: + st = os.stat(pin) + born = getattr(st, "st_birthtime", st.st_ctime) + if born > float(entry.get("ts") or 0) + PIN_LATE_S: + found.append(("calls.pin-late", f"its pin was written {born - float(entry.get('ts') or 0):.0f} s after " + f"the call opened")) + if used.get("inode") and used["inode"] != st.st_ino: + found.append(("calls.pin-replaced", "its pin is not the file its first verified use saw")) + except OSError: + pass + if identity.used_path(sid, tid).exists() and str(entry.get("caller") or "main") == "main": + try: + runs = [shellparse.dev_args(a) for a, _ in shellparse.shell_calls(str(entry.get("cmd") or ""), None) or []] + except Exception: + runs = [None] + if not any(r for r in runs) and not entry.get("cut"): + found.append(("caller.token-unexplained-use", "a dev command resolved this call's token, and its text " + "runs no dev command")) + for action, why in found: + try: + from . import audit + audit.record(action, tid[:80] or "-", why, "flagged", tool_use_id=tid[:80], session=sid[:80], + host_agent=str(entry.get("agent") or ""), command=str(entry.get("cmd") or "")[:300]) + except Exception as e: + _swallowed("post-tool", e) + + def _rewrite(agent: str, updated: dict) -> dict: """A PreToolUse that changes the tool's input. Claude Code applies updatedInput with no permission decision, and its own permission settings then apply to the new input. Codex applies it only with @@ -1584,14 +1629,23 @@ def _token_skipped(agent: str, data: dict, why: str): _swallowed("pre-tool", e) +def _unasked(agent: str, data: dict) -> bool: + """Does the agent run this call without checking it against the developer's rules? Codex where it never asks + (_codex_never_asks); Claude Code in bypassPermissions (the payload's permission_mode). Elsewhere a prefix the + developer's allow rules do not know would make the call prompt.""" + return _codex_never_asks(data) if agent == "codex" else data.get("permission_mode") == "bypassPermissions" + + def _with_token(agent: str, data: dict, new, token: str): - """The shell call's input (`new`, the routed one, else its own) with the call token in front of its command, or None - when this call's form cannot carry one: `export DEVKIT_CALL=; readonly DEVKIT_CALL;` in an sh-family shell - where Codex never asks (and always on Claude Code), the variable-list form `DEVKIT_CALL= dev …` for one plain - devkit call where Codex asks or the shell is another one. A token never costs a rewrite Codex would apply - (_codex_may_rewrite), and never makes one either: where Codex asks, `allow` would skip the developer's approval, - so only a call devkit rewrites anyway (routed or stamped) carries it. The leading space keeps the stamped command - out of the shell's history.""" + """The shell call's input (`new`, the routed one, else its own) with the call token, and who pins the call + ("shell" or "dev"), or None when this call's form cannot carry one: + - where the agent never asks (_unasked) and the shell is sh, bash or zsh: the pin's write first + (identity.pin_stamp), then `export DEVKIT_CALL=; readonly DEVKIT_CALL;`, on every call; + - elsewhere (a Claude Code permission mode that checks rules, a Codex that asks, fish or nushell): the plain form + `DEVKIT_CALL= dev …`, on one plain devkit call only, whose dev process pins the call itself. + A token never costs a rewrite Codex would apply (_codex_may_rewrite), and never makes one either: where Codex + asks, `allow` would skip the developer's approval, so only a call devkit rewrites anyway carries it. The leading + space keeps the stamped command out of the shell's history.""" from . import identity if agent == "codex" and new is None and not _codex_never_asks(data): return None @@ -1601,7 +1655,7 @@ def _with_token(agent: str, data: dict, new, token: str): return None key, cmd = cmds[0] var = identity.CALL_VAR - if agent == "codex" and not _codex_never_asks(data) or not _sh_family(agent, data): + if not _unasked(agent, data) or not _sh_family(agent, data): if not _plain_devkit_call(cmd): return None at = 0 # after devkit's own variables, right before `dev` @@ -1611,10 +1665,11 @@ def _with_token(agent: str, data: dict, new, token: str): break at = m.end() lead = cmd[:at].strip(" \t") - out = {**base, key: f"{lead + ' ' if lead else ''}{var}={token} {cmd[at:].lstrip(' ' + chr(9))}"} + out, by = {**base, key: f"{lead + ' ' if lead else ''}{var}={token} {cmd[at:].lstrip(' ' + chr(9))}"}, "dev" else: - out = {**base, key: f" export {var}={token}; readonly {var}; {cmd}"} - return out if agent != "codex" or _codex_may_rewrite(data, out) else None + pin = identity.pin_path(str(data.get("session_id") or ""), str(data.get("tool_use_id") or "")) + out, by = {**base, key: f" {identity.pin_stamp(pin)}export {var}={token}; readonly {var}; {cmd}"}, "shell" + return (out, by) if agent != "codex" or _codex_may_rewrite(data, out) else None def _hook_launched_by(pid: int) -> bool: @@ -1641,25 +1696,36 @@ def _stamped_token(agent: str, data: dict, new, token: str, digest: str): sid, tid = str(data.get("session_id") or ""), str(data.get("tool_use_id") or "") if not token: return None - tokened = _with_token(agent, data, new, token) - if tokened is None: + formed = _with_token(agent, data, new, token) + if formed is None: if new is not None: _token_skipped(agent, data, "the rewrite would not carry the token: it goes out without it") identity.note_opened(agent, sid) return None + tokened, by = formed host = (os.environ.get(identity.THREAD_VAR) or "").strip()[:80] if agent == "claude" and host: # a Claude Code started from a Codex shell: its commands carry that thread progress.call_note(data, host_thread=host) owner = progress.call_entry(data).get("agent_pid") - if isinstance(owner, int) and not _hook_launched_by(owner): + launched = isinstance(owner, int) and _hook_launched_by(owner) + if isinstance(owner, int) and not launched: progress.call_note(data, agent_pid=None) # an agent further up started what runs this hook, not the hook + pin = str(identity.pin_path(sid, tid)) + try: + identity.make_pin_folder(sid) + except OSError: + _token_skipped(agent, data, "its pin folder could not be made") + return None + # the call's pin, who writes it, and the process that starts the agent's calls (the agent, or its launcher) + progress.call_note(data, pin=pin, pin_by=by, **({"launcher_pid": os.getppid()} if launched else {})) entry = progress.call_entry(data) ttl = identity.codex_ttl(data.get("tool_input")) if agent == "codex" else None if not hmac.compare_digest(str(entry.get("token_sha256") or ""), digest) or \ - ttl is not None and entry.get("ttl") != ttl or agent == "claude" and entry.get("host_thread", "") != host: + ttl is not None and entry.get("ttl") != ttl or agent == "claude" and entry.get("host_thread", "") != host \ + or entry.get("pin") != pin or entry.get("pin_by") != by: _token_skipped(agent, data, "its call ledger entry does not hold the token") return None - if not identity.note_opened(agent, sid, tid, every=agent != "codex" or _codex_never_asks(data)): + if not identity.note_opened(agent, sid, tid, every=_unasked(agent, data) and _sh_family(agent, data)): _token_skipped(agent, data, "the session record is busy") return None return tokened @@ -2992,15 +3058,16 @@ def _scope_advice(agent: str, data: dict) -> list: UNROUTED_LANE_CALL = ("devkit could not route the dev progress, dev crew or dev watch call in this command to your lane, " - "so it will run as the main session: it may close a step of the main run, speak as the tech " - "lead or take the tech lead's wait. Run that call alone, as a command of its own; if it closed " - "the wrong step, tell the tech lead (dev progress reopen repairs it).") + "so devkit cannot tell who runs it: a change (a step, a note, a message, an answer) is refused " + "rather than made as the tech lead, and a read may name nobody. Run that call alone, as a " + "command of its own.") def _unroutable_lane_advice(agent: str, data: dict) -> list: """A crew member's shell command that runs a `dev progress` or `dev crew` lane call devkit could not route or stamp to its lane (called only when neither did, and Codex's gate turned no rewrite down: _pre_tool then gives - UNROUTED_LANE_CALL itself): that call acts as the main session, so the member is told.""" + UNROUTED_LANE_CALL itself): devkit cannot name that call's caller, so its changes are refused, and the member is + told.""" if not data.get("agent_id") or data.get("tool_name") not in SHELL_TOOLS: return [] from . import laneroute diff --git a/lib/devkit/identity.py b/lib/devkit/identity.py index ab21c0af..3f4b1617 100644 --- a/lib/devkit/identity.py +++ b/lib/devkit/identity.py @@ -53,6 +53,7 @@ import hashlib import hmac +import json import os import re import sys @@ -103,6 +104,8 @@ PLAIN_CALL = ("devkit could not verify which Codex thread runs this: run it as one plain dev command (no pipeline, " "script or other command around it)") CONFLICT = "this call's token and its lane variable or thread name different callers" +UNPINNED = ("devkit could not tell which agent process runs this call, so its token names nobody for a state change: " + "run it again as a command of its own") @dataclass(frozen=True) @@ -519,7 +522,8 @@ def strip_token(cmd): (the ledger, the records of closed calls, the audit trail, notices).""" if not isinstance(cmd, str): return cmd - cmd = re.sub(r"\A ?export DEVKIT_CALL=[A-Za-z0-9_.-]+; readonly DEVKIT_CALL; ", "", cmd) + cmd = re.sub(r"\A ?(?:\(set -C; printf '%s\\n' \"\$\$\" > .+?\) 2>/dev/null \|\| \(: > .+?\) 2>/dev/null; )?" + r"export DEVKIT_CALL=[A-Za-z0-9_.-]+; readonly DEVKIT_CALL; ", "", cmd) return re.sub(r"\A((?:DEVKIT_[A-Z_]+=[A-Za-z0-9_.:-]+ )*)DEVKIT_CALL=[A-Za-z0-9_.-]+ ", r"\1", cmd) @@ -568,10 +572,12 @@ def note_closed(agent: str, sid: str, tid: str): """The call ended: its tid moves from the opened calls to the closed ones (at most CALLS_KEPT), and its use mark goes.""" from . import progress, state - try: - used_path(sid, tid).unlink() - except OSError: - pass + pin = pin_path(sid, tid) + for f in (used_path(sid, tid), pin, pin.with_name(pin.name + ".contested")): + try: + f.unlink() + except OSError: + pass def put(d): if tid in (d.get("calls_opened") or []): @@ -613,7 +619,7 @@ def _token_verdict(agent: str, sid: str, args: list, now): key = (os.getpid(), value, str(progress.CALLS), agent, sid) if key not in _RESOLVED: _RESOLVED[key] = v = _verify(agent, sid, value, now, args) - if v.code and (state_changing(args) or v.code not in ("caller.stale-token",)): + if v.code and (state_changing(args) or v.code not in ("caller.stale-token", "caller.token-unpinned")): _audit_identity(v.code, v, agent, sid, args, "deny" if state_changing(args) else "flagged") return _RESOLVED[key] @@ -626,89 +632,136 @@ def _chain() -> list: return [(p, lines.get(p, "")) for p in pids] -def _command_line(pid) -> str: - """The whole command line of process `pid` (`ps -ww -o command=`), "" when ps gives no answer.""" - import subprocess - try: - out = subprocess.run(["ps", "-ww", "-o", "command=", "-p", str(int(pid))], capture_output=True, text=True, - timeout=5) - except (OSError, subprocess.SubprocessError, TypeError, ValueError): - return "" - return out.stdout.strip() if out.returncode == 0 else "" +# The call's pin binds its token to one process: the call's own shell, by kernel facts only (its pid, its parent and +# its start time), never by a command line, which any process can forge. The stamp writes the shell's pid as its +# first action, under noclobber, into a per-user 0700 folder a sandboxed shell may write (pin_dir); a pin that was +# already there marks the call contested, and then the token names nobody. For the plain form (`DEVKIT_CALL= dev +# …`, where no stamp runs first) the dev process pins the process right below the agent itself (O_EXCL). +_PIN_TEXT = re.compile(r"\d{1,10}\n?") -# Where the hook writes the token in a call's command, as the call's shell shows it in its command line: first in the -# script its shell runs (after `eval '` on Claude Code, after `-c` or `-lc` on Codex), either as -# ` export DEVKIT_CALL=; readonly DEVKIT_CALL;` or after devkit's own variables right before `dev` -_STAMP_BEFORE = re.compile(r"(?:eval '|\s-l?c\s)\s*(?:export\s+|(?:DEVKIT_[A-Z_]+=[A-Za-z0-9_.:-]+\s+)*)\Z") +def pin_dir(): + """The per-user folder of call pins: devkit-calls-- in the user's own $TMPDIR (macOS: /var/folders/…/T/, + which Codex's workspace-write sandbox and Claude Code's bash sandbox let a shell write), one per devkit state + folder; never the shared /tmp: devkit's state folder when $TMPDIR is unset or is /tmp.""" + from pathlib import Path + from . import core, progress + base = os.environ.get("TMPDIR") or "" + if not base or os.path.realpath(base).rstrip("/") in ("/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"): + return progress.CALLS / ".pins" + return Path(base) / f"devkit-calls-{os.getuid()}-{hashlib.sha256(str(core.STATE).encode()).hexdigest()[:8]}" -_SHELL_C = re.compile(r"(?:\S*/)?(?:ba|z|da|k|fi)?sh(?:\s+-[A-Za-z]+)*?\s+-[A-Za-z]*c[A-Za-z]*\s") # zsh -c, bash -lc +def pin_path(sid: str, tid: str): + """Call `tid`'s pin: //.pin, beside its `.contested` marker. The session + folder is named by a hash, so a crew member's stamped command never shows the root thread's id.""" + from . import progress + return pin_dir() / hashlib.sha256(str(sid).encode()).hexdigest()[:16] / f"{progress._safe_name(tid)}.pin" -def _call_shell(below: list) -> tuple: - """The shell the agent ran the call in: of this command's parents below the agent (nearest first), the one - closest to the agent that runs a script (`zsh -c …`, `bash -lc …`), past any program in between that runs - none. -> (pid, its whole command line), or (None, "") when there is none.""" - for pid in reversed(below or []): - line = _command_line(pid) - if _SHELL_C.match(line): - return pid, line - return None, "" +def make_pin_folder(sid: str): + """The session's pin folder, 0700 like the per-user one above it (the hook makes it before the stamp writes).""" + import stat + folder = pin_path(sid, "x").parent + for d in (folder.parent, folder): + d.mkdir(parents=True, exist_ok=True, mode=0o700) + st = os.lstat(d) + if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.getuid(): # a link or another user's folder planted there + raise OSError(f"the pin folder {d} is not a folder of this user's own") + os.chmod(d, 0o700) # nosemgrep: python.lang.security.audit.insecure-file-permissions.insecure-file-permissions (0700 is owner-only) + return folder -def _runs_this(entry: dict, args: list) -> bool: - """Does the token's call run this very dev command? For a dev process with no call shell above it: the shell - replaced itself with the command it ran last (zsh and bash exec it), so the process is that command. Its - arguments must be a dev invocation of the call's own text, each word as typed or produced by an expansion there.""" - from . import progress, shellparse - if not args: - return False - if progress.args_hash(args) in (entry.get("dev_args") or []): - return True - if entry.get("cut"): - return False +def pin_stamp(path) -> str: + """The stamp's first action, for sh, bash and zsh (Codex's -lc too): the shell's own pid into the pin, in a + subshell under noclobber so the user's command never runs with it, errors to /dev/null; a pin already there + leaves the contested marker instead.""" + import shlex + pin, contested = shlex.quote(str(path)), shlex.quote(f"{path}.contested") + return f"(set -C; printf '%s\\n' \"$$\" > {pin}) 2>/dev/null || (: > {contested}) 2>/dev/null; " + + +def _pid() -> int: + return os.getpid() + + +def _proc(pid): + """(parent pid, start time in seconds with microseconds) of process `pid`, from the kernel: proc_pidinfo on macOS, + /proc on Linux. None when it has exited or the system does not say.""" + import struct try: - calls = shellparse.shell_calls(str(entry.get("cmd") or ""), None) or [] - except Exception: - return False - for argv, _ in calls: - words = shellparse.dev_args(argv) - if words is not None and len(words) == len(args) and all( - w == a or re.fullmatch("".join(".*" if e else re.escape(t) for e, t in _expansion_parts(w)), a, re.S) - for w, a in zip(words, args)): - return True - return False + pid = int(pid) + except (TypeError, ValueError): + return None + if sys.platform == "darwin": + import ctypes + try: + lib = _proc.lib = getattr(_proc, "lib", None) or ctypes.CDLL("/usr/lib/libproc.dylib") + buf = ctypes.create_string_buffer(136) # struct proc_bsdinfo (PROC_PIDTBSDINFO) + if lib.proc_pidinfo(ctypes.c_int(pid), ctypes.c_int(3), ctypes.c_uint64(0), buf, ctypes.c_int(136)) != 136: + return None + except (OSError, AttributeError): + return None + sec, usec = struct.unpack_from("QQ", buf, 120) + return struct.unpack_from("I", buf, 16)[0], sec + usec / 1e6 + try: + with open(f"/proc/{pid}/stat") as fh: + stat = fh.read() + fields = stat[stat.rindex(")") + 2:].split() + with open("/proc/stat") as fh: + boot = next(float(ln.split()[1]) for ln in fh if ln.startswith("btime")) + return int(fields[1]), boot + int(fields[19]) / os.sysconf("SC_CLK_TCK") + except (OSError, ValueError, StopIteration, IndexError): + return None -def _stamped(line: str, value: str) -> bool: - """Does a shell's command line carry `value` as its call's token, where the hook writes it: the first - DEVKIT_CALL= in it is the hook's stamp and names this value? A shell that only prints or quotes a token - elsewhere, or carries another call's, does not.""" - i = (line or "").find("DEVKIT_CALL=") - if i < 0 or not _STAMP_BEFORE.search(line[:i]): - return False - rest = line[i + len("DEVKIT_CALL="):] - if not rest.startswith(value): +def _read_pin(path): + """The pid a pin names; None when there is no pin; -1 when it holds anything but digits.""" + try: + with open(path) as fh: + text = fh.read(32) + except FileNotFoundError: + return None + except OSError: + return -1 + return int(text) if _PIN_TEXT.fullmatch(text) else -1 + + +def _write_pin(path, pid: int) -> bool: + """The dev process pins the plain form's call to `pid` itself: True when this write made the pin (O_EXCL).""" + try: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except OSError: return False - after = rest[len(value):] - return after.startswith("; readonly DEVKIT_CALL;") if line[:i].rstrip().endswith("export") else \ - after[:1] in (" ", "\t") + with os.fdopen(fd, "w") as fh: + fh.write(f"{int(pid)}\n") + return True def used_path(sid: str, tid: str): - """The mark a dev command leaves when it resolved its caller by call `tid`'s token: CALLS//..used (a - dot-file: no reader of the ledger takes it for an entry). The PostToolUse hook reads it (caller.mismatch).""" + """What the first verified use of call `tid`'s token saw: CALLS//..used (a dot-file: no reader of the + ledger takes it for an entry), {pid, start, inode} of its pin. Later uses compare with it; the PostToolUse hook + reads it (caller.mismatch, calls.pin-replaced, caller.token-unexplained-use).""" from . import progress return progress.CALLS / progress._safe_name(sid) / f".{progress._safe_name(tid)}.used" -def _mark_used(sid: str, tid: str): +def _read_used(sid: str, tid: str) -> dict: + try: + doc = json.loads(used_path(sid, tid).read_text() or "{}") + except (OSError, ValueError): + return {} + return doc if isinstance(doc, dict) else {} + + +def _mark_used(sid: str, tid: str, pid=None, start=None, inode=None): + """Record the first verified use: the pinned pid, its start time and the pin's inode (O_EXCL: the first one).""" try: - fd = os.open(used_path(sid, tid), os.O_WRONLY | os.O_CREAT, 0o600) - os.close(fd) + fd = os.open(used_path(sid, tid), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) except OSError: - pass + return + with os.fdopen(fd, "w") as fh: + fh.write(json.dumps({"pid": pid, "start": start, "inode": inode})) def _session_of(pid): @@ -756,27 +809,19 @@ def _verify(agent: str, sid: str, value: str, now, args=()) -> _Verdict: agents = [p for p, line in chain if core.is_agent_process(line)] owner = entry.get("agent_pid") above = tuple(pids[:pids.index(owner) + 1] if owner in pids else pids) - if isinstance(owner, int): - if not agents: - return _Verdict(tid, code="caller.stale-token", why=STALE, detail="no agent process runs it (detached)", - ancestors=above) - if agents[0] != owner: - return _Verdict(tid, code="caller.foreign-agent", why=FOREIGN, ancestors=above, - detail=f"its nearest agent process is {agents[0]}, its call's is {owner}") - below = pids[:pids.index(owner)] - mine = _session_of(0) - if mine is None or mine not in {_session_of(p) for p in below or [0]}: - return _Verdict(tid, code="caller.stale-token", why=STALE, ancestors=above, - detail="it runs in a process session of its own (detached)") - shell, line = _call_shell(below) - if shell is not None and not _stamped(line, value) or shell is None and not _runs_this(entry, args): - return _Verdict(tid, code="caller.token-foreign-use", why=FOREIGN_USE, ancestors=above, - detail=f"the call shell below the agent ({shell or 'none'}, of {list(below)}) does not " - f"carry this call's token where the hook writes it" if shell is not None else - f"no call shell runs it (of {list(below)}), and its call does not run this command") - _mark_used(sid, tid) - else: + if not isinstance(owner, int): # the hook could not tell which agent runs the call: no binding to a process _unpinned_once(agent, sid, tid, above) + return _Verdict(tid, code="caller.token-unpinned", why=UNPINNED, ancestors=above, + detail="its call's agent process is not known, so its token binds to no process") + if not agents: + return _Verdict(tid, code="caller.stale-token", why=STALE, detail="no agent process runs it (detached)", + ancestors=above) + if agents[0] != owner: + return _Verdict(tid, code="caller.foreign-agent", why=FOREIGN, ancestors=above, + detail=f"its nearest agent process is {agents[0]}, its call's is {owner}") + pinned = _pinned(sid, tid, entry, pids[:pids.index(owner)], above) + if isinstance(pinned, _Verdict): + return pinned if agent == "claude" and str(entry.get("host_thread") or "") != (os.environ.get(THREAD_VAR) or "").strip(): return _Verdict(tid, code="caller.foreign-agent", why=FOREIGN, ancestors=above, detail="it carries a Codex thread id its Claude Code call did not: another agent runs it") @@ -785,12 +830,66 @@ def _verify(agent: str, sid: str, value: str, now, args=()) -> _Verdict: return _Verdict(tid, code="caller.conflict", why=CONFLICT, ancestors=above, detail=f"the token names {caller}, the lane variable {lane}") if agent == "codex": - clash = _thread_evidence(agent, sid, caller, owner) + clash = _thread_evidence(agent, sid, caller, owner, tid) if clash: return _Verdict(tid, code="caller.conflict", why=CONFLICT, ancestors=above, detail=clash) return _Verdict(tid, caller=caller, ancestors=above) +def _pinned(sid: str, tid: str, entry: dict, below: list, above: tuple): + """The call's pin, checked (the module's notes on the pin): the pinned pid, or the _Verdict that refuses.""" + from pathlib import Path + + def no(code, detail, why=FOREIGN_USE): + return _Verdict(tid, code=code, why=why, ancestors=above, detail=detail) + path = Path(str(entry.get("pin") or "")) + if not entry.get("pin"): + return no("caller.token-foreign-use", "its call recorded no pin") + if Path(f"{path}.contested").exists(): + return no("calls.pin-contested", "another process wrote its call's pin first: its token names nobody") + pinned = _read_pin(path) + if pinned == -1: + return no("calls.pin-malformed", "its call's pin holds something other than a pid") + me = _pid() + if pinned is None: + if entry.get("pin_by") != "dev": + return no("caller.token-foreign-use", "its call's shell never pinned its token") + # the plain form: the call's own process, right below the agent or below the loop that launches its calls + # (its hooks' parent), which is dev itself when the shell exec'd it + own = [p for p in below if p != entry.get("launcher_pid")] + target = own[-1] if own else me + pinned = target if _write_pin(path, target) else _read_pin(path) + if not isinstance(pinned, int) or pinned < 0: + return no("calls.pin-malformed", "its call's pin could not be read") + if pinned != me and pinned not in below: + return no("caller.token-foreign-use", f"its call is pinned to process {pinned}, and this command runs in " + f"{me} below {list(below)}, not at or below it") + info = _proc(pinned) + if info is None: + return no("caller.stale-token", f"its pinned process {pinned} has exited", STALE) + parent, start = info + if parent not in (entry.get("agent_pid"), entry.get("launcher_pid")): + return no("caller.token-foreign-use", f"its pinned process {pinned} is not a call shell of the agent " + f"(its parent is {parent})") + ts, ttl = float(entry.get("ts") or 0), float(entry.get("ttl") or 0) + if start < ts - 0.001 or start > ts + max(ttl, 1.0): + return no("calls.pin-early", f"its pinned process {pinned} started at {start:.6f}, outside its call " + f"({ts:.3f} for {ttl:g} s)") + used = _read_used(sid, tid) + if used and (used.get("pid") != pinned or used.get("start") != start): + return no("caller.token-foreign-use", f"its pin named process {used.get('pid')} at its first use, and now " + f"{pinned}: another process took that pid") + if pinned != me and _session_of(0) != _session_of(pinned): + return no("caller.stale-token", "it runs in a process session of its own (detached)", STALE) + if not used: + try: + inode = os.stat(path).st_ino + except OSError: + inode = None + _mark_used(sid, tid, pinned, start, inode) + return pinned + + def _unpinned_once(agent: str, sid: str, tid: str, above: tuple): """A token whose entry names no agent process binds to its session only: audited once per session.""" from . import progress, state @@ -804,7 +903,7 @@ def _unpinned_once(agent: str, sid: str, tid: str, above: tuple): ancestors=above), agent, sid, sys.argv[1:], "flagged") -def _thread_evidence(agent: str, sid: str, caller: str, owner) -> str: +def _thread_evidence(agent: str, sid: str, caller: str, owner, tid: str = "") -> str: """A Codex call whose token holds: CODEX_THREAD_ID must not name another known thread ('' when it agrees, else the conflict). A member's verified token call records whether Codex gives members their own thread id (per-agent) or the root's (shared, which turns the root mapping off for the session for good).""" @@ -818,11 +917,13 @@ def _thread_evidence(agent: str, sid: str, caller: str, owner) -> str: if thread != caller and thread in lanes: return f"the token names {caller[:40]}, CODEX_THREAD_ID the lane {thread[:40]}" if isinstance(owner, int) and thread in (caller, sid): - _record_threads(agent, sid, "per-agent" if thread == caller else "shared") + _record_threads(agent, sid, "per-agent" if thread == caller else "shared", tid, caller) return "" -def _record_threads(agent: str, sid: str, seen: str): +def _record_threads(agent: str, sid: str, seen: str, tid: str = "", caller: str = ""): + """Record what a member's verified call showed of Codex's thread ids; "shared" is audited with that member's call + (its tid and lane), since one such call turns the root mapping off for the session.""" from . import progress, state path = progress.session_path(agent, sid) before = (state.read(path) or {}).get("codex_threads") @@ -833,8 +934,9 @@ def _record_threads(agent: str, sid: str, seen: str): except (state.StateBusy, OSError, ValueError): return if seen == "shared": - _audit_identity("codex.thread-shared", _Verdict("", detail="a member's command carries the root thread's id: " - "the root thread no longer maps to the tech lead"), + _audit_identity("codex.thread-shared", _Verdict(tid, detail=f"the command of member {caller[:80]} carries the " + f"root thread's id: the root thread no longer maps " + f"to the tech lead"), agent, sid, sys.argv[1:], "flagged") @@ -858,19 +960,32 @@ def _thread_rule(agent: str, sid: str, args: list, changes: bool, now=None) -> s "main" if thread == sid and sess.get("codex_threads") == "per-agent" else "" if not who: return "" - if changes and not any(str(c.get("caller")) == who and (_typed_exactly(c, args) or ( - progress._names_args(c, args) and not _ran_elsewhere(c, args))) for c in progress.open_calls(sid, now)): - return "" + if changes and not any(str(c.get("caller")) == who and _is_exactly(c, args) for c in progress.open_calls(sid, now)): + return "" # a state change needs the caller's own call to be this very dev command, typed alone key = ("thread", os.getpid(), agent, sid, who, tuple(args)) if key not in _NOTED: # once per command (and never again from the audit record's own lookup of its actor) _NOTED.add(key) _audit_identity("caller.thread", _Verdict("", detail=f"CODEX_THREAD_ID names {who[:40]}, and its own open " - f"call holds this command" if changes else + f"call is this very command" if changes else f"CODEX_THREAD_ID names {who[:40]} for a read"), - agent, sid, args, "allowed") + agent, sid, args, "flagged" if changes else "allowed") return who +def _is_exactly(entry: dict, args: list) -> bool: + """Is the call this one dev command and nothing else, as the shell reads it: one program, `dev` with exactly these + arguments? A call that only mentions the words (`gh pr comment … 'dev progress add x'`), runs more, or was cut + is not.""" + from . import shellparse + if entry.get("cut") or not args: + return False + try: + calls = shellparse.shell_calls(str(entry.get("cmd") or ""), None) + except Exception: + return False + return bool(calls) and len(calls) == 1 and shellparse.dev_args(calls[0][0]) == list(args) + + def _token_session(agent: str, sid: str) -> bool: """Does the hook stamp call tokens in this session (call_token in its record)?""" from . import progress, state diff --git a/tests/test_caller_identity.py b/tests/test_caller_identity.py index bf693d4a..0351d07f 100644 --- a/tests/test_caller_identity.py +++ b/tests/test_caller_identity.py @@ -571,7 +571,8 @@ def test_a_member_lane_command_is_rewritten_without_approving_it(self): hooks.run("pre-tool", "claude") spec = json.loads(out.getvalue())["hookSpecificOutput"] command = spec["updatedInput"]["command"] - self.assertTrue(command.startswith(" export DEVKIT_CALL="), command) # the call token goes in front + # no bypass mode: the plain form, the token right before dev, so the call still reads as a dev command + self.assertRegex(command, r"\ADEVKIT_FROM_AGENT=a_tank DEVKIT_CALL=toolu_r\.[A-Za-z0-9_-]{22} dev progress note x\Z") self.assertEqual(identity.strip_token(command), "DEVKIT_FROM_AGENT=a_tank dev progress note x") self.assertNotIn("permissionDecision", spec) diff --git a/tests/test_codex_identity_token.py b/tests/test_codex_identity_token.py index 286258d2..4c5aaa11 100644 --- a/tests/test_codex_identity_token.py +++ b/tests/test_codex_identity_token.py @@ -74,7 +74,9 @@ def thread(self, tid, token="", **env): class CodexStampTests(CodexTokenCase): def test_codex_rewrite_carries_call_token_when_never_asks(self): _, token, new = self.exec("git status") - self.assertTrue(new.startswith(f" export DEVKIT_CALL={token}; readonly DEVKIT_CALL; "), new) + self.assertTrue(new.startswith(" (set -C; printf"), new) # the pin's write first, then the token + self.assertIn(f"; export DEVKIT_CALL={token}; readonly DEVKIT_CALL; git status", new) + self.assertEqual(identity.strip_token(new), "git status") self.assertEqual(self.last.get("permissionDecision"), "allow") rc, out = self.lead(token) self.assertEqual(rc, 0, out) @@ -121,6 +123,21 @@ def test_codex_exec_entry_dies_at_its_yield(self): class CodexThreadTests(CodexTokenCase): never_asks = False # Codex asks: a compound command goes out as it is, with no token + def test_an_unrouted_member_lane_call_is_told_what_happens_and_that_happens(self): + self.exec("dev progress note 'half' | tail -1", aid=SUB) # Codex asks: no rewrite, no token + told = self.last.get("additionalContext") or "" + self.assertIn(hooks.UNROUTED_LANE_CALL, told) + self.assertIn("is refused rather than made as the tech lead", told) + self.assertNotIn("main session", told) + for thread in (SUB, SID): # what it says: the change is refused, in the member's lane and as the tech lead + with self.subTest(thread=thread): + rc, out = self.dev("progress", "note", "half", env=self.thread(thread)) + self.assertEqual(rc, 2, out) + run = self.run_() + self.assertEqual([u for a in (run.get("agents") or {}).values() for u in a.get("updates") or [] + if u.get("text") == "half"] + [u for u in run.get("updates") or [] if u.get("text") == "half"], + []) + def test_codex_root_thread_without_evidence_refuses_with_the_plain_call_fix(self): _, token, new = self.exec("dev progress add extra | tail -3") self.assertEqual((token, new), ("", "")) @@ -144,7 +161,7 @@ def test_codex_member_token_with_its_own_thread_turns_the_root_mapping_on(self): self.assertTrue(token) self.assertEqual(self.dev("crew", "inbox", token=token, env=self.thread(SUB))[0], 0) self.assertEqual(self.sess().get("codex_threads"), "per-agent") - self.exec("dev progress add extra | tail -3") # the tech lead's own open call holds the command + self.call("dev progress add extra", sid=SID, agent="codex") # the tech lead's own plain call, its token lost rc, out = self.lead(env=self.thread(SID)) self.assertEqual(rc, 0, out) self.assertTrue(self.added()) @@ -157,10 +174,14 @@ def test_codex_member_token_with_another_lanes_thread_is_a_conflict(self): self.assertEqual(rc, 2, out) self.assertEqual(len(self.records("caller.conflict")), 1) - def test_codex_compound_command_uses_the_thread_rule_for_a_lane(self): + def test_codex_compound_command_gets_the_plain_call_fix_and_a_lanes_own_plain_call_its_lane(self): _, token, new = self.exec("dev progress note 'api half done' | tail -1", aid=SUB) self.assertEqual(token, "") rc, out = self.dev("progress", "note", "api half done", env=self.thread(SUB)) + self.assertEqual(rc, 2, out) # a compound call proves nothing about which thread runs the dev command + self.assertIn("run it as one plain dev command", out) + self.call("dev progress note 'api half done'", aid=SUB, sid=SID, agent="codex") # its plain call, no token + rc, out = self.dev("progress", "note", "api half done", env=self.thread(SUB)) self.assertEqual(rc, 0, out) self.assertIn("api half done", [u.get("text") for u in self.run_()["agents"][SUB].get("updates") or []]) diff --git a/tests/test_hooks_wiring.py b/tests/test_hooks_wiring.py index e0f35b98..ad40a611 100644 --- a/tests/test_hooks_wiring.py +++ b/tests/test_hooks_wiring.py @@ -238,7 +238,8 @@ def test_a_members_routed_progress_call_still_routes_when_its_lessons_fail(self) spec = json.loads(out)["hookSpecificOutput"] self.assertNotIn("permissionDecision", spec) command = spec["updatedInput"]["command"] - self.assertTrue(command.startswith(" export DEVKIT_CALL="), out) # the call token goes in front + # no bypass mode in the payload: the plain form, the token right before dev + self.assertRegex(command, r"\ADEVKIT_FROM_AGENT=a_tank DEVKIT_CALL=toolu_1\.[A-Za-z0-9_-]{22} dev progress step ") self.assertTrue(identity.strip_token(command).startswith("DEVKIT_FROM_AGENT=a_tank dev progress step"), out) diff --git a/tests/test_identity_redteam.py b/tests/test_identity_redteam.py index 0824f12f..e7a31fe6 100644 --- a/tests/test_identity_redteam.py +++ b/tests/test_identity_redteam.py @@ -7,8 +7,12 @@ # tests.test_identity_token's (Claude Code) and tests.test_codex_identity_token's (Codex 0.167 exec payloads). # Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). # Run: python3 -m unittest tests.test_identity_redteam -v +import json import os +import subprocess import sys +import tempfile +import time import unittest from pathlib import Path from unittest import mock @@ -20,10 +24,11 @@ _hermetic.activate() sys.path.insert(0, str(ROOT / "lib")) -from devkit import core, identity # noqa: E402 +from devkit import core, hooks, identity # noqa: E402 from devkit import progress as pg # noqa: E402 from test_codex_identity_token import SID, SUB, SUB2, CodexTokenCase # noqa: E402 -from test_identity_token import AGENT, INNER, NESTED, TokenCase # noqa: E402 +from test_identity_token import AGENT, INNER, NESTED, TOKEN, TokenCase # noqa: E402 +from test_pre_tool_hook import TANK, PreToolCase # noqa: E402 from test_progress import launch # noqa: E402 NPX_CODEX = "node /Users/u/.npm/_npx/9f/node_modules/.bin/codex exec review" @@ -68,7 +73,7 @@ def test_a_member_forging_another_lanes_thread_cannot_close_its_step(self): def test_the_thread_rule_takes_a_lane_only_with_its_own_open_call_and_audits_it(self): self.never_asks = False - self.exec("dev progress note 'api half done' | tail -1", aid=SUB) # the member's own open call + self.call("dev progress note 'api half done'", aid=SUB, sid=SID, agent="codex") # its own plain call rc, out = self.dev("progress", "note", "api half done", env=self.thread(SUB)) self.assertEqual(rc, 0, out) self.assertEqual(len(self.records("caller.thread")), 1) @@ -138,5 +143,344 @@ def parents_of(self, token): return self.parents() +class ClaudeCallPinTests(TokenCase): + # the retest of 2026-11-19: a command line proves nothing about which call a process belongs to; the pid the + # call's shell pinned as its first action does + def stolen(self, lead="pytest -q tests"): + if not self.run_(): + self.plan_with_link() + _, token, _ = self.hook(lead) # the tech lead's call runs no dev command yet + self.hook("exec python3 do.py", aid="a_link") # the member's call shell becomes python + return token, self.shell + + def refused(self, token): + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.token-foreign-use")), 1) + + def test_a_dev_exec_d_by_the_member_cannot_run_the_tech_leads_pending_command(self): + for lead in ("pytest -q && dev progress add extra", + 'pytest -q && for s in $(cat todo.txt); do dev progress add "$s"; done'): + with self.subTest(lead=lead): + token, member = self.stolen(lead) + self.own_pid, self.chain = member, [(AGENT, "claude")] # dev took the member's shell pid + self.refused(token) + self.tearDown_records() + + def test_the_tech_leads_own_uses_resolve_main(self): + self.plan_with_link() + ref = pg.crew_ask("Report: " + "x" * 400, from_agent="a_link")["id"] + data, token, _ = self.hook(f'dev crew ack {ref} --sha256 "$(dev crew read {ref} --json | jq -r .digest)" ' + f'--generation 1; python3 tools/report.py; dev progress add extra') + shell = self.shell + for chain in ([(shell, ""), (AGENT, "claude")], # a dev call of its own + [(73001, "zsh"), (shell, ""), (AGENT, "claude")], # the $(…) subshell's dev + [(73002, "python3 tools/report.py"), (shell, ""), (AGENT, "claude")]): # a script run by path + with self.subTest(chain=chain): + self.chain = chain + self.assertEqual(self.speak(token).lane, "main") + identity._forget() + self.own_pid, self.chain = shell, [(AGENT, "claude")] # the shell exec'd its last command: dev is its pid + rc, out = self.lead(token) + self.assertEqual(rc, 0, out) + + def test_an_unpinned_entry_is_no_bearer_token(self): + self.plan_with_link() + with mock.patch.object(hooks, "_hook_launched_by", lambda pid: False): + _, token, _ = self.hook("pytest -q tests") # no agent pid in its entry + self.hook("python3 do.py", aid="a_link") + self.chain = [(self.shell, ""), (AGENT, "claude")] + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.own_pid, self.chain = 79002, [] # a detached process, reparented + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertEqual([r["ref"]["result"] for r in self.records("caller.token-unpinned")][-1:], ["deny"]) + + def test_an_unpinned_call_changes_nothing_even_from_its_own_shell_and_still_reads(self): + self.plan_with_link() + ref = pg.crew_ask("Report: " + "x" * 400, from_agent="a_link")["id"] + with mock.patch.object(hooks, "_hook_launched_by", lambda pid: False): + _, token, _ = self.hook(f"dev progress add extra; dev crew read {ref} --json") + rc, out = self.lead(token) # its own text, its own shell: no process binds the token + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + rc, out = self.dev("crew", "read", ref, "--json", token=token) # a read falls to the ledger's rules + self.assertEqual(rc, 0, out) + + def test_a_tech_lead_call_running_no_dev_whose_token_another_process_used_is_audited(self): + self.plan_with_link() + data, token, new = self.hook("pytest -q tests") + identity._mark_used("s1", data["tool_use_id"]) # a dev command resolved through its token + self.closed(data) + found = self.records("caller.token-unexplained-use") + self.assertEqual(len(found), 1) + self.assertEqual(found[0]["ref"]["result"], "flagged") + + def tearDown_records(self): + # the next subtest's own call and records: a fresh plan and audit + from devkit import audit as audit_module + for f in audit_module.AUDIT.glob("*.jsonl") if audit_module.AUDIT.exists() else []: + f.unlink() + self.chain, self.own_pid = None, 71999 + with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): + run = pg.load_run("claude", "s1") + run["plan"] = [s for s in run["plan"] if s["name"] != "extra"] + pg._save(run) + + +class ClaudePermissionModeTests(TokenCase): + # outside bypassPermissions Claude Code checks its allow rules on the rewritten command: the token goes only on + # calls that visibly run dev, and devkit never writes or advises an allow rule for export + def mode(self, cmd, mode): + _, token, new = self.hook(cmd, permission_mode=mode) + return token, new, json.dumps(self.last) + + def test_bypass_stamps_every_call(self): + token, new, _ = self.mode("git status", "bypassPermissions") + self.assertTrue(token) + + def test_default_and_accept_edits_stamp_only_visible_dev_calls(self): + for mode in ("default", "acceptEdits", "plan"): + with self.subTest(mode=mode): + token, new, out = self.mode("git status", mode) + self.assertEqual((token, new), ("", "")) + token, new, out = self.mode("dev crew inbox 2>&1 | tail -5", mode) # visible, but not plain + self.assertEqual(token, "") + token, new, out = self.mode("dev crew inbox", mode) + self.assertTrue(new.startswith(f"DEVKIT_CALL={token} dev crew inbox") or + f" DEVKIT_CALL={token} dev crew inbox" in new, new) + self.assertNotIn("set -C", new) # dev pins the plain form itself: no redirect outside the project + self.assertNotIn("export:", out) + self.assertNotIn("Bash(export", out) + + +class CodexCallPinTests(CodexTokenCase): + def test_a_second_exec_d_use_of_a_plain_calls_token_is_refused(self): + self.never_asks = False + _, token, new = self.exec("dev progress add extra") # one plain call: the variable-list form, dev pins + self.assertNotIn("set -C", new) + self.own_pid, self.chain = 74001, [(self.agent_pid, "codex")] # the shell exec'd dev + self.assertEqual(self.dev("progress", "note", "first", token=token)[0], 0) + self.own_pid = 74002 # another process with the same token + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + + def test_a_plain_call_below_the_agents_launch_loop_pins_its_own_process(self): + self.never_asks, loop = False, 74100 + with mock.patch.object(hooks.os, "getppid", lambda: loop): # the loop that starts the agent's hooks and calls + data, token, _ = self.exec("dev progress add extra") + self.starts[loop] = time.time() - 600 # it runs for the agent's whole life + self.parent_of.update({74001: loop, loop: self.agent_pid}) + self.own_pid, self.chain = 74001, [(loop, "python3"), (self.agent_pid, "codex")] # the shell exec'd dev + rc, out = self.lead(token) + self.assertEqual(rc, 0, out) + self.assertTrue(self.added()) + self.assertEqual(identity._read_pin(identity.pin_path(SID, data["tool_use_id"])), 74001) + + +class CodexAskingThreadTests(CodexTokenCase): + never_asks = False + + def per_agent(self): + _, token, _ = self.exec("dev crew inbox", aid=SUB) + self.dev("crew", "inbox", token=token, env=self.thread(SUB)) + self.assertEqual(self.sess().get("codex_threads"), "per-agent") + + def test_a_thread_claim_on_a_compound_or_mentioning_call_is_refused(self): + self.per_agent() + for lead in ("dev ci --run && dev progress add extra", "gh pr comment 5 --body 'next: dev progress add extra'", + 'echo "dev progress add extra"'): + with self.subTest(lead=lead): + self.exec(lead) + self.exec("python3 x.py; true", aid=SUB) + rc, out = self.lead(env=self.thread(SID)) + self.assertEqual(rc, 2, out) + self.assertIn("run it as one plain dev command", out) + self.assertFalse(self.added()) + + def test_a_forged_lane_thread_cannot_close_a_step_its_compound_call_holds(self): + with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): + pg.assign("ui", "Trinity", why="the test's assignment") + launch(SUB2, "trinity", "Trinity: ui", sid=SID, agent="codex") + self.exec("npm test && dev progress step 'ui done' --step ui --check '✓ 40 tests'", aid=SUB2) + self.exec("python3 x.py; true", aid=SUB) + rc, out = self.dev("progress", "step", "ui done", "--step", "ui", "--check", "✓ 40 tests", + env=self.thread(SUB2)) + self.assertEqual(rc, 2, out) + self.assertEqual(next(s for s in self.run_()["plan"] if s["name"] == "ui")["state"], "running") + + def test_a_state_change_by_the_thread_rule_is_flagged(self): + self.exec("dev progress note 'api half done'", aid=SUB) # its plain call, whose token was not used + rc, out = self.dev("progress", "note", "api half done", env=self.thread(SUB)) + self.assertEqual(rc, 0, out) + self.assertEqual([r["ref"]["result"] for r in self.records("caller.thread")], ["flagged"]) + + def test_the_thread_shared_record_names_the_member_and_its_call(self): + data, token, _ = self.exec("dev crew inbox", aid=SUB) + self.dev("crew", "inbox", token=token, env=self.thread(SID)) + found = self.records("codex.thread-shared") + self.assertEqual(len(found), 1) + self.assertEqual(found[0]["crew"]["tool_use_id"], data["tool_use_id"]) + self.assertIn(SUB, found[0]["detail"]) + + +class PinRaceTests(TokenCase): + # the pin is written after the shell sourced its snapshot or login profile: a member polling ps may write it first + def test_a_pin_naming_a_shell_older_than_the_call_is_refused(self): + self.plan_with_link() + _, token, _ = self.hook("pytest -q tests") + self.starts[self.shell] = time.time() - 30 # the member's own long-running shell won the race + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertEqual(len(self.records("calls.pin-early")), 1) + + def test_a_contested_call_names_nobody(self): + self.plan_with_link() + _, token, _ = self.hook("pytest -q tests") + tid = identity.parse_token(token)[0] + pin = identity.pin_path("s1", tid) + pin.with_name(pin.name + ".contested").write_text("") # the victim's write found a pin already there + for chain in (None, [(79003, "zsh"), (AGENT, "claude")]): + with self.subTest(chain=chain): + self.chain = chain + self.assertEqual(self.lead(token)[0], 2) + self.assertEqual(len(self.records("calls.pin-contested")), 2) + + def test_a_malformed_pin_fails_closed(self): + self.plan_with_link() + data, token, _ = self.hook("pytest -q tests") + identity.pin_path("s1", data["tool_use_id"]).write_text("72001; rm -rf ~\n") + self.assertEqual(self.lead(token)[0], 2) + self.assertEqual(len(self.records("calls.pin-malformed")), 1) + + def test_a_pin_written_again_later_is_audited_when_the_call_ends(self): + self.plan_with_link() + data, token, _ = self.hook("dev progress add extra") + self.assertEqual(self.lead(token)[0], 0) # its first use records the pin's inode + pin = identity.pin_path("s1", data["tool_use_id"]) + pin.unlink() + pin.write_text(f"{self.shell}\n") # deleted and written again: another file + self.closed(data) + self.assertEqual(len(self.records("calls.pin-replaced")), 1) + + def test_fish_gets_no_shell_pin_and_its_plain_call_pins_from_dev(self): + with mock.patch.object(hooks, "_sh_family", lambda agent, data: False): + _, token, new = self.hook("git status") + self.assertEqual((token, new), ("", "")) + data, token, new = self.hook("dev crew inbox") + self.assertNotIn("set -C", new) + self.own_pid, self.chain = self.shell, [(AGENT, "claude")] # fish ran dev as its own process + self.assertEqual(self.dev("crew", "inbox", token=token)[0], 0) + self.assertEqual(identity._read_pin(identity.pin_path("s1", data["tool_use_id"])), self.shell) + + +class PinFolderTests(TokenCase): + def test_a_link_planted_where_the_pin_folder_goes_gets_no_token(self): + target = self.root / "elsewhere" + target.mkdir() + folder = identity.pin_path("s1", "x").parent + folder.parent.mkdir(parents=True, exist_ok=True) + folder.symlink_to(target) # the pins would land where its planter reads and writes + _, token, new = self.hook("pytest -q tests") + self.assertEqual((token, new), ("", "")) + self.assertEqual(list(target.iterdir()), []) + self.assertEqual(len(self.records("calls.token-skipped")), 1) + + +class ShellFormTests(unittest.TestCase): + # the stamp's first action, run by the real shells: the shell's own pid in the pin, noclobber off afterwards, an + # earlier pin left alone and the call marked contested + def run_stamp(self, shell, setup=""): + with tempfile.TemporaryDirectory() as d: + pin = Path(d) / "pins dir" / "t.pin" # a folder with a space: the path is quoted + pin.parent.mkdir() + script = f"{setup}{identity.pin_stamp(pin)}echo $$; echo x > {d}/f; echo y > {d}/f && echo clobber-ok" + out = subprocess.run([shell, "-c", script], capture_output=True, text=True, timeout=10) + first = (out.stdout.split()[0], identity._read_pin(pin), "clobber-ok" in out.stdout, out.stderr) + again = subprocess.run([shell, "-c", identity.pin_stamp(pin) + "true"], capture_output=True, text=True, + timeout=10) + return first, identity._read_pin(pin), pin.with_name("t.pin.contested").exists(), again.stderr + + def test_sh_bash_and_zsh_pin_their_own_pid_and_leave_noclobber_off(self): + for shell, setup in (("/bin/sh", ""), ("/bin/bash", ""), ("/bin/zsh", ""), ("/bin/zsh", "setopt clobber; "), + ("/bin/zsh", "setopt clobber_empty 2>/dev/null; ")): + with self.subTest(shell=shell, setup=setup): + (pid, pinned, clobber_ok, err), after, contested, err2 = self.run_stamp(shell, setup) + self.assertEqual(int(pid), pinned) + self.assertTrue(clobber_ok) # the user's own redirects still overwrite + self.assertEqual((err, err2), ("", "")) + self.assertEqual(after, pinned) # a second write leaves the first pin + self.assertTrue(contested) + + +class RealProcessTheftTests(PreToolCase): + # Claude Code's process shapes, with real processes below an agent stand-in: the tech lead's long call is + # running, and a member that read its token from ps tries each trick from its own call + def lead_call(self, s, cmd): + c = s.begin(cmd) + token = TOKEN.search(c["ran"]).group(1) + rid = s.host.send(["/bin/bash", "-c", c["ran"]], s.repo, env=dict(s.exports)) + entry = json.loads((s.mac.state / "calls" / s.sid / f"{c['call']['tool_use_id']}.json").read_text()) + pin, end = Path(entry.get("pin") or s.repo / "no-pin"), time.time() + (20 if entry.get("pin") else 1) + while not pin.exists() and time.time() < end: # the call's shell writes it as its first action + time.sleep(0.05) + return c, token, rid + + def plan(self, s): + return [st["name"] for st in s.run_doc()["plan"]] + + def test_each_trick_with_a_stolen_token_is_refused(self): + self.steal("claude", "devkit:tank") + + def test_each_trick_with_a_stolen_codex_token_is_refused(self): + self.codex_policy("never") # every call stamped, its shell pins it + self.steal("codex", "tank") + + def steal(self, agent, member_type): + s = self.lead_on(agent) + (s.repo / "todo.txt").write_text("") + # the tech lead's call will run `dev progress add ` later: any such command matches its text + c, token, rid = self.lead_call(s, 'sleep 6; for s in $(cat todo.txt); do dev progress add "$s"; done') + payload = s.repo / "payload.sh" + + def forged(n): # the stamp where the hook writes it, first in the shell's script; the member's lane dropped + return f" export DEVKIT_CALL={token}; readonly DEVKIT_CALL; unset DEVKIT_FROM_AGENT; dev progress add stolen{n}" + payload.write_text(forged(3)) + tricks = (f"exec {sys.executable} -I -c \"import subprocess; subprocess.run(['/bin/zsh', '-c', '{forged(1)}'])\"", + f"exec -a '/bin/zsh -c {forged(2)}' /bin/zsh -c '{forged(2)}'", + f"exec /bin/zsh -c \"$(cat {payload})\"", + f"/usr/bin/time /bin/zsh -c '{forged(4)}'") + for n, trick in enumerate(tricks, 1): + with self.subTest(trick=trick[:40]): + s.sh(trick, member=TANK, member_type=member_type) + self.assertNotIn(f"stolen{n}", self.plan(s)) + self.done(s, c, rid) + self.assertEqual(len(self.audit("caller.token-foreign-use")), len(tricks)) + + @staticmethod + def done(s, c, rid) -> dict: + r = s.host.wait(rid) + c.update(rc=r["rc"], out=r["out"], err=r["err"]) + return s.finish(c) + + def test_the_tech_leads_own_uses_resolve_main(self): + s = self.lead_on("claude") + script = s.repo / "lead.sh" + script.write_text("#!/bin/sh\ndev progress add by-script\n") + script.chmod(0o755) + c, token, rid = self.lead_call(s, f"dev progress add one; dev progress note two | tail -1; " + f"X=$(dev progress add three); {script}; dev progress add four & wait") + r = self.done(s, c, rid) + self.assertEqual(r["rc"], 0, r["err"]) + s.ok("progress", "add", "exec-d") # one plain call: its shell runs dev as its last command + for name in ("one", "three", "by-script", "four", "exec-d"): + with self.subTest(name=name): + self.assertIn(name, self.plan(s)) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_identity_token.py b/tests/test_identity_token.py index bc23cd99..43236fd5 100644 --- a/tests/test_identity_token.py +++ b/tests/test_identity_token.py @@ -15,7 +15,9 @@ import json import os import re +import shlex import sys +import time import unittest from pathlib import Path from unittest import mock @@ -47,22 +49,32 @@ def setUp(self): super().setUp() identity._forget() self.addCleanup(identity._forget) - # Each shell call runs in a shell of its own right below the agent process, whose command line holds the - # command as the hook rewrote it (the shells map). A dev command runs below the shell of the call whose token - # it carries, unless a test sets `chain` to the parents it runs below instead. + # Each shell call runs in a shell of its own right below the agent process (the shells map); a stamped one + # writes its pid to the call's pin as its first action, as the stamp makes it. A dev command runs below the + # shell of the call whose token it carries, unless a test sets `chain` to the parents it runs below instead. + # Every process started after the call opened (starts), in one process session (own_session for this one). self.chain = None self.shells, self.lines = {}, {SHELL: "/bin/zsh -c source snapshot && eval 'pytest'", SIBLING: "zsh"} - self.own_session = None # the process session the dev command runs in: by default its nearest shell's + self.own_session = None + self.own_pid, self.starts, self.parent_of = 71999, {}, {} for p in (mock.patch.object(pg, "_call_agent_pid", lambda: self.agent_pid), mock.patch.object(hooks, "_hook_launched_by", lambda pid: pid == self.agent_pid, create=True), mock.patch.object(identity, "_chain", self.parents), - mock.patch.object(identity, "_command_line", lambda pid: self.lines.get(pid, ""), create=True), - mock.patch.object(identity, "_session_of", lambda pid: ( - self.own_session or (self.parents()[0][0] if self.parents() else 1)) if pid == 0 else pid)): + mock.patch.object(identity, "_pid", lambda: self.own_pid, create=True), + mock.patch.object(identity, "_proc", self.proc, create=True), + mock.patch.object(identity, "pin_dir", lambda: self.root / "pins", create=True), + mock.patch.object(identity, "_session_of", lambda pid: (self.own_session or 1) if pid == 0 else 1)): p.start() self.addCleanup(p.stop) (hooks.STATE / "logs").mkdir(parents=True, exist_ok=True) + def proc(self, pid): + # the kernel's facts on a process: its parent (the agent, for a call shell) and its start time (after its call + # opened, unless a test says otherwise); None once it exited + if pid in self.starts and self.starts[pid] is None: + return None + return self.parent_of.get(pid, self.agent_pid), self.starts.setdefault(pid, time.time()) + def parents(self) -> list: if self.chain is not None: return list(self.chain) @@ -86,10 +98,11 @@ def added(self): return "extra" in [s["name"] for s in self.run_()["plan"]] # the PreToolUse hook on a shell call, in-process -> (payload, its token or "", the command as rewritten) - def hook(self, cmd, aid=None, sid="s1", tool="Bash", key="command", **inp): + def hook(self, cmd, aid=None, sid="s1", tool="Bash", key="command", permission_mode="bypassPermissions", **inp): self.n += 1 data = {"session_id": sid, "tool_use_id": f"toolu_{self.n:04d}", "tool_name": tool, - "hook_event_name": "PreToolUse", "tool_input": {key: cmd, **inp}, "cwd": str(self.root)} + "hook_event_name": "PreToolUse", "tool_input": {key: cmd, **inp}, "cwd": str(self.root), + "permission_mode": permission_mode} if aid: data["agent_id"] = aid out = io.StringIO() @@ -103,6 +116,12 @@ def hook(self, cmd, aid=None, sid="s1", tool="Bash", key="command", **inp): self.lines[shell] = self.shell_line(new or cmd) self.shells[found.group(1) if found else f"none-{self.n}"] = shell self.shell = shell + if found and "set -C; printf" in new: # the stamp's first action: the shell pins its pid (noclobber) + pin = identity.pin_path(sid, data["tool_use_id"]) + if pin.exists(): + pin.with_name(pin.name + ".contested").write_text("") + else: + pin.write_text(f"{shell}\n") return data, (found.group(1) if found else ""), new def closed(self, data, event="PostToolUse"): @@ -132,7 +151,11 @@ def records(self, action): class StampTests(TokenCase): def test_every_main_shell_call_gets_a_readonly_token_whose_hash_its_entry_holds(self): data, token, new = self.hook("git status") - self.assertTrue(new.startswith(f" export DEVKIT_CALL={token}; readonly DEVKIT_CALL; git status"), new) + pin = identity.pin_path("s1", data["tool_use_id"]) + self.assertEqual(new, f" (set -C; printf '%s\\n' \"$$\" > {shlex.quote(str(pin))}) 2>/dev/null || " + f"(: > {shlex.quote(str(pin) + '.contested')}) 2>/dev/null; export DEVKIT_CALL={token}; " + f"readonly DEVKIT_CALL; git status") + self.assertEqual(identity.strip_token(new), "git status") tid, nonce = identity.parse_token(token) entry = pg.call_entry(data) self.assertEqual(tid, data["tool_use_id"]) @@ -244,12 +267,16 @@ def test_a_use_from_a_sibling_shell_is_refused_and_the_calls_own_shell_still_res def test_a_shell_pid_the_system_gave_to_another_process_is_refused(self): self.plan_with_link() _, token, _ = self.hook("dev progress begin ci-redirect") - self.assertEqual(self.speak(token).lane, "main") - self.lines[self.shell] = "/bin/zsh -c vim notes.md" # the call's shell ended and its pid runs another one + self.starts[self.shell] = time.time() + 1 + self.assertEqual(self.speak(token).lane, "main") # its first use records the pid's start time + self.starts[self.shell] += 5 # the call's shell ended and its pid went to a newer process rc, out = self.lead(token) self.assertEqual(rc, 2, out) self.assertFalse(self.added()) self.assertEqual(len(self.records("caller.token-foreign-use")), 1) + self.starts[self.shell] = None # and once the pinned process exited, the token is stale + self.assertEqual(self.lead(token)[0], 2) + self.assertEqual(len(self.records("caller.stale-token")), 1) def test_a_detached_process_holding_a_live_token_changes_nothing_but_may_read(self): self.plan_with_link() @@ -389,9 +416,13 @@ def test_no_devkit_file_holds_the_nonce_after_a_stamped_call(self): tool_input={"command": new}, tool_response={"stdout": "ok", "exit_code": 0})) self.assertIn(nonce, new) + self.assertIn("set -C", new) held = [str(f.relative_to(self.root)) for f in self.root.rglob("*") if f.is_file() and nonce.encode() in f.read_bytes()] self.assertEqual(held, []) + stamped = [str(f.relative_to(self.root)) for f in self.root.rglob("*") if f.is_file() + and (b"set -C" in f.read_bytes() or b"readonly DEVKIT_CALL" in f.read_bytes())] + self.assertEqual(stamped, []) # every stored command text is the one the agent typed self.assertEqual(audit.redact(f"x DEVKIT_CALL={token} y"), "x DEVKIT_CALL=…[redacted] y") def test_malformed_tokens_are_rejected_before_any_file_read(self): From 0984d8cd273abd0a8a6419f566602ff504e2a844 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 22:19:21 -0800 Subject: [PATCH 39/52] docs(crew): say how the call token is pinned to its process the token is bound to the process its call pins, and an unplaced lane call's state change is refused; the guides still described a shell binding and a fallback to the main session Verified: dev docs check on the four pages: 0 issues, all links resolve --- SECURITY.md | 4 ++-- docs/agents.md | 2 +- docs/crew.md | 7 +++++-- docs/troubleshooting.md | 5 ++--- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 9566b30a..d41e10fc 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -41,8 +41,8 @@ To limit what agents can do, use the controls that do enforce limits: ### What the call token protects devkit names who runs each `dev` command by a call token: the pre-tool hook puts `DEVKIT_CALL` in front of the call, -and the token holds only for the shell the agent ran the call in, and its child processes, and only while the call is -open (see [The crew › Who is calling](docs/crew.md#who-is-calling)). It protects against mistakes and makes misuse +and the token holds only for the process whose id the call's prefix pins first (or the `dev` process of a single +plain call) and the processes below it, and only while the call is open (see [The crew › Who is calling](docs/crew.md#who-is-calling)). It protects against mistakes and makes misuse visible: - **Mix-ups between callers.** A crew member's command is never taken as the tech lead's, or as another member's: diff --git a/docs/agents.md b/docs/agents.md index 6d82a434..ed9502fd 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -240,7 +240,7 @@ works from the Desktop and ChatGPT apps, whose PATH is minimal. | --- | --- | --- | --- | | SessionStart | `startup\|resume\|clear\|compact`, 30 s | `startup\|resume\|clear\|compact`, 30 s | Records the session's starting commit and branch, refreshes the project's generated blocks, exports `DEVKIT_SESSION` (Claude), restores managed settings in the background, clones `node_modules` into a fresh worktree, queues a sync that pulls the claims of other machines, and prints the workspace context. Shows you the [welcome](concepts.md#the-session-start-welcome) as its `systemMessage`, on both agents (at most five lines: what needs you, what runs, what is next, and where you are), and tells the model which lines you saw; the notices about an older devkit copy and extensions become need lines in it, and a headless run, a crew member's session, or a scratch repository gets none. The context stays under both agents' limits on a hook's output (at most 9,000 bytes: past 10,000 characters Claude Code shows the model a 2,000-character preview, and Codex past about 2,500 tokens), with what matters most first, so a cut takes the end, the handoff note's excerpt, at whole lines. In a project, it carries an index of the kinds of work the agent declares by id, with the lesson anchors and where the rest is (`dev crew raci`, `dev crew rules`, and `config/skill-rules.json` for the skills); the three most relevant known pitfalls; and the handoff note's path, Now tasks, and current state. After a compaction or a resume, the continuity brief comes first, after the line about the welcome you saw: the run and its current step, the crew working now (not to relaunch), the decisions and messages waiting, your latest requests verbatim, the last status block and git, at most 4 KB. After `/clear`, a notice of the previous session's open run and `dev session carry` | | UserPromptSubmit | 10 s | 10 s | Starts the turn clock, except for a message you type while the agent works, which Claude Code sends with the running turn's `prompt_id` and Codex with the running turn's `turn_id`: devkit keeps that turn and its request, and adds the message beside them once, even when the transcript or rollout reports it again at a later hook; gives the agent a short reminder of the presentation rules the final message of its last development turn missed (the status block, a role, the Progress line with the run's current counts, the reply language), recorded by Stop instead of sending that turn back, tells it to follow them when this turn is development work, and not to rewrite or repeat that reply. The reminder comes with your prompts only, never with a background notification or a message typed mid-turn, and again at each one until a turn that Stop classes as development work ends after it; adds real progress records and the branch's CI/CD pipelines when you ask for status; reminds the tech lead to declare the request's kinds of work by their ids from the catalog and route each by the RACI, the same reminder in every language and never a guess from the request's words (`crew.route_hint` turns it off); reminds the agent of the status block in a session that already missed it once, naming the failure mode (nothing comes before the block); registers a session that missed SessionStart and injects its context, catalog included. When decisions wait for you that you have not seen since your last prompt, tells the tech lead once per batch to ask them together in as few question calls as the rules allow (see [The crew › How the tech lead asks you](crew.md#how-the-tech-lead-asks-you)). It does not read your prompt for corrections or for skills. Background notifications (subagent results, system notices) and relayed comments are not treated as your request. Keeps your prompt, redacted and cut to 1,000 characters, as pending in the session's continuity checkpoint until Stop classes the turn, and gives the main session, once and first, what waits for it: the brief of a compaction only the transcript showed, or "Not in the summary." A prompt that wakes the session for a background event (a task notification, an agent message) also carries what waits for it: crew questions, decisions, ready steps, CI results, and notices | -| PreToolUse | `Bash\|Monitor\|Write\|Edit\|MultiEdit\|NotebookEdit\|Agent\|Task\|WebFetch\|mcp__.*`, 15 s | `^(Bash\|apply_patch\|spawn_agent)$`, 15 s | `dev hook pre-tool` (`dev hook guard`, its earlier name, still runs it for sessions started before the update). It never refuses a call or asks you about one: its output is nothing, context for the call, or the command rewritten to carry its call token and, for a crew member, its lane. On Codex, which reads no PreToolUse context, a member gets the advice as a devkit notice at its next PostToolUse, and a rewrite carries `allow` only when Codex's approval policy is `never`, or for one plain `dev progress`, `dev crew`, `dev watch`, or `dev session` call with nothing the shell would expand; otherwise the call is not rewritten and the member is told. Starts the call's timer, records each shell call with the agent that made it (the call ledger), and puts the call token in front of it, which tells devkit [who is calling](crew.md#who-is-calling): every shell call carries it in Claude Code's `bypassPermissions` mode and under Codex's `never` approval policy; elsewhere only a call that visibly runs `dev` does, so you get no more permission prompts than before. On a Claude Code subagent launch (Agent, Task), records its description for its lane and appends the required skills, the known pitfalls, and the report format to the brief. Before that, a crew member's launch whose description names none of the member's steps gets the name of the one step that waits for its launch, so the launch binds it, and the tech lead is told; with two or more waiting, or two or more named equally, the tech lead gets the exact description that takes each. A follow-up launch that names one of the member's steps that is already done is left unchanged. Codex fires no PreToolUse for `spawn_agent`: a Codex launch is recorded at SubagentStart (see below the table). A Codex `exec_command` is read by its `cmd` in its `workdir`, like Bash's `command`. Inside a subagent (the input carries `agent_id`), routes a single `dev progress` or `dev crew` command to that subagent's lane. Adds one line of advice to the call's context for a write outside a member's file scope or by a read-only member, a launch past the crew's slots, an edit of a file a working member holds, a lane call it cannot route (which runs as the main session), and a commit that would take untracked unfinished work. Names the open [lessons](lessons.md) anchored on the command the call runs or the file it writes, each at most once an hour per agent, and adds the lesson of each matching [lesson rule](lessons.md#lesson-rules). Codex does not read a call's context, so there a rule's lesson is not counted as shown. When the hook itself fails, it logs the error and the call runs | +| PreToolUse | `Bash\|Monitor\|Write\|Edit\|MultiEdit\|NotebookEdit\|Agent\|Task\|WebFetch\|mcp__.*`, 15 s | `^(Bash\|apply_patch\|spawn_agent)$`, 15 s | `dev hook pre-tool` (`dev hook guard`, its earlier name, still runs it for sessions started before the update). It never refuses a call or asks you about one: its output is nothing, context for the call, or the command rewritten to carry its call token and, for a crew member, its lane. On Codex, which reads no PreToolUse context, a member gets the advice as a devkit notice at its next PostToolUse, and a rewrite carries `allow` only when Codex's approval policy is `never`, or for one plain `dev progress`, `dev crew`, `dev watch`, or `dev session` call with nothing the shell would expand; otherwise the call is not rewritten and the member is told. Starts the call's timer, records each shell call with the agent that made it (the call ledger), and puts the call token in front of it, which tells devkit [who is calling](crew.md#who-is-calling): every shell call carries it in Claude Code's `bypassPermissions` mode and under Codex's `never` approval policy; elsewhere only a call that visibly runs `dev` does, so you get no more permission prompts than before. On a Claude Code subagent launch (Agent, Task), records its description for its lane and appends the required skills, the known pitfalls, and the report format to the brief. Before that, a crew member's launch whose description names none of the member's steps gets the name of the one step that waits for its launch, so the launch binds it, and the tech lead is told; with two or more waiting, or two or more named equally, the tech lead gets the exact description that takes each. A follow-up launch that names one of the member's steps that is already done is left unchanged. Codex fires no PreToolUse for `spawn_agent`: a Codex launch is recorded at SubagentStart (see below the table). A Codex `exec_command` is read by its `cmd` in its `workdir`, like Bash's `command`. Inside a subagent (the input carries `agent_id`), routes a single `dev progress` or `dev crew` command to that subagent's lane. Adds one line of advice to the call's context for a write outside a member's file scope or by a read-only member, a launch past the crew's slots, an edit of a file a working member holds, a lane call it cannot route (a state change there is refused, never made as the main session), and a commit that would take untracked unfinished work. Names the open [lessons](lessons.md) anchored on the command the call runs or the file it writes, each at most once an hour per agent, and adds the lesson of each matching [lesson rule](lessons.md#lesson-rules). Codex does not read a call's context, so there a rule's lesson is not counted as shown. When the hook itself fails, it logs the error and the call runs | | PostToolUse | `Bash\|Agent\|Task\|TaskStop\|Monitor\|Write\|Edit\|MultiEdit\|WebFetch\|WebSearch\|AskUserQuestion\|SendMessage`, 10 s | `^(Bash\|apply_patch)$`, 10 s | Closes the shell call in the call ledger. Records every Write, Edit, and MultiEdit call with its file, its caller, and its time: a file that changed during a read-only member's shell call is credited only to the member whose own edit call touched it, and any other such file is held against the read-only member. Ends the lane of an agent TaskStop stopped (it fires no SubagentStop): its slot frees and its step waits for a new launch. Names the open lessons whose error signature the call's output shows, each at most once an hour per agent, and the lesson rules whose text it shows. Adds each call to the [bug registry's](bug-registry.md) session ledger, and, for a marker of devkit's own failure in the output, gives the known detour or tells the agent how to find one. Right after a call that usually ends the turn (a subagent launch, a monitor, a background command, or `dev progress done`, `dev handoff --log`, `dev sync`, `dev task done`, a push, a PR, or a release), shows the main session the status block its final message opens with, with the project and branch filled in, at most once per 2 minutes in a turn; records slow calls; delivers crew messages to their recipient (the main session, or the subagent that made the call); tells the main session about decisions waiting for you and members ready to launch; reminds the main session to update you after a long silence; after a `git commit`, `push`, `merge`, `tag`, `rebase`, `cherry-pick`, or `revert`, or a `gh pr create`, `gh pr merge`, or `gh release create`, queues a sync of the handoff repository (see [Teams and machines › Near-real-time sync](teams.md#near-real-time-sync)). Gives the main session, once and first, the brief of a compaction only the transcript showed or "Not in the summary"; gives a member, after its own compaction, a reminder of its role, step, scope, procedure, and report format. A SendMessage from the main session to a member answers the questions to the tech lead that its text names (`M3: …`): each is marked answered via SendMessage, the text is kept as its answer, and the audit trail records `crew.message-answered`; a SendMessage that names none answers none, and a notice lists the questions that still wait. In Claude Code's main session, reads the messages you typed while it worked from the transcript (Claude Code also runs UserPromptSubmit for each, with the running turn's `prompt_id`): each counts as your latest request for the crew slot kept for you and for continuity, never as an approval. The crew messages, decisions, ready steps, CI results, and notices it delivers are the ones a `dev watch --wait` takes too: each reaches the session once, whichever reads it first | | PostToolUseFailure | `Agent\|Task\|Bash`, 10 s | — | A subagent launch that failed (an unknown agent type, an interrupt) started no agent, so its launch record goes at once: it never labels another agent or holds a crew slot. A failed or interrupted shell call leaves the call ledger, and its line goes to the [bug registry's](bug-registry.md) session ledger. When one agent's shell command fails twice in a row with the same error, it stops that agent once per command with the root-cause paragraph, the lessons the error matches, and the devkit bugs the registry knows (see [Lessons › Recall](lessons.md#recall)); a crew member's third identical failure sends the tech lead one notice. Names the open lessons and lesson rules whose error text the failure shows, and, for a marker of devkit's own failure, the known detour | | SubagentStart · SubagentStop | 5 s · 10 s | 5 s · 10 s | Opens and closes the subagent's progress lane (its persona, its step, its active time); a lane binds to exactly one launch. At SubagentStop, for a member someone launched, sends it back once for each of these, in order: a report that does not start with its own status block (`**[Firefly> DevKit · Neo]**`); no `dev progress step` in its lane; and the [crew gates](crew.md#every-report-is-checked) (proofs, skills, unfinished work, tests that cannot fail, lessons). The crew gates judge every stop. A member is sent back once per lane life (its launch, or a resume), and its next stop is judged again: a clean report with Check ✓ passes, so a review it finishes ends done. A stop let through with findings approves nothing; it is audited as `crew.gate` let through, and its findings reach the tech lead in one notice. On Codex, the gates read a member's executed command without devkit's own stamps in front of it. The gates get 6 s of the hook's 10: past that they do not judge the stop, the member goes through, no earlier pass of its gates approves anything, and the audit trail records `crew.gate` as let through. Then it closes the lane and its step, records no observed repeat for lessons shown without a later observed miss, without claiming success, and reads the member's transcript once more for a compaction no hook saw. The compaction summarizer's stop is skipped: it owes no report and binds nothing | diff --git a/docs/crew.md b/docs/crew.md index a742af5d..98cda4e6 100644 --- a/docs/crew.md +++ b/docs/crew.md @@ -414,8 +414,11 @@ lead. **Each call carries a token that names its caller.** The PreToolUse hook records every shell call with the agent that made it, from the hook's own input (the call ledger, in devkit's state, closed when the call ends), and puts -`DEVKIT_CALL=.` in front of the call. The token holds only for the shell the agent ran the call in, -and its child processes, and only while the call is open. A `dev` command reads its caller from the token once, when +`DEVKIT_CALL=.` in front of the call. Before anything else runs, the call's prefix writes its shell's +process id to a pin file (for a single plain `dev` call without that prefix, the `dev` process writes its own). The +token then names its caller only for a `dev` command that runs in that process or below it, and only while the call +is open, so another process cannot use the token even with a copy. If another process wrote the pin first, the call +names nobody. A `dev` command reads its caller from the token once, when it starts: a main-session call names the tech lead, and a member's call names that member, whatever other calls are open or waiting at the same time. These work for the tech lead and for members alike: diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 07a3e4b0..99e6b825 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -677,9 +677,8 @@ devkit does not know. A member's `dev progress` or `dev crew` call that devkit cannot place in its lane, such as one inside `$(…)`, a loop, or a pipeline into a file, still acts as the member when its call carries the call token, and a state change without -the token is refused (see [The crew › Who is calling](crew.md#who-is-calling)). Only in a session whose hook never -stamped a token, such as one an older devkit started, does such a call run as the main session's; the hook adds -advice to run it alone. When such a call closed or noted the wrong step, repair it with +the token is refused (see [The crew › Who is calling](crew.md#who-is-calling)). A state change devkit cannot +place is refused, never made as the main session's; the hook adds advice to run it alone. When such a call closed or noted the wrong step, repair it with `dev progress reopen --why "…"`, and have the member run the call again as a command of its own. ### An agent ran something devkit used to refuse From 8a809aa287ac85672a180c2074b2da20781c54c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 23:22:55 -0800 Subject: [PATCH 40/52] fix(identity): run project code without the token, audit unlisted uses A crew member could plant a dev command in a workflow step, a test or a git hook, and when the tech lead ran dev ci --run, dev test or dev commit, that command inherited the tech lead's call token and acted as the tech lead with no record. Two smaller pin gaps let a call be taken silently: a pin written in advance beside a dangling .contested link, and a pid reused after an interrupted call whose token was never used. Root cause: devkit's runners passed their own environment, call token and lane marks included, to the project's code (gitx's step env, testx's test env, core.GIT_ENV for git and its hooks); the contested marker was checked with Path.exists, which is False for a dangling link, while the stamp only tried to create the marker; and nothing tied the pin file to the moment its pinned process started. - identity.runner_env drops DEVKIT_CALL, DEVKIT_FROM_AGENT and DEVKIT_SPEAKER; dev ci --run's steps, dev test's and dev test prove's test commands, and every git command devkit runs (core.GIT_ENV) start with it, so a dev command there names nobody and its state change is refused (caller.no-token). - Each verified use appends its arguments' hash, whether it changes state, and whether the call's text runs it to ..uses; when the call ends, state changes its text does not run are audited as caller.token-unlisted-use (flagged, allowed: the tech lead's own scripts do this). - The stamp moves a pin already there onto the contested name (mv -f replaces a planted link) and checks the marker with os.path.lexists, so a call is contested rather than taken. - A pin must be born within 20 s after its pinned process started, so a pid given to a newer process is not the call's. - SECURITY.md says which project code devkit runs without the token and that crew code the tech lead runs by a raw command still acts as the tech lead, recorded in the audit trail. - Test repairs for the pin form: the member wait route asserts its lane and its token; a member call whose rewrite is dropped is refused and lands nowhere. Verified: dev test run on 47 identity, runner, git, CI and coordination files: 1500 of 1500 passed; then test_watch_requests, test_acceptance_crew_sessions, test_progress and test_identity_redteam: 270 of 270; dev test prove --since HEAD: 11 new tests fail without the change. --- SECURITY.md | 9 ++ lib/devkit/core.py | 10 ++- lib/devkit/gitx.py | 8 +- lib/devkit/hooks.py | 14 +++- lib/devkit/identity.py | 112 +++++++++++++++++++++++-- lib/devkit/testx.py | 2 + tests/test_acceptance_crew_sessions.py | 12 ++- tests/test_identity_redteam.py | 88 ++++++++++++++++++- tests/test_identity_runners.py | 110 ++++++++++++++++++++++++ tests/test_identity_token.py | 12 +-- tests/test_watch_requests.py | 4 +- 11 files changed, 354 insertions(+), 27 deletions(-) create mode 100644 tests/test_identity_runners.py diff --git a/SECURITY.md b/SECURITY.md index d41e10fc..ad570415 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -51,6 +51,10 @@ visible: - **Commands outside their call.** A background or detached job, a nested agent such as `codex exec` or `claude -p`, and a token copied from a log or a transcript name nobody once their call has closed, or outside the call's own shell, so the state changes they try are refused. +- **Project code that devkit runs.** `dev ci --run`, `dev test`, and `dev test prove` start the project's workflow + steps and tests without the token or the lane marks, and so does every git command devkit runs, with the git hooks + that `dev commit` and `dev push` start. A `dev` command in a step, a test, or a hook that a crew member wrote names + nobody there, so devkit refuses its state change. - **A record of each attempt.** Each failed check and each state change without a token writes a caller identity record to the audit trail ([The audit trail › Caller identity records](docs/audit.md#caller-identity-records)). devkit keeps only a hash of the token, and removes its value from every command text it records. @@ -60,6 +64,11 @@ What it does not protect: - **devkit's own state.** The call ledger, the session records, and the audit log are files your user owns. A crew member that edits them can still act as another caller. The next tech-lead call shows the damage, but devkit does not stop it, and such an attack is out of scope for reports (see [Scope](#scope)). +- **Crew code that the tech lead runs.** A crew member's code that the tech lead starts with an ordinary command, + such as `npm test`, `make`, or a git hook that a plain `git commit` starts, runs inside the tech lead's call. A + `dev` command in that code acts as the tech lead, with your full permissions. When the call ends, devkit records + each state change that the call's own text does not run (`caller.token-unlisted-use`), so the change shows in the + audit trail, but devkit does not stop it. - **What an agent may run.** The token names who runs a `dev` command and limits nothing else. Against an agent set on misuse, the controls that hold are the agent's permission mode and your Git host's branch protection. - **The token while its call runs.** Any process of your user can read it from the process list then: holding only diff --git a/lib/devkit/core.py b/lib/devkit/core.py index f858e8d1..3d08dacf 100644 --- a/lib/devkit/core.py +++ b/lib/devkit/core.py @@ -553,7 +553,15 @@ def ensure_roots(home=None): # --------------------------------------------------------------------------- shell -GIT_ENV = dict(os.environ, GIT_OPTIONAL_LOCKS="0", GIT_TERMINAL_PROMPT="0", LC_ALL="C") +def _git_env() -> dict: + """The environment of the git commands devkit runs: never the call token or the lane marks + (identity.runner_env), since git runs the repository's hooks, the project's code, which a crew member may have + written: a dev command in a hook that dev commit, dev push or a rebase starts names nobody.""" + from . import identity # its module level imports no devkit module: no cycle + return identity.runner_env(dict(os.environ, GIT_OPTIONAL_LOCKS="0", GIT_TERMINAL_PROMPT="0", LC_ALL="C")) + + +GIT_ENV = _git_env() def sh(args, cwd=None, timeout=30, env=None, input=None): diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 41479df8..611ba43a 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -2718,9 +2718,12 @@ def _runner_prep(run: str, cwd: str, root: str, env: dict): def _local_env(env) -> dict: + """A step's environment here: this Mac's, CI=true and the step's own variables, never the call token or the lane + marks (identity.runner_env): the step is the project's code, not the call that runs dev ci --run.""" + from . import identity step_env = dict(os.environ, CI="true") step_env.update({k: v for k, v in (env or {}).items() if "${{" not in str(v)}) - return step_env + return identity.runner_env(step_env) def runner_setup(run: str, root, cwd=None, env=None): @@ -3338,7 +3341,7 @@ def step_limit(s, rec=None, given=None) -> tuple: def run_local_ci(c, dry_run=False, keep_going=False, step_timeout=None, resume=False) -> int: - from . import pipelines + from . import identity, pipelines jobs = _job_order(plan(c.top)) if not jobs: return fail("no GitHub Actions workflows to run here", @@ -3404,6 +3407,7 @@ def run_step(s): key = _step_key(s) env = dict(os.environ, CI="true") env.update({k: v for k, v in s["env"].items() if "${{" not in v}) + env = identity.runner_env(env) # the step is the project's code: a dev command in it names nobody if shim: env["PATH"] = shim + os.pathsep + env.get("PATH", "") output = outdir / f"{n:02d}.output" diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index dec41ff7..e1fbd159 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -1558,7 +1558,7 @@ def _pin_audits(entry: dict, data: dict): pin, tid, sid = Path(str(entry["pin"])), str(data.get("tool_use_id") or ""), str(data.get("session_id") or "") used = identity._read_used(sid, tid) found = [] - if Path(f"{pin}.contested").exists(): + if os.path.lexists(f"{pin}.contested"): found.append(("calls.pin-contested", "another process wrote this call's pin before its shell did")) try: st = os.stat(pin) @@ -1577,12 +1577,18 @@ def _pin_audits(entry: dict, data: dict): runs = [None] if not any(r for r in runs) and not entry.get("cut"): found.append(("caller.token-unexplained-use", "a dev command resolved this call's token, and its text " - "runs no dev command")) - for action, why in found: + "runs no dev command", {})) + unlisted = [u for u in identity.read_uses(sid, tid) if u.get("change") and not u.get("listed")] + if unlisted: # code the call started (a script, a test, a git hook) changed state as the call's caller + found.append(("caller.token-unlisted-use", f"{len(unlisted)} state change(s) through this call's token by " + f"dev commands its text does not run: code it started ran them", + {"count": len(unlisted), "by": str(entry.get("caller") or "main")[:80]})) + for action, why, *more in found: try: from . import audit audit.record(action, tid[:80] or "-", why, "flagged", tool_use_id=tid[:80], session=sid[:80], - host_agent=str(entry.get("agent") or ""), command=str(entry.get("cmd") or "")[:300]) + host_agent=str(entry.get("agent") or ""), command=str(entry.get("cmd") or "")[:300], + **(more[0] if more else {})) except Exception as e: _swallowed("post-tool", e) diff --git a/lib/devkit/identity.py b/lib/devkit/identity.py index 3f4b1617..2956c128 100644 --- a/lib/devkit/identity.py +++ b/lib/devkit/identity.py @@ -517,13 +517,25 @@ def detached_env(env=None) -> dict: return {k: v for k, v in (os.environ if env is None else env).items() if k != CALL_VAR} +RUNNER_DROPS = (CALL_VAR, LANE_VAR, SPEAKER_VAR) + + +def runner_env(env=None) -> dict: + """The environment for the project's own code that a devkit runner starts (the steps of dev ci --run, the test + commands of dev test and dev test prove): `env`, default this process's, without the call token, the lane + variable and the speaker mark. That code is not the call that ran the runner, and a crew member may have written + it: a dev command in it names nobody, so its state change is refused in a session whose calls carry tokens + (caller.no-token).""" + return {k: v for k, v in (os.environ if env is None else env).items() if k not in RUNNER_DROPS} + + def strip_token(cmd): """A shell command without the call token the PreToolUse hook put in front of it, as devkit keeps command text (the ledger, the records of closed calls, the audit trail, notices).""" if not isinstance(cmd, str): return cmd - cmd = re.sub(r"\A ?(?:\(set -C; printf '%s\\n' \"\$\$\" > .+?\) 2>/dev/null \|\| \(: > .+?\) 2>/dev/null; )?" - r"export DEVKIT_CALL=[A-Za-z0-9_.-]+; readonly DEVKIT_CALL; ", "", cmd) + cmd = re.sub(r"\A ?(?:\(set -C; printf '%s\\n' \"\$\$\" > .+?\) 2>/dev/null \|\| mv -f .+? 2>/dev/null \|\| " + r"\(: > .+?\) 2>/dev/null; )?export DEVKIT_CALL=[A-Za-z0-9_.-]+; readonly DEVKIT_CALL; ", "", cmd) return re.sub(r"\A((?:DEVKIT_[A-Z_]+=[A-Za-z0-9_.:-]+ )*)DEVKIT_CALL=[A-Za-z0-9_.-]+ ", r"\1", cmd) @@ -573,7 +585,7 @@ def note_closed(agent: str, sid: str, tid: str): goes.""" from . import progress, state pin = pin_path(sid, tid) - for f in (used_path(sid, tid), pin, pin.with_name(pin.name + ".contested")): + for f in (used_path(sid, tid), uses_path(sid, tid), pin, pin.with_name(pin.name + ".contested")): try: f.unlink() except OSError: @@ -675,10 +687,12 @@ def make_pin_folder(sid: str): def pin_stamp(path) -> str: """The stamp's first action, for sh, bash and zsh (Codex's -lc too): the shell's own pid into the pin, in a subshell under noclobber so the user's command never runs with it, errors to /dev/null; a pin already there - leaves the contested marker instead.""" + moves a pin already there onto the contested name (mv -f replaces a link planted there), and writes the marker + when there was none to move: the call is then contested, never silently another process's.""" import shlex pin, contested = shlex.quote(str(path)), shlex.quote(f"{path}.contested") - return f"(set -C; printf '%s\\n' \"$$\" > {pin}) 2>/dev/null || (: > {contested}) 2>/dev/null; " + return (f"(set -C; printf '%s\\n' \"$$\" > {pin}) 2>/dev/null || mv -f {pin} {contested} 2>/dev/null || " + f"(: > {contested}) 2>/dev/null; ") def _pid() -> int: @@ -727,6 +741,23 @@ def _read_pin(path): return int(text) if _PIN_TEXT.fullmatch(text) else -1 +# The pinned process writes its pin (the shell, as the stamp's first action, once its snapshot or login profile ran) +# or is the call's process its dev command pins: the pin is born after that process started and soon after. A pid the +# system gave to a newer process (the call's shell exited before its token was first used) started after the pin. +PIN_BIRTH_S = 20.0 # a slow login profile (Codex's -lc) runs before the stamp +PIN_CLOCK_S = 0.05 # the start time's and the file time's rounding + + +def _born(path): + """When the pin was written: its birth time where the system keeps one (macOS), else its modification time (it + is written once). None when it cannot be read.""" + try: + st = os.stat(path) + except OSError: + return None + return float(getattr(st, "st_birthtime", 0) or st.st_mtime) + + def _write_pin(path, pid: int) -> bool: """The dev process pins the plain form's call to `pid` itself: True when this write made the pin (O_EXCL).""" try: @@ -764,6 +795,69 @@ def _mark_used(sid: str, tid: str, pid=None, start=None, inode=None): fh.write(json.dumps({"pid": pid, "start": start, "inode": inode})) +def uses_path(sid: str, tid: str): + """The verified uses of call `tid`'s token, one JSON line each, beside its use mark: CALLS//..uses.""" + from . import progress + return progress.CALLS / progress._safe_name(sid) / f".{progress._safe_name(tid)}.uses" + + +def _listed(entry: dict, args: list) -> bool: + """Is this dev command one of the call text's own: typed with these arguments, or with an expansion in place of + some (a loop's "$s", a substitution), as the shell reads the text? A dev command that a script, a test or a git + hook the call started runs is not.""" + from . import shellparse + if _typed_exactly(entry, args): + return True + text = str(entry.get("cmd") or "") + if entry.get("cut") or not any(c in text for c in "$`"): + return False + try: + calls = shellparse.shell_calls(text, None) or [] + except Exception: + return False + for argv, _ in calls: + words = shellparse.dev_args(argv) + if words and len(words) == len(args) and all( + w == a or re.fullmatch("".join(".*" if e else re.escape(t) for e, t in _expansion_parts(w)), a, re.S) + for w, a in zip(words, args)): + return True + return False + + +def _note_use(sid: str, tid: str, entry: dict, args: list): + """Append this verified use to its call's list: its arguments' hash (never their text), whether it changes state, + and whether the call's text runs it (_listed). Appended (O_APPEND), so each dev command of one call keeps its own + line; the PostToolUse hook audits the changes the text does not run (caller.token-unlisted-use).""" + from . import progress + line = json.dumps({"use": progress.args_hash(args), "change": bool(state_changing(args)), + "listed": _listed(entry, args)}) + "\n" + try: + fd = os.open(uses_path(sid, tid), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + except OSError: + return + try: + os.write(fd, line.encode()) + finally: + os.close(fd) + + +def read_uses(sid: str, tid: str) -> list: + """The verified uses _note_use appended for call `tid`, oldest first ([] when none).""" + try: + lines = uses_path(sid, tid).read_text().splitlines() + except OSError: + return [] + out = [] + for ln in lines: + try: + doc = json.loads(ln) + except ValueError: + continue + if isinstance(doc, dict): + out.append(doc) + return out + + def _session_of(pid): """The process session of `pid` (0: this process), None when the system does not say.""" try: @@ -833,6 +927,7 @@ def _verify(agent: str, sid: str, value: str, now, args=()) -> _Verdict: clash = _thread_evidence(agent, sid, caller, owner, tid) if clash: return _Verdict(tid, code="caller.conflict", why=CONFLICT, ancestors=above, detail=clash) + _note_use(sid, tid, entry, list(args)) return _Verdict(tid, caller=caller, ancestors=above) @@ -845,7 +940,7 @@ def no(code, detail, why=FOREIGN_USE): path = Path(str(entry.get("pin") or "")) if not entry.get("pin"): return no("caller.token-foreign-use", "its call recorded no pin") - if Path(f"{path}.contested").exists(): + if os.path.lexists(f"{path}.contested"): # a link counts, dangling or not: one planted there is contest enough return no("calls.pin-contested", "another process wrote its call's pin first: its token names nobody") pinned = _read_pin(path) if pinned == -1: @@ -875,6 +970,11 @@ def no(code, detail, why=FOREIGN_USE): if start < ts - 0.001 or start > ts + max(ttl, 1.0): return no("calls.pin-early", f"its pinned process {pinned} started at {start:.6f}, outside its call " f"({ts:.3f} for {ttl:g} s)") + born = _born(path) + if born is None or born < start - PIN_CLOCK_S or born > start + PIN_BIRTH_S: + return no("caller.token-foreign-use", f"its pin was written at {born or 0:.6f}, outside the first " + f"{PIN_BIRTH_S:g} s of its pinned process {pinned} (started " + f"{start:.6f}): the pid went to another process after it") used = _read_used(sid, tid) if used and (used.get("pid") != pinned or used.get("start") != start): return no("caller.token-foreign-use", f"its pin named process {used.get('pid')} at its first use, and now " diff --git a/lib/devkit/testx.py b/lib/devkit/testx.py index 5d128121..cf382c16 100644 --- a/lib/devkit/testx.py +++ b/lib/devkit/testx.py @@ -1972,10 +1972,12 @@ def run_tests(top, runner, files=(), ids=(), related=(), all_=False, env=None, s elif runner["name"] in ("jest", "vitest"): report = str(work / "report.json") cmd = build_command(top, runner, files, ids, report, related, all_) + from . import identity full_env = dict(os.environ) full_env.update(env or {}) for k, v in cmd["env"].items(): full_env[k] = v if k != "PYTHONPATH" or not (env or {}).get(k) else v + os.pathsep + env[k] + full_env = identity.runner_env(full_env) # the tests are the project's code: a dev command in them names nobody import_receipt = None completion = unittest_completion(work) if runner["name"] == "unittest" else None if isolated_imports: diff --git a/tests/test_acceptance_crew_sessions.py b/tests/test_acceptance_crew_sessions.py index c6fabd53..82b61558 100644 --- a/tests/test_acceptance_crew_sessions.py +++ b/tests/test_acceptance_crew_sessions.py @@ -696,16 +696,20 @@ def test_a_members_step_closes_only_in_its_own_run(self): self.assertNotIn("build done", json.dumps(b.run_doc()) + json.dumps(k.run_doc())) self.assertEqual(b.run_doc()["agents"]["b1"].get("updates") or [], []) - def test_a_members_progress_call_goes_to_its_lane_through_the_ledger_when_the_rewrite_is_dropped(self): + def test_a_members_progress_call_whose_rewrite_is_dropped_is_refused_and_lands_nowhere(self): a = self.claude(S1, self.api) self.staff(a, "Invoice export", "build=30m [backend]; review=20m after build [review]", ("a1", "tank", "Tank", "build", "backend")) - # it names no step: a --step for a step the member does not hold fails (tests/test_lane_binding.py) + # the command runs as typed: no call token, no lane variable. devkit no longer guesses its caller from the + # call ledger's text, so the change is refused, with the fix, rather than made in some lane r = a.sh("dev progress step 'review looks fine' --check 'read it'", member="a1", member_type="devkit:tank", raw=True) - self.assertEqual(r["rc"], 0, r) + self.assertEqual(r["rc"], 2, r) + self.assertIn("it carries no call token", r["err"]) + self.assertIn("run it again as a command of its own", r["err"]) self.assertEqual(a.step_state("review"), "pending") # the main plan's step never moved - self.assertEqual([u["text"] for u in a.run_doc()["agents"]["a1"]["updates"]], ["review looks fine"]) + self.assertEqual(a.run_doc()["agents"]["a1"].get("updates") or [], []) + self.assertNotIn("review looks fine", json.dumps(a.run_doc())) def test_two_sessions_of_one_repository_with_the_same_command_open_each_write_their_own_run(self): a = self.claude(S1, self.api) diff --git a/tests/test_identity_redteam.py b/tests/test_identity_redteam.py index e7a31fe6..3343f2ad 100644 --- a/tests/test_identity_redteam.py +++ b/tests/test_identity_redteam.py @@ -219,6 +219,19 @@ def test_a_tech_lead_call_running_no_dev_whose_token_another_process_used_is_aud self.assertEqual(len(found), 1) self.assertEqual(found[0]["ref"]["result"], "flagged") + def test_only_state_changes_the_call_text_does_not_run_are_audited_when_it_ends(self): + self.plan_with_link() + ref = pg.crew_ask("Report: " + "x" * 400, from_agent="a_link")["id"] + data, token, _ = self.hook('for s in one; do dev progress add "$s"; done; ./build.sh') + self.assertEqual(self.dev("progress", "add", "one", token=token)[0], 0) # its loop's own command + self.assertEqual(self.dev("crew", "read", ref, "--json", token=token)[0], 0) # build.sh reads: no change + self.assertEqual(self.dev("progress", "note", "from build.sh", token=token)[0], 0) # build.sh changes + self.closed(data) + found = self.records("caller.token-unlisted-use") + self.assertEqual([(r["evidence"]["count"], r["ref"]["result"]) for r in found], [(1, "flagged")]) + self.assertNotIn("from build.sh", json.dumps(found)) # the arguments' hash only, never their text + self.assertFalse(identity.uses_path("s1", data["tool_use_id"]).exists()) # gone with its call + def tearDown_records(self): # the next subtest's own call and records: a fresh plan and audit from devkit import audit as audit_module @@ -350,6 +363,19 @@ def test_a_contested_call_names_nobody(self): self.assertEqual(self.lead(token)[0], 2) self.assertEqual(len(self.records("calls.pin-contested")), 2) + def test_a_pin_written_in_advance_beside_a_dangling_contested_link_names_nobody(self): + self.plan_with_link() + data, token, _ = self.hook("pytest -q tests") + pin = identity.pin_path("s1", data["tool_use_id"]) + pin.write_text("79500\n") # the member's fresh shell, as if its pin was there before the victim's write + os.symlink("/nonexistent/dir/x", f"{pin}.contested") # and the victim's marker write failed on this link + self.chain = [(79500, "/bin/zsh -c x"), (AGENT, "claude")] + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.closed(data) + self.assertEqual(len(self.records("calls.pin-contested")), 2) # refused, and audited when the call ends + def test_a_malformed_pin_fails_closed(self): self.plan_with_link() data, token, _ = self.hook("pytest -q tests") @@ -378,6 +404,48 @@ def test_fish_gets_no_shell_pin_and_its_plain_call_pins_from_dev(self): self.assertEqual(identity._read_pin(identity.pin_path("s1", data["tool_use_id"])), self.shell) +class ClaudePinnedProcessLifeTests(TokenCase): + # the pinned pid is checked with its start time: a pid the system gave to a newer process is not the call's + # shell, and a pinned process that has exited holds no call. opened(): a stamped call that will run + # `dev progress add extra` -> (its token, its shell's pid); the Codex class below runs the same tests + def opened(self): + self.plan_with_link() + _, token, _ = self.hook("pytest -q tests; dev progress add extra") + return token, self.shell + + def test_the_pinned_pid_with_another_start_time_is_another_process(self): + token, shell = self.opened() + self.assertEqual(self.dev("crew", "inbox", token=token)[0], 0) # its first use records pid and start + self.starts[shell] += 5 # same pid, a later start: the call's shell ended and its pid went to another + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.token-foreign-use")), 1) + + def test_a_pid_reused_before_the_tokens_first_use_is_not_the_calls_shell(self): + token, shell = self.opened() # interrupted: no PostToolUse, and its token never used + self.starts[shell] += 120 # its shell exited; a member's new call shell, inside the call's time, got the pid + self.chain = [(79600, "python3 x.py"), (shell, "/bin/zsh -c member"), (self.agent_pid, self.agent)] + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.token-foreign-use")), 1) # its pin was born before that process + + def test_a_pinned_process_that_has_exited_holds_no_call(self): + token, shell = self.opened() + self.starts[shell] = None # gone while the call is still open (its agent has not closed it yet) + rc, out = self.lead(token) + self.assertEqual(rc, 2, out) + self.assertFalse(self.added()) + self.assertEqual(len(self.records("caller.stale-token")), 1) + + +class CodexPinnedProcessLifeTests(CodexTokenCase, ClaudePinnedProcessLifeTests): + def opened(self): + _, token, _ = self.exec("pytest -q tests; dev progress add extra") + return token, self.shell + + class PinFolderTests(TokenCase): def test_a_link_planted_where_the_pin_folder_goes_gets_no_token(self): target = self.root / "elsewhere" @@ -403,7 +471,21 @@ def run_stamp(self, shell, setup=""): first = (out.stdout.split()[0], identity._read_pin(pin), "clobber-ok" in out.stdout, out.stderr) again = subprocess.run([shell, "-c", identity.pin_stamp(pin) + "true"], capture_output=True, text=True, timeout=10) - return first, identity._read_pin(pin), pin.with_name("t.pin.contested").exists(), again.stderr + contested = pin.with_name("t.pin.contested") + return first, identity._read_pin(pin), (contested.exists(), identity._read_pin(contested)), again.stderr + + def test_a_pin_written_in_advance_is_moved_onto_a_dangling_contested_link(self): + for shell in ("/bin/sh", "/bin/bash", "/bin/zsh"): + with self.subTest(shell=shell), tempfile.TemporaryDirectory() as d: + pin = Path(d) / "t.pin" + pin.write_text("79500\n") # the member's shell wrote first + os.symlink(f"{d}/missing/x", f"{pin}.contested") # so that the victim's marker write fails + out = subprocess.run([shell, "-c", identity.pin_stamp(pin) + "true"], capture_output=True, text=True, + timeout=10) + self.assertEqual(out.stderr, "") + self.assertFalse(os.path.lexists(pin)) # the call is contested, never silently the member's + self.assertFalse(os.path.islink(f"{pin}.contested")) + self.assertEqual(identity._read_pin(Path(f"{pin}.contested")), 79500) def test_sh_bash_and_zsh_pin_their_own_pid_and_leave_noclobber_off(self): for shell, setup in (("/bin/sh", ""), ("/bin/bash", ""), ("/bin/zsh", ""), ("/bin/zsh", "setopt clobber; "), @@ -413,8 +495,8 @@ def test_sh_bash_and_zsh_pin_their_own_pid_and_leave_noclobber_off(self): self.assertEqual(int(pid), pinned) self.assertTrue(clobber_ok) # the user's own redirects still overwrite self.assertEqual((err, err2), ("", "")) - self.assertEqual(after, pinned) # a second write leaves the first pin - self.assertTrue(contested) + self.assertIsNone(after) # a second write moves the first pin onto the contested name + self.assertEqual(contested, (True, pinned)) class RealProcessTheftTests(PreToolCase): diff --git a/tests/test_identity_runners.py b/tests/test_identity_runners.py new file mode 100644 index 00000000..0ae0c7eb --- /dev/null +++ b/tests/test_identity_runners.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +# Code a crew member writes, run by the tech lead: a workflow step, a test, a script. devkit's own runners +# (dev ci --run, dev test, dev test prove) start the project's code without the call token and the lane marks, so a dev +# command in it names nobody and its state change is refused (caller.no-token). Code the tech lead runs by a raw +# command still runs in the tech lead's call: its state changes go through and are audited when the call ends +# (caller.token-unlisted-use), while the call text's own dev commands are not. Real processes, on both hosts. +import os +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +import _hermetic # noqa: E402 + +_hermetic.activate() +sys.path.insert(0, str(ROOT / "lib")) + +from devkit import identity # noqa: E402 +from test_pre_tool_hook import PreToolCase # noqa: E402 + +WORKFLOW = ("name: ci\non: [push]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n" + " - run: dev progress add planted-step\n") +PLANTED_TEST = ("import subprocess, unittest\n\n\nclass Planted(unittest.TestCase):\n def test_it(self):\n" + " subprocess.run(['dev', 'progress', 'add', 'planted-test'])\n") + + +class RunnerCase(PreToolCase): + def on(self, agent): + if agent == "codex": + self.codex_policy("never") # every call stamped: the planted code would inherit a live token + return self.lead_on(agent) + + @staticmethod + def plan(s): + return [st["name"] for st in s.run_doc()["plan"]] + + def both(self, fn): + for n, agent in enumerate(("claude", "codex")): + with self.subTest(agent=agent): + if n: + self.setUp() # a new Mac: the first one's hosts and files go at the test's end + fn(self.on(agent)) + + +class DevkitRunnerTests(RunnerCase): + def test_a_planted_workflow_step_under_dev_ci_run_is_refused(self): + def check(s): + wf = s.repo / ".github" / "workflows" + wf.mkdir(parents=True, exist_ok=True) + (wf / "ci.yml").write_text(WORKFLOW) + s.sh("dev ci --run") + self.assertNotIn("planted-step", self.plan(s)) + self.assertTrue(self.audit("caller.no-token")) + self.both(check) + + def test_a_planted_test_under_dev_test_is_refused(self): + def check(s): + (s.repo / "tests").mkdir(exist_ok=True) + (s.repo / "tests" / "test_planted.py").write_text(PLANTED_TEST) + r = s.sh("dev test run tests/test_planted.py") + self.assertIn("1 passed", r["out"] + r["err"]) # the test ran + self.assertNotIn("planted-test", self.plan(s)) + self.assertTrue(self.audit("caller.no-token")) + self.both(check) + + def test_a_planted_git_hook_under_dev_commit_is_refused(self): + def check(s): + hook = s.repo / ".git" / "hooks" / "pre-commit" + hook.parent.mkdir(parents=True, exist_ok=True) + hook.write_text("#!/bin/sh\ndev progress add planted-hook\nexit 0\n") # it never stops the commit + hook.chmod(0o755) + (s.repo / "notes.txt").write_text("notes\n") + s.sh("git update-ref refs/remotes/origin/main main && " # origin's default branch, as a clone knows it + "git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main && git switch -q -c docs/notes") + r = s.sh('dev commit -m "docs: add notes" --why "notes for the team" --verified "read them" notes.txt') + self.assertEqual(r["rc"], 0, r["out"] + r["err"]) # the hook ran, and the commit went through + self.assertNotIn("planted-hook", self.plan(s)) + self.assertTrue(self.audit("caller.no-token")) + self.both(check) + + def test_the_runner_env_drops_the_token_and_the_lane_marks_and_keeps_the_rest(self): + env = {identity.CALL_VAR: "toolu_1.x", identity.LANE_VAR: "a_tank", identity.SPEAKER_VAR: "main", + "DEVKIT_SESSION": "claude:s1", "PATH": "/usr/bin", "CI": "true"} + self.assertEqual(identity.runner_env(env), {"DEVKIT_SESSION": "claude:s1", "PATH": "/usr/bin", "CI": "true"}) + self.assertNotIn(identity.CALL_VAR, identity.runner_env(dict(os.environ, DEVKIT_CALL="toolu_1.x"))) + + +class RawCommandTests(RunnerCase): + def test_a_planted_dev_command_a_raw_test_command_runs_is_audited_and_the_calls_own_is_not(self): + def check(s): + script = s.repo / "run-tests.sh" # what `npm test` or a git hook runs: the member's code + script.write_text("#!/bin/sh\ndev progress add planted-raw\n") + script.chmod(0o755) + r = s.sh("./run-tests.sh; dev progress add mine") + self.assertEqual(r["rc"], 0, r["err"]) + self.assertIn("planted-raw", self.plan(s)) # it runs in the tech lead's call: not refused + self.assertIn("mine", self.plan(s)) + found = self.audit("caller.token-unlisted-use") + self.assertEqual(len(found), 1, found) + self.assertEqual(found[0]["ref"]["result"], "flagged") # recorded, not refused + self.assertEqual(found[0]["ref"]["by"], "main") + self.assertEqual(found[0]["evidence"].get("count"), 1) # the planted change, not the call's own + s.sh("dev progress add own-only") + self.assertEqual(len(self.audit("caller.token-unlisted-use")), 1) + self.both(check) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_identity_token.py b/tests/test_identity_token.py index 43236fd5..c2be1b7e 100644 --- a/tests/test_identity_token.py +++ b/tests/test_identity_token.py @@ -118,8 +118,9 @@ def hook(self, cmd, aid=None, sid="s1", tool="Bash", key="command", permission_m self.shell = shell if found and "set -C; printf" in new: # the stamp's first action: the shell pins its pid (noclobber) pin = identity.pin_path(sid, data["tool_use_id"]) - if pin.exists(): - pin.with_name(pin.name + ".contested").write_text("") + self.starts.setdefault(shell, time.time()) # the shell started, then wrote its pin + if os.path.lexists(pin): # a pin already there: the stamp moves it onto the contested name + os.replace(pin, pin.with_name(pin.name + ".contested")) else: pin.write_text(f"{shell}\n") return data, (found.group(1) if found else ""), new @@ -152,9 +153,9 @@ class StampTests(TokenCase): def test_every_main_shell_call_gets_a_readonly_token_whose_hash_its_entry_holds(self): data, token, new = self.hook("git status") pin = identity.pin_path("s1", data["tool_use_id"]) - self.assertEqual(new, f" (set -C; printf '%s\\n' \"$$\" > {shlex.quote(str(pin))}) 2>/dev/null || " - f"(: > {shlex.quote(str(pin) + '.contested')}) 2>/dev/null; export DEVKIT_CALL={token}; " - f"readonly DEVKIT_CALL; git status") + p, c = shlex.quote(str(pin)), shlex.quote(str(pin) + ".contested") + self.assertEqual(new, f" (set -C; printf '%s\\n' \"$$\" > {p}) 2>/dev/null || mv -f {p} {c} 2>/dev/null || " + f"(: > {c}) 2>/dev/null; export DEVKIT_CALL={token}; readonly DEVKIT_CALL; git status") self.assertEqual(identity.strip_token(new), "git status") tid, nonce = identity.parse_token(token) entry = pg.call_entry(data) @@ -267,7 +268,6 @@ def test_a_use_from_a_sibling_shell_is_refused_and_the_calls_own_shell_still_res def test_a_shell_pid_the_system_gave_to_another_process_is_refused(self): self.plan_with_link() _, token, _ = self.hook("dev progress begin ci-redirect") - self.starts[self.shell] = time.time() + 1 self.assertEqual(self.speak(token).lane, "main") # its first use records the pid's start time self.starts[self.shell] += 5 # the call's shell ended and its pid went to a newer process rc, out = self.lead(token) diff --git a/tests/test_watch_requests.py b/tests/test_watch_requests.py index 652537ca..83dae0f3 100644 --- a/tests/test_watch_requests.py +++ b/tests/test_watch_requests.py @@ -215,7 +215,9 @@ def pre(cmd, background): for background in (False, True): with self.subTest(background=background): got = pre("dev watch --wait --for me --timeout 9", background) - self.assertEqual(got.get("command"), "DEVKIT_FROM_AGENT=a_tank dev watch --wait --for me --timeout 9") + # its lane, and its call token right before dev (the plain form, where the payload names no bypass) + self.assertRegex(got.get("command") or "", r"\ADEVKIT_FROM_AGENT=a_tank DEVKIT_CALL=toolu_w\.[A-Za-z0-9_-]{22} " + r"dev watch --wait --for me --timeout 9\Z") self.assertEqual(got.get("run_in_background", False), background) self.assertEqual(pre("dev watch --wait; rm -rf build", False), {}) # only a call of its own is routed From f5d46421f8b478aac378db3b1e354bb01d8e3466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Thu, 19 Nov 2026 23:25:05 -0800 Subject: [PATCH 41/52] docs(audit): list the pin and unlisted-use records of the call token the call token's pin and the runners' tokenless environment added audit actions the reference did not list, and two rows described the older shell binding and a wrong category Verified: dev docs check on both pages: 0 issues, all links resolve; action names and categories checked against identity.py, hooks.py and audit.py --- docs/audit.md | 10 ++++++++-- docs/crew.md | 6 ++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/audit.md b/docs/audit.md index ab1ee0a9..168e4bb9 100644 --- a/docs/audit.md +++ b/docs/audit.md @@ -377,16 +377,22 @@ No record holds the token's value: devkit replaces it with a redaction mark in e | `caller.stale-token` | `security`, warning | A token whose call has closed or ran past its time limit, such as a background command's: refused for a state change | | `caller.foreign-session` | `security`, warning | A token of another session's call, such as one a nested `codex exec` or `claude -p` inherited: refused for a state change | | `caller.foreign-agent` | `security`, warning | A token used under another agent process than the one that made the call: refused for a state change | -| `caller.token-foreign-use` | `security`, warning | A token used from another shell than the one the agent ran the call in, naming both: refused for a state change | +| `caller.token-foreign-use` | `security`, warning | A token used outside the process its call pinned and the processes below it, or after that process id went to another process, naming both: refused for a state change | | `caller.token-unpinned` | `security`, warning | A token whose call's agent process devkit does not know: refused for a state change | | `caller.token-unexplained-use` | `security`, warning | A `dev` command resolved the token of a tech lead's call that runs no `dev` command, found when that call ends | +| `caller.token-unlisted-use` | `security`, warning | State changes through a call's token by `dev` commands the call's own text does not run, such as one a script or hook the call started ran, with their count and the caller, found when that call ends: allowed and recorded | | `caller.conflict` | `security`, warning | A token and a lane variable, or a Codex thread, that name different callers: refused for a state change | | `caller.mismatch` | `security`, warning | A Codex command that ran on another thread than the caller its `dev` command resolved to, found afterwards in the rollout | | `caller.spoof-suspect` | `security`, warning | A member's command that drops or sets `DEVKIT_CALL` or `CODEX_THREAD_ID` (`unset`, `env -u`, `env -i`, an assignment); the member also gets advice | | `caller.thread` | `security`, warning | A Codex command without a token that `CODEX_THREAD_ID` named: a read, or a state change that its caller's own open call holds exactly | | `calls.forged` | `lifecycle`, notice | A token whose call the hook never opened: refused for a state change | +| `calls.pin-contested` | `lifecycle`, notice | Another process wrote a call's pin before its shell did, so its token names nobody: refused for a state change, and recorded again when the call ends | +| `calls.pin-malformed` | `lifecycle`, notice | A call's pin holds something other than a process id, or cannot be read: refused for a state change | +| `calls.pin-early` | `lifecycle`, notice | A call's pinned process started outside the call's own time: refused for a state change | +| `calls.pin-late` | `lifecycle`, notice | A call's pin was written more than 30 seconds after the call opened, found when that call ends | +| `calls.pin-replaced` | `lifecycle`, notice | A call's pin is not the file its first verified use saw, found when that call ends | | `calls.token-skipped` | `lifecycle`, notice | A shell call that went out without its token, with the reason; its state changes are then refused | -| `codex.thread-shared` | `change`, info | A member's call carried the root thread's id, so the root thread names the tech lead no more in that session | +| `codex.thread-shared` | `security`, notice | A member's call carried the root thread's id, so the root thread names the tech lead no more in that session | `dev audit --action caller` and `dev audit --action calls` list them. The run's own history keeps the other half: in `dev progress history`, each step change a token-verified call makes names how devkit knew the caller (`how`) and diff --git a/docs/crew.md b/docs/crew.md index 98cda4e6..07accf66 100644 --- a/docs/crew.md +++ b/docs/crew.md @@ -417,8 +417,10 @@ that made it, from the hook's own input (the call ledger, in devkit's state, clo `DEVKIT_CALL=.` in front of the call. Before anything else runs, the call's prefix writes its shell's process id to a pin file (for a single plain `dev` call without that prefix, the `dev` process writes its own). The token then names its caller only for a `dev` command that runs in that process or below it, and only while the call -is open, so another process cannot use the token even with a copy. If another process wrote the pin first, the call -names nobody. A `dev` command reads its caller from the token once, when +is open, so another process cannot use the token even with a copy. If another process wrote the pin first, the prefix +moves that file aside, and the call names nobody. Project code that devkit runs for you (the steps of `dev ci --run`, +the tests of `dev test`, and git hooks that `dev commit` or `dev push` starts) runs without the token, so a `dev` +command in it changes no devkit state. A `dev` command reads its caller from the token once, when it starts: a main-session call names the tech lead, and a member's call names that member, whatever other calls are open or waiting at the same time. These work for the tech lead and for members alike: From 4f73b101604d2deb5660a8645dbb1de2f5390570 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 00:23:44 -0800 Subject: [PATCH 42/52] test: use neutral organization and step names in the fixtures test fixtures named a real organization and its copy-release step; a neutral name keeps the same cases without naming anyone Verified: dev test run on the seven files: 193 tests, all passed after the audit test's masked length followed the shorter name --- tests/test_audit.py | 4 ++-- tests/test_coord_kernel.py | 2 +- tests/test_coordination_identity.py | 10 +++++----- tests/test_coordination_lanes.py | 14 +++++++------- tests/test_hooks_stop_plans.py | 4 ++-- tests/test_identity_token.py | 6 +++--- tests/test_welcome_names.py | 2 +- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/tests/test_audit.py b/tests/test_audit.py index e44206cb..8b09fd05 100644 --- a/tests/test_audit.py +++ b/tests/test_audit.py @@ -1093,10 +1093,10 @@ def test_a_guard_detail_keeps_devkits_own_wording(self): f"`gh pr merge 12 --squash --body {t(12)} --head {t(20)}` merges PR #12", "`Ana Smith` is no crew member; `SECRET-plan` is unknown": f"`{t(9)}` is no crew member; `{t(11)}` is unknown", - "This session works on `signature-organization/devkit`; it must not change " + "This session works on `other-org/devkit`; it must not change " "`fireflysoftwaresolutions/devkit`'s handoff note.": # a path keeps its base name only when devkit's list has it - f"This session works on `{t(22)}/devkit`; it must not change `{t(24)}/devkit`'s handoff note."} + f"This session works on `{t(9)}/devkit`; it must not change `{t(24)}/devkit`'s handoff note."} for detail in kept + list(masked): audit.record("guard.deny", "Bash", detail, "deny", tool="Bash") details = [r["detail"] for r in audit.query(action="guard.deny")] diff --git a/tests/test_coord_kernel.py b/tests/test_coord_kernel.py index bc1f348e..1d5c1665 100644 --- a/tests/test_coord_kernel.py +++ b/tests/test_coord_kernel.py @@ -152,7 +152,7 @@ def test_an_answer_while_the_lane_is_busy_puts_the_step_first_in_that_lanes_queu self.assertEqual((s["owner"], coord.intent(s)["lane"], coord.intent(s)["front"]), ("main", "L", True)) def test_an_answer_after_the_lane_ended_goes_to_the_members_next_lane_not_the_tech_lead(self): - s = step("a", "blocked", "L", "Link: sig release", waiting="D3") + s = step("a", "blocked", "L", "Link: copy release", waiting="D3") run = run_of([s], {"L": lane("Link", "done")}) self.assertEqual(coord.unblock(run, s, False, T, review=review), "pending") self.assertEqual((coord.intent(s)["member"], coord.intent(s)["lane"], coord.intent(s)["front"]), diff --git a/tests/test_coordination_identity.py b/tests/test_coordination_identity.py index 19da84c0..3d1a53d9 100644 --- a/tests/test_coordination_identity.py +++ b/tests/test_coordination_identity.py @@ -19,11 +19,11 @@ class CoordinationCallerCase(CallerCase): def plan_with_link(self): - # the Release engineer works on sig2625; ci-redirect is the tech lead's to start + # the Release engineer works on copy-release; ci-redirect is the tech lead's to start with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): - pg.start("Release", plan=["sig2625", "ci-redirect"]) - pg.assign("sig2625", "Link", why="the test's assignment") - launch("a_link", "devkit:link", "Link: sig2625 copy release") + pg.start("Release", plan=["copy-release", "ci-redirect"]) + pg.assign("copy-release", "Link", why="the test's assignment") + launch("a_link", "devkit:link", "Link: copy-release fork release") def state_of(self, name): return next(s for s in self.run_()["plan"] if s["name"] == name).get("state") @@ -35,7 +35,7 @@ def test_the_tech_leads_begin_stays_theirs_while_a_member_waits_on_a_question_th # crew member's call" while the Release engineer's `dev crew ask` waited for its answer; that question quoted # the command, and the call ledger took the member's open call for the one that typed it self.plan_with_link() - self.call('dev crew ask "dev commit refuses my ci-redirect commit: my lane\'s scope is still sig2625\'s ' + self.call('dev crew ask "dev commit refuses my ci-redirect commit: my lane\'s scope is still copy-release\'s ' '(blocked, not closed), and dev progress begin is the tech lead\'s. Please start ci-redirect for ' 'my lane (dev progress begin ci-redirect, or whatever links it)."', aid="a_link") self.call("dev progress begin ci-redirect 2>&1 | tail -6") diff --git a/tests/test_coordination_lanes.py b/tests/test_coordination_lanes.py index 1f0ddd0b..ad93c8cf 100644 --- a/tests/test_coordination_lanes.py +++ b/tests/test_coordination_lanes.py @@ -74,15 +74,15 @@ def test_a_lane_whose_step_closes_takes_the_first_of_two_steps_assigned_to_its_m class BlockedStepTests(LaneCase): def test_a_blocked_step_leaves_its_lane_free_for_the_members_next_step_and_its_files(self): - # the Release engineer's sig2625 was blocked on the Actions budget; ci-redirect, assigned to him next, only - # "joins your lane once sig2625 closes", so dev commit refused ci-redirect's files and his + # the Release engineer's copy-release was blocked on the Actions budget; ci-redirect, assigned to him next, only + # "joins your lane once copy-release closes", so dev commit refused ci-redirect's files and his # `dev progress step --step ci-redirect` was refused - pg.start("Release", plan=["sig2625=60m", "ci-redirect=60m"], now=self.m(0)) - pg.assign("sig2625", "Link", scope="docs/copy.md", why="test", now=self.m(0)) - launch("a_link", "devkit:link", "Link: sig2625 copy release", at=self.m(1)) - pg.step("PR #20's run started no job: the Actions budget is spent", kind="blocked", which="sig2625", + pg.start("Release", plan=["copy-release=60m", "ci-redirect=60m"], now=self.m(0)) + pg.assign("copy-release", "Link", scope="docs/copy.md", why="test", now=self.m(0)) + launch("a_link", "devkit:link", "Link: copy-release fork release", at=self.m(1)) + pg.step("PR #20's run started no job: the Actions budget is spent", kind="blocked", which="copy-release", now=self.m(30)) - self.assertEqual(self.held("sig2625"), ("a_link", "blocked")) + self.assertEqual(self.held("copy-release"), ("a_link", "blocked")) pg.assign("ci-redirect", "Link", scope="lib/devkit/gitx.py,tests/test_gitx.py", why="test", now=self.m(31)) self.assertEqual(self.held("ci-redirect"), ("a_link", "running")) self.assertEqual(self.scope_of("a_link"), ["lib/devkit/gitx.py", "tests/test_gitx.py"]) diff --git a/tests/test_hooks_stop_plans.py b/tests/test_hooks_stop_plans.py index aba15210..b25517da 100644 --- a/tests/test_hooks_stop_plans.py +++ b/tests/test_hooks_stop_plans.py @@ -144,9 +144,9 @@ def test_a_read_of_a_plan_another_session_writes_meanwhile_is_not_this_sessions( class OwnPlansTests(PlanCheckCase): - # the session moved its working folder to another checkout (signature-organization/devkit) and wrote a plan of + # the session moved its working folder to another checkout (other-org/devkit) and wrote a plan of # the project it works for: the plan's own folder decides, not the folder the session is in now - MOVED = "signature-organization/devkit" + MOVED = "other-org/devkit" def test_a_plan_the_session_wrote_with_its_edit_tool_is_reminded(self): mine = self.plan("fireflysoftwaresolutions/devkit", "2026-11-10-hotfix.md") diff --git a/tests/test_identity_token.py b/tests/test_identity_token.py index c2be1b7e..e590078d 100644 --- a/tests/test_identity_token.py +++ b/tests/test_identity_token.py @@ -138,9 +138,9 @@ def dev(self, *args, token="", env=None, fresh=True): def plan_with_link(self): with mock.patch.object(pg, "caller", lambda *a, **k: {"caller": "main", "how": "test"}): - pg.start("Release", plan=["sig2625", "ci-redirect"]) - pg.assign("sig2625", "Link", why="the test's assignment") - launch("a_link", "devkit:link", "Link: sig2625 Signature release") + pg.start("Release", plan=["copy-release", "ci-redirect"]) + pg.assign("copy-release", "Link", why="the test's assignment") + launch("a_link", "devkit:link", "Link: copy-release fork release") def state_of(self, name): return next(s for s in self.run_()["plan"] if s["name"] == name).get("state") diff --git a/tests/test_welcome_names.py b/tests/test_welcome_names.py index de823b36..db4fb1f4 100644 --- a/tests/test_welcome_names.py +++ b/tests/test_welcome_names.py @@ -13,7 +13,7 @@ from devkit import welcome # noqa: E402 from test_welcome import NOW, OTHER, ROSTER, SID, Sandbox # noqa: E402 -MINE, THEIRS = "fireflysoftwaresolutions/devkit", "signature-organization/devkit" +MINE, THEIRS = "fireflysoftwaresolutions/devkit", "other-org/devkit" class SharedNames(Sandbox): From 198e199794ea9196b2f85a61f36d33c373e1111a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 00:25:07 -0800 Subject: [PATCH 43/52] fix(ci): let dev ci watch --timeout 0 take the derived limit a watch with --timeout 0 ended at once, while 0 meant the default before the limit was derived from the workflows Root cause: the derived limit made the option default None, and cmd_ci_watch passed any given value through, so 0 became a zero-minute limit instead of falling back as the old 'or 90' did Verified: new test failed first ([0.0, -5.0] != [None, None]), then dev test run tests/test_ci_watch_limits.py: 9 passed; /usr/bin/python3 3.9 OK --- lib/devkit/cli.py | 6 ++++-- tests/test_ci_watch_limits.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/devkit/cli.py b/lib/devkit/cli.py index e953d9a7..77d82172 100644 --- a/lib/devkit/cli.py +++ b/lib/devkit/cli.py @@ -2334,7 +2334,9 @@ def cmd_ci(a): def cmd_ci_watch(a, top): from . import ciwatch - res = ciwatch.watch(top, branch=a.branch, sha=getattr(a, "sha", None), timeout_min=getattr(a, "timeout", None), + limit = getattr(a, "timeout", None) # 0 or less: the repository's own limit, as 0 meant the default before + res = ciwatch.watch(top, branch=a.branch, sha=getattr(a, "sha", None), + timeout_min=limit if limit is not None and limit > 0 else None, quiet=getattr(a, "quiet", False) or a.json, since=getattr(a, "since", None)) if getattr(a, "session", None) and ":" in a.session: ciwatch.deliver(*a.session.split(":", 1), res) @@ -5185,7 +5187,7 @@ def wanted(*names): p.add_argument("--pr", help="watch --wait: the runs of this PR's head, or of its merge commit once merged") p.add_argument("--timeout", type=float, default=None, help="watch: minutes before giving up (default: the workflows' longest chain of jobs at their " - "timeout-minutes, plus 30 for the queue; 90 to 360)") + "timeout-minutes, plus 30 for the queue; 90 to 360; 0 or less takes it too)") p.add_argument("--session", help=argparse.SUPPRESS) p.add_argument("--since", type=float, help=argparse.SUPPRESS) # a PR made ready: its runs count from then p.add_argument("--quiet", action="store_true", help="watch: no progress lines, only the result") diff --git a/tests/test_ci_watch_limits.py b/tests/test_ci_watch_limits.py index f0c0ab10..01f118a6 100644 --- a/tests/test_ci_watch_limits.py +++ b/tests/test_ci_watch_limits.py @@ -122,6 +122,21 @@ def watch(top, **kw): self.assertEqual(asked, [None, 45]) +class WatchZeroTimeoutTests(unittest.TestCase): + # `--timeout 0` meant "the default" before the limit was derived; it must not end the watch at once + def test_dev_ci_watch_with_timeout_zero_takes_the_repositorys_limit(self): + from devkit import cli + asked = [] + + def watch(top, **kw): + asked.append(kw.get("timeout_min", "missing")) + return {"state": "none", "runs": [], "diagnoses": []} + with mock.patch.object(ciwatch, "watch", watch), contextlib.redirect_stdout(io.StringIO()): + cli.main(["ci", "watch", "--branch", "main", "--sha", "abc1234", "--json", "--timeout", "0"]) + cli.main(["ci", "watch", "--branch", "main", "--sha", "abc1234", "--json", "--timeout", "-5"]) + self.assertEqual(asked, [None, None]) + + class StuckJobTests(WatchCase): def test_a_job_no_runner_takes_is_named_with_its_next_action_once_nothing_else_of_its_commit_runs(self): # the deploy job's runs-on names a self-hosted label no runner has; the release job waits for an approval. From 34d73e75a21779d616df562b62141d8351f1788e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 00:59:07 -0800 Subject: [PATCH 44/52] fix(crew): advise a lane that runs no step when it edits a file After a reassignment, the old lane's edit of the new owner's file got no hook advice, and dev commit refused its staged files with the empty text "your step's scope ()". Root cause: hooks._lane_scope_miss skipped empty scope layers, so a crew lane whose only layer is empty (it runs no step, progress.lane_scope) held every path; gitx._lane_refusal printed that empty layer as () An empty layer now holds nothing in the edit check. The edit and the commit each say the lane runs no step and how to ask the tech lead for one. The reassignment tests check the hook's advice again. Verified: python3 -m unittest tests.test_coord_kernel_fixes tests.test_lane_binding tests.test_commit_lanes: 55 tests OK; dev test prove: the 3 reassignment tests and the commit text test fail without the fix --- lib/devkit/gitx.py | 7 ++++++- lib/devkit/hooks.py | 20 +++++++++++++------- tests/test_coord_kernel_fixes.py | 29 +++++++++++++++++++++++++++++ tests/test_lane_binding.py | 9 +++++++++ 4 files changed, 57 insertions(+), 8 deletions(-) create mode 100644 tests/test_coord_kernel_fixes.py diff --git a/lib/devkit/gitx.py b/lib/devkit/gitx.py index 611ba43a..13b10fea 100644 --- a/lib/devkit/gitx.py +++ b/lib/devkit/gitx.py @@ -1419,11 +1419,16 @@ def _sync_shared_index(top, before: str, left) -> str: def _lane_refusal(layers, left) -> int: - """No staged file of the lane's own: what stays staged, and why.""" + """No staged file of the lane's own: what stays staged, and why. An empty layer is a crew lane that runs no step + (progress.lane_scope): it holds no file.""" if not layers: return refuse(f"your crew lane has no file scope, so devkit cannot tell which of the {len(left)} staged " f"file(s) are yours; they stay staged: {_few(left)}", 'name your files: dev commit -m "type(scope): summary" ') + if not all(layers): + return refuse(f"your crew lane runs no step, so it holds no file: none of the {len(left)} staged file(s) is " + f"yours to commit, and they stay staged for their owner: {_few(left)}", + 'ask the tech lead to assign you a step: dev crew ask "which step is mine? I need to commit …"') where = "; ".join(", ".join(layer) for layer in layers) return refuse(f"none of the {len(left)} staged file(s) is in your step's scope ({where}); they stay staged for " f"their owner: {_few(left)}", diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index e1fbd159..691711eb 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -2968,7 +2968,8 @@ def _lane_scope_miss(path: str, cwd: str, top: str, layers: list, own_checkout: from the link's target, as the system resolves it. So a link inside the scope that leads out of the repository, or into its files that the scope does not name, holds nothing. A path in another checkout of the same repository counts from that checkout, unless the scope was given in `top` (`own_checkout`: it holds that checkout's files - only). -> (the path relative to the repository, where it lands when a link takes it out of the scope, else '').""" + only). An empty layer (a crew lane that runs no step, progress.lane_scope) holds nothing. + -> (the path relative to the repository, where it lands when a link takes it out of the scope, else '').""" from . import lanescope raw = path if os.path.isabs(path) else os.path.join(cwd, path) ap = os.path.normpath(raw) @@ -2981,7 +2982,7 @@ def _lane_scope_miss(path: str, cwd: str, top: str, layers: list, own_checkout: rel = lanescope.scope_rel(ap, cwd, base) def holds(p): - return all(lanescope.scope_holds(p, cwd, layer, base=base) for layer in layers if layer) + return all(lanescope.scope_holds(p, cwd, layer, base=base) for layer in layers) for lands in dict.fromkeys((os.path.realpath(raw), os.path.realpath(ap))): # `..` read physically, then lexically inside = os.path.relpath(lands, os.path.realpath(base)) if inside != rel and not holds(lands): # a link takes the write out of the scope @@ -3008,10 +3009,10 @@ def holds(p): def _scope_advice(agent: str, data: dict) -> list: """A crew member's file edit that its lane does not cover, as advice: an edit by a review-only or - read-only lane, or one outside its step's scope (a link that leads out of it included), which counts from the - run's repository. Scratch files and the plans its scope names are never a miss (_scope_free). An edit by an agent - devkit cannot place on a step (its launch unverified, unbound, claimed twice, or over the crew's limit) is named - too. A helper a member launches works within the member's tool level and scope, so its advice names + read-only lane, one by a lane that runs no step (it holds no file), or one outside its step's scope (a link that + leads out of it included), which counts from the run's repository. Scratch files and the plans its scope names + are never a miss (_scope_free). An edit by an agent devkit cannot place on a step (its launch unverified, + unbound, claimed twice, or over the crew's limit) is named too. A helper a member launches works within the member's tool level and scope, so its advice names that member.""" aid, tool = data.get("agent_id"), str(data.get("tool_name") or "") if not aid or tool not in EDIT_TOOLS: @@ -3053,7 +3054,12 @@ def _scope_advice(agent: str, data: dict) -> list: if not miss: continue rel, lands = miss - if lands: + if not all(layers): # its lane, or its member's, runs no step now: it holds no file + runs = f"{head}'s lane runs" if len(chain) > 1 else "your lane runs" + out.append(f"{rel} is not {name}'s to change: {runs} no step, so it holds no file (another crew member " + f"may own this one). Ask the tech lead to assign you a step: dev crew ask \"which step is " + f"mine? I need to change {rel} because …\"") + elif lands: out.append(f"{rel} leads through a link to {lands}, which is outside {name}'s scope ({where}): the write " f"lands there. Write to a path in your scope that is not a link, or ask the tech lead: " f"dev crew ask \"may I change {lands}? why: …\"") diff --git a/tests/test_coord_kernel_fixes.py b/tests/test_coord_kernel_fixes.py new file mode 100644 index 00000000..a95fdc5a --- /dev/null +++ b/tests/test_coord_kernel_fixes.py @@ -0,0 +1,29 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# Crew coordination at its edges: a lane that runs no step holds no file, and `dev commit` says so. +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_coord_kernel_fixes -v +import contextlib +import io +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +from devkit import gitx # noqa: E402 + + +class UnassignedLaneCommitTests(unittest.TestCase): + def test_a_commit_by_a_lane_that_runs_no_step_says_it_runs_none_and_names_no_empty_scope(self): + # lane_scope gives a crew lane that runs no step one empty layer: it holds no file + err = io.StringIO() + with contextlib.redirect_stderr(err): + rc = gitx._lane_refusal([[]], ["server/api.py"]) + text = err.getvalue() + self.assertEqual(rc, 2) + self.assertIn("runs no step", text) + self.assertIn("server/api.py", text) + self.assertNotIn("()", text) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_lane_binding.py b/tests/test_lane_binding.py index e0346676..1b59ddc9 100644 --- a/tests/test_lane_binding.py +++ b/tests/test_lane_binding.py @@ -314,12 +314,21 @@ def test_a_launch_that_names_none_of_the_members_steps_takes_the_oldest_step_wai class ResumeTests(LaneCase): def test_reassignment_revokes_the_old_members_scope_before_any_replacement_starts(self): self.reassignment("Tank: dashboard server", "server/**") + told = self.first_tool("a_tank", tool="Edit", file_path="server/api.py") # the new owner's file + self.assertIn(ADVICE, told) + self.assertIn("runs no step", told) def test_a_scored_launch_match_does_not_retain_authority_after_reassignment(self): self.reassignment("Tank: dashboard", "server/**") + told = self.first_tool("a_tank", tool="Edit", file_path="server/api.py") # the new owner's file + self.assertIn(ADVICE, told) + self.assertIn("runs no step", told) def test_an_unscoped_lane_loses_write_authority_after_reassignment(self): self.reassignment("Tank: dashboard server", "") + told = self.first_tool("a_tank", tool="Edit", file_path="server/api.py") # the new owner's file + self.assertIn(ADVICE, told) + self.assertIn("runs no step", told) def reassignment(self, label, scope): pg.start("Work", plan=["dashboard server"], now=self.m(0)) From 19a12f6cc666eb6b9d2a54ca7eee50809fffac98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 00:59:40 -0800 Subject: [PATCH 45/52] fix(crew): take the waiting step a launch names beside a done one A launch such as "Seraph: review the release" after a finished "review" became a follow-up of it, so "review-27", waiting for the Code reviewer, stayed pending and the lane could not write. Root cause: progress._bind_step and hooks._launch_naming made a launch a follow-up whenever a done step scored best, even when its description also named a step waiting for its member A launch is a follow-up only when it names none of the steps waiting for its member; otherwise it is scored by the waiting steps alone and claims as usual, and a tie among them gets the tech lead the dev progress assign line. The model hunt gains a launch that names a finished step and a word of a waiting one. Verified: python3 -m unittest tests.test_coord_kernel_fixes tests.test_launch_naming tests.test_hooks_launch tests.test_coord_scenarios tests.test_coord_model: 38 tests OK; the new tests and the hunt's rule fail without the fix --- lib/devkit/hooks.py | 12 +++++-- lib/devkit/progress.py | 21 ++++++++---- tests/test_coord_kernel_fixes.py | 56 ++++++++++++++++++++++++++++++-- tests/test_coord_model.py | 56 +++++++++++++++++++++++++++++--- tests/test_launch_naming.py | 51 +++++++++++++++++++++++++++++ 5 files changed, 179 insertions(+), 17 deletions(-) create mode 100644 tests/test_launch_naming.py diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 691711eb..b3568859 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -3203,8 +3203,10 @@ def _launch_naming(agent: str, data: dict) -> tuple: the exact description that takes each. - It names one (or every review it names, which one reviewer's launch holds together), its member has no step to take, or no step waits for it: (None, []). - - It names one of its member's steps that is done (a follow-up of finished work): (None, []), so it starts - unchanged and takes no step. Its description is scored against the member's done steps too. + - It names one of its member's steps that is done best, and none of the steps waiting for its launch (a + follow-up of finished work): (None, []), so it starts unchanged and takes no step. Its description is scored + against the member's done steps too. When it names a waiting step as well, it is scored by the waiting steps + alone, as above. A step waits for a launch only when its intent binds it to no lane (progress._queued_lanes, the one reader). Claude Code's Agent and Task calls only, launched by the main session with a devkit crew member's subagent_type. Codex is left as it is: it applies updatedInput only to a shell command (_codex_may_rewrite), and its spawn's @@ -3227,7 +3229,11 @@ def _launch_naming(agent: str, data: dict) -> tuple: done = [st for st in run.get("plan") or [] if st.get("state") in pg.DONE and st.get("label") and pg._label_matches(st["label"], lane)] binds, tied = _named_steps(label, steps + done) - if binds or any(st in done for st in tied): + if any(st in done for st in binds + tied): # a follow-up only when it names no waiting step + binds, tied = _named_steps(label, steps) + if not tied: + return None, [] + if binds: return None, [] who = crew.who(m) if tied: diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 1eefa1e5..66c7a11d 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -5954,11 +5954,13 @@ def _name_score(text: str, name: str) -> tuple: def _bind_step(run: dict, aid: str, lane: dict, now: float): """Give a newly bound lane its step. Its launch's task text is scored against all its member's steps, done ones - included ("Neo: session graph" → "session graph command"): a launch that names a done or skipped step best is a - follow-up of finished work (`follow_up`), left as it is, and takes no step its member was given by role; one that - names a step its member's ended lane left unverified looks at it again; otherwise the lane claims (_claim_lane): - the step it names first, else the oldest step waiting for its member. A named step whose dependencies are open - waits, and Morpheus is told.""" + included ("Neo: session graph" → "session graph command"): a launch that names a done or skipped step best, and + none of the steps waiting for its member, is a follow-up of finished work (`follow_up`), left as it is, and takes + no step its member was given by role ("Tank: api follow-up" next to "export"); one that names a waiting step too + ("Seraph: review the release" next to a done "review" and a waiting "review-27") is scored by the waiting steps + alone. One that names a step its member's ended lane left unverified looks at it again; otherwise the lane claims + (_claim_lane): the step it names first, else the oldest step waiting for its member. A named step whose + dependencies are open waits, and Morpheus is told.""" plan = run.get("plan") or [] lanes = run.get("agents") or {} mine = [st for st in plan if st.get("label") and _label_matches(st["label"], lane) and ( @@ -5972,8 +5974,13 @@ def _bind_step(run: dict, aid: str, lane: dict, now: float): top = [st for sc, st in scored if best[1] and sc == best] st = top[0] if len(top) == 1 else None if st is not None and st.get("state") in DONE: - lane["follow_up"] = st["name"] # a follow-up of finished work (B-igm9ittsioat): it binds no step - return + waiting = [(sc, x) for sc, x in scored if x.get("state") not in DONE and sc[1]] + if not waiting: # it names finished work and no step waiting for its member: it binds no step + lane["follow_up"] = st["name"] + return + best = max(sc for sc, _ in waiting) # a word it shares with a finished step does not hide a waiting one + top = [x for sc, x in waiting if sc == best] + st = top[0] if len(top) == 1 else None if st is not None and st.get("state") == "unverified": if deps_open(run, st) or coord.busy(run, aid, st, review=is_review_step): return # a dependency was reopened since: dev progress reopen gives it back once that is done diff --git a/tests/test_coord_kernel_fixes.py b/tests/test_coord_kernel_fixes.py index a95fdc5a..876a83e5 100644 --- a/tests/test_coord_kernel_fixes.py +++ b/tests/test_coord_kernel_fixes.py @@ -1,16 +1,23 @@ # Copyright (c) 2026 Firefly Software Solutions Inc. # SPDX-License-Identifier: Apache-2.0 -# Crew coordination at its edges: a lane that runs no step holds no file, and `dev commit` says so. +# Crew coordination at its edges: a lane that runs no step holds no file, and `dev commit` says so; a launch whose +# description shares a word with a finished step is a follow-up only when it names none of the steps waiting for its +# member. Progress state in a temporary folder (test_progress.TempState), every run checked against the coordination +# rules (coord.check). # Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). # Run: python3 -m unittest tests.test_coord_kernel_fixes -v import contextlib import io import sys +import time import unittest from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) -from devkit import gitx # noqa: E402 +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import coord, gitx # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_progress import TempState, launch # noqa: E402 class UnassignedLaneCommitTests(unittest.TestCase): @@ -25,5 +32,50 @@ def test_a_commit_by_a_lane_that_runs_no_step_says_it_runs_none_and_names_no_emp self.assertIn("server/api.py", text) self.assertNotIn("()", text) + +class GenericLaunchTests(unittest.TestCase): + def setUp(self): + self.state = TempState().__enter__() + self.addCleanup(self.state.__exit__, None, None, None) + self.t0 = time.time() - 3600 + + def m(self, k): + return self.t0 + k * 60 + + def run_(self): + return pg.load_run("claude", "s1") + + def held(self, name): + s = next(x for x in self.run_()["plan"] if x["name"] == name) + return s.get("owner"), s.get("state") + + def end(self, aid, kind): + pg.on_subagent("claude", {"session_id": "s1", "agent_id": aid, "agent_type": kind, + "last_assistant_message": "done"}, False, now=self.m(2)) + + def test_a_reviewers_launch_naming_a_finished_review_takes_the_review_waiting_for_it(self): + pg.start("Release", plan=["review=20m", "review-27=20m"], now=self.m(0)) + pg.assign("review", "Seraph", why="the first review", now=self.m(0), activity="review") + launch("a_s1", "devkit:seraph", "Seraph: review", at=self.m(1)) + self.end("a_s1", "devkit:seraph") + pg.reopen("review", "the first review is finished", skip=True, now=self.m(2)) + pg.assign("review-27", "Seraph", why="the release review", now=self.m(3), activity="review") + launch("a_s2", "devkit:seraph", "Seraph: review the release", at=self.m(4)) + self.assertEqual(self.held("review-27"), ("a_s2", "running")) + self.assertIsNone(self.run_()["agents"]["a_s2"].get("follow_up")) + self.assertEqual(coord.check(self.run_(), time.time(), review=pg.is_review_step), []) + + def test_a_launch_naming_a_done_step_best_still_takes_the_waiting_step_it_names(self): + pg.start("Export", plan=["api=30m", "api docs=15m"], now=self.m(0)) + pg.assign("api", "Tank", why="the api", now=self.m(0)) + launch("a_t1", "devkit:tank", "Tank: api", at=self.m(1)) + pg.step("api done", which="api", check="✓ 3 tests pass", from_agent="a_t1", now=self.m(2)) + self.end("a_t1", "devkit:tank") + pg.assign("api docs", "Tank", why="the docs", now=self.m(3)) + launch("a_t2", "devkit:tank", "Tank: api release notes", at=self.m(4)) + self.assertEqual(self.held("api docs"), ("a_t2", "running")) + self.assertIsNone(self.run_()["agents"]["a_t2"].get("follow_up")) + self.assertEqual(coord.check(self.run_(), time.time(), review=pg.is_review_step), []) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_coord_model.py b/tests/test_coord_model.py index a99d30e1..c2905dc1 100644 --- a/tests/test_coord_model.py +++ b/tests/test_coord_model.py @@ -28,24 +28,32 @@ "I-claim": "a free running lane never leaves a step waiting for it", "I-history": "the run's count of closed steps and each step's last history entry match the plan", "fix-after-changes": "the step after a review that asked for changes does not wait for that review", + "named-step-claimed": "a launch that names a step waiting for its member is no follow-up of a finished one", } -PLAN = model.PLAN + "; fix=20m [backend] after review" -STEPS, SCOPES = dict(model.STEPS, fix="tank"), dict(model.SCOPES, fix="fix/**") +# "api docs" shares a word with "api": a launch naming the finished "api" can name the waiting "api docs" too +PLAN = model.PLAN + "; fix=20m [backend] after review; api docs=15m [backend] after api" +STEPS = dict(model.STEPS, fix="tank", **{"api docs": "tank"}) +SCOPES = dict(model.SCOPES, fix="fix/**", **{"api docs": "docs/**"}) QA_PROPOSE = model.propose # the hunt patches model.propose with the one below def propose(rng, w=None): - """The QA engineer's proposals, and now and then the reviewer asking for changes on the review it runs.""" + """The QA engineer's proposals, and now and then the reviewer asking for changes on the review it runs, or a + launch of the Backend engineer whose description names a finished step of its and some other words.""" if w is not None and rng.random() < 0.15: return {"do": "reject", "member": "seraph", "step": "review", "how": "role", "named": True, "clean": True} + if w is not None and rng.random() < 0.1: + return {"do": "generic", "member": "tank", "step": "api docs", "how": "role", "named": False, "clean": True} return QA_PROPOSE(rng, w) def show(seq: list) -> str: - """model.show, with this hunt's own action.""" - return " → ".join(f"{i}. Seraph asks for changes on review" if x["do"] == "reject" else + """model.show, with this hunt's own actions.""" + own = {"reject": lambda x: "Seraph asks for changes on review", + "generic": lambda x: f"launch Tank “Tank: {x.get('used')}”"} + return " → ".join(f"{i}. {own[x['do']](x)}" if x["do"] in own else f"{i}. " + model.show([x]).split(". ", 1)[1] for i, x in enumerate(seq, 1)) @@ -53,6 +61,8 @@ class CoordWorld(model.World): """The QA engineer's world, checked against coord.check after each action as well as its own rules.""" def act(self, a): + if a["do"] == "generic": + return self.generic(a) if a["do"] != "reject": return super().act(a) aid = self.live("seraph") @@ -73,6 +83,39 @@ def act(self, a): self.check(a, before, None) return True + def generic(self, a): + """A new launch of the Backend engineer described by a finished step of its and other words (“Tank: api + release notes”): when the description names a step waiting for its member too, the lane is no follow-up of + the finished step.""" + member, name = "tank", model.MEMBERS["tank"][0] + if self.live(member) or (self.lanes.get(member) and self.lanes[member] not in self.ended): + return False + plan = self.plan() + done = [n for n, m in STEPS.items() if m == member and plan[n].get("state") in ("done", "skipped")] + if not done: + return False + before = {k: v.get("state") for k, v in plan.items()} + self.close_member_call(member) + task = a["used"] = f"{done[0]} release notes" + aid = f"a{member}g{self.k}" + try: + model.launch(aid, member if self.host == "codex" else f"devkit:{member}", f"{name}: {task}", + at=self.now(), agent=self.host) + except AssertionError: # Codex's admission refused the launch (a slot, the order): nothing started + return False + self.lanes[member] = aid + self.ended.discard(aid) + run = self.run_() + lane = run["agents"].get(aid) or {} + named = [s["name"] for s in run["plan"] if s.get("state") == "pending" and STEPS.get(s["name"]) == member + and (s.get("owner") or "main") == "main" and (s.get("label") or "").lower().startswith(member) + and pg._name_score(task, s["name"])[1]] + if named and lane.get("follow_up"): + self.flag("named-step-claimed", f"“{name}: {task}” names {', '.join(named)}, which waits for {name}, " + f"yet its lane follows up the finished “{lane['follow_up']}” and takes no step") + self.check(a, before, None) + return True + def check(self, a, before, expect): super().check(a, before, expect) for v in coord.check(self.run_(), time.time(), review=pg.is_review_step): @@ -131,6 +174,9 @@ def test_the_history_matches_the_plan(self): def test_the_fix_after_a_review_that_asked_for_changes_can_start(self): self.holds("fix-after-changes") + def test_a_launch_naming_a_waiting_step_is_no_follow_up_of_a_finished_one(self): + self.holds("named-step-claimed") + if __name__ == "__main__": unittest.main() diff --git a/tests/test_launch_naming.py b/tests/test_launch_naming.py new file mode 100644 index 00000000..9c7d8dd3 --- /dev/null +++ b/tests/test_launch_naming.py @@ -0,0 +1,51 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# A crew launch checked before it starts (hooks._launch_naming) by the rule that binds it once it runs +# (progress._bind_step): a description that names a finished step is a follow-up only when it names none of the +# steps waiting for its member; one that names two of them equally gets the tech lead the line that links the one it +# does. Progress state in a temporary folder (test_progress.TempState). +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_launch_naming -v +import sys +import tempfile +import time +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import hooks # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_progress import TempState, launch # noqa: E402 + + +def call(description: str, kind: str = "devkit:tank") -> dict: + return {"session_id": "s1", "tool_name": "Agent", "tool_use_id": "toolu_n1", "hook_event_name": "PreToolUse", + "cwd": tempfile.gettempdir(), + "tool_input": {"description": description, "subagent_type": kind, "prompt": "Write the docs."}} + + +class FollowUpNamingTests(unittest.TestCase): + def setUp(self): + self.state = TempState().__enter__() + self.addCleanup(self.state.__exit__, None, None, None) + t0 = time.time() - 3600 + pg.start("Export", plan=["api", "api docs", "api tests"], now=t0) + pg.assign("api", "Tank", why="the api", now=t0) + launch("a_t1", "devkit:tank", "Tank: api", at=t0 + 60) + pg.step("api done", which="api", check="✓ 3 tests pass", from_agent="a_t1", now=t0 + 120) + pg.on_subagent("claude", {"session_id": "s1", "agent_id": "a_t1", "agent_type": "devkit:tank", + "last_assistant_message": "done"}, False, now=t0 + 180) + + def test_a_launch_naming_a_done_step_and_two_waiting_steps_equally_gets_the_line_that_links_one(self): + for step in ("api docs", "api tests"): + pg.assign(step, "Tank", why="the follow-up work") + new, told = hooks._launch_naming("claude", call("Tank: api release notes")) + self.assertIsNone(new) + self.assertEqual(len(told), 1, told) + self.assertIn("names “api docs”, “api tests” equally", told[0]) + self.assertIn('dev progress assign "" --to "Tank: api release notes"', told[0]) + + +if __name__ == "__main__": + unittest.main() From 07fbdc64e994d2797cb1c86ef869a188585cdc6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 00:59:54 -0800 Subject: [PATCH 46/52] fix(hooks): keep a member's lane route when its call token fails An OSError while the call token was stamped made the PreToolUse hook raise, so the member's call ran without its lane route, its advice and its lessons. Root cause: hooks._pre_tool called _stamped_token outside any try, and each progress.call_note and call_entry inside it can raise A failure while stamping now costs the call its token only: it is logged and audited as calls.token-skipped with the reason, and the call still goes out with its route. Verified: python3 -m unittest tests.test_pre_tool_hook.TokenStampFailureTests tests.test_identity_token tests.test_codex_identity_token: 44 tests OK; dev test prove: the new test fails without the fix --- lib/devkit/hooks.py | 8 +++++++- tests/test_pre_tool_hook.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index b3568859..069ca683 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -3361,7 +3361,13 @@ def _pre_tool(agent: str, data: dict): for line in advice: _log(f"pre-tool {agent} advice: {line[:160]}") _post_codex_advice(agent, data, advice, bool(unroutable)) - final = _stamped_token(agent, data, routed or stamped, token, digest) if tool in SHELL_TOOLS else None + final = None + if tool in SHELL_TOOLS: + try: + final = _stamped_token(agent, data, routed or stamped, token, digest) + except Exception as e: # the call goes out without its token, never without its route, advice and lessons + _log(f"pre-tool token {agent}: {traceback.format_exc()[-300:]}") + _token_skipped(agent, data, f"stamping it failed ({type(e).__name__}: {e}): it goes out without it") if routed or stamped or final: if not routed: # a call that only gains who runs it records what every other call records try: diff --git a/tests/test_pre_tool_hook.py b/tests/test_pre_tool_hook.py index b7046494..a23ab2e2 100644 --- a/tests/test_pre_tool_hook.py +++ b/tests/test_pre_tool_hook.py @@ -574,5 +574,42 @@ def test_the_pre_tool_handler_keeps_a_read_only_lanes_worktree_state_before_its_ self.assertIn("notes.md", entry.get("wt_before") or {}, entry) +class TokenStampFailureTests(unittest.TestCase): + # a failure while the call token is stamped (its pin's ledger note here) costs the call its token, audited, + # never its lane route: the hook never fails closed on the session + def setUp(self): + from test_progress import TempState + self.state = TempState().__enter__() + self.addCleanup(self.state.__exit__, None, None, None) + + def test_a_ledger_failure_while_the_token_is_stamped_still_routes_the_members_call_to_its_lane(self): + import contextlib + import io + from devkit import audit, hooks, progress as pg + from test_progress import launch + pg.start("Export", plan=["api=30m"]) + pg.assign("api", "Tank", why="the api") + launch("a_tank", "devkit:tank", "Tank: api") + call = {"session_id": "s1", "agent_id": "a_tank", "agent_type": "devkit:tank", "tool_name": "Bash", + "tool_use_id": "toolu_stamp1", "permission_mode": "bypassPermissions", "cwd": str(ROOT), + "hook_event_name": "PreToolUse", "tool_input": {"command": 'dev progress note "working"'}} + real = pg.call_note + + def note(data, **fields): + if "pin" in fields: + raise OSError("No space left on device") + return real(data, **fields) + out = io.StringIO() + with mock.patch.object(pg, "call_note", note), mock.patch("sys.stdin", io.StringIO(json.dumps(call))), \ + contextlib.redirect_stdout(out): + hooks.run("pre-tool", "claude") + spec = (json.loads(out.getvalue()) if out.getvalue().strip() else {}).get("hookSpecificOutput") or {} + command = (spec.get("updatedInput") or {}).get("command", "") + self.assertEqual(command, 'DEVKIT_FROM_AGENT=a_tank dev progress note "working"') + skipped = audit.records(1, action="calls.token-skipped") + self.assertEqual(len(skipped), 1, skipped) + self.assertIn("No space left on device", json.dumps(skipped[0], ensure_ascii=False)) + + if __name__ == "__main__": unittest.main() From 3c5b8a17bfff68337898587c32e92200cf093e0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 01:00:11 -0800 Subject: [PATCH 47/52] fix(crew): start a delegated step through the claim rule dev crew delegate set the step running in a free lane with no history entry, so the coordination check reported that its last history entry said pending. Root cause: dispatch.delegate changed the step's owner and state itself instead of giving it an intent for the lane and letting coord.claim start it The delegated step gets an intent for its member's working lane, and _claim_free_lanes starts it there when the lane is free, or once its step closes. The delegation's own notice is the lane's only one: the claim sends none for a step its caller tells the lane about. Verified: python3 -m unittest tests.test_crew_delegate tests.test_dispatch tests.test_dispatch_busy_lane tests.test_lane_binding tests.test_plan_dag tests.test_raci: 99 tests OK; dev test prove: the new test fails without the fix --- lib/devkit/dispatch.py | 21 +++++++-------- lib/devkit/progress.py | 15 ++++++----- tests/test_crew_delegate.py | 51 +++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 16 deletions(-) create mode 100644 tests/test_crew_delegate.py diff --git a/lib/devkit/dispatch.py b/lib/devkit/dispatch.py index 7e0ce067..215111d1 100644 --- a/lib/devkit/dispatch.py +++ b/lib/devkit/dispatch.py @@ -25,7 +25,7 @@ import re import time -from . import core, progress +from . import coord, core, progress from .progress import StepError, _find_step, _lane, _log_change, _new_step, load_run, normalize, current_session # files that say who should do the work (globs on the repo-relative path) @@ -195,16 +195,17 @@ def delegate(task: str, to: str = "auto", files=None, scope: str = "", after: st if progress._label_matches(m["name"], v)), None) before = [] # the steps that close before it joins a busy lane if lane_id and lane_id != from_agent and not progress.deps_open(run, s): # a step that waits does not start - if progress._open_step_of(run, lane_id, s): - # the lane works on another step: as an assigned step, it joins the lane once that step closes, and - # takes its own scope then (progress._route_to_lane), instead of merging its files into the lane's now - s["waits_lane"] = {"lane": lane_id, "ts": round(now, 3)} - before = progress._closes_before(run, lane_id, s) + # an intent for that lane: the claim rule starts it there now when the lane is free, else once the lane's + # step closes, with its own scope then (coord.claim, with its history entry); the notice below tells the + # lane, so the claim sends none of its own + coord.set_intent(run, s, m["name"], lane_id, now) + progress._claim_free_lanes(run, now, told=(name,)) + if s.get("owner") == lane_id: + held = coord.scope(run, lane_id) # the readers' mirror of its running steps' scope, as normalize keeps + if held: + run["agents"][lane_id]["scope"] = held else: - s.update(owner=lane_id, state="running", started=now, joined=lane_id) # its launch does not name it - if s.get("scope"): - run["agents"][lane_id]["scope"] = sorted(set((run["agents"][lane_id].get("scope") or []) - + s["scope"])) + before = progress._closes_before(run, lane_id, s) progress._save(run, touch_session=False) progress._audit("crew.delegate", f"{by} → {m['name']}", task.strip()[:300], project=run.get("project") or "", step=name, routed="yes" if routed else "no") diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 66c7a11d..8810b843 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -2131,11 +2131,12 @@ def _launch_named(run: dict, aid: str, lane: dict): return top[0] if best[1] and len(top) == 1 else None -def _claim_lane(run: dict, aid: str, now: float, member_wide: bool = True) -> list: +def _claim_lane(run: dict, aid: str, now: float, member_wide: bool = True, told=()) -> list: """Lane `aid`, when it is free, takes the steps the claim rule gives it (coord.claim): the one its launch names, else the oldest intent for it; a reviewer's lane goes on taking ready reviews, since reviews share a lane. Each - step is recorded in the lane, and its member is told when its launch did not name it. `member_wide` False: a - resume whose member has a new launch on its way leaves the member's steps to that launch. -> the steps taken""" + step is recorded in the lane, and its member is told when its launch did not name it, unless the step is in + `told` (the caller tells the lane itself, as dev crew delegate does). `member_wide` False: a resume whose member + has a new launch on its way leaves the member's steps to that launch. -> the steps taken""" from . import crew lane = (run.get("agents") or {}).get(aid) taken = [] @@ -2155,6 +2156,7 @@ def _claim_lane(run: dict, aid: str, now: float, member_wide: bool = True) -> li s.pop("joined", None) else: s["joined"] = aid # its launch does not name it: only the lane's own evidence closes it (_steps_about) + if s["name"] != named and s["name"] not in told: rest = [x["name"] for x in _queued_for(run, aid)] scope = f" (your scope: {', '.join(s['scope'])})" if s.get("scope") else "" _post(run, "devkit", aid, f"devkit: “{s['name']}” is your step now{scope}: close it with dev progress " @@ -2165,10 +2167,11 @@ def _claim_lane(run: dict, aid: str, now: float, member_wide: bool = True) -> li return taken -def _claim_free_lanes(run: dict, now: float): +def _claim_free_lanes(run: dict, now: float, told=()): """Every lane that can take a step claims what waits for it (_claim_lane), oldest lane first: after any change that frees a lane, readies a step or gives one an intent. A lane the record lists as running whose member ended - or went stale (lane_states, read only when some lane has a step to claim) takes nothing.""" + or went stale (lane_states, read only when some lane has a step to claim) takes nothing. `told`: the steps whose + lane the caller tells itself.""" agents = run.get("agents") or {} states = None for aid in sorted(agents, key=lambda k: (agents[k].get("started") or 0, k)): @@ -2178,7 +2181,7 @@ def _claim_free_lanes(run: dict, now: float): states = lane_states(run, now, own=True) if (states.get(aid) or {}).get("state", "working") != "working": continue - _claim_lane(run, aid, now) + _claim_lane(run, aid, now, told=told) def _background_running(agent: str, sid: str, aid: str) -> list: diff --git a/tests/test_crew_delegate.py b/tests/test_crew_delegate.py new file mode 100644 index 00000000..aed49053 --- /dev/null +++ b/tests/test_crew_delegate.py @@ -0,0 +1,51 @@ +# Copyright (c) 2026 Firefly Software Solutions Inc. +# SPDX-License-Identifier: Apache-2.0 +# `dev crew delegate` gives the new step to its member by an intent, and a free working lane of that member claims +# it through the claim rule (coord.claim), so the step starts with its history entry and the run keeps every +# coordination rule (coord.check). Progress state in a temporary folder (test_progress.TempState). +# Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). +# Run: python3 -m unittest tests.test_crew_delegate -v +import sys +import time +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from devkit import coord, dispatch # noqa: E402 +from devkit import progress as pg # noqa: E402 +from test_progress import TempState, launch # noqa: E402 + + +class DelegateClaimTests(unittest.TestCase): + def setUp(self): + self.state = TempState().__enter__() + self.addCleanup(self.state.__exit__, None, None, None) + self.t0 = time.time() - 3600 + + def m(self, k): + return self.t0 + k * 60 + + def test_a_step_delegated_into_a_free_lane_starts_by_the_claim_rule_with_its_history(self): + pg.start("Export", plan=["api=30m", "docs=15m"], now=self.m(0)) + pg.assign("api", "Tank", why="the api", now=self.m(0)) + launch("a_tank", "devkit:tank", "Tank: api", at=self.m(1)) + launch("a_neo", "devkit:neo", "Neo: look", at=self.m(1)) + pg.step("api done", which="api", check="✓ 3 tests pass", from_agent="a_tank", now=self.m(5)) + out = dispatch.delegate("write the parser", to="Tank", from_agent="a_neo", scope="parser/**", now=self.m(6)) + run = pg.load_run("claude", "s1") + st = next(s for s in run["plan"] if s.get("task") == "write the parser") + self.assertEqual((out["lane"], st.get("owner"), st.get("state")), ("a_tank", "a_tank", "running")) + last = [h for h in run.get("history") or [] if h.get("step") == st["name"]][-1] + self.assertEqual((last.get("from"), last.get("to")), ("pending", "running")) + self.assertNotIn("intent", st) + self.assertEqual(pg.lane_scope(run, "a_tank"), [["parser/**"]]) + self.assertEqual(coord.check(run, time.time(), review=pg.is_review_step), []) + # one notice tells the lane: the delegation's, with who delegates and how to decline, not the claim's too + told = [x.get("text") or "" for x in run.get("messages") or [] if x.get("to") == "a_tank"] + self.assertEqual(len(told), 1, told) + self.assertIn("delegates “write the parser”", told[0]) + + +if __name__ == "__main__": + unittest.main() From 39f4816c3b800b2c8a23aad33a9356d78004a85b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 01:00:25 -0800 Subject: [PATCH 48/52] fix(crew): tell the tech lead once about a stop the gates let through A stop the crew gates let through sent the tech lead two notices at once: what the gates still found, and which reviews of that stop count for nothing. Root cause: hooks._tell_lead_findings and progress._tell_uncounted each posted their own notice for the same lane's end The hook words the findings (hooks._findings_told) and passes them to the lane's end as a parameter, which posts one notice with both. A stop that meets a busy session lock keeps them in its pending file, like its stop time. Verified: python3 -m unittest tests.test_coord_kernel_fixes tests.test_hooks_gate_findings tests.test_hook_capture tests.test_approvals_token: 28 tests OK; dev test run of the 53 stop-path test files: 1154 passed, 1 skipped --- lib/devkit/hooks.py | 42 ++++++++++----------------- lib/devkit/progress.py | 50 ++++++++++++++++++++------------ tests/test_coord_kernel_fixes.py | 43 +++++++++++++++++++++++++-- 3 files changed, 87 insertions(+), 48 deletions(-) diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 069ca683..6483c672 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -4322,31 +4322,14 @@ def judge(): FINDINGS_TOLD = 6 # gate findings one notice to the tech lead names, the rest counted -def _tell_lead_findings(agent: str, data: dict, findings: list): - """A member's stop the crew gates let through with findings (sent back once in this lane life already, or only - recorded): the tech lead hears them as devkit's notice, with the member's name, since that stop's Check approves - nothing and no review it closes counts. Never raises (logged).""" - from . import progress - sid, aid = str(data.get("session_id") or ""), str(data.get("agent_id") or "") - if not findings or not sid: - return - try: - with progress._tx(agent, sid): - run = progress.load_run(agent, sid) - if not run: - return - run = progress.normalize(run) - lane = (run.get("agents") or {}).get(aid) or {} - who = _who(lane.get("persona") or lane.get("label") or str(data.get("agent_type") or "A crew member")) - named = "; ".join(_inline(f"{f.get('rule')}: {f.get('item')}", 160) for f in findings[:FINDINGS_TOLD]) - more = f" and {len(findings) - FINDINGS_TOLD} more" if len(findings) > FINDINGS_TOLD else "" - progress._post(run, "devkit", "main", - f"devkit: {who} stopped, and the crew gates let it through with what is still missing: " - f"{named}{more}. A review or verdict of that stop counts for nothing: check its work, or " - f"send it back with the fix.", time.time(), from_name="devkit", kind="notice") - progress._save(run, touch_session=False) - except Exception: - _log(f"subagent-stop findings {agent}: {traceback.format_exc()[-300:]}") +def _findings_told(findings: list) -> str: + """What the crew gates still found in a member's stop they let through (sent back once in this lane life already, + or only recorded), as the tech lead's notice names it: the first FINDINGS_TOLD, the rest counted. The lane's end + puts it in its one notice to the tech lead (progress._tell_uncounted), since that stop's Check approves nothing + and no review it closes counts. '' without findings.""" + named = "; ".join(_inline(f"{f.get('rule')}: {f.get('item')}", 160) for f in (findings or [])[:FINDINGS_TOLD]) + more = f" and {len(findings) - FINDINGS_TOLD} more" if len(findings or []) > FINDINGS_TOLD else "" + return named + more def subagent_stop(agent: str): @@ -4470,8 +4453,13 @@ def subagent_stop(agent: str): print(json.dumps(out)) return _lessons_end(data, str(data.get("agent_id") or "")) # the member's lane ended: what it did not hit was heeded - progress.on_subagent(agent, data, False) - _tell_lead_findings(agent, data, let_through) + # the lane's end tells the tech lead once: what the gates still found, and what of its work counts for nothing + try: + told = _findings_told(let_through) + except Exception as e: # findings devkit cannot word never keep the lane from ending + told = "" + _swallowed("subagent-stop", e) + progress.on_subagent(agent, data, False, findings=told) _continuity("on_subagent_stop", agent, data) # a last read of its transcript: a compaction no hook saw _prompt_refresh(data, force=True) # a lane closed: the prompt's crew count follows diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 8810b843..28ea5a23 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -4975,17 +4975,26 @@ def _lane_verdicts(run: dict, lane: dict, aid: str, passed: bool, now: float): project=run.get("project") or "") -def _tell_uncounted(run: dict, lane: dict, now: float): - """At a lane's end, one devkit notice to the tech lead naming the reviews and verdicts its member gave that do - not count (_end_member_step, _lane_verdicts), since the crew gates did not pass its report; the hook names the - gate findings themselves.""" +def _tell_uncounted(run: dict, lane: dict, now: float, findings: str = ""): + """At a lane's end, one devkit notice to the tech lead: what the crew gates still found in the stop they let + through (`findings`, the hook's summary, hooks._findings_told), and the reviews and verdicts its member gave that + do not count (_end_member_step, _lane_verdicts), since the gates did not pass its report. Nothing when there is + neither.""" held = list(dict.fromkeys(run.pop("_uncounted", None) or [])) - if held: - from . import crew - _post(run, "devkit", "main", f"devkit: {crew.who(lane.get('persona') or lane.get('label') or 'a member')}'s " - f"report did not pass the crew gates, so {_quoted_list(held)} count{'s' if len(held) == 1 else ''} " - f"for nothing yet: the work stays owed until a report the gates pass (resume the member, or launch the " - f"review again)", now, from_name="devkit", kind="notice") + if not held and not findings: + return + from . import crew + who = crew.who(lane.get("persona") or lane.get("label") or "a member") + owed = f"{_quoted_list(held)} count{'s' if len(held) == 1 else ''} for nothing yet" if held else "" + if findings: + text = (f"devkit: {who} stopped, and the crew gates let it through with what is still missing: {findings}. " + + (f"So {owed}: check its work, or send it back with the fix (resume the member, or launch the review " + f"again)." if held else "A review or verdict of that stop counts for nothing: check its work, or " + "send it back with the fix.")) + else: + text = (f"devkit: {who}'s report did not pass the crew gates, so {owed}: the work stays owed until a report " + f"the gates pass (resume the member, or launch the review again)") + _post(run, "devkit", "main", text, now, from_name="devkit", kind="notice") def _quoted_list(items: list) -> str: @@ -6868,22 +6877,23 @@ def _order_verdict(run, sess, kind: str, label: str, b: dict, cost: float, now: f"or record why this one goes ahead: dev crew next --first {shlex.quote(st['name'])} --why \"…\"") -def on_subagent(agent: str, data: dict, started: bool, now: float | None = None): +def on_subagent(agent: str, data: dict, started: bool, now: float | None = None, findings: str = ""): """SubagentStart / SubagentStop; see _on_subagent. Serialized per session like note_agent_launch: one hold covers the session record and the run (the run's save inside re-enters it). The stops that found the lock busy earlier go first. A stop that finds it busy now waits in a pending file (_defer_stop) instead of being dropped: the - member's report is its step's evidence.""" + member's report is its step's evidence. `findings`: what the crew gates still found in a stop they let through + (hooks._findings_told), which the lane's end tells the tech lead.""" sid = data.get("session_id") or "-" entered = False try: with state.hold(session_path(agent, sid)): entered = True _apply_stops(agent, sid) - return _on_subagent(agent, data, started, now) + return _on_subagent(agent, data, started, now, findings) except state.StateBusy: if entered or started: raise # a record that does not parse, or a start: a start binds again at the agent's first tool call - _defer_stop(agent, sid, data, now or time.time()) + _defer_stop(agent, sid, data, now or time.time(), findings) def _stops_dir(agent: str, sid: str) -> Path: @@ -6891,14 +6901,15 @@ def _stops_dir(agent: str, sid: str) -> Path: return SESSIONS.parent / "stops" / f"{_safe_name(agent)}-{_safe_name(sid)}" -def _defer_stop(agent: str, sid: str, data: dict, now: float): +def _defer_stop(agent: str, sid: str, data: dict, now: float, findings: str = ""): """Keep a SubagentStop the session's lock could not take, with when it happened, for the next hook (apply_stops). Without an agent id there is nothing to apply it to: it is dropped, as before, and audited.""" aid = str(data.get("agent_id") or data.get("subagent_id") or "") if not AGENT_ID.fullmatch(aid): _audit("crew.stop-dropped", aid or "?", "the session's lock was busy and the stop names no agent", "dropped") return - _write_private(_stops_dir(agent, sid) / f"{aid}.json", {**data, "stopped_at": now}) + _write_private(_stops_dir(agent, sid) / f"{aid}.json", {**data, "stopped_at": now, + **({"gate_findings": findings} if findings else {})}) _audit("crew.stop-deferred", aid[:16], "the session's lock was busy: applied at the next hook", "deferred") @@ -6928,7 +6939,7 @@ def when(stop): for data, p in sorted(((core.read_json(p, None), p) for p in d.glob("*.json")), key=when): if isinstance(data, dict): try: - _on_subagent(agent, data, False, data.get("stopped_at")) + _on_subagent(agent, data, False, data.get("stopped_at"), str(data.get("gate_findings") or "")) except state.StateBusy: return n # a record that does not parse: kept for the next hook except Exception as e: @@ -6944,7 +6955,7 @@ def _stop_report(data: dict) -> str: return str(data.get("last_assistant_message") or "") -def _on_subagent(agent: str, data: dict, started: bool, now: float | None = None): +def _on_subagent(agent: str, data: dict, started: bool, now: float | None = None, findings: str = ""): """SubagentStart: the agent binds to its launch when something names it already (the launch's result came first), else gets a provisional lane while a launch waits, and no lane as a helper; a known agent resumes its own lane and takes nothing else. SubagentStop: a last binding (an agent that used only tools without hooks), @@ -6995,7 +7006,8 @@ def finish(run, rsid=sid): spent.append(passed) _end_lane_steps(run, lane or {}, aid, report, now, agent, rsid, passed=passed) _lane_verdicts(run, lane or {}, aid, passed, now) - _tell_uncounted(run, lane or {}, now) + # what the gates still found goes in the session's own run, once + _tell_uncounted(run, lane or {}, now, findings if rsid == sid else "") run["step"] = sum(1 for x in run.get("plan") or [] if x.get("state") in ("done", "skipped")) _advance_main(run, now) _run_event(agent, sid, finish) diff --git a/tests/test_coord_kernel_fixes.py b/tests/test_coord_kernel_fixes.py index 876a83e5..a59b0006 100644 --- a/tests/test_coord_kernel_fixes.py +++ b/tests/test_coord_kernel_fixes.py @@ -2,8 +2,8 @@ # SPDX-License-Identifier: Apache-2.0 # Crew coordination at its edges: a lane that runs no step holds no file, and `dev commit` says so; a launch whose # description shares a word with a finished step is a follow-up only when it names none of the steps waiting for its -# member. Progress state in a temporary folder (test_progress.TempState), every run checked against the coordination -# rules (coord.check). +# member; a stop the crew gates let through tells the tech lead once. Progress state in a temporary folder +# (test_progress.TempState), every run checked against the coordination rules (coord.check). # Tests carry comments, not docstrings (`dev test prove` leaves out tests with one). # Run: python3 -m unittest tests.test_coord_kernel_fixes -v import contextlib @@ -12,11 +12,13 @@ import time import unittest from pathlib import Path +from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "lib")) sys.path.insert(0, str(Path(__file__).resolve().parent)) from devkit import coord, gitx # noqa: E402 from devkit import progress as pg # noqa: E402 +from test_approvals_token import StopCase # noqa: E402 from test_progress import TempState, launch # noqa: E402 @@ -77,5 +79,42 @@ def test_a_launch_naming_a_done_step_best_still_takes_the_waiting_step_it_names( self.assertIsNone(self.run_()["agents"]["a_t2"].get("follow_up")) self.assertEqual(coord.check(self.run_(), time.time(), review=pg.is_review_step), []) + +class LetThroughNoticeTests(StopCase): + # the Code reviewer's stop, sent back once for its missing step record and then let through: the tech lead hears + # it in one notice, with what the gates still found and the review that counts for nothing + def test_a_stop_the_gates_let_through_tells_the_tech_lead_once(self): + self.stop() + self.stop(stop_hook_active=True) + told = [x.get("text") or "" for x in self.run_().get("messages") or [] + if x.get("to") == "main" and x.get("from") == "devkit"] + self.assertEqual(len(told), 1, told) + self.assertIn("Code reviewer (Seraph) stopped, and the crew gates let it through", told[0]) + self.assertIn("proofs: dev progress step", told[0]) + self.assertIn("the review “review” counts for nothing yet", told[0]) + + +class DeferredStopNoticeTests(unittest.TestCase): + # a stop that meets a busy session lock waits in its pending file with what the gates still found, and the tech + # lead hears it when the stop is applied + def test_a_deferred_stop_keeps_what_the_gates_found_for_the_tech_leads_notice(self): + from devkit import state + with TempState(): + pg.start("Export", plan=["api=30m"]) + pg.assign("api", "Tank", why="the api") + launch("a_tank", "devkit:tank", "Tank: api") + stop = {"session_id": "s1", "agent_id": "a_tank", "agent_type": "devkit:tank", + "last_assistant_message": "done"} + with mock.patch.object(state, "hold", side_effect=state.StateBusy("held by another hook")): + pg.on_subagent("claude", stop, False, findings="proofs: dev progress step") + self.assertEqual(pg.load_run("claude", "s1")["agents"]["a_tank"]["state"], "running") # not applied yet + self.assertEqual(pg.apply_stops("claude", "s1"), 1) + told = [x.get("text") or "" for x in pg.load_run("claude", "s1").get("messages") or [] + if x.get("to") == "main" and x.get("from") == "devkit" and "crew gates" in (x.get("text") or "")] + self.assertEqual(len(told), 1, told) + self.assertIn("Backend engineer (Tank) stopped, and the crew gates let it through with what is still missing: " + "proofs: dev progress step", told[0]) + + if __name__ == "__main__": unittest.main() From 2aa2d2ebae0fc9fcad436cdd1eb53de7c2fe81eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 01:07:08 -0800 Subject: [PATCH 49/52] fix(crew): say what a launch that names two steps equally takes the tech lead's notice said such a launch takes none of the member's steps, while the claim rule gives its lane the oldest step waiting for that member Root cause: the notice was written before claims went first-in first-out, and no test checked what it says the launch takes Verified: dev test run tests/test_hooks_launch.py tests/test_launch_naming.py: 9 passed --- lib/devkit/hooks.py | 4 ++-- tests/test_hooks_launch.py | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/devkit/hooks.py b/lib/devkit/hooks.py index 6483c672..bdf2c16d 100644 --- a/lib/devkit/hooks.py +++ b/lib/devkit/hooks.py @@ -3239,8 +3239,8 @@ def _launch_naming(agent: str, data: dict) -> tuple: if tied: given = [(st["name"], _naming_description(label, st["name"], m["name"], steps)) for st in tied] names = ", ".join(f"“{n}”" for n, _ in given) - return None, [f"the launch “{label}” names {names} equally, so it takes none of {who}'s steps when it " - f"starts. The description that takes one: " + return None, [f"the launch “{label}” names {names} equally, so when it starts it takes the oldest step " + f"waiting for {who}, not one by its name. The description that takes one: " + " · ".join(f"“{d}” for “{n}”" for n, d in given if d) + f"; for this launch, dev progress assign \"\" --to \"{label}\" links the one it does"] waiting = [st for st in steps if not pg._queued_lanes(st) and st.get("state") in ("pending", "unverified") diff --git a/tests/test_hooks_launch.py b/tests/test_hooks_launch.py index 0badceae..f3370383 100644 --- a/tests/test_hooks_launch.py +++ b/tests/test_hooks_launch.py @@ -164,6 +164,8 @@ def test_a_description_that_names_two_steps_equally_gets_a_notice_that_tells_the self.assertIsNone(new) self.assertEqual(len(told), 1, told) self.assertIn("“Mouse: tests” names “visual tests”, “unit tests” equally", told[0]) + self.assertIn("it takes the oldest step waiting for", told[0]) # what the claim rule does, not "none" + self.assertNotIn("takes none of", told[0]) self.assertIn("“Mouse: visual tests” for “visual tests” · “Mouse: unit tests” for “unit tests”", told[0]) self.assertEqual(again, (None, [])) From b2e2b7b3c006b5e73e07e20b05f66e5e8e3fc1c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 01:16:34 -0800 Subject: [PATCH 50/52] fix(crew): name the member in a gates notice its run does not list a stop under the conversation's newer session id, whose run does not list the lane, told the tech lead that 'a member stopped' Root cause: the single gates notice took the member's name only from the run's lane record, and the earlier fallback to the stop's agent type went with the second notice Verified: new test failed first ('a member stopped'), then dev test run of the coordination fix, lane binding and kernel tests: 45 passed; /usr/bin/python3 3.9 OK --- lib/devkit/progress.py | 3 ++- tests/test_coord_kernel_fixes.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/devkit/progress.py b/lib/devkit/progress.py index 28ea5a23..e148f29a 100644 --- a/lib/devkit/progress.py +++ b/lib/devkit/progress.py @@ -7007,7 +7007,8 @@ def finish(run, rsid=sid): _end_lane_steps(run, lane or {}, aid, report, now, agent, rsid, passed=passed) _lane_verdicts(run, lane or {}, aid, passed, now) # what the gates still found goes in the session's own run, once - _tell_uncounted(run, lane or {}, now, findings if rsid == sid else "") + # a run that does not list the lane names the member from the stop's own agent type + _tell_uncounted(run, lane or {"persona": kind}, now, findings if rsid == sid else "") run["step"] = sum(1 for x in run.get("plan") or [] if x.get("state") in ("done", "skipped")) _advance_main(run, now) _run_event(agent, sid, finish) diff --git a/tests/test_coord_kernel_fixes.py b/tests/test_coord_kernel_fixes.py index a59b0006..aa62deda 100644 --- a/tests/test_coord_kernel_fixes.py +++ b/tests/test_coord_kernel_fixes.py @@ -116,5 +116,21 @@ def test_a_deferred_stop_keeps_what_the_gates_found_for_the_tech_leads_notice(se "proofs: dev progress step", told[0]) +class UnlistedLaneStopNoticeTests(unittest.TestCase): + # a stop under a session whose run does not list the member's lane (its newer session id after a compaction) + # still names the member in the tech lead's notice, from the stop's own agent type + def test_the_notice_of_a_stop_whose_lane_the_run_does_not_list_names_the_member(self): + with TempState(): + pg.start("Export", plan=["api=30m"]) + stop = {"session_id": "s1", "agent_id": "a_tank", "agent_type": "devkit:tank", + "last_assistant_message": "done"} + pg.on_subagent("claude", stop, False, findings="proofs: dev progress step") + told = [x.get("text") or "" for x in pg.load_run("claude", "s1").get("messages") or [] + if x.get("to") == "main" and x.get("from") == "devkit" and "crew gates" in (x.get("text") or "")] + self.assertEqual(len(told), 1, told) + self.assertIn("Backend engineer (Tank) stopped, and the crew gates let it through", told[0]) + self.assertNotIn("a member stopped", told[0]) + + if __name__ == "__main__": unittest.main() From 064e048aa4505482044856f464a199b19b513630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 01:16:34 -0800 Subject: [PATCH 51/52] docs(crew): say what a launch naming done and waiting steps takes the guide said a launch naming a done step takes no step and that an unassigned lane's edit gets the out-of-scope advice; both changed with the latest fixes Verified: dev docs check docs/crew.md: 0 issues, all links resolve --- docs/crew.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/crew.md b/docs/crew.md index 07accf66..318a83c1 100644 --- a/docs/crew.md +++ b/docs/crew.md @@ -265,8 +265,9 @@ that launch alone, so two members launched together never swap lanes: the step or the lane runs no other step. Before a Claude Code launch starts, the pre-tool hook checks its description the same way: when it names none of the member's steps and one waits for its launch, the hook puts that step's name in the description and tells the tech lead; when two or more wait or it names two or more equally, - the tech lead gets the exact description that takes each. A follow-up launch that names one of the member's steps - that is already done is left unchanged and takes no step. Codex launches pick their step by `task_name` and are + the tech lead gets the exact description that takes each, and a launch that still names two equally takes the + oldest step waiting for the member. A follow-up launch that names one of the member's steps that is already done, + and none of the steps waiting for it, is left unchanged and takes no step. Codex launches pick their step by `task_name` and are not changed; a `task_name` that names a done step takes none. - **The steps given to it.** A pending step keeps its assignment on the step itself, so a lane that ends, stops, or resumes never drops it. `dev progress assign` with a launch description (`--to ""`) binds the @@ -314,8 +315,9 @@ that launch alone, so two members launched together never swap lanes: (`crew.queued`); it takes its slot at its first tool call after one frees. - **Files follow the running steps.** A lane's write scope is the union of the scopes of the steps it runs. A done, skipped, blocked, or unverified step gives its lane no files, so when a step and its files go to another lane, the - first lane keeps none of them, and two lanes never write the same files. A lane that runs no step has no scope: an - edit it makes gets the advice of a write outside its files. + first lane keeps none of them, and two lanes never write the same files. A lane that runs no step holds no file: an + edit it makes gets advice that its lane runs no step, with the `dev crew ask` line to ask the tech lead for one, and + `dev commit` refuses its files the same way. - **A launch whose record was lost** gets a restricted lane: read-only, no step, no scope, no slot, recorded as `crew.unbound`, until the tech lead assigns it a step. - **A stopped or silent member.** TaskStop fires no SubagentStop, so the PostToolUse hook ends the lane of an agent From 132c7152214c65217e44b3c041d40c79fc468e13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Contreras=20Guill=C3=A9n?= Date: Fri, 20 Nov 2026 02:50:23 -0800 Subject: [PATCH 52/52] chore(release): 26.11.27 crew coordination redesigned and the call token pinned to its process, with the CI step and watch limits taken from the workflows; the changelog entry and the version files for the release Verified: dev docs check CHANGELOG.md: 0 issues; dev test run of the consistency tests and the 5 files that read the version files: 30 and 91 passed --- CHANGELOG.md | 51 +++++++++++++++++++++++++++++++ VERSION | 2 +- desktop/manifest.json | 2 +- plugin/.claude-plugin/plugin.json | 2 +- plugin/.codex-plugin/plugin.json | 2 +- 5 files changed, 55 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 410e4b80..bcbb0751 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,57 @@ All notable changes to devkit. Versions follow CalVer `YY.MM.PATCH` (PATCH restarts at 0 each month); tags are `vYY.MM.PATCH`. Sections follow [Keep a Changelog](https://keepachangelog.com/). +## [26.11.27] - 2026-11-20 + +### Added + +- `dev ci --run` gives each step the time its workflow allows: the step's own `timeout-minutes`, else its job's, + else 1.5 times its longest local pass when that is over 30 minutes, else 30. A step past its limit ends with exit + 124, says where the limit came from, and names the `--resume` command with twice the limit. +- `dev ci watch` without `--timeout` lasts as long as the workflows' longest chain of jobs that need each other, at + their `timeout-minutes`, plus 30 minutes for the queue (90 to 360 minutes). +- A CI job that never started is classed and named with its next action: `not_started` (its annotation), `budget` + (an account limit: check billing, do not push again) and `workflow_invalid` (GitHub could not start the run). A + job that has waited 30 minutes for a runner gets one line in the `--wait` stream. +- The audit trail records how devkit knew each caller (`caller.*`), each call's pin (`calls.pin-*`), and state + changes made through a call's token by commands its text does not run (`caller.token-unlisted-use`). + +### Changed + +- The crew's coordination rules live in one module whose invariants every change is checked against. A step given + to a member waits for that member's next free lane and is claimed oldest first, whatever happens to the lane it + was meant for. A blocked step frees its lane and comes back first once its decision is answered. A lane's files + are the union of its running steps' scopes, and a resumed member takes its step and can write. +- A member's `dev progress step` without `--step` closes its lane's only running step; with two or more running it + is refused, and with none it says so. +- A review recorded with ✗ lets the step after it start; the reviewed work stays unapproved. +- The crew gates judge every stop. A member is sent back once per lane life, its next clean report with Check ✓ + passes, and a stop let through with findings approves nothing; the tech lead gets one notice with the findings. +- A launch that names one of the member's done steps and none of its waiting ones is left unchanged; one that names + a waiting step takes it. A lane that runs no step holds no file: an edit gets advice to ask for a step, and + `dev commit` refuses its files. `dev crew delegate` starts its step through the same claim rule. + +### Fixed + +- A crew member's review or approval no longer stays unverified when it reported ✓, on Claude Code and on Codex, + whose gates now read a member's commands without devkit's own stamps in front of them. +- A main-session `dev` command is no longer attributed to a crew member that has a long or waiting call open, and a + session started from another's shell (`codex exec`, `claude -p`) no longer acts as that session's tech lead. +- A literal filename no longer overlaps a glob it cannot match, so `docs/crew.md` and `docs/**/bug*.md` can go to two + members. +- `dev ci watch --timeout 0` takes the derived limit, as 0 meant the default before. + +### Security + +- Each shell call carries a token that names its caller, and the call's prefix pins it to the process it runs in, so + a copy of the token is useless to another process. A state change devkit cannot verify is refused, never made as + the tech lead's. Outside bypass mode only calls that visibly run `dev` carry it, so permission prompts do not grow. +- On Codex, `CODEX_THREAD_ID` decides no state change under the `never` approval policy; where Codex asks, a thread + names its caller only for the exact command of that caller's own open call. +- Project code devkit runs for you (the steps of `dev ci --run`, the tests of `dev test`, and git hooks that + devkit's git commands start) runs without the token. `SECURITY.md` lists what remains: code the tech lead starts + with a raw command acts with the developer's permissions, and its state changes are audited. + ## [26.11.26] - 2026-11-19 ### Added diff --git a/VERSION b/VERSION index 104cfb1c..abb83150 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -26.11.26 +26.11.27 diff --git a/desktop/manifest.json b/desktop/manifest.json index 6dd04860..abee2cca 100644 --- a/desktop/manifest.json +++ b/desktop/manifest.json @@ -2,7 +2,7 @@ "manifest_version": "0.4", "name": "devkit", "display_name": "devkit", - "version": "26.11.26", + "version": "26.11.27", "description": "Every repo in its place. Every agent on the same page. Your devkit portfolio, project status, tasks, CI and team, in Claude Desktop chat and Cowork.", "long_description": "devkit connects Claude Desktop to **devkit** from Firefly Software Solutions Inc.: every repository in its place under ~/Development, one handoff repository that keeps each project's status, tasks, plans, lessons and session log, and the same rules for Claude Code, Codex and the team. Claude Code already uses devkit through its plugin; this extension brings it to Desktop chat and Cowork.\n\n**What you can ask**\n\n- **Where things stand:** the portfolio overview, one project's status, its tasks, a standup of the last days, and a status report for the team or management.\n- **Delivery:** live CI/CD runs with job progress and an ETA, and a project's delivery policy (versioning, test gate, release flow) with its gaps.\n- **Team and history:** who is working on what, devkit's crew of specialist agents and the decisions waiting for you, lessons learned, devkit's audit trail, its scheduled jobs, and a health check of the whole setup.\n- **Tasks:** add a task, or start, finish, block, unblock or release one. Changes go through the `dev` command, so devkit's audit trail applies exactly as it does in the terminal.\n\nWhen Claude reports a project's status, it starts with the devkit status block (**[Firefly> DevKit]**), the same one Claude Code and Codex use.\n\n**Setting it up.** devkit must be installed on this Mac: run `./install.sh` in the devkit repository, which runs `dev setup`. The extension finds devkit on its own; set the devkit folder only if devkit is not where `dev setup` put it. At startup, the extension selects the configured devkit folder or the installed `dev` link. Install or update devkit through its supported policy, then restart Claude Desktop or turn the extension off and on to load the new tools. A running server keeps the version it started with. It needs Python 3.9 or later, which comes with the macOS Command Line Tools.\n\n**Privacy.** Everything runs on your Mac through the `dev` command and reads your workspace and handoff repository. The project status, CI status and doctor tools ask GitHub or your CI provider through your existing sign-in (for example `gh auth login`); task changes are pushed to your own handoff repository. No token is stored by the extension.", "author": { diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 8725a50e..8fe995cf 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devkit", - "version": "26.11.26", + "version": "26.11.27", "description": "Every repo in its place, every agent on the same page: project context and handoff notes, tasks, a portfolio overview, local-first delivery (one push, one CI run), backend methodology, and managed worktrees.", "icon": "./assets/icon.png", "author": { diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json index 48895102..a3934fd4 100644 --- a/plugin/.codex-plugin/plugin.json +++ b/plugin/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "devkit", - "version": "26.11.26", + "version": "26.11.27", "description": "Every repo in its place, every agent on the same page: project context and handoff notes, tasks, a portfolio overview, local-first delivery (one push, one CI run), backend methodology, and managed worktrees.", "author": { "name": "Firefly Software Solutions Inc.",