trusty-code 0.7.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
//! `SessionRegistry`'s #2055 tool/log/progress/message event-recording
//! plumbing. Split out of `registry.rs` (#2344) purely to keep that
//! production file under the crate's 500-SLOC cap as the #2344
//! persistent-transcript methods grew it past the limit — this is a child
//! module of `registry` (declared via `#[path = ...] mod events;`), so it
//! shares full access to `SessionRegistry`'s private `lock`/`record` helpers
//! exactly as if these methods were still defined in that file.
//!
//! Why: gives the agent loop a stable, already-wired call for each #2055
//! event kind without it needing to touch the ring buffer, sequencing, or
//! bus directly.
//! What: `record_tool_started`/`record_tool_finished`/`record_tool_error`/
//! `record_log`/`record_progress`/`record_message`, plus the shared
//! `ensure_exists` existence guard they all call before recording. The
//! permission-prompt half lives in the `registry_permission_events` sibling
//! (#8100), split out to keep this file under the cap.
//! Test: `registry_tests::record_tool_started_publishes_event`,
//! `registry_tests::record_tool_finished_publishes_event`,
//! `registry_tests::record_tool_error_publishes_event`,
//! `registry_tests::record_log_publishes_event`,
//! `registry_tests::record_progress_publishes_event`,
//! `registry_tests::record_message_publishes_event`.

use serde::Serialize;

use super::*;
use crate::tools::telemetry::{RecallTelemetry, SearchTelemetry};

use crate::events::{ContextBudgetSnapshot, IndexReadinessSnapshot};

/// `Event::IndexReadiness.state` when the semantic lane is queryable — an
/// empty search result IS evidence of absence.
const READINESS_STATE_READY: &str = "ready";
/// `Event::IndexReadiness.state` while a lane is still building — an empty
/// search result is NOT evidence of absence.
const READINESS_STATE_WARMING: &str = "warming";
/// `Event::IndexReadiness.state` when no index could be probed at all (no
/// daemon / no derivable id) — likewise not evidence of absence.
const READINESS_STATE_UNAVAILABLE: &str = "unavailable";

/// `session.get_readiness`'s response payload (DOC-39 §5.6 Slice D).
///
/// Why: a session's readiness is a single cached value, not a collection —
/// `session.get_goals`'s "empty array means nothing yet" convention doesn't
/// fit here, and a bare `Option` serialising to `null` would be exactly the
/// kind of untyped "nothing yet" signal the design explicitly rules out (a
/// consumer can't tell "never probed" from "probed, and every field happens
/// to be absent" without a discriminant). This is a thin, tagged wrapper
/// around [`IndexReadinessSnapshot`] — the SAME struct
/// `SessionRegistry::record_index_readiness` caches and `Event::IndexReadiness`
/// derives from — so the query and event surfaces can never independently
/// drift on field names.
/// What: `#[serde(tag = "status")]` (internally tagged, matching `Event`'s own
/// `tag = "type"` convention) so the wire shape is
/// `{"status":"probed","state":...,"index_id":...,...}` for a session with a
/// recorded snapshot, or `{"status":"never_probed"}` for one with none.
/// Test: `registry_tests::record_index_readiness_caches_snapshot_for_late_query`,
/// `protocol_readiness::tests::get_readiness_never_probed_session_returns_never_probed`.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ReadinessQuery {
    /// A probe has landed for this session; wraps the last-recorded snapshot.
    Probed(IndexReadinessSnapshot),
    /// No `record_index_readiness` call has ever landed for this session.
    NeverProbed,
}

/// `session.get_context_budget`'s response payload (issue #3015).
///
/// Why: a session's working-context budget is a single cached value, not a
/// collection — the same "typed nothing-yet, never a bare `null`" rationale
/// as [`ReadinessQuery`] applies verbatim: a consumer must be able to tell
/// "no turn has completed yet" from "a turn completed and every field
/// happens to be zero" without a discriminant.
/// What: `#[serde(tag = "status", rename_all = "snake_case")]` so the wire
/// shape is `{"status":"recorded", ...snapshot fields}` for a session with a
/// cached measurement, or `{"status":"never_recorded"}` for one with none.
/// Test: `registry_tests::record_context_budget_caches_snapshot_for_late_query`,
/// `protocol_budget::tests::get_context_budget_never_recorded_session_returns_never_recorded`.
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ContextBudgetQuery {
    /// A turn has completed for this session; wraps the last-recorded
    /// snapshot.
    Recorded(ContextBudgetSnapshot),
    /// No `record_context_budget` call has ever landed for this session.
    NeverRecorded,
}

