From 8a940ddb1c83120f94d0ed34dbb434d10cb28433 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 28 Nov 2026 12:22:14 -0500 Subject: [PATCH] Apply NRA Wave 5: 48 mechanical P51/P38/P39 recipes (53 findings) --- src/agent_comms/acp_extension.py | 16 +++++++----- .../cli_bridges/claude_protocol.py | 18 ++++++------- .../cli_bridges/claude_transcript.py | 2 +- src/agent_comms/cli_bridges/cli_protocol.py | 2 +- src/agent_comms/cli_bridges/codex_protocol.py | 16 ++++++------ src/agent_comms/cli_bridges/codex_records.py | 7 +++-- src/agent_comms/cli_bridges/opencode_parts.py | 14 +++++----- .../cli_bridges/opencode_protocol.py | 4 +-- src/agent_comms/cli_bridges/shared.py | 2 +- src/agent_comms/execution/child_process.py | 15 +++++++---- src/agent_comms/execution/tracked_turn.py | 19 ++++++++------ .../execution/transcript_sources.py | 11 +++++--- src/agent_comms/execution/turn_phase.py | 13 +++++----- src/agent_comms/installer/upgrade.py | 15 ++++++----- src/agent_comms/messaging/bus_read.py | 8 +++--- .../messaging/notification_progress.py | 26 ++++++++++--------- src/agent_comms/messaging/task_sources.py | 21 +++++++++------ src/agent_comms/projects/head_review.py | 18 ++++++------- src/agent_comms/registry/thread_model.py | 14 ++-------- src/agent_comms/registry/thread_text.py | 11 ++++++-- .../transcript/external_transcript_rows.py | 8 +++++- src/agent_comms/transport/background_runs.py | 15 ++++++----- .../transport/connector_profile.py | 10 +++++-- src/agent_comms/transport/connector_store.py | 6 ++--- .../transport/serving/served_requests.py | 6 ++--- src/agent_comms/transport/zmq_comms_server.py | 25 +++++++++--------- tools/repairs.py | 6 ++--- 27 files changed, 177 insertions(+), 151 deletions(-) diff --git a/src/agent_comms/acp_extension.py b/src/agent_comms/acp_extension.py index 80ef66c292..a4fb00e2ce 100644 --- a/src/agent_comms/acp_extension.py +++ b/src/agent_comms/acp_extension.py @@ -145,13 +145,19 @@ def needs_refresh(self) -> bool: return True -@dataclass(frozen=True) -class UnavailableCursorObservation(StaleCursorObservation): +class UnavailableExtensionStatus: + """An ACP extension status that reports unavailable.""" + @property def status(self) -> str: return "unavailable" +@dataclass(frozen=True) +class UnavailableCursorObservation(UnavailableExtensionStatus, StaleCursorObservation): + pass + + @dataclass(frozen=True) class EmptyCursorObservation(StaleCursorObservation): @property @@ -322,11 +328,7 @@ def feedback(self, supported: bool) -> str: @dataclass(frozen=True) -class UnavailableQueueProjection(QueueProjection): - @property - def status(self) -> str: - return "unavailable" - +class UnavailableQueueProjection(UnavailableExtensionStatus, QueueProjection): def feedback(self, supported: bool) -> str: return "Remote queue unavailable (input status unchanged)" diff --git a/src/agent_comms/cli_bridges/claude_protocol.py b/src/agent_comms/cli_bridges/claude_protocol.py index 0b6fba4263..22482809ad 100644 --- a/src/agent_comms/cli_bridges/claude_protocol.py +++ b/src/agent_comms/cli_bridges/claude_protocol.py @@ -722,7 +722,7 @@ def tally(self, ledger: SessionLedger) -> None: """What this record adds to the session's ledger; most records add nothing.""" -class AssistantBlock(TaggedWire, ABC, affix="", declared_name=None): +class AssistantBlock(TaggedWire, affix="", declared_name=None): @classmethod def undeclared_tag(cls, tag: str) -> str: @@ -877,7 +877,7 @@ def subagent_progress(self) -> tuple[SubagentProgress, ...]: for progress in block.subagent_progress(self)) -class ResultPart(TaggedWire, ABC, affix=""): +class ResultPart(TaggedWire, affix=""): @abstractmethod def result_text(self) -> str: ... @@ -902,7 +902,7 @@ class KindHeader(WireHeader): type: str = Field(alias='kind') -class PromptOrigin(TaggedWire, ABC, affix=""): +class PromptOrigin(TaggedWire, affix=""): """Who wrote a prompt. Only a person's prompt is shown live as input; another agent's message is conversation history the live view hides.""" header = KindHeader @@ -928,7 +928,7 @@ def delivered(self, text: str) -> tuple[MessageReference, ...]: return () -class Prompting(PromptOrigin, ABC, declared_name=None): +class Prompting(PromptOrigin, declared_name=None): """An origin whose text is a request to the model.""" def request(self, text: str) -> str: @@ -1008,7 +1008,7 @@ def delivered(self) -> tuple[MessageReference, ...]: return self.origin.delivered(self.prompt_text()) -class UserBlock(TaggedWire, ABC, affix=""): +class UserBlock(TaggedWire, affix=""): def ends_turn(self) -> bool: return False @@ -1188,7 +1188,7 @@ def text(self) -> str: return '\n'.join(text for block in self.content if (text := block.prompt_text())) -class PromptRecord(ClaudeRecord, TimedRecord, ABC, declared_name=None): +class PromptRecord(ClaudeRecord, TimedRecord, declared_name=None): """The first prompt after retirement owns the turn; promptId may be reused.""" promptId: NativeTurnId @@ -1270,7 +1270,7 @@ class SubtypeHeader(WireHeader): type: str = Field(alias='subtype') -class SystemEvent(TaggedWire, ABC, affix=""): +class SystemEvent(TaggedWire, affix=""): header = SubtypeHeader @classmethod @@ -1413,7 +1413,7 @@ def ends_turn(self) -> bool: return self.subtype.ends_turn() -class MetadataRecord(ClaudeRecord, ABC, declared_name=None): +class MetadataRecord(ClaudeRecord, declared_name=None): pass @@ -1425,7 +1425,7 @@ class DataFlowRecords(MetadataRecord, declared_name="data-flow-records"): """The harness's own record of which tools moved data; no model input or turn boundary.""" -class AttachmentPayload(OpenWire, ABC, affix=""): +class AttachmentPayload(OpenWire, affix=""): @abstractmethod def updates(self, record: TimedRecord, session: ClaudeSession) -> tuple[RuntimeUpdate, ...]: ... diff --git a/src/agent_comms/cli_bridges/claude_transcript.py b/src/agent_comms/cli_bridges/claude_transcript.py index 2eaf64ac84..b2759c7094 100644 --- a/src/agent_comms/cli_bridges/claude_transcript.py +++ b/src/agent_comms/cli_bridges/claude_transcript.py @@ -257,7 +257,7 @@ class LedgerFields(WatchReportFields): ledger: PrintLedgerId -class WatchReport(WatchReportFields, TaggedWire, ABC, affix="", declared_name=None): +class WatchReport(WatchReportFields, TaggedWire, affix="", declared_name=None): """What a watch client says up its socket besides its transcript: the messages it may have shown. A reference is written to the client's ledger before its event is printed, so the ledger can only overstate what was shown; a message missing from it was never printed.""" diff --git a/src/agent_comms/cli_bridges/cli_protocol.py b/src/agent_comms/cli_bridges/cli_protocol.py index 4b428d58b1..d961da5f27 100644 --- a/src/agent_comms/cli_bridges/cli_protocol.py +++ b/src/agent_comms/cli_bridges/cli_protocol.py @@ -131,7 +131,7 @@ def __get_pydantic_core_schema__( return handler(family.declared_union()) -class OpenWire(TaggedWire, ABC, declared_name=None): +class OpenWire(TaggedWire, declared_name=None): """A family whose source adds kinds freely: a tag it does not declare decodes as its member tagged 'foreign', which carries no conversation.""" diff --git a/src/agent_comms/cli_bridges/codex_protocol.py b/src/agent_comms/cli_bridges/codex_protocol.py index f3a89a82a9..88611189fa 100644 --- a/src/agent_comms/cli_bridges/codex_protocol.py +++ b/src/agent_comms/cli_bridges/codex_protocol.py @@ -75,7 +75,7 @@ from agent_comms.transport.tool_declaration import ToolDeclaration -class UserInput(TaggedWire, ABC, affix=""): +class UserInput(TaggedWire, affix=""): @property @abstractmethod @@ -258,7 +258,7 @@ class ResumeThread(RequestParams): excludeTurns: bool = True -class ThreadStatus(TaggedWire, ABC, affix=""): +class ThreadStatus(TaggedWire, affix=""): """What Codex says its thread is doing; the bridge reports it on attaching.""" def update(self) -> RuntimeUpdate: @@ -378,7 +378,7 @@ def route(self, connection: RpcReplyTarget) -> None: RPC_RESPONSE = WireModel.adapter(RpcSuccess | RpcRequestFailure | RpcConnectionFailure | RpcNotification) -class Item(TaggedWire, ABC, affix=""): +class Item(TaggedWire, affix=""): wire_tag: ClassVar[str] @classmethod @@ -471,7 +471,7 @@ def completed( return self.clientId.completed(self, turn_id, events) -class ToolItem(ToolCallItem, Item, ABC): +class ToolItem(ToolCallItem, Item): def accumulator(self, started_at: EventTime) -> ToolDraft: return ToolDraft(started_at, (self.call.started(self.id, started_at.recorded_at('Codex tool start')),)) @@ -531,7 +531,7 @@ def succeeded(self) -> bool: return self.status == 'completed' and self.exitCode == 0 -class ToolContentPart(TaggedWire, ABC, affix=""): +class ToolContentPart(TaggedWire, affix=""): @property @abstractmethod @@ -733,7 +733,7 @@ def phase(self) -> TurnPhase: return ToolRunningPhase(tools=((self.call_id, f'Searching: {self.query}'),)) -class PatchChange(TaggedWire, ABC, affix=""): +class PatchChange(TaggedWire, affix=""): @abstractmethod def patch(self, path: str, content: str) -> ToolDiff | NoToolDiff: ... @@ -936,7 +936,7 @@ def apply(self, stream: ItemStream) -> RuntimeUpdate: return self.turn.finished() -class ItemNotification(TranscriptNotification, ABC): +class ItemNotification(TranscriptNotification): turnId: str @property @@ -963,7 +963,7 @@ def apply(self, stream: ItemStream) -> RuntimeUpdate: completedAtMs=self.completedAtMs).publication() -class TextDelta(ItemNotification, ABC, declared_name=None): +class TextDelta(ItemNotification, declared_name=None): item_id: NativeItemId = Field(alias='itemId') delta: str def section(self) -> int: diff --git a/src/agent_comms/cli_bridges/codex_records.py b/src/agent_comms/cli_bridges/codex_records.py index 81c7a4dbaa..5ec4de94f4 100644 --- a/src/agent_comms/cli_bridges/codex_records.py +++ b/src/agent_comms/cli_bridges/codex_records.py @@ -4,7 +4,6 @@ import hashlib import json -from abc import ABC from dataclasses import ( dataclass, field, @@ -90,7 +89,7 @@ def role(cls, value: dict) -> dict: return {'type': '/'.join(part for part in (value.get('type'), value.get('role')) if part)} -class RolloutItem(OpenWire, ABC, affix=""): +class RolloutItem(OpenWire, affix=""): header = RolloutItemHeader def updates(self, state: RolloutState, position: int, timestamp: float) -> tuple[RuntimeUpdate, ...]: @@ -107,7 +106,7 @@ class ForeignItem(RolloutItem, declared_name='foreign'): """Reasoning, searches and other items that are not portable conversation.""" -class MessageItem(RolloutItem, ABC, declared_name=None): +class MessageItem(RolloutItem, declared_name=None): content: list[ContentPart] @field_validator('content', mode='before') @@ -135,7 +134,7 @@ def updates(self, state: RolloutState, position: int, timestamp: float) -> tuple return (HiddenItem((AssistantTranscript(self.text, position=position, timestamp=timestamp),)),) -class InstructionMessage(MessageItem, ABC, declared_name=None): +class InstructionMessage(MessageItem, declared_name=None): """Instructions the source session ran under: kept as references to their bytes, never as messages, because they were that session's instructions and are not this thread's.""" diff --git a/src/agent_comms/cli_bridges/opencode_parts.py b/src/agent_comms/cli_bridges/opencode_parts.py index d4c0514e1c..e0227fa525 100644 --- a/src/agent_comms/cli_bridges/opencode_parts.py +++ b/src/agent_comms/cli_bridges/opencode_parts.py @@ -2,7 +2,7 @@ from __future__ import annotations import builtins -from abc import ABC, abstractmethod +from abc import abstractmethod from typing import ClassVar, Literal from pydantic import ConfigDict, Field, JsonValue, model_validator @@ -63,7 +63,7 @@ def summary(cls, value: dict) -> dict: return {'type': value.get('role')} -class MessageInfo(TaggedWire, ABC, affix=""): +class MessageInfo(TaggedWire, affix=""): header = RoleHeader id: str sessionID: str @@ -109,7 +109,7 @@ def present(self, part: Part) -> tuple[RuntimeUpdate, ...]: return (*part.present(self), *part.summarized()) -class Part(TaggedWire, ABC, affix=""): +class Part(TaggedWire, affix=""): id: NativeItemId sessionID: str messageID: str @@ -137,7 +137,7 @@ class PartTime(WireModel): end: int | float | None = None -class TextualPart(Part, ABC, declared_name=None): +class TextualPart(Part, declared_name=None): text: str time: PartTime | None = None event_type: ClassVar[builtins.type[LiveTextTranscript]] @@ -190,7 +190,7 @@ class StatusHeader(WireHeader): type: str = Field(alias='status') -class ToolState(TaggedWire, ABC, affix=""): +class ToolState(TaggedWire, affix=""): header = StatusHeader input: ToolArguments def is_finished(self) -> bool: @@ -229,7 +229,7 @@ class EndedPartTime(PartTime): end: int | float = Field(...) -class EndedTool(ToolState, ABC): +class EndedTool(ToolState): time: EndedPartTime ok: ClassVar[bool] def is_finished(self) -> bool: @@ -277,7 +277,7 @@ def present(self, message: AssistantMessage) -> tuple[RuntimeUpdate, ...]: return self.state.present(self, message) -class StructuralPart(Part, ABC, declared_name=None): +class StructuralPart(Part, declared_name=None): """Native bookkeeping and input attachments are not assistant transcript items.""" def present(self, message: AssistantMessage) -> tuple[RuntimeUpdate, ...]: return () diff --git a/src/agent_comms/cli_bridges/opencode_protocol.py b/src/agent_comms/cli_bridges/opencode_protocol.py index 7ed59342c0..3309ea7693 100644 --- a/src/agent_comms/cli_bridges/opencode_protocol.py +++ b/src/agent_comms/cli_bridges/opencode_protocol.py @@ -1,7 +1,7 @@ """OpenCode's session events drive both input confirmation and live output.""" from __future__ import annotations -from abc import ABC, abstractmethod +from abc import abstractmethod from collections.abc import Iterable, Iterator from itertools import takewhile from typing import TYPE_CHECKING, ClassVar, Literal @@ -88,7 +88,7 @@ class SessionError(WireModel): error: NativeError | None = None -class SessionStatus(TaggedWire, ABC, affix=""): +class SessionStatus(TaggedWire, affix=""): @abstractmethod def publication(self) -> RuntimeUpdate: ... diff --git a/src/agent_comms/cli_bridges/shared.py b/src/agent_comms/cli_bridges/shared.py index d64619b84e..a60e3052ec 100644 --- a/src/agent_comms/cli_bridges/shared.py +++ b/src/agent_comms/cli_bridges/shared.py @@ -1633,7 +1633,7 @@ class DirectDeliveryBridge(TranscriptBridge[BridgeOptions]): """A message reference on our wire lines, in the one spelling FieldCodec gives it.""" -class MonitorFrame(TaggedWire, ABC, affix=""): +class MonitorFrame(TaggedWire, affix=""): """Our line protocol inside the harness's task-notification envelope.""" async def confirm( self, bridge: TranscriptConfirmsDelivery, record: ObservedMonitor, diff --git a/src/agent_comms/execution/child_process.py b/src/agent_comms/execution/child_process.py index 633fa1457c..e1104a0574 100644 --- a/src/agent_comms/execution/child_process.py +++ b/src/agent_comms/execution/child_process.py @@ -699,9 +699,18 @@ def from_returncode(cls, code: int) -> ChildOutcome: @dataclass(frozen=True) -class ExitedOutcome(ChildOutcome): +class ExitCodeSummary: + """A process exit outcome carrying its integer exit code and summary.""" + code: int + @property + def summary(self) -> str: + return f"exited with code {self.code}" + + +@dataclass(frozen=True) +class ExitedOutcome(ExitCodeSummary, ChildOutcome): def printed_count(self, stdout: bytes) -> CheckPrinted: return CheckPrinted.decoded(stdout) @@ -709,10 +718,6 @@ def report_stopped(self, report: Callable[[], None], stop_exits: frozenset[int]) if self.code in stop_exits: report() - @property - def summary(self) -> str: - return f"exited with code {self.code}" - @property def successful(self) -> bool: return self.code == 0 diff --git a/src/agent_comms/execution/tracked_turn.py b/src/agent_comms/execution/tracked_turn.py index b1769e08c9..9e34dcec9f 100644 --- a/src/agent_comms/execution/tracked_turn.py +++ b/src/agent_comms/execution/tracked_turn.py @@ -161,8 +161,8 @@ def keep_response(self): return NotifiedTrackedTerminal(self.text) -class NotificationTrackedTerminal(NotificationIgnoringTerminal): - """Notice handling cannot answer or revise the original requested task.""" +class UnansweredTrackedTerminal: + """A tracked terminal turn outcome that produced no answer.""" def answered(self, text: str) -> TrackedTerminal: return self @@ -170,6 +170,13 @@ def answered(self, text: str) -> TrackedTerminal: def empty_answer(self) -> TrackedTerminal: return self + +class NotificationTrackedTerminal( + UnansweredTrackedTerminal, + NotificationIgnoringTerminal, +): + """Notice handling cannot answer or revise the original requested task.""" + def tool_round(self): return self @@ -184,12 +191,8 @@ def empty_answer(self) -> TrackedTerminal: return EmptyAnswerTrackedTerminal() -class AmbiguousTrackedTerminal(PendingTrackedTerminal): - def answered(self, text: str) -> TrackedTerminal: - return self - - def empty_answer(self) -> TrackedTerminal: - return self +class AmbiguousTrackedTerminal(UnansweredTrackedTerminal, PendingTrackedTerminal): + pass class TrackedTurnSession(TurnSession, FollowingTurnSource[OwnedSend]): diff --git a/src/agent_comms/execution/transcript_sources.py b/src/agent_comms/execution/transcript_sources.py index aaabc026fa..40119cdd8b 100644 --- a/src/agent_comms/execution/transcript_sources.py +++ b/src/agent_comms/execution/transcript_sources.py @@ -83,6 +83,7 @@ NoEarlierPage, NoItems, ReplyWindow, + TranscriptItemRow, ) from agent_comms.transcript.transcript_drafts import NoDraft, TranscriptDraft from agent_comms.transcript.transcript_events import ( @@ -874,12 +875,14 @@ def stored(cls, connection: Connection) -> tuple[RetiredDraftRow, ...]: @dataclass(frozen=True) -class DraftAppendRow(ExternalTranscriptRows, TypedTable, declared_name="external_draft_append"): +class DraftAppendRow( + TranscriptItemRow, + ExternalTranscriptRows, + TypedTable, + declared_name="external_draft_append", +): """One ordered event append for one live draft message.""" - thread: Annotated[ThreadLookup, Column(primary_key=True)] - turn_id: Annotated[NativeTurnId, Column(primary_key=True)] - item_id: Annotated[NativeItemId, Column(primary_key=True)] ordinal: Annotated[int, Column(primary_key=True)] event: TranscriptEvent diff --git a/src/agent_comms/execution/turn_phase.py b/src/agent_comms/execution/turn_phase.py index 13636df039..48cfe8eadf 100644 --- a/src/agent_comms/execution/turn_phase.py +++ b/src/agent_comms/execution/turn_phase.py @@ -44,12 +44,16 @@ class AcceptsPrompt: """A native observation proves that Pi accepted the current prompt.""" -class ClosingTurn: - """Native tail observations cannot reopen a closing turn.""" +class NoFollowupTurnPhase: + """A turn phase capability that refuses follow-up prompts.""" def accepts_followup(self) -> bool: return False + +class ClosingTurn(NoFollowupTurnPhase): + """Native tail observations cannot reopen a closing turn.""" + def can_cancel(self) -> bool: return False @@ -181,12 +185,9 @@ class PreparingPhase(TurnPhase): label = "Preparing input" -class NonFollowupTurnPhase(TurnPhase, declared_name=None): +class NonFollowupTurnPhase(NoFollowupTurnPhase, TurnPhase, declared_name=None): """A turn phase that does not accept follow-up prompts.""" - def accepts_followup(self) -> bool: - return False - class IdlePhase(ActivityWord, NonFollowupTurnPhase): busy = False diff --git a/src/agent_comms/installer/upgrade.py b/src/agent_comms/installer/upgrade.py index 7a6d40d745..33aa5448ec 100644 --- a/src/agent_comms/installer/upgrade.py +++ b/src/agent_comms/installer/upgrade.py @@ -176,8 +176,8 @@ @dataclass(frozen=True) -class ObservedInstall(UnfinishedInstall): - """A live result returned before harness registration or cleanup can fail.""" +class ObservedLiveInstall: + """An install result carrying a live run and its formatted output lines.""" live: LiveRun @@ -185,6 +185,11 @@ def live_lines(self) -> tuple[str, ...]: return self.live.lines() +@dataclass(frozen=True) +class ObservedInstall(ObservedLiveInstall, UnfinishedInstall): + """A live result returned before harness registration or cleanup can fail.""" + + @dataclass(frozen=True) class FinishedInstall(InstallOutcome): result: RehearsedUpgrade @@ -474,8 +479,7 @@ def lines(self) -> tuple[str, ...]: @dataclass(frozen=True) -class InstalledUpgrade(RehearsedUpgrade, Extendable): - live: LiveRun +class InstalledUpgrade(ObservedLiveInstall, RehearsedUpgrade, Extendable): install: InstallResult """The harnesses registered on the bus the target now reads.""" processes: RuntimeProcesses = field(kw_only=True, default=RuntimeProcesses(())) @@ -490,9 +494,6 @@ class InstalledUpgrade(RehearsedUpgrade, Extendable): finished: ClassVar[str] = "Install finished" """The headline of the post that reports this upgrade.""" - def live_lines(self) -> tuple[str, ...]: - return self.live.lines() - def lines(self) -> tuple[str, ...]: return (*super().lines(), *self.live_lines(), *self.processes.lines(), self.retirement.line(), diff --git a/src/agent_comms/messaging/bus_read.py b/src/agent_comms/messaging/bus_read.py index de0856e7ea..62019b5ebb 100644 --- a/src/agent_comms/messaging/bus_read.py +++ b/src/agent_comms/messaging/bus_read.py @@ -1,10 +1,7 @@ from __future__ import annotations import asyncio -from abc import ( - ABC, - abstractmethod, -) +from abc import abstractmethod from collections.abc import Callable from dataclasses import dataclass from functools import partial @@ -60,7 +57,8 @@ def apply(self, comms: BusContext, caller: ReadAuthority) -> TranscriptSnapshotU class OwnerScopedRead[Result: ToolResult = ToolResult]( - BusRead[Result], ThreadReadTool[Result], ABC, + BusRead[Result], + ThreadReadTool[Result], ): """The captured registration selects live evidence or the declared unavailable answer.""" diff --git a/src/agent_comms/messaging/notification_progress.py b/src/agent_comms/messaging/notification_progress.py index 9ad8efa764..f9bd62a6cd 100644 --- a/src/agent_comms/messaging/notification_progress.py +++ b/src/agent_comms/messaging/notification_progress.py @@ -230,7 +230,14 @@ def summary_counts(self, *, displayed: bool = False) -> DeliverySummaryCounts: return DeliverySummaryCounts(read=1) -class ConsumedDelivery(ReadDelivery): +class OfflineVisibleDelivery: + """A delivery progress state that remains visible when the peer is offline.""" + + def shown_when_offline(self) -> bool: + return True + + +class ConsumedDelivery(OfflineVisibleDelivery, ReadDelivery): """The harness or native runtime proved the message entered the model's context.""" # A model taking the message into its context is that recipient reading it. Calling @@ -241,9 +248,6 @@ class ConsumedDelivery(ReadDelivery): def is_consumed(self) -> bool: return True - def shown_when_offline(self) -> bool: - return True - def model_consumed(self, proof: ShownToModelProgress) -> Self: """An earlier proof already timed the entry; a later one adds nothing.""" return self @@ -261,14 +265,11 @@ def ignored(self) -> DeliveryProgress: @dataclass(frozen=True) -class HumanReadProgress(ReadDelivery, DeliveryProgress): +class HumanReadProgress(OfflineVisibleDelivery, ReadDelivery, DeliveryProgress): """Human display is not model-context input.""" label: ClassVar[str] = "Read" - def shown_when_offline(self) -> bool: - return True - @dataclass(frozen=True) class ContextualProgress(WaitingDelivery, DeliveryProgress): @@ -364,12 +365,13 @@ class FailedProgress(ContextualProgress): label = "Failed" -class OfflineVisibleContextualProgress(ContextualProgress, declared_name=None): +class OfflineVisibleContextualProgress( + OfflineVisibleDelivery, + ContextualProgress, + declared_name=None, +): """A contextual delivery progress state that remains visible when offline.""" - def shown_when_offline(self) -> bool: - return True - @dataclass(frozen=True) class AnsweredProgress(ReadDelivery, OfflineVisibleContextualProgress): diff --git a/src/agent_comms/messaging/task_sources.py b/src/agent_comms/messaging/task_sources.py index 7ab9bc2bc0..8ac8d53423 100644 --- a/src/agent_comms/messaging/task_sources.py +++ b/src/agent_comms/messaging/task_sources.py @@ -100,8 +100,19 @@ def direct(self, goals: MessageDirections[messages.Message], message: messages.M goals.todos.record_directive(request, directive) +class TaskRevisionSource: + """A task source that revises an earlier record and retains its root source.""" + + def revises_after(self, previous: messages.Message) -> bool: + return True + + @dataclass(frozen=True) -class UserTaskSupersession(TaskAttachment, declared_name="user_supersession"): +class UserTaskSupersession( + TaskRevisionSource, + TaskAttachment, + declared_name="user_supersession", +): """The human's exact correction stays on its original enclosing messages.Message. This event retires a declared choice; it does not infer replacement valid @@ -129,9 +140,6 @@ def current_roots( return None return self.root_source(message, originals) - def revises_after(self, previous: messages.Message) -> bool: - return True - def require_publication(self, sender: str, registry: TaskRegistry[TaskOwner], original_source: MessageReferencesRead[messages.Message]) -> None: registry.require(sender).role.require_user( RelationViolationError("A task revision requires the original human sender") @@ -291,7 +299,7 @@ def retained_task_facts(self, message: messages.Message): @dataclass(frozen=True, kw_only=True) -class HumanConstraintPin(ScopedTaskDeclaration): +class HumanConstraintPin(TaskRevisionSource, ScopedTaskDeclaration): """Original human wording is referenced, never copied into a pin's body.""" subject: MessageReference source_user: ThreadIncarnation @@ -323,9 +331,6 @@ def require_user_revision(self, sender: str, registry: RegistryNames[ThreadIdent if self.author.resolved(registry) != registry.require(sender).incarnation: raise RelationViolationError("A USER cannot revise another human's constraint") - def revises_after(self, previous: messages.Message) -> bool: - return True - def lineage_reference(self, root: messages.Message) -> MessageReference: return self.subject diff --git a/src/agent_comms/projects/head_review.py b/src/agent_comms/projects/head_review.py index 926a643d48..f746067624 100644 --- a/src/agent_comms/projects/head_review.py +++ b/src/agent_comms/projects/head_review.py @@ -867,16 +867,17 @@ def arm(self) -> MergeArm: return RequestedMergeArm(self.head) -class HeadReviewRelation(DeclaredFamily): - """Order relationships share one declaration family and compose their capabilities.""" +class OrderlessReviewSource: + """A head-review declaration defaulting to no orderless authority sources.""" - def accepted_orderless_sources( - self, record: HeadReviewRecord - ) -> tuple[PullRequestHead, ...]: - """Only an orderless relationship supplies authority outside current Todo links.""" + def accepted_orderless_sources(self, record): return () +class HeadReviewRelation(OrderlessReviewSource, DeclaredFamily): + """Order relationships share one declaration family and compose their capabilities.""" + + class HeadReviewOrder(HeadReviewRelation, declared_name=None): """The input that authorizes a head review's optional order change.""" @@ -909,7 +910,7 @@ class PreparedHeadReview: subject: str -class HeadReview(DeclaredFamily, affix="HeadReview"): +class HeadReview(OrderlessReviewSource, DeclaredFamily, affix="HeadReview"): context: ClassVar[str] = "agent-comms/review" # GitHub's commit-status states, an external contract. state: ClassVar[str] @@ -955,9 +956,6 @@ def post(self, repo: RepositoryName, head: str, reviewer: str, subject: str) -> if posted.returncode: raise ToolRefusedError(posted.stderr.strip() or f"Review status on {head} failed.") - def accepted_orderless_sources(self, record): - return () - class AcceptedHeadReview(HeadReview, declared_name=None): """A head review that permits integration (success status and orderless source authority).""" diff --git a/src/agent_comms/registry/thread_model.py b/src/agent_comms/registry/thread_model.py index a95aa01a2a..ebc90cafe3 100644 --- a/src/agent_comms/registry/thread_model.py +++ b/src/agent_comms/registry/thread_model.py @@ -30,7 +30,7 @@ boundary_decoder, compile_decoder, ) -from agent_comms.registry.thread_text import AbsentText, TextChoice +from agent_comms.registry.thread_text import AbsentText, RequiredTextChoice, TextChoice @dataclass(frozen=True, slots=True) @@ -191,11 +191,10 @@ def __str__(self) -> str: return self.wire_value -class NamedModel(ExternalField, WireValue, ModelSelection): +class NamedModel(RequiredTextChoice, ExternalField, WireValue, ModelSelection): """Atomic model name value object (not a nested config dataclass for ObjectState).""" __slots__ = ("text",) - text: str def __init__(self, text: str) -> None: if type(text) is not str or not text.strip(): @@ -217,15 +216,6 @@ def __repr__(self) -> str: def __str__(self) -> str: return self.text - def otherwise[Default](self, default: Default) -> str: - return self.text - - def require(self, missing: str) -> str: - return self.text - - def texts(self) -> tuple[str, ...]: - return (self.text,) - def native(self, arguments: NativeArguments) -> NativeArguments: return arguments.with_model(self.text) diff --git a/src/agent_comms/registry/thread_text.py b/src/agent_comms/registry/thread_text.py index e2344a6a66..dc5d12552d 100644 --- a/src/agent_comms/registry/thread_text.py +++ b/src/agent_comms/registry/thread_text.py @@ -39,10 +39,11 @@ def require(self, missing: str) -> str: def texts(self) -> tuple[str, ...]: ... -class GivenText(SingleFieldValue, TextChoice): - """The given member: its declared ``text`` field is the whole wire value.""" +class RequiredTextChoice: + """A non-empty text selection that returns itself for fallback and requirement checks.""" __slots__ = () + text: str def otherwise[Default](self, default: Default) -> str: @@ -55,6 +56,12 @@ def texts(self) -> tuple[str, ...]: return (self.text,) +class GivenText(RequiredTextChoice, SingleFieldValue, TextChoice): + """The given member: its declared ``text`` field is the whole wire value.""" + + __slots__ = () + + class DefaultWhenAbsent: """The absent member holds no value, so it answers the caller's default.""" diff --git a/src/agent_comms/transcript/external_transcript_rows.py b/src/agent_comms/transcript/external_transcript_rows.py index f9827d0e34..763444976e 100644 --- a/src/agent_comms/transcript/external_transcript_rows.py +++ b/src/agent_comms/transcript/external_transcript_rows.py @@ -176,10 +176,16 @@ def pending(self, request) -> bool: @dataclass(frozen=True) -class ExternalPageRow(TypedRow): +class TranscriptItemRow: + """A transcript row keyed by thread, turn identifier, and item identifier.""" + thread: Annotated[ThreadLookup, Column(primary_key=True)] turn_id: Annotated[NativeTurnId, Column(primary_key=True)] item_id: Annotated[NativeItemId, Column(primary_key=True)] + + +@dataclass(frozen=True) +class ExternalPageRow(TranscriptItemRow, TypedRow): seq: int earlier: ExternalPage = field(default_factory=NoEarlierPage, kw_only=True) diff --git a/src/agent_comms/transport/background_runs.py b/src/agent_comms/transport/background_runs.py index f2aadedbab..b8c366db99 100644 --- a/src/agent_comms/transport/background_runs.py +++ b/src/agent_comms/transport/background_runs.py @@ -24,7 +24,12 @@ from typing import ClassVar from agent_comms.bus_context import BusContext -from agent_comms.execution.child_process import OutlivesLauncherLifetime, Platform, SpawnedProcess +from agent_comms.execution.child_process import ( + ExitCodeSummary, + OutlivesLauncherLifetime, + Platform, + SpawnedProcess, +) from agent_comms.execution.process_identity import ProcessIdentity from agent_comms.installer.native_build_inputs import DetachedChildStdio from agent_comms.messaging.channel_targets import ThreadTarget @@ -64,12 +69,8 @@ def summary(self) -> str: @dataclass(frozen=True) -class ExitedOutcome(RunOutcome): - code: int - - @property - def summary(self) -> str: - return f"exited with code {self.code}" +class ExitedOutcome(ExitCodeSummary, RunOutcome): + pass @dataclass(frozen=True) diff --git a/src/agent_comms/transport/connector_profile.py b/src/agent_comms/transport/connector_profile.py index 1f0d8f22ea..d0f4ce081d 100644 --- a/src/agent_comms/transport/connector_profile.py +++ b/src/agent_comms/transport/connector_profile.py @@ -234,11 +234,17 @@ def reaches(self, address: str) -> bool: @dataclass(frozen=True) -class UiGrant: - """Which UI grant was issued, for which bus root, and when it expires.""" +class ScopedUiGrant: + """A UI grant record carrying its grant identifier and namespace.""" grant_id: UiGrantId namespace: RootId + + +@dataclass(frozen=True) +class UiGrant(ScopedUiGrant): + """Which UI grant was issued, for which bus root, and when it expires.""" + expires_at: float diff --git a/src/agent_comms/transport/connector_store.py b/src/agent_comms/transport/connector_store.py index deeabcb856..34dab42469 100644 --- a/src/agent_comms/transport/connector_store.py +++ b/src/agent_comms/transport/connector_store.py @@ -45,6 +45,7 @@ MCP_PATH, BearerSecret, HttpsMcpEndpoint, + ScopedUiGrant, UiConnectionProfile, UiCredential, UiGrantId, @@ -412,7 +413,7 @@ def spent_in(self, grants: ConnectorGrants, key: str) -> ConnectorGrants: @dataclass(frozen=True) -class UiGrantAccess(ExpiringGrant, ConnectorAccess, declared_name=None): +class UiGrantAccess(ScopedUiGrant, ExpiringGrant, ConnectorAccess, declared_name=None): """Shared UI issuance facts; the concrete member declares its caller capability.""" maximum_seconds: ClassVar[int] = UI_GRANT_SECONDS @@ -420,9 +421,6 @@ class UiGrantAccess(ExpiringGrant, ConnectorAccess, declared_name=None): """A UI grant's own default lifetime, an hour; not the OAuth access clock, which may move.""" caller_type: ClassVar[type[ScopedUiCaller]] - grant_id: UiGrantId - namespace: RootId - def authorized_caller(self) -> ConnectorCaller: return self.caller_type(self.namespace) diff --git a/src/agent_comms/transport/serving/served_requests.py b/src/agent_comms/transport/serving/served_requests.py index 0891c0b70a..28222200c8 100644 --- a/src/agent_comms/transport/serving/served_requests.py +++ b/src/agent_comms/transport/serving/served_requests.py @@ -7,7 +7,7 @@ from __future__ import annotations -from abc import ABC, abstractmethod +from abc import abstractmethod from collections.abc import AsyncIterator from contextlib import asynccontextmanager, suppress from dataclasses import dataclass @@ -98,12 +98,12 @@ from agent_comms.working_memory.working_memory_labels import ModelLabel -class OwnedRead[Result: ToolResult = ToolResult](OwnerScopedRead[Result], ABC): +class OwnedRead[Result: ToolResult = ToolResult](OwnerScopedRead[Result]): @abstractmethod async def owned(self, ctx: AttachedRuntimeRequestContext) -> Result: ... -class OwnerLiveRead[Result: ToolResult = ToolResult](OwnedRead[Result], ABC): +class OwnerLiveRead[Result: ToolResult = ToolResult](OwnedRead[Result]): """This subfamily has no answer without the selected live native owner.""" def unavailable(self, comms: Comms, owner: ThreadIncarnation) -> Result: diff --git a/src/agent_comms/transport/zmq_comms_server.py b/src/agent_comms/transport/zmq_comms_server.py index a1fc55263b..35dbac83b1 100644 --- a/src/agent_comms/transport/zmq_comms_server.py +++ b/src/agent_comms/transport/zmq_comms_server.py @@ -100,13 +100,21 @@ def for_root(cls, root: Path, *, port: int = DEFAULT_COMMS_ZMQ_PORT) -> CommsZMQ return cls(bus_root=root.resolve(), default_port=port) -@dataclass(frozen=True, slots=True) -class CliConnectionRecord: - """One external CLI session attached to ``CommsZMQServer``.""" +@dataclass(frozen=True) +class CliSessionIdentity: + """Shared thread, client kind, and process identifier fields for a CLI session.""" + + __slots__ = () thread_name: str client_kind: str pid: int + + +@dataclass(frozen=True, slots=True) +class CliConnectionRecord(CliSessionIdentity): + """One external CLI session attached to ``CommsZMQServer``.""" + connected_at: float last_seen: float @@ -146,10 +154,7 @@ class ServerReadyEvent(CommsServerEvent): @dataclass(frozen=True, slots=True) -class CliAttachedEvent(CommsServerEvent): - thread_name: str - client_kind: str - pid: int +class CliAttachedEvent(CliSessionIdentity, CommsServerEvent): connected_count: int @@ -176,11 +181,7 @@ def apply(self, server: CommsZMQServer) -> dict[str, object]: ... @dataclass(frozen=True, slots=True) -class CliAttachRequest(CommsZmqRequest): - thread_name: str - client_kind: str - pid: int - +class CliAttachRequest(CliSessionIdentity, CommsZmqRequest): def apply(self, server: CommsZMQServer) -> dict[str, object]: return server.attach_cli(self.thread_name, self.client_kind, self.pid) diff --git a/tools/repairs.py b/tools/repairs.py index 4da2d74414..2e239eac41 100644 --- a/tools/repairs.py +++ b/tools/repairs.py @@ -59,7 +59,7 @@ class OutsidePackage(Kept): why = "outside the agent_comms package" -class Repair(DeclaredFamily, ABC): +class Repair(DeclaredFamily): """One measure's repair over some files of the working tree.""" repairs: ClassVar[type[audit.gate.LocatedSource]] @@ -278,7 +278,7 @@ def root(self) -> str: return "" -class HoistVerdict(DeclaredFamily, ABC): +class HoistVerdict(DeclaredFamily): """What the hoist does with one local import: the first member, in declaration order, that holds for it decides.""" @@ -295,7 +295,7 @@ def of(cls, local: LocalImport) -> type[HoistVerdict]: return next(verdict for verdict in cls.members_with(cls) if verdict.holds(local)) -class KeptImport(Kept, HoistVerdict, ABC): +class KeptImport(Kept, HoistVerdict): """The import stays in its function, and the hoist tallies why.""" @classmethod