Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions src/agent_comms/cli_verbs/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,15 @@
from agent_comms.installer.active_route import CommsRoute
from agent_comms.messaging.channel_targets import CommandTarget
from agent_comms.messaging.channels import AnyChannel
from agent_comms.messaging.historical_views import HistoryView
from agent_comms.messaging.historical_views import HistoricalBusReader, HistoryView
from agent_comms.messaging.history_result import (
ChannelHistoryPageResult,
DmHistoryPageResult,
EverythingHistoryPageResult,
HistoryPageResult,
)
from agent_comms.messaging.message_bus import MessageBus
from agent_comms.messaging.message_page import PageBounds
from agent_comms.messaging.page_traversal import NewestCursor, PageCursor
from agent_comms.messaging.publisher import OwnerPublisher
from agent_comms.messaging.read_basis import AnonymousViewer, DisplayViewer
from agent_comms.nominal.field_codec import Argument
from agent_comms.planning.goal_snapshot_reader import GoalSnapshotReader
Expand Down Expand Up @@ -76,7 +74,7 @@ def apply(self, ctx: CliBus) -> HistoryPageResult:

def execute(self, route: CommsRoute, output: TextIO, open_bus: BusOpener) -> int:
with ActivityClient.client(route) as client:
bus = MessageBus(client.root, client.registry, OwnerPublisher)
bus = HistoricalBusReader(client.root, client.registry)
goals = GoalSnapshotReader(client.root, client.agents)
presentation = BusPresentation(
bus, client.registry, ChannelCatalog.at(client.root), client.agents, goals,
Expand Down
7 changes: 3 additions & 4 deletions src/agent_comms/cli_verbs/inbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
from agent_comms.cli_verbs.cli_commands import ThreadArgument
from agent_comms.cli_verbs.cli_result import CliResult
from agent_comms.installer.active_route import CommsRoute
from agent_comms.messaging.bus_reader import BusReader
from agent_comms.messaging.history_result import HistoryPageResult
from agent_comms.messaging.message_bus import MessageBus
from agent_comms.messaging.message_reference import NewestUnreadStart
from agent_comms.messaging.page_traversal import NewestCursor, PageCursor
from agent_comms.messaging.publisher import OwnerPublisher
from agent_comms.nominal.field_codec import Argument
from agent_comms.registry.route_client import RouteClient

Expand All @@ -38,7 +37,7 @@ class InboxCliCommand(ThreadArgument, CliCommand):
),
] = NewestCursor()

def _read(self, bus: MessageBus) -> InboxResult:
def _read(self, bus: BusReader) -> InboxResult:
inbox = bus.inbox(self.thread, after=NewestUnreadStart(self.before))
shown = tuple(reversed(inbox.page.messages))
return InboxResult(shown, inbox.page.has_older, len(shown) + inbox.remaining)
Expand All @@ -48,5 +47,5 @@ def apply(self, ctx: CliBus) -> CliResult:

def execute(self, route: CommsRoute, output: TextIO, open_bus: BusOpener) -> int:
with RouteClient.client(route) as client:
bus = MessageBus(client.root, client.registry, OwnerPublisher)
bus = BusReader(client.root, client.registry)
return self._read(bus).write(output)
5 changes: 2 additions & 3 deletions src/agent_comms/cli_verbs/threads.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
from agent_comms.cli_verbs.cli_verb import BusOpener, CliBus, CliCommand
from agent_comms.cli_verbs.cli_result import CliResult
from agent_comms.installer.active_route import CommsRoute
from agent_comms.messaging.message_bus import MessageBus
from agent_comms.messaging.publisher import OwnerPublisher
from agent_comms.messaging.bus_reader import BusReader
from agent_comms.nominal.field_codec import Argument, WireForm
from agent_comms.planning.goal_snapshot_reader import GoalSnapshotReader
from agent_comms.thread_views import ThreadRecord
Expand All @@ -31,7 +30,7 @@ def apply(self, ctx: CliBus) -> ThreadsResult:

