From 9a62cf1e2e2c8dde6ab2f5a3ab58b0667f76a80d Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:08:29 -0400 Subject: [PATCH 01/36] Exercise copied native creation assignment evidence and strikes; repair deadline projection owners --- src/agent_comms/commander/order.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/agent_comms/commander/order.py b/src/agent_comms/commander/order.py index 19dcab0564..e8dedf7be6 100644 --- a/src/agent_comms/commander/order.py +++ b/src/agent_comms/commander/order.py @@ -742,8 +742,8 @@ def due(self, pid: str, at: str, why: str) -> None: moved = RecordedEventTime(time.time()).at_clock(at) self.call(CommsChangeProblemTool(problem=pid, operation=AssignTodo( todo.revision, todo.assignment, moved, todo.order, todo.goal))) - self.on_record(f'{time.strftime("%Y-%m-%d %H:%M")} {todo.holder} ({pid} order {todo.order.id} due ' - f'{todo.deadline.clock()} moved to {moved.clock()}): {why}', 'Deadline', + self.on_record(f'{time.strftime("%Y-%m-%d %H:%M")} {todo.holder} ({pid} order {todo.order.id} ' + f'deadline changed): {why}', 'Deadline', VerdictAudience.of(todo.held().owner, todo.goal)) print(f'{pid}: due {moved.clock()}') From 1329a27fc46028115ebd77a460e21ab35a8bb784 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:57:47 -0400 Subject: [PATCH 02/36] Compare real current and native refusals to hand delivered checked work to another unit --- src/agent_comms/commander_parity/handoff.py | 144 ++++++++++++++++++ src/agent_comms/commander_parity/lifecycle.py | 12 ++ src/agent_comms/commander_parity/rows.py | 3 + 3 files changed, 159 insertions(+) create mode 100644 src/agent_comms/commander_parity/handoff.py diff --git a/src/agent_comms/commander_parity/handoff.py b/src/agent_comms/commander_parity/handoff.py new file mode 100644 index 0000000000..70b951ec78 --- /dev/null +++ b/src/agent_comms/commander_parity/handoff.py @@ -0,0 +1,144 @@ +"""Actual current/native refusals to transfer delivered checked work.""" + +from __future__ import annotations + +import contextlib +import io +import json +import subprocess +from dataclasses import dataclass, replace +from pathlib import Path +from uuid import uuid4 + +from ..change_report import FileLine +from ..commander.config import CommanderConfig +from ..commander.order import OrderFile, deadline +from ..field_codec import FieldCodec +from ..goal_actions import OrderGoalAction +from ..tools import CommsOrderTool +from . import ParityComparison, UnverifiedParity +from .lifecycle import LifecycleRun, MeasuredCommander + + +@dataclass(frozen=True) +class HandoffComparison(ParityComparison): + cases: tuple[tuple[str, int, int, tuple[str, ...], tuple[str, ...], bool], ...] + + @property + def passed(self) -> bool: + return len(self.cases) == 2 and all( + all((expected != 0, actual != 0, bool(reference), reference == refusal, unchanged)) + for _, expected, actual, reference, refusal, unchanged in self.cases + ) + + def describe(self) -> str: + return f"actual finished-order transfer refusals (current/native): {self.cases!r}" + + +class FinishedHandoffCase: + @staticmethod + def state(run: LifecycleRun, pid: str, receiver: str) -> str: + return json.dumps( + FieldCodec.encode( + ( + run.commander.comms.goals.todos.get(pid), + run.commander.comms.registry.require(run.worker).goal, + run.commander.comms.registry.require(receiver).goal, + ) + ), + sort_keys=True, + ) + + @staticmethod + def current( + run: LifecycleRun, receiver: str, document: OrderFile, pid: str + ) -> subprocess.CompletedProcess[str]: + return run.invoke( + "import sys; from agent_comms.commander.order import Commander, OrderFile; " + "Commander.model_validate_json(sys.argv[1]).send(sys.argv[2], sys.argv[3], " + "OrderFile.read(sys.argv[4]), reassign=sys.argv[5], traced=sys.argv[6])", + run.commander.model_dump_json(), + receiver, + run.due, + json.dumps(FieldCodec.encode(document)), + "Compare the actual refusal to hand completed checked work to another real unit.", + f"{Path(__file__).resolve()}:1", + ) + + @staticmethod + def native( + run: LifecycleRun, receiver: str, document: OrderFile, pid: str + ) -> subprocess.CompletedProcess[str]: + context = run.commander + todo = context.comms.goals.todos.get(pid) + tool = CommsOrderTool( + owner=receiver, + order=OrderGoalAction( + problem=pid, + expected_revision=todo.revision, + assigner=context.incarnation, + order=document.order, + deadline=deadline(run.due), + commander=context.commander, + request=document.order.request( + context.comms.registry.require(context.commander), (pid,) + ), + traced=FileLine.from_wire(f"{Path(__file__).resolve()}:1"), + ), + ) + return run.invoke( + "from pathlib import Path; import sys; from agent_comms.comms import Comms; " + "from agent_comms.field_codec import FieldCodec; " + "from agent_comms.tool_caller import ThreadCaller; " + "from agent_comms.tools import CommsOrderTool; " + "ThreadCaller(sys.argv[2]).invoke(FieldCodec.decode(CommsOrderTool, " + "FieldCodec.parse(sys.argv[3])), Comms(Path(sys.argv[1])))", + str(context.root), + context.commander, + json.dumps(FieldCodec.encode(tool)), + ) + + @classmethod + def read(cls) -> ParityComparison: + authority = MeasuredCommander.read(CommanderConfig.path()) + owners = tuple( + dict.fromkeys( + todo.held().owner + for todo in authority.comms.goals.todos.held_for_commander(authority.incarnation) + ) + )[-2:] + if len(owners) < 2: + return UnverifiedParity("Finished-work transfer needs two real registered unit holders") + cases = [] + for label, execute in (("current", cls.current), ("native", cls.native)): + with LifecycleRun.open(extra_threads=owners) as run: + with contextlib.redirect_stdout(io.StringIO()): + receiver = next(owner for owner in owners if owner != run.worker) + delivered = run.complete(run.create()) + before = cls.state(run, delivered.id, receiver) + document = OrderFile.read(run.document.read_text()) + document = replace( + document, + problems=(delivered.id,), + order=replace(document.order, id=uuid4().hex), + ) + run.decisions.write_text(json.dumps([receiver])) + reference = run.invoke( + "from pathlib import Path; import sys; from agent_comms.comms import Comms; " + "todo=Comms(Path(sys.argv[1])).goals.todos.get(sys.argv[2]); " + "todo.order.require_transfer(todo)", + str(run.commander.root), + delivered.id, + ) + attempt = execute(run, receiver, document, delivered.id) + cases.append( + ( + label, + reference.returncode, + attempt.returncode, + tuple(reference.stderr.splitlines()[-1:]), + tuple(attempt.stderr.splitlines()[-1:]), + before == cls.state(run, delivered.id, receiver), + ) + ) + return HandoffComparison(tuple(cases)) diff --git a/src/agent_comms/commander_parity/lifecycle.py b/src/agent_comms/commander_parity/lifecycle.py index 2c0e441cb0..0e633e1bf0 100644 --- a/src/agent_comms/commander_parity/lifecycle.py +++ b/src/agent_comms/commander_parity/lifecycle.py @@ -7,6 +7,7 @@ import json import os import shlex +import subprocess import sys import time from abc import ABC, abstractmethod @@ -180,6 +181,17 @@ def open(cls, *, extra_threads: tuple[str, ...] = ()) -> Iterator[LifecycleRun]: ) yield cls(commander, worker.name, decisions, document, root / "application.json") + @staticmethod + def invoke(program: str, *arguments: str) -> subprocess.CompletedProcess[str]: + source = str(Path(__file__).resolve().parents[2]) + return subprocess.run( + (sys.executable, "-c", program, *arguments), + capture_output=True, + text=True, + timeout=120, + env={**os.environ, "PYTHONPATH": source}, + ) + @property def due(self) -> str: return time.strftime("%H:%M", time.localtime(time.time() + 3600)) diff --git a/src/agent_comms/commander_parity/rows.py b/src/agent_comms/commander_parity/rows.py index 3772660101..9bde23f563 100644 --- a/src/agent_comms/commander_parity/rows.py +++ b/src/agent_comms/commander_parity/rows.py @@ -11,6 +11,7 @@ StoryPhase, ) from . import ParityComparison, ParityRow, UnverifiedParity +from .handoff import FinishedHandoffCase from .lifecycle import ( AssignOrderCase, BuildBoundProofCase, @@ -288,6 +289,8 @@ class FinishedWorkTransferParityRow(ParityRow): native = "Transfer refuses delivered checked work; that owner merges; check is reused" phases = (RecordPlanePhase,) + comparison = FinishedHandoffCase.read + class BuildBoundProofParityRow(ParityRow): number = 30 From 303e9265cfa47e7197545ca7bf7b1e02f59fbd55 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:02:41 -0400 Subject: [PATCH 03/36] Let BoundedRun own native comparison process outcomes and retirement for all argv forms --- src/agent_comms/commander_parity/handoff.py | 32 +++++++++++-------- src/agent_comms/commander_parity/lifecycle.py | 21 +++++++----- 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/src/agent_comms/commander_parity/handoff.py b/src/agent_comms/commander_parity/handoff.py index 70b951ec78..2507f40859 100644 --- a/src/agent_comms/commander_parity/handoff.py +++ b/src/agent_comms/commander_parity/handoff.py @@ -5,12 +5,12 @@ import contextlib import io import json -import subprocess from dataclasses import dataclass, replace from pathlib import Path from uuid import uuid4 from ..change_report import FileLine +from ..child_process import ChildOutcome, ChildResult, ExitedOutcome from ..commander.config import CommanderConfig from ..commander.order import OrderFile, deadline from ..field_codec import FieldCodec @@ -22,12 +22,22 @@ @dataclass(frozen=True) class HandoffComparison(ParityComparison): - cases: tuple[tuple[str, int, int, tuple[str, ...], tuple[str, ...], bool], ...] + cases: tuple[ + tuple[str, ChildOutcome, ChildOutcome, tuple[str, ...], tuple[str, ...], bool], ... + ] @property def passed(self) -> bool: return len(self.cases) == 2 and all( - all((expected != 0, actual != 0, bool(reference), reference == refusal, unchanged)) + all( + ( + expected == ExitedOutcome(1), + actual == ExitedOutcome(1), + bool(reference), + reference == refusal, + unchanged, + ) + ) for _, expected, actual, reference, refusal, unchanged in self.cases ) @@ -50,9 +60,7 @@ def state(run: LifecycleRun, pid: str, receiver: str) -> str: ) @staticmethod - def current( - run: LifecycleRun, receiver: str, document: OrderFile, pid: str - ) -> subprocess.CompletedProcess[str]: + def current(run: LifecycleRun, receiver: str, document: OrderFile, pid: str) -> ChildResult: return run.invoke( "import sys; from agent_comms.commander.order import Commander, OrderFile; " "Commander.model_validate_json(sys.argv[1]).send(sys.argv[2], sys.argv[3], " @@ -66,9 +74,7 @@ def current( ) @staticmethod - def native( - run: LifecycleRun, receiver: str, document: OrderFile, pid: str - ) -> subprocess.CompletedProcess[str]: + def native(run: LifecycleRun, receiver: str, document: OrderFile, pid: str) -> ChildResult: context = run.commander todo = context.comms.goals.todos.get(pid) tool = CommsOrderTool( @@ -134,10 +140,10 @@ def read(cls) -> ParityComparison: cases.append( ( label, - reference.returncode, - attempt.returncode, - tuple(reference.stderr.splitlines()[-1:]), - tuple(attempt.stderr.splitlines()[-1:]), + reference.outcome, + attempt.outcome, + tuple(reference.stderr.decode(errors="replace").splitlines()[-1:]), + tuple(attempt.stderr.decode(errors="replace").splitlines()[-1:]), before == cls.state(run, delivered.id, receiver), ) ) diff --git a/src/agent_comms/commander_parity/lifecycle.py b/src/agent_comms/commander_parity/lifecycle.py index 0e633e1bf0..2331074ec3 100644 --- a/src/agent_comms/commander_parity/lifecycle.py +++ b/src/agent_comms/commander_parity/lifecycle.py @@ -2,12 +2,12 @@ from __future__ import annotations +import asyncio import contextlib import io import json import os import shlex -import subprocess import sys import time from abc import ABC, abstractmethod @@ -21,6 +21,7 @@ from ..change_report import FileLine from ..check_root import CheckRoot +from ..child_process import BoundedRun, ChildResult from ..commander.config import CommanderConfig from ..commander.order import Commander, OrderFile, hhmm from ..commander.request import RequestAddVerb @@ -181,15 +182,19 @@ def open(cls, *, extra_threads: tuple[str, ...] = ()) -> Iterator[LifecycleRun]: ) yield cls(commander, worker.name, decisions, document, root / "application.json") + @classmethod + def invoke(cls, program: str, *arguments: str) -> ChildResult: + return cls.invoke_command((sys.executable, "-c", program, *arguments)) + @staticmethod - def invoke(program: str, *arguments: str) -> subprocess.CompletedProcess[str]: + def invoke_command(command: tuple[str, ...]) -> ChildResult: source = str(Path(__file__).resolve().parents[2]) - return subprocess.run( - (sys.executable, "-c", program, *arguments), - capture_output=True, - text=True, - timeout=120, - env={**os.environ, "PYTHONPATH": source}, + return asyncio.run( + BoundedRun.run( + command, + timeout=120, + env={**os.environ, "PYTHONPATH": source}, + ) ) @property From 3d2758a20bedc801bbf761410957ac5de4c1776b Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:04:52 -0400 Subject: [PATCH 04/36] Preserve caller-owned cwd and sanitized environments in the bounded process owner --- src/agent_comms/commander_parity/lifecycle.py | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/agent_comms/commander_parity/lifecycle.py b/src/agent_comms/commander_parity/lifecycle.py index 2331074ec3..60117649bd 100644 --- a/src/agent_comms/commander_parity/lifecycle.py +++ b/src/agent_comms/commander_parity/lifecycle.py @@ -182,20 +182,24 @@ def open(cls, *, extra_threads: tuple[str, ...] = ()) -> Iterator[LifecycleRun]: ) yield cls(commander, worker.name, decisions, document, root / "application.json") + @staticmethod + def python_environment() -> dict[str, str]: + return {**os.environ, "PYTHONPATH": str(Path(__file__).resolve().parents[2])} + @classmethod def invoke(cls, program: str, *arguments: str) -> ChildResult: - return cls.invoke_command((sys.executable, "-c", program, *arguments)) + return cls.invoke_command( + (sys.executable, "-c", program, *arguments), env=cls.python_environment() + ) @staticmethod - def invoke_command(command: tuple[str, ...]) -> ChildResult: - source = str(Path(__file__).resolve().parents[2]) - return asyncio.run( - BoundedRun.run( - command, - timeout=120, - env={**os.environ, "PYTHONPATH": source}, - ) - ) + def invoke_command( + command: tuple[str, ...], + *, + cwd: str | Path | None = None, + env: dict[str, str] | None = None, + ) -> ChildResult: + return asyncio.run(BoundedRun.run(command, timeout=120, cwd=cwd, env=env)) @property def due(self) -> str: From c0d70885778c667010dfb44f4b2899ceaacc3332 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:07:12 -0400 Subject: [PATCH 05/36] Confirm real child environment and project preservation through the shared process owner --- src/agent_comms/commander_parity/handoff.py | 60 +++++++++++---------- tests/test_commander_parity_lifecycle.py | 30 +++++++++++ 2 files changed, 61 insertions(+), 29 deletions(-) create mode 100644 tests/test_commander_parity_lifecycle.py diff --git a/src/agent_comms/commander_parity/handoff.py b/src/agent_comms/commander_parity/handoff.py index 2507f40859..5f6b6ef720 100644 --- a/src/agent_comms/commander_parity/handoff.py +++ b/src/agent_comms/commander_parity/handoff.py @@ -117,34 +117,36 @@ def read(cls) -> ParityComparison: return UnverifiedParity("Finished-work transfer needs two real registered unit holders") cases = [] for label, execute in (("current", cls.current), ("native", cls.native)): - with LifecycleRun.open(extra_threads=owners) as run: - with contextlib.redirect_stdout(io.StringIO()): - receiver = next(owner for owner in owners if owner != run.worker) - delivered = run.complete(run.create()) - before = cls.state(run, delivered.id, receiver) - document = OrderFile.read(run.document.read_text()) - document = replace( - document, - problems=(delivered.id,), - order=replace(document.order, id=uuid4().hex), - ) - run.decisions.write_text(json.dumps([receiver])) - reference = run.invoke( - "from pathlib import Path; import sys; from agent_comms.comms import Comms; " - "todo=Comms(Path(sys.argv[1])).goals.todos.get(sys.argv[2]); " - "todo.order.require_transfer(todo)", - str(run.commander.root), - delivered.id, - ) - attempt = execute(run, receiver, document, delivered.id) - cases.append( - ( - label, - reference.outcome, - attempt.outcome, - tuple(reference.stderr.decode(errors="replace").splitlines()[-1:]), - tuple(attempt.stderr.decode(errors="replace").splitlines()[-1:]), - before == cls.state(run, delivered.id, receiver), - ) + with ( + LifecycleRun.open(extra_threads=owners) as run, + contextlib.redirect_stdout(io.StringIO()), + ): + receiver = next(owner for owner in owners if owner != run.worker) + delivered = run.complete(run.create()) + before = cls.state(run, delivered.id, receiver) + document = OrderFile.read(run.document.read_text()) + document = replace( + document, + problems=(delivered.id,), + order=replace(document.order, id=uuid4().hex), + ) + run.decisions.write_text(json.dumps([receiver])) + reference = run.invoke( + "from pathlib import Path; import sys; from agent_comms.comms import Comms; " + "todo=Comms(Path(sys.argv[1])).goals.todos.get(sys.argv[2]); " + "todo.order.require_transfer(todo)", + str(run.commander.root), + delivered.id, + ) + attempt = execute(run, receiver, document, delivered.id) + cases.append( + ( + label, + reference.outcome, + attempt.outcome, + tuple(reference.stderr.decode(errors="replace").splitlines()[-1:]), + tuple(attempt.stderr.decode(errors="replace").splitlines()[-1:]), + before == cls.state(run, delivered.id, receiver), ) + ) return HandoffComparison(tuple(cases)) diff --git a/tests/test_commander_parity_lifecycle.py b/tests/test_commander_parity_lifecycle.py new file mode 100644 index 0000000000..0f2a827c05 --- /dev/null +++ b/tests/test_commander_parity_lifecycle.py @@ -0,0 +1,30 @@ +"""The common comparison process owner preserves its callers' process contract.""" + +import json +import sys +from pathlib import Path + +from agent_comms.child_process import ExitedOutcome +from agent_comms.commander_parity import lifecycle +from agent_comms.commander_parity.lifecycle import LifecycleRun + + +def test_command_preserves_explicit_project_and_sanitized_environment(tmp_path: Path): + result = LifecycleRun.invoke_command( + ( + sys.executable, + "-c", + "import json,os; print(json.dumps([os.getcwd(), " + "os.environ.get('PARITY_PROCESS'), 'NODE_OPTIONS' in os.environ]))", + ), + cwd=tmp_path, + env={"PARITY_PROCESS": "actual child"}, + ) + assert result.outcome == ExitedOutcome(0) + assert json.loads(result.stdout) == [str(tmp_path), "actual child", False] + + +def test_python_adapter_uses_the_candidate_source_environment(): + result = LifecycleRun.invoke("import os; print(os.environ['PYTHONPATH'])") + assert result.outcome == ExitedOutcome(0) + assert result.stdout.decode().strip() == str(Path(lifecycle.__file__).resolve().parents[2]) From 0de65cea6a3c9c6088b8545649e2d27fb208f447 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:36:55 -0400 Subject: [PATCH 06/36] Place checked-commit worktrees under the configured checkout owner --- src/agent_comms/goals.py | 5 +++-- src/agent_comms/todos.py | 10 +++++----- tests/test_order_progress.py | 4 ++-- tests/test_standing_rules.py | 6 +++--- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/agent_comms/goals.py b/src/agent_comms/goals.py index 5cd5f236cf..be2daa6035 100644 --- a/src/agent_comms/goals.py +++ b/src/agent_comms/goals.py @@ -331,12 +331,13 @@ def recorded(self, sha: str, repository: str) -> tuple[ChildResult, ...]: return tuple(checked.result for checked in CheckedCommit.stored(repository, sha) if checked.command == self.command)[:1] - def at(self, revision: str, repository: str) -> ChildResult: + def at(self, revision: str, repository: str, checkout_base: Path) -> ChildResult: """Read the result on ``revision``, or explicitly run the check in a detached checkout.""" sha = CheckedCommit.git(repository, "rev-parse", f"{revision}^{{commit}}").strip() for recorded in self.recorded(sha, repository): return recorded - with tempfile.TemporaryDirectory(prefix="order-check-") as scratch: + checkout_base.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="order-check-", dir=checkout_base) as scratch: tree = str(Path(scratch) / "tree") CheckedCommit.git(repository, "worktree", "add", "--detach", tree, sha) try: diff --git a/src/agent_comms/todos.py b/src/agent_comms/todos.py index eb0b8ea756..35d7d2311e 100644 --- a/src/agent_comms/todos.py +++ b/src/agent_comms/todos.py @@ -108,14 +108,14 @@ async def verified(self, todo: Todo, registry: Registration) -> OrderDelivery: check = order.check for each in (check, *order.deletes.checks): await self.require_source(each) - each.result.require(await self.checked(each)) + each.result.require(await self.checked(each, registry.storage_rule.checkout_base)) return replace(self, at=await self.delivery_time(check)) @abstractmethod async def require_source(self, check): ... @abstractmethod - async def checked(self, check: OrderCheck) -> ChildResult: ... + async def checked(self, check: OrderCheck, checkout_base: Path) -> ChildResult: ... @abstractmethod async def delivery_time(self, check): ... @@ -162,8 +162,8 @@ def check_failed(self, goals: Goals, todo: Todo, error: OrderCheckFailedError) - async def require_source(self, check: OrderCheck) -> None: raise ValueError("A commit delivery names the unit's delivered commit and the checked one.") - async def checked(self, check: OrderCheck) -> ChildResult: - return await asyncio.to_thread(check.at, self.commit, check.directory) + async def checked(self, check: OrderCheck, checkout_base: Path) -> ChildResult: + return await asyncio.to_thread(check.at, self.commit, check.directory, checkout_base) async def delivery_time(self, check: OrderCheck) -> EventTime: return EventTime.capture(float( @@ -294,7 +294,7 @@ def line(self) -> str: async def require_source(self, check): pass - async def checked(self, check: OrderCheck) -> ChildResult: + async def checked(self, check: OrderCheck, checkout_base: Path) -> ChildResult: return await check.run() async def delivery_time(self, check): diff --git a/tests/test_order_progress.py b/tests/test_order_progress.py index da1e20fce6..25a51e2ab8 100644 --- a/tests/test_order_progress.py +++ b/tests/test_order_progress.py @@ -115,7 +115,7 @@ def test_uncounted_check_keeps_other_overdue_orders_visible(commander, commander replace(todo, order=broken).upsert(db) create(commander, 'P2', deadline=1) commit(unit) - broken.check.at(git(unit, 'rev-parse', 'HEAD'), str(unit)) + broken.check.at(git(unit, 'rev-parse', 'HEAD'), str(unit), unit.parent) progress = read((comms.goals.todos.get('P1'), unit)) assert progress.line.endswith("; check prints no integer: printf 'no count here'") @@ -213,7 +213,7 @@ def test_progress_reads_only_explicit_check_receipts(checkout, tmp_path): source = ProgressSource.of(todo, StorageRule(checkout_base=unit.parent), Listed()) assert not source.readings().readings assert not marker.exists() - check.at(git(unit, 'rev-parse', 'HEAD').strip(), str(unit)) + check.at(git(unit, 'rev-parse', 'HEAD').strip(), str(unit), unit.parent) assert marker.read_text() == 'x' assert len(source.readings().readings) == 1 assert source.readings().readings[0].distance == CountPrinted(todo.order.checked().untouched(())) diff --git a/tests/test_standing_rules.py b/tests/test_standing_rules.py index 14858627b5..71b080c8b0 100644 --- a/tests/test_standing_rules.py +++ b/tests/test_standing_rules.py @@ -206,17 +206,17 @@ def commit(left): check = f"echo run >> {runs}; cat left" todo = create(commander, "P1", command=check, expected=0, deadline=time.time() + 3600) ordered_check = todo.order.checked().check - ordered_check.at(git("rev-parse", "HEAD").strip(), str(unit)) + ordered_check.at(git("rev-parse", "HEAD").strip(), str(unit), unit.parent) def progress(): return OrderProgress.read(comms.goals.todos.get("P1"), storage, PullRequests()) commit(2) - ordered_check.at(git("rev-parse", "HEAD").strip(), str(unit)) + ordered_check.at(git("rev-parse", "HEAD").strip(), str(unit), unit.parent) assert "; distance 2, projected done " in progress().line assert isinstance(progress().distance_readings().trend, MovingTrend) commit(2) - ordered_check.at(git("rev-parse", "HEAD").strip(), str(unit)) + ordered_check.at(git("rev-parse", "HEAD").strip(), str(unit), unit.parent) assert progress().line.endswith("; distance 2, not falling") assert runs.read_text().count("run") == 3 # once per commit: base, then each branch commit From a4d9ee7f25f0fdaa60755e756913878bd00d6743 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:37:16 -0400 Subject: [PATCH 07/36] Exercise current and native delivered-commit outcomes on the copied bus --- src/agent_comms/commander_parity/delivery.py | 143 +++++++++++++++++++ src/agent_comms/commander_parity/rows.py | 2 + 2 files changed, 145 insertions(+) create mode 100644 src/agent_comms/commander_parity/delivery.py diff --git a/src/agent_comms/commander_parity/delivery.py b/src/agent_comms/commander_parity/delivery.py new file mode 100644 index 0000000000..b5c2a5ae49 --- /dev/null +++ b/src/agent_comms/commander_parity/delivery.py @@ -0,0 +1,143 @@ +"""Compare commit delivery through the current command and the native tool.""" + +from __future__ import annotations + +import contextlib +import io +import json +import subprocess +from dataclasses import dataclass, replace +from pathlib import Path + +from ..commander.order import OrderFile +from ..field_codec import FieldCodec +from ..progress_claims import MergedClaim +from ..todos import CommitDelivery, FileDeliveryEvidence, Todo +from ..tools import CommsOrderDoneTool +from . import ParityComparison +from .lifecycle import LifecycleRun + + +@dataclass(frozen=True) +class DeliveryOutcome: + pending: bool + order_line: str + refusal: str + + @classmethod + def saved(cls, todo: Todo, refusal: str) -> DeliveryOutcome: + return cls(todo.pending, todo.order.line, refusal) + + +@dataclass(frozen=True) +class DeliveryComparison(ParityComparison): + cases: tuple[tuple[str, str, DeliveryOutcome, DeliveryOutcome], ...] + + @property + def passed(self) -> bool: + return len(self.cases) == 3 and not self.cases[0][2].pending and all( + current.pending == native.pending + and current.order_line == native.order_line + and (not current.pending or (commit in current.refusal and commit in native.refusal + and "not in" in current.refusal and "not in" in native.refusal)) + for _, commit, current, native in self.cases) + + def describe(self) -> str: + return repr(self.cases) + + +@dataclass(frozen=True) +class DeliveryRepository: + path: Path + + def git(self, *arguments: str) -> str: + return subprocess.check_output( + ("git", "-C", str(self.path), "-c", "user.name=parity", + "-c", "user.email=parity@invalid", *arguments), + text=True, stderr=subprocess.PIPE).strip() + + @classmethod + def create(cls, root: Path) -> DeliveryRepository: + path = root / "delivery-repository" + path.mkdir() + repo = cls(path) + remote = root / "delivery-origin.git" + subprocess.run(("git", "init", "--bare", "-q", str(remote)), check=True) + repo.git("init", "-q", "-b", "main") + url = "https://github.com/parity-local/delivery.git" + repo.git("config", f"url.{remote}.insteadOf", url) + repo.git("remote", "add", "origin", url) + repo.git("commit", "-q", "--allow-empty", "-m", "copied delivery base") + repo.git("push", "-q", "origin", "main") + repo.git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + return repo + + def cases(self) -> tuple[tuple[str, str], ...]: + base = self.git("rev-parse", "HEAD") + self.git("switch", "-q", "-c", "main-answer") + self.git("commit", "-q", "--allow-empty", "-m", "answer integrated on main") + main = self.git("rev-parse", "HEAD") + self.git("switch", "-q", "main") + self.git("merge", "-q", "--no-ff", "main-answer", "-m", "integrate main answer") + self.git("push", "-q", "origin", "main") + self.git("switch", "-q", "-c", "branch-answer", base) + self.git("commit", "-q", "--allow-empty", "-m", "answer integrated elsewhere") + branch = self.git("rev-parse", "HEAD") + self.git("switch", "-q", "-c", "integration", base) + self.git("merge", "-q", "--no-ff", "branch-answer", "-m", "integrate branch answer") + self.git("push", "-q", "origin", "integration") + self.git("switch", "-q", "-c", "unmerged-answer", base) + self.git("commit", "-q", "--allow-empty", "-m", "published but not integrated") + unmerged = self.git("rev-parse", "HEAD") + self.git("push", "-q", "origin", "unmerged-answer") + self.git("switch", "-q", "main") + return (("merged to main", main), ("merged to another branch", branch), + ("not merged", unmerged)) + + +class DeliveredCommitCase: + @classmethod + def create_order(cls, run: LifecycleRun, repository: DeliveryRepository) -> Todo: + document = OrderFile.read(run.document.read_text()) + document = replace(document, order=replace(document.order, + check=replace(document.order.check, directory=str(repository.path)))) + run.document.write_text(json.dumps(FieldCodec.encode(document))) + before = {todo.id for todo in run.commander.comms.goals.todos.for_commander( + run.commander.incarnation)} + run.commander.problem(str(run.document), run.worker, run.due, + f"{Path(__file__).resolve()}:1") + created, = (todo for todo in run.commander.comms.goals.todos.for_commander( + run.commander.incarnation) if todo.id not in before) + return created + + @classmethod + def read(cls) -> ParityComparison: + cases = [] + with LifecycleRun.open() as run, contextlib.redirect_stdout(io.StringIO()): + repository = DeliveryRepository.create(run.commander.root) + run.decisions.write_text("[]") + run.artifact.write_text("Copied-bus delivered-commit comparison; no source input executed.") + for name, commit in repository.cases(): + current_order = cls.create_order(run, repository) + refusal = "" + try: + run.commander.done(current_order.id, commit, seen=str(run.artifact)) + except (SystemExit, ValueError) as error: + refusal = str(error) + current = DeliveryOutcome.saved( + run.commander.comms.goals.todos.get(current_order.id), refusal) + native_order = cls.create_order(run, repository) + refusal = "" + try: + run.commander.call(CommsOrderDoneTool( + problem=native_order.id, order_id=native_order.order.id, + delivery=CommitDelivery(commit=repository.git("rev-parse", "HEAD"), + delivered_commit=commit, evidence=FileDeliveryEvidence(str(run.artifact))), + claims=(MergedClaim(commit),))) + except ValueError as error: + refusal = str(error) + native = DeliveryOutcome.saved( + run.commander.comms.goals.todos.get(native_order.id), refusal) + cases.append((name, commit, current, native)) + return DeliveryComparison(tuple(cases)) + diff --git a/src/agent_comms/commander_parity/rows.py b/src/agent_comms/commander_parity/rows.py index 9bde23f563..546abd1636 100644 --- a/src/agent_comms/commander_parity/rows.py +++ b/src/agent_comms/commander_parity/rows.py @@ -11,6 +11,7 @@ StoryPhase, ) from . import ParityComparison, ParityRow, UnverifiedParity +from .delivery import DeliveredCommitCase from .handoff import FinishedHandoffCase from .lifecycle import ( AssignOrderCase, @@ -51,6 +52,7 @@ class DeliveredCommitParityRow(ParityRow): current = "`order.py done`" native = "`CommsOrderDoneTool`: merged to main, another branch, or not merged" phases = (OneOrderOwnerPhase, RecordPlanePhase) + comparison = DeliveredCommitCase.read class InstalledEvidenceParityRow(ParityRow): From 5a9cb35513418f4d567dab8537b759c081dbdc69 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:40:40 -0400 Subject: [PATCH 08/36] Keep every copied delivery order failing until its actual run --- src/agent_comms/commander_parity/delivery.py | 2 ++ tests/test_commander_parity_delivery.py | 34 ++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 tests/test_commander_parity_delivery.py diff --git a/src/agent_comms/commander_parity/delivery.py b/src/agent_comms/commander_parity/delivery.py index b5c2a5ae49..022de0615a 100644 --- a/src/agent_comms/commander_parity/delivery.py +++ b/src/agent_comms/commander_parity/delivery.py @@ -102,12 +102,14 @@ def create_order(cls, run: LifecycleRun, repository: DeliveryRepository) -> Todo document = replace(document, order=replace(document.order, check=replace(document.order.check, directory=str(repository.path)))) run.document.write_text(json.dumps(FieldCodec.encode(document))) + run.decisions.write_text(json.dumps([run.worker])) before = {todo.id for todo in run.commander.comms.goals.todos.for_commander( run.commander.incarnation)} run.commander.problem(str(run.document), run.worker, run.due, f"{Path(__file__).resolve()}:1") created, = (todo for todo in run.commander.comms.goals.todos.for_commander( run.commander.incarnation) if todo.id not in before) + run.decisions.write_text("[]") return created @classmethod diff --git a/tests/test_commander_parity_delivery.py b/tests/test_commander_parity_delivery.py new file mode 100644 index 0000000000..09d3e736fc --- /dev/null +++ b/tests/test_commander_parity_delivery.py @@ -0,0 +1,34 @@ +from agent_comms.commander_parity.delivery import DeliveryRepository, DeliveredCommitCase +from agent_comms.commander_parity.rows import DeliveredCommitParityRow +from agent_comms.goals import CountCheckResult, OrderCheck + + +def test_delivery_graph_is_pushed_and_distinguishes_integration(tmp_path): + repository = DeliveryRepository.create(tmp_path) + main, branch, unmerged = repository.cases() + for _, commit in (main, branch, unmerged): + assert repository.git("branch", "--remotes", "--contains", commit, "--list", "origin/*") + assert repository.git("merge-base", main[1], "origin/main") == main[1] + assert repository.git("merge-base", branch[1], "origin/integration") == branch[1] + assert repository.git("merge-base", branch[1], "origin/main") != branch[1] + assert repository.git("merge-base", unmerged[1], "origin/main") != unmerged[1] + assert repository.git("merge-base", unmerged[1], "origin/integration") != unmerged[1] + + +def test_check_uses_configured_persistent_checkout_and_retains_real_result(tmp_path): + repository = DeliveryRepository.create(tmp_path) + checkout_base = tmp_path / "persistent-checkouts" + marker = tmp_path / "observed-checkouts" + check = OrderCheck(str(repository.path), f'pwd >> "{marker}"; echo 0', CountCheckResult(0)) + commit = repository.git("rev-parse", "HEAD") + first = check.at(commit, str(repository.path), checkout_base) + assert check.at(commit, str(repository.path), checkout_base) == first + actual, = marker.read_text().splitlines() + assert actual.startswith(str(checkout_base) + "/order-check-") + assert not tuple(checkout_base.iterdir()) + assert len(check.recorded(commit, str(repository.path))) == 1 + + +def test_delivery_row_declares_comparison_once(): + assert "verify" not in vars(DeliveredCommitParityRow) + assert DeliveredCommitParityRow.comparison == DeliveredCommitCase.read From deed3b43ee0cb94d5cd2c46bc30e01c331f7620c Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:45:22 -0400 Subject: [PATCH 09/36] State the checked main commit and migrate the explicit check proof --- src/agent_comms/commander_parity/delivery.py | 11 +++++++---- tools/proofs/cn_progress_read_only.py | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/agent_comms/commander_parity/delivery.py b/src/agent_comms/commander_parity/delivery.py index 022de0615a..fe69c920fc 100644 --- a/src/agent_comms/commander_parity/delivery.py +++ b/src/agent_comms/commander_parity/delivery.py @@ -31,6 +31,7 @@ def saved(cls, todo: Todo, refusal: str) -> DeliveryOutcome: @dataclass(frozen=True) class DeliveryComparison(ParityComparison): + checked_commit: str cases: tuple[tuple[str, str, DeliveryOutcome, DeliveryOutcome], ...] @property @@ -38,12 +39,13 @@ def passed(self) -> bool: return len(self.cases) == 3 and not self.cases[0][2].pending and all( current.pending == native.pending and current.order_line == native.order_line - and (not current.pending or (commit in current.refusal and commit in native.refusal - and "not in" in current.refusal and "not in" in native.refusal)) + and (all(commit in outcome.refusal and "not in" in outcome.refusal + for outcome in (current, native)) + if current.pending else commit in current.order_line) for _, commit, current, native in self.cases) def describe(self) -> str: - return repr(self.cases) + return f"checked main={self.checked_commit}; outcomes={self.cases!r}" @dataclass(frozen=True) @@ -141,5 +143,6 @@ def read(cls) -> ParityComparison: native = DeliveryOutcome.saved( run.commander.comms.goals.todos.get(native_order.id), refusal) cases.append((name, commit, current, native)) - return DeliveryComparison(tuple(cases)) + checked_commit = repository.git("rev-parse", "HEAD") + return DeliveryComparison(checked_commit, tuple(cases)) diff --git a/tools/proofs/cn_progress_read_only.py b/tools/proofs/cn_progress_read_only.py index 5065895634..05d2364053 100644 --- a/tools/proofs/cn_progress_read_only.py +++ b/tools/proofs/cn_progress_read_only.py @@ -63,7 +63,7 @@ def verify() -> None: assert not MARKER.exists() sha = CheckedCommit.git(str(checkout), "rev-parse", "HEAD").strip() assert not check.recorded(sha, str(checkout)) - check.at(sha, str(checkout)) # Deliberately explicit, never a board read. + check.at(sha, str(checkout), comms.registry.storage_rule.checkout_base) assert MARKER.read_bytes() == MARKER_CONTENT assert len(board(todo).readings) == 1 assert MARKER.read_bytes() == MARKER_CONTENT From 2fdae4c8d3cd6aaf19263ff0dfb5609a00f96830 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:48:27 -0400 Subject: [PATCH 10/36] Compare real command process exits without swallowing native refusals --- src/agent_comms/commander_parity/delivery.py | 147 ++++++++++++++----- tests/test_commander_parity_delivery.py | 2 +- 2 files changed, 108 insertions(+), 41 deletions(-) diff --git a/src/agent_comms/commander_parity/delivery.py b/src/agent_comms/commander_parity/delivery.py index fe69c920fc..be0a9ce940 100644 --- a/src/agent_comms/commander_parity/delivery.py +++ b/src/agent_comms/commander_parity/delivery.py @@ -5,7 +5,9 @@ import contextlib import io import json +import os import subprocess +import sys from dataclasses import dataclass, replace from pathlib import Path @@ -20,13 +22,14 @@ @dataclass(frozen=True) class DeliveryOutcome: + exit_code: int pending: bool order_line: str refusal: str @classmethod - def saved(cls, todo: Todo, refusal: str) -> DeliveryOutcome: - return cls(todo.pending, todo.order.line, refusal) + def saved(cls, todo: Todo, process: subprocess.CompletedProcess[str]) -> DeliveryOutcome: + return cls(process.returncode, todo.pending, todo.order.line, process.stderr) @dataclass(frozen=True) @@ -36,13 +39,23 @@ class DeliveryComparison(ParityComparison): @property def passed(self) -> bool: - return len(self.cases) == 3 and not self.cases[0][2].pending and all( - current.pending == native.pending - and current.order_line == native.order_line - and (all(commit in outcome.refusal and "not in" in outcome.refusal - for outcome in (current, native)) - if current.pending else commit in current.order_line) - for _, commit, current, native in self.cases) + return ( + len(self.cases) == 3 + and not self.cases[0][2].pending + and all( + (current.exit_code, current.pending) == (native.exit_code, native.pending) + and current.order_line == native.order_line + and ( + all( + commit in outcome.refusal and "not in" in outcome.refusal + for outcome in (current, native) + ) + if current.pending + else commit in current.order_line + ) + for _, commit, current, native in self.cases + ) + ) def describe(self) -> str: return f"checked main={self.checked_commit}; outcomes={self.cases!r}" @@ -54,9 +67,19 @@ class DeliveryRepository: def git(self, *arguments: str) -> str: return subprocess.check_output( - ("git", "-C", str(self.path), "-c", "user.name=parity", - "-c", "user.email=parity@invalid", *arguments), - text=True, stderr=subprocess.PIPE).strip() + ( + "git", + "-C", + str(self.path), + "-c", + "user.name=parity", + "-c", + "user.email=parity@invalid", + *arguments, + ), + text=True, + stderr=subprocess.PIPE, + ).strip() @classmethod def create(cls, root: Path) -> DeliveryRepository: @@ -93,24 +116,48 @@ def cases(self) -> tuple[tuple[str, str], ...]: unmerged = self.git("rev-parse", "HEAD") self.git("push", "-q", "origin", "unmerged-answer") self.git("switch", "-q", "main") - return (("merged to main", main), ("merged to another branch", branch), - ("not merged", unmerged)) + return ( + ("merged to main", main), + ("merged to another branch", branch), + ("not merged", unmerged), + ) class DeliveredCommitCase: + @staticmethod + def invoke(program: str, *arguments: str) -> subprocess.CompletedProcess[str]: + source = str(Path(__file__).resolve().parents[2]) + return subprocess.run( + (sys.executable, "-c", program, *arguments), + capture_output=True, + text=True, + timeout=120, + env={**os.environ, "PYTHONPATH": source}, + ) + @classmethod def create_order(cls, run: LifecycleRun, repository: DeliveryRepository) -> Todo: document = OrderFile.read(run.document.read_text()) - document = replace(document, order=replace(document.order, - check=replace(document.order.check, directory=str(repository.path)))) + document = replace( + document, + order=replace( + document.order, check=replace(document.order.check, directory=str(repository.path)) + ), + ) run.document.write_text(json.dumps(FieldCodec.encode(document))) run.decisions.write_text(json.dumps([run.worker])) - before = {todo.id for todo in run.commander.comms.goals.todos.for_commander( - run.commander.incarnation)} - run.commander.problem(str(run.document), run.worker, run.due, - f"{Path(__file__).resolve()}:1") - created, = (todo for todo in run.commander.comms.goals.todos.for_commander( - run.commander.incarnation) if todo.id not in before) + before = { + todo.id + for todo in run.commander.comms.goals.todos.for_commander(run.commander.incarnation) + } + run.commander.problem( + str(run.document), run.worker, run.due, f"{Path(__file__).resolve()}:1" + ) + (created,) = ( + todo + for todo in run.commander.comms.goals.todos.for_commander(run.commander.incarnation) + if todo.id not in before + ) run.decisions.write_text("[]") return created @@ -120,29 +167,49 @@ def read(cls) -> ParityComparison: with LifecycleRun.open() as run, contextlib.redirect_stdout(io.StringIO()): repository = DeliveryRepository.create(run.commander.root) run.decisions.write_text("[]") - run.artifact.write_text("Copied-bus delivered-commit comparison; no source input executed.") + run.artifact.write_text( + "Copied-bus delivered-commit comparison; no source input executed." + ) for name, commit in repository.cases(): current_order = cls.create_order(run, repository) - refusal = "" - try: - run.commander.done(current_order.id, commit, seen=str(run.artifact)) - except (SystemExit, ValueError) as error: - refusal = str(error) + process = cls.invoke( + "from agent_comms.commander.order import Commander; import sys; " + "Commander.model_validate_json(sys.argv[1]).done(" + "sys.argv[2],sys.argv[3],seen=sys.argv[4])", + run.commander.model_dump_json(), + current_order.id, + commit, + str(run.artifact), + ) current = DeliveryOutcome.saved( - run.commander.comms.goals.todos.get(current_order.id), refusal) + run.commander.comms.goals.todos.get(current_order.id), process + ) native_order = cls.create_order(run, repository) - refusal = "" - try: - run.commander.call(CommsOrderDoneTool( - problem=native_order.id, order_id=native_order.order.id, - delivery=CommitDelivery(commit=repository.git("rev-parse", "HEAD"), - delivered_commit=commit, evidence=FileDeliveryEvidence(str(run.artifact))), - claims=(MergedClaim(commit),))) - except ValueError as error: - refusal = str(error) + tool = CommsOrderDoneTool( + problem=native_order.id, + order_id=native_order.order.checked().id, + delivery=CommitDelivery( + commit=repository.git("rev-parse", "HEAD"), + delivered_commit=commit, + evidence=FileDeliveryEvidence(str(run.artifact)), + ), + claims=(MergedClaim(commit),), + ) + process = cls.invoke( + "from pathlib import Path; import sys; " + "from agent_comms.comms import Comms; " + "from agent_comms.field_codec import FieldCodec; " + "from agent_comms.tool_caller import ThreadCaller; " + "from agent_comms.tools import CommsOrderDoneTool; " + "ThreadCaller(sys.argv[2]).invoke(FieldCodec.decode(CommsOrderDoneTool, " + "FieldCodec.parse(sys.argv[3])),Comms(Path(sys.argv[1])))", + str(run.commander.root), + run.commander.commander, + json.dumps(FieldCodec.encode(tool)), + ) native = DeliveryOutcome.saved( - run.commander.comms.goals.todos.get(native_order.id), refusal) + run.commander.comms.goals.todos.get(native_order.id), process + ) cases.append((name, commit, current, native)) checked_commit = repository.git("rev-parse", "HEAD") return DeliveryComparison(checked_commit, tuple(cases)) - diff --git a/tests/test_commander_parity_delivery.py b/tests/test_commander_parity_delivery.py index 09d3e736fc..023bf6faa1 100644 --- a/tests/test_commander_parity_delivery.py +++ b/tests/test_commander_parity_delivery.py @@ -23,7 +23,7 @@ def test_check_uses_configured_persistent_checkout_and_retains_real_result(tmp_p commit = repository.git("rev-parse", "HEAD") first = check.at(commit, str(repository.path), checkout_base) assert check.at(commit, str(repository.path), checkout_base) == first - actual, = marker.read_text().splitlines() + (actual,) = marker.read_text().splitlines() assert actual.startswith(str(checkout_base) + "/order-check-") assert not tuple(checkout_base.iterdir()) assert len(check.recorded(commit, str(repository.path))) == 1 From ad185c87638492e67402cf0b29bdcca194b4c607 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:51:59 -0400 Subject: [PATCH 11/36] Keep child timeout and retirement outcomes in the delivery comparison --- src/agent_comms/commander_parity/delivery.py | 36 +++++++++++++------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/src/agent_comms/commander_parity/delivery.py b/src/agent_comms/commander_parity/delivery.py index be0a9ce940..859109a597 100644 --- a/src/agent_comms/commander_parity/delivery.py +++ b/src/agent_comms/commander_parity/delivery.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import contextlib import io import json @@ -11,6 +12,7 @@ from dataclasses import dataclass, replace from pathlib import Path +from ..child_process import BoundedRun, ChildOutcome, ChildResult, ExitedOutcome from ..commander.order import OrderFile from ..field_codec import FieldCodec from ..progress_claims import MergedClaim @@ -22,14 +24,20 @@ @dataclass(frozen=True) class DeliveryOutcome: - exit_code: int + outcome: ChildOutcome pending: bool order_line: str refusal: str @classmethod - def saved(cls, todo: Todo, process: subprocess.CompletedProcess[str]) -> DeliveryOutcome: - return cls(process.returncode, todo.pending, todo.order.line, process.stderr) + def saved(cls, todo: Todo, process: ChildResult) -> DeliveryOutcome: + return cls( + process.outcome, todo.pending, todo.order.line, process.stderr.decode(errors="replace") + ) + + @property + def delivered(self) -> bool: + return self.outcome.successful and not self.pending @dataclass(frozen=True) @@ -41,13 +49,15 @@ class DeliveryComparison(ParityComparison): def passed(self) -> bool: return ( len(self.cases) == 3 - and not self.cases[0][2].pending + and self.cases[0][2].delivered and all( - (current.exit_code, current.pending) == (native.exit_code, native.pending) + (current.outcome, current.pending) == (native.outcome, native.pending) and current.order_line == native.order_line and ( all( - commit in outcome.refusal and "not in" in outcome.refusal + outcome.outcome == ExitedOutcome(1) + and commit in outcome.refusal + and "not in" in outcome.refusal for outcome in (current, native) ) if current.pending @@ -125,14 +135,14 @@ def cases(self) -> tuple[tuple[str, str], ...]: class DeliveredCommitCase: @staticmethod - def invoke(program: str, *arguments: str) -> subprocess.CompletedProcess[str]: + def invoke(program: str, *arguments: str) -> ChildResult: source = str(Path(__file__).resolve().parents[2]) - return subprocess.run( - (sys.executable, "-c", program, *arguments), - capture_output=True, - text=True, - timeout=120, - env={**os.environ, "PYTHONPATH": source}, + return asyncio.run( + BoundedRun.run( + (sys.executable, "-c", program, *arguments), + timeout=120, + env={**os.environ, "PYTHONPATH": source}, + ) ) @classmethod From 968d6b7331f290aec614509e9e576d36e7ce0a9e Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:04:22 -0400 Subject: [PATCH 12/36] Use the lifecycle-owned candidate process launcher for delivered-commit parity --- src/agent_comms/commander_parity/delivery.py | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/src/agent_comms/commander_parity/delivery.py b/src/agent_comms/commander_parity/delivery.py index 859109a597..0026115cd7 100644 --- a/src/agent_comms/commander_parity/delivery.py +++ b/src/agent_comms/commander_parity/delivery.py @@ -2,17 +2,14 @@ from __future__ import annotations -import asyncio import contextlib import io import json -import os import subprocess -import sys from dataclasses import dataclass, replace from pathlib import Path -from ..child_process import BoundedRun, ChildOutcome, ChildResult, ExitedOutcome +from ..child_process import ChildOutcome, ChildResult, ExitedOutcome from ..commander.order import OrderFile from ..field_codec import FieldCodec from ..progress_claims import MergedClaim @@ -134,17 +131,6 @@ def cases(self) -> tuple[tuple[str, str], ...]: class DeliveredCommitCase: - @staticmethod - def invoke(program: str, *arguments: str) -> ChildResult: - source = str(Path(__file__).resolve().parents[2]) - return asyncio.run( - BoundedRun.run( - (sys.executable, "-c", program, *arguments), - timeout=120, - env={**os.environ, "PYTHONPATH": source}, - ) - ) - @classmethod def create_order(cls, run: LifecycleRun, repository: DeliveryRepository) -> Todo: document = OrderFile.read(run.document.read_text()) @@ -182,7 +168,7 @@ def read(cls) -> ParityComparison: ) for name, commit in repository.cases(): current_order = cls.create_order(run, repository) - process = cls.invoke( + process = run.invoke( "from agent_comms.commander.order import Commander; import sys; " "Commander.model_validate_json(sys.argv[1]).done(" "sys.argv[2],sys.argv[3],seen=sys.argv[4])", @@ -205,7 +191,7 @@ def read(cls) -> ParityComparison: ), claims=(MergedClaim(commit),), ) - process = cls.invoke( + process = run.invoke( "from pathlib import Path; import sys; " "from agent_comms.comms import Comms; " "from agent_comms.field_codec import FieldCodec; " From b266156991756b14419cc5e68b8c64f50bfba649 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:40:30 -0400 Subject: [PATCH 13/36] Compare deletion-intent refusal and acceptance through both real delivery adapters --- src/agent_comms/commander_parity/deletion.py | 185 +++++++++++++++++++ src/agent_comms/commander_parity/rows.py | 8 - 2 files changed, 185 insertions(+), 8 deletions(-) create mode 100644 src/agent_comms/commander_parity/deletion.py diff --git a/src/agent_comms/commander_parity/deletion.py b/src/agent_comms/commander_parity/deletion.py new file mode 100644 index 0000000000..060026a5c1 --- /dev/null +++ b/src/agent_comms/commander_parity/deletion.py @@ -0,0 +1,185 @@ +"""Deletion intent parity through real orders, pushed commits and native delivery checks.""" + +from __future__ import annotations + +import contextlib +import io +import json +import shlex +import subprocess +import sys +import tempfile +from abc import ABC, abstractmethod +from dataclasses import dataclass, replace +from pathlib import Path + +from ..change_report import FileLine +from ..child_process import CountPrinted +from ..commander.order import OrderFile, deadline +from ..field_codec import FieldCodec +from ..goal_actions import CreateProblemGoalAction +from ..goals import CountCheckResult, OrderCheck +from ..progress_claims import MergedClaim +from ..plan_phases import RecordPlanePhase +from ..repo import Repo +from ..todos import CommitDelivery, FamilyDeletion, MechanicalOrderRun, Todo +from ..tools import CommsOrderDoneTool, CommsTodoCreateTool, ProblemOrdered +from . import ParityComparison, ParityRow +from .lifecycle import LifecycleObservation, LifecycleRun, MeasuredCommander + + +@dataclass(frozen=True) +class DeletionComparison(ParityComparison): + current: LifecycleObservation + native: LifecycleObservation + + @property + def passed(self) -> bool: + return (self.current.passed and self.native.passed + and self.current.checks == self.native.checks) + + def describe(self) -> str: + return f"current: {self.current.describe()}; native: {self.native.describe()}" + + @classmethod + def read(cls) -> DeletionComparison: + return cls(CurrentDeletionPath.read(), NativeDeletionPath.read()) + + +class DeletionPath(ABC): + """Both adapters exercise the same scenario on independent LifecycleRun copies.""" + + @classmethod + @abstractmethod + def send(cls, run: LifecycleRun, document: OrderFile) -> Todo: ... + + @classmethod + @abstractmethod + def delivery_command(cls, run: LifecycleRun, todo: Todo, commit: str) -> tuple[str, ...]: ... + + @staticmethod + def commit(repository: Path, text: str, message: str) -> str: + (repository / 'family.py').write_text(text) + Repo.git(repository, 'add', 'family.py') + Repo.git(repository, 'commit', '-qm', message) + Repo.git(repository, 'push', '-q', 'origin', 'main') + return Repo.git(repository, 'rev-parse', 'HEAD').strip() + + @classmethod + def read(cls) -> LifecycleObservation: + with LifecycleRun.open() as original: + # Keep source checkouts out of the copied worker's storage accounting. + # Limits remain unchanged; all detached checks use this persistent owned base. + rule = original.commander.comms.registry.storage_rule + with tempfile.TemporaryDirectory(prefix='parity-deletion-', + dir=rule.checkout_base) as checkouts: + root = original.commander.root + (root / 'storage.json').write_text(json.dumps(FieldCodec.encode( + replace(rule, checkout_base=Path(checkouts))))) + (root / 'commander.json').write_text(original.commander.model_dump_json()) + run = replace(original, commander=MeasuredCommander.read_root(root)) + return cls.exercise(run) + + @classmethod + def exercise(cls, run: LifecycleRun) -> LifecycleObservation: + repository = Path(run.commander.comms.registry.require(run.worker).worktree) + remote = repository.parent / 'deletion-origin.git' + Repo.git(repository, 'init', '-q', '-b', 'main') + Repo.git(repository, 'config', 'user.name', 'Deletion parity') + Repo.git(repository, 'config', 'user.email', 'deletion-parity@localhost') + Repo.git(repository, 'init', '--bare', '-q', '--initial-branch=main', str(remote)) + Repo.git(repository, 'remote', 'add', 'origin', str(remote)) + family = 'class RetiredDecision:\n pass\n\n' + cls.commit(repository, family + 'def decisions():\n return [RetiredDecision()]\n', + 'Declare the obsolete decision family and its caller') + count = OrderCheck(str(repository), shlex.join((sys.executable, '-c', + "import ast;from pathlib import Path;" + "print(sum(isinstance(node,ast.ClassDef) for node in " + "ast.walk(ast.parse(Path('family.py').read_text()))))")), CountCheckResult(0)) + deletion = FamilyDeletion('obsolete decision family', + FileLine(str(repository / 'family.py'), 1), count) + initial = OrderFile.read(run.document.read_text()) + order = replace(initial.order, + check=OrderCheck(str(repository), shlex.join((sys.executable, '-c', + 'import family;assert not family.decisions()'))), + run=MechanicalOrderRun(), deletes=deletion) + document = replace(initial, order=order) + run.document.write_text(json.dumps(FieldCodec.encode(document))) + output = io.StringIO() + with contextlib.redirect_stdout(output): + before = cls.send(run, document) + partial = cls.commit(repository, family + 'def decisions():\n return []\n', + 'Repair the caller but leave one obsolete family site') + refused = subprocess.run(cls.delivery_command(run, before, partial), + capture_output=True, text=True, timeout=90) + after_refusal = run.commander.comms.goals.todos.get(before.id) + remaining = count.recorded(partial, str(repository)) + complete = cls.commit(repository, 'def decisions():\n return []\n', + 'Delete the last obsolete family declaration') + accepted = subprocess.run(cls.delivery_command(run, before, complete), + capture_output=True, text=True, timeout=90) + after_acceptance = run.commander.comms.goals.todos.get(before.id) + zero = count.recorded(complete, str(repository)) + primary = order.check.recorded(partial, str(repository)) + checks = ( + ('native order retained deletion intent', before.order.checked().deletes == deletion), + ('partial commit passed primary check', bool(primary) + and order.check.result.distance(primary[0]) == CountPrinted(0)), + ('partial commit retained one family site', bool(remaining) + and count.result.distance(remaining[0]) == CountPrinted(1)), + ('nonzero delivery refused', refused.returncode != 0), + ('refusal preserved pending order', before == after_refusal and after_refusal.pending), + ('zero count checked on delivered commit', bool(zero) + and count.result.distance(zero[0]) == CountPrinted(0)), + ('zero delivery accepted', accepted.returncode == 0 and not after_acceptance.pending), + ) + return LifecycleObservation( + CommsOrderDoneTool.__qualname__, len((refused, accepted)), checks, + output.getvalue() + f'partial={partial}; zero={complete}; ' + f'refused={refused.returncode}: {refused.stderr}; ' + f'accepted={accepted.returncode}: {accepted.stdout}{accepted.stderr}') + + +class CurrentDeletionPath(DeletionPath): + @classmethod + def send(cls, run: LifecycleRun, document: OrderFile) -> Todo: + return run.create() + + @classmethod + def delivery_command(cls, run: LifecycleRun, todo: Todo, commit: str) -> tuple[str, ...]: + return (sys.executable, '-c', 'from agent_comms.commander.cli import main;main()', + '--config', str(run.commander.root / 'commander.json'), + 'order', 'done', todo.id, commit) + + +class NativeDeletionPath(DeletionPath): + @classmethod + def send(cls, run: LifecycleRun, document: OrderFile) -> Todo: + result: ProblemOrdered = run.commander.call(CommsTodoCreateTool( + owner=run.worker, order=CreateProblemGoalAction( + problem='P1', repo=Repo.of(Path(document.order.check.directory)).github, + text=document.defect, order=document.order, + request=document.order.request( + run.commander.comms.registry.require(run.commander.commander), ('P1',)), + deadline=deadline(run.due), commander=run.commander.commander))) + return result.todo + + @classmethod + def delivery_command(cls, run: LifecycleRun, todo: Todo, commit: str) -> tuple[str, ...]: + request = CommsOrderDoneTool(problem=todo.id, order_id=todo.order.id, + delivery=CommitDelivery(commit=commit, delivered_commit=commit), + claims=(MergedClaim(commit),)) + arguments = FieldCodec.encode(request) + arguments.pop(request.family_discriminator) + return (sys.executable, '-m', 'agent_comms', '--root', str(run.commander.root), + 'tool', '--from', run.commander.commander, '--tool', request.declared_name, + '--arguments', json.dumps(arguments)) + + +class DeletionTargetParityRow(ParityRow): + number = 31 + capability = 'An order states its intent as a deletion target' + current = 'Current order command with a declared FamilyDeletion' + native = 'CommsTodoCreateTool and CommsOrderDoneTool check the delivered family count' + phases = (RecordPlanePhase,) + comparison = DeletionComparison.read diff --git a/src/agent_comms/commander_parity/rows.py b/src/agent_comms/commander_parity/rows.py index 546abd1636..7847f5531c 100644 --- a/src/agent_comms/commander_parity/rows.py +++ b/src/agent_comms/commander_parity/rows.py @@ -304,14 +304,6 @@ class BuildBoundProofParityRow(ParityRow): comparison = BuildBoundProofCase.read -class DeletionTargetParityRow(ParityRow): - number = 31 - capability = "An order states its intent as a deletion target" - current = "none; P520 renamed a decision rather than deleting it" - native = "Order owns deletion family/site/count; delivery refuses nonzero or renamed decisions" - phases = (RecordPlanePhase,) - - class UnitTimeParityRow(ParityRow): number = 32 capability = "Where units' time goes, classified" From f9f65caeca490b4a0e74fb0892db446ce471365b Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:47:25 -0400 Subject: [PATCH 14/36] Exercise current command and native entrypoints with exact delivered-commit observations --- src/agent_comms/commander_parity/deletion.py | 232 +++++++++++++------ 1 file changed, 159 insertions(+), 73 deletions(-) diff --git a/src/agent_comms/commander_parity/deletion.py b/src/agent_comms/commander_parity/deletion.py index 060026a5c1..d4655a9c13 100644 --- a/src/agent_comms/commander_parity/deletion.py +++ b/src/agent_comms/commander_parity/deletion.py @@ -19,10 +19,17 @@ from ..field_codec import FieldCodec from ..goal_actions import CreateProblemGoalAction from ..goals import CountCheckResult, OrderCheck -from ..progress_claims import MergedClaim from ..plan_phases import RecordPlanePhase +from ..progress_claims import MergedClaim from ..repo import Repo -from ..todos import CommitDelivery, FamilyDeletion, MechanicalOrderRun, Todo +from ..todos import ( + CheckedCommitDelivery, + CommitDelivery, + DeliveredProblemOrder, + FamilyDeletion, + MechanicalOrderRun, + Todo, +) from ..tools import CommsOrderDoneTool, CommsTodoCreateTool, ProblemOrdered from . import ParityComparison, ParityRow from .lifecycle import LifecycleObservation, LifecycleRun, MeasuredCommander @@ -35,8 +42,9 @@ class DeletionComparison(ParityComparison): @property def passed(self) -> bool: - return (self.current.passed and self.native.passed - and self.current.checks == self.native.checks) + return ( + self.current.passed and self.native.passed and self.current.checks == self.native.checks + ) def describe(self) -> str: return f"current: {self.current.describe()}; native: {self.native.describe()}" @@ -59,11 +67,11 @@ def delivery_command(cls, run: LifecycleRun, todo: Todo, commit: str) -> tuple[s @staticmethod def commit(repository: Path, text: str, message: str) -> str: - (repository / 'family.py').write_text(text) - Repo.git(repository, 'add', 'family.py') - Repo.git(repository, 'commit', '-qm', message) - Repo.git(repository, 'push', '-q', 'origin', 'main') - return Repo.git(repository, 'rev-parse', 'HEAD').strip() + (repository / "family.py").write_text(text) + Repo.git(repository, "add", "family.py") + Repo.git(repository, "commit", "-qm", message) + Repo.git(repository, "push", "-q", "origin", "main") + return Repo.git(repository, "rev-parse", "HEAD").strip() @classmethod def read(cls) -> LifecycleObservation: @@ -71,73 +79,118 @@ def read(cls) -> LifecycleObservation: # Keep source checkouts out of the copied worker's storage accounting. # Limits remain unchanged; all detached checks use this persistent owned base. rule = original.commander.comms.registry.storage_rule - with tempfile.TemporaryDirectory(prefix='parity-deletion-', - dir=rule.checkout_base) as checkouts: + with tempfile.TemporaryDirectory( + prefix="parity-deletion-", dir=rule.checkout_base + ) as checkouts: root = original.commander.root - (root / 'storage.json').write_text(json.dumps(FieldCodec.encode( - replace(rule, checkout_base=Path(checkouts))))) - (root / 'commander.json').write_text(original.commander.model_dump_json()) + (root / "storage.json").write_text( + json.dumps(FieldCodec.encode(replace(rule, checkout_base=Path(checkouts)))) + ) + (root / "commander.json").write_text(original.commander.model_dump_json()) run = replace(original, commander=MeasuredCommander.read_root(root)) return cls.exercise(run) @classmethod def exercise(cls, run: LifecycleRun) -> LifecycleObservation: repository = Path(run.commander.comms.registry.require(run.worker).worktree) - remote = repository.parent / 'deletion-origin.git' - Repo.git(repository, 'init', '-q', '-b', 'main') - Repo.git(repository, 'config', 'user.name', 'Deletion parity') - Repo.git(repository, 'config', 'user.email', 'deletion-parity@localhost') - Repo.git(repository, 'init', '--bare', '-q', '--initial-branch=main', str(remote)) - Repo.git(repository, 'remote', 'add', 'origin', str(remote)) - family = 'class RetiredDecision:\n pass\n\n' - cls.commit(repository, family + 'def decisions():\n return [RetiredDecision()]\n', - 'Declare the obsolete decision family and its caller') - count = OrderCheck(str(repository), shlex.join((sys.executable, '-c', - "import ast;from pathlib import Path;" - "print(sum(isinstance(node,ast.ClassDef) for node in " - "ast.walk(ast.parse(Path('family.py').read_text()))))")), CountCheckResult(0)) - deletion = FamilyDeletion('obsolete decision family', - FileLine(str(repository / 'family.py'), 1), count) + remote = repository.parent / "deletion-origin.git" + Repo.git(repository, "init", "-q", "-b", "main") + Repo.git(repository, "config", "user.name", "Deletion parity") + Repo.git(repository, "config", "user.email", "deletion-parity@localhost") + Repo.git(repository, "init", "--bare", "-q", "--initial-branch=main", str(remote)) + Repo.git(repository, "remote", "add", "origin", str(remote)) + family = "class RetiredDecision:\n pass\n\n" + cls.commit( + repository, + family + "def decisions():\n return [RetiredDecision()]\n", + "Declare the obsolete decision family and its caller", + ) + count = OrderCheck( + str(repository), + shlex.join( + ( + sys.executable, + "-c", + "import ast;from pathlib import Path;" + "print(sum(isinstance(node,ast.ClassDef) for node in " + "ast.walk(ast.parse(Path('family.py').read_text()))))", + ) + ), + CountCheckResult(0), + ) + deletion = FamilyDeletion( + "obsolete decision family", FileLine(str(repository / "family.py"), 1), count + ) initial = OrderFile.read(run.document.read_text()) - order = replace(initial.order, - check=OrderCheck(str(repository), shlex.join((sys.executable, '-c', - 'import family;assert not family.decisions()'))), - run=MechanicalOrderRun(), deletes=deletion) + order = replace( + initial.order, + check=OrderCheck( + str(repository), + shlex.join((sys.executable, "-c", "import family;assert not family.decisions()")), + ), + run=MechanicalOrderRun(), + deletes=deletion, + ) document = replace(initial, order=order) run.document.write_text(json.dumps(FieldCodec.encode(document))) output = io.StringIO() with contextlib.redirect_stdout(output): before = cls.send(run, document) - partial = cls.commit(repository, family + 'def decisions():\n return []\n', - 'Repair the caller but leave one obsolete family site') - refused = subprocess.run(cls.delivery_command(run, before, partial), - capture_output=True, text=True, timeout=90) + partial = cls.commit( + repository, + family + "def decisions():\n return []\n", + "Repair the caller but leave one obsolete family site", + ) + refused = subprocess.run( + cls.delivery_command(run, before, partial), capture_output=True, text=True, timeout=90 + ) after_refusal = run.commander.comms.goals.todos.get(before.id) remaining = count.recorded(partial, str(repository)) - complete = cls.commit(repository, 'def decisions():\n return []\n', - 'Delete the last obsolete family declaration') - accepted = subprocess.run(cls.delivery_command(run, before, complete), - capture_output=True, text=True, timeout=90) + complete = cls.commit( + repository, + "def decisions():\n return []\n", + "Delete the last obsolete family declaration", + ) + accepted = subprocess.run( + cls.delivery_command(run, before, complete), capture_output=True, text=True, timeout=90 + ) after_acceptance = run.commander.comms.goals.todos.get(before.id) zero = count.recorded(complete, str(repository)) primary = order.check.recorded(partial, str(repository)) + delivered = after_acceptance.order checks = ( - ('native order retained deletion intent', before.order.checked().deletes == deletion), - ('partial commit passed primary check', bool(primary) - and order.check.result.distance(primary[0]) == CountPrinted(0)), - ('partial commit retained one family site', bool(remaining) - and count.result.distance(remaining[0]) == CountPrinted(1)), - ('nonzero delivery refused', refused.returncode != 0), - ('refusal preserved pending order', before == after_refusal and after_refusal.pending), - ('zero count checked on delivered commit', bool(zero) - and count.result.distance(zero[0]) == CountPrinted(0)), - ('zero delivery accepted', accepted.returncode == 0 and not after_acceptance.pending), + ("native order retained deletion intent", before.order.checked().deletes == deletion), + ( + "partial commit passed primary check", + bool(primary) and order.check.result.distance(primary[0]) == CountPrinted(0), + ), + ( + "partial commit retained one family site", + bool(remaining) and count.result.distance(remaining[0]) == CountPrinted(1), + ), + ("nonzero delivery refused", refused.returncode != 0), + ("refusal preserved pending order", before == after_refusal and after_refusal.pending), + ( + "zero count checked on delivered commit", + bool(zero) and count.result.distance(zero[0]) == CountPrinted(0), + ), + ("zero delivery accepted", accepted.returncode == 0 and not after_acceptance.pending), + ( + "accepted delivery names the zero-site commit", + isinstance(delivered, DeliveredProblemOrder) + and isinstance(delivered.delivery, CheckedCommitDelivery) + and delivered.delivery.delivered_commit == complete, + ), + ("accepted delivery retained deletion intent", delivered.checked().deletes == deletion), ) return LifecycleObservation( - CommsOrderDoneTool.__qualname__, len((refused, accepted)), checks, - output.getvalue() + f'partial={partial}; zero={complete}; ' - f'refused={refused.returncode}: {refused.stderr}; ' - f'accepted={accepted.returncode}: {accepted.stdout}{accepted.stderr}') + CommsOrderDoneTool.__qualname__, + len((refused, accepted)), + checks, + output.getvalue() + f"partial={partial}; zero={complete}; " + f"refused={refused.returncode}: {refused.stdout}{refused.stderr}; " + f"accepted={accepted.returncode}: {accepted.stdout}{accepted.stderr}", + ) class CurrentDeletionPath(DeletionPath): @@ -147,39 +200,72 @@ def send(cls, run: LifecycleRun, document: OrderFile) -> Todo: @classmethod def delivery_command(cls, run: LifecycleRun, todo: Todo, commit: str) -> tuple[str, ...]: - return (sys.executable, '-c', 'from agent_comms.commander.cli import main;main()', - '--config', str(run.commander.root / 'commander.json'), - 'order', 'done', todo.id, commit) + return ( + sys.executable, + "-c", + "import sys;from agent_comms.commander.order import Commander,DoneVerb;" + "DoneVerb(unit=sys.argv[2],message=sys.argv[3],sha=sys.argv[4]).run(" + "Commander.read_root(sys.argv[1]))", + str(run.commander.root), + run.worker, + todo.order.checked().id, + commit, + ) class NativeDeletionPath(DeletionPath): @classmethod def send(cls, run: LifecycleRun, document: OrderFile) -> Todo: - result: ProblemOrdered = run.commander.call(CommsTodoCreateTool( - owner=run.worker, order=CreateProblemGoalAction( - problem='P1', repo=Repo.of(Path(document.order.check.directory)).github, - text=document.defect, order=document.order, - request=document.order.request( - run.commander.comms.registry.require(run.commander.commander), ('P1',)), - deadline=deadline(run.due), commander=run.commander.commander))) + result = run.commander.call( + CommsTodoCreateTool( + owner=run.worker, + order=CreateProblemGoalAction( + problem="P1", + repo=Repo.of(Path(document.order.check.directory)).github, + text=document.defect, + order=document.order, + request=document.order.request( + run.commander.comms.registry.require(run.commander.commander), ("P1",) + ), + deadline=deadline(run.due), + commander=run.commander.commander, + ), + ) + ) + if not isinstance(result, ProblemOrdered): + raise TypeError("Native creation returned no ordered problem") return result.todo @classmethod def delivery_command(cls, run: LifecycleRun, todo: Todo, commit: str) -> tuple[str, ...]: - request = CommsOrderDoneTool(problem=todo.id, order_id=todo.order.id, + request = CommsOrderDoneTool( + problem=todo.id, + order_id=todo.order.checked().id, delivery=CommitDelivery(commit=commit, delivered_commit=commit), - claims=(MergedClaim(commit),)) + claims=(MergedClaim(commit),), + ) arguments = FieldCodec.encode(request) arguments.pop(request.family_discriminator) - return (sys.executable, '-m', 'agent_comms', '--root', str(run.commander.root), - 'tool', '--from', run.commander.commander, '--tool', request.declared_name, - '--arguments', json.dumps(arguments)) + return ( + sys.executable, + "-m", + "agent_comms.cli", + "--root", + str(run.commander.root), + "tool", + "--from", + run.commander.commander, + "--tool", + request.declared_name, + "--arguments", + json.dumps(arguments), + ) class DeletionTargetParityRow(ParityRow): number = 31 - capability = 'An order states its intent as a deletion target' - current = 'Current order command with a declared FamilyDeletion' - native = 'CommsTodoCreateTool and CommsOrderDoneTool check the delivered family count' + capability = "An order states its intent as a deletion target" + current = "Current order command with a declared FamilyDeletion" + native = "CommsTodoCreateTool and CommsOrderDoneTool check the delivered family count" phases = (RecordPlanePhase,) comparison = DeletionComparison.read From 598a009afee957356c17709eba7ec628b37ef35e Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:55:35 -0400 Subject: [PATCH 15/36] Let declared requests compose argument projection and let the CLI own tool argv --- src/agent_comms/tools.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/agent_comms/tools.py b/src/agent_comms/tools.py index 80f1ee08b8..bc36c65a72 100644 --- a/src/agent_comms/tools.py +++ b/src/agent_comms/tools.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import sys import threading from abc import abstractmethod from collections.abc import Mapping @@ -68,7 +69,7 @@ TodoOperation, VerdictAudience) from .change_report import ChangeReport from .messages import InfoKind, MessageKind, NoticeRole, SendableMessageKind -from .native_tools import NativeToolDeclaration, NativeRequestTools +from .native_tools import ArgumentTool, NativeToolDeclaration, NativeRequestTools from .tool_caller import ToolCaller, ThreadCaller, NoThreadCaller, ThreadListing from .thread_identity import ThreadIncarnation from .cli_result import ToolCatalogResult @@ -293,7 +294,7 @@ def tool_field( @dataclass(frozen=True, kw_only=True) class ToolRequest[Caller: ToolCaller = ToolCaller]( - ThreadCommandAvailability, NativeRequestTools, NativeToolDeclaration + ArgumentTool, ThreadCommandAvailability, NativeRequestTools, NativeToolDeclaration ): description: ClassVar[str] bus_effect: ClassVar[str] = ("Changes the bus. Tristan has authorized claude-ai " @@ -329,6 +330,10 @@ def schema(cls) -> dict[str, object]: ) return result + def cli_command(self, caller: str | None = None) -> InvokeCliCommand: + """Project this declaration into Core's existing external tool command.""" + return InvokeCliCommand(caller=caller, tool=self.declared_name, arguments=self.arguments) + @classmethod def invoke( cls, comms: Comms, arguments: Mapping[str, object], *, caller: ToolCaller @@ -1388,6 +1393,15 @@ class InvokeCliCommand(CliCommand, declared_name="tool"): "--arguments", help="Tool arguments as a JSON object", default_factory=dict, parser_default="{}") + def argv(self, root: Path) -> tuple[str, ...]: + """The CLI boundary owns its module, grammar and argument serialization.""" + from . import cli + + caller = ('--from', self.caller) if self.caller is not None else () + return (sys.executable, '-m', cli.__name__, '--root', str(root), + self.declared_name, *caller, '--tool', self.tool, + '--arguments', json.dumps(self.arguments)) + def apply(self, ctx: Comms) -> dict[str, JsonValue]: return invoke_tool(ctx, self.tool, self.arguments, caller=ToolCaller.from_actor(self.caller)) From 1131375433899470abeb93b68af0170c4261dd8d Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:56:33 -0400 Subject: [PATCH 16/36] Use caller-owned identity and declared native CLI projection in deletion parity --- plans/commander-native-plan.md | 2 +- src/agent_comms/commander_parity/deletion.py | 18 ++---------------- src/agent_comms/tools.py | 9 +++++---- 3 files changed, 8 insertions(+), 21 deletions(-) diff --git a/plans/commander-native-plan.md b/plans/commander-native-plan.md index 05042371b2..4fbae94e3a 100644 --- a/plans/commander-native-plan.md +++ b/plans/commander-native-plan.md @@ -61,7 +61,7 @@ | 28 | Measured load and self-report | `capacity.py` unit count | `commander.capacity.Load.of` reports orders, overdue, edits and forks; self-report comparison unverified | `control_plane` | | 29 | No handoff of finished, checked work | none; scratch transfer moved P507 after its fix was pushed and checked | Transfer refuses delivered checked work; that owner merges; check is reused | `record_plane` | | 30 | A proof is bound to the build it ran on | none; screenshots and logs are bare paths | Build run records runtime and Core/Toad revisions; close requires delivered commit | `record_plane` | -| 31 | An order states its intent as a deletion target | none; P520 renamed a decision rather than deleting it | Order owns deletion family/site/count; delivery refuses nonzero or renamed decisions | `record_plane` | +| 31 | An order states its intent as a deletion target | Current order command with a declared FamilyDeletion | CommsTodoCreateTool and CommsOrderDoneTool check the delivered family count | `record_plane` | | 32 | Where units' time goes, classified | none; activity.log lacks durations and turn boundaries | `UnitTime`: model, build/check/test/shell, dependency/commander waits and idle; classify large waits | `commander_page`, `control_plane` | | 33 | Order progress beside its deadline; the unit never sees a due time | `order.py board`, `overdue`, `due`, `send`; `rotate.py` | Derived `OrderProgress`; merged work draws no strike; first commit 10 min, later progress 15 min STALL; units see no due time | `one_order_owner`, `control_plane` | | 34 | Several commanders on one machine and bus, one per project | none; a second commander.json install overwrites the first | Registry commander/project ownership; caller from --from; scoped orders, strikes, load, board, alarms and forks; raw-send guard; duplicate project commander refused | `one_order_owner`, `cutover` | diff --git a/src/agent_comms/commander_parity/deletion.py b/src/agent_comms/commander_parity/deletion.py index d4655a9c13..e66014991a 100644 --- a/src/agent_comms/commander_parity/deletion.py +++ b/src/agent_comms/commander_parity/deletion.py @@ -30,6 +30,7 @@ MechanicalOrderRun, Todo, ) +from ..tool_caller import ThreadCaller from ..tools import CommsOrderDoneTool, CommsTodoCreateTool, ProblemOrdered from . import ParityComparison, ParityRow from .lifecycle import LifecycleObservation, LifecycleRun, MeasuredCommander @@ -244,22 +245,7 @@ def delivery_command(cls, run: LifecycleRun, todo: Todo, commit: str) -> tuple[s delivery=CommitDelivery(commit=commit, delivered_commit=commit), claims=(MergedClaim(commit),), ) - arguments = FieldCodec.encode(request) - arguments.pop(request.family_discriminator) - return ( - sys.executable, - "-m", - "agent_comms.cli", - "--root", - str(run.commander.root), - "tool", - "--from", - run.commander.commander, - "--tool", - request.declared_name, - "--arguments", - json.dumps(arguments), - ) + return request.cli_command(ThreadCaller(run.commander.commander)).argv(run.commander.root) class DeletionTargetParityRow(ParityRow): diff --git a/src/agent_comms/tools.py b/src/agent_comms/tools.py index bc36c65a72..e37d7d8491 100644 --- a/src/agent_comms/tools.py +++ b/src/agent_comms/tools.py @@ -330,9 +330,10 @@ def schema(cls) -> dict[str, object]: ) return result - def cli_command(self, caller: str | None = None) -> InvokeCliCommand: + def cli_command(self, caller: ToolCaller) -> InvokeCliCommand: """Project this declaration into Core's existing external tool command.""" - return InvokeCliCommand(caller=caller, tool=self.declared_name, arguments=self.arguments) + return InvokeCliCommand(caller=caller.acting_name(''), + tool=self.declared_name, arguments=self.arguments) @classmethod def invoke( @@ -1397,9 +1398,9 @@ def argv(self, root: Path) -> tuple[str, ...]: """The CLI boundary owns its module, grammar and argument serialization.""" from . import cli - caller = ('--from', self.caller) if self.caller is not None else () + caller = ToolCaller.from_actor(self.caller) return (sys.executable, '-m', cli.__name__, '--root', str(root), - self.declared_name, *caller, '--tool', self.tool, + self.declared_name, '--from', caller.acting_name(''), '--tool', self.tool, '--arguments', json.dumps(self.arguments)) def apply(self, ctx: Comms) -> dict[str, JsonValue]: From 209fdd94b300713a51a7e4f815758ed183822543 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:58:03 -0400 Subject: [PATCH 17/36] Bind the native CLI module at its ordinary module import boundary --- src/agent_comms/tools.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/agent_comms/tools.py b/src/agent_comms/tools.py index e37d7d8491..f391302df0 100644 --- a/src/agent_comms/tools.py +++ b/src/agent_comms/tools.py @@ -13,6 +13,7 @@ from pydantic import JsonValue +from . import cli as comms_cli from .commander.capacity import Load from .progress_claims import ProgressClaim from .pi_vocabulary import ServiceTier, ThinkingLevel, ThinkingLevelField @@ -1396,10 +1397,8 @@ class InvokeCliCommand(CliCommand, declared_name="tool"): def argv(self, root: Path) -> tuple[str, ...]: """The CLI boundary owns its module, grammar and argument serialization.""" - from . import cli - caller = ToolCaller.from_actor(self.caller) - return (sys.executable, '-m', cli.__name__, '--root', str(root), + return (sys.executable, '-m', comms_cli.__name__, '--root', str(root), self.declared_name, '--from', caller.acting_name(''), '--tool', self.tool, '--arguments', json.dumps(self.arguments)) From 9be6bdbfb9642c0655b3bc6526b1c4ce332ddc91 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:59:15 -0400 Subject: [PATCH 18/36] Delete the other hand-built native tool argv and envelope projection --- tools/proofs/cn_phase3_record.py | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/tools/proofs/cn_phase3_record.py b/tools/proofs/cn_phase3_record.py index d925660ffd..54cda2f8d8 100644 --- a/tools/proofs/cn_phase3_record.py +++ b/tools/proofs/cn_phase3_record.py @@ -11,12 +11,10 @@ import os import shutil import subprocess -import sys import time from dataclasses import replace from pathlib import Path -from agent_comms import cli as comms_cli from agent_comms.change_report import FileLine from agent_comms.comms import Comms from agent_comms.field_codec import FieldCodec @@ -50,22 +48,7 @@ def cli[Caller: ToolCaller](caller: str, tool: ToolRequest[Caller]) -> str: - arguments = FieldCodec.encode(tool) - del arguments[tool.family_discriminator] - command = [ - sys.executable, - "-m", - comms_cli.__name__, - "--root", - str(ROOT), - "tool", - "--from", - caller, - "--tool", - tool.declared_name, - "--arguments", - json.dumps(arguments), - ] + command = tool.cli_command(ToolCaller.from_actor(caller)).argv(ROOT) result = subprocess.run( command, capture_output=True, From 8ca3e68402619626141049ffce80232e95a4040b Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:04:10 -0400 Subject: [PATCH 19/36] Use the shared bounded lifecycle producer and typed delivery outcomes --- src/agent_comms/commander_parity/deletion.py | 24 ++++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/agent_comms/commander_parity/deletion.py b/src/agent_comms/commander_parity/deletion.py index e66014991a..f199ea9733 100644 --- a/src/agent_comms/commander_parity/deletion.py +++ b/src/agent_comms/commander_parity/deletion.py @@ -6,7 +6,6 @@ import io import json import shlex -import subprocess import sys import tempfile from abc import ABC, abstractmethod @@ -14,7 +13,7 @@ from pathlib import Path from ..change_report import FileLine -from ..child_process import CountPrinted +from ..child_process import CountPrinted, ExitedOutcome from ..commander.order import OrderFile, deadline from ..field_codec import FieldCodec from ..goal_actions import CreateProblemGoalAction @@ -142,9 +141,7 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: family + "def decisions():\n return []\n", "Repair the caller but leave one obsolete family site", ) - refused = subprocess.run( - cls.delivery_command(run, before, partial), capture_output=True, text=True, timeout=90 - ) + refused = run.invoke_command(cls.delivery_command(run, before, partial)) after_refusal = run.commander.comms.goals.todos.get(before.id) remaining = count.recorded(partial, str(repository)) complete = cls.commit( @@ -152,9 +149,7 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: "def decisions():\n return []\n", "Delete the last obsolete family declaration", ) - accepted = subprocess.run( - cls.delivery_command(run, before, complete), capture_output=True, text=True, timeout=90 - ) + accepted = run.invoke_command(cls.delivery_command(run, before, complete)) after_acceptance = run.commander.comms.goals.todos.get(before.id) zero = count.recorded(complete, str(repository)) primary = order.check.recorded(partial, str(repository)) @@ -169,13 +164,16 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: "partial commit retained one family site", bool(remaining) and count.result.distance(remaining[0]) == CountPrinted(1), ), - ("nonzero delivery refused", refused.returncode != 0), + ("nonzero delivery refused", refused.outcome == ExitedOutcome(1)), ("refusal preserved pending order", before == after_refusal and after_refusal.pending), ( "zero count checked on delivered commit", bool(zero) and count.result.distance(zero[0]) == CountPrinted(0), ), - ("zero delivery accepted", accepted.returncode == 0 and not after_acceptance.pending), + ( + "zero delivery accepted", + accepted.outcome == ExitedOutcome(0) and not after_acceptance.pending, + ), ( "accepted delivery names the zero-site commit", isinstance(delivered, DeliveredProblemOrder) @@ -189,8 +187,10 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: len((refused, accepted)), checks, output.getvalue() + f"partial={partial}; zero={complete}; " - f"refused={refused.returncode}: {refused.stdout}{refused.stderr}; " - f"accepted={accepted.returncode}: {accepted.stdout}{accepted.stderr}", + f"refused={refused.outcome.summary}: " + f"{refused.stdout.decode(errors='replace')}{refused.stderr.decode(errors='replace')}; " + f"accepted={accepted.outcome.summary}: " + f"{accepted.stdout.decode(errors='replace')}{accepted.stderr.decode(errors='replace')}", ) From 93321e0f4dc753449e0adb742668afeac48fadac Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:04:45 -0400 Subject: [PATCH 20/36] Remove codec imports made obsolete by native declaration ownership --- tools/proofs/cn_phase3_record.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tools/proofs/cn_phase3_record.py b/tools/proofs/cn_phase3_record.py index 54cda2f8d8..bbadb40bd5 100644 --- a/tools/proofs/cn_phase3_record.py +++ b/tools/proofs/cn_phase3_record.py @@ -7,7 +7,6 @@ from __future__ import annotations import argparse -import json import os import shutil import subprocess @@ -17,7 +16,6 @@ from agent_comms.change_report import FileLine from agent_comms.comms import Comms -from agent_comms.field_codec import FieldCodec from agent_comms.goal_actions import CreateProblemGoalAction, SetGoalAction from agent_comms.goals import CountCheckResult, OrderCheck, RequestGoalOrder from agent_comms.progress_claims import MergedClaim From 4e8a8c89836593ebb41107827e2842094d004256 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:07:04 -0400 Subject: [PATCH 21/36] Pass candidate Python environment through the shared process owner explicitly --- src/agent_comms/commander_parity/deletion.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/agent_comms/commander_parity/deletion.py b/src/agent_comms/commander_parity/deletion.py index f199ea9733..78834661c6 100644 --- a/src/agent_comms/commander_parity/deletion.py +++ b/src/agent_comms/commander_parity/deletion.py @@ -141,7 +141,9 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: family + "def decisions():\n return []\n", "Repair the caller but leave one obsolete family site", ) - refused = run.invoke_command(cls.delivery_command(run, before, partial)) + refused = run.invoke_command( + cls.delivery_command(run, before, partial), env=run.python_environment() + ) after_refusal = run.commander.comms.goals.todos.get(before.id) remaining = count.recorded(partial, str(repository)) complete = cls.commit( @@ -149,7 +151,9 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: "def decisions():\n return []\n", "Delete the last obsolete family declaration", ) - accepted = run.invoke_command(cls.delivery_command(run, before, complete)) + accepted = run.invoke_command( + cls.delivery_command(run, before, complete), env=run.python_environment() + ) after_acceptance = run.commander.comms.goals.todos.get(before.id) zero = count.recorded(complete, str(repository)) primary = order.check.recorded(partial, str(repository)) From 9492f6c4f49149cdfafbeeb4ef45417fe1cea9ad Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:15:06 -0400 Subject: [PATCH 22/36] Require explicit project and environment at the common process boundary --- src/agent_comms/commander_parity/deletion.py | 6 ++++-- src/agent_comms/commander_parity/lifecycle.py | 8 +++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/agent_comms/commander_parity/deletion.py b/src/agent_comms/commander_parity/deletion.py index 78834661c6..fdfbb19ad0 100644 --- a/src/agent_comms/commander_parity/deletion.py +++ b/src/agent_comms/commander_parity/deletion.py @@ -142,7 +142,7 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: "Repair the caller but leave one obsolete family site", ) refused = run.invoke_command( - cls.delivery_command(run, before, partial), env=run.python_environment() + cls.delivery_command(run, before, partial), cwd=repository, env=run.python_environment() ) after_refusal = run.commander.comms.goals.todos.get(before.id) remaining = count.recorded(partial, str(repository)) @@ -152,7 +152,9 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: "Delete the last obsolete family declaration", ) accepted = run.invoke_command( - cls.delivery_command(run, before, complete), env=run.python_environment() + cls.delivery_command(run, before, complete), + cwd=repository, + env=run.python_environment(), ) after_acceptance = run.commander.comms.goals.todos.get(before.id) zero = count.recorded(complete, str(repository)) diff --git a/src/agent_comms/commander_parity/lifecycle.py b/src/agent_comms/commander_parity/lifecycle.py index 60117649bd..f5f2d68034 100644 --- a/src/agent_comms/commander_parity/lifecycle.py +++ b/src/agent_comms/commander_parity/lifecycle.py @@ -189,15 +189,17 @@ def python_environment() -> dict[str, str]: @classmethod def invoke(cls, program: str, *arguments: str) -> ChildResult: return cls.invoke_command( - (sys.executable, "-c", program, *arguments), env=cls.python_environment() + (sys.executable, "-c", program, *arguments), + cwd=Path.cwd(), + env=cls.python_environment(), ) @staticmethod def invoke_command( command: tuple[str, ...], *, - cwd: str | Path | None = None, - env: dict[str, str] | None = None, + cwd: str | Path, + env: dict[str, str], ) -> ChildResult: return asyncio.run(BoundedRun.run(command, timeout=120, cwd=cwd, env=env)) From e563fb2a490fab89e3ec7be2e32490efab6afc9c Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:25:56 -0400 Subject: [PATCH 23/36] Use the current recorded-time owner throughout native lifecycle comparisons --- src/agent_comms/commander_parity/deletion.py | 4 ++-- src/agent_comms/commander_parity/handoff.py | 4 ++-- src/agent_comms/commander_parity/lifecycle.py | 15 ++++++++++----- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/agent_comms/commander_parity/deletion.py b/src/agent_comms/commander_parity/deletion.py index fdfbb19ad0..e1dd7a6d9d 100644 --- a/src/agent_comms/commander_parity/deletion.py +++ b/src/agent_comms/commander_parity/deletion.py @@ -14,7 +14,7 @@ from ..change_report import FileLine from ..child_process import CountPrinted, ExitedOutcome -from ..commander.order import OrderFile, deadline +from ..commander.order import OrderFile from ..field_codec import FieldCodec from ..goal_actions import CreateProblemGoalAction from ..goals import CountCheckResult, OrderCheck @@ -234,7 +234,7 @@ def send(cls, run: LifecycleRun, document: OrderFile) -> Todo: request=document.order.request( run.commander.comms.registry.require(run.commander.commander), ("P1",) ), - deadline=deadline(run.due), + deadline=run.deadline, commander=run.commander.commander, ), ) diff --git a/src/agent_comms/commander_parity/handoff.py b/src/agent_comms/commander_parity/handoff.py index 5f6b6ef720..4657912be7 100644 --- a/src/agent_comms/commander_parity/handoff.py +++ b/src/agent_comms/commander_parity/handoff.py @@ -12,7 +12,7 @@ from ..change_report import FileLine from ..child_process import ChildOutcome, ChildResult, ExitedOutcome from ..commander.config import CommanderConfig -from ..commander.order import OrderFile, deadline +from ..commander.order import OrderFile from ..field_codec import FieldCodec from ..goal_actions import OrderGoalAction from ..tools import CommsOrderTool @@ -84,7 +84,7 @@ def native(run: LifecycleRun, receiver: str, document: OrderFile, pid: str) -> C expected_revision=todo.revision, assigner=context.incarnation, order=document.order, - deadline=deadline(run.due), + deadline=run.deadline, commander=context.commander, request=document.order.request( context.comms.registry.require(context.commander), (pid,) diff --git a/src/agent_comms/commander_parity/lifecycle.py b/src/agent_comms/commander_parity/lifecycle.py index f5f2d68034..c876893b9d 100644 --- a/src/agent_comms/commander_parity/lifecycle.py +++ b/src/agent_comms/commander_parity/lifecycle.py @@ -23,10 +23,11 @@ from ..check_root import CheckRoot from ..child_process import BoundedRun, ChildResult from ..commander.config import CommanderConfig -from ..commander.order import Commander, OrderFile, hhmm +from ..commander.order import Commander, OrderFile from ..commander.request import RequestAddVerb from ..field_codec import FieldCodec from ..goals import CountCheckResult, OrderCheck, ProblemGoalOrder +from ..recorded_time import RecordedEventTime from ..todos import ( ApplicationOrderRun, MergedProgress, @@ -205,7 +206,11 @@ def invoke_command( @property def due(self) -> str: - return time.strftime("%H:%M", time.localtime(time.time() + 3600)) + return RecordedEventTime(time.time() + 3600).clock() + + @property + def deadline(self) -> RecordedEventTime: + return RecordedEventTime(time.time()).at_clock(self.due) def create(self) -> Todo: self.commander.problem( @@ -437,16 +442,16 @@ def checks( ( "unit messages hide clocks", all( - hhmm(clock) not in message.body + clock.clock() not in message.body for clock in (before.deadline, after.deadline) for message in messages ), ), ( "unit goal hides deadline", - "Deadline:" not in instructions and hhmm(after.deadline) not in instructions, + "Deadline:" not in instructions and after.deadline.clock() not in instructions, ), - ("commander still sees deadline", f"due {hhmm(after.deadline)}" in output), + ("commander still sees deadline", f"due {after.deadline.clock()}" in output), ) From 805e86e3c12f2b418d5ce71f1ea968c69f2a7dc9 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:28:50 -0400 Subject: [PATCH 24/36] Drop the deleted commander CLI field from the lifecycle constructor --- src/agent_comms/commander_parity/lifecycle.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/agent_comms/commander_parity/lifecycle.py b/src/agent_comms/commander_parity/lifecycle.py index c876893b9d..6ae95221a0 100644 --- a/src/agent_comms/commander_parity/lifecycle.py +++ b/src/agent_comms/commander_parity/lifecycle.py @@ -126,7 +126,6 @@ def open(cls, *, extra_threads: tuple[str, ...] = ()) -> Iterator[LifecycleRun]: commander = MeasuredCommander( commander=config.commander, root=root, - cli=config.cli, state=root / "commander-state", board=root / "board.md", narrative=root / "narrative.md", From c545e397a55caef19c8eebfc03a8167630a3dd6d Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:31:36 -0400 Subject: [PATCH 25/36] Keep generated deadline input in the actual CLI HH:MM grammar --- src/agent_comms/commander_parity/lifecycle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/agent_comms/commander_parity/lifecycle.py b/src/agent_comms/commander_parity/lifecycle.py index 6ae95221a0..d4b89594cd 100644 --- a/src/agent_comms/commander_parity/lifecycle.py +++ b/src/agent_comms/commander_parity/lifecycle.py @@ -205,7 +205,7 @@ def invoke_command( @property def due(self) -> str: - return RecordedEventTime(time.time() + 3600).clock() + return time.strftime("%H:%M", time.localtime(time.time() + 3600)) @property def deadline(self) -> RecordedEventTime: From efd61aeb328d09b5f937a622bbad6e28208240a9 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:14:59 -0400 Subject: [PATCH 26/36] Use Repo.git for the complete delivered-commit fixture lifecycle --- src/agent_comms/commander_parity/delivery.py | 79 ++++++++------------ tests/test_commander_parity_delivery.py | 30 ++++++-- 2 files changed, 55 insertions(+), 54 deletions(-) diff --git a/src/agent_comms/commander_parity/delivery.py b/src/agent_comms/commander_parity/delivery.py index 0026115cd7..fa0e5bf6c3 100644 --- a/src/agent_comms/commander_parity/delivery.py +++ b/src/agent_comms/commander_parity/delivery.py @@ -5,7 +5,6 @@ import contextlib import io import json -import subprocess from dataclasses import dataclass, replace from pathlib import Path @@ -13,6 +12,7 @@ from ..commander.order import OrderFile from ..field_codec import FieldCodec from ..progress_claims import MergedClaim +from ..repo import Repo from ..todos import CommitDelivery, FileDeliveryEvidence, Todo from ..tools import CommsOrderDoneTool from . import ParityComparison @@ -72,57 +72,44 @@ def describe(self) -> str: class DeliveryRepository: path: Path - def git(self, *arguments: str) -> str: - return subprocess.check_output( - ( - "git", - "-C", - str(self.path), - "-c", - "user.name=parity", - "-c", - "user.email=parity@invalid", - *arguments, - ), - text=True, - stderr=subprocess.PIPE, - ).strip() - @classmethod def create(cls, root: Path) -> DeliveryRepository: path = root / "delivery-repository" path.mkdir() - repo = cls(path) remote = root / "delivery-origin.git" - subprocess.run(("git", "init", "--bare", "-q", str(remote)), check=True) - repo.git("init", "-q", "-b", "main") + Repo.git(root, "init", "--bare", "-q", str(remote)) + Repo.git(path, "init", "-q", "-b", "main") + Repo.git(path, "config", "user.name", "parity") + Repo.git(path, "config", "user.email", "parity@invalid") url = "https://github.com/parity-local/delivery.git" - repo.git("config", f"url.{remote}.insteadOf", url) - repo.git("remote", "add", "origin", url) - repo.git("commit", "-q", "--allow-empty", "-m", "copied delivery base") - repo.git("push", "-q", "origin", "main") - repo.git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") - return repo + Repo.git(path, "config", f"url.{remote}.insteadOf", url) + Repo.git(path, "remote", "add", "origin", url) + Repo.git(path, "commit", "-q", "--allow-empty", "-m", "copied delivery base") + Repo.git(path, "push", "-q", "origin", "main") + Repo.git(path, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + return cls(path) def cases(self) -> tuple[tuple[str, str], ...]: - base = self.git("rev-parse", "HEAD") - self.git("switch", "-q", "-c", "main-answer") - self.git("commit", "-q", "--allow-empty", "-m", "answer integrated on main") - main = self.git("rev-parse", "HEAD") - self.git("switch", "-q", "main") - self.git("merge", "-q", "--no-ff", "main-answer", "-m", "integrate main answer") - self.git("push", "-q", "origin", "main") - self.git("switch", "-q", "-c", "branch-answer", base) - self.git("commit", "-q", "--allow-empty", "-m", "answer integrated elsewhere") - branch = self.git("rev-parse", "HEAD") - self.git("switch", "-q", "-c", "integration", base) - self.git("merge", "-q", "--no-ff", "branch-answer", "-m", "integrate branch answer") - self.git("push", "-q", "origin", "integration") - self.git("switch", "-q", "-c", "unmerged-answer", base) - self.git("commit", "-q", "--allow-empty", "-m", "published but not integrated") - unmerged = self.git("rev-parse", "HEAD") - self.git("push", "-q", "origin", "unmerged-answer") - self.git("switch", "-q", "main") + base = Repo.git(self.path, "rev-parse", "HEAD").strip() + Repo.git(self.path, "switch", "-q", "-c", "main-answer") + Repo.git(self.path, "commit", "-q", "--allow-empty", "-m", "answer integrated on main") + main = Repo.git(self.path, "rev-parse", "HEAD").strip() + Repo.git(self.path, "switch", "-q", "main") + Repo.git(self.path, "merge", "-q", "--no-ff", "main-answer", "-m", "integrate main answer") + Repo.git(self.path, "push", "-q", "origin", "main") + Repo.git(self.path, "switch", "-q", "-c", "branch-answer", base) + Repo.git(self.path, "commit", "-q", "--allow-empty", "-m", "answer integrated elsewhere") + branch = Repo.git(self.path, "rev-parse", "HEAD").strip() + Repo.git(self.path, "switch", "-q", "-c", "integration", base) + Repo.git( + self.path, "merge", "-q", "--no-ff", "branch-answer", "-m", "integrate branch answer" + ) + Repo.git(self.path, "push", "-q", "origin", "integration") + Repo.git(self.path, "switch", "-q", "-c", "unmerged-answer", base) + Repo.git(self.path, "commit", "-q", "--allow-empty", "-m", "published but not integrated") + unmerged = Repo.git(self.path, "rev-parse", "HEAD").strip() + Repo.git(self.path, "push", "-q", "origin", "unmerged-answer") + Repo.git(self.path, "switch", "-q", "main") return ( ("merged to main", main), ("merged to another branch", branch), @@ -185,7 +172,7 @@ def read(cls) -> ParityComparison: problem=native_order.id, order_id=native_order.order.checked().id, delivery=CommitDelivery( - commit=repository.git("rev-parse", "HEAD"), + commit=Repo.git(repository.path, "rev-parse", "HEAD").strip(), delivered_commit=commit, evidence=FileDeliveryEvidence(str(run.artifact)), ), @@ -207,5 +194,5 @@ def read(cls) -> ParityComparison: run.commander.comms.goals.todos.get(native_order.id), process ) cases.append((name, commit, current, native)) - checked_commit = repository.git("rev-parse", "HEAD") + checked_commit = Repo.git(repository.path, "rev-parse", "HEAD").strip() return DeliveryComparison(checked_commit, tuple(cases)) diff --git a/tests/test_commander_parity_delivery.py b/tests/test_commander_parity_delivery.py index 023bf6faa1..c3f58bc664 100644 --- a/tests/test_commander_parity_delivery.py +++ b/tests/test_commander_parity_delivery.py @@ -1,18 +1,32 @@ -from agent_comms.commander_parity.delivery import DeliveryRepository, DeliveredCommitCase +from agent_comms.commander_parity.delivery import DeliveredCommitCase, DeliveryRepository from agent_comms.commander_parity.rows import DeliveredCommitParityRow from agent_comms.goals import CountCheckResult, OrderCheck +from agent_comms.repo import Repo def test_delivery_graph_is_pushed_and_distinguishes_integration(tmp_path): repository = DeliveryRepository.create(tmp_path) + assert "git" not in vars(DeliveryRepository) + assert Repo.git(repository.path, "config", "user.name").strip() == "parity" + assert Repo.git(repository.path, "config", "user.email").strip() == "parity@invalid" main, branch, unmerged = repository.cases() for _, commit in (main, branch, unmerged): - assert repository.git("branch", "--remotes", "--contains", commit, "--list", "origin/*") - assert repository.git("merge-base", main[1], "origin/main") == main[1] - assert repository.git("merge-base", branch[1], "origin/integration") == branch[1] - assert repository.git("merge-base", branch[1], "origin/main") != branch[1] - assert repository.git("merge-base", unmerged[1], "origin/main") != unmerged[1] - assert repository.git("merge-base", unmerged[1], "origin/integration") != unmerged[1] + assert Repo.git( + repository.path, "branch", "--remotes", "--contains", commit, "--list", "origin/*" + ).strip() + assert Repo.git(repository.path, "merge-base", main[1], "origin/main").strip() == main[1] + assert ( + Repo.git(repository.path, "merge-base", branch[1], "origin/integration").strip() + == branch[1] + ) + assert Repo.git(repository.path, "merge-base", branch[1], "origin/main").strip() != branch[1] + assert ( + Repo.git(repository.path, "merge-base", unmerged[1], "origin/main").strip() != unmerged[1] + ) + assert ( + Repo.git(repository.path, "merge-base", unmerged[1], "origin/integration").strip() + != unmerged[1] + ) def test_check_uses_configured_persistent_checkout_and_retains_real_result(tmp_path): @@ -20,7 +34,7 @@ def test_check_uses_configured_persistent_checkout_and_retains_real_result(tmp_p checkout_base = tmp_path / "persistent-checkouts" marker = tmp_path / "observed-checkouts" check = OrderCheck(str(repository.path), f'pwd >> "{marker}"; echo 0', CountCheckResult(0)) - commit = repository.git("rev-parse", "HEAD") + commit = Repo.git(repository.path, "rev-parse", "HEAD").strip() first = check.at(commit, str(repository.path), checkout_base) assert check.at(commit, str(repository.path), checkout_base) == first (actual,) = marker.read_text().splitlines() From da07d6c90281aaf74100f84dfe0f06596d1ef221 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:50:16 -0400 Subject: [PATCH 27/36] Declare why disposable parity scenarios are not live phase implementation tasks --- src/agent_comms/commander_parity/lifecycle.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/agent_comms/commander_parity/lifecycle.py b/src/agent_comms/commander_parity/lifecycle.py index d4b89594cd..27ace41dec 100644 --- a/src/agent_comms/commander_parity/lifecycle.py +++ b/src/agent_comms/commander_parity/lifecycle.py @@ -176,6 +176,10 @@ def open(cls, *, extra_threads: tuple[str, ...] = ()) -> Iterator[LifecycleRun]: "from reaching zero.", "This is stupid because an unfinished copied decision must not count " "as delivered work.", + unplanned_reason=( + "This disposable comparison scenario measures the requested parity " + "workflow without implementing a phase task." + ), ) ) ) From 41e2552436ce2cb3deffaccf1cfa33e39bc1bc06 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:39:10 -0400 Subject: [PATCH 28/36] Compare judge and native Verdict on actual copied-session edits --- src/agent_comms/commander_parity/rows.py | 2 + .../commander_parity/verdict_edit.mjs | 21 ++ src/agent_comms/commander_parity/verdicts.py | 205 ++++++++++++++++++ 3 files changed, 228 insertions(+) create mode 100644 src/agent_comms/commander_parity/verdict_edit.mjs create mode 100644 src/agent_comms/commander_parity/verdicts.py diff --git a/src/agent_comms/commander_parity/rows.py b/src/agent_comms/commander_parity/rows.py index 7847f5531c..65385cf795 100644 --- a/src/agent_comms/commander_parity/rows.py +++ b/src/agent_comms/commander_parity/rows.py @@ -22,6 +22,7 @@ verify_order_progress, ) from .load import LoadComparison +from .verdicts import VerdictComparison from .measurements import RuleComparison, StorageComparison, measured_load from .story import StoryCase @@ -97,6 +98,7 @@ class VerdictParityRow(ParityRow): current = "`judge.py ok`, `back`; `verdicts.jsonl`" native = "Order `Verdict`; send-back revises the Goal and records its strike atomically" phases = (RecordPlanePhase,) + comparison = VerdictComparison.read class PlainWordsParityRow(ParityRow): diff --git a/src/agent_comms/commander_parity/verdict_edit.mjs b/src/agent_comms/commander_parity/verdict_edit.mjs new file mode 100644 index 0000000000..37570d850b --- /dev/null +++ b/src/agent_comms/commander_parity/verdict_edit.mjs @@ -0,0 +1,21 @@ +// A controlled request to the installed native edit tool; persist its actual result. +// No provider call, replacement tool, fabricated result, or original session write. +import { pathToFileURL } from "node:url"; +const [packagePath, sessionPath, path, callId, replacement] = process.argv.slice(2); +const { createEditTool, SessionManager } = await import(pathToFileURL(`${packagePath}/dist/index.js`).href); +const { readFile } = await import("node:fs/promises"); +const oldText = await readFile(path, "utf8"); +const args = { path, edits: [{ oldText, newText: replacement }] }; +const session = SessionManager.open(sessionPath); +session.appendMessage({ role: "user", content: "Execute one isolated verdict-check edit.", timestamp: Date.now() }); +session.appendMessage({ + role: "assistant", content: [{ type: "toolCall", id: callId, name: "edit", arguments: args }], + api: "controlled-verification", provider: "controlled-verification", model: "local-native-edit", + usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, + stopReason: "toolUse", timestamp: Date.now(), +}); +const result = await createEditTool(process.cwd()).execute(callId, args); +session.appendMessage({ role: "toolResult", toolCallId: callId, toolName: "edit", + content: result.content, details: result.details, isError: false, timestamp: Date.now() }); +console.log(JSON.stringify({ callId, changed: (await readFile(path, "utf8")) === replacement })); diff --git a/src/agent_comms/commander_parity/verdicts.py b/src/agent_comms/commander_parity/verdicts.py new file mode 100644 index 0000000000..03146f861a --- /dev/null +++ b/src/agent_comms/commander_parity/verdicts.py @@ -0,0 +1,205 @@ +"""Judge/native verdicts on actual native edits in LifecycleRun's disposable bus.""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import subprocess +from abc import ABC, abstractmethod +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import ClassVar +from uuid import uuid4 + +from ..active_route import resolve_comms_route +from ..commander.judge import BackVerb, Edit, OkVerb, VerdictVerb +from ..todos import Todo +from ..tools import CommsVerdictTool, TodoChanged +from ..turn_context import GoalSegment +from . import ParityComparison +from .lifecycle import LifecycleRun + + +@dataclass(frozen=True) +class VerdictEffect: + call_id: str + verdicts: int + todo_revisions: int + strikes: int + goal_revisions: int + goal_transitions: int + goal_retained: bool + goal_state_retained: bool + progress: str + native_calls: int + native_result_retained: bool + + +class VerdictCase(ABC): + changes: ClassVar[int] + + @classmethod + @abstractmethod + def replacement(cls, run: LifecycleRun) -> str: ... + + @classmethod + @abstractmethod + def command(cls, run: LifecycleRun, todo: Todo, edit: Edit) -> VerdictVerb: ... + + @staticmethod + def judge(run: LifecycleRun, command: VerdictVerb, todo: Todo, edit: Edit) -> object: + return command.apply(run.commander) + + @staticmethod + def native(run: LifecycleRun, command: VerdictVerb, todo: Todo, edit: Edit) -> object: + return run.commander.call( + CommsVerdictTool( + problem=todo.id, operation=command.operation(run.commander, todo, edit.id) + ) + ) + + @classmethod + def capture( + cls, call_id: str, invoke: Callable[[LifecycleRun, VerdictVerb, Todo, Edit], object] + ) -> VerdictEffect: + with LifecycleRun.open() as run, contextlib.redirect_stdout(io.StringIO()): + before = run.create() + worker = run.commander.comms.registry.require(run.worker) + goal = worker.goal.require() + history = len(run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)) + package = resolve_comms_route().launch().require_private().validate() + subprocess.run( + ( + "node", + "--no-global-search-paths", + str(Path(__file__).with_name("verdict_edit.mjs")), + str(package.path), + worker.session_file, + str(run.decisions), + call_id, + cls.replacement(run), + ), + cwd=worker.worktree, + env=package.node_environment(dict(os.environ)), + capture_output=True, + text=True, + timeout=30, + check=True, + ) + edits = Edit.unjudged(run.commander.comms, run.commander.commander) + if len(edits) != 1 or edits[0].id != call_id: + raise ValueError("The copied unit must expose exactly its one real native edit") + edit = edits[0] + invoke(run, cls.command(run, before, edit), before, edit) + saved = run.commander.comms.goals.todos.get(before.id) + worker = run.commander.comms.registry.require(run.worker) + after = worker.goal.require() + native = tuple( + item + for item in run.commander.invocations + if isinstance(item.request, CommsVerdictTool) + ) + return VerdictEffect( + call_id, + len(saved.verdicts) - len(before.verdicts), + saved.revision - before.revision, + saved.strike_count - before.strike_count, + after.revision - goal.revision, + len(run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)) - history, + after.id == goal.id, + after.state == goal.state, + GoalSegment.capture(worker, after, run.commander.comms.goals).progress, + len(native), + len(native) == 1 and native[0].result == TodoChanged(saved, saved.strike_count), + ) + + @classmethod + def valid(cls, effect: VerdictEffect) -> bool: + return ( + effect.verdicts == effect.todo_revisions == effect.native_calls == 1 + and effect.strikes == effect.goal_revisions == effect.goal_transitions == cls.changes + and effect.goal_retained + and effect.goal_state_retained + and effect.native_result_retained + ) + + +class AcceptedCase(VerdictCase): + changes = 0 + + @classmethod + def replacement(cls, run: LifecycleRun) -> str: + return "[]" + + @classmethod + def command(cls, run: LifecycleRun, todo: Todo, edit: Edit) -> OkVerb: + return OkVerb( + ids=(f"{edit.id}:{edit.code()}",), + why="The native edit removes the copied workflow decision.", + serves="Remove the copied workflow decision", + lines=(edit.hunks[0].new_text,), + ) + + +class SendBackCase(VerdictCase): + changes = 1 + + @classmethod + def replacement(cls, run: LifecycleRun) -> str: + return json.dumps([run.worker, run.worker]) + + @classmethod + def command(cls, run: LifecycleRun, todo: Todo, edit: Edit) -> BackVerb: + return BackVerb( + ids=(f"{edit.id}:{edit.code()}",), + msg=todo.messages[-1].message_id, + lines=(edit.hunks[0].new_text,), + why="The edit duplicates the copied workflow decision instead of removing it.", + roast=( + "This is stupid because the edit keeps two copies of the same decision " + "instead of deleting it." + ), + fix="Remove the copied decision and let the existing check measure its absence.", + pattern="AGENT-2", + fact="the copied workflow decision collection", + at=f"{run.decisions}:1", + derive="delete-copy", + by=f"{Path(__file__).resolve()}:1", + ) + + +@dataclass(frozen=True) +class VerdictComparison(ParityComparison): + accepted_current: VerdictEffect + accepted_native: VerdictEffect + back_current: VerdictEffect + back_native: VerdictEffect + + @property + def passed(self) -> bool: + return ( + self.accepted_current == self.accepted_native + and self.back_current == self.back_native + and AcceptedCase.valid(self.accepted_native) + and SendBackCase.valid(self.back_native) + ) + + def describe(self) -> str: + return ( + f"accepted current/native equal={self.accepted_current == self.accepted_native}; " + f"send-back current/native equal={self.back_current == self.back_native}; " + f"accepted={self.accepted_native!r}; send-back={self.back_native!r}" + ) + + @classmethod + def read(cls) -> VerdictComparison: + call_id = uuid4().hex + return cls( + AcceptedCase.capture(call_id, AcceptedCase.judge), + AcceptedCase.capture(call_id, AcceptedCase.native), + SendBackCase.capture(call_id, SendBackCase.judge), + SendBackCase.capture(call_id, SendBackCase.native), + ) From ec8d3e71ed03b12aeb43b7382c89529a0250deea Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:41:30 -0400 Subject: [PATCH 29/36] Verify persisted verdict call identity and the strike event --- src/agent_comms/commander_parity/verdicts.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/agent_comms/commander_parity/verdicts.py b/src/agent_comms/commander_parity/verdicts.py index 03146f861a..fcb3c59d86 100644 --- a/src/agent_comms/commander_parity/verdicts.py +++ b/src/agent_comms/commander_parity/verdicts.py @@ -36,6 +36,7 @@ class VerdictEffect: progress: str native_calls: int native_result_retained: bool + strike_matches_verdict_event: bool class VerdictCase(ABC): @@ -98,12 +99,15 @@ def capture( worker = run.commander.comms.registry.require(run.worker) after = worker.goal.require() native = tuple( - item + (item.request, item.result) for item in run.commander.invocations if isinstance(item.request, CommsVerdictTool) ) + if len(native) != 1 or native[0][0].operation.tool_call_id != call_id: + raise ValueError("The native verdict must judge this one original copied tool call") + request, result = native[0] return VerdictEffect( - call_id, + request.operation.tool_call_id, len(saved.verdicts) - len(before.verdicts), saved.revision - before.revision, saved.strike_count - before.strike_count, @@ -113,7 +117,13 @@ def capture( after.state == goal.state, GoalSegment.capture(worker, after, run.commander.comms.goals).progress, len(native), - len(native) == 1 and native[0].result == TodoChanged(saved, saved.strike_count), + result == TodoChanged(saved, saved.strike_count) + and request.operation in saved.verdicts, + all( + strike.at == request.operation.at + and strike.previous == request.operation.previous + for strike in saved.strikes[len(before.strikes) :] + ), ) @classmethod @@ -124,6 +134,7 @@ def valid(cls, effect: VerdictEffect) -> bool: and effect.goal_retained and effect.goal_state_retained and effect.native_result_retained + and effect.strike_matches_verdict_event ) From 7b4a9ec114426c3b0da2cd52bd42273858c12f35 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:44:07 -0400 Subject: [PATCH 30/36] Check the concrete verdict kind and its committed Goal transition --- src/agent_comms/commander_parity/verdicts.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/agent_comms/commander_parity/verdicts.py b/src/agent_comms/commander_parity/verdicts.py index fcb3c59d86..bae6e12111 100644 --- a/src/agent_comms/commander_parity/verdicts.py +++ b/src/agent_comms/commander_parity/verdicts.py @@ -16,7 +16,7 @@ from ..active_route import resolve_comms_route from ..commander.judge import BackVerb, Edit, OkVerb, VerdictVerb -from ..todos import Todo +from ..todos import AcceptedVerdict, SendBackVerdict, Todo, ToolCallVerdict from ..tools import CommsVerdictTool, TodoChanged from ..turn_context import GoalSegment from . import ParityComparison @@ -37,10 +37,13 @@ class VerdictEffect: native_calls: int native_result_retained: bool strike_matches_verdict_event: bool + declared_verdict_recorded: bool + goal_transition_retained: bool class VerdictCase(ABC): changes: ClassVar[int] + native_owner: ClassVar[type[ToolCallVerdict]] @classmethod @abstractmethod @@ -71,6 +74,8 @@ def capture( worker = run.commander.comms.registry.require(run.worker) goal = worker.goal.require() history = len(run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)) + for path in (Path(worker.session_file), run.decisions, Path(worker.worktree)): + path.resolve().relative_to(run.commander.root.resolve()) package = resolve_comms_route().launch().require_private().validate() subprocess.run( ( @@ -106,13 +111,16 @@ def capture( if len(native) != 1 or native[0][0].operation.tool_call_id != call_id: raise ValueError("The native verdict must judge this one original copied tool call") request, result = native[0] + transitions = run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)[ + history: + ] return VerdictEffect( request.operation.tool_call_id, len(saved.verdicts) - len(before.verdicts), saved.revision - before.revision, saved.strike_count - before.strike_count, after.revision - goal.revision, - len(run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)) - history, + len(transitions), after.id == goal.id, after.state == goal.state, GoalSegment.capture(worker, after, run.commander.comms.goals).progress, @@ -124,6 +132,8 @@ def capture( and strike.previous == request.operation.previous for strike in saved.strikes[len(before.strikes) :] ), + isinstance(request.operation, cls.native_owner), + all(entry.before == goal and entry.after == after for entry in transitions), ) @classmethod @@ -135,11 +145,14 @@ def valid(cls, effect: VerdictEffect) -> bool: and effect.goal_state_retained and effect.native_result_retained and effect.strike_matches_verdict_event + and effect.declared_verdict_recorded + and effect.goal_transition_retained ) class AcceptedCase(VerdictCase): changes = 0 + native_owner = AcceptedVerdict @classmethod def replacement(cls, run: LifecycleRun) -> str: @@ -157,6 +170,7 @@ def command(cls, run: LifecycleRun, todo: Todo, edit: Edit) -> OkVerb: class SendBackCase(VerdictCase): changes = 1 + native_owner = SendBackVerdict @classmethod def replacement(cls, run: LifecycleRun) -> str: From 6d8254648857e17ecb137700a91b74b7ab858c97 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:46:51 -0400 Subject: [PATCH 31/36] Prepare the real copied-root rule review before invoking judge --- .../commander_parity/verdict_edit.mjs | 1 + src/agent_comms/commander_parity/verdicts.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/agent_comms/commander_parity/verdict_edit.mjs b/src/agent_comms/commander_parity/verdict_edit.mjs index 37570d850b..a3ec46c81f 100644 --- a/src/agent_comms/commander_parity/verdict_edit.mjs +++ b/src/agent_comms/commander_parity/verdict_edit.mjs @@ -16,6 +16,7 @@ session.appendMessage({ stopReason: "toolUse", timestamp: Date.now(), }); const result = await createEditTool(process.cwd()).execute(callId, args); +if ((await readFile(path, "utf8")) !== replacement) throw new Error("Native edit did not apply its request"); session.appendMessage({ role: "toolResult", toolCallId: callId, toolName: "edit", content: result.content, details: result.details, isError: false, timestamp: Date.now() }); console.log(JSON.stringify({ callId, changed: (await readFile(path, "utf8")) === replacement })); diff --git a/src/agent_comms/commander_parity/verdicts.py b/src/agent_comms/commander_parity/verdicts.py index bae6e12111..e885610a4c 100644 --- a/src/agent_comms/commander_parity/verdicts.py +++ b/src/agent_comms/commander_parity/verdicts.py @@ -16,6 +16,8 @@ from ..active_route import resolve_comms_route from ..commander.judge import BackVerb, Edit, OkVerb, VerdictVerb +from ..commander.rules import AnswerVerb, ReviewVerb +from ..rule_reviews import DrawnRule, RuleReviews from ..todos import AcceptedVerdict, SendBackVerdict, Todo, ToolCallVerdict from ..tools import CommsVerdictTool, TodoChanged from ..turn_context import GoalSegment @@ -70,6 +72,21 @@ def capture( cls, call_id: str, invoke: Callable[[LifecycleRun, VerdictVerb, Todo, Edit], object] ) -> VerdictEffect: with LifecycleRun.open() as run, contextlib.redirect_stdout(io.StringIO()): + # Satisfy the actual current command's gate in this copy; never bypass it + # or transfer the original commander's review authority into a new root. + ReviewVerb().apply(run.commander) + with RuleReviews(run.commander.root).snapshot() as db: + drawn = DrawnRule.select(db, reviewer=run.commander.commander, order_by=("n",)) + for rule in drawn: + AnswerVerb( + n=rule.n, + text=( + f'"{rule.rule}" This isolated comparison keeps verdict mutation in ' + "its existing native owner, preserves original sessions, and checks " + "the actual stored Goal and strike rather than a second state store: " + f"{Path(__file__).resolve()}:1" + ), + ).apply(run.commander) before = run.create() worker = run.commander.comms.registry.require(run.worker) goal = worker.goal.require() From d5071db816cf7a5ead3d748533a60c6afabbf619 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 19 Oct 2026 23:49:19 -0400 Subject: [PATCH 32/36] Require the send-back reason in the derived Goal and test the verdict family --- src/agent_comms/commander_parity/rows.py | 2 +- src/agent_comms/commander_parity/verdicts.py | 7 ++- tests/test_commander_parity_verdicts.py | 55 ++++++++++++++++++++ 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 tests/test_commander_parity_verdicts.py diff --git a/src/agent_comms/commander_parity/rows.py b/src/agent_comms/commander_parity/rows.py index 65385cf795..d01e09767e 100644 --- a/src/agent_comms/commander_parity/rows.py +++ b/src/agent_comms/commander_parity/rows.py @@ -22,9 +22,9 @@ verify_order_progress, ) from .load import LoadComparison -from .verdicts import VerdictComparison from .measurements import RuleComparison, StorageComparison, measured_load from .story import StoryCase +from .verdicts import VerdictComparison class CreateProblemParityRow(ParityRow): diff --git a/src/agent_comms/commander_parity/verdicts.py b/src/agent_comms/commander_parity/verdicts.py index e885610a4c..43fd259ba5 100644 --- a/src/agent_comms/commander_parity/verdicts.py +++ b/src/agent_comms/commander_parity/verdicts.py @@ -188,6 +188,11 @@ def command(cls, run: LifecycleRun, todo: Todo, edit: Edit) -> OkVerb: class SendBackCase(VerdictCase): changes = 1 native_owner = SendBackVerdict + why: ClassVar[str] = "The edit duplicates the copied workflow decision instead of removing it." + + @classmethod + def valid(cls, effect: VerdictEffect) -> bool: + return super().valid(effect) and cls.why in effect.progress @classmethod def replacement(cls, run: LifecycleRun) -> str: @@ -199,7 +204,7 @@ def command(cls, run: LifecycleRun, todo: Todo, edit: Edit) -> BackVerb: ids=(f"{edit.id}:{edit.code()}",), msg=todo.messages[-1].message_id, lines=(edit.hunks[0].new_text,), - why="The edit duplicates the copied workflow decision instead of removing it.", + why=cls.why, roast=( "This is stupid because the edit keeps two copies of the same decision " "instead of deleting it." diff --git a/tests/test_commander_parity_verdicts.py b/tests/test_commander_parity_verdicts.py new file mode 100644 index 0000000000..75676f9cf5 --- /dev/null +++ b/tests/test_commander_parity_verdicts.py @@ -0,0 +1,55 @@ +"""Comparison invariants; the configured LifecycleRun journey supplies native proof.""" + +from dataclasses import replace + +from agent_comms.commander_parity.rows import VerdictParityRow +from agent_comms.commander_parity.verdicts import ( + AcceptedCase, + SendBackCase, + VerdictComparison, + VerdictEffect, +) + + +def test_verdict_family_requires_the_actual_call_event_goal_and_strike_together(): + accepted = VerdictEffect( + call_id="one-call", + verdicts=1, + todo_revisions=1, + strikes=0, + goal_revisions=0, + goal_transitions=0, + goal_retained=True, + goal_state_retained=True, + progress="P1: Open", + native_calls=1, + native_result_retained=True, + strike_matches_verdict_event=True, + declared_verdict_recorded=True, + goal_transition_retained=True, + ) + back = replace( + accepted, strikes=1, goal_revisions=1, goal_transitions=1, progress=SendBackCase.why + ) + compared = VerdictComparison(accepted, accepted, back, back) + assert compared.passed and AcceptedCase.valid(accepted) and SendBackCase.valid(back) + for changed in ( + replace(back, verdicts=0), + replace(back, todo_revisions=2), + replace(back, strikes=0), + replace(back, goal_revisions=0), + replace(back, goal_transitions=2), + replace(back, native_calls=0), + replace(back, goal_retained=False), + replace(back, goal_state_retained=False), + replace(back, native_result_retained=False), + replace(back, strike_matches_verdict_event=False), + replace(back, declared_verdict_recorded=False), + replace(back, goal_transition_retained=False), + replace(back, progress=""), + ): + assert not SendBackCase.valid(changed) + assert not replace(compared, back_current=changed, back_native=changed).passed + assert not replace(compared, accepted_native=replace(accepted, call_id="other-call")).passed + assert "verify" not in VerdictParityRow.__dict__ + assert VerdictParityRow.comparison == VerdictComparison.read From b29e38974008b10172b76ac07c00d2a13b0934eb Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:00:53 -0400 Subject: [PATCH 33/36] Use LifecycleObservation for verdict proof and retain control input with its Python owner --- .../commander_parity/verdict_edit.mjs | 22 --- src/agent_comms/commander_parity/verdicts.py | 161 +++++++++++------- tests/test_commander_parity_verdicts.py | 56 +++--- 3 files changed, 125 insertions(+), 114 deletions(-) delete mode 100644 src/agent_comms/commander_parity/verdict_edit.mjs diff --git a/src/agent_comms/commander_parity/verdict_edit.mjs b/src/agent_comms/commander_parity/verdict_edit.mjs deleted file mode 100644 index a3ec46c81f..0000000000 --- a/src/agent_comms/commander_parity/verdict_edit.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// A controlled request to the installed native edit tool; persist its actual result. -// No provider call, replacement tool, fabricated result, or original session write. -import { pathToFileURL } from "node:url"; -const [packagePath, sessionPath, path, callId, replacement] = process.argv.slice(2); -const { createEditTool, SessionManager } = await import(pathToFileURL(`${packagePath}/dist/index.js`).href); -const { readFile } = await import("node:fs/promises"); -const oldText = await readFile(path, "utf8"); -const args = { path, edits: [{ oldText, newText: replacement }] }; -const session = SessionManager.open(sessionPath); -session.appendMessage({ role: "user", content: "Execute one isolated verdict-check edit.", timestamp: Date.now() }); -session.appendMessage({ - role: "assistant", content: [{ type: "toolCall", id: callId, name: "edit", arguments: args }], - api: "controlled-verification", provider: "controlled-verification", model: "local-native-edit", - usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, - cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, - stopReason: "toolUse", timestamp: Date.now(), -}); -const result = await createEditTool(process.cwd()).execute(callId, args); -if ((await readFile(path, "utf8")) !== replacement) throw new Error("Native edit did not apply its request"); -session.appendMessage({ role: "toolResult", toolCallId: callId, toolName: "edit", - content: result.content, details: result.details, isError: false, timestamp: Date.now() }); -console.log(JSON.stringify({ callId, changed: (await readFile(path, "utf8")) === replacement })); diff --git a/src/agent_comms/commander_parity/verdicts.py b/src/agent_comms/commander_parity/verdicts.py index 43fd259ba5..06b8140e0a 100644 --- a/src/agent_comms/commander_parity/verdicts.py +++ b/src/agent_comms/commander_parity/verdicts.py @@ -22,25 +22,59 @@ from ..tools import CommsVerdictTool, TodoChanged from ..turn_context import GoalSegment from . import ParityComparison -from .lifecycle import LifecycleRun +from .lifecycle import LifecycleObservation, LifecycleRun + +# Comparison-side controlled input, like load.OBSERVE_CAPACITY, not a new native +# runtime bootstrap/resource. The unchanged pinned SDK owns execution and storage. +NATIVE_EDIT = """ +import { pathToFileURL } from 'node:url'; +import { readFile } from 'node:fs/promises'; +const [packagePath, sessionPath, path, callId, replacement] = process.argv.slice(1); +const sdk = pathToFileURL(`${packagePath}/dist/index.js`).href; +const { createEditTool, SessionManager } = await import(sdk); +const args = {path, edits: [{oldText: await readFile(path, 'utf8'), newText: replacement}]}; +const session = SessionManager.open(sessionPath); +session.appendMessage({role: 'user', content: 'Execute one isolated verdict-check edit.', + timestamp: Date.now()}); +session.appendMessage({ + role: 'assistant', content: [{type: 'toolCall', id: callId, name: 'edit', arguments: args}], + api: 'controlled-verification', provider: 'controlled-verification', model: 'local-native-edit', + usage: {input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, + cost: {input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0}}, + stopReason: 'toolUse', timestamp: Date.now(), +}); +const result = await createEditTool(process.cwd()).execute(callId, args); +if ((await readFile(path, 'utf8')) !== replacement) { + throw new Error('Native edit did not apply its request'); +} +session.appendMessage({role: 'toolResult', toolCallId: callId, toolName: 'edit', + content: result.content, details: result.details, isError: false, timestamp: Date.now()}); +""" @dataclass(frozen=True) -class VerdictEffect: +class VerdictMutation: call_id: str verdicts: int todo_revisions: int strikes: int goal_revisions: int goal_transitions: int - goal_retained: bool - goal_state_retained: bool progress: str - native_calls: int - native_result_retained: bool - strike_matches_verdict_event: bool - declared_verdict_recorded: bool - goal_transition_retained: bool + + def checks(self, changes: int) -> tuple[tuple[str, bool], ...]: + return ( + ("one verdict", self.verdicts == 1), + ("one Todo revision", self.todo_revisions == 1), + ("strike delta", self.strikes == changes), + ("Goal revision delta", self.goal_revisions == changes), + ("committed Goal transition delta", self.goal_transitions == changes), + ) + + +@dataclass(frozen=True) +class VerdictObservation(LifecycleObservation): + mutation: VerdictMutation class VerdictCase(ABC): @@ -56,8 +90,8 @@ def replacement(cls, run: LifecycleRun) -> str: ... def command(cls, run: LifecycleRun, todo: Todo, edit: Edit) -> VerdictVerb: ... @staticmethod - def judge(run: LifecycleRun, command: VerdictVerb, todo: Todo, edit: Edit) -> object: - return command.apply(run.commander) + def judge(run: LifecycleRun, command: VerdictVerb, todo: Todo, edit: Edit) -> None: + command.apply(run.commander) @staticmethod def native(run: LifecycleRun, command: VerdictVerb, todo: Todo, edit: Edit) -> object: @@ -70,10 +104,9 @@ def native(run: LifecycleRun, command: VerdictVerb, todo: Todo, edit: Edit) -> o @classmethod def capture( cls, call_id: str, invoke: Callable[[LifecycleRun, VerdictVerb, Todo, Edit], object] - ) -> VerdictEffect: + ) -> VerdictObservation: with LifecycleRun.open() as run, contextlib.redirect_stdout(io.StringIO()): - # Satisfy the actual current command's gate in this copy; never bypass it - # or transfer the original commander's review authority into a new root. + # Satisfy the actual gate in this copy, without transferring original authority. ReviewVerb().apply(run.commander) with RuleReviews(run.commander.root).snapshot() as db: drawn = DrawnRule.select(db, reviewer=run.commander.commander, order_by=("n",)) @@ -91,16 +124,21 @@ def capture( worker = run.commander.comms.registry.require(run.worker) goal = worker.goal.require() history = len(run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)) - for path in (Path(worker.session_file), run.decisions, Path(worker.worktree)): + session_file = worker.session_file + if not session_file: + raise ValueError("The copied unit must have its own recorded native session") + for path in (Path(session_file), run.decisions, Path(worker.worktree)): path.resolve().relative_to(run.commander.root.resolve()) package = resolve_comms_route().launch().require_private().validate() subprocess.run( ( "node", "--no-global-search-paths", - str(Path(__file__).with_name("verdict_edit.mjs")), + "--input-type=module", + "-e", + NATIVE_EDIT, str(package.path), - worker.session_file, + session_file, str(run.decisions), call_id, cls.replacement(run), @@ -131,40 +169,44 @@ def capture( transitions = run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)[ history: ] - return VerdictEffect( + progress = GoalSegment.capture(worker, after, run.commander.comms.goals).progress + mutation = VerdictMutation( request.operation.tool_call_id, len(saved.verdicts) - len(before.verdicts), saved.revision - before.revision, saved.strike_count - before.strike_count, after.revision - goal.revision, len(transitions), - after.id == goal.id, - after.state == goal.state, - GoalSegment.capture(worker, after, run.commander.comms.goals).progress, - len(native), - result == TodoChanged(saved, saved.strike_count) - and request.operation in saved.verdicts, - all( - strike.at == request.operation.at - and strike.previous == request.operation.previous - for strike in saved.strikes[len(before.strikes) :] + progress, + ) + checks = ( + *mutation.checks(cls.changes), + ("same Goal identity", after.id == goal.id), + ("same Goal state", after.state == goal.state), + ("native result retained", result == TodoChanged(saved, saved.strike_count)), + ("native verdict retained", request.operation in saved.verdicts), + ( + "strike is the verdict event", + all( + strike.at == request.operation.at + and strike.previous == request.operation.previous + for strike in saved.strikes[len(before.strikes) :] + ), ), - isinstance(request.operation, cls.native_owner), - all(entry.before == goal and entry.after == after for entry in transitions), + ("declared verdict kind", isinstance(request.operation, cls.native_owner)), + ( + "Goal publication retained", + all(entry.before == goal and entry.after == after for entry in transitions), + ), + ("native verdict visible in Goal", request.operation.line in progress), + ) + return VerdictObservation( + f"{cls.native_owner.__module__}.{cls.native_owner.__qualname__}", + len(native), + checks, + "", + mutation, ) - - @classmethod - def valid(cls, effect: VerdictEffect) -> bool: - return ( - effect.verdicts == effect.todo_revisions == effect.native_calls == 1 - and effect.strikes == effect.goal_revisions == effect.goal_transitions == cls.changes - and effect.goal_retained - and effect.goal_state_retained - and effect.native_result_retained - and effect.strike_matches_verdict_event - and effect.declared_verdict_recorded - and effect.goal_transition_retained - ) class AcceptedCase(VerdictCase): @@ -190,10 +232,6 @@ class SendBackCase(VerdictCase): native_owner = SendBackVerdict why: ClassVar[str] = "The edit duplicates the copied workflow decision instead of removing it." - @classmethod - def valid(cls, effect: VerdictEffect) -> bool: - return super().valid(effect) and cls.why in effect.progress - @classmethod def replacement(cls, run: LifecycleRun) -> str: return json.dumps([run.worker, run.worker]) @@ -220,25 +258,32 @@ def command(cls, run: LifecycleRun, todo: Todo, edit: Edit) -> BackVerb: @dataclass(frozen=True) class VerdictComparison(ParityComparison): - accepted_current: VerdictEffect - accepted_native: VerdictEffect - back_current: VerdictEffect - back_native: VerdictEffect + accepted_current: VerdictObservation + accepted_native: VerdictObservation + back_current: VerdictObservation + back_native: VerdictObservation @property def passed(self) -> bool: + observations = ( + self.accepted_current, + self.accepted_native, + self.back_current, + self.back_native, + ) return ( - self.accepted_current == self.accepted_native - and self.back_current == self.back_native - and AcceptedCase.valid(self.accepted_native) - and SendBackCase.valid(self.back_native) + all(observation.passed for observation in observations) + and self.accepted_current.mutation == self.accepted_native.mutation + and self.back_current.mutation == self.back_native.mutation ) def describe(self) -> str: return ( - f"accepted current/native equal={self.accepted_current == self.accepted_native}; " - f"send-back current/native equal={self.back_current == self.back_native}; " - f"accepted={self.accepted_native!r}; send-back={self.back_native!r}" + "accepted current/native equal=" + f"{self.accepted_current.mutation == self.accepted_native.mutation}; " + "send-back current/native equal=" + f"{self.back_current.mutation == self.back_native.mutation}; " + f"accepted={self.accepted_native.describe()}; send-back={self.back_native.describe()}" ) @classmethod diff --git a/tests/test_commander_parity_verdicts.py b/tests/test_commander_parity_verdicts.py index 75676f9cf5..38385b033f 100644 --- a/tests/test_commander_parity_verdicts.py +++ b/tests/test_commander_parity_verdicts.py @@ -1,55 +1,43 @@ -"""Comparison invariants; the configured LifecycleRun journey supplies native proof.""" +"""Observation invariants; the configured LifecycleRun journey supplies native proof.""" from dataclasses import replace from agent_comms.commander_parity.rows import VerdictParityRow from agent_comms.commander_parity.verdicts import ( - AcceptedCase, - SendBackCase, VerdictComparison, - VerdictEffect, + VerdictMutation, + VerdictObservation, ) -def test_verdict_family_requires_the_actual_call_event_goal_and_strike_together(): - accepted = VerdictEffect( - call_id="one-call", - verdicts=1, - todo_revisions=1, - strikes=0, - goal_revisions=0, - goal_transitions=0, - goal_retained=True, - goal_state_retained=True, - progress="P1: Open", - native_calls=1, - native_result_retained=True, - strike_matches_verdict_event=True, - declared_verdict_recorded=True, - goal_transition_retained=True, - ) +def observation(mutation: VerdictMutation, changes: int) -> VerdictObservation: + return VerdictObservation("native verdict owner", 1, mutation.checks(changes), "", mutation) + + +def test_verdict_requires_the_actual_call_event_goal_and_strike_together(): + accepted = VerdictMutation("one-call", 1, 1, 0, 0, 0, "P1: Open · Accepted") back = replace( - accepted, strikes=1, goal_revisions=1, goal_transitions=1, progress=SendBackCase.why + accepted, strikes=1, goal_revisions=1, goal_transitions=1, progress="P1: Open · Sent back" ) - compared = VerdictComparison(accepted, accepted, back, back) - assert compared.passed and AcceptedCase.valid(accepted) and SendBackCase.valid(back) + ok, sent_back = observation(accepted, 0), observation(back, 1) + compared = VerdictComparison(ok, ok, sent_back, sent_back) + assert compared.passed for changed in ( replace(back, verdicts=0), replace(back, todo_revisions=2), replace(back, strikes=0), replace(back, goal_revisions=0), replace(back, goal_transitions=2), - replace(back, native_calls=0), - replace(back, goal_retained=False), - replace(back, goal_state_retained=False), - replace(back, native_result_retained=False), - replace(back, strike_matches_verdict_event=False), - replace(back, declared_verdict_recorded=False), - replace(back, goal_transition_retained=False), - replace(back, progress=""), ): - assert not SendBackCase.valid(changed) + observed = observation(changed, 1) + assert not observed.passed + assert not replace(compared, back_current=observed, back_native=observed).passed + for changed in ( + replace(sent_back, invocations=0), + replace(sent_back, checks=(*sent_back.checks, ("retained native identity", False))), + ): assert not replace(compared, back_current=changed, back_native=changed).passed - assert not replace(compared, accepted_native=replace(accepted, call_id="other-call")).passed + for changed in (replace(back, call_id="other-call"), replace(back, progress="")): + assert not replace(compared, back_native=observation(changed, 1)).passed assert "verify" not in VerdictParityRow.__dict__ assert VerdictParityRow.comparison == VerdictComparison.read From ebb756e9c4268ce7dd2f343490666130a8f8c0b8 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:09:58 -0400 Subject: [PATCH 34/36] Use the shared bounded producer for real native edit execution --- src/agent_comms/commander_parity/verdicts.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/agent_comms/commander_parity/verdicts.py b/src/agent_comms/commander_parity/verdicts.py index 06b8140e0a..3810a3eaea 100644 --- a/src/agent_comms/commander_parity/verdicts.py +++ b/src/agent_comms/commander_parity/verdicts.py @@ -6,7 +6,6 @@ import io import json import os -import subprocess from abc import ABC, abstractmethod from collections.abc import Callable from dataclasses import dataclass @@ -130,7 +129,7 @@ def capture( for path in (Path(session_file), run.decisions, Path(worker.worktree)): path.resolve().relative_to(run.commander.root.resolve()) package = resolve_comms_route().launch().require_private().validate() - subprocess.run( + child = run.invoke_command( ( "node", "--no-global-search-paths", @@ -145,11 +144,11 @@ def capture( ), cwd=worker.worktree, env=package.node_environment(dict(os.environ)), - capture_output=True, - text=True, - timeout=30, - check=True, ) + if not child.outcome.successful: + raise RuntimeError( + f"Native edit {child.outcome.summary}: {child.stderr.decode('utf-8')}" + ) edits = Edit.unjudged(run.commander.comms, run.commander.commander) if len(edits) != 1 or edits[0].id != call_id: raise ValueError("The copied unit must expose exactly its one real native edit") @@ -196,7 +195,10 @@ def capture( ("declared verdict kind", isinstance(request.operation, cls.native_owner)), ( "Goal publication retained", - all(entry.before == goal and entry.after == after for entry in transitions), + all( + entry.kind == "transition" and entry.before == goal and entry.after == after + for entry in transitions + ), ), ("native verdict visible in Goal", request.operation.line in progress), ) From 1c32b37ade5854779f8756380e6838aa3418c298 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 00:26:46 -0400 Subject: [PATCH 35/36] Keep verdict proof on committed Goal history and correct its owner declaration --- plans/commander-native-plan.md | 2 +- src/agent_comms/commander_parity/rows.py | 2 +- src/agent_comms/commander_parity/verdicts.py | 14 ++++++-------- tests/test_commander_parity_verdicts.py | 8 ++++++-- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/plans/commander-native-plan.md b/plans/commander-native-plan.md index 4fbae94e3a..d1c870e1d3 100644 --- a/plans/commander-native-plan.md +++ b/plans/commander-native-plan.md @@ -38,7 +38,7 @@ | 5 | Board, overdue, silent, spinning | `order.py board`, `overdue`; `fleet-board.md` | `CommsTodoListTool` and the fleet tool, derived | `one_order_owner` | | 6 | Branch hygiene | `branches-*.txt` by hand | `CommsWorkBranchesTool` | `one_order_owner` | | 7 | Strikes and the strike limit | `order.py strike`; `strikes.jsonl` | `Strike` rows, author-declared `StrikeLimit`, one `comms_fire` | `record_plane` | -| 8 | Verdicts on a unit's tool calls | `judge.py ok`, `back`; `verdicts.jsonl` | Order `Verdict`; send-back revises the Goal and records its strike atomically | `record_plane` | +| 8 | Verdicts on a unit's tool calls | `judge.py ok`, `back`; both invoke `CommsVerdictTool` | Order `Verdict`; send-back revises the Goal and records its strike atomically | `record_plane` | | 9 | Plain words in verdicts and strikes | judge and order checks | `PlainText` | `record_plane` | | 10 | Refuse soft or vague orders | `order.py` | `OrderText` on every order action | `record_plane` | | 11 | What a unit did during its order | `tool_watch.py`; `edits.jsonl`; `judge.py show` | `comms_order_work`: both transcript families by `tool_call_id` | `review_queue` | diff --git a/src/agent_comms/commander_parity/rows.py b/src/agent_comms/commander_parity/rows.py index d01e09767e..1f1ca4d605 100644 --- a/src/agent_comms/commander_parity/rows.py +++ b/src/agent_comms/commander_parity/rows.py @@ -95,7 +95,7 @@ class StrikeLimitParityRow(ParityRow): class VerdictParityRow(ParityRow): number = 8 capability = "Verdicts on a unit's tool calls" - current = "`judge.py ok`, `back`; `verdicts.jsonl`" + current = "`judge.py ok`, `back`; both invoke `CommsVerdictTool`" native = "Order `Verdict`; send-back revises the Goal and records its strike atomically" phases = (RecordPlanePhase,) comparison = VerdictComparison.read diff --git a/src/agent_comms/commander_parity/verdicts.py b/src/agent_comms/commander_parity/verdicts.py index 3810a3eaea..e194d7fbf7 100644 --- a/src/agent_comms/commander_parity/verdicts.py +++ b/src/agent_comms/commander_parity/verdicts.py @@ -58,7 +58,7 @@ class VerdictMutation: todo_revisions: int strikes: int goal_revisions: int - goal_transitions: int + goal_history_entries: int progress: str def checks(self, changes: int) -> tuple[tuple[str, bool], ...]: @@ -67,7 +67,7 @@ def checks(self, changes: int) -> tuple[tuple[str, bool], ...]: ("one Todo revision", self.todo_revisions == 1), ("strike delta", self.strikes == changes), ("Goal revision delta", self.goal_revisions == changes), - ("committed Goal transition delta", self.goal_transitions == changes), + ("committed Goal history delta", self.goal_history_entries == changes), ) @@ -165,7 +165,8 @@ def capture( if len(native) != 1 or native[0][0].operation.tool_call_id != call_id: raise ValueError("The native verdict must judge this one original copied tool call") request, result = native[0] - transitions = run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)[ + # goal_history returns committed revisions; its internal tags stay there. + history_entries = run.commander.comms.goals.goal_history(run.worker, goal_id=goal.id)[ history: ] progress = GoalSegment.capture(worker, after, run.commander.comms.goals).progress @@ -175,7 +176,7 @@ def capture( saved.revision - before.revision, saved.strike_count - before.strike_count, after.revision - goal.revision, - len(transitions), + len(history_entries), progress, ) checks = ( @@ -195,10 +196,7 @@ def capture( ("declared verdict kind", isinstance(request.operation, cls.native_owner)), ( "Goal publication retained", - all( - entry.kind == "transition" and entry.before == goal and entry.after == after - for entry in transitions - ), + all(entry.before == goal and entry.after == after for entry in history_entries), ), ("native verdict visible in Goal", request.operation.line in progress), ) diff --git a/tests/test_commander_parity_verdicts.py b/tests/test_commander_parity_verdicts.py index 38385b033f..c5264b93cb 100644 --- a/tests/test_commander_parity_verdicts.py +++ b/tests/test_commander_parity_verdicts.py @@ -17,7 +17,11 @@ def observation(mutation: VerdictMutation, changes: int) -> VerdictObservation: def test_verdict_requires_the_actual_call_event_goal_and_strike_together(): accepted = VerdictMutation("one-call", 1, 1, 0, 0, 0, "P1: Open · Accepted") back = replace( - accepted, strikes=1, goal_revisions=1, goal_transitions=1, progress="P1: Open · Sent back" + accepted, + strikes=1, + goal_revisions=1, + goal_history_entries=1, + progress="P1: Open · Sent back", ) ok, sent_back = observation(accepted, 0), observation(back, 1) compared = VerdictComparison(ok, ok, sent_back, sent_back) @@ -27,7 +31,7 @@ def test_verdict_requires_the_actual_call_event_goal_and_strike_together(): replace(back, todo_revisions=2), replace(back, strikes=0), replace(back, goal_revisions=0), - replace(back, goal_transitions=2), + replace(back, goal_history_entries=2), ): observed = observation(changed, 1) assert not observed.passed From 8bf3e138880fdbb521d6c0504a9173cb1a9418f6 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Tue, 20 Oct 2026 01:12:36 -0400 Subject: [PATCH 36/36] Assert the failed-check strike in deletion parity without changing custody --- src/agent_comms/commander_parity/deletion.py | 34 +++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/agent_comms/commander_parity/deletion.py b/src/agent_comms/commander_parity/deletion.py index e1dd7a6d9d..d0a07f7471 100644 --- a/src/agent_comms/commander_parity/deletion.py +++ b/src/agent_comms/commander_parity/deletion.py @@ -25,6 +25,7 @@ CheckedCommitDelivery, CommitDelivery, DeliveredProblemOrder, + FailedCheckStrike, FamilyDeletion, MechanicalOrderRun, Todo, @@ -136,6 +137,10 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: output = io.StringIO() with contextlib.redirect_stdout(output): before = cls.send(run, document) + goal_threads = (run.commander.commander, run.worker) + before_goals = tuple( + run.commander.comms.registry.require(name).goal for name in goal_threads + ) partial = cls.commit( repository, family + "def decisions():\n return []\n", @@ -146,6 +151,22 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: ) after_refusal = run.commander.comms.goals.todos.get(before.id) remaining = count.recorded(partial, str(repository)) + after_refusal_goals = tuple( + run.commander.comms.registry.require(name).goal for name in goal_threads + ) + failed_check = False + strike_only = False + match after_refusal.strikes[len(before.strikes) :]: + case (FailedCheckStrike() as strike,): + failed_check = strike == FailedCheckStrike.make( + before, strike.at.recorded_at("The failed delivery"), strike.reason + ) and strike.reason.startswith( + f"reported done at {partial} but its order check failed: " + f"The order check is 1 away from {count.result}." + ) + strike_only = after_refusal == replace( + before, strikes=(*before.strikes, strike), revision=before.revision + 1 + ) complete = cls.commit( repository, "def decisions():\n return []\n", @@ -171,7 +192,18 @@ def exercise(cls, run: LifecycleRun) -> LifecycleObservation: bool(remaining) and count.result.distance(remaining[0]) == CountPrinted(1), ), ("nonzero delivery refused", refused.outcome == ExitedOutcome(1)), - ("refusal preserved pending order", before == after_refusal and after_refusal.pending), + ( + "refusal preserved pending order and assignment", + after_refusal.order == before.order + and after_refusal.assignment == before.assignment + and after_refusal.pending, + ), + ( + "refusal preserved order and thread goals", + after_refusal.goal == before.goal and after_refusal_goals == before_goals, + ), + ("partial delivery recorded its precise failed-check strike", failed_check), + ("refusal changed only the failed-check strike and revision", strike_only), ( "zero count checked on delivered commit", bool(zero) and count.result.distance(zero[0]) == CountPrinted(0),