trusty-code 0.1.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
//! Daemon-owned session registry: storage, per-session sequencing, ring
//! buffer, and attach/detach bookkeeping (#2054, #2055).
//!
//! Why: this is the object Axiom 4 describes — sessions live INSIDE the
//! daemon, not in a CLI-side tmux pane. `SessionRegistry` is the single
//! owner of every `Session`'s state, its bounded event history, and (#2055)
//! the per-session sequence counter that makes replay -> live gap detection
//! possible. Designed so persistence (Phase 2+, out of scope per §12) can be
//! added by swapping the storage backing this type without touching
//! `session::protocol`'s handlers or the wire protocol at all.
//! What: [`SessionRegistry`] holds `HashMap<String, SessionEntry>` behind a
//! `std::sync::Mutex` (never held across an `.await` — every method here is
//! synchronous; `attach` uses `tokio::spawn` to hand off, not to block).
//! Each entry carries the `Session` snapshot, a monotonic per-session `seq`
//! counter, a bounded ring buffer of recent
//! `crate::events::SessionEventEnvelope`s (§12.1.5: default 1000, oldest
//! dropped first), and a map of live attachments (`connection_id` ->
//! `oneshot::Sender<()>` used by `detach` to stop that connection's
//! forwarder task). [`Self::record`] is the ONE place that assigns `seq`
//! (under the same lock that pushes the ring buffer entry), so replay and
//! every subsequent live event share one gap-free, strictly increasing
//! sequence — see `crate::events`'s module docs for the full envelope
//! rationale. `attach` replays the ring buffer synchronously, then spawns a
//! task that subscribes to the existing process-global `crate::events` bus,
//! filters by `session_id`, and forwards matching envelopes into the
//! caller's `NotifySender` until detached or the channel closes (the
//! connection is gone).
//! Test: see `registry_tests` (sibling file, `#[cfg(test)]`).

use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use chrono::Utc;
use serde_json::json;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;
use uuid::Uuid;

use crate::events::{Event, SessionEventEnvelope};
use crate::jsonrpc::{NotifySender, RpcError};
use crate::mode::HarnessMode;
use crate::perf::TokenUsage;
use crate::run_task::TurnRecord;

use super::model::{Session, SessionStatus};
use super::transcript::TranscriptRecord;

/// Default ring-buffer capacity per session (vision spec §12, 11.5).
///
/// Why: bounds per-session memory use; a freshly-attached client sees
/// "recent progress but not the full session history" per spec — the ring
/// buffer is the LIVE-event window, distinct from the full run transcript
/// `session.get_transcript` (#2058) exposes via `Self::get_transcript`.
/// Test: `registry_tests::ring_buffer_drops_oldest_when_full`.
pub const DEFAULT_RING_CAPACITY: usize = 1000;

/// One session's storage: the domain snapshot, its sequence counter, ring
/// buffer, the live attachments forwarding its events, and (#2056) its
/// background execution state + last completed run's outcome.
struct SessionEntry {
    session: Session,
    /// Last-assigned per-session sequence number; the next event gets
    /// `seq + 1`. Starts at `0` so the first recorded event is `seq = 1`.
    seq: u64,
    ring: VecDeque<SessionEventEnvelope>,
    /// `connection_id` -> the cancel sender for that connection's forwarder
    /// task. Re-attaching the same connection to the same session replaces
    /// (and thus cancels, via `Sender` drop) the previous forwarder.
    attachments: HashMap<Uuid, oneshot::Sender<()>>,
    /// #2056: set while a background task-execution is in flight; `None`
    /// when idle (never started, or already finished).
    execution: Option<Execution>,
    /// #2056: the run transcript populated once an execution finishes;
    /// exposed read-only via `session.get_transcript` (#2058,
    /// `Self::get_transcript`). Empty until the first execution completes.
    transcript: Vec<TurnRecord>,
    /// #2056: aggregated token usage from the last completed execution.
    usage: TokenUsage,
    /// #2056: summed USD cost from the last completed execution (`None` if
    /// pricing was unavailable — mirrors `run_task::RunReport::cost_usd`).
    cost_usd: Option<f64>,
}

