From c844dae19178cca9e40ec2ebcd1c0945fc644bc6 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Sat, 28 Nov 2026 09:55:07 -0500 Subject: [PATCH] Apply 14-recipe P58 sibling_override batch 1 via NRA #653 --- src/agent_comms/acp_extension.py | 15 +++--- .../cli_bridges/runtime_updates.py | 18 +++---- .../coordination/obligation_states.py | 28 ++++++----- src/agent_comms/execution/child_process.py | 44 ++++++----------- src/agent_comms/execution/input_drain.py | 11 +++-- src/agent_comms/execution/provider_records.py | 19 +++---- src/agent_comms/execution/turn_phase.py | 12 +++-- src/agent_comms/messaging/send_result.py | 14 ++++-- src/agent_comms/pi_payloads.py | 18 ++++--- src/agent_comms/planning/orders.py | 49 ++++++++++--------- src/agent_comms/storage/private_path.py | 14 +++--- 11 files changed, 123 insertions(+), 119 deletions(-) diff --git a/src/agent_comms/acp_extension.py b/src/agent_comms/acp_extension.py index 0373000556..da4b61504d 100644 --- a/src/agent_comms/acp_extension.py +++ b/src/agent_comms/acp_extension.py @@ -137,24 +137,23 @@ def needs_refresh(self) -> bool: return False -@dataclass(frozen=True) -class UnavailableCursorObservation(CursorObservation): +class StaleCursorObservation(CursorObservation, declared_name=None): + """A cursor observation that requires a refresh.""" + @property def needs_refresh(self) -> bool: return True + +@dataclass(frozen=True) +class UnavailableCursorObservation(StaleCursorObservation): @property def status(self) -> str: return "unavailable" @dataclass(frozen=True) -class EmptyCursorObservation(CursorObservation): - @property - def needs_refresh(self) -> bool: - # Absence of a durable projection does not settle an original proof. - return True - +class EmptyCursorObservation(StaleCursorObservation): @property def status(self) -> str: return "none" diff --git a/src/agent_comms/cli_bridges/runtime_updates.py b/src/agent_comms/cli_bridges/runtime_updates.py index a56f2c3126..11dc129be3 100644 --- a/src/agent_comms/cli_bridges/runtime_updates.py +++ b/src/agent_comms/cli_bridges/runtime_updates.py @@ -73,16 +73,19 @@ def finish(self, update: CompletedItem) -> tuple[ClosedDraft, FinishedItem]: return ClosedDraft(self.started_at), FinishedItem(turn_id=update.turn_id, item_id=update.item_id, events=update.events) -class NoPrefixDraft(DraftAccumulator): +class ImmutableDraftAccumulator(DraftAccumulator): + """A draft accumulator that accepts no appended text.""" + + def append(self, update: AppendDraftItem) -> tuple[RuntimeUpdate, ...]: + return () + + +class NoPrefixDraft(ImmutableDraftAccumulator): """No observed prefix; retain no per-item state so the instance can be shared.""" def __init__(self) -> None: super().__init__(UnrecordedEventTime()) - def append(self, update: AppendDraftItem) -> tuple[RuntimeUpdate, ...]: - """Drop the suffix: without an observed prefix it cannot form a whole item.""" - return () - NO_PREFIX = NoPrefixDraft() @@ -151,7 +154,7 @@ class ParagraphDraft(TextDraft): separator = "\n\n" -class ClosedDraft(DraftAccumulator): +class ClosedDraft(ImmutableDraftAccumulator): """Completed snapshots reject overlapping older starts and late suffixes.""" def restarted(self, replacement: DraftAccumulator) -> DraftAccumulator: @@ -163,9 +166,6 @@ def started(self, update: StartedItem) -> tuple[RuntimeUpdate, ...]: def activity(self, update: ActiveItem) -> tuple[RuntimeUpdate, ...]: return () - def append(self, update: AppendDraftItem) -> tuple[RuntimeUpdate, ...]: - return () - @dataclass class ThreadOutput(activity.ThreadOutput): diff --git a/src/agent_comms/coordination/obligation_states.py b/src/agent_comms/coordination/obligation_states.py index 98e4ee3012..babc08656c 100644 --- a/src/agent_comms/coordination/obligation_states.py +++ b/src/agent_comms/coordination/obligation_states.py @@ -109,11 +109,15 @@ def validate_acknowledgement(self, acknowledgement) -> None: raise CoordinationError("publication acknowledgement exists iff published") -class PendingResponse(Retryable, Pending, ResponseState): +class UnpublishedResponseState(ResponseState, declared_name=None): + """A response state that has not yet been published.""" def require_nonpublication(self) -> None: pass + +class PendingResponse(Retryable, Pending, UnpublishedResponseState): + def require_preparation(self) -> None: pass @@ -122,12 +126,16 @@ def successors(cls): return PublishingResponse, DeferredResponse, SilentResponse, FailedResponse -class PublishingResponse(Publishing, ResponseState): +class PublicationResponseState(ResponseState, declared_name=None): + """A response state that participates in publication intent validation.""" def validate_intent(self, intent) -> None: if intent is None: raise CoordinationError("publishing and published obligations require intent") + +class PublishingResponse(Publishing, PublicationResponseState): + def require_publishing(self) -> None: pass @@ -139,10 +147,7 @@ def successors(cls): return PublishedResponse, FailedResponse -class DeferredResponse(Retryable, Deferred, ResponseState): - - def require_nonpublication(self) -> None: - pass +class DeferredResponse(Retryable, Deferred, UnpublishedResponseState): @classmethod def resume_response( @@ -164,7 +169,12 @@ def successors(cls): @dataclass(frozen=True) -class PublishedResponse(Published, RequiresIntent, Successful, ResponseState): +class PublishedResponse( + Published, + RequiresIntent, + Successful, + PublicationResponseState, +): message_id: MessageId seq: int @@ -183,10 +193,6 @@ def published_message_id(self): def publication_seq(self): return self.seq - def validate_intent(self, intent) -> None: - if intent is None: - raise CoordinationError("publishing and published obligations require intent") - def published_reference(self) -> MessageReference: return MessageReference(self.seq, self.message_id) diff --git a/src/agent_comms/execution/child_process.py b/src/agent_comms/execution/child_process.py index c91453890a..78feee0479 100644 --- a/src/agent_comms/execution/child_process.py +++ b/src/agent_comms/execution/child_process.py @@ -725,8 +725,16 @@ def fork_failure(self, interrupted_consequence: Callable[[], str]) -> str: return interrupted_consequence() +class UnsuccessfulChildOutcome(ChildOutcome, declared_name=None): + """A child process outcome that did not exit cleanly with code zero.""" + + @property + def successful(self) -> bool: + return False + + @dataclass(frozen=True) -class SignaledOutcome(InterruptedForkOutcome): +class SignaledOutcome(UnsuccessfulChildOutcome, InterruptedForkOutcome): signal_number: int def report_stopped(self, report: Callable[[], None], stop_exits: frozenset[int]) -> None: @@ -736,13 +744,9 @@ def report_stopped(self, report: Callable[[], None], stop_exits: frozenset[int]) def summary(self) -> str: return f"stopped by {signal.Signals(self.signal_number).name}" - @property - def successful(self) -> bool: - return False - @dataclass(frozen=True) -class TimedOutOutcome(InterruptedForkOutcome): +class TimedOutOutcome(UnsuccessfulChildOutcome, InterruptedForkOutcome): termination: ChildOutcome def report_shutdown(self, report_timeout: Callable[[], None]) -> None: @@ -752,10 +756,6 @@ def report_shutdown(self, report_timeout: Callable[[], None]) -> None: def summary(self) -> str: return f"timed out; {self.termination.summary}" - @property - def successful(self) -> bool: - return False - class _StopStage(ABC): """One phase of retiring a process group: graceful termination, then forced kill.""" @@ -846,17 +846,13 @@ def report_forced(self, report: Callable[[str], None]) -> None: @dataclass(frozen=True) -class FailedToStartOutcome(ChildOutcome): +class FailedToStartOutcome(UnsuccessfulChildOutcome, ChildOutcome): error: str @property def summary(self) -> str: return f"failed to start: {self.error}" - @property - def successful(self) -> bool: - return False - @dataclass(frozen=True) class ChildResult: @@ -1402,6 +1398,10 @@ async def exchange( class SynchronousProcess(ChildProcess): """Identity-checked process control; each subclass supplies synchronous reaping.""" + async def wait(self) -> ChildOutcome: + await self.platform.wait_exited(self.identity) + return self.reap() + def __init__(self, identity: ProcessIdentity): super().__init__(identity) self._retirement_lock = threading.Lock() @@ -1517,10 +1517,6 @@ def require_stop_authority(self) -> None: def reap(self) -> ChildOutcome: return DetachedExitOutcome() - async def wait(self) -> ChildOutcome: - await self.platform.wait_exited(self.identity) - return self.reap() - class SpawnedProcess(SynchronousProcess): """A launched process handle; surviving the launcher does not preserve its parent.""" @@ -1607,10 +1603,6 @@ def reap(self) -> ChildOutcome: """Collect the owned child's actual exit; stop grace belongs to its stop plan.""" return ChildOutcome.from_returncode(self.process.wait()) - async def wait(self) -> ChildOutcome: - await self.platform.wait_exited(self.identity) - return self.reap() - def close_streams(self) -> None: for stream in (self.process.stdin, self.process.stdout, self.process.stderr): if stream is not None: @@ -1807,17 +1799,13 @@ def submit[T, **P]( @dataclass(frozen=True) -class DetachedExitOutcome(ChildOutcome): +class DetachedExitOutcome(UnsuccessfulChildOutcome, ChildOutcome): """Exit observed; a non-parent cannot claim an exit code.""" @property def summary(self) -> str: return "exited; status unavailable" - @property - def successful(self) -> bool: - return False - class ChildCommand(DeclaredFamily, affix="Command"): """Internal child entrypoints decode once through their declaration owner.""" diff --git a/src/agent_comms/execution/input_drain.py b/src/agent_comms/execution/input_drain.py index 8c895ffe26..360b168148 100644 --- a/src/agent_comms/execution/input_drain.py +++ b/src/agent_comms/execution/input_drain.py @@ -1066,10 +1066,14 @@ async def resume(self, maintenance: MaintenanceIngress) -> None: ... async def finish_original(self, inputs: InputDrain) -> None: ... -class NoDrainTurn(DrainTurn): +class UnstartedDrainTurn(DrainTurn): + """A drain turn that has not started an original input to finish.""" + async def finish_original(self, inputs: InputDrain) -> None: pass + +class NoDrainTurn(UnstartedDrainTurn): def opened(self) -> DrainTurn: return AwaitingDrainTurn(TurnInbox()) @@ -1081,15 +1085,12 @@ async def resume(self, maintenance: MaintenanceIngress) -> None: @dataclass(frozen=True) -class AwaitingDrainTurn(DrainTurn): +class AwaitingDrainTurn(UnstartedDrainTurn): inbox: TurnInbox def is_open(self) -> bool: return True - async def finish_original(self, inputs: InputDrain) -> None: - pass - def opened(self) -> DrainTurn: return self diff --git a/src/agent_comms/execution/provider_records.py b/src/agent_comms/execution/provider_records.py index 18ce24fd5c..d350eb2f67 100644 --- a/src/agent_comms/execution/provider_records.py +++ b/src/agent_comms/execution/provider_records.py @@ -145,8 +145,15 @@ def parse(cls, text: str, reasoning: str = "") -> ParsedThinking: return cls(thinking="\n\n".join(parts), visible=remaining.strip()) +class ToolRoundAllowedContent(PiContent, declared_name=None): + """A Pi content block permitted inside a tool round.""" + + def require_tool_round_allowed(self) -> None: + pass + + @dataclass(frozen=True) -class TextContent(PiContent): +class TextContent(ToolRoundAllowedContent): def text_parts(self) -> tuple[str, ...]: return (self.text,) @@ -170,8 +177,6 @@ def assistant_transcript(self, position: int, timestamp: float): text_signature: Annotated[ PiField[str | PiOmitted], WireName("textSignature") ] = PiOmitted() - def require_tool_round_allowed(self) -> None: - pass @property @@ -180,7 +185,7 @@ def final_text(self) -> str: @dataclass(frozen=True) -class ThinkingContent(PiContent): +class ThinkingContent(ToolRoundAllowedContent): def assistant_transcript(self, position: int, timestamp: float): return [ThinkingTranscript(self.thinking, position=position, timestamp=timestamp)] @@ -188,8 +193,6 @@ def assistant_transcript(self, position: int, timestamp: float): thinking_signature: Annotated[ PiField[str | PiOmitted], WireName("thinkingSignature") ] = PiOmitted() - def require_tool_round_allowed(self) -> None: - pass @property @@ -198,7 +201,7 @@ def final_text(self) -> str: @dataclass(frozen=True) -class ToolCallContent(PiContent, declared_name="toolCall"): +class ToolCallContent(ToolRoundAllowedContent, declared_name="toolCall"): def tool_calls(self) -> tuple[ToolCallContent, ...]: return (self,) @@ -211,8 +214,6 @@ def assistant_transcript(self, position: int, timestamp: float): id: ToolCallId name: str arguments: object - def require_tool_round_allowed(self) -> None: - pass diff --git a/src/agent_comms/execution/turn_phase.py b/src/agent_comms/execution/turn_phase.py index 98a847c62d..13636df039 100644 --- a/src/agent_comms/execution/turn_phase.py +++ b/src/agent_comms/execution/turn_phase.py @@ -181,12 +181,16 @@ class PreparingPhase(TurnPhase): label = "Preparing input" -class IdlePhase(ActivityWord, TurnPhase): - busy = False +class NonFollowupTurnPhase(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 + def can_cancel(self) -> bool: return False activity_state = ActivityState.IDLE @@ -275,9 +279,7 @@ def stall_message(self, budget: float) -> str: ) -class SettlingStatsPhase(TurnPhase): - def accepts_followup(self) -> bool: - return False +class SettlingStatsPhase(NonFollowupTurnPhase): label = "Finishing native statistics" diff --git a/src/agent_comms/messaging/send_result.py b/src/agent_comms/messaging/send_result.py index 325de8150d..f00db1faac 100644 --- a/src/agent_comms/messaging/send_result.py +++ b/src/agent_comms/messaging/send_result.py @@ -18,12 +18,18 @@ class CorrectionResult(DeclaredFamily): def notices(self, message_id: MessageId) -> tuple[str, ...]: ... -@dataclass(frozen=True) -class CorrectionComplete(CorrectionResult, declared_name="complete"): +class NoticeFreeCorrectionResult(CorrectionResult, declared_name=None): + """A correction result carrying no notices.""" + def notices(self, message_id: MessageId) -> tuple[str, ...]: return () +@dataclass(frozen=True) +class CorrectionComplete(NoticeFreeCorrectionResult, declared_name="complete"): + pass + + @dataclass(frozen=True) class CorrectionFailed(CorrectionResult, declared_name="failed"): error: str @@ -33,10 +39,8 @@ def notices(self, message_id: MessageId) -> tuple[str, ...]: @dataclass(frozen=True) -class CorrectionUnreported(CorrectionResult, declared_name="unreported"): +class CorrectionUnreported(NoticeFreeCorrectionResult, declared_name="unreported"): """Older retained tool replies did not report their correction outcome.""" - def notices(self, message_id: MessageId) -> tuple[str, ...]: - return () @dataclass(frozen=True) diff --git a/src/agent_comms/pi_payloads.py b/src/agent_comms/pi_payloads.py index fbc72ceaab..17c5c895a7 100644 --- a/src/agent_comms/pi_payloads.py +++ b/src/agent_comms/pi_payloads.py @@ -540,8 +540,16 @@ class AbsentMessage(ExternalNullMember, PiMessage): update_context = True +class ConversationPiMessage(PiMessage, declared_name=None): + """A user or assistant Pi message that invalidates a fresh start.""" + + @property + def invalidates_start(self): + return True + + @dataclass(frozen=True) -class AssistantMessage(PublicInstructionAnnotations, PiMessage): +class AssistantMessage(PublicInstructionAnnotations, ConversationPiMessage): # Pi's assistant record always carries an array, including failed terminals. content: Annotated[ReportedParts, WireRequired()] = ReportedParts(()) # Original Pi completion metadata. These are observations, not registry @@ -556,9 +564,6 @@ class AssistantMessage(PublicInstructionAnnotations, PiMessage): provider_thinking_level: Annotated[ PiField[str | PiOmitted], WireName("providerThinkingLevel") ] = PiOmitted() - @property - def invalidates_start(self): - return True update_context = True @@ -617,13 +622,10 @@ def transcript_events(self, context, timestamp: float): return [replace(event, routing=context.routing) for event in events] -class UserMessage(PiMessage, ProjectedUserMessage[PiContent]): +class UserMessage(ConversationPiMessage, ProjectedUserMessage[PiContent]): def is_user_message(self) -> bool: return True - @property - def invalidates_start(self): - return True part_separator = "\n" def preserve_evidence(self, raw: Mapping[str, object]) -> Self: diff --git a/src/agent_comms/planning/orders.py b/src/agent_comms/planning/orders.py index 2e3f8d8131..485637bc6f 100644 --- a/src/agent_comms/planning/orders.py +++ b/src/agent_comms/planning/orders.py @@ -1287,16 +1287,20 @@ def published(self, selected: CommitFilter) -> Iterator[ProgressPoint]: return iter(()) -class MissingCheckout(ProgressCheckout): +class EmptyProgressCheckout(ProgressCheckout, declared_name=None): + """A progress checkout without readable local git references.""" + + def references(self, storage: StorageRule, owner: Thread) -> tuple[str, ...]: + return () + + +class MissingCheckout(EmptyProgressCheckout): """A retired checkout contributes no local history, not a failed Git read.""" def commits(self, selected: CommitFilter, refs: tuple[str, ...], *excluded: str) -> Iterator[ProgressPoint]: return iter(()) - def references(self, storage: StorageRule, owner: Thread) -> tuple[str, ...]: - return () - def readings(self, source: ProgressSource, refs: tuple[str, ...]) -> DistanceReadings: return DistanceReadings() @@ -1305,7 +1309,7 @@ def pushes(self, selected: CommitFilter) -> Iterator[tuple[str, float]]: @dataclass(frozen=True) -class UnreadCheckout(ProgressCheckout): +class UnreadCheckout(EmptyProgressCheckout): """A failed source read is data, never a missing checkout or no progress.""" reason: str @@ -1317,9 +1321,6 @@ def commits(self, selected: CommitFilter, refs: tuple[str, ...], *excluded: str) -> Iterator[ProgressPoint]: raise WorkBranchError(self.reason) - def references(self, storage: StorageRule, owner: Thread) -> tuple[str, ...]: - return () - def readings(self, source: ProgressSource, refs: tuple[str, ...]) -> DistanceReadings: raise WorkBranchError(self.reason) @@ -4161,25 +4162,31 @@ def description(self, reviewer: str, subject: str) -> str: return f"{self.verb} by {reviewer} on {subject}: {self.reason.text}" +class OrderReviewHeadVerdict(HeadVerdict, declared_name=None): + """A head verdict accepted for order review.""" + + @classmethod + def accepted_for_order_review(cls) -> bool: + return True + + @dataclass(frozen=True) -class QualifiedHeadVerdict(DecidedHeadVerdict): +class QualifiedHeadVerdict(OrderReviewHeadVerdict, DecidedHeadVerdict): """A reviewed source stage, without permission to promote the whole change.""" state = "pending" verb = "Qualified" - @classmethod - def accepted_for_order_review(cls) -> bool: - return True @dataclass(frozen=True) -class ReviewedHeadVerdict(DecidedHeadVerdict, AcceptedHeadReview): +class ReviewedHeadVerdict( + OrderReviewHeadVerdict, + DecidedHeadVerdict, + AcceptedHeadReview, +): """Accept an exact source for combination, never enqueue its individual PR.""" verb = "Accepted" - @classmethod - def accepted_for_order_review(cls) -> bool: - return True preparation_field = GrowthReason.option preparation_fix = (f"repeat {GrowthReason.option} 'PATH REASON' for each growing source file; " f'each reason names its file in {GrowthReason.least_words}+ words') @@ -4259,13 +4266,10 @@ class GrownHeadVerdict(ExplainedGrowth, ReviewedHeadVerdict): @dataclass(frozen=True) -class RejectedHeadVerdict(DecidedHeadVerdict): +class RejectedHeadVerdict(OrderReviewHeadVerdict, DecidedHeadVerdict): reason: StrikeReason state = "failure" verb = "Sent back" - @classmethod - def accepted_for_order_review(cls) -> bool: - return True def after_record(self, goals: ProblemGoals, record: HeadReviewRecord) -> None: record.order.rejected(goals, record) @@ -4319,11 +4323,8 @@ class UnrecordedHeadVerdict(HeadVerdict, declared_name=None): """No decision is recorded on this exact head.""" -class UnderReviewHeadVerdict(HeadVerdict): +class UnderReviewHeadVerdict(OrderReviewHeadVerdict, HeadVerdict): state = "pending" - @classmethod - def accepted_for_order_review(cls) -> bool: - return True def description(self, reviewer: str, subject: str) -> str: return f"Under review by {reviewer} on {subject}" diff --git a/src/agent_comms/storage/private_path.py b/src/agent_comms/storage/private_path.py index 0dd9334bc2..773cda80ed 100644 --- a/src/agent_comms/storage/private_path.py +++ b/src/agent_comms/storage/private_path.py @@ -193,13 +193,17 @@ def created_stream( path, cls.create_flags, refusal, dir_fd=dir_fd, mode=cls.permissions), "wb") -class PrivateFileRole(PrivateRole): - permissions = 0o600 +class NonBlockingFilesystemRole(PrivateRole, declared_name=None): + """A filesystem role opened with O_NONBLOCK.""" @classmethod def kind_flags(cls) -> int: return os.O_NONBLOCK + +class PrivateFileRole(NonBlockingFilesystemRole): + permissions = 0o600 + @classmethod def accepts_kind(cls, mode: int) -> bool: return stat.S_ISREG(mode) @@ -241,13 +245,9 @@ def accepts_kind(cls, mode: int) -> bool: return stat.S_ISDIR(mode) -class PrivateSocketRole(PrivateRole): +class PrivateSocketRole(NonBlockingFilesystemRole): permissions = 0o600 - @classmethod - def kind_flags(cls) -> int: - return os.O_NONBLOCK - @classmethod def accepts_kind(cls, mode: int) -> bool: return stat.S_ISSOCK(mode)