impl SessionRegistry {
    /// Record a project's trusty-search index readiness (issue #2784's
    /// UI Phase-1 follow-up).
    ///
    /// Why: `trusty_common::search_readiness` already probes this per lane and
    /// then only logged it to stderr, where no API consumer could reach it.
    /// The UI is a thin client over this daemon — anything it renders must
    /// arrive as an event — so a warming index was structurally unrenderable.
    /// Critically, this is what lets a consumer tell a COLD index from a READY
    /// one with genuinely zero hits: both return an empty search, but they mean
    /// opposite things, and conflating them is exactly what makes a model
    /// conclude "nothing there" and hand-explore to the wrong target.
    /// What: takes the probe's `Option<IndexReadiness>` — `None` (fail-open: no
    /// daemon, undrivable id, HTTP error) maps to `state: "unavailable"` with
    /// every lane `false` and no index fields, which is itself the useful
    /// signal rather than something to swallow. `Some` maps to `"ready"` when
    /// `semantic_search_ready()` and `"warming"` otherwise, carrying the
    /// per-lane flags through verbatim. Errors with `session_not_found` if `id`
    /// is unknown.
    /// (DOC-39 §5.6 Slice D) Also caches the resulting [`IndexReadinessSnapshot`]
    /// on the session (last-writer-wins), so a client that attaches AFTER this
    /// one-time event fires can still retrieve it via
    /// [`Self::get_readiness`]/`session.get_readiness`.
    /// Test: `registry_tests::record_index_readiness_warming_publishes_event`,
    /// `registry_tests::record_index_readiness_ready_publishes_event`,
    /// `registry_tests::record_index_readiness_unavailable_publishes_event`,
    /// `registry_tests::record_index_readiness_caches_snapshot_for_late_query`.
    pub fn record_index_readiness(
        &self,
        id: &str,
        readiness: Option<&trusty_common::search_readiness::IndexReadiness>,
        summary: &str,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        let snapshot = match readiness {
            Some(r) => IndexReadinessSnapshot {
                state: if r.semantic_search_ready() {
                    READINESS_STATE_READY
                } else {
                    READINESS_STATE_WARMING
                }
                .to_string(),
                index_id: Some(r.index_id.clone()),
                lifecycle_status: Some(r.lifecycle_status.clone()),
                chunk_count: Some(r.chunk_count),
                lexical_ready: r.lexical_ready,
                semantic_ready: r.semantic_ready,
                graph_ready: r.graph_ready,
                summary: summary.to_string(),
            },
            None => IndexReadinessSnapshot {
                state: READINESS_STATE_UNAVAILABLE.to_string(),
                index_id: None,
                lifecycle_status: None,
                chunk_count: None,
                lexical_ready: false,
                semantic_ready: false,
                graph_ready: false,
                summary: summary.to_string(),
            },
        };
        {
            let mut sessions = self.lock();
            if let Some(entry) = sessions.get_mut(id) {
                entry.readiness = Some(snapshot.clone());
            }
        }
        self.record(
            id,
            Event::IndexReadiness {
                session_id: id.to_string(),
                state: snapshot.state,
                index_id: snapshot.index_id,
                lifecycle_status: snapshot.lifecycle_status,
                chunk_count: snapshot.chunk_count,
                lexical_ready: snapshot.lexical_ready,
                semantic_ready: snapshot.semantic_ready,
                graph_ready: snapshot.graph_ready,
                summary: snapshot.summary,
            },
        );
        Ok(())
    }