/// #2056: bookkeeping for one in-flight background task execution.
///
/// Why: `SessionRegistry` needs to (a) reject a second overlapping run for
/// the same session, (b) signal cooperative cancellation, and (c) — on
/// graceful daemon shutdown — wait, bounded, for the task to actually stop.
/// What: `cancel` is shared with every `AgentLoop`/`InProcessAgentRunner`
/// the execution drives (via `with_cancel_flag`); `handle` is the
/// `tokio::spawn` join handle, attached shortly after `begin_execution`
/// returns (see [`SessionRegistry::attach_execution_handle`]) since the
/// handle does not exist until the caller has actually spawned the task.
struct Execution {
    cancel: Arc<AtomicBool>,
    handle: Option<JoinHandle<()>>,
}

/// The daemon-owned session registry (Axiom 4).
///
/// Why: single source of truth for every session's state, in-memory only
/// (§12, M1) — see the module docs for the full rationale.
/// What: see method docs below; `new()` uses [`DEFAULT_RING_CAPACITY`],
/// `with_capacity` lets tests use a tiny buffer to exercise eviction cheaply.
/// Test: `registry_tests::*`.
pub struct SessionRegistry {
    sessions: Mutex<HashMap<String, SessionEntry>>,
    ring_capacity: usize,
}