def execute(self, route: CommsRoute, output: TextIO, open_bus: BusOpener) -> int:
with ActivityClient.client(route) as client:
bus = MessageBus(client.root, client.registry, OwnerPublisher)
bus = BusReader(client.root, client.registry)
goals = GoalSnapshotReader(client.root, client.agents)
return ThreadsResult(ThreadRecord.list_threads(
client.registry.snapshot(), bus, client.agents, goals, active_only=self.active_only,
Expand Down
259 changes: 259 additions & 0 deletions src/agent_comms/messaging/bus_reader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
"""Read-only bus snapshots, unread counts, inbox pages, and display read marks."""

from __future__ import annotations

import threading
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from functools import partial
from pathlib import Path

from agent_comms.messaging.bus import Bus, BusSnapshot
from agent_comms.messaging.bus_read_source import BusReadSource
from agent_comms.messaging.bus_route_counts import HeldUnseenCounts
from agent_comms.messaging.channel_targets import NamedTarget
from agent_comms.messaging.channels import AnyChannel, Channel
from agent_comms.messaging.message_page import (
DisplayedMessagePage,
InboxPage,
MessagePageRequest,
PageBounds,
)
from agent_comms.messaging.message_reference import FirstUnreadStart, InboxStart, NewestUnreadStart
from agent_comms.messaging.messages import Message
from agent_comms.messaging.published_bus import BusCatalog
from agent_comms.messaging.read_basis import (
AnonymousViewer,
Conversation,
DisplayBasis,
DisplayedConversation,
DisplayViewer,
ListedDeliveries,
NamedViewer,
ReadCursor,
)
from agent_comms.messaging.read_ledger import ReadDocument, ReadLedger
from agent_comms.messaging.read_selection import CapturedSelection
from agent_comms.messaging.recorded_bus import RecordedBus
from agent_comms.messaging.routing import DeliveryScope
from agent_comms.registry.catalog_document import CatalogDocument
from agent_comms.registry.catalog_store import ChannelCatalog
from agent_comms.registry.registration import Registration
from agent_comms.registry.registry_document import RegistrySnapshot
from agent_comms.storage.file_observation import FileIdentity


@dataclass(frozen=True, slots=True)
class _CachedPendingProjection:
held: HeldUnseenCounts
registry: RegistrySnapshot
catalog: CatalogDocument
document: ReadDocument
actors: frozenset[str]

def same_cut(self, basis: CapturedSelection) -> bool:
return (
self.registry is basis.registry
and self.catalog is basis.catalog
and self.document is basis.document
)

def serves(self, basis: CapturedSelection, actor_set: frozenset[str], source: BusSnapshot) -> bool:
return (
self.same_cut(basis)
and actor_set <= self.actors
and source.revision() == self.held.through
)


_pending_counts_lock = threading.Lock()
_pending_counts_cache: dict[tuple[Path, FileIdentity], _CachedPendingProjection] = {}


@dataclass(frozen=True)
class UnreadCut:
"""One unread page's rows in one source cut; a count of the rest must read the same cut."""

source: BusSnapshot
snapshot: RegistrySnapshot
require_channel: Callable[[str], Channel]
delivery: DeliveryScope
seen: ReadCursor
cursor: int
request: MessagePageRequest
document: ReadDocument

def counts(self) -> dict[str, int]:
"""Inside the cut: what is pending for this thread, per conversation."""
actor = self.delivery.actor
counts: dict[str, int] = self.source.unseen_counts(
self.snapshot, {actor: self.delivery}, {actor: self.seen}, after=self.cursor,
)[actor]
return counts


class BusReader(BusCatalog, BusReadSource):
"""Live read-only bus access independent of publication, history archive, and coordination."""

def __init__(self, root: Path, registry: Registration):
self.bus = Bus(Bus.path_in(root))
self.reads = ReadLedger.at(root)
self._registry = registry
self._channels = ChannelCatalog.at(root)
self._pending = HeldUnseenCounts()

@contextmanager
def snapshot(self, viewer: DisplayViewer = AnonymousViewer()) -> Iterator[tuple[CapturedSelection, BusSnapshot]]:
with self.bus.reading() as source:
basis = CapturedSelection.load(
self._registry, self._channels, self.reads, viewer, source.activity_clocks(),
)
yield basis, source

def inbox(
self, name: str, target: NamedTarget = AnyChannel.target(), *,
after: InboxStart = NewestUnreadStart(), bounds: PageBounds = PageBounds(),
) -> InboxPage:
"""A glance at a thread's unread messages: newest first, with the unread beyond them."""
return self.inbox_at(name, self._registry.snapshot(), target, after=after, bounds=bounds)

def inbox_at(
self, name: str, snapshot: RegistrySnapshot, target: NamedTarget = AnyChannel.target(), *,
after: InboxStart = FirstUnreadStart(), bounds: PageBounds = PageBounds(),
) -> InboxPage:
with self._unread_cut(name, snapshot, target, after, bounds) as cut:
counts = cut.counts()
result = self._displayed(cut)
total = target.pending_count(counts, snapshot, cut.require_channel)
return InboxPage(result.page, result.displayed, total - len(result.page.messages))

def untaken_at(
self, name: str, snapshot: RegistrySnapshot, target: NamedTarget = AnyChannel.target(), *,
after: InboxStart = FirstUnreadStart(), bounds: PageBounds = PageBounds(),
) -> DisplayedMessagePage:
"""The page alone. A watch wakes on every bus commit and never reads the remainder:
counting it was a second full route query per empty wake per open socket."""
with self._unread_cut(name, snapshot, target, after, bounds) as cut:
pass
return self._displayed(cut)

def _displayed(self, cut: UnreadCut) -> DisplayedMessagePage:
page: DisplayedMessagePage = cut.request.displayed(
self.reads, cut.document, cut.delivery.actor, cut.snapshot, cut.snapshot, self.bus,
)
return page

@contextmanager
def _unread_cut(
self, name: str, snapshot: RegistrySnapshot, target: NamedTarget, after: InboxStart,
bounds: PageBounds,
) -> Iterator[UnreadCut]:
catalog = self._channels.read_shared()
require_channel = partial(self.channel_in, catalog)
delivery = DeliveryScope.capture(name, snapshot, catalog)
selection = delivery.selection(target, snapshot, require_channel)
document, seen = after.read_basis(self.reads, delivery.actor, snapshot)
self.bus.messages_for_references(after.references())
cursor = after.cursor()
traversal = after.traversal()
with self.bus.reading() as source:
with source.observing() as db:
seen = seen.attached(db, self.bus.path.parent, self._registry.store.privacy())
unread = source.unseen_deliveries(
snapshot, delivery, seen, after=cursor, scope=selection, limit=bounds.limit + 1,
traversal=traversal,
)
yield UnreadCut(
source, snapshot, require_channel, delivery, seen, cursor,
MessagePageRequest.listed(
ListedDeliveries(selection, frozenset(row.seq for row in unread),
frozenset(row.target for row in unread)),
PageBounds(traversal, bounds.limit),
), document,
)

def pending_count(self, name: str, target: NamedTarget = AnyChannel.target()) -> int:
with self.snapshot() as (basis, source):
counts = self._pending_projection(source, basis, [name])[name]
return target.pending_count(counts, basis.registry,
lambda name: basis.catalog.require_channel(name, basis.activity))

def pending_counts_all(self, names: Sequence[str]) -> Mapping[str, int]:
if not names:
return {}
with self.snapshot() as (basis, source):
return {name: sum(counts.values())
for name, counts in self._pending_projection(source, basis, names).items()}

def _pending_projection(self, source: BusSnapshot, basis: CapturedSelection, names: Sequence[str]):
actors = {name: basis.registry.canonical_name(name) for name in names}
actor_set = frozenset(actors.values())
cache_key = (self.bus.path, source.identity)
with _pending_counts_lock:
cached = _pending_counts_cache.get(cache_key)
if cached is not None and cached.serves(basis, actor_set, source):
return {name: cached.held.counts[actor] for name, actor in actors.items()}
deliveries = {actor: DeliveryScope.capture(actor, basis.registry, basis.catalog)
for actor in actor_set}
seen = {actor: basis.document.cursor(actor, basis.registry, source)
for actor in deliveries}
held = cached.held if cached is not None else HeldUnseenCounts()
updated = source.advanced_unseen_counts(held, basis.registry, deliveries, seen)
with _pending_counts_lock:
_pending_counts_cache[cache_key] = _CachedPendingProjection(
updated, basis.registry, basis.catalog, basis.document, actor_set,
)
return {name: updated.counts[actor] for name, actor in actors.items()}

def pending_counts_opened(
self, source: BusSnapshot, selection: CapturedSelection, *, conversations: Iterable[str] = (),
) -> Mapping[str, int]:
actor = selection.require_viewer()
delivery = DeliveryScope.capture(actor, selection.registry, selection.catalog)
# Every viewer snapshot asks; between two of them only appended rows can be new.
self._pending = source.advanced_unseen_counts(
self._pending, selection.registry, {actor: delivery}, {actor: selection.seen(source)})
return {**dict.fromkeys(conversations, 0), **self._pending.counts[actor]}

def mark_read_through(
self, name: str, sequence: int, *, target: NamedTarget = AnyChannel.target(),
) -> None:
if sequence < 0:
raise ValueError("Delivery sequence cannot be negative.")
with self.snapshot(NamedViewer(name)) as (basis, source):
canonical = basis.require_viewer()
delivery = DeliveryScope.capture(canonical, basis.registry, basis.catalog)
scope = delivery.selection(target, basis.registry,
lambda channel: basis.catalog.require_channel(channel, basis.activity))
displayed = scope.capture_deliveries(
self.reads, canonical, basis.registry, source, document=basis.document,
audience=delivery, through=sequence,
)
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())
9 changes: 9 additions & 0 deletions src/agent_comms/messaging/historical_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from agent_comms.execution.host_platform import HostPlatform
from agent_comms.execution.transcript_routes import TranscriptRoutes
from agent_comms.messaging.bus import Bus
from agent_comms.messaging.bus_reader import BusReader
from agent_comms.messaging.channel_targets import CommandTarget, NamedTarget, ThreadTarget
from agent_comms.messaging.channels import Channel
from agent_comms.messaging.display_references import (
Expand Down Expand Up @@ -803,3 +804,11 @@ def threads(self, senders: HistoricalSenders) -> tuple[HistoricalThread, ...]:
for thread in source.provenance.threads.values()
if senders.includes(thread, source.provenance))
return tuple(result)


class HistoricalBusReader(BusReader):
"""Read-only bus access with its historical archive, independent of publication."""

def __init__(self, root: Path, registry):
super().__init__(root, registry)
self.history = HistoryArchive.at(self.bus.path.parent)
Loading
Loading