    /// `session.get_readiness`: return the last-recorded index-readiness
    /// probe for a session, for clients that attach after the one-time
    /// `Event::IndexReadiness` already fired (DOC-39 §5.6 Slice D).
    ///
    /// Why: [`Self::record_index_readiness`] emits its event exactly once, at
    /// task start (see `run_task::ensure_project_indexed_in_background`'s
    /// call site in `task::executor`). A UI that connects even a moment later
    /// has no query surface to ask "what is the readiness state right now" —
    /// only a stream it may have missed. This is that query surface.
    /// What: `Err(session_not_found)` if `id` is unknown. Otherwise
    /// [`ReadinessQuery::Probed`] wrapping the cached [`IndexReadinessSnapshot`]
    /// if a probe has ever landed for this session, or
    /// [`ReadinessQuery::NeverProbed`] — a distinct, clearly-typed state,
    /// never a bare `null` — if no `record_index_readiness` call has happened
    /// yet (e.g. a projectless session, or one queried before its background
    /// indexing probe completes).
    /// Test: `registry_tests::record_index_readiness_caches_snapshot_for_late_query`,
    /// `protocol_readiness::tests::get_readiness_never_probed_session_returns_never_probed`,
    /// `registry_tests::get_readiness_unknown_session_errors`.
    pub fn get_readiness(&self, id: &str) -> Result<ReadinessQuery, RpcError> {
        self.ensure_exists(id)?;
        Ok(self
            .lock()
            .get(id)
            .and_then(|e| e.readiness.clone())
            .map(ReadinessQuery::Probed)
            .unwrap_or(ReadinessQuery::NeverProbed))
    }

    /// Record one turn's working-context budget measurement (epic #2343;
    /// caches the snapshot for late queries as of issue #3015).
    ///
    /// Why: the Infinite Sessions guarantee (working context >= 60%, session
    /// overhead <= 40%) is enforced every single turn and was visible to
    /// nothing — `CadenceOutcome` was computed and dropped. This is the
    /// emission plumbing that lets `task::SessionToolEventSink` forward the
    /// measurement to a `session.attach`ed UI's budget indicator. (issue
    /// #3015) Also caches the resulting [`ContextBudgetSnapshot`] on the
    /// session (last-writer-wins), mirroring [`Self::record_index_readiness`],
    /// so a client that attaches or reconnects AFTER a turn's event already
    /// fired can still retrieve it via [`Self::get_context_budget`]/
    /// `session.get_context_budget` — the API PR #3014's GUI status bar
    /// polls instead of leaving "budget: unavailable" permanently.
    /// What: maps the caller's `agent_loop::ContextBudgetSnapshot` field-for-
    /// field onto a cached [`ContextBudgetSnapshot`] first, then derives
    /// `Event::ContextBudget` from that cached value so the two can never
    /// disagree; every value is already computed by the caller, so this adds
    /// no arithmetic of its own. Errors with `session_not_found` if `id` is
    /// unknown.
    /// (#3868) `lifetime_compaction_alarm_count` is stored as a `0`
    /// placeholder here — this method runs on the EVERY-TURN write path
    /// (`AgentLoop::maybe_cadence_compress` forwards to it once per cadence
    /// tick), so a `File::open` + line-scan here would pay the durable-log
    /// read cost once per turn per session. [`Self::get_context_budget`]
    /// (the actual RPC query path — called far less often, once per client
    /// poll) overwrites this field with a fresh read before returning, so no
    /// caller ever observes the placeholder.
    /// (#3948) The session's working-context floor takes the opposite route:
    /// it is folded in HERE, under the same lock that stores the snapshot,
    /// because a `min` over one `u8` costs nothing per turn while the query
    /// path's alternative — rescanning the multi-session
    /// `compression.jsonl` — grows with the machine's whole compression
    /// history.
    /// Test: `registry_tests::record_context_budget_publishes_event`,
    /// `registry_tests::record_context_budget_caches_snapshot_for_late_query`,
    /// `registry_tests::context_floor_tracks_every_measurement`,
    /// `registry_tests::context_floor_is_session_scoped`.
    pub fn record_context_budget(
        &self,
        id: &str,
        measurement: &crate::agent_loop::ContextBudgetSnapshot,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        let mut snapshot = ContextBudgetSnapshot {
            context_window_tokens: measurement.context_window,
            overhead_tokens: measurement.overhead_tokens,
            overhead_cap_tokens: measurement.overhead_cap_tokens,
            working_context_pct: measurement.working_context_pct,
            overhead_pct: measurement.overhead_pct,
            within_budget: measurement.within_budget,
            compaction_fired: measurement.fired,
            compaction_rounds: measurement.rounds,
            // (#3868) Placeholder — see doc note above. Never observed: only
            // `get_context_budget` reads this field back out, and it always
            // overwrites it first.
            lifetime_compaction_alarm_count: 0,
            // (#3948) Overwritten from this entry's retained floor under the
            // registry lock below, before the snapshot is stored.
            working_context_pct_low_water_mark: None,
            working_context_pct_sample_count: 0,
            // (#3911) Same placeholder contract as
            // `lifetime_compaction_alarm_count` above.
            lifetime_cadence_floor_breach_count: 0,
        };
        {
            let mut sessions = self.lock();
            if let Some(entry) = sessions.get_mut(id) {
                entry.context_floor.record(measurement.working_context_pct);
                snapshot.working_context_pct_low_water_mark = entry.context_floor.low_water_mark;
                snapshot.working_context_pct_sample_count = entry.context_floor.sample_count;
                entry.context_budget = Some(snapshot);
            }
        }
        self.record(
            id,
            Event::ContextBudget {
                session_id: id.to_string(),
                context_window_tokens: snapshot.context_window_tokens,
                overhead_tokens: snapshot.overhead_tokens,
                overhead_cap_tokens: snapshot.overhead_cap_tokens,
                working_context_pct: snapshot.working_context_pct,
                overhead_pct: snapshot.overhead_pct,
                within_budget: snapshot.within_budget,
                compaction_fired: snapshot.compaction_fired,
                compaction_rounds: snapshot.compaction_rounds,
            },
        );
        Ok(())
    }