impl Default for SessionRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl SessionRegistry {
    /// Construct an empty registry with the default ring-buffer capacity.
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_RING_CAPACITY)
    }

    /// Construct an empty registry with an explicit ring-buffer capacity.
    ///
    /// Why: unit tests need a small capacity to exercise eviction without
    /// pushing 1000 events.
    pub fn with_capacity(ring_capacity: usize) -> Self {
        Self {
            sessions: Mutex::new(HashMap::new()),
            ring_capacity,
        }
    }

    /// `session.create`: register a brand-new session and publish its
    /// lifecycle-start events.
    ///
    /// Why: the sole entry point that mints a session id and puts a
    /// `Session` into the registry.
    /// What: builds a `Session` with a fresh UUIDv4 id and
    /// `status = Created`, inserts it (with a fresh `seq = 0` counter),
    /// publishes `Event::SessionStarted` (assigned `seq = 1`), then
    /// immediately transitions to `Running` (M1 has no queue ahead of real
    /// task execution — see `session::model` docs) which publishes
    /// `Event::SessionStatusChanged` (`seq = 2`). Returns the
    /// post-transition snapshot (so the caller sees `status: "running"`,
    /// not the momentary `"created"`).
    /// Test: `registry_tests::create_publishes_started_and_status_events`.
    pub fn create(&self, task: String, agent: Option<String>, project: Option<String>) -> Session {
        let id = Uuid::new_v4().to_string();
        let session = Session {
            id: id.clone(),
            task,
            agent,
            project: project.clone(),
            status: SessionStatus::Created,
            created_at: Utc::now(),
            mode: None,
        };
        {
            let mut sessions = self.lock();
            sessions.insert(
                id.clone(),
                SessionEntry {
                    session: session.clone(),
                    seq: 0,
                    ring: VecDeque::new(),
                    attachments: HashMap::new(),
                    execution: None,
                    transcript: Vec::new(),
                    usage: TokenUsage::default(),
                    cost_usd: None,
                },
            );
        }
        self.record(
            &id,
            Event::SessionStarted {
                session_id: id.clone(),
                project: project.unwrap_or_default(),
            },
        );
        self.transition(&id, SessionStatus::Running);
        self.status(&id).unwrap_or(session)
    }

    /// `session.list`: snapshot every session currently in the registry.
    ///
    /// Why: the read side of the registry for operators/CLI/TUI to enumerate
    /// running sessions.
    /// What: clones every `Session` snapshot; order is unspecified (backed
    /// by a `HashMap`).
    /// Test: `registry_tests::list_returns_every_created_session`.
    pub fn list(&self) -> Vec<Session> {
        self.lock().values().map(|e| e.session.clone()).collect()
    }

    /// `session.status`: snapshot one session by id.
    ///
    /// Why: shared by `create`'s return value and the standalone
    /// `session.status` method.
    /// What: `Ok(Session)` if present, `Err(RpcError::session_not_found)`
    /// otherwise.
    /// Test: `registry_tests::status_returns_not_found_for_unknown_id`.
    pub fn status(&self, id: &str) -> Result<Session, RpcError> {
        self.lock()
            .get(id)
            .map(|e| e.session.clone())
            .ok_or_else(|| RpcError::session_not_found(id))
    }

    /// `session.send`: deliver input to a session and publish an observable
    /// event proving the daemon received it.
    ///
    /// Why: #2054/#2055 do not wire a real agent loop (that is `task.*`,
    /// #2056); publishing `Event::SessionInput` is what makes `session.send`
    /// observably reach a `session.attach`ed client NOW, and gives #2056 a
    /// concrete event to build real echo/ack behaviour on top of.
    /// What: errors with `session_not_found` if `id` is unknown; otherwise
    /// records+publishes `Event::SessionInput { session_id, input }`.
    /// Test: `registry_tests::send_publishes_input_event`,
    /// `registry_tests::send_unknown_session_errors`.
    pub fn send(&self, id: &str, input: &str) -> Result<(), RpcError> {
        if !self.lock().contains_key(id) {
            return Err(RpcError::session_not_found(id));
        }
        self.record(
            id,
            Event::SessionInput {
                session_id: id.to_string(),
                input: input.to_string(),
            },
        );
        Ok(())
    }

    /// `session.cancel`: send a cancellation signal and mark the session
    /// terminal.
    ///
    /// Why: vision spec §12 (11.6) Cancellation Semantics — cancellation is
    /// a status transition + event, not a deletion. #2054/#2055 have no
    /// in-flight agent loop to interrupt yet (that lands with #2056), so
    /// this is the full implementation available today: it marks the
    /// session `Cancelled` and publishes the terminal events; #2056 hooks
    /// the actual agent-loop interrupt onto the same status transition.
    /// What: idempotent — cancelling an already-terminal session is a no-op
    /// that returns the current snapshot rather than erroring (repeated
    /// `session.cancel` calls are safe). Errors with `session_not_found` if
    /// `id` is unknown. On a live session: publishes
    /// `Event::SessionStatusChanged` (`status: "cancelled"`), then the
    /// dedicated `Event::SessionCancelled` signal, then the generic terminal
    /// `Event::SessionDone` (`status: "cancelled"`) — matching the vision
    /// spec's `started/status-changed/input/cancelled/done` taxonomy — and
    /// returns the updated snapshot.
    /// Test: `registry_tests::cancel_transitions_to_cancelled_and_publishes`,
    /// `registry_tests::cancel_is_idempotent_on_terminal_session`,
    /// `registry_tests::cancel_unknown_session_errors`.
    pub fn cancel(&self, id: &str) -> Result<Session, RpcError> {
        let already_terminal = {
            let sessions = self.lock();
            let entry = sessions
                .get(id)
                .ok_or_else(|| RpcError::session_not_found(id))?;
            entry.session.status.is_terminal()
        };
        if already_terminal {
            return self.status(id);
        }
        self.transition(id, SessionStatus::Cancelled);
        self.record(
            id,
            Event::SessionCancelled {
                session_id: id.to_string(),
            },
        );
        self.record(
            id,
            Event::SessionDone {
                session_id: id.to_string(),
                status: SessionStatus::Cancelled.as_str().to_string(),
            },
        );
        self.status(id)
    }

    /// Mark a session terminal (finished, failed, or cancelled while
    /// executing) and publish the terminal `Event::SessionDone` (#2056).
    ///
    /// Why: the background executor (`crate::task::executor`) needs to set
    /// the FINAL status once an agent loop returns, distinctly from the
    /// user-initiated `session.cancel` JSON-RPC path ([`Self::cancel`]),
    /// which ALSO emits a dedicated `Event::SessionCancelled` signal that
    /// only makes sense for an explicit user cancel request — not a natural
    /// finish or failure, and not a cancellation the EXECUTOR itself
    /// observed (that path already went through `request_cancel`, which
    /// does not transition status; the executor calls this afterward to
    /// actually land the transition once it has unwound).
    /// What: idempotent — a no-op (returns the current snapshot) if the
    /// session is already terminal, since a race between `request_cancel`'s
    /// caller and the executor noticing cancellation is possible but
    /// harmless. Errors with `session_not_found` if `id` is unknown.
    /// Otherwise transitions to `status` and publishes
    /// `Event::SessionDone { status }`.
    /// Test: `registry_tests::finish_transitions_and_publishes_session_done`,
    /// `registry_tests::finish_is_idempotent_on_terminal_session`,
    /// `registry_tests::finish_unknown_session_errors`.
    pub fn finish(&self, id: &str, status: SessionStatus) -> Result<Session, RpcError> {
        let already_terminal = {
            let sessions = self.lock();
            let entry = sessions
                .get(id)
                .ok_or_else(|| RpcError::session_not_found(id))?;
            entry.session.status.is_terminal()
        };
        if !already_terminal {
            self.transition(id, status);
            self.record(
                id,
                Event::SessionDone {
                    session_id: id.to_string(),
                    status: status.as_str().to_string(),
                },
            );
        }
        self.status(id)
    }

    /// `session.attach`: replay recent history and start forwarding this
    /// session's live events to `notify`.
    ///
    /// Why: the streaming half of the session-attach protocol (vision spec
    /// §4.4/Axiom 4). Works identically regardless of transport — the
    /// difference between STDIO (long-lived `notify`, events interleaved on
    /// stdout) and HTTP (throwaway `notify`; the real live path is the `GET
    /// /sessions/{id}/events` SSE route) lives entirely in
    /// `crate::jsonrpc::ConnectionContext`'s docs and `crate::serve`'s
    /// transports, not here.
    /// What: errors with `session_not_found` if `id` is unknown. Otherwise
    /// takes a snapshot of the ring buffer (oldest-first, each entry a full
    /// [`SessionEventEnvelope`] with its `seq` intact) to return as the
    /// replay, registers `connection_id`'s cancel sender (replacing — and
    /// thus cancelling — any prior forwarder for the same
    /// `(session, connection)` pair), and spawns a task that subscribes to
    /// `crate::events::subscribe()`, filters by `session_id`, and forwards
    /// each match into `notify` as a JSON-RPC notification whose `params` IS
    /// the envelope (`{"jsonrpc":"2.0","method":"session.event","params":
    /// {"session_id":...,"seq":...,"at":...,"kind":...,"event":{...}}}`)
    /// until `detach` fires the cancel sender or `notify.send` fails (the
    /// connection is gone). Because every envelope — replayed or live —
    /// comes from the SAME per-session `seq` counter (`record`), a client
    /// that concatenates the replay array with the live notifications it
    /// receives afterward sees one gap-free, strictly increasing sequence.
    /// Test: `registry_tests::attach_returns_ring_buffer_replay`,
    /// `registry_tests::attach_forwards_live_events_until_detach`,
    /// `registry_tests::attach_replay_then_live_seq_is_contiguous`,
    /// `registry_tests::attach_unknown_session_errors`.
    pub fn attach(
        &self,
        id: &str,
        connection_id: Uuid,
        notify: NotifySender,
    ) -> Result<Vec<SessionEventEnvelope>, RpcError> {
        let replay = {
            let mut sessions = self.lock();
            let entry = sessions
                .get_mut(id)
                .ok_or_else(|| RpcError::session_not_found(id))?;
            let (cancel_tx, cancel_rx) = oneshot::channel();
            entry.attachments.insert(connection_id, cancel_tx);
            spawn_forwarder(id.to_string(), notify, cancel_rx);
            entry.ring.iter().cloned().collect::<Vec<_>>()
        };
        Ok(replay)
    }

    /// `session.detach`: stop forwarding this session's live events to the
    /// calling connection.
    ///
    /// Why: the other half of the attach protocol — releases the forwarder
    /// task started by `attach` for this `(session, connection)` pair.
    /// What: errors with `session_not_found` if `id` is unknown. If the
    /// connection has no live attachment (already detached, or never
    /// attached), this is a no-op success rather than an error — detach is
    /// idempotent. Otherwise fires the stored cancel sender, which stops the
    /// forwarder task on its next `select!` poll.
    /// Test: `registry_tests::detach_stops_the_forwarder`,
    /// `registry_tests::detach_without_prior_attach_is_a_noop`,
    /// `registry_tests::detach_unknown_session_errors`.
    pub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError> {
        let mut sessions = self.lock();
        let entry = sessions
            .get_mut(id)
            .ok_or_else(|| RpcError::session_not_found(id))?;
        if let Some(cancel_tx) = entry.attachments.remove(&connection_id) {
            let _ = cancel_tx.send(());
        }
        Ok(())
    }

    /// Snapshot the ring buffer for a session without attaching to it.
    ///
    /// Why: the HTTP SSE route (`crate::serve::http`) needs the same replay
    /// burst `attach` returns, but subscribes to the live bus itself (one
    /// `Stream` per SSE connection) rather than going through a
    /// `NotifySender` forwarder — so it calls this directly instead of
    /// `attach`.
    /// What: same replay semantics as `attach` (full envelopes, `seq`
    /// intact), no side effects (no forwarder spawned, no attachment
    /// recorded).
    /// Test: `registry_tests::replay_returns_ring_buffer_without_attaching`.
    pub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError> {
        self.lock()
            .get(id)
            .map(|e| e.ring.iter().cloned().collect())
            .ok_or_else(|| RpcError::session_not_found(id))
    }

    /// Begin tracking a new background task execution for `id` (#2056).
    ///
    /// Why: `task.run` (and `session.send` on an idle session) must not start
    /// a second overlapping run for the same session, and the returned flag
    /// is how the executor's `AgentLoop`(s) later observe cancellation.
    /// What: errors with `session_not_found` if `id` is unknown,
    /// `invalid_argument` if the session is already terminal or already has
    /// an execution in flight. On success, stores a fresh `Arc<AtomicBool>`
    /// cancel flag (initially `false`) with `handle: None` — the caller
    /// attaches the real `JoinHandle` via
    /// [`Self::attach_execution_handle`] immediately after spawning, since
    /// the handle cannot exist before that — and returns the flag.
    /// Test: `registry_tests::begin_execution_rejects_second_overlapping_run`,
    /// `registry_tests::begin_execution_rejects_terminal_session`,
    /// `registry_tests::begin_execution_unknown_session_errors`.
    pub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError> {
        let mut sessions = self.lock();
        let entry = sessions
            .get_mut(id)
            .ok_or_else(|| RpcError::session_not_found(id))?;
        if entry.session.status.is_terminal() {
            return Err(RpcError::invalid_argument(format!(
                "session {id} is already terminal"
            )));
        }
        if entry.execution.is_some() {
            return Err(RpcError::invalid_argument(format!(
                "session {id} already has a task running"
            )));
        }
        let cancel = Arc::new(AtomicBool::new(false));
        entry.execution = Some(Execution {
            cancel: Arc::clone(&cancel),
            handle: None,
        });
        Ok(cancel)
    }

    /// Attach the real `JoinHandle` to `id`'s tracked execution (#2056).
    ///
    /// Why: the handle only exists once the caller has actually called
    /// `tokio::spawn`, which must happen after `begin_execution` returns (the
    /// spawned future needs the cancel flag `begin_execution` produces).
    /// What: best-effort — a no-op if `id` or its execution is already gone
    /// (e.g. the run finished astonishingly fast, or the session vanished).
    /// Test: `registry_tests::shutdown_executions_awaits_cancelled_tasks`
    /// (exercises this indirectly via a real spawn).
    pub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>) {
        let mut sessions = self.lock();
        if let Some(entry) = sessions.get_mut(id)
            && let Some(execution) = entry.execution.as_mut()
        {
            execution.handle = Some(handle);
        }
    }

    /// Clear the execution-in-flight marker for `id` (#2056).
    ///
    /// Why: called by the executor once the background task has stopped
    /// (finished, failed, or cancelled) so a later `task.run`/`session.send`
    /// can start a new run against the same session.
    /// What: best-effort — a no-op if `id` is already gone.
    /// Test: `registry_tests::begin_execution_rejects_second_overlapping_run`
    /// (calls this between the two `begin_execution` attempts).
    pub fn finish_execution(&self, id: &str) {
        let mut sessions = self.lock();
        if let Some(entry) = sessions.get_mut(id) {
            entry.execution = None;
        }
    }

    /// Whether `id` currently has a background execution in flight (#2056).
    ///
    /// Why: `session::protocol::cancel` uses this to choose between
    /// cooperative cancellation ([`Self::request_cancel`]) and the original
    /// #2054 immediate-transition [`Self::cancel`].
    /// What: `false` for both "unknown session" and "known but idle" — callers
    /// that need to distinguish those already call another method first.
    /// Test: `registry_tests::request_cancel_*`.
    pub fn is_executing(&self, id: &str) -> bool {
        self.lock().get(id).is_some_and(|e| e.execution.is_some())
    }

    /// Request cooperative cancellation of `id`'s in-flight execution, if any
    /// (#2056).
    ///
    /// Why: `session.cancel` on a RUNNING session must signal the background
    /// task rather than force an immediate status transition — the task
    /// itself transitions to `Cancelled` once it actually observes the flag
    /// and unwinds (see `crate::task::executor`).
    /// What: `Err(session_not_found)` if `id` is unknown. `Ok(true)` if an
    /// execution was in flight and its flag was set; `Ok(false)` if the
    /// session exists but nothing is executing (the caller should fall back
    /// to [`Self::cancel`] for the immediate-transition path).
    /// Test: `registry_tests::request_cancel_sets_flag_when_executing`,
    /// `registry_tests::request_cancel_returns_false_when_idle`.
    pub fn request_cancel(&self, id: &str) -> Result<bool, RpcError> {
        let sessions = self.lock();
        let entry = sessions
            .get(id)
            .ok_or_else(|| RpcError::session_not_found(id))?;
        match &entry.execution {
            Some(execution) => {
                execution.cancel.store(true, Ordering::Relaxed);
                Ok(true)
            }
            None => Ok(false),
        }
    }

    /// Persist a finished execution's transcript/usage/cost into the session
    /// (#2056).
    ///
    /// Why: populates the storage `Self::get_transcript` (#2058) reads back
    /// over the wire.
    /// What: best-effort — a no-op if `id` is already gone (e.g. the daemon
    /// is shutting down mid-run).
    /// Test: `registry_tests::set_run_outcome_stores_transcript_and_usage`.
    pub fn set_run_outcome(
        &self,
        id: &str,
        transcript: Vec<TurnRecord>,
        usage: TokenUsage,
        cost_usd: Option<f64>,
    ) {
        let mut sessions = self.lock();
        if let Some(entry) = sessions.get_mut(id) {
            entry.transcript = transcript;
            entry.usage = usage;
            entry.cost_usd = cost_usd;
        }
    }

    /// `session.get_transcript`: fetch the stored run record for a session
    /// (#2058).
    ///
    /// Why: [`Self::set_run_outcome`] populates the storage; this is its read
    /// counterpart — the M1 cut-line's "inspect transcript" verb. A never-run
    /// session is a valid, empty transcript, not an error: `SessionEntry`'s
    /// `transcript`/`usage`/`cost_usd` fields already default to
    /// empty/zero/`None` at `create` time, so returning them unconditionally
    /// (once the session itself is confirmed to exist) is correct with no
    /// extra branching.
    /// What: `Err(session_not_found)` if `id` is unknown; otherwise a clone of
    /// whatever is currently stored, wrapped in a self-describing
    /// [`TranscriptRecord`]. Never recomputes cost or usage — exposes exactly
    /// what [`Self::set_run_outcome`] last stored.
    /// Test: `registry_tests::get_transcript_returns_stored_record`,
    /// `registry_tests::get_transcript_on_never_run_session_is_empty`,
    /// `registry_tests::get_transcript_unknown_session_errors`.
    pub fn get_transcript(&self, id: &str) -> Result<TranscriptRecord, RpcError> {
        let sessions = self.lock();
        let entry = sessions
            .get(id)
            .ok_or_else(|| RpcError::session_not_found(id))?;
        Ok(TranscriptRecord {
            session_id: id.to_string(),
            turns: entry.transcript.clone(),
            usage: entry.usage,
            cost_usd: entry.cost_usd,
            mode: entry.session.mode,
        })
    }

    /// `task.run`: persist the resolved `HarnessMode` onto the session
    /// (#2059).
    ///
    /// Why: `task::protocol::task_run` resolves the mode (env var >
    /// `task.run` param > `.claude/settings.json` > default) BEFORE spawning
    /// the execution; storing it here — rather than waiting for
    /// `set_run_outcome` at the end of the run — makes it queryable via
    /// `session.status`/`session.list` (`Session.mode`) and
    /// `session.get_transcript` (`TranscriptRecord.mode`, which reads the
    /// SAME field) as soon as `task.run` returns, not only after the run
    /// completes.
    /// What: `Err(session_not_found)` if `id` is unknown; otherwise sets
    /// `entry.session.mode = Some(mode)`. No event is published — mode is
    /// bookkeeping metadata, not a session-lifecycle transition in the
    /// #2055 event taxonomy.
    /// Test: `registry_tests::set_mode_stores_on_session`,
    /// `registry_tests::set_mode_unknown_session_errors`.
    pub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError> {
        let mut sessions = self.lock();
        let entry = sessions
            .get_mut(id)
            .ok_or_else(|| RpcError::session_not_found(id))?;
        entry.session.mode = Some(mode);
        Ok(())
    }

    /// Cooperatively cancel every in-flight execution and wait, bounded by
    /// `grace`, for them to actually stop (#2056 — graceful daemon shutdown).
    ///
    /// Why: without this, a `tokio::spawn`'d background execution would be
    /// abruptly dropped — never given a chance to unwind — the instant the
    /// process's tokio runtime shuts down, violating the connection-safe
    /// daemon-restart convention (issue #534) this extends from connections
    /// to long-running tasks.
    /// What: flips every tracked execution's cancel flag, takes ownership of
    /// each `JoinHandle`, then awaits all of them concurrently with an
    /// overall `grace` timeout. A handle that doesn't finish in time is left
    /// to be dropped when the process exits (best-effort, not a hard
    /// guarantee — matching the same best-effort framing as every other
    /// shutdown step in this codebase).
    /// Test: `registry_tests::shutdown_executions_awaits_cancelled_tasks`.
    pub async fn shutdown_executions(&self, grace: Duration) {
        let handles: Vec<JoinHandle<()>> = {
            let mut sessions = self.lock();
            sessions
                .values_mut()
                .filter_map(|entry| {
                    let execution = entry.execution.as_mut()?;
                    execution.cancel.store(true, Ordering::Relaxed);
                    execution.handle.take()
                })
                .collect()
        };
        if handles.is_empty() {
            return;
        }
        let _ = tokio::time::timeout(grace, futures_util::future::join_all(handles)).await;
    }

    /// Record a tool invocation starting (#2055 emission plumbing for
    /// #2056's agent loop).
    ///
    /// Why: gives the future agent loop a stable, already-wired call for
    /// `ToolStarted` without it needing to touch the ring buffer, sequencing,
    /// or bus directly.
    /// What: errors with `session_not_found` if `id` is unknown; `args_preview`
    /// is truncated via `crate::events::preview` before emission so a large
    /// argument payload can't blow the ring buffer / wire size.
    /// Test: `registry_tests::record_tool_started_publishes_event`.
    pub fn record_tool_started(
        &self,
        id: &str,
        tool: &str,
        call_id: &str,
        args: &str,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::ToolStarted {
                session_id: id.to_string(),
                tool: tool.to_string(),
                call_id: call_id.to_string(),
                args_preview: crate::events::preview(args, 500),
            },
        );
        Ok(())
    }

    /// Record a tool invocation finishing (#2055 emission plumbing for
    /// #2056's agent loop). See [`Self::record_tool_started`].
    /// Test: `registry_tests::record_tool_finished_publishes_event`.
    pub fn record_tool_finished(
        &self,
        id: &str,
        tool: &str,
        call_id: &str,
        success: bool,
        result: &str,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::ToolFinished {
                session_id: id.to_string(),
                tool: tool.to_string(),
                call_id: call_id.to_string(),
                success,
                result_preview: crate::events::preview(result, 500),
            },
        );
        Ok(())
    }

    /// Record a tool invocation raising an exceptional error (#2055 emission
    /// plumbing for #2056's agent loop). See [`Self::record_tool_started`].
    /// Test: `registry_tests::record_tool_error_publishes_event`.
    pub fn record_tool_error(
        &self,
        id: &str,
        tool: &str,
        call_id: &str,
        error: &str,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::ToolError {
                session_id: id.to_string(),
                tool: tool.to_string(),
                call_id: call_id.to_string(),
                error: error.to_string(),
            },
        );
        Ok(())
    }

    /// Record a session-scoped diagnostic log line (#2055 emission plumbing).
    /// Test: `registry_tests::record_log_publishes_event`.
    pub fn record_log(&self, id: &str, level: &str, message: &str) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::Log {
                session_id: id.to_string(),
                level: level.to_string(),
                message: message.to_string(),
            },
        );
        Ok(())
    }

    /// Record a coarse progress update (#2055 emission plumbing).
    /// Test: `registry_tests::record_progress_publishes_event`.
    pub fn record_progress(
        &self,
        id: &str,
        message: &str,
        percent: Option<f32>,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::Progress {
                session_id: id.to_string(),
                message: message.to_string(),
                percent,
            },
        );
        Ok(())
    }

    /// Record a generic freeform session message (#2055 emission plumbing).
    /// Test: `registry_tests::record_message_publishes_event`.
    pub fn record_message(&self, id: &str, text: &str) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::Message {
                session_id: id.to_string(),
                text: text.to_string(),
            },
        );
        Ok(())
    }

    /// Return `Ok(())` if `id` exists, `Err(session_not_found)` otherwise.
    ///
    /// Why: every `record_*` plumbing method needs the same existence guard
    /// before recording; centralising it keeps each one a two-line body.
    fn ensure_exists(&self, id: &str) -> Result<(), RpcError> {
        if self.lock().contains_key(id) {
            Ok(())
        } else {
            Err(RpcError::session_not_found(id))
        }
    }

    /// Assign the next per-session `seq`, wrap `event` in a
    /// [`SessionEventEnvelope`], push it onto `id`'s ring buffer (evicting
    /// the oldest entry if full), and publish the envelope on the
    /// process-global bus.
    ///
    /// Why: every lifecycle/tool/log/progress/message event goes through
    /// this ONE function so `seq` assignment, the ring buffer, and the live
    /// bus can never drift out of sync with each other — the correctness
    /// property `attach_replay_then_live_seq_is_contiguous` verifies.
    /// What: a no-op (no envelope built, nothing published) if `id` is
    /// unknown — callers that need a hard error check existence first
    /// (`send`, `cancel`, every `record_*` plumbing method all do).
    fn record(&self, id: &str, event: Event) {
        let envelope = {
            let mut sessions = self.lock();
            let Some(entry) = sessions.get_mut(id) else {
                return;
            };
            entry.seq += 1;
            let envelope = SessionEventEnvelope::new(id.to_string(), entry.seq, Utc::now(), event);
            if entry.ring.len() >= self.ring_capacity {
                entry.ring.pop_front();
            }
            entry.ring.push_back(envelope.clone());
            envelope
        };
        crate::events::publish(envelope);
    }

    /// Update a session's status in place, then record+publish
    /// `Event::SessionStatusChanged`.
    fn transition(&self, id: &str, status: SessionStatus) {
        {
            let mut sessions = self.lock();
            if let Some(entry) = sessions.get_mut(id) {
                entry.session.status = status;
            }
        }
        self.record(
            id,
            Event::SessionStatusChanged {
                session_id: id.to_string(),
                status: status.as_str().to_string(),
            },
        );
    }

    /// Lock the session map, recovering from poisoning.
    ///
    /// Why: a panic inside another handler while holding this lock should
    /// not permanently wedge the whole registry for every other session —
    /// recovering the poisoned guard is safer than propagating a panic into
    /// unrelated requests.
    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, SessionEntry>> {
        self.sessions
            .lock()
            .unwrap_or_else(|poison| poison.into_inner())
    }
}

