diff --git a/src/agent_comms/acp_extension.py b/src/agent_comms/acp_extension.py index da4b61504d..80ef66c292 100644 --- a/src/agent_comms/acp_extension.py +++ b/src/agent_comms/acp_extension.py @@ -360,8 +360,15 @@ def input_identity(self, acquire_scope: Callable[[], LiveAttachmentScope]) -> Cl return acquire_scope().claimed_identity +class SessionScopedUpdate(AgentCommsUpdate, declared_name=None): + """An agent-comms update scoped to a session.""" + + def for_session(self, session_id: AcpSessionId) -> Self: + return replace(self, scope=self.scope.for_session(session_id)) + + @dataclass(frozen=True) -class QueueChangedUpdate(AgentCommsUpdate): +class QueueChangedUpdate(SessionScopedUpdate): scope: QueueScope revision: int projection: QueueProjection @@ -369,9 +376,6 @@ class QueueChangedUpdate(AgentCommsUpdate): def __post_init__(self): self.scope.validate_scope(self.projection) - def for_session(self, session_id: AcpSessionId) -> QueueChangedUpdate: - return replace(self, scope=self.scope.for_session(session_id)) - @property def status(self) -> str | None: return self.projection.status @@ -382,7 +386,7 @@ def digest(self) -> str: @dataclass(frozen=True) -class InputStartedUpdate(AgentCommsUpdate, declared_name=None): +class InputStartedUpdate(SessionScopedUpdate, declared_name=None): text: str | None scope: QueueScope revision: int | None @@ -404,9 +408,6 @@ def started_request(self, input_id: InputId) -> bool: def when_unidentified(self, action: Callable[[], None]) -> None: pass - def for_session(self, session_id: AcpSessionId) -> InputStartedUpdate: - return replace(self, scope=self.scope.for_session(session_id)) - @dataclass(frozen=True) class IdentifiedInputStarted(InputStartedUpdate): diff --git a/src/agent_comms/cli_bridges/harness_delivery_states.py b/src/agent_comms/cli_bridges/harness_delivery_states.py index 57e26eb6d1..aa3f90c77f 100644 --- a/src/agent_comms/cli_bridges/harness_delivery_states.py +++ b/src/agent_comms/cli_bridges/harness_delivery_states.py @@ -21,10 +21,10 @@ from agent_comms.execution.turn_item import NativeItemId, NativeTurnId from agent_comms.messaging.message_reference import MessageReference from agent_comms.messaging.notification_progress import ( - ConsumptionEvidence, ConsumingProgress, DeliveryProgress, HarnessConsumedProgress, + PassthroughConsumptionEvidence, ) from agent_comms.nominal.declared_family import DeclaredFamily from agent_comms.nominal.field_codec import TranscriptRecordId @@ -40,7 +40,7 @@ @dataclass(frozen=True) -class MonitorEvidence(ConsumptionEvidence, DeclaredFamily): +class MonitorEvidence(PassthroughConsumptionEvidence, DeclaredFamily): """Unsent and terminal observations cannot accept another delivery.""" async def confirm(self, bridge: TranscriptConfirmsDelivery, delivery: HarnessDelivery, @@ -52,9 +52,6 @@ def evidence(self, recorded: type[Outcome]) -> tuple[type[Outcome], MonitorEvide proves nothing leaves the recorded outcome.""" return recorded, self - def consumed_progress(self, progress: DeliveryProgress) -> DeliveryProgress: - return progress - def claim_handoff(self, state: AssignmentState) -> tuple[type[AssignmentState], ...]: return state.harness_handoff() diff --git a/src/agent_comms/cli_verbs/cli_result.py b/src/agent_comms/cli_verbs/cli_result.py index 67dfe6c46c..f2cf1439a6 100644 --- a/src/agent_comms/cli_verbs/cli_result.py +++ b/src/agent_comms/cli_verbs/cli_result.py @@ -9,7 +9,7 @@ from pydantic import JsonValue -from agent_comms.nominal.field_codec import SubclassUnion +from agent_comms.nominal.field_codec import FieldCodec, PresenceExclude, SubclassUnion from agent_comms.transport.tool_result import DeclaredReply, ToolResult @@ -47,6 +47,13 @@ def write(self, output: TextIO) -> int: return self.exit_code() +class PresenceExcludedReply(CliResult): + """A declared reply whose wire projection excludes presence-only fields.""" + + def to_wire(self) -> object: + return FieldCodec.project(self, PresenceExclude) + + @dataclass(frozen=True) class RegisteredResult(CliResult): registered: str diff --git a/src/agent_comms/coordination/assignment_states.py b/src/agent_comms/coordination/assignment_states.py index 78d9284233..d2a5fb14c9 100644 --- a/src/agent_comms/coordination/assignment_states.py +++ b/src/agent_comms/coordination/assignment_states.py @@ -341,7 +341,19 @@ def notification( ) -class TriagePendingAssignment(PreengagementTarget, PendingNotification, AssignmentState): +class BoundedTriageAssignment(AssignmentState, declared_name=None): + """An assignment state whose wake mode is BoundedTriageWake.""" + + @property + def mode(self): + return BoundedTriageWake() + + +class TriagePendingAssignment( + PreengagementTarget, + PendingNotification, + BoundedTriageAssignment, +): def wake_frame(self, source: Delivered, obligation: ResponseObligation | None) -> tuple[str, str]: if obligation is not None: raise IdentityConflict("bounded triage cannot inherit a response obligation") @@ -354,10 +366,6 @@ def requires_selected_triage(self) -> bool: def harness_ignore(self) -> tuple[type[AssignmentState], ...]: return (IgnoredAssignment,) - @property - def mode(self): - return BoundedTriageWake() - @classmethod def successors(cls): return IgnoredAssignment, EngagedAssignment, DeferredAssignment, FailedAssignment @@ -376,13 +384,14 @@ def successors(cls): return EngagedAssignment, DeferredAssignment, FailedAssignment -class IgnoredAssignment(ChangedNotification, PreengagementTarget, Terminal, AssignmentState): +class IgnoredAssignment( + ChangedNotification, + PreengagementTarget, + Terminal, + BoundedTriageAssignment, +): notification_state = IgnoredProgress - @property - def mode(self): - return BoundedTriageWake() - @property def verdict(self): return "ignore" diff --git a/src/agent_comms/coordination/attempt_states.py b/src/agent_comms/coordination/attempt_states.py index a0f400ae71..7fdc751168 100644 --- a/src/agent_comms/coordination/attempt_states.py +++ b/src/agent_comms/coordination/attempt_states.py @@ -281,7 +281,9 @@ def successors(cls): ) -class AbortingAttempt(LiveAttempt): +class RetryableFailureAttempt(LiveAttempt, declared_name=None): + """An attempt state that transitions to either retry or unsuccessful terminal.""" + @classmethod def successors(cls): return ( @@ -290,6 +292,10 @@ def successors(cls): ) +class AbortingAttempt(RetryableFailureAttempt): + pass + + class RetryingAttempt(LiveAttempt): @classmethod def successors(cls): @@ -302,13 +308,8 @@ def successors(cls): ) -class ProviderUnavailableAttempt(LiveAttempt): - @classmethod - def successors(cls): - return ( - UnsuccessfulTerminal, - RetryingAttempt, - ) +class ProviderUnavailableAttempt(RetryableFailureAttempt): + pass class SucceededAttempt(TerminalAttempt): diff --git a/src/agent_comms/execution/cli_inbox_backend.py b/src/agent_comms/execution/cli_inbox_backend.py index 431164b82a..73e8197507 100644 --- a/src/agent_comms/execution/cli_inbox_backend.py +++ b/src/agent_comms/execution/cli_inbox_backend.py @@ -24,12 +24,12 @@ RuntimeLocation, ) from agent_comms.execution.launch_runtime import LaunchRuntime -from agent_comms.execution.unstarted_runtime import ExternalTranscriptLocation +from agent_comms.execution.unstarted_runtime import UnwrittenRuntimeLocation from agent_comms.nominal.field_codec import AcpSessionId @dataclass(frozen=True) -class CliInboxRuntime(ExternalTranscriptLocation): +class CliInboxRuntime(UnwrittenRuntimeLocation): """Runtime location for a CLI-inbox thread. ``path`` is empty for a pure CLI inbox, or holds a preserved native Pi session @@ -46,9 +46,6 @@ def is_resumable(self) -> bool: def require_forkable(self) -> None: pass - def last_written(self) -> float: - return 0.0 - async def compact(self, operation): return FailedCompaction("A CLI-inbox thread compacts in its own CLI session.") diff --git a/src/agent_comms/execution/native_input_proof.py b/src/agent_comms/execution/native_input_proof.py index e520d1fa64..b9f3f8ef94 100644 --- a/src/agent_comms/execution/native_input_proof.py +++ b/src/agent_comms/execution/native_input_proof.py @@ -41,8 +41,7 @@ ImmutableRows, Index, IntegerStorage, - ReconciledFile, - TableSchema, + SelfSchemaReconciledFile, TypedTable, WithoutRowid, ) @@ -223,16 +222,17 @@ def corroborate( return self.at(session_file, session_entry_start=location.session_entry_start) -class NativeInputProof(DurableFile, ReconciledFile, PatternFile, DurableTables): +class NativeInputProof( + DurableFile, + SelfSchemaReconciledFile, + PatternFile, + DurableTables, +): """The retained proof file names its journal without joining their two families.""" __slots__ = () filename = "input-proofs/{lookup}/{name}.sqlite" - @classmethod - def table_schema(cls) -> type[TableSchema]: - return cls - @classmethod def schema_rows(cls) -> tuple[type[TypedTable], ...]: return (NativeContextJournal,) diff --git a/src/agent_comms/execution/native_input_record.py b/src/agent_comms/execution/native_input_record.py index ff2307cb66..eb499856f2 100644 --- a/src/agent_comms/execution/native_input_record.py +++ b/src/agent_comms/execution/native_input_record.py @@ -43,7 +43,7 @@ ) from agent_comms.storage.typed_table import ( LOCAL_TABLE_SOURCE, - SqlStorage, + ExplicitSqlStorage, TableSource, TextStorage, sql_literal, @@ -80,15 +80,11 @@ def offset(self) -> int: return self.value -class NativeStageStorage(SqlStorage): +class NativeStageStorage(ExplicitSqlStorage): """A nullable stage column keeps the execution family's generated name CHECK.""" sql_type = "TEXT" - @classmethod - def accepts(cls, annotation: object) -> bool: - return False # Declared on the column; a NativeColumn names no family itself. - @classmethod def constraints(cls, column: str, annotation: object = None) -> tuple[str, ...]: return (NativeInputExecution.sql_constraint(column),) diff --git a/src/agent_comms/execution/transcript_sources.py b/src/agent_comms/execution/transcript_sources.py index d18e35876d..374612cca2 100644 --- a/src/agent_comms/execution/transcript_sources.py +++ b/src/agent_comms/execution/transcript_sources.py @@ -96,7 +96,16 @@ from agent_comms.transport.tool_declaration import ToolDeclaration -class WireFrontier(DeclaredFamily, ResolvesSentReports, affix="WireFrontier"): +class UnassignedSentReportResolver(ResolvesSentReports): + """A sent-report resolver for sources without sender assignment qualification.""" + + def resolve_sent( + self, messages: tuple[SentTranscript, ...], + ) -> tuple[SentTranscript | PublishedSentMessage, ...]: + return tuple(messages) + + +class WireFrontier(DeclaredFamily, UnassignedSentReportResolver, affix="WireFrontier"): """The wire coordinate owns cursor construction, bounds and source authority.""" sequence: int @@ -122,11 +131,6 @@ def require_source(self, identity: AssignedSourceIdentity) -> None: def require_native(self) -> None: """An unassigned position carries only the native coordinate.""" - def resolve_sent( - self, messages: tuple[SentTranscript, ...], - ) -> tuple[SentTranscript | PublishedSentMessage, ...]: - return tuple(messages) - @dataclass(frozen=True) class NoWireFrontier(WireFrontier): @@ -398,7 +402,11 @@ class CapturedTranscriptAppend: events: tuple[TranscriptEvent, ...] -class TranscriptSource(TranscriptHistorySource, ReadsPublishedMessages, ResolvesSentReports): +class TranscriptSource( + TranscriptHistorySource, + ReadsPublishedMessages, + UnassignedSentReportResolver, +): """Recorded items alone carry no assigned-wire or publication authority. Native and external stores supply their original records. An assigned @@ -516,10 +524,6 @@ def project(records, *, max_records: int, max_bytes: int): def sent_messages(self, references: Iterable[MessageReference]) -> dict[MessageReference, Message]: return {} - def resolve_sent(self, messages: tuple[SentTranscript, ...]): - """Records without a sender assignment cannot qualify Send reports.""" - return tuple(messages) - frontier = NoWireFrontier() def window(self, *, limit: int = 1, sent_limit: int = 0) -> AssignedSourceWindow: @@ -656,8 +660,15 @@ def with_prefix(self, prefix: TranscriptCursor) -> TranscriptCursor: return self.at_offset(prefix.offset) +class NoOpReadTranscriptCursor(TranscriptCursor, declared_name=None): + """A transcript cursor with no displayed messages to mark read.""" + + def mark_read(self, reads: MarksSourceRead[RecordsCut], viewer: str, runtime: TranscriptRuntime) -> None: + ... + + @dataclass(frozen=True, slots=True) -class UnreadTranscriptCursor(TranscriptCursor): +class UnreadTranscriptCursor(NoOpReadTranscriptCursor, TranscriptCursor): """No source has been read; this is not a source position or a read mark.""" def contains(self, other: TranscriptCursor) -> bool: @@ -697,9 +708,6 @@ def at_offset(self, offset: int) -> TranscriptCursor: def with_frontier(self, frontier: WireFrontier) -> TranscriptCursor: return self - def mark_read(self, reads: MarksSourceRead[RecordsCut], viewer: str, runtime: TranscriptRuntime) -> None: - """Nothing has been drawn, so there is nothing to acknowledge.""" - class FileTranscriptCursor(TranscriptCursor, declared_name=None): """A position in a file's bytes: a session rewritten through os.replace is another file, diff --git a/src/agent_comms/execution/unstarted_runtime.py b/src/agent_comms/execution/unstarted_runtime.py index 5109918c41..a44227f688 100644 --- a/src/agent_comms/execution/unstarted_runtime.py +++ b/src/agent_comms/execution/unstarted_runtime.py @@ -56,8 +56,15 @@ def history_source(self, root, incarnation): return ExternalTranscript(root, incarnation) +class UnwrittenRuntimeLocation(ExternalTranscriptLocation, declared_name=None): + """A runtime location with no recorded transcript write timestamp.""" + + def last_written(self) -> float: + return 0.0 + + @dataclass(frozen=True) -class UnstartedRuntime(ExternalTranscriptLocation): +class UnstartedRuntime(UnwrittenRuntimeLocation): owner: type[AgentBackend] def is_resumable(self) -> bool: return False @@ -73,10 +80,6 @@ def path(self) -> str: def require_forkable(self): raise ValueError("Canonical saved session required") - def last_written(self) -> float: - """No saved session exists to have grown.""" - return 0.0 - async def compact(self, operation): return FailedCompaction("This thread has no saved session to compact.") diff --git a/src/agent_comms/history_views.py b/src/agent_comms/history_views.py index 859729d3d0..fdd4f3c337 100644 --- a/src/agent_comms/history_views.py +++ b/src/agent_comms/history_views.py @@ -13,7 +13,7 @@ from typing import Annotated from agent_comms.bus_context import BusViews, ThreadPresentationBatch -from agent_comms.cli_verbs.cli_result import CliResult +from agent_comms.cli_verbs.cli_result import PresenceExcludedReply from agent_comms.context_segments.retained import RetainedSegment from agent_comms.coordination.errors import DeferredRead, StaleRevision from agent_comms.errors import UnknownChannelError @@ -59,7 +59,7 @@ from agent_comms.messaging.retained_task_facts import RetainedTaskFacts from agent_comms.messaging.revision_views import ActivityView from agent_comms.messaging.sent_message import AssignedSourceIdentity -from agent_comms.nominal.field_codec import FieldCodec, PresenceExclude, WireForm +from agent_comms.nominal.field_codec import WireForm from agent_comms.notification_assignment import NotificationAssignment, NotificationSelection from agent_comms.projects.checkouts import Checkout from agent_comms.ui_model.retired_views import RetiredViews @@ -119,16 +119,13 @@ @dataclass(frozen=True) -class ThreadPoll(CliResult): +class ThreadPoll(PresenceExcludedReply): """One thread's state, its inbox, the shared ledger and its peers at one read.""" thread: ThreadRecord inbox: tuple[Annotated[Message, WireForm], ...] ledger: Annotated[LedgerDocument, WireForm] peers: tuple[ThreadView, ...] - def to_wire(self) -> object: - return FieldCodec.project(self, PresenceExclude) - @dataclass(frozen=True) class ThreadViewRead(ConversationPreparation): diff --git a/src/agent_comms/input_attempt.py b/src/agent_comms/input_attempt.py index 14a86a54d5..8d07abcb7e 100644 --- a/src/agent_comms/input_attempt.py +++ b/src/agent_comms/input_attempt.py @@ -14,8 +14,8 @@ from agent_comms.execution.native_input_proof import NativeContextProof from agent_comms.execution.reported_turn import ReportedTurnState from agent_comms.messaging.notification_progress import ( - ConsumptionEvidence, DeliveryProgress, + PassthroughConsumptionEvidence, ShownToModelProgress, ) from agent_comms.nominal.declared_family import DeclaredFamily @@ -99,7 +99,12 @@ def require_moved(self, refusal: str) -> MovedInput: @dataclass(frozen=True) -class InputAttempt(LifecycleCapability, ConsumptionEvidence, DeclaredFamily, affix="Input"): +class InputAttempt( + LifecycleCapability, + PassthroughConsumptionEvidence, + DeclaredFamily, + affix="Input", +): def counts_as_started(self) -> bool: return False @@ -160,9 +165,6 @@ def context_provenance(self) -> input_origin.InputProvenance: def model_contexts(self) -> tuple[NativeContextProof, ...]: return () - def consumed_progress(self, progress: DeliveryProgress) -> DeliveryProgress: - return progress - def context_committed( self, lease: TurnFence, diff --git a/src/agent_comms/installer/build_identity.py b/src/agent_comms/installer/build_identity.py index 25748f7439..f4230c2b5b 100644 --- a/src/agent_comms/installer/build_identity.py +++ b/src/agent_comms/installer/build_identity.py @@ -70,8 +70,15 @@ class UninstalledRepositoryCommitInstallation(InstalledCommitInstallation): merged_state = "no runtime install" +class UninstalledCommitState(CommitInstallation, declared_name=None): + """A commit installation state that marks merged orders waiting for install.""" + + def after_merge(self, todo: Todo, merged: MergedProblemOrder) -> Todo: + return merged.waiting_in(todo) + + @dataclass(frozen=True) -class MissingCommitInstallation(CommitInstallation): +class MissingCommitInstallation(UninstalledCommitState): commit: str installed: RecordedBuildIdentity merged_state = "waiting on install" @@ -81,21 +88,15 @@ def require(self) -> None: f"Delivered commit {self.commit} is not contained in installed {self.installed}." ) - def after_merge(self, todo: Todo, merged: MergedProblemOrder) -> Todo: - return merged.waiting_in(todo) - @dataclass(frozen=True) -class NoRuntimeCommitInstallation(CommitInstallation): +class NoRuntimeCommitInstallation(UninstalledCommitState): """No runtime is installed on this home, so it contains no delivered commit.""" merged_state = "no runtime installed" def require(self) -> None: raise DeliveredCommitNotInstalledError("No agent-comms runtime is installed on this home.") - def after_merge(self, todo: Todo, merged: MergedProblemOrder) -> Todo: - return merged.waiting_in(todo) - class InstalledBuild(ABC): """The build this home runs, which the board reads merged orders against.""" diff --git a/src/agent_comms/installer/native_build_inputs.py b/src/agent_comms/installer/native_build_inputs.py index b0c67129ad..654d2efdbf 100644 --- a/src/agent_comms/installer/native_build_inputs.py +++ b/src/agent_comms/installer/native_build_inputs.py @@ -205,19 +205,20 @@ def of(cls, checkout: Path) -> CloneShape: return shape -class UnreadableClone(CloneShape): - """Git could not read the checkout's configuration. The read itself then fails through its - caller's own Git failure, and the next read probes again instead of remembering this.""" +class PlainReadCloneShape(CloneShape): + """A clone shape that passes no extra git read options.""" def read_options(self, program: Path) -> tuple[str, ...]: return () -class FullClone(CloneShape): - """Every object is local, so a read can never fetch: reads pass nothing, on any Git.""" +class UnreadableClone(PlainReadCloneShape): + """Git could not read the checkout's configuration. The read itself then fails through its + caller's own Git failure, and the next read probes again instead of remembering this.""" - def read_options(self, program: Path) -> tuple[str, ...]: - return () + +class FullClone(PlainReadCloneShape): + """Every object is local, so a read can never fetch: reads pass nothing, on any Git.""" class PartialClone(CloneShape): diff --git a/src/agent_comms/messaging/messages.py b/src/agent_comms/messaging/messages.py index 72574ffe1a..05d9f9e93d 100644 --- a/src/agent_comms/messaging/messages.py +++ b/src/agent_comms/messaging/messages.py @@ -60,7 +60,7 @@ ResponsePolicy, ) from agent_comms.messaging.task_attachment import NoTaskAttachment, TaskAttachment -from agent_comms.messaging.task_fact_base import ExactTaskFact +from agent_comms.messaging.task_fact_base import ExactTaskFact, SingleSourceTaskFact from agent_comms.nominal.class_fact import ClassFact from agent_comms.nominal.compact_text import CompactText from agent_comms.nominal.declared_family import DeclaredFamily @@ -1399,12 +1399,9 @@ def retained_task_facts(self) -> Iterator[ExactTaskFact]: @dataclass(frozen=True) -class UserSourceTaskFact(ExactTaskFact): +class UserSourceTaskFact(SingleSourceTaskFact): source: Message - def wire_sources(self): - return (self.source,) - def __post_init__(self) -> None: self.source.sender_role.require_user( RelationViolationError("A peer message is not an original user source") @@ -1412,11 +1409,8 @@ def __post_init__(self) -> None: @dataclass(frozen=True) -class ClaimTaskFact(ExactTaskFact): +class ClaimTaskFact(SingleSourceTaskFact): source: ClaimMessage def __post_init__(self) -> None: self.source.require_claim_transition() - - def wire_sources(self): - return (self.source,) diff --git a/src/agent_comms/messaging/notification_progress.py b/src/agent_comms/messaging/notification_progress.py index 2b8076f7bb..9ad8efa764 100644 --- a/src/agent_comms/messaging/notification_progress.py +++ b/src/agent_comms/messaging/notification_progress.py @@ -211,6 +211,13 @@ class ConsumptionEvidence(ABC): def consumed_progress(self, progress: DeliveryProgress) -> DeliveryProgress: ... +class PassthroughConsumptionEvidence(ConsumptionEvidence): + """Consumption evidence that preserves the recorded delivery progress unchanged.""" + + def consumed_progress(self, progress: DeliveryProgress) -> DeliveryProgress: + return progress + + class ReadDelivery(SettledDelivery): """The recipient opened or read this message; its summary is counted, never raw-prefixed.""" @@ -357,8 +364,15 @@ class FailedProgress(ContextualProgress): label = "Failed" +class OfflineVisibleContextualProgress(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, ContextualProgress): +class AnsweredProgress(ReadDelivery, OfflineVisibleContextualProgress): response: AnsweredResponse label = "Answered" @@ -366,9 +380,6 @@ class AnsweredProgress(ReadDelivery, ContextualProgress): def answer(self) -> AnsweredResponse: return self.response - def shown_when_offline(self) -> bool: - return True - def answered_notification(self, notification: AssignmentNotice[DeliveryProgress], response: AnsweredResponse) -> AssignmentNotice[DeliveryProgress]: """A later independent response cannot replace an already recorded answer.""" @@ -381,15 +392,12 @@ def summary_counts(self, *, displayed: bool = False) -> DeliverySummaryCounts: return DeliverySummaryCounts(read=1, answered=1) -class CompletedProgress(ReadDelivery, ContextualProgress): +class CompletedProgress(ReadDelivery, OfflineVisibleContextualProgress): """Workflow completion is not evidence of an independent reply.""" label = "Completed" detail = "The response workflow completed." - def shown_when_offline(self) -> bool: - return True - class AssignmentProgress(DeliveryProgress): @property diff --git a/src/agent_comms/messaging/retained_task_facts.py b/src/agent_comms/messaging/retained_task_facts.py index fd017237df..b824676c9b 100644 --- a/src/agent_comms/messaging/retained_task_facts.py +++ b/src/agent_comms/messaging/retained_task_facts.py @@ -17,7 +17,7 @@ from agent_comms.messaging.message_reads import ConversationRead from agent_comms.messaging.message_reference import MessageReference from agent_comms.messaging.messages import UserSourceTaskFact -from agent_comms.messaging.task_fact_base import ExactTaskFact +from agent_comms.messaging.task_fact_base import ExactTaskFact, SingleSourceTaskFact from agent_comms.nominal.field_codec import FieldCodec from agent_comms.nominal.text_digest import TextDigest from agent_comms.registry.task_owner import TaskOwner @@ -26,16 +26,13 @@ @dataclass(frozen=True) -class AuthoredTaskFact(ExactTaskFact): +class AuthoredTaskFact(SingleSourceTaskFact): """Captured projection only; its original declaration owns applicability.""" source: messages.Message def authored_sources(self): return (self.source,) - def wire_sources(self): - return (self.source,) - @abstractmethod def current_fact(self): ... diff --git a/src/agent_comms/messaging/task_fact_base.py b/src/agent_comms/messaging/task_fact_base.py index 2ba8392ee4..08a9125cbd 100644 --- a/src/agent_comms/messaging/task_fact_base.py +++ b/src/agent_comms/messaging/task_fact_base.py @@ -32,3 +32,10 @@ def for_tasks(self, current: frozenset[MessageReference]) -> ExactTaskFact: def for_owner(self, owner, registry) -> ExactTaskFact: return self + + +class SingleSourceTaskFact(ExactTaskFact, declared_name=None): + """An exact task fact backed by a single wire source message.""" + + def wire_sources(self): + return (self.source,) diff --git a/src/agent_comms/planning/pull_requests.py b/src/agent_comms/planning/pull_requests.py index c79a0d92c0..f329b02d94 100644 --- a/src/agent_comms/planning/pull_requests.py +++ b/src/agent_comms/planning/pull_requests.py @@ -202,17 +202,21 @@ def remedy(self) -> str: return "restore the repository's write access or drop it from the teammate's repos" -@dataclass(frozen=True) -class BehindMergeBlock(MergeBlock): - def what(self) -> str: - return 'BEHIND: head is behind its base' +class QueueMergeBlock(MergeBlock, declared_name=None): + """A merge block whose remedy is to wait in or enter the merge queue.""" def remedy(self) -> str: return 'queue' @dataclass(frozen=True) -class WaitingMergeBlock(MergeBlock): +class BehindMergeBlock(QueueMergeBlock): + def what(self) -> str: + return 'BEHIND: head is behind its base' + + +@dataclass(frozen=True) +class WaitingMergeBlock(QueueMergeBlock): """The grace period belongs to the cause, not to a second standing rule.""" seconds: ClassVar[int] = 3 * 60 @@ -223,9 +227,6 @@ def since(self) -> float: def what(self) -> str: return 'required checks finished but the armed head has not merged' - def remedy(self) -> str: - return 'queue' - @dataclass(frozen=True) class PullRequestUpdate: diff --git a/src/agent_comms/practice_fixture.py b/src/agent_comms/practice_fixture.py index 7a2555ee5e..82eee3be05 100644 --- a/src/agent_comms/practice_fixture.py +++ b/src/agent_comms/practice_fixture.py @@ -47,16 +47,19 @@ def declare(comms: Comms, request: FixtureRequest, *names: str) -> None: Checkout(directory))) -class EmptyInboxScenario(PracticeScenario): +class DeclaredParticipantScenario(PracticeScenario, declared_name=None): + """A practice scenario prepared by declaring its reader and sender threads.""" + def prepare(self, comms: Comms, request: FixtureRequest) -> None: self.declare(comms, request, request.reader, request.sender) -class LateMessageScenario(PracticeScenario): - """Start empty; the CPU harness invokes PublishFixtureMessage after observing that read.""" +class EmptyInboxScenario(DeclaredParticipantScenario): + pass - def prepare(self, comms: Comms, request: FixtureRequest) -> None: - self.declare(comms, request, request.reader, request.sender) + +class LateMessageScenario(DeclaredParticipantScenario): + """Start empty; the CPU harness invokes PublishFixtureMessage after observing that read.""" class ArchivedTargetScenario(PracticeScenario): diff --git a/src/agent_comms/registry/recipient_activity.py b/src/agent_comms/registry/recipient_activity.py index 081dab66c6..84ac3633e3 100644 --- a/src/agent_comms/registry/recipient_activity.py +++ b/src/agent_comms/registry/recipient_activity.py @@ -51,9 +51,8 @@ def shows_notification( return displayed or notification.state.shown_when_offline() -@dataclass(frozen=True) -class OnlineRecipientActivity(RecipientActivity): - """An online recipient without a live native turn lease (for example an active CLI bridge).""" +class NotifyingRecipientActivity(RecipientActivity, declared_name=None): + """A recipient activity state that displays assignment notifications.""" def shows_notification( self, notification: AssignmentNotice[DeliveryProgress], *, displayed: bool, @@ -62,7 +61,12 @@ def shows_notification( @dataclass(frozen=True) -class RecordedRecipientActivity(RecipientActivity): +class OnlineRecipientActivity(NotifyingRecipientActivity): + """An online recipient without a live native turn lease (for example an active CLI bridge).""" + + +@dataclass(frozen=True) +class RecordedRecipientActivity(NotifyingRecipientActivity): """Durable history supplies no current process, readiness or inbox check.""" def displayed_recipient(self, notification, source, reads, document, snapshot) -> tuple[ThreadIncarnation, ...]: @@ -70,11 +74,6 @@ def displayed_recipient(self, notification, source, reads, document, snapshot) - source.message, notification.recipient_identity, snapshot, document=document ) - def shows_notification( - self, notification: AssignmentNotice[DeliveryProgress], *, displayed: bool, - ) -> bool: - return True - @dataclass(frozen=True) class UnavailableRecipientActivity(RecipientActivity): diff --git a/src/agent_comms/registry/thread_status.py b/src/agent_comms/registry/thread_status.py index 8ad9bd4077..3e3de261be 100644 --- a/src/agent_comms/registry/thread_status.py +++ b/src/agent_comms/registry/thread_status.py @@ -362,14 +362,22 @@ def process_seen(self, process: ProcessState) -> ThreadStatus: return RunningThreadStatus().process_seen(process) -class RunningThreadStatus(SelfRenaming, ActiveThreadPresence): - def is_running(self) -> bool: - return True +class LiveAnsweringThreadStatus(ThreadStatus, declared_name=None): + """A thread status whose bridge answers deliveries later.""" @property def answers_later(self) -> bool: return True + +class RunningThreadStatus( + LiveAnsweringThreadStatus, + SelfRenaming, + ActiveThreadPresence, +): + def is_running(self) -> bool: + return True + def declaration(self) -> ThreadStatus: return ProcessThreadStatus() @@ -466,7 +474,13 @@ def claimed_readers(self, name: str) -> tuple[str, ...]: return (name,) -class PausedBridgeThreadStatus(SelfRenaming, DeclaredReaderPresence, AlwaysListed, StoppedPresence): +class PausedBridgeThreadStatus( + LiveAnsweringThreadStatus, + SelfRenaming, + DeclaredReaderPresence, + AlwaysListed, + StoppedPresence, +): """A live session bridge waiting for a Monitor to confirm its probe.""" def registered(self, thread: PresenceThread, last_seen: float) -> ThreadStatus: @@ -475,12 +489,6 @@ def registered(self, thread: PresenceThread, last_seen: float) -> ThreadStatus: def paused_since(self, last_seen: float) -> tuple[float, ...]: return (last_seen,) - @property - def answers_later(self) -> bool: - """Its live bridge keeps every delivery until a Monitor confirms the probe, so a - wait on it is answered; only a dead bridge (NoBridgeThreadStatus) is not.""" - return True - class NoBridgeThreadStatus(SelfRenaming, CliInboxPresence, StoppedPresence): """A CLI inbox with no bridge attached; its messages wait unread. diff --git a/src/agent_comms/storage/typed_table.py b/src/agent_comms/storage/typed_table.py index e7bcaacec5..b8d80c4178 100644 --- a/src/agent_comms/storage/typed_table.py +++ b/src/agent_comms/storage/typed_table.py @@ -165,6 +165,14 @@ def for_type(cls, annotation: object) -> type[SqlStorage]: raise TypeError(f"Unsupported SQLite field type: {annotation!r}") +class ExplicitSqlStorage(SqlStorage, declared_name=None): + """A SQL storage codec selected explicitly rather than by annotation matching.""" + + @classmethod + def accepts(cls, annotation: object) -> bool: + return False # Declared on the column; a NativeColumn names no family itself. + + class TextStorage(SqlStorage): sql_type = "TEXT" @@ -255,15 +263,11 @@ def accepts(cls, annotation: object) -> bool: return get_origin(annotation) is type and bool(args) and issubclass(args[0], DeclaredFamily) -class ExactStorage(SqlStorage): +class ExactStorage(ExplicitSqlStorage): """SQLite ANY retains the input storage class without affinity coercion.""" sql_type = "ANY" - @classmethod - def accepts(cls, annotation: object) -> bool: - return False # Explicit field capability, never an inferred representation. - class JsonStorage(SqlStorage): sql_type = "TEXT" @@ -3408,6 +3412,14 @@ def declaring_owner(cls): return super(RootFile, cls).declaring_owner() +class SelfSchemaReconciledFile(ReconciledFile, declared_name=None): + """A reconciled SQLite file whose declaring class is its own table schema.""" + + @classmethod + def table_schema(cls) -> type[TableSchema]: + return cls + + class ExternalStore(ExternalFile, DeclaredFamily, affix="Store"): """Durable files outside the bus that their own writer owns. An installed package declares each one through the ``agent_comms.writer_owned_stores`` entry point; the installer @@ -3706,13 +3718,9 @@ def snapshot(self) -> Iterator[sqlite3.Connection]: yield connection -class DurableStore(ReconciledFile, TypedStore, DurableTables, CarriedWriter): +class DurableStore(SelfSchemaReconciledFile, TypedStore, DurableTables, CarriedWriter): """Rows nothing else can rebuild, in a file every installation carries.""" - @classmethod - def table_schema(cls) -> type[TableSchema]: - return cls - class DerivedStore(TypedStore, DerivedTables, RuntimeWriter): """Rows rebuilt from another source, in a file running owners rewrite at any time, diff --git a/src/agent_comms/task_attachments/team_pings.py b/src/agent_comms/task_attachments/team_pings.py index 1894406b20..530b21eb20 100644 --- a/src/agent_comms/task_attachments/team_pings.py +++ b/src/agent_comms/task_attachments/team_pings.py @@ -685,13 +685,17 @@ def members(cls, packets: tuple[TeamUpdate, ...], return tuple(line for ping in opened for line in ping.alarm_pings() if line not in new_members) -class WatchingAlarms(MainAlarms): - """A still-failing source remains visible, but it has no teammate disposal to wake for.""" +class RetainedAlarmGroup(AlarmGroup, declared_name=None): + """An alarm group that does not require disposal.""" @classmethod def needs_disposal(cls) -> bool: return False + +class WatchingAlarms(RetainedAlarmGroup, MainAlarms): + """A still-failing source remains visible, but it has no teammate disposal to wake for.""" + @classmethod def members(cls, packets: tuple[TeamUpdate, ...], opened: tuple[Ping, ...], new: tuple[Ping, ...]) -> tuple[Ping, ...]: @@ -700,14 +704,10 @@ def members(cls, packets: tuple[TeamUpdate, ...], if not ping.team_disposes for line in ping.alarm_pings() if line not in new_members) -class ParkedAlarms(AlarmGroup): +class ParkedAlarms(RetainedAlarmGroup, AlarmGroup): """Lines waiting on a stopped thread: one count below the cards, never on the board. Their rows stay in comms_hud's records, and return when the thread runs again.""" - @classmethod - def needs_disposal(cls) -> bool: - return False - @classmethod def row_lines(cls, section: AlarmSection, now: float) -> tuple[str, ...]: return () diff --git a/src/agent_comms/team/standing.py b/src/agent_comms/team/standing.py index fd125a4594..ef2eaad948 100644 --- a/src/agent_comms/team/standing.py +++ b/src/agent_comms/team/standing.py @@ -81,6 +81,7 @@ OwedAnswer, OwnerFlaggedStandingRule, ReasonedStandingRule, + SinceDatedStandingRule, StandingRule, UndatedStandingRule, UrgentStandingRule, @@ -687,7 +688,12 @@ class WaitingUnownedWheelSpin(UnownedWheelSpin): @dataclass(frozen=True) -class HeartbeatSilent(IndependentStandingRule, DatedStandingRule, FamilyScan, declared_name=None): +class HeartbeatSilent( + IndependentStandingRule, + SinceDatedStandingRule, + FamilyScan, + declared_name=None, +): """A missing or stale successful pass, independent of whether a DM needed sending.""" seconds: ClassVar[float] = TeamPass.completion_ceiling() @@ -720,9 +726,6 @@ def violations(cls, comms: Comms, *, found.append(rule) return tuple(found) - def began(self) -> float: - return self.since - @dataclass(frozen=True) class MissedHeartbeat(HeartbeatSilent): @@ -744,7 +747,11 @@ def line(self) -> str: @dataclass(frozen=True) -class InboxUnavailable(IndependentStandingRule, DatedStandingRule, declared_name=None): +class InboxUnavailable( + IndependentStandingRule, + SinceDatedStandingRule, + declared_name=None, +): """A thread nothing can reach: every message sent to it waits undelivered. Each member owns how its inbox reports the pause; the window and the date are shared. @@ -768,9 +775,6 @@ def violations(cls, comms: Comms, *, if rule.since < now ) - def began(self) -> float: - return self.since - @dataclass(frozen=True) class TeamDeaf(InboxUnavailable, declared_name="team_deaf"): diff --git a/src/agent_comms/team/standing_rules.py b/src/agent_comms/team/standing_rules.py index ca3e8b7322..2197bbf8ee 100644 --- a/src/agent_comms/team/standing_rules.py +++ b/src/agent_comms/team/standing_rules.py @@ -905,6 +905,13 @@ def broke_after(self, after: float) -> bool: return self.began() >= after +class SinceDatedStandingRule(DatedStandingRule, declared_name=None): + """A dated standing rule whose start timestamp is stored in self.since.""" + + def began(self) -> float: + return self.since + + @dataclass(frozen=True) class OwedAnswer(IndependentStandingRule, FamilyScan, declared_name=None): """A question or delivery awaiting the teammate; each member owns what clears it @@ -1302,8 +1309,15 @@ class HeadReviewTimerUp(OrderHeadReviewCommands, ReviewTimerUp): """A timer with a current PR head offers only that order's accepted verdicts.""" +class DueAtDatedStandingRule(DatedStandingRule, declared_name=None): + """A dated standing rule whose start timestamp is stored in self.due_at.""" + + def began(self) -> float: + return self.due_at + + @dataclass(frozen=True) -class DeliveredHeadReview(HeldOrderLine, DatedStandingRule): +class DeliveredHeadReview(HeldOrderLine, DueAtDatedStandingRule): """A recorded delivery waits on a review of its current ready PR head.""" repo: RepositoryName @@ -1338,9 +1352,6 @@ def scan_observed( ) ) - def began(self) -> float: - return self.due_at - def subjects(self) -> tuple[HeartbeatSubject, ...]: return (*super().subjects(), HeadSubject(PullRequestHead(self.repo, self.pr, self.head))) @@ -1351,7 +1362,12 @@ def line(self) -> str: @dataclass(frozen=True) -class UnreviewedHead(HeadLine, HeadReviewCommands, DatedStandingRule, declared_name=None): +class UnreviewedHead( + HeadLine, + HeadReviewCommands, + DueAtDatedStandingRule, + declared_name=None, +): """One ready head waiting too long for a decision; a reviewing mark is not one.""" due_at: float seconds: ClassVar[int] = 10 * 60 @@ -1386,9 +1402,6 @@ def scan_reviews(cls, goals: Goals, pulls: ProgressRead, *, def for_head(cls, request: PullRequestHead, due: float, todos: Sequence[Todo]) -> tuple[Self, ...]: return (cls(request=request, due_at=due),) - def began(self) -> float: - return self.due_at - def line(self) -> str: return (f"JUDGE {self.request.repo.to_wire()}#{self.request.pr} {self.request.head[:9]} is sitting" f" there unjudged. you read it yet?") @@ -1601,7 +1614,7 @@ def line(self) -> str: @dataclass(frozen=True) -class HuntDue(ReasonedStandingRule, DatedStandingRule, FamilyScan): +class HuntDue(ReasonedStandingRule, SinceDatedStandingRule, FamilyScan): """Its scan picks the located member when a hot file is known; the members share it.""" since: float @@ -1650,9 +1663,6 @@ def line(self) -> str: return ("HUNT nothing hot found in any held order's production source. so what's slow?" " -> hunt it and order the fix this wake") - def began(self) -> float: - return self.since - @dataclass(frozen=True) class LocatedHuntDue(HuntDue): @@ -1718,7 +1728,12 @@ def line(self) -> str: @dataclass(frozen=True) -class ServicePassFailing(FailingPass, IndependentStandingRule, DatedStandingRule, FamilyScan): +class ServicePassFailing( + FailingPass, + IndependentStandingRule, + SinceDatedStandingRule, + FamilyScan, +): """A Core service watch whose newest pass failed; the connector's log reaches nobody.""" watch: str @@ -1736,9 +1751,6 @@ def from_passes(cls, passes: ServicePasses) -> tuple[Self, ...]: failed_at=failed.failed_at) for watch, failed in sorted(passes.failing.items())) - def began(self) -> float: - return self.since - def line(self) -> str: return self.failure_line(self.watch) diff --git a/src/agent_comms/thread_views.py b/src/agent_comms/thread_views.py index 34f6e75288..9d0fd208c8 100644 --- a/src/agent_comms/thread_views.py +++ b/src/agent_comms/thread_views.py @@ -8,13 +8,12 @@ from functools import partial from typing import Annotated -from agent_comms.cli_verbs.cli_result import CliResult +from agent_comms.cli_verbs.cli_result import PresenceExcludedReply from agent_comms.execution.process_identity import NoProcess, ProcessState from agent_comms.execution.runtime_info import RuntimeInfo from agent_comms.messaging.pending_count_source import PendingCountSource from agent_comms.nominal.declared_family import DeclaredFamily from agent_comms.nominal.field_codec import ( - FieldCodec, JsonShapeFamily, JsonShapeMember, PresenceExclude, @@ -83,7 +82,7 @@ def counts(self, bus: PendingCountSource, names: Sequence[str]) -> Mapping[str, @dataclass(frozen=True, slots=True) -class ThreadRecord(CliResult): +class ThreadRecord(PresenceExcludedReply): """A thread's wire record; every reader of one thread writes these fields from here.""" thread: Annotated[Thread, WireInline()] @@ -147,9 +146,6 @@ def read( for thread, goal in zip(threads, executions, strict=True) ) - def to_wire(self) -> object: - return FieldCodec.project(self, PresenceExclude) - def compact_text(self) -> str: bits = [f"{self.thread.name} [{self.status.declared_name}]"] if self.thread.tags: diff --git a/src/agent_comms/transcript/no_native_transcript_cursor.py b/src/agent_comms/transcript/no_native_transcript_cursor.py index 4bfc7ecc41..ef0063fb90 100644 --- a/src/agent_comms/transcript/no_native_transcript_cursor.py +++ b/src/agent_comms/transcript/no_native_transcript_cursor.py @@ -3,10 +3,9 @@ from dataclasses import dataclass, field, replace from agent_comms.agent_backend import RuntimeLocation -from agent_comms.execution.transcript_cursor_reads import MarksSourceRead, TranscriptRuntime -from agent_comms.execution.transcript_record_base import RecordsCut from agent_comms.execution.transcript_sources import ( FileTranscriptCursor, + NoOpReadTranscriptCursor, NoWireFrontier, TranscriptCursor, WireFrontier, @@ -15,7 +14,7 @@ @dataclass(frozen=True, slots=True) -class NoNativeTranscriptCursor(FileTranscriptCursor): +class NoNativeTranscriptCursor(NoOpReadTranscriptCursor, FileTranscriptCursor): """A thread owns no native read mark, even while showing an inherited source.""" source: RuntimeLocation = field(kw_only=True) @@ -29,6 +28,3 @@ def session_file(self) -> str | None: def with_frontier(self, frontier: WireFrontier) -> TranscriptCursor: return replace(self, wire=frontier) - - def mark_read(self, reads: MarksSourceRead[RecordsCut], viewer: str, runtime: TranscriptRuntime) -> None: - """There is no painted native transcript to acknowledge.""" diff --git a/src/agent_comms/transcript/transcript_events.py b/src/agent_comms/transcript/transcript_events.py index e9a0d6fd7b..c7ea24ad65 100644 --- a/src/agent_comms/transcript/transcript_events.py +++ b/src/agent_comms/transcript/transcript_events.py @@ -175,7 +175,15 @@ class RecordedTranscript(TranscriptEvent): routing: Routing = NoTurnRouting() -class TextTranscript(TranscriptEvent): +class TextSizedTranscriptEvent(TranscriptEvent, declared_name=None): + """A transcript event whose text_size is the length of self.text.""" + + @property + def text_size(self) -> int: + return len(self.text) + + +class TextTranscript(TextSizedTranscriptEvent, TranscriptEvent): text: str def activity_items(self) -> tuple[TranscriptEvent, ...]: @@ -194,10 +202,6 @@ def as_context(self) -> ContextTranscript: starts_activity = True - @property - def text_size(self) -> int: - return len(self.text) - @dataclass(frozen=True) class NativeTextTranscript(TextTranscript, RecordedTranscript): @@ -501,7 +505,7 @@ def import_to(self, accept: Callable[[ImportedMessage], None]) -> None: @dataclass(frozen=True, kw_only=True) -class ToolEndTranscript(ToolTranscript): +class ToolEndTranscript(TextSizedTranscriptEvent, ToolTranscript): def sent_reports(self) -> tuple[SentTranscript, ...]: return self.sent_message.sent_reports() @@ -517,10 +521,6 @@ def parts_for(text, diff=NoToolDiff(), sent_message=NoSentMessage()): def result_parts(self): return self.parts_for(self.text, self.diff, self.sent_message) - @property - def text_size(self) -> int: - return len(self.text) - def without_tool_result(self, tool_name: str) -> TranscriptEvent: """A tool never embeds a prior rendering of its own transcript read. diff --git a/src/agent_comms/transport/tool_caller.py b/src/agent_comms/transport/tool_caller.py index f2c0cf37fe..c3ea0192c2 100644 --- a/src/agent_comms/transport/tool_caller.py +++ b/src/agent_comms/transport/tool_caller.py @@ -119,8 +119,15 @@ def origin(self) -> AgentOrigin: return AgentOrigin() +class NonDirectiveToolCaller(ToolCaller): + """A tool caller that imposes no directive requirement.""" + + def require_directive(self, comms: BusContext, body: str) -> None: + ... + + @dataclass(frozen=True) -class NoThreadCaller(OperatorOutcomes, ToolCaller): +class NoThreadCaller(OperatorOutcomes, NonDirectiveToolCaller): def history_viewer(self, named: str) -> DisplayViewer: """Omitted participant means an anonymous channel read, not an agent identity.""" return FieldCodec.decode(DisplayViewer, named or None) @@ -146,9 +153,6 @@ def catalog(self, comms: BusContext, tools: tuple[dict[str, object], ...]) -> To def from_flag(self) -> tuple[str, ...]: return () - def require_directive(self, comms: BusContext, body: str) -> None: - """A caller with no thread gives no directive.""" - @dataclass(frozen=True) class HumanCaller(NoThreadCaller): @@ -159,7 +163,7 @@ def require_human(self) -> None: @dataclass(frozen=True) -class ThreadCaller(ToolCaller): +class ThreadCaller(NonDirectiveToolCaller): name: str def teammate(self) -> ThreadCaller: @@ -214,9 +218,6 @@ def own_incarnation(self, comms: BusContext) -> ThreadIncarnation: told to that caller.""" return comms.registry.require(self.name).incarnation - def require_directive(self, comms: BusContext, body: str) -> None: - """A unit's or a script's send is a message, not a directive.""" - @dataclass(frozen=True) class SubagentCaller(ThreadCaller):