    /// `session.get_context_budget`: return the last-recorded working-context
    /// budget measurement for a session, for clients that attach after the
    /// per-turn `Event::ContextBudget` already fired (issue #3015).
    ///
    /// Why: [`Self::record_context_budget`] emits its event once per PM turn
    /// boundary — a client that attaches (or reconnects) between turns has no
    /// query surface to ask "what is the budget right now", only a stream it
    /// may have missed. This is that query surface, the exact counterpart to
    /// [`Self::get_readiness`].
    /// What: `Err(session_not_found)` if `id` is unknown. Otherwise
    /// [`ContextBudgetQuery::Recorded`] wrapping the cached
    /// [`ContextBudgetSnapshot`] if a turn has ever completed for this
    /// session, or [`ContextBudgetQuery::NeverRecorded`] — a distinct,
    /// clearly-typed state, never a bare `null` — if no
    /// `record_context_budget` call has happened yet (e.g. a session queried
    /// before its first PM turn completes, or a delegated sub-agent session,
    /// which never emits cadence budget events at all).
    /// (#3868) `lifetime_compaction_alarm_count` is read fresh from the
    /// durable, cross-session alarm log HERE — the query path, called once
    /// per client poll — rather than in [`Self::record_context_budget`] (the
    /// every-turn write path), so the `File::open` + line-scan cost is paid
    /// once per query, not once per turn per session. This is also why the
    /// count reflects fires from ANY session on this machine, not just this
    /// one: it is derived from a shared log, not a per-session cache.
    /// (#3948) `working_context_pct_low_water_mark`/
    /// `working_context_pct_sample_count` are read from the state
    /// [`Self::record_context_budget`] retains per session, NOT from
    /// `compression.jsonl`. This query used to call
    /// `telemetry::session_working_context_floor`, which reopens and reparses
    /// the machine-wide compression log on every poll; that function is
    /// unchanged and remains the offline-history reader, but no live query
    /// path calls it. The two answers are not identical, and the difference
    /// is deliberate: the live floor samples EVERY cadence tick, while the
    /// log only carries a percentage for turns where compaction work
    /// happened (`rounds > 0`) plus threshold-compaction fires, which
    /// `record_context_budget` never sees. So the live floor is over a
    /// per-turn superset of this session's cadence measurements, and
    /// `working_context_pct_sample_count` counts cadence measurements rather
    /// than durable rows.
    /// Test: `registry_tests::record_context_budget_caches_snapshot_for_late_query`,
    /// `protocol_budget::tests::get_context_budget_never_recorded_session_returns_never_recorded`,
    /// `registry_tests::get_context_budget_unknown_session_errors`,
    /// `protocol_budget::tests::get_context_budget_reflects_lifetime_compaction_alarm_count`,
    /// `protocol_budget::tests::get_context_budget_reflects_working_context_floor`,
    /// `registry_tests::context_budget_query_does_not_open_compression_log`,
    /// `registry_tests::context_floor_after_restart_is_absent_not_wrong`.
    pub fn get_context_budget(&self, id: &str) -> Result<ContextBudgetQuery, RpcError> {
        self.ensure_exists(id)?;
        let cached = self.lock().get(id).and_then(|entry| {
            entry.context_budget.map(|mut snapshot| {
                snapshot.working_context_pct_low_water_mark = entry.context_floor.low_water_mark;
                snapshot.working_context_pct_sample_count = entry.context_floor.sample_count;
                snapshot
            })
        });
        Ok(cached
            .map(|mut snapshot| {
                let data_dir = crate::agent_loop::telemetry::default_data_dir();
                snapshot.lifetime_compaction_alarm_count =
                    crate::agent_loop::telemetry::lifetime_compaction_alarm_count(&data_dir);
                snapshot.lifetime_cadence_floor_breach_count =
                    crate::agent_loop::telemetry::lifetime_cadence_floor_breach_count(&data_dir);
                ContextBudgetQuery::Recorded(snapshot)
            })
            .unwrap_or(ContextBudgetQuery::NeverRecorded))
    }

