From 6bd791642ce40cc5442f3574102be42c164560f3 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 28 Nov 2026 09:24:59 -0500 Subject: [PATCH] Apply 47-recipe 6-class NRA codemod batch (12 P40, 11 P44, 11 P54, 8 P33, 3 P49, 2 P36) --- src/agent_comms/agent_event_updates.py | 3 +- src/agent_comms/agent_events.py | 5 ++ .../cli_bridges/claude_protocol.py | 37 ++++++++++-- .../cli_bridges/claude_transcript.py | 3 +- src/agent_comms/cli_bridges/cli_arguments.py | 10 +++- src/agent_comms/cli_bridges/opencode_parts.py | 7 +++ .../cli_bridges/opencode_protocol.py | 6 +- src/agent_comms/cli_bridges/shared.py | 4 +- src/agent_comms/cli_verbs/cli_commands.py | 31 +++++++++- src/agent_comms/cli_verbs/target_fields.py | 10 +--- src/agent_comms/cli_verbs/thread_tags.py | 4 +- .../coordination/assignment_states.py | 7 ++- .../coordination/attempt_recovery.py | 6 +- src/agent_comms/coordination/contracts.py | 36 +++++++++-- .../coordination/execution_store.py | 8 +-- .../coordination/tables/assignments.py | 3 +- src/agent_comms/execution/acp_failure.py | 2 +- src/agent_comms/execution/antigravity_acp.py | 3 - .../execution/antigravity_backend.py | 10 ++-- src/agent_comms/execution/child_process.py | 4 ++ src/agent_comms/execution/cursor_owner.py | 40 +++++++++++-- src/agent_comms/execution/diagnostics.py | 51 ++++++++++++---- src/agent_comms/execution/extension_ui.py | 4 +- src/agent_comms/execution/helper_workers.py | 34 +++++++++-- src/agent_comms/execution/input_drain.py | 11 +++- src/agent_comms/execution/native_arguments.py | 3 +- src/agent_comms/execution/native_child.py | 20 ++----- .../execution/native_input_record.py | 10 ++++ src/agent_comms/execution/native_pi.py | 31 +++++++++- .../execution/native_transcript.py | 2 +- src/agent_comms/execution/pi_commands.py | 12 ++-- src/agent_comms/execution/pi_wire.py | 44 +++++++++++--- .../execution/private_nk_entrypoint.py | 6 +- .../execution/proven_source_coverage.py | 22 +++---- src/agent_comms/execution/queued_input.py | 40 ++++++++++--- src/agent_comms/execution/turn_digests.py | 4 +- .../execution/turn_goal_account.py | 2 +- src/agent_comms/execution/turn_output.py | 4 +- src/agent_comms/execution/turn_phase.py | 9 +-- src/agent_comms/execution/turn_watchdog.py | 4 +- src/agent_comms/input_attempt.py | 7 +++ src/agent_comms/input_disposition.py | 3 +- src/agent_comms/messaging/read_basis.py | 2 +- src/agent_comms/nominal/field_codec.py | 34 ++++++++--- src/agent_comms/pi_native_backend.py | 25 +++----- src/agent_comms/planning/orders.py | 17 +++++- src/agent_comms/projects/git_history.py | 25 ++++---- src/agent_comms/projects/storage_rules.py | 11 +++- src/agent_comms/projects/work_branches.py | 7 +-- .../registry/heartbeat_delivery.py | 9 +++ src/agent_comms/registry/registry_document.py | 4 +- .../registry/relationship_store.py | 9 ++- src/agent_comms/registry/thread_identity.py | 9 +++ .../registry/thread_presentation.py | 7 +++ src/agent_comms/registry/thread_status.py | 7 +++ src/agent_comms/registry/threads.py | 41 ++++++++++--- src/agent_comms/storage/locked_store.py | 26 ++++---- src/agent_comms/storage/store_files.py | 4 ++ src/agent_comms/storage/typed_table.py | 8 +++ .../task_attachments/team_pings.py | 3 +- src/agent_comms/team/team_heartbeat.py | 3 +- src/agent_comms/team/team_hud.py | 59 ++++++++++++++----- .../transport/native_tool_transport.py | 4 +- src/agent_comms/ui_model/sidebar.py | 2 +- tests/test_agent_backend.py | 11 +++- tests/test_board_freshness.py | 3 +- tests/test_mcp_relay.py | 22 +++++-- tests/test_registration_inheritance.py | 8 +-- tests/test_team_notifications.py | 3 +- 69 files changed, 655 insertions(+), 270 deletions(-) diff --git a/src/agent_comms/agent_event_updates.py b/src/agent_comms/agent_event_updates.py index 9a82ca039a..0df89928c8 100644 --- a/src/agent_comms/agent_event_updates.py +++ b/src/agent_comms/agent_event_updates.py @@ -123,8 +123,7 @@ async def on_tool_start(self, event: events.ToolStart) -> None: kind=AcpToolAction.kind(event.kind), status="in_progress", ) - if event.args is not None: - start_update.raw_input = event.args + event.apply_raw_input(start_update) await client.publish_update( session_id=session_id, update=start_update, diff --git a/src/agent_comms/agent_events.py b/src/agent_comms/agent_events.py index d1cd61fa6c..561ec102a5 100644 --- a/src/agent_comms/agent_events.py +++ b/src/agent_comms/agent_events.py @@ -156,6 +156,11 @@ def from_call(cls, call_id: ToolCallId, name: str, arguments: object) -> ToolSta title = ToolDeclaration.caption(name, ToolDeclaration.record(name, arguments, call_id=call_id)) return cls(call_id, name, title, arguments, declaration.declared_action()) + def apply_raw_input(self, start_update) -> None: + """Attach raw input args to the tool-call start update when present.""" + if self.args is not None: + start_update.raw_input = self.args + @dataclass(frozen=True) class ToolProgress(ToolEvent): diff --git a/src/agent_comms/cli_bridges/claude_protocol.py b/src/agent_comms/cli_bridges/claude_protocol.py index 58168c03da..8ef2324ced 100644 --- a/src/agent_comms/cli_bridges/claude_protocol.py +++ b/src/agent_comms/cli_bridges/claude_protocol.py @@ -524,6 +524,36 @@ def untracked_tool_result(self, tool_id: str) -> tuple[RuntimeUpdate, ...]: return (ActiveItem(self.id, NativeItemId(tool_id), ModelWaitPhase()),) +class ReportedVersion(ABC): + """An optional Claude protocol version reported by the peer.""" + + @abstractmethod + def version_reported(self, owner: ClaudeSession) -> tuple[RuntimeUpdate, ...]: + ... + + @classmethod + def from_optional(cls, value: str | None) -> ReportedVersion: + return AbsentReportedVersion() if value is None else HeldReportedVersion(value) + + +@dataclass(frozen=True) +class AbsentReportedVersion(ReportedVersion): + """Absent `ReportedVersion` carrying no value.""" + + def version_reported(self, owner: ClaudeSession) -> tuple[RuntimeUpdate, ...]: + return () + + +@dataclass(frozen=True) +class HeldReportedVersion(ReportedVersion): + """Held `ReportedVersion` carrying its present value.""" + + value: str + + def version_reported(self, owner: ClaudeSession) -> tuple[RuntimeUpdate, ...]: + return tuple((update for offered in owner.offered_tools.on_version(self.value) for update in owner.offered(offered))) + + @dataclass class ClaudeSession: turn: ClaudeTurn = field(default_factory=UnknownTurn) @@ -533,11 +563,8 @@ class ClaudeSession: offered_tools: OfferedTools = field(default_factory=UnobservedTools) answered_by: TranscriptModelUsage = field(default_factory=TranscriptModelUsage) - def version_reported(self, version: str | None) -> tuple[RuntimeUpdate, ...]: - if version is None: - return () - return tuple(update for offered in self.offered_tools.on_version(version) - for update in self.offered(offered)) + def version_reported(self, version: ReportedVersion) -> tuple[RuntimeUpdate, ...]: + return version.version_reported(self) def offered(self, offered: OfferedTools) -> tuple[RuntimeUpdate, ...]: self.offered_tools = offered diff --git a/src/agent_comms/cli_bridges/claude_transcript.py b/src/agent_comms/cli_bridges/claude_transcript.py index 3cc9352da5..2eaf64ac84 100644 --- a/src/agent_comms/cli_bridges/claude_transcript.py +++ b/src/agent_comms/cli_bridges/claude_transcript.py @@ -14,6 +14,7 @@ ClaudeMonitorFrame, ClaudeRecord, ClaudeSession, + ReportedVersion, SubagentProgress, ) from agent_comms.cli_bridges.cli_protocol import TaggedWire @@ -78,7 +79,7 @@ def record_updates(self, record: ClaudeRecord, state: ClaudeSession, offset: int raw: bytes) -> Iterator[RuntimeUpdate]: if (located := state.located(record.cwd)) is not None: yield located - for update in (*state.version_reported(record.version), *record.updates(state)): + for update in (*state.version_reported(ReportedVersion.from_optional(record.version)), *record.updates(state)): yield from update.during(state.phase) diff --git a/src/agent_comms/cli_bridges/cli_arguments.py b/src/agent_comms/cli_bridges/cli_arguments.py index bd837da158..cfcb42e5d6 100644 --- a/src/agent_comms/cli_bridges/cli_arguments.py +++ b/src/agent_comms/cli_bridges/cli_arguments.py @@ -38,6 +38,12 @@ def declarations(self) -> tuple[type[CliCommand], ...]: class _CommandParsingArguments(argparse.Namespace): command: str | None + def resolve_parsing(self) -> CommandParsing: + """Resolve parsed arguments into a selected command or empty parsing.""" + if self.command is None: + return CommandParsing() + return SelectedCommand.from_name(self.command) + class CliArguments(argparse.Namespace): root: LaunchRequest @@ -96,9 +102,7 @@ def command_parsing(self, arguments: Sequence[str]) -> CommandParsing: # cause, five clauses into the line. selection.add_argument("command", nargs="?", default=None, help=argparse.SUPPRESS) args, _ = selection.parse_known_args(arguments, namespace=_CommandParsingArguments()) - if args.command is None: - return CommandParsing() - return SelectedCommand.from_name(args.command) + return args.resolve_parsing() def exit(self, status: int = 0, message: object = None) -> Never: raise CliParserExit(status, NoCliParserText()) diff --git a/src/agent_comms/cli_bridges/opencode_parts.py b/src/agent_comms/cli_bridges/opencode_parts.py index df4837f451..d4c0514e1c 100644 --- a/src/agent_comms/cli_bridges/opencode_parts.py +++ b/src/agent_comms/cli_bridges/opencode_parts.py @@ -45,6 +45,13 @@ class MessageTime(WireModel): created: int | float completed: int | float | None = None + async def snapshot_when_completed(self, info, stream) -> tuple[RuntimeUpdate, ...]: + """Fetch and snapshot the OpenCode message once this timestamp records completion.""" + if self.completed is None: + return () + saved = await stream.connection.message(info.id) + return stream.snapshot(saved) + class RoleHeader(WireHeader): @model_validator(mode='before') diff --git a/src/agent_comms/cli_bridges/opencode_protocol.py b/src/agent_comms/cli_bridges/opencode_protocol.py index 2bfb83ebe4..7ed59342c0 100644 --- a/src/agent_comms/cli_bridges/opencode_protocol.py +++ b/src/agent_comms/cli_bridges/opencode_protocol.py @@ -196,11 +196,7 @@ async def receive(self, stream: OpenCodeStream) -> tuple[RuntimeUpdate, ...]: if info.sessionID != stream.connection.session: return () stream.messages[info.id] = info - if info.time.completed is None: - return () - # Completion also covers an item that began before we subscribed. - saved = await stream.connection.message(info.id) - return stream.snapshot(saved) + return await info.time.snapshot_when_completed(info, stream) class StatusChanged(OpenCodeEvent, declared_name='session.status'): diff --git a/src/agent_comms/cli_bridges/shared.py b/src/agent_comms/cli_bridges/shared.py index 86cc1e94d5..d64619b84e 100644 --- a/src/agent_comms/cli_bridges/shared.py +++ b/src/agent_comms/cli_bridges/shared.py @@ -1182,9 +1182,9 @@ def routed(cls, reply_route: str) -> type[Self]: @property def route(self) -> str: """The reply line, under a message whose sender hears each reply (a person).""" - if not self.reply_route or not self.message.sender_role.hears_each_reply(): + if not self.reply_route: return '' - return '\n' + self.reply_route.format(target=self.message.exact_reply_target) + return self.message.sender_role.format_reply_route(self) OWED_PREFIX: ClassVar[str] = 'Comms owed · ' """How a reminder starts: no header (`HEADER_PREFIX`), so a transcript reads it as text diff --git a/src/agent_comms/cli_verbs/cli_commands.py b/src/agent_comms/cli_verbs/cli_commands.py index be6ab69709..6355004fa4 100644 --- a/src/agent_comms/cli_verbs/cli_commands.py +++ b/src/agent_comms/cli_verbs/cli_commands.py @@ -5,6 +5,7 @@ import argparse import re import shlex +from abc import ABC from dataclasses import dataclass from typing import Annotated @@ -42,8 +43,34 @@ def _tag_choice_text(value: str | None) -> str | None: return value -def _tag_text(value: frozenset[str] | None) -> str | None: - return None if value is None else ', '.join(sorted(value)) +class TagSet(ABC): + """An optional set of thread tags formatted for CLI output.""" + + def _tag_text(self) -> str | None: + pass + + @classmethod + def from_optional(cls, value: frozenset[str] | None) -> TagSet: + return AbsentTagSet() if value is None else HeldTagSet(value) + + +@dataclass(frozen=True) +class AbsentTagSet(TagSet): + """Absent `TagSet` carrying no value.""" + + +@dataclass(frozen=True) +class HeldTagSet(TagSet): + """Held `TagSet` carrying its present value.""" + + value: frozenset[str] + + def _tag_text(self) -> str | None: + return ', '.join(sorted(self.value)) + + +def _tag_text(value: TagSet) -> str | None: + return value._tag_text() def _shell_words(value: str) -> list[str]: diff --git a/src/agent_comms/cli_verbs/target_fields.py b/src/agent_comms/cli_verbs/target_fields.py index 10ebd8ba5f..6a5745d0c8 100644 --- a/src/agent_comms/cli_verbs/target_fields.py +++ b/src/agent_comms/cli_verbs/target_fields.py @@ -28,10 +28,6 @@ def of(cls, plan: field_codec.FieldPlan, value: object) -> TargetField: ) return editor(plan, value) - @property - def annotation(self) -> object: - return self.plan.annotation - @property def name(self) -> str: return self.plan.key @@ -68,7 +64,7 @@ def with_offered(self, options: tuple[CatalogChoice, ...]) -> TargetField: return self def value_schema(self) -> dict[str, JsonValue]: - return FieldCodec.value_schema(self.annotation) + return FieldCodec.value_schema(self.plan.annotation) def json_schema(self) -> dict[str, JsonValue]: return {**self.value_schema(), 'multiline': self.multiline, @@ -104,7 +100,7 @@ def with_offered(self, options: tuple[CatalogChoice, ...]) -> ChoiceTargetField: async def prepare(self, catalogs: ConfigCatalogSource, selection: object) -> ChoiceTargetField: - decoder = field_codec.compile_decoder(self.annotation) + decoder = field_codec.compile_decoder(self.plan.annotation) options = (CatalogChoice( name=label, value=decoder.encode_editor(decoder.decode(value))) for label, value in decoder.editor_choices()) @@ -145,5 +141,5 @@ async def prepare(self, catalogs: ConfigCatalogSource, return replace(self, options=tuple(options)) def value_schema(self) -> dict[str, JsonValue]: - return {**FieldCodec.value_schema(self.annotation), + return {**FieldCodec.value_schema(self.plan.annotation), 'configuration': FieldCodec.encode(self.catalog)} diff --git a/src/agent_comms/cli_verbs/thread_tags.py b/src/agent_comms/cli_verbs/thread_tags.py index 54cb60b111..fbda717598 100644 --- a/src/agent_comms/cli_verbs/thread_tags.py +++ b/src/agent_comms/cli_verbs/thread_tags.py @@ -6,7 +6,7 @@ from agent_comms.cli_verbs.cli_verb import CliBus from agent_comms.cli_support.named import NamedCliCommand from agent_comms.cli_verbs.cli_command import TargetActionCommand -from agent_comms.cli_verbs.cli_commands import ThreadTagsResult, _tag_text, _tags +from agent_comms.cli_verbs.cli_commands import TagSet, ThreadTagsResult, _tag_text, _tags from agent_comms.messaging.channel_targets import SurroundingChannel from agent_comms.nominal.field_codec import Argument, EditorFormat, Normalize from agent_comms.registry.catalog_document import CatalogAccess @@ -22,7 +22,7 @@ class ThreadTagsCliCommand(NamedCliCommand, TargetActionCommand[ThreadTagsResult tags: Annotated[ frozenset[str], Normalize(_tags), - EditorFormat(_tag_text), + EditorFormat(lambda value: _tag_text(TagSet.from_optional(value))), Argument( flags=("--tags",), options={"help": "Complete tags, separated by commas"} ), diff --git a/src/agent_comms/coordination/assignment_states.py b/src/agent_comms/coordination/assignment_states.py index 0363221872..78d9284233 100644 --- a/src/agent_comms/coordination/assignment_states.py +++ b/src/agent_comms/coordination/assignment_states.py @@ -8,6 +8,7 @@ from agent_comms.coordination.errors import IdentityConflict, CoordinationError from agent_comms.coordination.vocabulary import CoordinatorVocabulary +from agent_comms.messaging.bus_publication import Delivered from agent_comms.messaging.frozen_recipient import FrozenRecipient from agent_comms.messaging.notification_progress import ( CompletedProgress, @@ -56,7 +57,6 @@ HistoricalNativeInput, ) from agent_comms.execution.native_input_record import TriageNativeExecution - from agent_comms.messaging.bus_publication import Delivered from agent_comms.messaging.message_notification import MessageNotification from agent_comms.notification_assignment import AssignmentActivity @@ -243,6 +243,11 @@ def preengagement(self, disposition: type[AssignmentState]) -> AssignmentState: raise IdentityConflict("preengagement cannot change frozen wake policy") return after + def require_unengaged_for(self) -> None: + """Reject an assignment whose recipient differs or that already holds an execution.""" + if self.execution_id is not None: + raise IdentityConflict('claim cannot engage this execution') + class PassiveAssignment(Terminal, AssignmentState): notification_state = PassiveProgress diff --git a/src/agent_comms/coordination/attempt_recovery.py b/src/agent_comms/coordination/attempt_recovery.py index 5d596a8997..fa4217c82a 100644 --- a/src/agent_comms/coordination/attempt_recovery.py +++ b/src/agent_comms/coordination/attempt_recovery.py @@ -451,11 +451,7 @@ def recover_released_triage( with VerifiedOwnerLoss.observe_owner_release(store, owner, boundary, releases) as loss: for source, stage in pending: current = NativeRuntimeInput.require(store.session._connection, input_id=source.input_id) - if current.reference.has_session_proof(): - continue - loss.require_input_loss(current) - with boundary.registry_cut.current(), store.session.writing() as db: - stage.fail_claims(store, db) + current.reference.recover_unproven(current, loss, store, stage, boundary) @classmethod def recover_released_native_attempt( diff --git a/src/agent_comms/coordination/contracts.py b/src/agent_comms/coordination/contracts.py index 19e7dccb9d..60c9372f08 100644 --- a/src/agent_comms/coordination/contracts.py +++ b/src/agent_comms/coordination/contracts.py @@ -2,6 +2,8 @@ from __future__ import annotations +from abc import ABC +from dataclasses import dataclass from typing import Final RESOLVER_VERSION: Final = "resolver-v1" @@ -32,11 +34,35 @@ def require_bounded(value: str, field: str, maximum: int) -> None: raise ValueError(f"{field} exceeds {maximum} characters") -def require_optional_nonempty(value: str | None, field: str, maximum: int) -> None: - if value is None: - return - require_nonempty(value, field) - require_bounded(value, field, maximum) +class OptionalBoundedText(ABC): + """An optional non-empty bounded text value validated at a coordination contract.""" + + def require_optional_nonempty(self, field: str, maximum: int) -> None: + pass + + @classmethod + def from_optional(cls, value: str | None) -> OptionalBoundedText: + return AbsentOptionalBoundedText() if value is None else HeldOptionalBoundedText(value) + + +@dataclass(frozen=True) +class AbsentOptionalBoundedText(OptionalBoundedText): + """Absent `OptionalBoundedText` carrying no value.""" + + +@dataclass(frozen=True) +class HeldOptionalBoundedText(OptionalBoundedText): + """Held `OptionalBoundedText` carrying its present value.""" + + value: str + + def require_optional_nonempty(self, field: str, maximum: int) -> None: + require_nonempty(self.value, field) + require_bounded(self.value, field, maximum) + + +def require_optional_nonempty(value: OptionalBoundedText, field: str, maximum: int) -> None: + value.require_optional_nonempty(field, maximum) def validate_execution_id(execution_id: str) -> None: diff --git a/src/agent_comms/coordination/execution_store.py b/src/agent_comms/coordination/execution_store.py index fb17354ad4..58f2ac8725 100644 --- a/src/agent_comms/coordination/execution_store.py +++ b/src/agent_comms/coordination/execution_store.py @@ -114,11 +114,9 @@ def _create( exact_target = source.delivery.message.exact_reply_target routes.setdefault(exact_target, None) assignment.lifecycle.require_engageable() - if ( - assignment.recipient_lookup != owner_lookup - or assignment.lifecycle.execution_id is not None - ): - raise IdentityConflict("claim cannot engage this execution") + if assignment.recipient_lookup != owner_lookup: + raise IdentityConflict('claim cannot engage this execution') + assignment.lifecycle.require_unengaged_for() decision = EngagedAssignment.build( assignment.lifecycle.mode, execution_id, exact_target ) diff --git a/src/agent_comms/coordination/tables/assignments.py b/src/agent_comms/coordination/tables/assignments.py index f6218aa085..dd084b0040 100644 --- a/src/agent_comms/coordination/tables/assignments.py +++ b/src/agent_comms/coordination/tables/assignments.py @@ -12,6 +12,7 @@ MAX_IDENTIFIER_CHARS, POLICY_VERSION, RESOLVER_VERSION, + OptionalBoundedText, require_bounded, require_nonempty, require_optional_nonempty, @@ -220,7 +221,7 @@ def __post_init__(self) -> None: ): require_nonempty(value, field) require_bounded(value, field, MAX_IDENTIFIER_CHARS) - require_optional_nonempty(self.lifecycle.exact_target, "exact_target", MAX_IDENTIFIER_CHARS) + require_optional_nonempty(OptionalBoundedText.from_optional(self.lifecycle.exact_target), "exact_target", MAX_IDENTIFIER_CHARS) if self.lifecycle.execution_id is not None: validate_execution_id(self.lifecycle.execution_id) if self.wire_seq <= 0 or self.revision <= 0: diff --git a/src/agent_comms/execution/acp_failure.py b/src/agent_comms/execution/acp_failure.py index 232b43bed3..4b09a527ca 100644 --- a/src/agent_comms/execution/acp_failure.py +++ b/src/agent_comms/execution/acp_failure.py @@ -19,6 +19,7 @@ from agent_comms.execution.session_updates import AgentCommsUpdate from agent_comms.execution.turn_failure import TurnFailure from agent_comms.input_attempt import InputAttempt +from agent_comms.input_disposition import InputDocument from agent_comms.messaging.delivery_presentation import DeliveryPresentation from agent_comms.nominal.declared_family import DeclaredFamily, UnknownFamilyMember from agent_comms.nominal.field_codec import ( @@ -38,7 +39,6 @@ from agent_comms.agent_events import Done, Error from agent_comms.execution.turn_input_source import OriginalTurnInput - from agent_comms.input_disposition import InputDocument class DeliveryFailure(DeliveryPresentation, DeclaredFamily, affix="Failure"): diff --git a/src/agent_comms/execution/antigravity_acp.py b/src/agent_comms/execution/antigravity_acp.py index 39d85a5f30..c0d435023e 100644 --- a/src/agent_comms/execution/antigravity_acp.py +++ b/src/agent_comms/execution/antigravity_acp.py @@ -674,9 +674,6 @@ def alive(self) -> bool: def process_identity(self) -> ProcessState: return self._state.identity - def require_process_identity(self) -> ProcessIdentity: - return self._state.require_identity() - async def ensure_started(self) -> None: async with self._start_lock: if self.alive and self._initialized: diff --git a/src/agent_comms/execution/antigravity_backend.py b/src/agent_comms/execution/antigravity_backend.py index f22ef3dd59..d6865a59fc 100644 --- a/src/agent_comms/execution/antigravity_backend.py +++ b/src/agent_comms/execution/antigravity_backend.py @@ -291,7 +291,7 @@ async def run_turn( thought_level=self._applied_thinking, ) last_phase: TurnPhase = state.phase - yield NativePhaseChanged(last_phase, self._process.require_process_identity()) + yield NativePhaseChanged(last_phase, self._process._state.require_identity()) live = await self._process.open_prompt(session_id, content.acp_prompt_blocks()) inbox_task: asyncio.Task[TurnInboxItem] = asyncio.create_task(delivery.inbox.get()) frames_task: asyncio.Task[tuple[AcpPromptFrame, ...]] = asyncio.create_task( @@ -324,7 +324,7 @@ async def run_turn( if quiet is not None: last_phase = quiet yield NativePhaseChanged( - last_phase, self._process.require_process_identity() + last_phase, self._process._state.require_identity() ) stall_budget = state.phase.silence_budget( model_wait=self.MODEL_STALL_SECONDS, @@ -356,7 +356,7 @@ async def run_turn( if state.phase != last_phase: last_phase = state.phase yield NativePhaseChanged( - last_phase, self._process.require_process_identity() + last_phase, self._process._state.require_identity() ) inbox_task = asyncio.create_task(delivery.inbox.get()) if frames_task in done: @@ -370,7 +370,7 @@ async def run_turn( if state.phase != last_phase: last_phase = state.phase yield NativePhaseChanged( - last_phase, self._process.require_process_identity() + last_phase, self._process._state.require_identity() ) frames_task = asyncio.create_task(live.next_frames()) except asyncio.CancelledError: @@ -384,7 +384,7 @@ async def run_turn( await pending_task live.close() yield NativePhaseChanged( - SettlingStatsPhase(), self._process.require_process_identity() + SettlingStatsPhase(), self._process._state.require_identity() ) yield events.StreamSettled() yield events.Done(text=state.full_text, ok=True) diff --git a/src/agent_comms/execution/child_process.py b/src/agent_comms/execution/child_process.py index c9d4301d1b..c91453890a 100644 --- a/src/agent_comms/execution/child_process.py +++ b/src/agent_comms/execution/child_process.py @@ -1271,6 +1271,10 @@ async def finish(self) -> ChildOutcome: except TimeoutError: return TimedOutOutcome(await self.stop()) + def exit_code_diagnostic(self): + """Return the exit-code diagnostic mapping when the child has exited.""" + return {'exit_code': self.returncode} if self.returncode is not None else {} + class HandedOffAttachedChild(AttachedChild): """The gate was reaped; resident completion has no parent exit status.""" diff --git a/src/agent_comms/execution/cursor_owner.py b/src/agent_comms/execution/cursor_owner.py index ac62b999a4..586bc03223 100644 --- a/src/agent_comms/execution/cursor_owner.py +++ b/src/agent_comms/execution/cursor_owner.py @@ -45,6 +45,36 @@ +class ObservedRuntimeInput(ABC): + """An optional stored native runtime input matched against a cursor owner.""" + + @abstractmethod + def _matches_input(self, reference: NativeInputReference, owner: CursorOwner) -> bool: + ... + + @classmethod + def from_optional(cls, value: NativeRuntimeInput | None) -> ObservedRuntimeInput: + return AbsentObservedRuntimeInput() if value is None else HeldObservedRuntimeInput(value) + + +@dataclass(frozen=True) +class AbsentObservedRuntimeInput(ObservedRuntimeInput): + """Absent `ObservedRuntimeInput` carrying no value.""" + + def _matches_input(self, reference: NativeInputReference, owner: CursorOwner) -> bool: + return False + + +@dataclass(frozen=True) +class HeldObservedRuntimeInput(ObservedRuntimeInput): + """Held `ObservedRuntimeInput` carrying its present value.""" + + value: NativeRuntimeInput + + def _matches_input(self, reference: NativeInputReference, owner: CursorOwner) -> bool: + return self.value.owner_identity.within(owner.participant_identity) and self.value.sent_owner_claimed_generation.sent_by_lineage(owner.claimed_generation) and (self.value.reference == reference) + + @dataclass(frozen=True) class CursorOwner(RegistryOwner): """Record this started input; deciding whether tools may run belongs to its turn.""" @@ -167,13 +197,11 @@ def state(self, db: sqlite3.Connection) -> CursorState: return InheritedCursor(row) return RecordedCursor(row) - def _matches_input(self, row: NativeRuntimeInput | None, reference: NativeInputReference) -> bool: - return (row is not None and row.owner_identity.within(self.participant_identity) - and row.sent_owner_claimed_generation.sent_by_lineage(self.claimed_generation) - and row.reference == reference) + def _matches_input(self, row: ObservedRuntimeInput, reference: NativeInputReference) -> bool: + return (row._matches_input(reference, self)) def matches_prefix(self, db: Connection, evidence: tuple[HistoricalNativeInput, ...]) -> bool: - return all(self._matches_input(NativeRuntimeInput.one(db, input_id=item.input_id), item.reference) + return all(self._matches_input(ObservedRuntimeInput.from_optional(NativeRuntimeInput.one(db, input_id=item.input_id)), item.reference) for item in evidence) def require_recorded_input(self, db: Connection, cursor: CurrentNativeCursor) -> None: @@ -192,7 +220,7 @@ def require_recorded_reference(self, db: Connection, reference: NativeInputRefer row = NativeRuntimeInput.one(db, input_id=reference.input_id) if row is None or not row.sent_owner_claimed_generation.sent_by_lineage(self.claimed_generation): raise IdentityConflict("current cursor input claim_scope differs") - if not self._matches_input(row, reference): + if not self._matches_input(HeldObservedRuntimeInput(row), reference): raise IdentityConflict("current cursor proof differs from journal") diff --git a/src/agent_comms/execution/diagnostics.py b/src/agent_comms/execution/diagnostics.py index 70ecc30922..85902e2b12 100644 --- a/src/agent_comms/execution/diagnostics.py +++ b/src/agent_comms/execution/diagnostics.py @@ -5,9 +5,10 @@ import hashlib import json import os +from abc import ABC, abstractmethod from collections.abc import Mapping from contextlib import contextmanager -from dataclasses import replace +from dataclasses import dataclass, replace from pathlib import Path from traceback import TracebackException from typing import TYPE_CHECKING @@ -25,12 +26,12 @@ TurnId, ) from agent_comms.registry.activity import DrainDiagnostic +from agent_comms.registry.threads import Thread from agent_comms.storage.locked_store import PatternFile, RuntimeFile from agent_comms.storage.store_files import AtomicFile if TYPE_CHECKING: from agent_comms.execution.pi_events import Response - from agent_comms.registry.threads import Thread class OwnerProcessOutput(RuntimeFile, PatternFile): @@ -92,7 +93,7 @@ def record_terminal_failure( } if native_response is not None: document["native_response"] = native_response.rejection_details() - document.update(DiagnosticDocument.source_error_evidence(source_error)) + document.update(DiagnosticDocument.source_error_evidence(DiagnosticSourceError.from_optional(source_error))) return DiagnosticDocument.write(root, subject, document) @@ -116,7 +117,7 @@ def record_drain_failure( replace(diagnostic, reason=str(source_error)), ArtifactExclude ), "outcome": "inbox observation failed; this record grants no retry authority", - **DiagnosticDocument.source_error_evidence(source_error), + **DiagnosticDocument.source_error_evidence(HeldDiagnosticSourceError(source_error)), } digest = hashlib.sha256(json.dumps(document, sort_keys=True).encode()).hexdigest() path = DiagnosticDocument.path_in(root, name=f"drain-{digest}") @@ -129,20 +130,46 @@ def record_drain_failure( return path.resolve() +class DiagnosticSourceError(ABC): + """An optional exception recorded as diagnostic evidence.""" + + @abstractmethod + def source_error_evidence(self, owner: type[DiagnosticDocument]) -> dict: + ... + + @classmethod + def from_optional(cls, value: BaseException | None) -> DiagnosticSourceError: + return AbsentDiagnosticSourceError() if value is None else HeldDiagnosticSourceError(value) + + +@dataclass(frozen=True) +class AbsentDiagnosticSourceError(DiagnosticSourceError): + """Absent `DiagnosticSourceError` carrying no value.""" + + def source_error_evidence(self, owner: type[DiagnosticDocument]) -> dict: + return {} + + +@dataclass(frozen=True) +class HeldDiagnosticSourceError(DiagnosticSourceError): + """Held `DiagnosticSourceError` carrying its present value.""" + + value: BaseException + + def source_error_evidence(self, owner: type[DiagnosticDocument]) -> dict: + document = {'source_error': ''.join(TracebackException.from_exception(self.value, capture_locals=False).format(chain=True))} + document.update(owner.handler_for(type(self.value))(self.value)) + return document + + class DiagnosticDocument(RuntimeFile, PatternFile, MroDispatch): """Publish diagnostic documents through their single declared location.""" filename = "diagnostics/{name}.json" @classmethod - def source_error_evidence(cls, source_error: BaseException | None) -> dict: - if source_error is None: - return {} - document = {"source_error": "".join( - TracebackException.from_exception(source_error, capture_locals=False).format(chain=True) - )} - document.update(cls.handler_for(type(source_error))(source_error)) - return document + def source_error_evidence(cls, source_error: DiagnosticSourceError) -> dict: + return source_error.source_error_evidence(cls) @handles(NativeRequestFailure) @staticmethod diff --git a/src/agent_comms/execution/extension_ui.py b/src/agent_comms/execution/extension_ui.py index 7deeeaa345..acad3c6edf 100644 --- a/src/agent_comms/execution/extension_ui.py +++ b/src/agent_comms/execution/extension_ui.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING from agent_comms.execution.pi_events import CancelledUiChoice, DialogUiRequest, ExtensionUiChoice -from agent_comms.execution.pi_wire import McpLiveAcknowledgement +from agent_comms.execution.pi_wire import LiveStatusClaim, McpLiveAcknowledgement from agent_comms.execution.turn_failure import ExtensionUiFailed if TYPE_CHECKING: @@ -25,7 +25,7 @@ def observe(self, text: str | None, session: TurnSession) -> McpLiveAcknowledgem # A acknowledgement is informational, never permission to call a tool or send. if self.acknowledgement is not None or not session.permits_live_status(): return None - self.acknowledgement = McpLiveAcknowledgement.from_status(text, session.command.input_id) + self.acknowledgement = McpLiveAcknowledgement.from_status(LiveStatusClaim.from_optional(text), session.command.input_id) return self.acknowledgement async def choose(self, request: DialogUiRequest, session: TurnSession) -> ExtensionUiChoice: diff --git a/src/agent_comms/execution/helper_workers.py b/src/agent_comms/execution/helper_workers.py index 317932d6bb..e908887003 100644 --- a/src/agent_comms/execution/helper_workers.py +++ b/src/agent_comms/execution/helper_workers.py @@ -27,6 +27,7 @@ from collections.abc import Callable from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor from contextlib import suppress +from dataclasses import dataclass from functools import partial from struct import Struct from typing import ClassVar, NoReturn @@ -227,6 +228,32 @@ def _left(self) -> None: time.sleep(0.0005) +class WorkerInitializer(ABC): + """An optional worker-process initializer invoked before serving calls.""" + + def initialize(self, initargs: tuple[object, ...]) -> None: + pass + + @classmethod + def from_optional(cls, value: Callable[..., object] | None) -> WorkerInitializer: + return AbsentWorkerInitializer() if value is None else HeldWorkerInitializer(value) + + +@dataclass(frozen=True) +class AbsentWorkerInitializer(WorkerInitializer): + """Absent `WorkerInitializer` carrying no value.""" + + +@dataclass(frozen=True) +class HeldWorkerInitializer(WorkerInitializer): + """Held `WorkerInitializer` carrying its present value.""" + + value: Callable[..., object] + + def initialize(self, initargs: tuple[object, ...]) -> None: + self.value(*initargs) + + class ForkedTemplate: """The application forked once, into a process with one thread that forks each worker. @@ -306,7 +333,7 @@ def _serve_forks(cls, control: socket.socket) -> None: if pid == 0: control.close() application_end.close() - _leave(partial(cls._work, worker_end, initializer, initargs)) + _leave(partial(cls._work, worker_end, WorkerInitializer.from_optional(initializer), initargs)) worker_end.close() try: socket.send_fds(control, [PID.pack(pid)], [application_end.fileno()]) @@ -316,10 +343,9 @@ def _serve_forks(cls, control: socket.socket) -> None: application_end.close() @staticmethod - def _work(stream: socket.socket, initializer: Callable[..., object] | None, + def _work(stream: socket.socket, initializer: WorkerInitializer, initargs: tuple[object, ...]) -> None: - if initializer is not None: - initializer(*initargs) + initializer.initialize(initargs) _serve_calls(stream) def worker(self, initializer: Callable[..., object] | None, diff --git a/src/agent_comms/execution/input_drain.py b/src/agent_comms/execution/input_drain.py index 0e2fca6c54..8c895ffe26 100644 --- a/src/agent_comms/execution/input_drain.py +++ b/src/agent_comms/execution/input_drain.py @@ -495,6 +495,10 @@ async def drain(self, inputs: InputDrain, session_id: AcpSessionId) -> None: """A tick's share of this debt.""" await inputs.drain_inbox(session_id) + def schedule_observation(self, state) -> None: + """Signal observation readiness when inbox changed or this debt asks again.""" + pass + class HeldInboxDebt(InboxDebt): """An inbox debt carrying the last observed private state.""" @@ -524,6 +528,9 @@ def witnessed(self, note: PrivateObservation) -> InboxDebt: def confirmed(self) -> InboxDebt: return InboxSettled(self.held) + def schedule_observation(self, state) -> None: + state.observation_ready.set() + @dataclass(frozen=True, slots=True) class InboxSettled(HeldInboxDebt): @@ -867,8 +874,10 @@ async def observe_root(self) -> None: if state.observing(): # Pending producers have their own completion wake; # only an explicit local request owes another tick. - if inbox_changed or state.inbox.asks_again: + if inbox_changed: state.observation_ready.set() + else: + state.inbox.schedule_observation(state) state.observation_watcher = watcher finally: self.root_observer = BackgroundTask() diff --git a/src/agent_comms/execution/native_arguments.py b/src/agent_comms/execution/native_arguments.py index f5d2d3f359..24777b0807 100644 --- a/src/agent_comms/execution/native_arguments.py +++ b/src/agent_comms/execution/native_arguments.py @@ -20,12 +20,12 @@ from agent_comms.execution.pi_vocabulary import NoThinkingOverride, ThinkingChoice, ThinkingLevel from agent_comms.nominal.declared_family import DeclaredFamily from agent_comms.nominal.field_codec import FieldCodec, NullMember, SingleFieldValue, SubclassUnion +from agent_comms.team.rule_deal import OffDealMode, UndealtRecord from agent_comms.transport.native_tool_mode import NativeToolMode if TYPE_CHECKING: from agent_comms.execution.owner_lifecycle import OwnerLifecycle from agent_comms.execution.channel_coding_tools import CodingToolOwner - from agent_comms.team.rule_deal import UndealtRecord from agent_comms.registry.thread_model import ThreadModel logger = logging.getLogger(__name__) @@ -332,7 +332,6 @@ def native_tool_mode(cls, mode: NativeToolMode, owner: CodingToolOwner) -> Nativ def undealt(cls, record: UndealtRecord) -> UndealtRecord: """No papers, rules or audit by default (Tristan, 2026-11-20): the deal is context the checkpoint never saw and its window cannot hold, and its audit is not its protocol.""" - from agent_comms.team.rule_deal import OffDealMode return replace(record, mode=OffDealMode) diff --git a/src/agent_comms/execution/native_child.py b/src/agent_comms/execution/native_child.py index 8f75507de6..bf5a9c199c 100644 --- a/src/agent_comms/execution/native_child.py +++ b/src/agent_comms/execution/native_child.py @@ -8,7 +8,7 @@ from contextlib import AbstractContextManager, AsyncExitStack, ExitStack, asynccontextmanager from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, NoReturn, Self +from typing import NoReturn, Self from agent_comms.execution.async_retirement import join_retirement from agent_comms.execution.child_process import AttachedChild, ChildOutcome @@ -16,7 +16,7 @@ from agent_comms.execution.launch_runtime import INHERITED_ENVIRONMENT from agent_comms.execution.native_attestation import NativeAttestation, PendingAttestation from agent_comms.execution.native_failures import NativePiUnavailable, NativeRequestFailure -from agent_comms.execution.native_pi import NativePiRpcLaunch +from agent_comms.execution.native_pi import NativePiRpcLaunch, RequestedSessionFile from agent_comms.execution.native_prompt_send import send_fenced_prompt from agent_comms.execution.native_session_reopen import NativeSessionIdentity from agent_comms.execution.native_turn_context import PublishedContext @@ -33,14 +33,10 @@ from agent_comms.installer.native_package import VerifiedNativePackage from agent_comms.nominal.declared_family import DeclaredFamily from agent_comms.pi_payloads import PiResponseData, StateData +from agent_comms.registry.threads import Thread from agent_comms.storage.private_path import PrivateSocketRole from agent_comms.team.deal_delivery import DealDelivery -if TYPE_CHECKING: - - from agent_comms.registry.threads import Thread - - class RetirementState(DeclaredFamily): """The shutdown result owns completion, failure and cancellation behavior.""" @@ -450,13 +446,7 @@ async def inspect_acquired(self, persistent: NativeSessionRetention[PiSessionChi async with persistent.lock: current = persistent.child_state.idle() data = await current.child.request(request) - if request.writes_session(): - # This child wrote the file itself; its loaded context is the new revision. - launch = current.child.key[0] - current.revision = SessionRevision.observe( - launch.session.files(launch.root) - ).require_available() - current.child.forget_context() + request.refresh_written_session(current) return data def reuse(self, key: tuple[NativePiRpcLaunch, tuple[tuple[int, int], ...]]) -> PiSessionChild | None: @@ -470,7 +460,7 @@ def managed_launch(self, command: str, arguments: tuple[str, ...], *, package: V original, authentication = self.child.key candidate = original.retained_managed(command, arguments, root=root, owner=owner, directory=directory, worktree=worktree, delivery=delivery, - environment=environment, session_file=session_file) + environment=environment, session_file=RequestedSessionFile.from_optional(session_file)) if candidate is not None and (candidate, candidate.configuration.auth_revision()) == ( original, authentication ): diff --git a/src/agent_comms/execution/native_input_record.py b/src/agent_comms/execution/native_input_record.py index 5b7c7fbd4e..ff2307cb66 100644 --- a/src/agent_comms/execution/native_input_record.py +++ b/src/agent_comms/execution/native_input_record.py @@ -14,6 +14,7 @@ from agent_comms.coordination.assignment_states import AssignmentState, TriagePendingAssignment from agent_comms.coordination.contracts import validate_execution_id from agent_comms.coordination.errors import IdentityConflict, UnrecordedNativeContext +from agent_comms.coordination.session import NativeCapture from agent_comms.coordination.tables.assignments import ExecutionAssignmentLink, WakeAssignment from agent_comms.coordination.tables.executions import ExecutionRecord from agent_comms.coordination.tables.participants import OwnerGenerations, OwnerRecord @@ -425,6 +426,12 @@ def acknowledge_context( """The first verified entry is immutable; later settlement does not own it.""" row.write_context(db, context) + def recover_unproven(self, current, loss, store, stage, boundary: NativeCapture) -> None: + """Fail triage claims only when this context reference lacks session proof.""" + loss.require_input_loss(current) + with boundary.registry_cut.current(), store.session.writing() as db: + stage.fail_claims(store, db) + @dataclass(frozen=True) class UnrecordedNativeInputReference(NativeContextReference): @@ -480,6 +487,9 @@ def acknowledge_context( def require_recorded_input(self, owner: CursorOwner, db: sqlite3.Connection) -> None: owner.require_recorded_reference(db, self) + def recover_unproven(self, current, loss, store, stage, boundary: NativeCapture) -> None: + pass + class NativeInputRecord(OwnerRecord, ABC): input_id: InputId diff --git a/src/agent_comms/execution/native_pi.py b/src/agent_comms/execution/native_pi.py index 0e31b48fbc..edd7eebd22 100644 --- a/src/agent_comms/execution/native_pi.py +++ b/src/agent_comms/execution/native_pi.py @@ -9,6 +9,7 @@ import os import shutil import sys +from abc import ABC from dataclasses import dataclass, field from pathlib import Path @@ -135,6 +136,32 @@ def require_publishable(self) -> None: context: NativeContextProof +class RequestedSessionFile(ABC): + """An optional requested session file path compared against a retained managed launch.""" + + def resolved_path(self): + pass + + @classmethod + def from_optional(cls, value: str | None) -> RequestedSessionFile: + return AbsentRequestedSessionFile() if value is None else HeldRequestedSessionFile(value) + + +@dataclass(frozen=True) +class AbsentRequestedSessionFile(RequestedSessionFile): + """Absent `RequestedSessionFile` carrying no value.""" + + +@dataclass(frozen=True) +class HeldRequestedSessionFile(RequestedSessionFile): + """Held `RequestedSessionFile` carrying its present value.""" + + value: str + + def resolved_path(self): + return Path(self.value).absolute() + + @dataclass(frozen=True, slots=True) class NativePiRpcLaunch: """Verified native Pi subprocess launch, not an authorization to send input.""" @@ -276,7 +303,7 @@ def _managed( def retained_managed( self, command: str, arguments: tuple[str, ...], *, worktree: Path, root: Path, directory: Path, owner: ParticipantIdentity, delivery: DealDelivery, - environment: dict[str, str] | None, session_file: str | None, + environment: dict[str, str] | None, session_file: RequestedSessionFile, ) -> NativePiRpcLaunch | None: """Derive a candidate from this acquired immutable launch, not a path cache. @@ -285,7 +312,7 @@ def retained_managed( A different package or selected file needs its own fresh acquisition. """ self._command_selection(command, self.runtime, self.package) - saved = Path(session_file).absolute() if session_file is not None else None + saved = session_file.resolved_path() if ((saved, directory) != (self.session.path, self.session.directory) or self.session.files(root).owner.lookup != owner.lookup): return None diff --git a/src/agent_comms/execution/native_transcript.py b/src/agent_comms/execution/native_transcript.py index e81cc39eb2..0fbf3327e7 100644 --- a/src/agent_comms/execution/native_transcript.py +++ b/src/agent_comms/execution/native_transcript.py @@ -55,6 +55,7 @@ ) from agent_comms.execution.turn_item import FreshNativeId, NativeItemId, NativeTurnId from agent_comms.nominal.field_codec import FieldCodec, InputId, MalformedRecord +from agent_comms.registry.registration import Registration from agent_comms.registry.thread_identity import RecordedThreadIncarnation from agent_comms.storage.file_observation import FileRevision from agent_comms.storage.locked_store import RegistryFile @@ -353,7 +354,6 @@ def open(cls, root: Path, input_id: InputId) -> Iterator[DraftPublication]: if original is None: yield cls() return - from agent_comms.registry.registration import Registration thread = Registration(RegistryFile.path_in(root)).require_lookup(original.owner_lookup) original.owner_identity.require_recorded_owner(thread) transcript = ExternalTranscript(root, thread.incarnation) diff --git a/src/agent_comms/execution/pi_commands.py b/src/agent_comms/execution/pi_commands.py index 9e156deb3c..9a057d66a7 100644 --- a/src/agent_comms/execution/pi_commands.py +++ b/src/agent_comms/execution/pi_commands.py @@ -23,6 +23,7 @@ from agent_comms.execution.native_failures import NativePiUnavailable from agent_comms.execution.native_input_proof import NativeContextProof, NativeInputCommit from agent_comms.execution.native_pi import NativePiRpcLaunch +from agent_comms.execution.session_revision import SessionRevision from agent_comms.registry.thread_settings import SettingRequest from agent_comms.execution.native_session_reopen import NativeSessionIdentity from agent_comms.execution.pi_wire import PiOmitted, PiRequestId, RequestId @@ -89,8 +90,9 @@ def invalidates_identity(cls, response: Response, session: TurnSession) -> bool: class PiCommand(DeclaredFamily): family_discriminator = "type" # Pi's RPC names the command in ``type`` response_payload: ClassVar[type[PiResponseData]] = EmptyData - def writes_session(self) -> bool: - return False + def refresh_written_session(self, current) -> None: + """Refresh the retained child revision and forget context when this command writes the session.""" + pass id: Annotated[PiRequestId, WireAbsentNone()] = field( default_factory=lambda: RequestId(PiRequestKey.fresh()) ) @@ -493,8 +495,10 @@ class Compact(NativeQuery): """Pi's own compaction engine, run now; Pi adds Core's task brief to the instructions.""" response_payload = CompactionData - def writes_session(self) -> bool: - return True + def refresh_written_session(self, current) -> None: + launch = current.child.key[0] + current.revision = SessionRevision.observe(launch.session.files(launch.root)).require_available() + current.child.forget_context() custom_instructions: Annotated[ str | PiOmitted, WireOmitDefault(), WireName("customInstructions") ] = PiOmitted() diff --git a/src/agent_comms/execution/pi_wire.py b/src/agent_comms/execution/pi_wire.py index a142758c3f..1b91d77746 100644 --- a/src/agent_comms/execution/pi_wire.py +++ b/src/agent_comms/execution/pi_wire.py @@ -4,7 +4,7 @@ import re import typing -from abc import abstractmethod +from abc import ABC, abstractmethod from collections.abc import Mapping from dataclasses import dataclass from decimal import Decimal @@ -336,6 +336,38 @@ def __post_init__(self): self.state.validate(self.calls, counts) +class LiveStatusClaim(ABC): + """An optional raw status payload decoded as a live MCP acknowledgement.""" + + def from_status(self, owner: type[McpLiveAcknowledgement], input_id: InputId) -> McpLiveAcknowledgement | None: + pass + + @classmethod + def from_optional(cls, value: str | None) -> LiveStatusClaim: + return AbsentLiveStatusClaim() if value is None else HeldLiveStatusClaim(value) + + +@dataclass(frozen=True) +class AbsentLiveStatusClaim(LiveStatusClaim): + """Absent `LiveStatusClaim` carrying no value.""" + + +@dataclass(frozen=True) +class HeldLiveStatusClaim(LiveStatusClaim): + """Held `LiveStatusClaim` carrying its present value.""" + + value: str + + def from_status(self, owner: type[McpLiveAcknowledgement], input_id: InputId) -> McpLiveAcknowledgement | None: + if len(self.value) > 8192: + return None + try: + acknowledgement = FieldCodec.decode(owner, FieldCodec.parse(self.value)) + except MalformedRecord: + return None + return acknowledgement if acknowledgement.input_id == input_id else None + + @dataclass(frozen=True) class McpLiveAcknowledgement: version: Literal[1] @@ -346,19 +378,13 @@ class McpLiveAcknowledgement: servers: tuple[McpServerReceipt, ...] @classmethod - def from_status(cls, text: str | None, input_id: InputId) -> McpLiveAcknowledgement | None: + def from_status(cls, text: LiveStatusClaim, input_id: InputId) -> McpLiveAcknowledgement | None: """Decode the package's external status claim once at its boundary. Same-user extensions can imitate this claim. It is never a package attestation or permission, even when the current input identity matches. """ - if text is None or len(text) > 8192: - return None - try: - acknowledgement = FieldCodec.decode(cls, FieldCodec.parse(text)) - except MalformedRecord: - return None - return acknowledgement if acknowledgement.input_id == input_id else None + return text.from_status(cls, input_id) def __post_init__(self): if len(self.servers) > 32 or len({server.id for server in self.servers}) != len( diff --git a/src/agent_comms/execution/private_nk_entrypoint.py b/src/agent_comms/execution/private_nk_entrypoint.py index 798a46c158..817528c2ba 100644 --- a/src/agent_comms/execution/private_nk_entrypoint.py +++ b/src/agent_comms/execution/private_nk_entrypoint.py @@ -11,7 +11,6 @@ from abc import ABC, abstractmethod from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING from agent_comms.coordination.errors import IdentityConflict, PublicationActivationBlocked from agent_comms.execution.launch_runtime import LaunchRuntime @@ -24,13 +23,10 @@ pinned_native_package, ) from agent_comms.nominal.field_codec import RootId +from agent_comms.registry.threads import Thread from agent_comms.storage.locked_store import BusRevisionReader, RegistryFile from agent_comms.storage.private_path import PrivateDirectoryRole -if TYPE_CHECKING: - from agent_comms.registry.threads import Thread - - class RootLaunch(ABC): """Native launch policy derived from the registry's existing authority.""" diff --git a/src/agent_comms/execution/proven_source_coverage.py b/src/agent_comms/execution/proven_source_coverage.py index 1ceb5d75e1..2c2e06d515 100644 --- a/src/agent_comms/execution/proven_source_coverage.py +++ b/src/agent_comms/execution/proven_source_coverage.py @@ -214,6 +214,12 @@ def evidence(self, *, through_seq: int | None = None) -> tuple[HistoricalNativeI return self.inputs return tuple(item for item in self.inputs if item.source_seq <= through_seq) + def stops_coverage(self, covered, owner: SourceCoverage, inputs, no_wake, prefix): + """Report whether this coverage page is blocked or has no more sources.""" + if self.blocked_seq is not None or not self.more_sources: + return ProvenSourceCoverage(owner.wire_root_id, owner.recipient_lookup, covered, tuple(inputs), tuple(no_wake), self.blocked_seq, self.more_sources, source_prefix=prefix) + return None + class SourceCoverage: """Canonical SQLite prefix reader bound to one stable recipient. @@ -362,18 +368,6 @@ def since(self, state: CursorState, *, covered = page.covered_seq inputs.extend(page.inputs) no_wake.extend(page.no_wake_seqs) - if ( - page.blocked_seq is not None - or not page.more_sources - ): - return ProvenSourceCoverage( - self.wire_root_id, - self.recipient_lookup, - covered, - tuple(inputs), - tuple(no_wake), - page.blocked_seq, - page.more_sources, - source_prefix=prefix, - ) + if (_found := page.stops_coverage(covered, self, inputs, no_wake, prefix)) is not None: + return _found raise IdentityConflict("source coverage exceeded bounded canonical page budget") diff --git a/src/agent_comms/execution/queued_input.py b/src/agent_comms/execution/queued_input.py index 4c0334cdd0..48d0fb87cb 100644 --- a/src/agent_comms/execution/queued_input.py +++ b/src/agent_comms/execution/queued_input.py @@ -7,6 +7,7 @@ from __future__ import annotations import os +from abc import ABC from collections.abc import AsyncIterator from contextlib import AsyncExitStack, ExitStack, asynccontextmanager from dataclasses import dataclass, field, replace @@ -164,6 +165,32 @@ def active_goal_id(self) -> GoalId | None: return self.goal.active().reported_id() +class ExpectedInputOwner(ABC): + """An optional expected owner identity verified when resolving a queued input.""" + + def verify_owner(self, owner, canonical, snapshot: RegistrySnapshot) -> None: + pass + + @classmethod + def from_optional(cls, value: OwnerIdentity | None) -> ExpectedInputOwner: + return AbsentExpectedInputOwner() if value is None else HeldExpectedInputOwner(value) + + +@dataclass(frozen=True) +class AbsentExpectedInputOwner(ExpectedInputOwner): + """Absent `ExpectedInputOwner` carrying no value.""" + + +@dataclass(frozen=True) +class HeldExpectedInputOwner(ExpectedInputOwner): + """Held `ExpectedInputOwner` carrying its present value.""" + + value: OwnerIdentity + + def verify_owner(self, owner, canonical, snapshot: RegistrySnapshot) -> None: + self.value.require_current(owner, snapshot.owner_identity(canonical).generation, ProcessIdentity.capture(os.getpid())) + + @dataclass(frozen=True, slots=True) class QueuedInput: text: str @@ -191,17 +218,12 @@ def source(self) -> AcceptedFollowingInput: @staticmethod def owner_in( - snapshot: RegistrySnapshot, name: str, expected: OwnerIdentity | None, + snapshot: RegistrySnapshot, name: str, expected: ExpectedInputOwner, ) -> tuple[str, Thread]: """Resolve one owner and prove the allocation selected by the input destination.""" canonical = snapshot.canonical_name(name) owner = snapshot.threads[canonical] - if expected is not None: - expected.require_current( - owner, - snapshot.owner_identity(canonical).generation, - ProcessIdentity.capture(os.getpid()), - ) + expected.verify_owner(owner, canonical, snapshot) return canonical, owner @classmethod @@ -222,7 +244,7 @@ def capture( expected_owner: OwnerIdentity | None = None, ) -> tuple[Self, InputAttempt]: """The current registry selection permits this durable input reservation.""" - canonical, owner = cls.owner_in(snapshot, name, expected_owner) + canonical, owner = cls.owner_in(snapshot, name, ExpectedInputOwner.from_optional(expected_owner)) context = QueuedInputContext.capture( owner, snapshot.claimed_identity(canonical), @@ -296,7 +318,7 @@ def place( self.owner_in( cut.snapshot, self.context.claimed_identity.incarnation.name, - expected_owner, + HeldExpectedInputOwner(expected_owner), ) inputs.require_inbox(session_id, inbox) source = self.source() diff --git a/src/agent_comms/execution/turn_digests.py b/src/agent_comms/execution/turn_digests.py index 9640c1b28b..72ed7967f2 100644 --- a/src/agent_comms/execution/turn_digests.py +++ b/src/agent_comms/execution/turn_digests.py @@ -250,9 +250,7 @@ def judgeable(cls, root: Path, holds: Iterable[LiveHold], workplaces: Mapping[ThreadIncarnation, EditWorkplaces]) -> Iterator[Self]: """The reads a verdict can still clear: an order whose PR merged has no head left to judge, so its edits are nobody's review and its transcript is never read.""" - return (replace(read, progress=progress[read.todo.id]) - for read in cls.for_orders(root, holds, workplaces) - if progress[read.todo.id].for_verdict()) + return (_item for read in cls.for_orders(root, holds, workplaces) for _item in progress[read.todo.id].select_judgeable(read)) @classmethod def for_orders(cls, root: Path, holds: Iterable[LiveHold], diff --git a/src/agent_comms/execution/turn_goal_account.py b/src/agent_comms/execution/turn_goal_account.py index c99cbdf52c..b102056996 100644 --- a/src/agent_comms/execution/turn_goal_account.py +++ b/src/agent_comms/execution/turn_goal_account.py @@ -14,10 +14,10 @@ from agent_comms.planning.goal_attempts import GoalAttemptStore, LaunchPermit from agent_comms.planning.goal_states import ActiveGoal, CompletedGoal, PausedGoal from agent_comms.planning.goals import Goal +from agent_comms.registry.threads import Thread if TYPE_CHECKING: from agent_comms.comms import Comms - from agent_comms.registry.threads import Thread @dataclass diff --git a/src/agent_comms/execution/turn_output.py b/src/agent_comms/execution/turn_output.py index 8896d1e38c..de641607bc 100644 --- a/src/agent_comms/execution/turn_output.py +++ b/src/agent_comms/execution/turn_output.py @@ -136,9 +136,7 @@ def done(self, session: NativeSessionCallbacks, stderr: str) -> Iterator[events. diagnostic={ **self.diagnostic, **( - {"exit_code": session.native.proc.returncode} - if session.native.proc.returncode is not None - else {} + session.native.proc.exit_code_diagnostic() ), }, ) diff --git a/src/agent_comms/execution/turn_phase.py b/src/agent_comms/execution/turn_phase.py index d2ad88eef9..98a847c62d 100644 --- a/src/agent_comms/execution/turn_phase.py +++ b/src/agent_comms/execution/turn_phase.py @@ -80,8 +80,9 @@ class TurnPhase(DeclaredFamily, affix="Phase"): # excursion's own backstop bounds the stall instead. busy: ClassVar[bool] = True - def pauses_input_clock(self) -> bool: - return False + def input_start_wait(self, owner, active): + """Select the input wait while awaiting start unless this phase pauses the input clock.""" + return owner.input_wait def accepts_followup(self) -> bool: return True @@ -162,8 +163,8 @@ def phase_effects(self, agents: AgentActivity, lease: TurnLeaseFence) -> None: class Excursion(TurnPhase, declared_name=None): - def pauses_input_clock(self) -> bool: - return True + def input_start_wait(self, owner, active): + return active class PromptAcceptancePhase(TurnPhase): diff --git a/src/agent_comms/execution/turn_watchdog.py b/src/agent_comms/execution/turn_watchdog.py index 58f6b524c4..e78cea4768 100644 --- a/src/agent_comms/execution/turn_watchdog.py +++ b/src/agent_comms/execution/turn_watchdog.py @@ -243,8 +243,8 @@ def wait_for(self, session: WatchdogSessionRead[ProgressWatchdog, StatsRequest]) if session.awaiting_native_attestation: return self.preflight_wait active = self.phase.model_wait(self.model_wait, self.unbounded_wait) - if session.prompt_state.awaiting_start and not self.phase.pauses_input_clock(): - active = self.input_wait + if session.prompt_state.awaiting_start: + active = self.phase.input_start_wait(self, active) return session.stats.wait_for(self, active) async def read(self, session: WatchdogSessionRead[ProgressWatchdog, StatsRequest]) -> bytes: diff --git a/src/agent_comms/input_attempt.py b/src/agent_comms/input_attempt.py index 09511800f1..14a86a54d5 100644 --- a/src/agent_comms/input_attempt.py +++ b/src/agent_comms/input_attempt.py @@ -217,6 +217,10 @@ def delivered_in( """The bus message this input delivered into the lease's turn.""" return input_origin.UndeliveredInput() + def started_for_owners(self, key): + """Report whether this attempt counts as started for any of the given owners.""" + return () + class InputDeliveryScope(DeclaredFamily, affix="InputDeliveryScope"): """The queue evidence available to this delivery read, not an input outcome.""" @@ -527,6 +531,9 @@ def context_committed( def record_context(self, context: NativeContextProof) -> InputTransition: return MovedInput(self._transition(ContextConsumedInput, context=context)) + def started_for_owners(self, key): + return (key,) + @dataclass(frozen=True) class ContextConsumedInput(StartedInput): diff --git a/src/agent_comms/input_disposition.py b/src/agent_comms/input_disposition.py index 6416e2f491..901df0e366 100644 --- a/src/agent_comms/input_disposition.py +++ b/src/agent_comms/input_disposition.py @@ -143,8 +143,7 @@ def all_started(self, keys) -> bool: def started_for(self, owners: frozenset[str]) -> frozenset[InputKey]: """Keys these owners' turns already took in; a delivered input needs no review.""" - return frozenset( - key for key, row in self.rows.items() if row.counts_as_started() and row.owner in owners) + return frozenset(_item for key, row in self.rows.items() for _item in row.started_for_owners(key) if row.owner in owners) def unknown(self, owners: frozenset[str]) -> tuple[StoredInput, ...]: return tuple( diff --git a/src/agent_comms/messaging/read_basis.py b/src/agent_comms/messaging/read_basis.py index e276a51d39..3019a862f1 100644 --- a/src/agent_comms/messaging/read_basis.py +++ b/src/agent_comms/messaging/read_basis.py @@ -23,6 +23,7 @@ from agent_comms.messaging.activity_clocks import ChannelActivity from agent_comms.messaging.channel_sources import ChannelHistorySource, ChannelScopeFactory from agent_comms.messaging.channel_targets import CommandTarget, ThreadTarget +from agent_comms.messaging.channels import AnyChannel from agent_comms.messaging.mentions import ThreadMention from agent_comms.messaging.message_reads import ScopedMessage from agent_comms.messaging.message_reference import MessageReference @@ -608,7 +609,6 @@ def resolved(self, snapshot: RegistryProvenance): return self def scope(self, snapshot: RegistryProvenance) -> AllChannelDisplayScope: - from agent_comms.messaging.channels import AnyChannel return AllChannelDisplayScope(AnyChannel.address()) diff --git a/src/agent_comms/nominal/field_codec.py b/src/agent_comms/nominal/field_codec.py index 7205c113b0..e0713e0563 100644 --- a/src/agent_comms/nominal/field_codec.py +++ b/src/agent_comms/nominal/field_codec.py @@ -1041,7 +1041,7 @@ def unknown_under(self, refused: MalformedRecord, owner: DecoderPlan) -> tuple[U def inlined(self) -> type: declared, representation = FieldCodec.representation(self.annotation) match representation: - case type() as inline if issubclass(inline, InlineRecord): + case type() as inline if inline.inlined_wire_type(): return inline.wire_record() return cast(type, declared) @@ -1733,6 +1733,16 @@ def stored_as_text(cls): """Whether SQLite stores this field representation as TEXT.""" return False + @classmethod + def inlined_wire_type(cls) -> bool: + """Return the inline wire record type or the declared type for this field representation.""" + return False + + @classmethod + def project_record_value(cls, current, view: type[ViewExclusion], entry): + """Project a record field value for the requested view using this representation.""" + return cls.project_view(current, view, entry.annotation) + class StructuralRepresentation(FieldRepresentation): """The value has no representation codec, so FieldCodec handles its structure.""" @@ -1785,6 +1795,15 @@ def schema_for(cls, annotation: object) -> dict[str, JsonValue]: return FieldCodec.record_schema(annotation) return compile_decoder(annotation).value_schema() + @classmethod + def project_record_value(cls, current, view: type[ViewExclusion], entry): + current_type = type(current) + if current is None or current_type is str or current_type is bool or (current_type is int): + encoded: object = current + else: + encoded = cls.for_value(current).project_view(current, view, entry.annotation) + return encoded + class AcceptsNull[T](FieldRepresentation[T]): """Null is this representation's input, not the structural target's.""" @@ -2212,6 +2231,10 @@ def wire_structure(cls, structural: DecoderPlan) -> DecoderPlan: def schema(cls): return FieldCodec.record_schema(cls.wire_record()) + @classmethod + def inlined_wire_type(cls) -> bool: + return True + class JsonShapeMember: """A declared external JSON shape with one typed ``value`` field. @@ -3338,14 +3361,7 @@ def _project_record(cls, value: object, view: type[ViewExclusion]) -> JsonValue: current = entry.current(value) if entry.omitted(current): continue - if rep is StructuralRepresentation: - current_type = type(current) - if current is None or current_type is str or current_type is bool or current_type is int: - encoded: object = current - else: - encoded = rep.for_value(current).project_view(current, view, entry.annotation) - else: - encoded = rep.project_view(current, view, entry.annotation) + encoded = rep.project_record_value(current, view, entry) entry.write_encoded(result, encoded, key) properties = cls.projections(record_type, view) if properties: diff --git a/src/agent_comms/pi_native_backend.py b/src/agent_comms/pi_native_backend.py index e7b97230df..4fb574d846 100644 --- a/src/agent_comms/pi_native_backend.py +++ b/src/agent_comms/pi_native_backend.py @@ -15,7 +15,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable from functools import partial from pathlib import Path -from typing import TYPE_CHECKING, ClassVar, Self +from typing import ClassVar, Self from agent_comms import agent_events as events from agent_comms.agent_backend import ( @@ -27,7 +27,10 @@ ServedAgentBackend, ServedRuntimeLocation, ) +from agent_comms.comms import Comms +from agent_comms.config_options import ConfigOptions from agent_comms.coordination.work import CoordinationWork +from agent_comms.execution import backend from agent_comms.execution.agent_event import AgentEvent from agent_comms.execution.backend_declarations import ( PiNativeBackendDeclaration, @@ -44,6 +47,8 @@ NativeSessionFiles, NativeSessionLocks, ) +from agent_comms.execution.native_session_prepare import NativeSessionPreparation +from agent_comms.execution.owned_turn import TurnDelivery from agent_comms.execution.persistent_pi_session import ( PersistentPiSession as PersistentPiSession, ) @@ -59,18 +64,13 @@ from agent_comms.execution.selected.session import SavedSelectedSession from agent_comms.execution.session_revision import SessionObservation, SessionRevision from agent_comms.execution.turn_inbox import InputContent +from agent_comms.execution.turn_runner import TurnRunner from agent_comms.installer.active_route import resolve_comms_route from agent_comms.nominal.field_codec import AcpSessionId from agent_comms.pi_payloads import PiResponseData, StateData from agent_comms.registry.thread_model import ThreadModel, UndeclaredModel - -if TYPE_CHECKING: - from agent_comms.comms import Comms - from agent_comms.config_options import ConfigOptions - from agent_comms.execution.owned_turn import TurnDelivery - from agent_comms.execution.turn_runner import TurnRunner - from agent_comms.registry.threads import Thread - +from agent_comms.registry.threads import Thread +from agent_comms.team.pi_rule_gate import PiRuleGate # The event kinds Pi 0.85.1 writes to RPC stdout, as built for Core. Sources, # all in @earendil-works/pi-coding-agent 0.85.1 as patched by stack/: @@ -174,10 +174,6 @@ def arguments(self, thread: Thread) -> tuple[str, ...]: async def prepare(self, thread: Thread, *, open_native=None) -> StateData: """Launch (or reuse) and attest the idle child for ``thread``'s saved session.""" - from agent_comms.execution.native_session_prepare import ( - NativeSessionPreparation, - ) - from agent_comms.team.pi_rule_gate import PiRuleGate if open_native is None: open_native = NativeSessionPreparation.open @@ -235,8 +231,6 @@ async def run_turn( yield event def _turn_events(self, thread, content, delivery, images, package): - from agent_comms.execution import backend - from agent_comms.team.pi_rule_gate import PiRuleGate return backend.stream_agent_events( self.configuration.launch.binary, @@ -265,7 +259,6 @@ def _turn_events(self, thread, content, delivery, images, package): ) async def abort[Result](self, owner: asyncio.Task[Result]) -> None: - from agent_comms.execution import backend await backend.terminate_task_process(owner) diff --git a/src/agent_comms/planning/orders.py b/src/agent_comms/planning/orders.py index 1836b78d95..2e3f8d8131 100644 --- a/src/agent_comms/planning/orders.py +++ b/src/agent_comms/planning/orders.py @@ -1727,6 +1727,10 @@ def missing_merges(self, source: ProgressSource) -> tuple[MergedProgress, ...]: """Linked merges this progress incorrectly reports as no commit.""" return () + def select_judgeable(self, read): + """Include this order edit read only when the progress still admits a verdict.""" + return (replace(read, progress=self),) + @dataclass(frozen=True) class FoundProgress(OrderProgress): @@ -1805,6 +1809,9 @@ def waiting_on_install(self, todo: Todo) -> tuple[Todo, ...]: def for_verdict(self) -> bool: return False + def select_judgeable(self, read): + return () + @dataclass(frozen=True) class OpenPrProgress(GitProgress): @@ -1988,6 +1995,10 @@ def folded(self, into: str, why: str) -> ProblemOrder: raise TodoError("The problem has open orders; link or drop them first.") return FoldedProblemOrder(original=self, into=into, why=why) + def blocks_incoming(self, todo): + """Report whether this order occupies its holder against an uncovered incoming work item.""" + return (todo,) + @dataclass(frozen=True, kw_only=True) class UnorderedProblemOrder(ProblemOrder): @@ -2557,6 +2568,9 @@ def orphan_clearing(self, todo: Todo) -> str: return (f"its work is done and waits on install; once installed, close it with " f"`order close {todo.id} --works WHAT-RAN --artifact FILE`") + def blocks_incoming(self, todo): + return () + @dataclass(frozen=True, kw_only=True) class MergedProblemOrder(CommittedCheckSource, AwaitingInstallationProblemOrder): @@ -3292,8 +3306,7 @@ def require_free(self, db: sqlite3.Connection, unit: ThreadIncarnation, Creator and previous assigner confer no rank. Work waiting only on install holds no unit, as ProblemOrder.occupies_holder answers.""" held = TransactionTodoHistory(db).attach(TodoStore.held_in(db, '1', (), unit=unit)) - if other := tuple(todo for todo in held - if todo.order.occupies_holder() and not self.covers(todo)): + if other := tuple(_item for todo in held for _item in todo.order.blocks_incoming(todo) if not self.covers(todo)): raise TeammateOccupied( f"{unit.name} already holds orders " + ", ".join(f"{todo.id} (assigned by {todo.held().parent})" for todo in other) diff --git a/src/agent_comms/projects/git_history.py b/src/agent_comms/projects/git_history.py index 8034a58da5..a392138b50 100644 --- a/src/agent_comms/projects/git_history.py +++ b/src/agent_comms/projects/git_history.py @@ -641,19 +641,7 @@ def retaining(cls, previous: RepositoryReads) -> Self: retained: dict[Path, CheckoutHistory] = {} successors: dict[int, CheckoutHistory] = {} for common_dir, history in previous._histories.items(): - if history.source_revision is None: - continue - try: - successor = ( - history - if history.sources_current() - else history.following(CheckoutHistory.capture(history.checkout, history)) - ) - retained[common_dir] = successor - successors[id(history)] = successor - except (GitCommandError, OSError): - # A later requested acquisition owns reporting its unreadable source. - continue + history.retain_if_observed(retained, common_dir, successors) reads = cls() reads._histories = retained reads._worktree_histories = { @@ -1774,3 +1762,14 @@ def merge_base(self, left: str, right: str) -> tuple[str, ...]: def count(self, head: str, *excluded: str) -> int: return (self.ancestors(head) & ~self.ancestors(*excluded)).bit_count() + def retain_if_observed(self, retained, common_dir, successors) -> None: + """Retain and refresh this checkout history only when it has an observed source revision.""" + if self.source_revision is None: + return + try: + successor = self if self.sources_current() else self.following(CheckoutHistory.capture(self.checkout, self)) + retained[common_dir] = successor + successors[id(self)] = successor + except (GitCommandError, OSError): + return + diff --git a/src/agent_comms/projects/storage_rules.py b/src/agent_comms/projects/storage_rules.py index c261f120ab..c251cd23c5 100644 --- a/src/agent_comms/projects/storage_rules.py +++ b/src/agent_comms/projects/storage_rules.py @@ -159,6 +159,10 @@ def edit_boundary(self, rule: StorageRule, owner: Thread, path: Path, store: TodoStore, reads: RepositoryReads) -> frozenset[Path]: return frozenset() + def owns_reserved_checkout(self, caller: StorageRule, owner: Thread, path: Path, reads: RepositoryReads): + """Report whether a boundary-reserving allocation owns this present checkout.""" + return () + @dataclass(frozen=True) class HomeCheckoutAllocation(CheckoutAllocation): @@ -216,6 +220,9 @@ def edit_boundary(self, rule: StorageRule, owner: Thread, path: Path, except (GitCommandError, TodoError) as error: raise StorageDenied(f'Cannot authorize source write in {path}: {error}') from error + def owns_reserved_checkout(self, caller: StorageRule, owner: Thread, path: Path, reads: RepositoryReads): + return (self.owns_present(caller, owner, path, reads),) + class WorkCheckoutAllocation(EditableCheckoutAllocation, declared_name=None): """An allocation whose paths are declared from a problem or goal identity.""" @@ -493,9 +500,7 @@ def owns_editable_checkout(self, owner: Thread, path: Path, repository: RepositoryName, reads: RepositoryReads) -> bool: """Qualify this exact reuse target, without inventorying unrelated history.""" return ((path / '.git').is_file() and not path.is_symlink() - and any(allocation.owns_present(self, owner, path, reads) - for allocation in CheckoutAllocation.for_path(self, owner, path) - if allocation.reserves_boundary()) + and any(_item for allocation in CheckoutAllocation.for_path(self, owner, path) for _item in allocation.owns_reserved_checkout(self, owner, path, reads)) and reads.repository(path).github == repository) def owned_checkouts(self, owner: Thread, repository: RepositoryName, diff --git a/src/agent_comms/projects/work_branches.py b/src/agent_comms/projects/work_branches.py index a13ad8e15a..fd958f9c0a 100644 --- a/src/agent_comms/projects/work_branches.py +++ b/src/agent_comms/projects/work_branches.py @@ -636,12 +636,7 @@ def checkouts(self, snapshot: RegistrySnapshot, branch: str, def _checkout(snapshot: RegistrySnapshot, worktree: str) -> BranchCheckout: resolved = str(Path(worktree).resolve()) threads = tuple( - sorted( - thread.name - for thread in snapshot.threads.values() - if not snapshot.statuses[thread.name].is_archived() - and str(thread.worktree.path.expanduser().resolve()) == resolved - ) + sorted(_item for thread in snapshot.threads.values() for _item in snapshot.statuses[thread.name].active_checkout_matches(thread) if str(thread.worktree.path.expanduser().resolve()) == resolved) ) if not threads: return UnregisteredBranchCheckout(worktree) diff --git a/src/agent_comms/registry/heartbeat_delivery.py b/src/agent_comms/registry/heartbeat_delivery.py index e646960add..84740809fc 100644 --- a/src/agent_comms/registry/heartbeat_delivery.py +++ b/src/agent_comms/registry/heartbeat_delivery.py @@ -16,6 +16,11 @@ def publish[Publication](cls, operation: Callable[[], Publication]) -> tuple[Pub def publishes(cls) -> bool: return False + @classmethod + def published_entries(cls, owner, announced): + """Select newly changed team pings only when this delivery policy publishes updates.""" + return () + class OnHeartbeatDelivery(HeartbeatDelivery): """Execute the packet owner's publication, retaining its notice or wake behavior.""" @@ -28,6 +33,10 @@ def publish[Publication](cls, operation: Callable[[], Publication]) -> tuple[Pub def publishes(cls) -> bool: return True + @classmethod + def published_entries(cls, owner, announced): + return tuple((ping for ping in owner.handled if announced.get(ping.key) != ping)) + class OffHeartbeatDelivery(HeartbeatDelivery): """The observation and HUD remain current; no bus message is created.""" diff --git a/src/agent_comms/registry/registry_document.py b/src/agent_comms/registry/registry_document.py index b9ab013992..cb520556b9 100644 --- a/src/agent_comms/registry/registry_document.py +++ b/src/agent_comms/registry/registry_document.py @@ -118,7 +118,7 @@ ThreadStatus, ) from agent_comms.registry.thread_text import ForkedParent, NoParent -from agent_comms.registry.threads import Thread, ThreadWorkState +from agent_comms.registry.threads import PreviousThreadRegistration, Thread, ThreadWorkState from agent_comms.registry.user_thread_lookup import FoundUserThread, NoUserThread, UserThreadLookup from agent_comms.storage.row_mapping import ReadOnlyRows, RowKeys, RowMapping from agent_comms.transport.tool_result import ToolResult @@ -986,7 +986,7 @@ def set_team_project(self, project: TeamProject) -> TeamProject: def prepare_declaration(self, thread: Thread, status: ThreadStatus) -> RegistrationChange: canonical = self.canonical_name(thread.name) - requested = thread.for_registration(canonical, self.threads.get(canonical)) + requested = thread.for_registration(canonical, PreviousThreadRegistration.from_optional(self.threads.get(canonical))) change = self.prepare_registration(requested, status, new_owner=False) return change.declared(requested) diff --git a/src/agent_comms/registry/relationship_store.py b/src/agent_comms/registry/relationship_store.py index 3e1d9c9fcb..b2c74ddb96 100644 --- a/src/agent_comms/registry/relationship_store.py +++ b/src/agent_comms/registry/relationship_store.py @@ -205,10 +205,13 @@ def revalidates(self, earlier: RelationshipEntry) -> bool: """A fresh navigation target must retain its identity and incarnation.""" if not self.available or self.identity != earlier.identity: return False - if earlier.person is None: + return earlier.person_matches(self) + + def person_matches(self, owner: RelationshipEntry) -> bool: + """Check that a current relationship entry preserves the earlier person incarnation.""" + if self.person is None: return True - return (self.person is not None - and self.person.thread.incarnation == earlier.person.thread.incarnation) + return owner.person is not None and owner.person.thread.incarnation == self.person.thread.incarnation @dataclass(frozen=True, slots=True) diff --git a/src/agent_comms/registry/thread_identity.py b/src/agent_comms/registry/thread_identity.py index 026360ae90..6d43bea1ac 100644 --- a/src/agent_comms/registry/thread_identity.py +++ b/src/agent_comms/registry/thread_identity.py @@ -731,6 +731,11 @@ def reply_target(cls, message: Message) -> str | None: @abstractmethod def user_task_facts(cls, message: Message) -> Iterable[object]: ... + @classmethod + def format_reply_route(cls, owner) -> str: + """Format the reply route line only when this sender role hears each reply.""" + return '' + class NonExecutingThreadRole: """Authorship without an owner turn: human readers and service publishers.""" @@ -888,3 +893,7 @@ def last_user_input(cls, previous: float, timestamp: float) -> float: @classmethod def user_task_facts(cls, message: Message) -> Iterable[object]: return message.task.user_task_facts(message) + + @classmethod + def format_reply_route(cls, owner) -> str: + return '\n' + owner.reply_route.format(target=owner.message.exact_reply_target) diff --git a/src/agent_comms/registry/thread_presentation.py b/src/agent_comms/registry/thread_presentation.py index c75b46b657..f443c9b0b6 100644 --- a/src/agent_comms/registry/thread_presentation.py +++ b/src/agent_comms/registry/thread_presentation.py @@ -169,6 +169,10 @@ def with_disconnection[T](self, ordinary: T, disconnected: Callable[[], T]) -> T """A failed viewer connection normally supplies the displayed state.""" return disconnected() + def include_as_working(self, name): + """Report whether this thread status counts as working in sidebar aggregation.""" + return () + @dataclass(frozen=True, slots=True) class IdleThreadPresentationStatus(ThreadPresentationStatus): @@ -207,6 +211,9 @@ def activity_presentation(self, title: str, activity: str, detail: str) -> Threa summary += f" · {detail}" return ThreadPresentation(title, "", summary, status=self) + def include_as_working(self, name): + return (name,) + @dataclass(frozen=True, slots=True) class StatusPending(ThreadPresentationStatus): diff --git a/src/agent_comms/registry/thread_status.py b/src/agent_comms/registry/thread_status.py index a9458d57bd..8ad9bd4077 100644 --- a/src/agent_comms/registry/thread_status.py +++ b/src/agent_comms/registry/thread_status.py @@ -259,6 +259,10 @@ def presentation( return ThreadPresentation(title, "○", self.declared_name.title(), status=InactiveThreadPresentationStatus()) + def active_checkout_matches(self, thread): + """Report whether a non-archived thread matches the resolved worktree path.""" + return (thread.name,) + class HostBoundPresence: """A session still running in the recorded process: it keeps that host alive, and a @@ -528,6 +532,9 @@ def in_view(self, visibility: RosterVisibility) -> bool: def restored(self) -> ThreadStatus: return self + def active_checkout_matches(self, thread): + return () + class DeletingThreadStatus(ThreadStatus): def in_view(self, visibility: RosterVisibility) -> bool: diff --git a/src/agent_comms/registry/threads.py b/src/agent_comms/registry/threads.py index bbc16469bb..57d90eae18 100644 --- a/src/agent_comms/registry/threads.py +++ b/src/agent_comms/registry/threads.py @@ -514,6 +514,37 @@ class ThreadCatalogFile(DurableFile, PatternFile): filename: ClassVar[str] = "native-sessions/{lookup}/comms-catalog.json" +class PreviousThreadRegistration(ABC): + """An optional previous thread record supplying registration-inherited metadata.""" + + @abstractmethod + def inherited_fields(self, inherited, owner: Thread): + ... + + @classmethod + def from_optional(cls, value: Thread | None) -> PreviousThreadRegistration: + return AbsentPreviousThreadRegistration() if value is None else HeldPreviousThreadRegistration(value) + + +@dataclass(frozen=True) +class AbsentPreviousThreadRegistration(PreviousThreadRegistration): + """Absent `PreviousThreadRegistration` carrying no value.""" + + def inherited_fields(self, inherited, owner: Thread): + return inherited + + +@dataclass(frozen=True) +class HeldPreviousThreadRegistration(PreviousThreadRegistration): + """Held `PreviousThreadRegistration` carrying its present value.""" + + value: Thread + + def inherited_fields(self, inherited, owner: Thread): + inherited = {plan.name: directive.value.choose(getattr(owner, plan.name), getattr(self.value, plan.name)) for plan in FieldCodec.field_plans(type(owner)) for directive in RegistrationPolicy.single(plan.annotation)} + return inherited + + @dataclass(frozen=True, slots=True) class Thread( ThreadSettings, @@ -965,20 +996,14 @@ def for_claim(self, name: str) -> Thread: """Assign an allocated name, retaining the creation value's allocation policy.""" return replace(self, name=name) - def for_registration(self, canonical_name: str, previous: Thread | None) -> Thread: + def for_registration(self, canonical_name: str, previous: PreviousThreadRegistration) -> Thread: """Resolve metadata once from its field declarations, retaining exact identity. Executor and turn authority are not metadata. The creation value retains its own allocation policy across replacements. """ inherited = {} - if previous is not None: - inherited = { - plan.name: directive.value.choose( - getattr(self, plan.name), getattr(previous, plan.name)) - for plan in FieldCodec.field_plans(type(self)) - for directive in RegistrationPolicy.single(plan.annotation) - } + inherited = previous.inherited_fields(inherited, self) resolved = replace(self, name=canonical_name, **inherited) return self if resolved == self else resolved diff --git a/src/agent_comms/storage/locked_store.py b/src/agent_comms/storage/locked_store.py index b406663ea8..00a10fca4c 100644 --- a/src/agent_comms/storage/locked_store.py +++ b/src/agent_comms/storage/locked_store.py @@ -467,23 +467,11 @@ def primaries_in(cls, root: Path) -> dict[Path, type[Self]]: @classmethod def declaring_owner(cls) -> type[RootFile]: """A locking store can inherit its filename from a location-only declaration.""" - if issubclass(cls, StoreLockFile): - return cls - stores = tuple( - owner - for owner in StoreLockFile.members_with(cls) - if issubclass(owner, RootFile) - and owner.filename == cls.filename - and owner.root_directory == cls.root_directory - ) + stores = tuple((owner for owner in StoreLockFile.members_with(cls) if issubclass(owner, RootFile) and owner.filename == cls.filename and (owner.root_directory == cls.root_directory))) if not stores: return cls - roots = tuple( - owner - for owner in stores - if not any(other is not owner and issubclass(owner, other) for other in stores) - ) - (owner,) = roots + roots = tuple((owner for owner in stores if not any((other is not owner and issubclass(owner, other) for other in stores)))) + owner, = roots return owner @classmethod @@ -826,6 +814,10 @@ def copy_group(cls, source: Path, target: Path) -> frozenset[Path]: with cls.read_guard(source): return super().copy_group(source, target) + @classmethod + def declaring_owner(cls): + return super(RootFile, cls).declaring_owner() + @dataclass(frozen=True, slots=True, eq=False, repr=False) class FileStore(RootFile): @@ -1487,6 +1479,10 @@ def _copy_sources(*sources: CopyingStore) -> tuple[DocumentBytes, ...]: with CopyingStore._capturing_sources(*sources) as captured: return captured + @classmethod + def declaring_owner(cls): + return super(RootFile, cls).declaring_owner() + class DocumentTransactions(CopyingStore, JsonDocument[T], FileTransactions, declared_name=None): """Document changes own their write guard, independent of path construction.""" diff --git a/src/agent_comms/storage/store_files.py b/src/agent_comms/storage/store_files.py index 74ebc228b6..efea39b62b 100644 --- a/src/agent_comms/storage/store_files.py +++ b/src/agent_comms/storage/store_files.py @@ -275,6 +275,10 @@ class StoreLockFile(StoreOwner, declared_name=None): __slots__ = () + @classmethod + def declaring_owner(cls): + return cls + class StoreGuard: """Explicit-path lock behavior without a file-declaration or wire family.""" diff --git a/src/agent_comms/storage/typed_table.py b/src/agent_comms/storage/typed_table.py index 769d06187d..e7bcaacec5 100644 --- a/src/agent_comms/storage/typed_table.py +++ b/src/agent_comms/storage/typed_table.py @@ -3403,6 +3403,10 @@ def reconcile_at( with cls.exclusive_writer(path, uri=True) as db: return schema.reconcile_schema(db, cls.schema_change(path), rebuild=rebuild) + @classmethod + def declaring_owner(cls): + return super(RootFile, cls).declaring_owner() + class ExternalStore(ExternalFile, DeclaredFamily, affix="Store"): """Durable files outside the bus that their own writer owns. An installed package declares @@ -3624,6 +3628,10 @@ def writing(self) -> Iterator[sqlite3.Connection]: raise self._retire_committed(lifetime) + @classmethod + def declaring_owner(cls): + return super(RootFile, cls).declaring_owner() + class StoreRows: """The marker a store's rows inherit; the store names it once and derives its rows.""" diff --git a/src/agent_comms/task_attachments/team_pings.py b/src/agent_comms/task_attachments/team_pings.py index c0fdf05e2b..1894406b20 100644 --- a/src/agent_comms/task_attachments/team_pings.py +++ b/src/agent_comms/task_attachments/team_pings.py @@ -420,8 +420,7 @@ def delivery(self, recipient: ThreadIncarnation, *, delivery: type[HeartbeatDelivery] = OnHeartbeatDelivery) -> TeamDelivery: """Only the recipient's actual publications decide which lines are new.""" announced = {ping.key: ping for packet in published for ping in packet.handled} - new = (tuple(ping for ping in self.handled if announced.get(ping.key) != ping) - if delivery.publishes() else ()) + new = (delivery.published_entries(self, announced)) wakes = delivery.publishes() and ( self.open_wakes or any(not ping.parked(self.stopped_threads) for ping in new) ) diff --git a/src/agent_comms/team/team_heartbeat.py b/src/agent_comms/team/team_heartbeat.py index 1875d01ea7..d353f390d8 100644 --- a/src/agent_comms/team/team_heartbeat.py +++ b/src/agent_comms/team/team_heartbeat.py @@ -43,6 +43,7 @@ TeamInputs, ) from agent_comms.team.team_hud import ( + PreviousTeamHud, RetainedTeamBoard, TeamBoardPublicationStore, TeamHud, @@ -356,7 +357,7 @@ def pass_body( plan = TeamPlan(board.phases) for delivery in deliveries: hud = board.for_delivery(delivery).retaining_rendering( - retained_huds.get(delivery.packet.teammate) + PreviousTeamHud.from_optional(retained_huds.get(delivery.packet.teammate)) ) recipient = delivery.packet.teammate huds[recipient] = hud diff --git a/src/agent_comms/team/team_hud.py b/src/agent_comms/team/team_hud.py index 9677fe5a15..14a7f54286 100644 --- a/src/agent_comms/team/team_hud.py +++ b/src/agent_comms/team/team_hud.py @@ -4,6 +4,7 @@ import threading import time +from abc import ABC, abstractmethod from collections.abc import Mapping from dataclasses import dataclass, field, replace from functools import cached_property @@ -241,6 +242,47 @@ class TeamHudRecord(TeamLoad): """The team plan's phases, read from the atomic board publication with the frame, never stored in it.""" +class PreviousTeamHud(ABC): + """An optional previous HUD snapshot whose unchanged derived renders may be retained.""" + + @abstractmethod + def retaining_rendering(self, owner: TeamHud) -> TeamHud: + ... + + @classmethod + def from_optional(cls, value: TeamHud | None) -> PreviousTeamHud: + return AbsentPreviousTeamHud() if value is None else HeldPreviousTeamHud(value) + + +@dataclass(frozen=True) +class AbsentPreviousTeamHud(PreviousTeamHud): + """Absent `PreviousTeamHud` carrying no value.""" + + def retaining_rendering(self, owner: TeamHud) -> TeamHud: + return owner + + +@dataclass(frozen=True) +class HeldPreviousTeamHud(PreviousTeamHud): + """Held `PreviousTeamHud` carrying its present value.""" + + value: TeamHud + + def retaining_rendering(self, owner: TeamHud) -> TeamHud: + if owner == self.value: + for name in ('groups', 'plain_group_text'): + if name in self.value.__dict__: + object.__setattr__(owner, name, self.value.__dict__[name]) + same_alarms = owner.alarm_source == self.value.alarm_source + if same_alarms: + for name in ('alarm_displays', 'alarms'): + if name in self.value.__dict__: + object.__setattr__(owner, name, self.value.__dict__[name]) + if owner.display == self.value.display: + object.__setattr__(owner, 'display', self.value.display) + return owner + + @dataclass(frozen=True) class TeamHud(TeamHudRecord): """One disposable view of native records, shared by comms_hud and the team board. @@ -405,26 +447,13 @@ def for_delivery(self, delivery: TeamDelivery) -> TeamHud: object.__setattr__(hud, "display", self.display) return hud - def retaining_rendering(self, previous: TeamHud | None) -> TeamHud: + def retaining_rendering(self, previous: PreviousTeamHud) -> TeamHud: """Carry each derived owner only when its complete source remains unchanged. Service completion clocks remain fresh on ``self``. Recipient-neutral display sources retain their facts and folded words independently of dispatch binding. """ - if previous is None: - return self - if self == previous: - for name in ("groups", "plain_group_text"): - if name in previous.__dict__: - object.__setattr__(self, name, previous.__dict__[name]) - same_alarms = self.alarm_source == previous.alarm_source - if same_alarms: - for name in ("alarm_displays", "alarms"): - if name in previous.__dict__: - object.__setattr__(self, name, previous.__dict__[name]) - if self.display == previous.display: - object.__setattr__(self, "display", previous.display) - return self + return previous.retaining_rendering(self) @cached_property def board(self) -> tuple[BoardEntry, ...]: diff --git a/src/agent_comms/transport/native_tool_transport.py b/src/agent_comms/transport/native_tool_transport.py index fb497ea233..cffee9ff56 100644 --- a/src/agent_comms/transport/native_tool_transport.py +++ b/src/agent_comms/transport/native_tool_transport.py @@ -19,11 +19,13 @@ from agent_comms.coordination.database import CoordinationStore from agent_comms.errors import RelationViolationError from agent_comms.execution.async_retirement import join_retirement +from agent_comms.execution.pi_events import ToolExecutionEnd, ToolExecutionStart from agent_comms.messaging.message_files import MAX_SEND_REQUEST_BYTES from agent_comms.nominal.field_codec import FieldCodec, InputId, MalformedRecord, Token256Text from agent_comms.nominal.lifecycle_capability import Complete from agent_comms.pi_payloads import AssistantMessage from agent_comms.storage.private_path import PrivateDirectoryRole, PrivateSocketRole +from agent_comms.team.pi_rule_gate import PiRuleGate from agent_comms.transport.native_tool_call import ( DuplicateToolCallIdentity, NativeToolCall, @@ -36,8 +38,6 @@ if TYPE_CHECKING: from agent_comms.execution.backend import TurnSession - from agent_comms.execution.pi_events import ToolExecutionEnd, ToolExecutionStart - from agent_comms.team.pi_rule_gate import PiRuleGate _LOG = logging.getLogger(__name__) diff --git a/src/agent_comms/ui_model/sidebar.py b/src/agent_comms/ui_model/sidebar.py index 5589505bed..8d4c2a9208 100644 --- a/src/agent_comms/ui_model/sidebar.py +++ b/src/agent_comms/ui_model/sidebar.py @@ -281,7 +281,7 @@ def derive(snapshot: CoordinationSnapshot) -> tuple[dict[str, ChannelRowModel], threads = {name: ThreadRowModel.of( person, person.thread.prepare_conversation(PersonUnread(person, snapshot))) for name, person in snapshot.threads.items()} - working = frozenset(name for name, row in threads.items() if row.status.is_working()) + working = frozenset(_item for name, row in threads.items() for _item in row.status.include_as_working(name)) channels = {name: ChannelRowModel.of(view, snapshot, working) for name, view in snapshot.channels.items()} return channels, threads diff --git a/tests/test_agent_backend.py b/tests/test_agent_backend.py index eb56fd0bf4..82d8534121 100644 --- a/tests/test_agent_backend.py +++ b/tests/test_agent_backend.py @@ -32,7 +32,12 @@ from agent_comms.pi_native_backend import PI_0_85_1_EVENT_KINDS, PiNativeBackend, PiSessionFile from agent_comms.projects.checkouts import Checkout from agent_comms.registry.thread_model import DeclaredModel -from agent_comms.registry.threads import ExternalThread, NativeThread, Thread +from agent_comms.registry.threads import ( + ExternalThread, + NativeThread, + PreviousThreadRegistration, + Thread, +) from agent_comms.transport.serving.owner_launch import ServedReadNativeChildProcessRuntimeRequest # -- registry --------------------------------------------------------------- @@ -237,7 +242,7 @@ def test_thread_declares_its_backend_once_and_keeps_it_on_reregistration(*, thre assert FieldCodec.decode(Thread, {**encoded, "backend": "pi_native"}) == thread with pytest.raises(ValueError): FieldCodec.decode(Thread, {**encoded, "runtime": {"backend": "pi_durable", "location": None}}) - assert thread.for_registration("owner", thread).backend is PiNativeBackend + assert thread.for_registration("owner", PreviousThreadRegistration.from_optional(thread)).backend is PiNativeBackend external = thread_registration.declare( ExternalThread("ext", frozenset(), Checkout(Path("/tmp/ext"))) @@ -248,7 +253,7 @@ def test_thread_declares_its_backend_once_and_keeps_it_on_reregistration(*, thre assert "backend" not in ext_encoded assert FieldCodec.decode(Thread, ext_encoded) == external assert FieldCodec.decode(Thread, {**ext_encoded, "backend": "cli_inbox"}) == external - assert external.for_registration("ext", external).backend is CliInboxBackend + assert external.for_registration("ext", PreviousThreadRegistration.from_optional(external)).backend is CliInboxBackend def test_cli_registry_reads_do_not_load_the_pi_runtime(tmp_path): diff --git a/tests/test_board_freshness.py b/tests/test_board_freshness.py index d1f6c57638..7b1e5a2a40 100644 --- a/tests/test_board_freshness.py +++ b/tests/test_board_freshness.py @@ -21,6 +21,7 @@ TodoStore, ) from agent_comms.presentation import WireRevision +from agent_comms.team.team_hud import PreviousTeamHud from agent_comms.task_attachments.owner_notices import VibeCheckNotice from agent_comms.task_attachments.team_pings import ( AlarmDisplay, @@ -234,7 +235,7 @@ def test_steady_heartbeat_retains_its_board_derivations(held_bus, account_read, open_pings=(changed_ping, *rendered.open_pings[1:]), ) assert changed == rendered # Occurrence evidence is deliberately outside ping equality. - changed.retaining_rendering(rendered) + changed.retaining_rendering(PreviousTeamHud.from_optional(rendered)) assert changed.alarms is not rendered.alarms changed_huds = tuple( diff --git a/tests/test_mcp_relay.py b/tests/test_mcp_relay.py index 6dce2f02f3..0429da8e75 100644 --- a/tests/test_mcp_relay.py +++ b/tests/test_mcp_relay.py @@ -6,7 +6,7 @@ import pytest from agent_comms.execution.owner_protocol import OwnerLine, OwnerPermissionRequest -from agent_comms.execution.pi_wire import McpLiveAcknowledgement +from agent_comms.execution.pi_wire import LiveStatusClaim, McpLiveAcknowledgement from agent_comms.nominal.field_codec import FieldCodec from agent_comms.transport.runtime_server import SocketClient @@ -32,24 +32,34 @@ def test_live_receipt_rejects_stale_input_malformed_and_ambiguous_claims(): ], } - assert McpLiveAcknowledgement.from_status(json.dumps(valid), input_id) == FieldCodec.decode( + assert McpLiveAcknowledgement.from_status( + LiveStatusClaim.from_optional(json.dumps(valid)), input_id + ) == FieldCodec.decode( McpLiveAcknowledgement, valid, ) - assert McpLiveAcknowledgement.from_status(json.dumps(valid), "b" * 32) is None + assert McpLiveAcknowledgement.from_status( + LiveStatusClaim.from_optional(json.dumps(valid)), "b" * 32 + ) is None assert ( McpLiveAcknowledgement.from_status( - json.dumps(valid).replace('"version": 1', '"version": 1, "version": 1'), + LiveStatusClaim.from_optional( + json.dumps(valid).replace('"version": 1', '"version": 1, "version": 1') + ), input_id, ) is None ) valid["servers"][0]["calls"] = "automatic" valid["servers"][0]["state"] = "denied" - assert McpLiveAcknowledgement.from_status(json.dumps(valid), input_id) is None + assert McpLiveAcknowledgement.from_status( + LiveStatusClaim.from_optional(json.dumps(valid)), input_id + ) is None valid["servers"][0]["calls"] = "unavailable" valid["servers"][0]["id"] = "\x1b[2J" - assert McpLiveAcknowledgement.from_status(json.dumps(valid), input_id) is None + assert McpLiveAcknowledgement.from_status( + LiveStatusClaim.from_optional(json.dumps(valid)), input_id + ) is None async def test_explicit_owner_cancellation_is_not_swallowed_by_socket_permission(): diff --git a/tests/test_registration_inheritance.py b/tests/test_registration_inheritance.py index 10642012b2..2dbf0546b1 100644 --- a/tests/test_registration_inheritance.py +++ b/tests/test_registration_inheritance.py @@ -19,12 +19,12 @@ from agent_comms.projects.checkouts import Checkout from agent_comms.registry.thread_model import DeclaredModel from agent_comms.registry.thread_text import GivenThreadText -from agent_comms.registry.threads import NativeThread, Thread +from agent_comms.registry.threads import NativeThread, PreviousThreadRegistration, Thread def test_unchanged_registration_retains_creation_allocation(): incoming = NativeThread('fresh', frozenset(), Checkout(Path('/wt'))) - assert incoming.for_registration("fresh", None) is incoming + assert incoming.for_registration("fresh", PreviousThreadRegistration.from_optional(None)) is incoming renamed = incoming.for_claim("allocated") assert renamed.created_at is incoming.created_at assert renamed.created_at.distinct_from({incoming.created_at}) > incoming.created_at @@ -43,9 +43,9 @@ class CountedThread(Thread): previous = CountedThread('owner', frozenset(), '/wt', created_at=42.0, count=9, storage_roots=thread_registration.storage_rule.initial_roots('owner')) omitted = replace(previous, count=-1) - assert omitted.for_registration("owner", previous) == previous + assert omitted.for_registration("owner", PreviousThreadRegistration.from_optional(previous)) == previous explicit = replace(previous, count=0) - assert explicit.for_registration("owner", previous) is explicit + assert explicit.for_registration("owner", PreviousThreadRegistration.from_optional(previous)) is explicit def test_registry_redeclaration_inherits_metadata_but_respects_explicit_values(tmp_path): diff --git a/tests/test_team_notifications.py b/tests/test_team_notifications.py index 9db11fb62a..aa4a68963a 100644 --- a/tests/test_team_notifications.py +++ b/tests/test_team_notifications.py @@ -33,6 +33,7 @@ from agent_comms.messaging.channel_targets import TeammatesTag, ThreadTarget from agent_comms.messaging.initial_origin import HumanOrigin from agent_comms.messaging.message_page import MessagePageRequest +from agent_comms.registry.threads import PreviousThreadRegistration from agent_comms.messaging.messages import ConversationRole, InfoKind, Message from agent_comms.messaging.read_basis import DMDisplayScope from agent_comms.nominal.field_codec import FieldCodec, OrderId @@ -152,7 +153,7 @@ def test_heartbeat_delivery_preserves_membership_board_history_and_direct_messag assert result.delivery is selected.heartbeat_delivery is mode assert selected == replace(original, heartbeat_delivery=mode) assert FieldCodec.decode(Thread, FieldCodec.encode(selected)) == selected - assert selected.for_registration(selected.name, selected).heartbeat_delivery is mode + assert selected.for_registration(selected.name, PreviousThreadRegistration.from_optional(selected)).heartbeat_delivery is mode assert selected in comms.registry.snapshot().team_project.colleagues(comms.registry.snapshot()) now = time.time()