/// Spawn the background task that forwards one session's live event
/// envelopes to a connection until cancelled or the connection is gone.
///
/// Why: split out of `attach` for readability; also gives `registry_tests`
/// a single well-named spawn site to reason about. Subscribing to the bus
/// SYNCHRONOUSLY here — before `tokio::spawn` schedules the forwarder body
/// — matters: if the subscription happened inside the spawned `async`
/// block instead, a caller that calls `send()` immediately after `attach()`
/// returns could publish its event before the spawned task ever gets polled
/// and subscribes, and `broadcast::Receiver`s only see events published
/// after `subscribe()` was called — the event would be silently missed.
/// What: subscribes to `crate::events::subscribe()` immediately, then
/// spawns a task that forwards envelopes whose `session_id` matches
/// `session_id` as a JSON-RPC notification via `notify` (`params` is the
/// envelope itself — `seq`/`at`/`kind`/`event` all present), skips
/// envelopes for other sessions and lag gaps, and exits on `cancel_rx`
/// firing (either a real detach or the sender being dropped) or
/// `notify.send` failing (connection gone).
/// Test: `registry_tests::attach_forwards_live_events_until_detach`.
fn spawn_forwarder(session_id: String, notify: NotifySender, cancel_rx: oneshot::Receiver<()>) {
    use tokio::sync::broadcast::error::RecvError;

    // Subscribe before spawning (see the Why above) so no event published
    // by the caller right after `attach()` returns can be missed.
    let mut events = crate::events::subscribe();

    tokio::spawn(async move {
        tokio::pin!(cancel_rx);
        loop {
            tokio::select! {
                biased;
                _ = &mut cancel_rx => break,
                received = events.recv() => match received {
                    Ok(envelope) if envelope.session_id == session_id => {
                        let notification = json!({
                            "jsonrpc": "2.0",
                            "method": "session.event",
                            "params": envelope,
                        });
                        if notify.send(notification).is_err() {
                            break;
                        }
                    }
                    Ok(_) => continue,
                    Err(RecvError::Lagged(_)) => continue,
                    Err(RecvError::Closed) => break,
                },
            }
        }
    });
}

#[cfg(test)]
#[path = "registry_tests.rs"]
mod registry_tests;