    /// 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. `agent`
    /// (UI Phase 1) is the dispatching agent's name — see
    /// [`crate::events::Event::ToolStarted`]. `agent_id` (DOC-39 AC-13) is
    /// that same agent's stable per-spawn id.
    /// Test: `registry_tests::record_tool_started_publishes_event`.
    pub fn record_tool_started(
        &self,
        id: &str,
        agent: &str,
        agent_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(),
                agent: agent.to_string(),
                agent_id: agent_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`.
    /// (DOC-39 AC-13) `agent_id` pushed this past clippy's
    /// `too_many_arguments` gate; every parameter is a plain, independent
    /// piece of the event and none pair naturally into a sub-struct, so the
    /// attribute is the pragmatic choice here (mirrors
    /// `serve::transport::run_loop`'s same allowance).
    #[allow(clippy::too_many_arguments)]
    pub fn record_tool_finished(
        &self,
        id: &str,
        agent: &str,
        agent_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(),
                agent: agent.to_string(),
                agent_id: agent_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,
        agent: &str,
        agent_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(),
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                tool: tool.to_string(),
                call_id: call_id.to_string(),
                error: error.to_string(),
            },
        );
        Ok(())
    }

    /// Record a `search_code` call's real lane + hit count + per-hit
    /// path/score + latency (UI Phase 1; `hits` added DOC-39 Slice B). See
    /// [`crate::events::Event::SearchPerformed`].
    ///
    /// Why: emitted ALONGSIDE the generic tool events so the UI can trace a
    /// change back to the searches that drove it without re-parsing prose.
    /// What: same existence guard + ring-buffer/sequencing path as every
    /// other `record_*`, so a structured event replays on `session.attach`
    /// exactly like the generic ones.
    /// Test: `registry_tests::record_search_performed_publishes_event`,
    /// `registry_search_audit::tests::get_search_audit_returns_records_after_recording`.
    pub fn record_search_performed(
        &self,
        id: &str,
        agent: &str,
        agent_id: &str,
        telemetry: &SearchTelemetry,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        // (issue #3072) Append to the retained audit trail BEFORE emitting
        // the SSE event, mirroring `record_context_budget`'s cache-then-emit
        // ordering — a client that queries `session.get_search_audit` right
        // after observing this event on the stream is guaranteed to see it.
        self.push_search_audit(
            id,
            crate::events::SearchAuditRecord::Search {
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                lane: telemetry.lane.clone(),
                query: telemetry.query.clone(),
                hit_count: telemetry.hit_count,
                latency_ms: telemetry.latency_ms,
                at: Utc::now(),
            },
        );
        self.record(
            id,
            Event::SearchPerformed {
                session_id: id.to_string(),
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                lane: telemetry.lane.clone(),
                query: telemetry.query.clone(),
                hit_count: telemetry.hit_count,
                hits: telemetry.hits.clone(),
                latency_ms: telemetry.latency_ms,
            },
        );
        Ok(())
    }

    /// Record a `recall_session` call's results and which ones entered
    /// context (UI Phase 1). See [`crate::events::Event::MemoryRecalled`].
    ///
    /// Why: the `injected` flag is the UI's differentiating surface —
    /// injected memories vs ones recalled and held back.
    /// What: as [`Self::record_search_performed`].
    /// Test: `registry_tests::record_memory_recalled_publishes_event`,
    /// `registry_search_audit::tests::get_search_audit_returns_records_after_recording`.
    pub fn record_memory_recalled(
        &self,
        id: &str,
        agent: &str,
        agent_id: &str,
        telemetry: &RecallTelemetry,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        // (issue #3072) Append to the retained audit trail BEFORE emitting
        // the SSE event — see `record_search_performed`'s matching comment.
        self.push_search_audit(
            id,
            crate::events::SearchAuditRecord::Recall {
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                query: telemetry.query.clone(),
                result_count: telemetry.results.len(),
                injected_count: telemetry.results.iter().filter(|r| r.injected).count(),
                at: Utc::now(),
            },
        );
        self.record(
            id,
            Event::MemoryRecalled {
                session_id: id.to_string(),
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                query: telemetry.query.clone(),
                results: telemetry.results.clone(),
            },
        );
        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(())
    }

    /// Record one assistant turn's text as an `AgentMessageDelta` (tcode
    /// streaming epic #3696, Gap A, Slice 1). See
    /// [`crate::events::Event::AgentMessageDelta`] for the `turn_id`
    /// uniqueness requirement and the `(agent_id, turn_id)` grouping contract.
    /// Test: `registry_tests::record_agent_message_delta_publishes_event`.
    pub fn record_agent_message_delta(
        &self,
        id: &str,
        agent: &str,
        agent_id: &str,
        turn_id: &str,
        delta: &str,
        done: bool,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::AgentMessageDelta {
                session_id: id.to_string(),
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                turn_id: turn_id.to_string(),
                delta: delta.to_string(),
                done,
            },
        );
        Ok(())
    }

    /// Record a delegated sub-agent's loop starting (#7940).
    ///
    /// Why: the opening bracket of a delegation block — see
    /// [`crate::events::Event::AgentSpawned`] for why a client cannot infer
    /// it from the attributed tool/message events alone.
    /// What: errors with `session_not_found` if `id` is unknown;
    /// `task_preview` is truncated via `crate::events::preview` so a long
    /// delegation brief can't blow the ring buffer / wire size.
    /// Test: `registry_tests::record_agent_spawned_publishes_event`.
    pub fn record_agent_spawned(
        &self,
        id: &str,
        agent: &str,
        agent_id: &str,
        task: &str,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::AgentSpawned {
                session_id: id.to_string(),
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                task_preview: crate::events::preview(task, 200),
            },
        );
        Ok(())
    }

    /// Record a delegated sub-agent's loop returning normally (#7940). See
    /// [`Self::record_agent_spawned`].
    /// Test: `registry_tests::record_agent_done_publishes_event`.
    pub fn record_agent_done(
        &self,
        id: &str,
        agent: &str,
        agent_id: &str,
        status: &str,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::AgentDone {
                session_id: id.to_string(),
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                status: status.to_string(),
            },
        );
        Ok(())
    }

    /// Record a delegated sub-agent's loop aborting (#7940). See
    /// [`Self::record_agent_spawned`].
    /// Test: `registry_tests::record_agent_failed_publishes_event`.
    pub fn record_agent_failed(
        &self,
        id: &str,
        agent: &str,
        agent_id: &str,
        error: &str,
    ) -> Result<(), RpcError> {
        self.ensure_exists(id)?;
        self.record(
            id,
            Event::AgentFailed {
                session_id: id.to_string(),
                agent: agent.to_string(),
                agent_id: agent_id.to_string(),
                error: crate::events::preview(error, 500),
            },
        );
        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.
    // #8100: `pub(super)` so the `registry_permission_events` sibling, split
    // out of this file for the SLOC cap, can still use the same guard.
    pub(super) fn ensure_exists(&self, id: &str) -> Result<(), RpcError> {
        if self.lock().contains_key(id) {
            Ok(())
        } else {
            Err(RpcError::session_not_found(id))
        }
    }
}