diff --git a/src/agent_comms/agent_backend.py b/src/agent_comms/agent_backend.py index a35293f15e..27837a14e8 100644 --- a/src/agent_comms/agent_backend.py +++ b/src/agent_comms/agent_backend.py @@ -117,6 +117,15 @@ def acknowledge_direct_turn_inputs( bridge: type[HarnessSession], ) -> None: ... + @abstractmethod + def ignore_direct_turn_inputs( + self, + thread: Thread, + origins: tuple[Message, ...], + *, + bridge: type[HarnessSession], + ) -> None: ... + class TurnTranscriptSink: """Per-turn transcript publisher for backends whose history lives in ``ExternalTranscript``.""" @@ -448,6 +457,16 @@ def acknowledge_turn_inputs( """Record model-context delivery acknowledgements when a backend starts origins.""" del acknowledger, thread, origins + @classmethod + def ignore_turn_inputs( + cls, + acknowledger: TurnInputAcknowledger, + thread: Thread, + origins: tuple[Message, ...], + ) -> None: + """Settle non-waking direct-inbox origins without starting a model turn.""" + del acknowledger, thread, origins + async def context_for_input(self, thread, context): return context diff --git a/src/agent_comms/cli_bridges/harness_delivery_states.py b/src/agent_comms/cli_bridges/harness_delivery_states.py index cde7e78b5d..d8041805a8 100644 --- a/src/agent_comms/cli_bridges/harness_delivery_states.py +++ b/src/agent_comms/cli_bridges/harness_delivery_states.py @@ -90,6 +90,9 @@ def evidence(self, recorded: type[Outcome]) -> tuple[type[Outcome], MonitorEvide def consumed_progress(self, progress: DeliveryProgress) -> DeliveryProgress: return progress + def claim_handoff(self, state: AssignmentState) -> tuple[type[AssignmentState], ...]: + return state.harness_handoff() + def claim_steps(self, state: AssignmentState) -> tuple[type[AssignmentState], ...]: return () @@ -106,6 +109,20 @@ class UnrecordedMonitor(MonitorEvidence): pass +@dataclass(frozen=True) +class IgnoredMonitor(MonitorEvidence): + """This recipient's direct-inbox backend dismissed a non-waking message without running a turn.""" + + def consumed_progress(self, progress: DeliveryProgress) -> DeliveryProgress: + return progress.ignored() + + def claim_handoff(self, state: AssignmentState) -> tuple[type[AssignmentState], ...]: + return () + + def claim_steps(self, state: AssignmentState) -> tuple[type[AssignmentState], ...]: + return state.harness_ignore() + + @dataclass(frozen=True) class ReceivingMonitor(MonitorEvidence): total: int diff --git a/src/agent_comms/comms.py b/src/agent_comms/comms.py index 7d8083072f..9ffc253236 100644 --- a/src/agent_comms/comms.py +++ b/src/agent_comms/comms.py @@ -77,6 +77,19 @@ def acknowledge_direct_turn_inputs( bridge=bridge, ) + def ignore_direct_turn_inputs( + self, + thread: Thread, + origins: tuple[Message, ...], + *, + bridge: type[HarnessSession], + ) -> None: + self.messaging.ignore_direct_turn_inputs( + thread, + origins, + bridge=bridge, + ) + def __init__(self, root: CommsRoute) -> None: super().__init__(root) self.goals = Goals(self.root, self.registry, self.bus, self.agents) diff --git a/src/agent_comms/coordination/assignment_states.py b/src/agent_comms/coordination/assignment_states.py index bdbd821ac9..0363221872 100644 --- a/src/agent_comms/coordination/assignment_states.py +++ b/src/agent_comms/coordination/assignment_states.py @@ -231,6 +231,10 @@ def harness_delivery(self) -> tuple[type[AssignmentState], ...]: """Steps when that harness confirms the message started; a settled claim keeps its state.""" return () + def harness_ignore(self) -> tuple[type[AssignmentState], ...]: + """Steps when a direct-inbox backend dismisses a non-waking message without running a turn.""" + return () + def preengagement(self, disposition: type[AssignmentState]) -> AssignmentState: if self.execution_id is not None or disposition not in self.successors(): raise IdentityConflict("preengagement transition is not declared") @@ -342,6 +346,9 @@ def wake_frame(self, source: Delivered, obligation: ResponseObligation | None) - def requires_selected_triage(self) -> bool: return True + def harness_ignore(self) -> tuple[type[AssignmentState], ...]: + return (IgnoredAssignment,) + @property def mode(self): return BoundedTriageWake() diff --git a/src/agent_comms/coordination/tables/harness_deliveries.py b/src/agent_comms/coordination/tables/harness_deliveries.py index b5c95ef356..2291c2f56c 100644 --- a/src/agent_comms/coordination/tables/harness_deliveries.py +++ b/src/agent_comms/coordination/tables/harness_deliveries.py @@ -130,7 +130,7 @@ def settle_claims(self, assignments: AssignmentStore, db: sqlite3.Connection) -> native queue, then took the steps this outcome proves. Each phase reads the claim as it stands, so a claim accepted after the attempt ends where one that existed before it would; a claim already settled keeps its state.""" - for steps in (lambda state: state.harness_handoff(), self.monitor.claim_steps): + for steps in (self.monitor.claim_handoff, self.monitor.claim_steps): assignments.settle_harness_inputs(db, self.recipient_lookup, (self.reference,), steps) def begin(self, assignments: AssignmentStore, db: sqlite3.Connection) -> bool: diff --git a/src/agent_comms/execution/antigravity_backend.py b/src/agent_comms/execution/antigravity_backend.py index 83d13ab405..f37491114f 100644 --- a/src/agent_comms/execution/antigravity_backend.py +++ b/src/agent_comms/execution/antigravity_backend.py @@ -176,6 +176,19 @@ def acknowledge_turn_inputs( bridge=AntigravityAcpSession, ) + @classmethod + def ignore_turn_inputs( + cls, + acknowledger: TurnInputAcknowledger, + thread: Thread, + origins: tuple[Message, ...], + ) -> None: + acknowledger.ignore_direct_turn_inputs( + thread, + origins, + bridge=AntigravityAcpSession, + ) + @classmethod def turn_transcript_sink( cls, diff --git a/src/agent_comms/execution/input_drain.py b/src/agent_comms/execution/input_drain.py index 9a3e8825e4..5b66c269f0 100644 --- a/src/agent_comms/execution/input_drain.py +++ b/src/agent_comms/execution/input_drain.py @@ -1512,12 +1512,45 @@ async def drain_private_inbox(self, session_id: AcpSessionId) -> None: await self._drain_private_if_changed(session_id, private_root) WakeScheduleCheck(session_id=session_id, inputs=self).schedule() + def _partition_direct_inbox( + self, + owner: Thread, + messages: tuple[Message, ...], + displayed: DisplayBasis, + aliases: Mapping[str, str], + ) -> tuple[Message, ...]: + """Split direct-inbox messages into waking turns vs non-waking posts. + + Non-waking messages are settled as ignored and marked displayed immediately. + Waking messages stay unmarked until ``TurnProgress.input_started`` records durable + ``HarnessDelivery``, so a restart before the turn starts never drops them. + """ + waking = tuple( + message + for message in messages + if message.sender != owner.name + and message.role.response_policy(message).direct_wake_for( + message, owner.name, aliases + ) + ) + waking_seqs = frozenset(message.seq for message in waking) + non_waking = tuple(message for message in messages if message.seq not in waking_seqs) + if non_waking: + dismissed = tuple(message for message in non_waking if message.sender != owner.name) + if dismissed: + owner.backend.ignore_turn_inputs(self.comms, owner, dismissed) + self.comms.bus.reads.mark_displayed( + owner.name, + displayed.select(tuple(message.seq for message in non_waking)), + ) + return waking + async def _steer_direct_inbox(self, session_id: AcpSessionId, thread: Thread) -> None: turn = (await self.effects.turns.active_backend_turn(session_id)).turn if not turn.has_source(): return - def capture_pending() -> tuple[tuple[Thread, tuple[Message, ...], DisplayBasis], ...]: + def capture_pending() -> tuple[tuple[Thread, tuple[Message, ...]], ...]: if self.comms.owners.maintenance.read().turn_pending: return () snapshot = self.comms.registry.snapshot() @@ -1528,25 +1561,13 @@ def capture_pending() -> tuple[tuple[Thread, tuple[Message, ...], DisplayBasis], messages = tuple(sorted(inbox.page.messages, key=lambda item: item.seq)) if not messages: return () - waking = tuple( - message - for message in messages - if message.sender != owner.name - and message.role.response_policy(message).starts_turn_for( - message, owner.name, snapshot.aliases - ) - ) + waking = self._partition_direct_inbox(owner, messages, inbox.displayed, snapshot.aliases) if not waking: - self.comms.bus.reads.mark_displayed(owner.name, inbox.displayed) return () - return ((owner, waking, inbox.displayed),) + return ((owner, waking),) - for owner, waking, displayed in await Coordination.run_worker(capture_pending): - placed = await DirectDeliveredInput.deliver_direct(self, session_id, owner, waking) - if placed: - await Coordination.run_worker( - partial(self.comms.bus.reads.mark_displayed, owner.name, displayed) - ) + for owner, waking in await Coordination.run_worker(capture_pending): + await DirectDeliveredInput.deliver_direct(self, session_id, owner, waking) async def drain_direct_inbox(self, session_id: AcpSessionId, thread: Thread) -> None: if self.background_wakes_disabled: @@ -1572,15 +1593,7 @@ def capture() -> tuple[ScheduledTurn, ...]: messages = tuple(sorted(inbox.page.messages, key=lambda item: item.seq)) if not messages: return () - self.comms.bus.reads.mark_displayed(owner.name, inbox.displayed) - waking = tuple( - message - for message in messages - if message.sender != owner.name - and message.role.response_policy(message).starts_turn_for( - message, owner.name, snapshot.aliases - ) - ) + waking = self._partition_direct_inbox(owner, messages, inbox.displayed, snapshot.aliases) return tuple( ScheduledTurn.incoming(message, aliases=snapshot.aliases) for message in waking diff --git a/src/agent_comms/execution/selected/triage.py b/src/agent_comms/execution/selected/triage.py index 77a5f642e7..b9c79af5d6 100644 --- a/src/agent_comms/execution/selected/triage.py +++ b/src/agent_comms/execution/selected/triage.py @@ -56,6 +56,7 @@ class InvalidTriageDecision(ValueError): class SelectedTriage(DeclaredFamily, affix="SelectedTriage"): family_discriminator = "decision" + suppresses_reply: ClassVar[bool] = False @classmethod def output_values(cls) -> dict[str, str]: @@ -85,6 +86,14 @@ def recognizes(cls, text: str) -> bool: return False return True + @classmethod + def suppresses_channel_reply(cls, text: str) -> bool: + """Whether this text is a bounded IGNORE verdict rather than a channel reply.""" + try: + return cls.parse(text).suppresses_reply + except InvalidTriageDecision: + return False + @classmethod @abstractmethod def proves_source(cls, evidence: tuple[HistoricalNativeInput, ...]) -> bool: ... @@ -101,6 +110,8 @@ async def continue_turn( @dataclass(frozen=True) class IgnoreSelectedTriage(SelectedTriage, declared_name="IGNORE"): + suppresses_reply = True + @classmethod def proves_source(cls, evidence: tuple[HistoricalNativeInput, ...]) -> bool: return True diff --git a/src/agent_comms/execution/turn_progress.py b/src/agent_comms/execution/turn_progress.py index 1a271229e9..44ac9efe26 100644 --- a/src/agent_comms/execution/turn_progress.py +++ b/src/agent_comms/execution/turn_progress.py @@ -17,10 +17,12 @@ from agent_comms.execution.native_turn_context import ContextObserved from agent_comms.execution.publication_measurements import PublicationMeasurements from agent_comms.execution.runtime_observations import AgentEventConsumer, NativeMetadataObservation +from agent_comms.execution.selected.triage import SelectedTriage from agent_comms.execution.turn_failure import ModelRequestFailed, NoTurnFailure, TurnFailure from agent_comms.execution.turn_lease import TurnState from agent_comms.execution.turn_phase import NativePhaseChanged, PublishingPhase from agent_comms.execution.turn_progress_reads import ProgressGoalAccount, ProgressTurn +from agent_comms.messaging.channel_targets import CommandTarget from agent_comms.messaging.messages import AlertKind, NoticeRole from agent_comms.messaging.send_result import SendResult from agent_comms.nominal.field_codec import AcpSessionId @@ -156,6 +158,15 @@ async def report_sends(self, results: Iterable[SendResult]) -> None: for text in result.notices: await self.consume(events.Notice(text=text)) + def _publishable_reply_targets(self, text: str) -> tuple[str, ...]: + if SelectedTriage.suppresses_channel_reply(text): + return tuple( + target + for target in self.turn.reply_targets + if not CommandTarget.named(target).suppresses_ignore_reply + ) + return self.turn.reply_targets + def publish_progress(self, progress: str) -> tuple[SendResult, ...]: """Join the committed notice and consume its streamed text together.""" results: tuple[SendResult, ...] = () @@ -166,7 +177,7 @@ def publish_progress(self, progress: str) -> tuple[SendResult, ...]: # final reply contains only subsequent assistant text. results = tuple(self.comms.messaging.send( self.thread_name, target, progress, role=NoticeRole() - ) for target in self.turn.reply_targets) + ) for target in self._publishable_reply_targets(progress)) self.reply_parts.clear() if progress: self.transcript_sink.on_committed_progress( @@ -308,9 +319,10 @@ def record_publication() -> None: with ExitStack() as publications: publications.callback(record_publication) if self.reply_parts: - for target in self.turn.reply_targets: + reply = "".join(self.reply_parts) + for target in self._publishable_reply_targets(reply): published.append(self.comms.messaging.send( - self.thread_name, target, "".join(self.reply_parts) + self.thread_name, target, reply )) self.comms.agents.recover_completed_turn(self.turn_lease, self.thread.backend) return tuple(published) diff --git a/src/agent_comms/messaging/channel_targets.py b/src/agent_comms/messaging/channel_targets.py index 172c6c848b..78bfca7714 100644 --- a/src/agent_comms/messaging/channel_targets.py +++ b/src/agent_comms/messaging/channel_targets.py @@ -295,6 +295,7 @@ def direct_names(self) -> tuple[str, ...]: guidance_scope = "" default_audience = MessageAudience.DIRECT + suppresses_ignore_reply: ClassVar[bool] = False @abstractmethod def display_history(self, views: HistoryViews, project: Checkout) -> ConversationHistoryView: @@ -568,6 +569,7 @@ def accepts_batch(self, seq: int) -> bool: return seq > 0 kind = "channel" default_audience = MessageAudience.COLLECTIVE + suppresses_ignore_reply: ClassVar[bool] = True sigil = "#" route: ClassVar[ReplyRoute] = ChannelReply() diff --git a/src/agent_comms/messaging/message_bus.py b/src/agent_comms/messaging/message_bus.py index 4ce4fd4d50..5e22ac8e1b 100644 --- a/src/agent_comms/messaging/message_bus.py +++ b/src/agent_comms/messaging/message_bus.py @@ -29,12 +29,16 @@ from agent_comms.messaging.read_basis import ( AnonymousViewer, ChannelDisplayScope, + Conversation, + DisplayBasis, + DisplayedConversation, DisplayViewer, ListedDeliveries, NamedViewer, ReadCursor, SenderDisplayScope, ) +from agent_comms.messaging.recorded_bus import RecordedBus from agent_comms.messaging.read_ledger import ReadDocument, ReadLedger from agent_comms.messaging.read_selection import CapturedSelection from agent_comms.messaging.routing import DeliveryScope @@ -253,6 +257,29 @@ def mark_read_through( ) self.reads.mark_displayed(canonical, displayed) + def mark_messages_displayed(self, name: str, messages: Sequence[Message]) -> None: + """Advance the read ledger for exactly these delivered messages without skipping others.""" + deliveries = tuple(message for message in messages if message.seq > 0) + if not deliveries: + return + with self.snapshot(NamedViewer(name)) as (basis, source): + canonical = basis.require_viewer() + delivery = DeliveryScope.capture(canonical, basis.registry, basis.catalog) + grouped: dict[Conversation, list[int]] = {} + for message in deliveries: + conversation = delivery.read_key(message.sender, message.target, basis.registry) + grouped.setdefault(conversation, []).append(message.seq) + displayed = DisplayBasis( + canonical, + basis.registry.require(canonical).incarnation.wire_birth, + tuple( + DisplayedConversation(conversation, tuple(sorted(set(sequences)))) + for conversation, sequences in grouped.items() + ), + RecordedBus(source.identity), + ) + self.reads.mark_displayed(canonical, displayed) + def channels(self) -> Sequence[str]: return list(self.channel_declarations()) diff --git a/src/agent_comms/messaging/notification_progress.py b/src/agent_comms/messaging/notification_progress.py index beb210b23c..4e8ccff6df 100644 --- a/src/agent_comms/messaging/notification_progress.py +++ b/src/agent_comms/messaging/notification_progress.py @@ -164,6 +164,10 @@ def model_consumed(self, proof: ShownToModelProgress) -> DeliveryProgress: """The first proof that the message entered the model's context, at its own time.""" return proof + def ignored(self) -> DeliveryProgress: + """A non-waking dismissal only settles a still-pending claim; other states keep their proof.""" + return self + class ConsumedDelivery(SettledDelivery): """The harness or native runtime proved the message entered the model's context.""" @@ -240,6 +244,9 @@ def is_queued(self) -> bool: def model_consumed(self, proof: ShownToModelProgress) -> DeliveryProgress: return self.proof.model_consumed(proof) + def ignored(self) -> DeliveryProgress: + return IgnoredProgress(self.proof) + class PassiveProgress(ContextualProgress): label = "Passive" diff --git a/src/agent_comms/messaging/response_policy.py b/src/agent_comms/messaging/response_policy.py index a8f8fac4b7..91650c3108 100644 --- a/src/agent_comms/messaging/response_policy.py +++ b/src/agent_comms/messaging/response_policy.py @@ -61,6 +61,10 @@ def guidance(self, message: ResponseMessageSource, *, aliases: Mapping[str, str] def starts_turn_for(self, message: ResponseMessageSource, name: str, aliases: Mapping[str, str] = NO_ALIASES) -> bool: return name in self.recipients(message, (name,), aliases=aliases) + def direct_wake_for(self, message: ResponseMessageSource, name: str, aliases: Mapping[str, str] = NO_ALIASES) -> bool: + """Whether a direct-inbox backend without a hidden triage phase wakes on this message.""" + return name in self.required_responders(message, (name,), aliases=aliases) + def context_peer(self, owner: str, sender: str, target: str) -> str | None: return None @@ -86,6 +90,9 @@ class DirectPolicy(NoChannelRecipients, ResponsePolicy): def starts_turn_for(self, message: ResponseMessageSource, name: str, aliases: Mapping[str, str] = NO_ALIASES) -> bool: return self.starts_turn + def direct_wake_for(self, message: ResponseMessageSource, name: str, aliases: Mapping[str, str] = NO_ALIASES) -> bool: + return self.starts_turn + def guidance(self, message: ResponseMessageSource, *, aliases: Mapping[str, str] = NO_ALIASES) -> str: return "direct; reply to the sender" diff --git a/src/agent_comms/messaging/sending.py b/src/agent_comms/messaging/sending.py index 5c9031a4b3..63314346c7 100644 --- a/src/agent_comms/messaging/sending.py +++ b/src/agent_comms/messaging/sending.py @@ -10,6 +10,8 @@ from agent_comms.cli_bridges.harness_delivery_states import ( AcknowledgedReceipt, DeliveredOutcome, + FilteredOutcome, + IgnoredMonitor, UnconfirmedOutcome, ) from agent_comms.coordination.assignment_store import AssignmentStore @@ -220,11 +222,37 @@ def acknowledge_direct_turn_inputs( *, bridge: type[HarnessSession], ) -> tuple[MessageReference, ...]: - """Record durable model-context delivery acknowledgements for a direct backend turn.""" + """Record durable model-context delivery acknowledgements, then advance read markers.""" refs = tuple(dict.fromkeys(origin.reference for origin in origins if origin.seq > 0)) if not refs: return () - return self.acknowledge_deliveries(owner.name, refs, bridge=bridge) + acknowledged = self.acknowledge_deliveries(owner.name, refs, bridge=bridge) + self.bus.mark_messages_displayed(owner.name, origins) + return acknowledged + + def ignore_direct_turn_inputs( + self, + owner: Thread, + origins: tuple[Message, ...], + *, + bridge: type[HarnessSession], + ) -> tuple[MessageReference, ...]: + """Settle non-waking direct-inbox origins as ignored so triage claims never stick on Sent.""" + refs = tuple(dict.fromkeys(origin.reference for origin in origins if origin.seq > 0)) + if not refs: + return () + lookup = owner.incarnation.require_recorded().lookup + evidence = IgnoredMonitor() + path = str(CoordinationStore.path_in(self.root)) + with NativeCoordinationSession(path) as session, session.writing() as db: + assignments = AssignmentStore(session) + for ref in refs: + if not HarnessDelivery.for_recipients(db, ((lookup, ref),)): + HarnessDelivery( + bridge, lookup, ref.message_id, ref.seq, + FilteredOutcome, monitor=evidence, + ).record(assignments, db) + return refs def _settle_answered_remote_deliveries( self, diff --git a/tests/test_antigravity_acp_backend.py b/tests/test_antigravity_acp_backend.py index b4d52428d2..7da153d31f 100644 --- a/tests/test_antigravity_acp_backend.py +++ b/tests/test_antigravity_acp_backend.py @@ -839,5 +839,261 @@ async def test_antigravity_acp_steers_dm_during_active_persistent_goal( await agent.shutdown() +@pytest.mark.asyncio +async def test_antigravity_acp_ignores_unmentioned_channel_post_and_settles_receipt( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """An unmentioned MentionedPolicy channel post must not wake an Antigravity ACP + member and must settle its BoundedTriageWake claim to Not answering (never Sent).""" + import os + from bus_record_fixture import prepare_native_comms + from agent_comms.comms import wire + from agent_comms.execution.acp import CommsAgent, RetainedOwnerLaunch + from agent_comms.execution.child_process import ProcessIdentity + from agent_comms.execution.native_arguments import NativeArguments + from agent_comms.messaging.notification_evidence import AllOutcomes + from agent_comms.messaging.notification_progress import IgnoredProgress + from agent_comms.registry.threads import NextTurnConfiguration + + fake_script = tmp_path / "fake_agy.py" + fake_script.write_text(_FAKE_ACP_SERVER, encoding="utf-8") + fake_bin = tmp_path / "fake_agy" + fake_bin.write_text(f"#!/bin/sh\nexec {sys.executable} {fake_script} \"$@\"\n", encoding="utf-8") + fake_bin.chmod(0o755) + monkeypatch.setenv("AGENT_COMMS_AGY_BIN", str(fake_bin)) + + root = tmp_path / "comms-root" + worktree = tmp_path / "wt" + worktree.mkdir() + comms = prepare_native_comms(wire(root)) + comms.registry.declare(NativeThread("sender", frozenset({"model"}), Checkout(worktree))) + comms.registry.declare(NativeThread("other-agent", frozenset({"model"}), Checkout(worktree))) + thread = comms.registry.declare(NativeThread("agy-idle", frozenset({"model"}), Checkout(worktree))) + thread = comms.threads.set_thread_configuration( + thread, NextTurnConfiguration(model=ChosenModel("antigravity/gemini-4-neon")), + ) + comms.owners.acquire_thread(thread.name) + owner = comms.registry.entry(thread.name).entry.owner_identity + proc = ProcessIdentity.capture(os.getpid()) + env = { + **os.environ, + "AGENT_COMMS_THREAD": thread.name, + "PI_WORKTREE": str(worktree), + NativeArguments.binary_key: NativeArguments.default_binary, + } + launch = RetainedOwnerLaunch(process=proc, interpreter=sys.executable, environment=env) + + agent = CommsAgent(comms, auto_wake=True) + sid = AcpSessionId(thread.name) + try: + await agent.sessions.start_owner(launch, owner) + sent = comms.messaging.send("sender", "#model", "@other-agent please check run 8") + ref = sent.message.reference + ignored_state = None + by_recipient: dict[str, object] = {} + for _ in range(80): + await asyncio.sleep(0.05) + win = comms.views.message_notifications_for_references(AllOutcomes(), (ref,)) + by_recipient = { + item.recipient: item.state + for item in win.outcomes.get((ref.seq, ref.message_id), ()) + } + if isinstance(by_recipient.get(thread.name), IgnoredProgress): + ignored_state = by_recipient[thread.name] + break + assert isinstance(ignored_state, IgnoredProgress), ( + f"Unmentioned BoundedTriageWake post stayed stuck instead of IgnoredProgress: {by_recipient!r}" + ) + assert not agent.inputs.turn_live(sid) + assert comms.bus.inbox(thread.name).page.messages == () + channel_msgs = [m.body for m in comms.bus.inbox("other-agent").page.messages] + assert channel_msgs == ["@other-agent please check run 8"] + finally: + await agent.shutdown() + + +@pytest.mark.asyncio +async def test_antigravity_acp_suppresses_ignore_channel_reply_without_posting( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """When a woken Antigravity ACP agent answers IGNORE on a channel turn (either in + CommittedProgress before a tool call or as final text), TurnProgress must suppress + posting IGNORE to the channel while still acknowledging the incoming message.""" + import os + from bus_record_fixture import prepare_native_comms + from agent_comms.comms import wire + from agent_comms.execution.acp import CommsAgent, RetainedOwnerLaunch + from agent_comms.execution.child_process import ProcessIdentity + from agent_comms.execution.native_arguments import NativeArguments + from agent_comms.messaging.channel_targets import ChannelTarget + from agent_comms.messaging.message_notification import MessageNotification + from agent_comms.messaging.notification_evidence import AllOutcomes + from agent_comms.registry.threads import NextTurnConfiguration + + ignore_server = """ +import json, sys, uuid + +for raw in sys.stdin: + if not raw.strip(): + continue + msg = json.loads(raw) + method = msg.get("method") + rid = msg.get("id") + params = msg.get("params") or {} + def send(payload): + sys.stdout.write(json.dumps(payload) + "\\n") + sys.stdout.flush() + if method == "initialize": + send({"jsonrpc": "2.0", "id": rid, "result": {"protocolVersion": 1}}) + elif method in ("session/new", "session/resume"): + sid = params.get("sessionId") or str(uuid.uuid4()) + send({"jsonrpc": "2.0", "id": rid, "result": {"sessionId": sid, "configOptions": []}}) + elif method == "session/prompt": + sid = params["sessionId"] + for update in ( + {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "IGNORE"}}, + {"sessionUpdate": "tool_call", "toolCallId": "call-1", "name": "run_command", "title": "run_command", "rawInput": {"CommandLine": "true"}}, + {"sessionUpdate": "tool_call_update", "toolCallId": "call-1", "name": "run_command", "status": "completed", "rawOutput": ""}, + {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "IGNORE"}}, + ): + send({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": sid, "update": update}}) + send({"jsonrpc": "2.0", "id": rid, "result": {"stopReason": "end_turn"}}) + elif rid is not None: + send({"jsonrpc": "2.0", "id": rid, "result": {}}) +""" + fake_script = tmp_path / "fake_agy_ignore.py" + fake_script.write_text(ignore_server, encoding="utf-8") + fake_bin = tmp_path / "fake_agy_ignore" + fake_bin.write_text(f"#!/bin/sh\nexec {sys.executable} {fake_script} \"$@\"\n", encoding="utf-8") + fake_bin.chmod(0o755) + monkeypatch.setenv("AGENT_COMMS_AGY_BIN", str(fake_bin)) + + root = tmp_path / "comms-root" + worktree = tmp_path / "wt" + worktree.mkdir() + comms = prepare_native_comms(wire(root)) + comms.registry.declare(NativeThread("tristan", frozenset({"model"}), Checkout(worktree))) + thread = comms.registry.declare(NativeThread("agy-ch", frozenset({"model"}), Checkout(worktree))) + thread = comms.threads.set_thread_configuration( + thread, NextTurnConfiguration(model=ChosenModel("antigravity/gemini-4-neon")), + ) + comms.owners.acquire_thread(thread.name) + owner = comms.registry.entry(thread.name).entry.owner_identity + proc = ProcessIdentity.capture(os.getpid()) + env = { + **os.environ, + "AGENT_COMMS_THREAD": thread.name, + "PI_WORKTREE": str(worktree), + NativeArguments.binary_key: NativeArguments.default_binary, + } + launch = RetainedOwnerLaunch(process=proc, interpreter=sys.executable, environment=env) + + agent = CommsAgent(comms, auto_wake=True) + sid = AcpSessionId(thread.name) + try: + await agent.sessions.start_owner(launch, owner) + sent = comms.messaging.send_user_message( + ChannelTarget("#model"), + "Guys, collective update with no mentions", + worktree=Checkout(worktree), + ) + ref = sent.reference + summary = "" + for _ in range(100): + await asyncio.sleep(0.05) + win = comms.views.message_notifications_for_references(AllOutcomes(), (ref,)) + summary = MessageNotification.summary( + win.outcomes.get((ref.seq, ref.message_id), ()) + ) + if "1 read" in summary and not agent.inputs.turn_live(sid): + break + assert "1 read" in summary, f"Expected collective post acknowledged, got {summary!r}" + posted_by_agent = [ + m.body for m in comms.bus.inbox("tristan").page.messages if m.sender == thread.name + ] + assert posted_by_agent == [], f"IGNORE must never be posted to #model: {posted_by_agent!r}" + finally: + await agent.shutdown() + + +@pytest.mark.asyncio +async def test_antigravity_acp_waking_dm_survives_restart_before_turn_starts( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """drain_direct_inbox must not mark waking messages displayed before TurnProgress.input_started + records durable HarnessDelivery, so a restart while queued redelivers the DM.""" + import os + from bus_record_fixture import prepare_native_comms + from agent_comms.comms import wire + from agent_comms.execution.acp import CommsAgent, RetainedOwnerLaunch + from agent_comms.execution.child_process import ProcessIdentity + from agent_comms.execution.native_arguments import NativeArguments + from agent_comms.messaging.message_notification import MessageNotification + from agent_comms.messaging.notification_evidence import AllOutcomes + from agent_comms.registry.threads import NextTurnConfiguration + + fake_script = tmp_path / "fake_agy.py" + fake_script.write_text(_FAKE_ACP_SERVER, encoding="utf-8") + fake_bin = tmp_path / "fake_agy" + fake_bin.write_text(f"#!/bin/sh\nexec {sys.executable} {fake_script} \"$@\"\n", encoding="utf-8") + fake_bin.chmod(0o755) + monkeypatch.setenv("AGENT_COMMS_AGY_BIN", str(fake_bin)) + + root = tmp_path / "comms-root" + worktree = tmp_path / "wt" + worktree.mkdir() + comms = prepare_native_comms(wire(root)) + comms.registry.declare(NativeThread("tristan", frozenset(), Checkout(worktree))) + thread = comms.registry.declare(NativeThread("agy-restart", frozenset(), Checkout(worktree))) + thread = comms.threads.set_thread_configuration( + thread, NextTurnConfiguration(model=ChosenModel("antigravity/gemini-4-neon")), + ) + comms.owners.acquire_thread(thread.name) + owner = comms.registry.entry(thread.name).entry.owner_identity + proc = ProcessIdentity.capture(os.getpid()) + env = { + **os.environ, + "AGENT_COMMS_THREAD": thread.name, + "PI_WORKTREE": str(worktree), + NativeArguments.binary_key: NativeArguments.default_binary, + } + launch = RetainedOwnerLaunch(process=proc, interpreter=sys.executable, environment=env) + + # First worker captures the waking DM into pending_turns, then dies before running it. + first_agent = CommsAgent(comms, auto_wake=True) + sid = AcpSessionId(thread.name) + monkeypatch.setattr( + first_agent.inputs, + "ensure_live_drain", + lambda *_a, **_kw: None, + ) + dm = comms.messaging.send("tristan", thread.name, "SURVIVE_RESTART_9852") + ref = dm.message.reference + first_agent.sessions.published[sid] = thread.name + first_agent.inputs.state(sid).owned_launch = launch + await first_agent.inputs.drain_direct_inbox(sid, thread) + assert len(first_agent.inputs.state(sid).pending_turns) == 1 + assert [m.seq for m in comms.bus.inbox(thread.name).page.messages] == [ref.seq] + await first_agent.shutdown() + + # Second worker starts fresh and redelivers the DM cleanly. + second_agent = CommsAgent(comms, auto_wake=True) + try: + await second_agent.sessions.start_owner(launch, owner) + summary = "" + for _ in range(100): + await asyncio.sleep(0.05) + win = comms.views.message_notifications_for_references(AllOutcomes(), (ref,)) + summary = MessageNotification.summary( + win.outcomes.get((ref.seq, ref.message_id), ()) + ) + if "1 read" in summary and not second_agent.inputs.turn_live(sid): + break + assert "1 read" in summary, f"Restarted worker failed to redeliver DM: {summary!r}" + assert comms.bus.inbox(thread.name).page.messages == () + finally: + await second_agent.shutdown() + +