Skip to main content

trusty_code/session/
registry.rs

1//! Daemon-owned session registry: storage, per-session sequencing, ring
2//! buffer, and attach/detach bookkeeping (#2054, #2055).
3//!
4//! Why: this is the object Axiom 4 describes — sessions live INSIDE the
5//! daemon, not in a CLI-side tmux pane. `SessionRegistry` is the single
6//! owner of every `Session`'s state, its bounded event history, and (#2055)
7//! the per-session sequence counter that makes replay -> live gap detection
8//! possible. Designed so persistence (Phase 2+, out of scope per §12) can be
9//! added by swapping the storage backing this type without touching
10//! `session::protocol`'s handlers or the wire protocol at all.
11//! What: [`SessionRegistry`] holds `HashMap<String, SessionEntry>` behind a
12//! `std::sync::Mutex` (never held across an `.await` — every method here is
13//! synchronous; `attach` uses `tokio::spawn` to hand off, not to block).
14//! Each entry carries the `Session` snapshot, a monotonic per-session `seq`
15//! counter, a bounded ring buffer of recent
16//! `crate::events::SessionEventEnvelope`s (§12.1.5: default 1000, oldest
17//! dropped first), and a map of live attachments (`connection_id` ->
18//! `oneshot::Sender<()>` used by `detach` to stop that connection's
19//! forwarder task). `Self::record` is the ONE place that assigns `seq`
20//! (under the same lock that pushes the ring buffer entry), so replay and
21//! every subsequent live event share one gap-free, strictly increasing
22//! sequence — see `crate::events`'s module docs for the full envelope
23//! rationale. `attach` replays the ring buffer synchronously, then spawns a
24//! task that subscribes to the existing process-global `crate::events` bus,
25//! filters by `session_id`, and forwards matching envelopes into the
26//! caller's `NotifySender` until detached or the channel closes (the
27//! connection is gone).
28//! Test: see `registry_tests` (sibling file, `#[cfg(test)]`).
29
30use std::collections::{HashMap, VecDeque};
31use std::sync::atomic::{AtomicBool, Ordering};
32use std::sync::{Arc, Mutex};
33use std::time::Duration;
34
35use chrono::Utc;
36use serde_json::json;
37use tokio::sync::oneshot;
38use tokio::task::JoinHandle;
39use uuid::Uuid;
40
41use crate::agent_loop::Transcript;
42use crate::binding::ProjectBinding;
43use crate::events::{
44    ContextBudgetSnapshot, Event, IndexReadinessSnapshot, SearchAuditRecord, SessionEventEnvelope,
45};
46use crate::jsonrpc::{NotifySender, RpcError};
47use crate::mode::HarnessMode;
48use crate::perf::TokenUsage;
49use crate::run_task::TurnRecord;
50
51use super::model::{Session, SessionStatus};
52use super::transcript::MemoryDurabilityStatus;
53
54/// Default ring-buffer capacity per session (vision spec §12, 11.5).
55///
56/// Why: bounds per-session memory use; a freshly-attached client sees
57/// "recent progress but not the full session history" per spec — the ring
58/// buffer is the LIVE-event window, distinct from the full run transcript
59/// `session.get_transcript` (#2058) exposes via `Self::get_transcript`.
60/// Test: `registry_tests::ring_buffer_drops_oldest_when_full`.
61pub const DEFAULT_RING_CAPACITY: usize = 1000;
62
63/// One session's storage: the domain snapshot, its sequence counter, ring
64/// buffer, the live attachments forwarding its events, and (#2056) its
65/// background execution state + last completed run's outcome.
66struct SessionEntry {
67    session: Session,
68    /// Last-assigned per-session sequence number; the next event gets
69    /// `seq + 1`. Starts at `0` so the first recorded event is `seq = 1`.
70    seq: u64,
71    ring: VecDeque<SessionEventEnvelope>,
72    /// `connection_id` -> the cancel sender for that connection's forwarder
73    /// task. Re-attaching the same connection to the same session replaces
74    /// (and thus cancels, via `Sender` drop) the previous forwarder.
75    attachments: HashMap<Uuid, oneshot::Sender<()>>,
76    /// #2056: set while a background task-execution is in flight; `None`
77    /// when idle (never started, or already finished).
78    execution: Option<Execution>,
79    /// #2056: the run transcript populated once an execution finishes;
80    /// exposed read-only via `session.get_transcript` (#2058,
81    /// `Self::get_transcript`). Empty until the first execution completes.
82    /// (#2344) CUMULATIVE across every run on this session — each
83    /// `set_run_outcome` call APPENDS its turns rather than overwriting.
84    transcript: Vec<TurnRecord>,
85    /// #2056: aggregated token usage from every completed execution on this
86    /// session. (#2344) CUMULATIVE — each `set_run_outcome` call adds its
87    /// usage onto the running total rather than overwriting it.
88    usage: TokenUsage,
89    /// #2056: summed USD cost across every completed execution on this
90    /// session (`None` if pricing was never available for any run — mirrors
91    /// `run_task::RunReport::cost_usd`). (#2344) CUMULATIVE, same rule as
92    /// `usage`.
93    cost_usd: Option<f64>,
94    /// (#2344) The PM's persistent, cumulative conversation `Transcript` —
95    /// distinct from `transcript` above (which is the flat `TurnRecord`
96    /// accounting view). `None` until the session's first `task.run` seeds
97    /// it via [`SessionRegistry::begin_pm_transcript`]; briefly taken back
98    /// out to `None` while a run is in flight (safe — `execution.is_some()`
99    /// already guarantees at most one run at a time per session) and
100    /// restored by [`SessionRegistry::store_pm_transcript`] once that run
101    /// ends, regardless of outcome, so the NEXT run continues from exactly
102    /// where this one left off.
103    pm_transcript: Option<Transcript>,
104    /// (#2345) The session's durable turn-recorder sink — `None` until the
105    /// session's first `task.run` lazily constructs it via
106    /// [`SessionRegistry::memory_sink_for`] (the project directory, needed to
107    /// derive the palace id, is only known once a run starts). Built once and
108    /// reused for the life of the session (see `memory_sink` module docs for
109    /// why its background drain task must outlive any single run).
110    memory_sink: Option<Arc<super::memory_sink::TurnMemorySink>>,
111    /// (#2425) Retained durable-memory degradation status, as
112    /// `session.get_transcript` reports it.
113    memory_durability: MemoryDurabilityStatus,
114    /// (#2425) Bounded logical-order projection folding the sink's detached and
115    /// synchronous outcomes into `memory_durability`.
116    memory_outcomes: super::memory_outcome_reconciler::MemoryOutcomeReconciler,
117    /// (DOC-39 §5.6 Slice D) The most recently recorded `IndexReadiness`
118    /// probe for this session — last-writer-wins, overwritten by every new
119    /// `record_index_readiness` call. `None` until the session's first probe
120    /// lands (or forever, for a session whose `task.run` never indexes —
121    /// e.g. projectless). This is the storage `session.get_readiness` reads
122    /// so a client that attaches AFTER the one-time `Event::IndexReadiness`
123    /// fired can still retrieve the current state.
124    readiness: Option<IndexReadinessSnapshot>,
125    /// (issue #3015) The most recently recorded [`ContextBudgetSnapshot`] for
126    /// this session — last-writer-wins, mirrors `readiness` above but for
127    /// `record_context_budget`'s per-turn measurement. `None` until the
128    /// session's first `Event::ContextBudget` fires (PM-only; a delegated
129    /// sub-agent loop never emits one), so `session.get_context_budget` can
130    /// distinguish "never recorded" from an all-zero snapshot.
131    context_budget: Option<ContextBudgetSnapshot>,
132    /// (issue #3948) This session's retained working-context low-water mark
133    /// and sample count, folded in by every `record_context_budget` call.
134    /// Kept beside `context_budget` rather than inside it so the latest
135    /// point-in-time snapshot stays a pure last-writer-wins value.
136    context_floor: super::registry_context_floor::ContextFloorState,
137    /// (DOC-39 §5.4) Live per-agent roster, in first-seen order — the
138    /// AUTHORITATIVE state `session.get_agents` reads (see
139    /// `session::registry::agents`'s module docs). Updated by [`Self::record`]
140    /// (the SAME call every `record_tool_*` plumbing method already routes
141    /// through) whenever the event carries `agent`/`agent_id`, so it is
142    /// exactly as fresh as the ring buffer — but unlike `ring`, it is NEVER
143    /// evicted by `ring_capacity`. A code-critic HIGH on the #2962 PR caught
144    /// the bug this field exists to close: `session.get_agents` originally
145    /// FOLDED the bounded ring buffer directly, so a long-running agent's
146    /// `ToolStarted` could age out of the ring before any later attributed
147    /// event for that same `agent_id` landed, making it vanish from the
148    /// roster entirely — indistinguishable from "never spawned" while it may
149    /// still genuinely be running. A `Vec` (not a `HashMap`) because the
150    /// roster's first-seen ORDER is part of its contract and one session's
151    /// distinct-agent cardinality is small, so `record`'s linear find-or-insert
152    /// scan is cheap.
153    agents: Vec<AgentRosterState>,
154    /// (issue #3072) Retained search/recall audit trail, oldest-first — see
155    /// `session::registry_search_audit` module docs for the cap and eviction
156    /// policy. Appended by `SessionRegistry::push_search_audit`, called from
157    /// `record_search_performed`/`record_memory_recalled` (`registry_events`)
158    /// alongside the existing SSE emission; unlike `ring`, capacity here is
159    /// its own bound (`SEARCH_AUDIT_CAP`), independent of `ring_capacity`.
160    search_audit: VecDeque<SearchAuditRecord>,
161}
162
163/// One agent's live roster state inside a [`SessionEntry`] (DOC-39 §5.4) —
164/// see that field's own docs for why this exists separately from the ring
165/// buffer. `session::registry::agents::get_agents` reads this directly (not
166/// the ring) to build `session.get_agents`'s wire response.
167///
168/// Why: `agent_id` is stored inline (rather than as a `HashMap` key) so the
169/// containing `Vec`'s order doubles as the roster's first-seen order with no
170/// second parallel structure to keep in sync.
171/// What: `running` is `true` from the last-seen `ToolStarted` for this
172/// `agent_id` until the next `ToolFinished`/`ToolError`/telemetry event for
173/// the SAME id flips it back to `false` — see
174/// `session::registry::agents::tool_attribution`'s docs for why tool-dispatch
175/// ordering makes "last event wins" well-defined without needing to
176/// correlate `call_id`.
177struct AgentRosterState {
178    agent_id: String,
179    name: String,
180    running: bool,
181}
182
183impl SessionEntry {
184    /// Fold one event into `self.agents` (DOC-39 §5.4) if it carries
185    /// `agent`/`agent_id`; a no-op for every other `Event` variant.
186    ///
187    /// Why: the single update path for the always-retained roster — called
188    /// from [`SessionRegistry::record`] under the SAME lock that pushes onto
189    /// `ring`, so the two can never observe a different set of events.
190    /// What: find-or-insert by `agent_id` (empty ids are skipped — nothing
191    /// to key a roster row on), updating `name` (last-writer-wins) and
192    /// `running` (`true` only for `ToolStarted`; every other attributed kind
193    /// fires only after its tool call already completed — see
194    /// `session::registry::agents`'s module docs for the tool-dispatch
195    /// ordering that makes this well-defined).
196    fn note_agent_activity(&mut self, event: &Event) {
197        let Some((agent, agent_id, running)) = tool_attribution(event) else {
198            return;
199        };
200        if agent_id.is_empty() {
201            return;
202        }
203        match self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
204            Some(existing) => {
205                existing.name = agent.to_string();
206                existing.running = running;
207            }
208            None => self.agents.push(AgentRosterState {
209                agent_id: agent_id.to_string(),
210                name: agent.to_string(),
211                running,
212            }),
213        }
214    }
215}
216
217/// Extract `(agent, agent_id, is_running)` from the attribution events the
218/// live roster (DOC-39 §5.4) cares about, or `None` for every other `Event`
219/// variant.
220///
221/// Why: shared by [`SessionEntry::note_agent_activity`] (the write path) and
222/// `session::registry::agents::get_agents`'s docs (which point back here) —
223/// centralises which events count as roster-relevant activity.
224/// What: `true` only for `ToolStarted`; every other attributed kind fires
225/// only after its tool call already completed
226/// (`ToolStarted` -> `ToolFinished`/`ToolError` -> optional telemetry).
227fn tool_attribution(event: &Event) -> Option<(&str, &str, bool)> {
228    match event {
229        Event::ToolStarted {
230            agent, agent_id, ..
231        } => Some((agent, agent_id, true)),
232        Event::ToolFinished {
233            agent, agent_id, ..
234        } => Some((agent, agent_id, false)),
235        Event::ToolError {
236            agent, agent_id, ..
237        } => Some((agent, agent_id, false)),
238        Event::SearchPerformed {
239            agent, agent_id, ..
240        } => Some((agent, agent_id, false)),
241        Event::MemoryRecalled {
242            agent, agent_id, ..
243        } => Some((agent, agent_id, false)),
244        _ => None,
245    }
246}
247
248/// #2056: bookkeeping for one in-flight background task execution.
249///
250/// Why: `SessionRegistry` needs to (a) reject a second overlapping run for
251/// the same session, (b) signal cooperative cancellation, and (c) — on
252/// graceful daemon shutdown — wait, bounded, for the task to actually stop.
253/// What: `cancel` is shared with every `AgentLoop`/`InProcessAgentRunner`
254/// the execution drives (via `with_cancel_flag`); `handle` is the
255/// `tokio::spawn` join handle, attached shortly after `begin_execution`
256/// returns (see [`SessionRegistry::attach_execution_handle`]) since the
257/// handle does not exist until the caller has actually spawned the task.
258struct Execution {
259    cancel: Arc<AtomicBool>,
260    handle: Option<JoinHandle<()>>,
261}
262
263/// The daemon-owned session registry (Axiom 4).
264///
265/// Why: single source of truth for every session's state, in-memory only
266/// (§12, M1) — see the module docs for the full rationale.
267/// What: see method docs below; `new()` uses [`DEFAULT_RING_CAPACITY`],
268/// `with_capacity` lets tests use a tiny buffer to exercise eviction cheaply.
269/// Test: `registry_tests::*`.
270pub struct SessionRegistry {
271    sessions: Mutex<HashMap<String, SessionEntry>>,
272    ring_capacity: usize,
273}
274
275impl Default for SessionRegistry {
276    fn default() -> Self {
277        Self::new()
278    }
279}
280
281impl SessionRegistry {
282    /// Construct an empty registry with the default ring-buffer capacity.
283    pub fn new() -> Self {
284        Self::with_capacity(DEFAULT_RING_CAPACITY)
285    }
286
287    /// Construct an empty registry with an explicit ring-buffer capacity.
288    ///
289    /// Why: unit tests need a small capacity to exercise eviction without
290    /// pushing 1000 events.
291    pub fn with_capacity(ring_capacity: usize) -> Self {
292        Self {
293            sessions: Mutex::new(HashMap::new()),
294            ring_capacity,
295        }
296    }
297
298    /// `session.create`: register a brand-new session and publish its
299    /// lifecycle-start events.
300    ///
301    /// Why: the sole entry point that mints a session id and puts a
302    /// `Session` into the registry.
303    /// What: builds a `Session` with a fresh UUIDv4 id and
304    /// `status = Created`, inserts it (with a fresh `seq = 0` counter),
305    /// publishes `Event::SessionStarted` (assigned `seq = 1`), then
306    /// immediately transitions to `Running` (M1 has no queue ahead of real
307    /// task execution — see `session::model` docs) which publishes
308    /// `Event::SessionStatusChanged` (`seq = 2`). Returns the
309    /// post-transition snapshot (so the caller sees `status: "running"`,
310    /// not the momentary `"created"`).
311    /// `binding` replaces what was an untyped `project: Option<String>` label.
312    /// The label still exists on the wire (`Session.project`) but is now DERIVED
313    /// from the binding via `ProjectBinding::label`, so the two can never
314    /// disagree — see `Session`'s docs. `ProjectBinding::None` (projectless) is
315    /// a fully supported binding, not a missing one.
316    /// Test: `registry_tests::create_publishes_started_and_status_events`,
317    /// `registry_tests::create_derives_project_label_from_binding`.
318    pub fn create(&self, task: String, agent: Option<String>, binding: ProjectBinding) -> Session {
319        let id = Uuid::new_v4().to_string();
320        let session = Session {
321            id: id.clone(),
322            task,
323            agent,
324            project: binding.label(),
325            binding,
326            status: SessionStatus::Created,
327            created_at: Utc::now(),
328            mode: None,
329            workstream_id: None,
330        };
331        {
332            let mut sessions = self.lock();
333            sessions.insert(
334                id.clone(),
335                SessionEntry {
336                    session: session.clone(),
337                    seq: 0,
338                    ring: VecDeque::new(),
339                    attachments: HashMap::new(),
340                    execution: None,
341                    transcript: Vec::new(),
342                    usage: TokenUsage::default(),
343                    cost_usd: None,
344                    pm_transcript: None,
345                    memory_sink: None,
346                    memory_durability: MemoryDurabilityStatus::default(),
347                    memory_outcomes: Default::default(),
348                    readiness: None,
349                    context_budget: None,
350                    context_floor: super::registry_context_floor::ContextFloorState::default(),
351                    agents: Vec::new(),
352                    search_audit: VecDeque::new(),
353                },
354            );
355        }
356        self.record(
357            &id,
358            Event::SessionStarted {
359                session_id: id.clone(),
360                // The binding-derived label. Projectless yields `""`, exactly
361                // as an absent `project` label already did before the binding
362                // existed — no wire change for this event.
363                project: session.project.clone().unwrap_or_default(),
364            },
365        );
366        self.transition(&id, SessionStatus::Running);
367        self.status(&id).unwrap_or(session)
368    }
369
370    /// `session.list`: snapshot every session currently in the registry.
371    ///
372    /// Why: the read side of the registry for operators/CLI/TUI to enumerate
373    /// running sessions.
374    /// What: clones every `Session` snapshot; order is unspecified (backed
375    /// by a `HashMap`).
376    /// Test: `registry_tests::list_returns_every_created_session`.
377    pub fn list(&self) -> Vec<Session> {
378        self.lock().values().map(|e| e.session.clone()).collect()
379    }
380
381    /// `session.status`: snapshot one session by id.
382    ///
383    /// Why: shared by `create`'s return value and the standalone
384    /// `session.status` method.
385    /// What: `Ok(Session)` if present, `Err(RpcError::session_not_found)`
386    /// otherwise.
387    /// Test: `registry_tests::status_returns_not_found_for_unknown_id`.
388    pub fn status(&self, id: &str) -> Result<Session, RpcError> {
389        self.lock()
390            .get(id)
391            .map(|e| e.session.clone())
392            .ok_or_else(|| RpcError::session_not_found(id))
393    }
394
395    /// `session.send`: deliver input to a session and publish an observable
396    /// event proving the daemon received it.
397    ///
398    /// Why: #2054/#2055 do not wire a real agent loop (that is `task.*`,
399    /// #2056); publishing `Event::SessionInput` is what makes `session.send`
400    /// observably reach a `session.attach`ed client NOW, and gives #2056 a
401    /// concrete event to build real echo/ack behaviour on top of.
402    /// What: errors with `session_not_found` if `id` is unknown; otherwise
403    /// records+publishes `Event::SessionInput { session_id, input }`.
404    /// Test: `registry_tests::send_publishes_input_event`,
405    /// `registry_tests::send_unknown_session_errors`.
406    pub fn send(&self, id: &str, input: &str) -> Result<(), RpcError> {
407        if !self.lock().contains_key(id) {
408            return Err(RpcError::session_not_found(id));
409        }
410        self.record(
411            id,
412            Event::SessionInput {
413                session_id: id.to_string(),
414                input: input.to_string(),
415            },
416        );
417        Ok(())
418    }
419
420    /// `session.cancel`: send a cancellation signal and mark the session
421    /// terminal.
422    ///
423    /// Why: vision spec §12 (11.6) Cancellation Semantics — cancellation is
424    /// a status transition + event, not a deletion. #2054/#2055 have no
425    /// in-flight agent loop to interrupt yet (that lands with #2056), so
426    /// this is the full implementation available today: it marks the
427    /// session `Cancelled` and publishes the terminal events; #2056 hooks
428    /// the actual agent-loop interrupt onto the same status transition.
429    /// What: idempotent — cancelling an already-terminal session is a no-op
430    /// that returns the current snapshot rather than erroring (repeated
431    /// `session.cancel` calls are safe). Errors with `session_not_found` if
432    /// `id` is unknown. On a live session: publishes
433    /// `Event::SessionStatusChanged` (`status: "cancelled"`), then the
434    /// dedicated `Event::SessionCancelled` signal, then the generic terminal
435    /// `Event::SessionDone` (`status: "cancelled"`) — matching the vision
436    /// spec's `started/status-changed/input/cancelled/done` taxonomy — and
437    /// returns the updated snapshot.
438    /// Test: `registry_tests::cancel_transitions_to_cancelled_and_publishes`,
439    /// `registry_tests::cancel_is_idempotent_on_terminal_session`,
440    /// `registry_tests::cancel_unknown_session_errors`.
441    pub fn cancel(&self, id: &str) -> Result<Session, RpcError> {
442        let already_terminal = {
443            let sessions = self.lock();
444            let entry = sessions
445                .get(id)
446                .ok_or_else(|| RpcError::session_not_found(id))?;
447            entry.session.status.is_terminal()
448        };
449        if already_terminal {
450            return self.status(id);
451        }
452        self.transition(id, SessionStatus::Cancelled);
453        self.record(
454            id,
455            Event::SessionCancelled {
456                session_id: id.to_string(),
457            },
458        );
459        self.record(
460            id,
461            Event::SessionDone {
462                session_id: id.to_string(),
463                status: SessionStatus::Cancelled.as_str().to_string(),
464            },
465        );
466        self.status(id)
467    }
468
469    /// Mark a session terminal (finished, failed, or cancelled while
470    /// executing) and publish the terminal `Event::SessionDone` (#2056).
471    ///
472    /// Why: the background executor (`crate::task::executor`) needs to set
473    /// the FINAL status once an agent loop returns, distinctly from the
474    /// user-initiated `session.cancel` JSON-RPC path ([`Self::cancel`]),
475    /// which ALSO emits a dedicated `Event::SessionCancelled` signal that
476    /// only makes sense for an explicit user cancel request — not a natural
477    /// finish or failure, and not a cancellation the EXECUTOR itself
478    /// observed (that path already went through `request_cancel`, which
479    /// does not transition status; the executor calls this afterward to
480    /// actually land the transition once it has unwound).
481    /// What: idempotent — a no-op (returns the current snapshot) if the
482    /// session is already terminal, since a race between `request_cancel`'s
483    /// caller and the executor noticing cancellation is possible but
484    /// harmless. Errors with `session_not_found` if `id` is unknown.
485    /// Otherwise transitions to `status` and publishes
486    /// `Event::SessionDone { status }`.
487    /// Test: `registry_tests::finish_transitions_and_publishes_session_done`,
488    /// `registry_tests::finish_is_idempotent_on_terminal_session`,
489    /// `registry_tests::finish_unknown_session_errors`.
490    pub fn finish(&self, id: &str, status: SessionStatus) -> Result<Session, RpcError> {
491        let already_terminal = {
492            let sessions = self.lock();
493            let entry = sessions
494                .get(id)
495                .ok_or_else(|| RpcError::session_not_found(id))?;
496            entry.session.status.is_terminal()
497        };
498        if !already_terminal {
499            self.transition(id, status);
500            self.record(
501                id,
502                Event::SessionDone {
503                    session_id: id.to_string(),
504                    status: status.as_str().to_string(),
505                },
506            );
507        }
508        self.status(id)
509    }
510
511    /// `session.attach`: replay recent history and start forwarding this
512    /// session's live events to `notify`.
513    ///
514    /// Why: the streaming half of the session-attach protocol (vision spec
515    /// §4.4/Axiom 4). Works identically regardless of transport — the
516    /// difference between STDIO (long-lived `notify`, events interleaved on
517    /// stdout) and HTTP (throwaway `notify`; the real live path is the `GET
518    /// /sessions/{id}/events` SSE route) lives entirely in
519    /// `crate::jsonrpc::ConnectionContext`'s docs and `crate::serve`'s
520    /// transports, not here.
521    /// What: errors with `session_not_found` if `id` is unknown. Otherwise
522    /// takes a snapshot of the ring buffer (oldest-first, each entry a full
523    /// [`SessionEventEnvelope`] with its `seq` intact) to return as the
524    /// replay, registers `connection_id`'s cancel sender (replacing — and
525    /// thus cancelling — any prior forwarder for the same
526    /// `(session, connection)` pair), and spawns a task that subscribes to
527    /// `crate::events::subscribe()`, filters by `session_id`, and forwards
528    /// each match into `notify` as a JSON-RPC notification whose `params` IS
529    /// the envelope (`{"jsonrpc":"2.0","method":"session.event","params":
530    /// {"session_id":...,"seq":...,"at":...,"kind":...,"event":{...}}}`)
531    /// until `detach` fires the cancel sender or `notify.send` fails (the
532    /// connection is gone). Because every envelope — replayed or live —
533    /// comes from the SAME per-session `seq` counter (`record`), a client
534    /// that concatenates the replay array with the live notifications it
535    /// receives afterward sees one gap-free, strictly increasing sequence.
536    /// Test: `registry_tests::attach_returns_ring_buffer_replay`,
537    /// `registry_tests::attach_forwards_live_events_until_detach`,
538    /// `registry_tests::attach_replay_then_live_seq_is_contiguous`,
539    /// `registry_tests::attach_unknown_session_errors`.
540    pub fn attach(
541        &self,
542        id: &str,
543        connection_id: Uuid,
544        notify: NotifySender,
545    ) -> Result<Vec<SessionEventEnvelope>, RpcError> {
546        let replay = {
547            let mut sessions = self.lock();
548            let entry = sessions
549                .get_mut(id)
550                .ok_or_else(|| RpcError::session_not_found(id))?;
551            let (cancel_tx, cancel_rx) = oneshot::channel();
552            entry.attachments.insert(connection_id, cancel_tx);
553            spawn_forwarder(id.to_string(), notify, cancel_rx);
554            entry.ring.iter().cloned().collect::<Vec<_>>()
555        };
556        Ok(replay)
557    }
558
559    /// `session.detach`: stop forwarding this session's live events to the
560    /// calling connection.
561    ///
562    /// Why: the other half of the attach protocol — releases the forwarder
563    /// task started by `attach` for this `(session, connection)` pair.
564    /// What: errors with `session_not_found` if `id` is unknown. If the
565    /// connection has no live attachment (already detached, or never
566    /// attached), this is a no-op success rather than an error — detach is
567    /// idempotent. Otherwise fires the stored cancel sender, which stops the
568    /// forwarder task on its next `select!` poll.
569    /// Test: `registry_tests::detach_stops_the_forwarder`,
570    /// `registry_tests::detach_without_prior_attach_is_a_noop`,
571    /// `registry_tests::detach_unknown_session_errors`.
572    pub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError> {
573        let mut sessions = self.lock();
574        let entry = sessions
575            .get_mut(id)
576            .ok_or_else(|| RpcError::session_not_found(id))?;
577        if let Some(cancel_tx) = entry.attachments.remove(&connection_id) {
578            let _ = cancel_tx.send(());
579        }
580        Ok(())
581    }
582
583    /// Snapshot the ring buffer for a session without attaching to it.
584    ///
585    /// Why: the HTTP SSE route (`crate::serve::http`) needs the same replay
586    /// burst `attach` returns, but subscribes to the live bus itself (one
587    /// `Stream` per SSE connection) rather than going through a
588    /// `NotifySender` forwarder — so it calls this directly instead of
589    /// `attach`.
590    /// What: same replay semantics as `attach` (full envelopes, `seq`
591    /// intact), no side effects (no forwarder spawned, no attachment
592    /// recorded).
593    /// Test: `registry_tests::replay_returns_ring_buffer_without_attaching`.
594    pub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError> {
595        self.lock()
596            .get(id)
597            .map(|e| e.ring.iter().cloned().collect())
598            .ok_or_else(|| RpcError::session_not_found(id))
599    }
600
601    /// Begin tracking a new background task execution for `id` (#2056; #2344
602    /// resumption semantics).
603    ///
604    /// Why: `task.run` (and `session.send` on an idle session) must not start
605    /// a second overlapping run for the same session, and the returned flag
606    /// is how the executor's `AgentLoop`(s) later observe cancellation.
607    /// (#2344/#3888) A `Finished` or `TurnCapExceeded` session is NOT dead —
608    /// see [`SessionStatus::is_resumable`] for which statuses resume and why.
609    /// Only `Cancelled`/`Failed`/`DeadlineExceeded` remain genuinely
610    /// terminal: those represent a broken run, and resuming one still
611    /// requires a fresh session.
612    /// What: errors with `session_not_found` if `id` is unknown,
613    /// `invalid_argument` if the session is `Cancelled`/`Failed`/
614    /// `DeadlineExceeded`, or already has an execution in flight — this
615    /// SINGLE in-flight-execution guard is also this ticket's concurrency
616    /// guard for `pm_transcript`: two overlapping `task.run` calls on one
617    /// session can never both hold the transcript, because the second one is
618    /// rejected here before either reaches `begin_pm_transcript`. On success,
619    /// stores a fresh `Arc<AtomicBool>` cancel flag (initially `false`) with
620    /// `handle: None` — the caller attaches the real `JoinHandle` via
621    /// [`Self::attach_execution_handle`] immediately after spawning, since
622    /// the handle cannot exist before that — and returns the flag. If the
623    /// session was resumable (`is_resumable`), transitions it back to
624    /// `Running` and publishes `Event::SessionStatusChanged` — matching the
625    /// transition every other status change in this module publishes.
626    /// Test: `registry_tests::begin_execution_rejects_second_overlapping_run`,
627    /// `registry_tests::begin_execution_rejects_terminal_session`,
628    /// `registry_tests::begin_execution_unknown_session_errors`,
629    /// `registry_tests::begin_execution_resumes_a_finished_session`,
630    /// `registry_tests::begin_execution_resumes_a_turn_cap_exceeded_session`.
631    pub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError> {
632        let (cancel, resumed) = {
633            let mut sessions = self.lock();
634            let entry = sessions
635                .get_mut(id)
636                .ok_or_else(|| RpcError::session_not_found(id))?;
637            if matches!(
638                entry.session.status,
639                SessionStatus::Cancelled | SessionStatus::Failed | SessionStatus::DeadlineExceeded
640            ) {
641                return Err(RpcError::invalid_argument(format!(
642                    "session {id} is already terminal"
643                )));
644            }
645            if entry.execution.is_some() {
646                return Err(RpcError::invalid_argument(format!(
647                    "session {id} already has a task running"
648                )));
649            }
650            let resumed = entry.session.status.is_resumable();
651            if resumed {
652                entry.session.status = SessionStatus::Running;
653            }
654            let cancel = Arc::new(AtomicBool::new(false));
655            entry.execution = Some(Execution {
656                cancel: Arc::clone(&cancel),
657                handle: None,
658            });
659            (cancel, resumed)
660        };
661        if resumed {
662            self.record(
663                id,
664                Event::SessionStatusChanged {
665                    session_id: id.to_string(),
666                    status: SessionStatus::Running.as_str().to_string(),
667                },
668            );
669        }
670        Ok(cancel)
671    }
672
673    /// Attach the real `JoinHandle` to `id`'s tracked execution (#2056).
674    ///
675    /// Why: the handle only exists once the caller has actually called
676    /// `tokio::spawn`, which must happen after `begin_execution` returns (the
677    /// spawned future needs the cancel flag `begin_execution` produces).
678    /// What: best-effort — a no-op if `id` or its execution is already gone
679    /// (e.g. the run finished astonishingly fast, or the session vanished).
680    /// Test: `registry_tests::shutdown_executions_awaits_cancelled_tasks`
681    /// (exercises this indirectly via a real spawn).
682    pub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>) {
683        let mut sessions = self.lock();
684        if let Some(entry) = sessions.get_mut(id)
685            && let Some(execution) = entry.execution.as_mut()
686        {
687            execution.handle = Some(handle);
688        }
689    }
690
691    /// Clear the execution-in-flight marker for `id` (#2056).
692    ///
693    /// Why: called by the executor once the background task has stopped
694    /// (finished, failed, or cancelled) so a later `task.run`/`session.send`
695    /// can start a new run against the same session.
696    /// What: best-effort — a no-op if `id` is already gone.
697    /// Test: `registry_tests::begin_execution_rejects_second_overlapping_run`
698    /// (calls this between the two `begin_execution` attempts).
699    pub fn finish_execution(&self, id: &str) {
700        let mut sessions = self.lock();
701        if let Some(entry) = sessions.get_mut(id) {
702            entry.execution = None;
703        }
704    }
705
706    /// Whether `id` currently has a background execution in flight (#2056).
707    ///
708    /// Why: `session::protocol::cancel` uses this to choose between
709    /// cooperative cancellation ([`Self::request_cancel`]) and the original
710    /// #2054 immediate-transition [`Self::cancel`].
711    /// What: `false` for both "unknown session" and "known but idle" — callers
712    /// that need to distinguish those already call another method first.
713    /// Test: `registry_tests::request_cancel_*`.
714    pub fn is_executing(&self, id: &str) -> bool {
715        self.lock().get(id).is_some_and(|e| e.execution.is_some())
716    }
717
718    /// Request cooperative cancellation of `id`'s in-flight execution, if any
719    /// (#2056).
720    ///
721    /// Why: `session.cancel` on a RUNNING session must signal the background
722    /// task rather than force an immediate status transition — the task
723    /// itself transitions to `Cancelled` once it actually observes the flag
724    /// and unwinds (see `crate::task::executor`).
725    /// What: `Err(session_not_found)` if `id` is unknown. `Ok(true)` if an
726    /// execution was in flight and its flag was set; `Ok(false)` if the
727    /// session exists but nothing is executing (the caller should fall back
728    /// to [`Self::cancel`] for the immediate-transition path).
729    /// Test: `registry_tests::request_cancel_sets_flag_when_executing`,
730    /// `registry_tests::request_cancel_returns_false_when_idle`.
731    pub fn request_cancel(&self, id: &str) -> Result<bool, RpcError> {
732        let sessions = self.lock();
733        let entry = sessions
734            .get(id)
735            .ok_or_else(|| RpcError::session_not_found(id))?;
736        match &entry.execution {
737            Some(execution) => {
738                execution.cancel.store(true, Ordering::Relaxed);
739                Ok(true)
740            }
741            None => Ok(false),
742        }
743    }
744
745    /// Persist a finished execution's transcript/usage/cost into the session
746    /// (#2056; #2344 made CUMULATIVE across runs).
747    ///
748    /// Why: populates the storage `Self::get_transcript` (#2058) reads back
749    /// over the wire. (#2344) A session's turns/usage/cost now accumulate
750    /// across every `task.run` rather than the last run overwriting the
751    /// previous one's — the whole point of a persistent session is that
752    /// `session.get_transcript` shows the FULL conversation, not just its
753    /// most recent slice.
754    /// What: best-effort — a no-op if `id` is already gone (e.g. the daemon
755    /// is shutting down mid-run). `transcript` is APPENDED onto the existing
756    /// turns (not replacing them); `usage` is added field-wise via
757    /// `TokenUsage::add` (the same accumulator `run_task::aggregate_usage_per_role`
758    /// uses internally); `cost_usd` sums the two `Option<f64>`s the same way
759    /// `TokenUsage::add` combines its own `cost_usd` field (`Some`+`Some` ->
760    /// sum, either `Some` alone passes through, `None`+`None` stays `None`).
761    /// Test: `registry_tests::set_run_outcome_stores_transcript_and_usage`,
762    /// `registry_tests::set_run_outcome_accumulates_across_two_calls`.
763    ///
764    /// (Issue #3298) Also records+publishes `Event::SessionActivityUpdate` —
765    /// the natural "a turn just happened" hook DOC-48 §5.3's event table asks
766    /// for, so a workstream observer can see which bound sessions are
767    /// recently active without polling. Published ONLY when `id` is
768    /// workstream-bound (`Session.workstream_id.is_some()`): the event
769    /// exists for workstream observers (§5.3 lists it in the WORKSTREAM
770    /// event set), an unbound session has no such observer, and — decisive
771    /// — the M1 cutline e2e contract (`tests/m1_cutline_e2e.rs`) freezes the
772    /// exact event-kind sequence a plain, workstream-less session emits;
773    /// firing this unconditionally inserted a new kind into that baseline
774    /// and broke both transports' frozen sequences (CI failure on PR #3354).
775    /// A no-op alongside the rest of this method if `id` is already gone.
776    /// Test: `registry_tests::set_run_outcome_publishes_activity_update_when_workstream_bound`,
777    /// `registry_tests::set_run_outcome_stays_silent_for_unbound_session`;
778    /// the frozen unbound-session baseline itself in
779    /// `m1_cutline_e2e::m1_cutline_full_scenario_over_stdio`/`_http`.
780    pub fn set_run_outcome(
781        &self,
782        id: &str,
783        transcript: Vec<TurnRecord>,
784        usage: TokenUsage,
785        cost_usd: Option<f64>,
786    ) {
787        let activity = {
788            let mut sessions = self.lock();
789            let Some(entry) = sessions.get_mut(id) else {
790                return;
791            };
792            entry.transcript.extend(transcript);
793            entry.usage.add(&usage);
794            entry.cost_usd = match (entry.cost_usd, cost_usd) {
795                (Some(a), Some(b)) => Some(a + b),
796                (Some(a), None) | (None, Some(a)) => Some(a),
797                (None, None) => None,
798            };
799            let bound = entry.session.workstream_id.is_some();
800            bound.then_some(entry.execution.is_some())
801        };
802        self.publish_activity_update(id, activity);
803    }
804
805    /// Retrieve this session's persistent PM conversation `Transcript`,
806    /// seeding it on the session's FIRST `task.run` and appending `task` as a
807    /// new user turn onto the existing history on every SUBSEQUENT one
808    /// (#2344 — the infinite-sessions conversation-continuity entry point).
809    ///
810    /// Why: `task::executor::run_and_record` must hand the PM's `AgentLoop`
811    /// the SAME growing `Transcript` every run drives via
812    /// `AgentLoop::run_with_transcript`, rather than reseeding fresh each
813    /// time (the pre-#2344 behaviour). Taking ownership OUT of the entry
814    /// (rather than cloning) lets the caller drive the loop against it
815    /// directly with no extra copy; briefly leaving `None` in storage while a
816    /// run is active can never be observed by a second concurrent caller —
817    /// `Self::begin_execution`'s single-in-flight-run guard already rejects a
818    /// second `task.run` on the same session before it would ever reach this
819    /// method (see that method's docs).
820    /// What: `Err(session_not_found)` if `id` is unknown. If `pm_transcript`
821    /// is `None` (the session has never run, or is between runs having been
822    /// `take`n and not yet restored — the call-order guarantee above means
823    /// the latter should never actually happen), seeds a fresh
824    /// `Transcript::seed(system, task)`. If `Some`, takes the existing
825    /// transcript out of storage and appends `task` as a new `user` turn via
826    /// `Transcript::push_user` — `system` is IGNORED on this branch: the
827    /// original seed's system message stays authoritative for the life of
828    /// the session (a refresh mechanism, if `agent`/`mode` config changes
829    /// between runs, is future work — not this ticket).
830    /// Test: `registry_tests::begin_pm_transcript_seeds_on_first_call`,
831    /// `registry_tests::begin_pm_transcript_appends_on_second_call`,
832    /// `registry_tests::begin_pm_transcript_unknown_session_errors`.
833    pub fn begin_pm_transcript(
834        &self,
835        id: &str,
836        system: &str,
837        task: &str,
838    ) -> Result<Transcript, RpcError> {
839        let mut sessions = self.lock();
840        let entry = sessions
841            .get_mut(id)
842            .ok_or_else(|| RpcError::session_not_found(id))?;
843        Ok(match entry.pm_transcript.take() {
844            Some(mut existing) => {
845                existing.push_user(task);
846                existing
847            }
848            None => Transcript::seed(system, task),
849        })
850    }
851
852    /// Persist the PM's conversation `Transcript` back onto the session once
853    /// a run ends (#2344).
854    ///
855    /// Why: pairs with [`Self::begin_pm_transcript`] — MUST be called
856    /// regardless of the run's outcome (success, failure, cancellation, or
857    /// timeout) so the conversation up to the point of interruption survives
858    /// for the NEXT `task.run` to continue from, rather than the session
859    /// being left with no `pm_transcript` at all (which would silently
860    /// re-seed from scratch on the next run instead of erroring).
861    /// What: best-effort — a no-op if `id` is already gone (mirrors
862    /// `Self::set_run_outcome`'s same best-effort framing).
863    /// Test: `registry_tests::begin_pm_transcript_appends_on_second_call`
864    /// (exercises both halves of the round trip).
865    pub fn store_pm_transcript(&self, id: &str, transcript: Transcript) {
866        let mut sessions = self.lock();
867        if let Some(entry) = sessions.get_mut(id) {
868            entry.pm_transcript = Some(transcript);
869        }
870    }
871
872    /// `task.run`: persist the resolved `HarnessMode` onto the session
873    /// (#2059).
874    ///
875    /// Why: `task::protocol::task_run` resolves the mode (env var >
876    /// `task.run` param > `.claude/settings.json` > default) BEFORE spawning
877    /// the execution; storing it here — rather than waiting for
878    /// `set_run_outcome` at the end of the run — makes it queryable via
879    /// `session.status`/`session.list` (`Session.mode`) and
880    /// `session.get_transcript` (`TranscriptRecord.mode`, which reads the
881    /// SAME field) as soon as `task.run` returns, not only after the run
882    /// completes.
883    /// What: `Err(session_not_found)` if `id` is unknown; otherwise sets
884    /// `entry.session.mode = Some(mode)`. No event is published — mode is
885    /// bookkeeping metadata, not a session-lifecycle transition in the
886    /// #2055 event taxonomy.
887    /// Test: `registry_tests::set_mode_stores_on_session`,
888    /// `registry_tests::set_mode_unknown_session_errors`.
889    pub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError> {
890        let mut sessions = self.lock();
891        let entry = sessions
892            .get_mut(id)
893            .ok_or_else(|| RpcError::session_not_found(id))?;
894        entry.session.mode = Some(mode);
895        Ok(())
896    }
897
898    /// Cooperatively cancel every in-flight execution and wait, bounded by
899    /// `grace`, for them to actually stop (#2056 — graceful daemon shutdown).
900    ///
901    /// Why: without this, a `tokio::spawn`'d background execution would be
902    /// abruptly dropped — never given a chance to unwind — the instant the
903    /// process's tokio runtime shuts down, violating the connection-safe
904    /// daemon-restart convention (issue #534) this extends from connections
905    /// to long-running tasks.
906    /// What: flips every tracked execution's cancel flag, takes ownership of
907    /// each `JoinHandle`, then awaits all of them concurrently with an
908    /// overall `grace` timeout. A handle that doesn't finish in time is left
909    /// to be dropped when the process exits (best-effort, not a hard
910    /// guarantee — matching the same best-effort framing as every other
911    /// shutdown step in this codebase).
912    /// Test: `registry_tests::shutdown_executions_awaits_cancelled_tasks`.
913    pub async fn shutdown_executions(&self, grace: Duration) {
914        let handles: Vec<JoinHandle<()>> = {
915            let mut sessions = self.lock();
916            sessions
917                .values_mut()
918                .filter_map(|entry| {
919                    let execution = entry.execution.as_mut()?;
920                    execution.cancel.store(true, Ordering::Relaxed);
921                    execution.handle.take()
922                })
923                .collect()
924        };
925        if handles.is_empty() {
926            return;
927        }
928        let _ = tokio::time::timeout(grace, futures_util::future::join_all(handles)).await;
929    }
930
931    /// Assign the next per-session `seq`, wrap `event` in a
932    /// [`SessionEventEnvelope`], push it onto `id`'s ring buffer (evicting
933    /// the oldest entry if full), and publish the envelope on the
934    /// process-global bus.
935    ///
936    /// Why: every lifecycle/tool/log/progress/message event goes through
937    /// this ONE function so `seq` assignment, the ring buffer, and the live
938    /// bus can never drift out of sync with each other — the correctness
939    /// property `attach_replay_then_live_seq_is_contiguous` verifies. It is
940    /// ALSO the one place `SessionEntry::agents` (DOC-39 §5.4) is updated —
941    /// the same critical section that pushes onto the capacity-bounded
942    /// `ring`, so the always-retained roster and the ring can never observe
943    /// a different event even transiently.
944    /// What: a no-op (no envelope built, nothing published) if `id` is
945    /// unknown — callers that need a hard error check existence first
946    /// (`send`, `cancel`, every `record_*` plumbing method all do).
947    fn record(&self, id: &str, event: Event) {
948        let envelope = {
949            let mut sessions = self.lock();
950            let Some(entry) = sessions.get_mut(id) else {
951                return;
952            };
953            entry.seq += 1;
954            let envelope = SessionEventEnvelope::new(id.to_string(), entry.seq, Utc::now(), event);
955            if entry.ring.len() >= self.ring_capacity {
956                entry.ring.pop_front();
957            }
958            entry.ring.push_back(envelope.clone());
959            entry.note_agent_activity(&envelope.event);
960            envelope
961        };
962        crate::events::publish(envelope);
963    }
964
965    /// Update a session's status in place, then record+publish
966    /// `Event::SessionStatusChanged`.
967    fn transition(&self, id: &str, status: SessionStatus) {
968        {
969            let mut sessions = self.lock();
970            if let Some(entry) = sessions.get_mut(id) {
971                entry.session.status = status;
972            }
973        }
974        self.record(
975            id,
976            Event::SessionStatusChanged {
977                session_id: id.to_string(),
978                status: status.as_str().to_string(),
979            },
980        );
981    }
982
983    /// Lock the session map, recovering from poisoning.
984    ///
985    /// Why: a panic inside another handler while holding this lock should
986    /// not permanently wedge the whole registry for every other session —
987    /// recovering the poisoned guard is safer than propagating a panic into
988    /// unrelated requests.
989    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, SessionEntry>> {
990        self.sessions
991            .lock()
992            .unwrap_or_else(|poison| poison.into_inner())
993    }
994}
995
996/// Spawn the background task that forwards one session's live event
997/// envelopes to a connection until cancelled or the connection is gone.
998///
999/// Why: split out of `attach` for readability; also gives `registry_tests`
1000/// a single well-named spawn site to reason about. Subscribing to the bus
1001/// SYNCHRONOUSLY here — before `tokio::spawn` schedules the forwarder body
1002/// — matters: if the subscription happened inside the spawned `async`
1003/// block instead, a caller that calls `send()` immediately after `attach()`
1004/// returns could publish its event before the spawned task ever gets polled
1005/// and subscribes, and `broadcast::Receiver`s only see events published
1006/// after `subscribe()` was called — the event would be silently missed.
1007/// What: subscribes to `crate::events::subscribe()` immediately, then
1008/// spawns a task that forwards envelopes whose `session_id` matches
1009/// `session_id` as a JSON-RPC notification via `notify` (`params` is the
1010/// envelope itself — `seq`/`at`/`kind`/`event` all present), skips
1011/// envelopes for other sessions and lag gaps, and exits on `cancel_rx`
1012/// firing (either a real detach or the sender being dropped) or
1013/// `notify.send` failing (connection gone).
1014/// Test: `registry_tests::attach_forwards_live_events_until_detach`.
1015fn spawn_forwarder(session_id: String, notify: NotifySender, cancel_rx: oneshot::Receiver<()>) {
1016    use tokio::sync::broadcast::error::RecvError;
1017
1018    // Subscribe before spawning (see the Why above) so no event published
1019    // by the caller right after `attach()` returns can be missed.
1020    let mut events = crate::events::subscribe();
1021
1022    tokio::spawn(async move {
1023        tokio::pin!(cancel_rx);
1024        loop {
1025            tokio::select! {
1026                biased;
1027                _ = &mut cancel_rx => break,
1028                received = events.recv() => match received {
1029                    Ok(envelope) if envelope.session_id == session_id => {
1030                        let notification = json!({
1031                            "jsonrpc": "2.0",
1032                            "method": "session.event",
1033                            "params": envelope,
1034                        });
1035                        if notify.send(notification).is_err() {
1036                            break;
1037                        }
1038                    }
1039                    Ok(_) => continue,
1040                    Err(RecvError::Lagged(_)) => continue,
1041                    Err(RecvError::Closed) => break,
1042                },
1043            }
1044        }
1045    });
1046}
1047
1048/// #2055 tool/log/progress/message event-recording plumbing, split out into
1049/// its own file (#2344) purely to keep this production file under the
1050/// 500-SLOC cap — these methods are still `impl SessionRegistry`, called
1051/// exactly the same way as if they lived here.
1052#[path = "registry_events.rs"]
1053mod events;
1054
1055/// #2345 turn-recorder sink lazy-init/lookup, split out into its own file for
1056/// the same 500-SLOC-cap reason as `events` above.
1057#[path = "registry_memory_sink.rs"]
1058mod memory_sink_ext;
1059
1060/// #2058's `session.get_transcript` projection, split out into its own file
1061/// for the same 500-SLOC-cap reason as `events` above.
1062#[path = "registry_transcript.rs"]
1063mod transcript_ops;
1064
1065/// #2350 operator-facing goal-slot plumbing (`session.set_goal`/
1066/// `clear_goal`/`get_goals`), split out into its own file for the same
1067/// 500-SLOC-cap reason as `events`/`memory_sink_ext` above.
1068#[path = "registry_goals.rs"]
1069mod goal_ops;
1070
1071/// `session.get_agents`'s live-roster fold (DOC-39 §5.4), split out into its
1072/// own file for the same 500-SLOC-cap reason as `events` above.
1073#[path = "registry_agents.rs"]
1074mod agents;
1075
1076/// `SessionRegistry::bind_workstream` (DOC-48 §4.1, issue #3298), split out
1077/// into its own file for the same 500-SLOC-cap reason as `events` above.
1078#[path = "registry_workstream.rs"]
1079mod workstream_binding;
1080
1081/// `session.get_search_audit`'s retained search/recall audit trail (issue
1082/// #3072), split out into its own file for the same 500-SLOC-cap reason as
1083/// `events` above.
1084#[path = "registry_search_audit.rs"]
1085mod search_audit;
1086
1087#[cfg(test)]
1088#[path = "registry_tests.rs"]
1089mod registry_tests;