trusty-common 0.49.0

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
//! Structured (JSON) catch-up digest — the `session_context_catchup` MCP
//! tool's core payload.
//!
//! Why: split out of `catchup/mod.rs` to keep it under the 500-SLOC
//! production cap once this JSON sibling of [`super::generate_catchup_context`]
//! pushed the parent file over the line. Kept in the `catchup` module (not a
//! standalone crate concept) since it reuses the exact same three sources —
//! paused sessions, git commits, palace drawers — `generate_catchup_context`
//! does.
//! What: [`PausedSessionJson`] / [`RecentMemoryJson`] / [`CatchupJson`] are the
//! structured output types; [`generate_catchup_json`] is the entry point,
//! mirroring [`super::generate_catchup_context`]'s watermark-filtering logic
//! but building typed values instead of markdown.
//! Test: `generate_catchup_json_returns_structured_fields`,
//! `generate_catchup_json_respects_watermark`,
//! `paused_session_to_json_maps_trusty_mpm_fields`,
//! `paused_session_to_json_maps_claude_mpm_fields`.

use chrono::{DateTime, Utc};
use serde::Serialize;

use super::CatchupOptions;
use super::derive_palace_id_for;
use super::git::{CommitSummary, git_commits_since};
use super::palace::fetch_recent_palace_drawers;
use super::session_finder::{
    FilteredSessions, PausedSession, filter_sessions_since, find_paused_sessions,
};
use super::state::load_catchup_state_in;

/// A single paused session, restructured as JSON fields instead of markdown
/// prose (MCP `session_context_catchup` tool).
///
/// Why: an MCP tool caller needs typed fields it can branch on (e.g. "does this
/// session have a tmux window to realign to?") rather than parsing a rendered
/// digest back apart. This is the structured sibling of
/// `session_finder::render_session` (private) — same source fields, JSON
/// shape instead of markdown.
/// What: `format` is `"trusty-mpm"` or `"claude-mpm"`; the remaining fields are
/// populated from whichever [`PausedSession`] variant produced them. A
/// `claude-mpm` (legacy) session has no on-disk single-file `source_file` (its
/// loader discards the path — see [`mpm_session::load_all_claude_mpm_sessions`](crate::catchup::mpm_session::load_all_claude_mpm_sessions)),
/// so that field is `None` for that variant; its `in_progress`/`next_steps`
/// are best-effort folds of `todos`+`task_list` / `open_questions`.
///
/// Every field here is populated unconditionally. Withholding the fields a
/// non-owning caller may not see is a separate, explicit step —
/// [`resolve::redact_sessions_not_owned_by`](crate::catchup::resolve::redact_sessions_not_owned_by),
/// which the MCP tool applies and the CLI digest does not (#5386).
/// Test: `paused_session_to_json_maps_trusty_mpm_fields`,
/// `paused_session_to_json_maps_claude_mpm_fields`.
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct PausedSessionJson {
    /// `"trusty-mpm"` (native markdown) or `"claude-mpm"` (legacy JSON).
    pub format: String,
    /// UTC pause timestamp, when parseable.
    pub paused_at: Option<DateTime<Utc>>,
    /// The session's summary / resume-instructions text.
    pub summary: String,
    /// In-progress work, when recorded.
    pub in_progress: Option<String>,
    /// Recommended next steps, when recorded.
    pub next_steps: Option<String>,
    /// Git branch/commit/status context captured at pause time.
    pub git_context: Option<String>,
    /// `session_name:window_index:window_id`, trusty-mpm sessions only.
    ///
    /// Withheld (`None`) from a caller that does not own this session, since a
    /// caller that learns another session's window can hand it straight back as
    /// its own and resolve that session's snapshot (#5386).
    pub tmux_window: Option<String>,
    /// Absolute path to the on-disk snapshot file, trusty-mpm sessions only.
    ///
    /// Withheld (`None`) from a caller that does not own this session.
    pub source_file: Option<String>,
    /// Whether the receiving caller owns this session.
    ///
    /// Why: without it, a withheld field is indistinguishable from an absent
    /// one — a redacted `tmux_window` reads exactly like a snapshot paused
    /// outside tmux, and a caller cannot tell "you may not see this" from
    /// "there is nothing to see" (#5386).
    /// What: `true` when the session is attributable to the caller — by
    /// `session_id` in `sessions-log.jsonl`, or by the caller sitting in the
    /// tmux window that paused it. Always `true` as constructed here; only
    /// [`resolve::redact_sessions_not_owned_by`](crate::catchup::resolve::redact_sessions_not_owned_by)
    /// sets it `false`, and it clears the withheld fields in the same pass.
    /// Test: `redaction_withholds_handles_and_restorable_state`,
    /// `owner_sees_every_field`.
    pub owned: bool,
}

/// Map a [`PausedSession`] to its structured JSON form.
///
/// Why: isolates the per-variant field mapping so [`generate_catchup_json`]
/// stays a straight orchestration function.
/// What: see [`PausedSessionJson`] field docs for the exact mapping.
/// Test: `paused_session_to_json_maps_trusty_mpm_fields`,
/// `paused_session_to_json_maps_claude_mpm_fields`.
fn paused_session_to_json(session: &PausedSession) -> PausedSessionJson {
    match session {
        PausedSession::TrustyMpm {
            path,
            paused_at,
            summary,
            git_context,
            in_progress,
            next_steps,
            tmux_window,
        } => PausedSessionJson {
            format: "trusty-mpm".to_string(),
            paused_at: *paused_at,
            summary: summary.clone(),
            in_progress: in_progress.clone(),
            next_steps: next_steps.clone(),
            git_context: git_context.clone(),
            tmux_window: tmux_window.clone(),
            source_file: Some(path.display().to_string()),
            owned: true,
        },
        PausedSession::ClaudeMpm { session: s } => {
            let in_progress = {
                let mut items: Vec<String> = Vec::new();
                if let Some(t) = &s.todos {
                    items.extend(t.iter().cloned());
                }
                if let Some(t) = &s.task_list {
                    items.extend(t.iter().cloned());
                }
                if items.is_empty() {
                    None
                } else {
                    Some(items.join("\n"))
                }
            };
            PausedSessionJson {
                format: "claude-mpm".to_string(),
                paused_at: s
                    .paused_at
                    .as_deref()
                    .and_then(|ts| ts.parse::<DateTime<Utc>>().ok()),
                summary: s.resume_instructions.clone().unwrap_or_default(),
                in_progress,
                next_steps: s
                    .open_questions
                    .as_ref()
                    .filter(|q| !q.is_empty())
                    .map(|q| q.join("\n")),
                git_context: s.git_context.clone(),
                tmux_window: None,
                source_file: None,
                owned: true,
            }
        }
    }
}

/// A recent memory-palace drawer, trimmed to the fields the catch-up JSON
/// output surfaces.
///
/// Why: [`palace::DrawerSummary`](crate::catchup::palace::DrawerSummary) also carries `created_at`, which the digest
/// doesn't need once drawers are already newest-first; keeping the tool output
/// to `title`/`tags` matches the documented `session_context_catchup` schema.
/// What: a two-field projection of [`palace::DrawerSummary`](crate::catchup::palace::DrawerSummary).
/// Test: covered by `generate_catchup_json_returns_structured_fields`.
#[derive(Debug, Clone, Serialize)]
pub struct RecentMemoryJson {
    /// The drawer's stored content / title.
    pub title: String,
    /// Tags associated with the drawer.
    pub tags: Vec<String>,
}

/// Structured (non-markdown) catch-up digest — the `session_context_catchup`
/// MCP tool's core payload.
///
/// Why: the MCP tool contract is JSON, not prose; this is the JSON sibling of
/// [`super::generate_catchup_context`]'s markdown string, built from the exact
/// same three sources so both surfaces stay in lockstep.
/// What: `sessions` (structured paused-session records), `recent_commits`
/// (unchanged [`git::CommitSummary`](crate::catchup::git::CommitSummary) values), and `recent_memory` (title+tags
/// drawer projections). Callers (the MCP daemon backend) layer
/// `resolved_snapshot` and `watermark_advanced` on top, since those depend on
/// an explicit `session_id` this function does not take.
/// Test: `generate_catchup_json_returns_structured_fields`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CatchupJson {
    /// Paused sessions since the watermark (or all, when `full`), newest-first.
    pub sessions: Vec<PausedSessionJson>,
    /// Recent git commits since the watermark (or the last `git_limit`).
    pub recent_commits: Vec<CommitSummary>,
    /// Recent memory-palace drawers since the watermark.
    pub recent_memory: Vec<RecentMemoryJson>,
    /// How many paused sessions were withheld because they could not be dated.
    ///
    /// Why: an empty `sessions` array means "nothing paused since your last
    /// catch-up" — unless this is non-zero, in which case sessions DID exist
    /// and were withheld. The watermark advances either way, so without this
    /// count a withheld session is invisible to the caller forever and there is
    /// nothing to tell them to re-run with `full` (#5072).
    /// What: [`session_finder::FilteredSessions::dropped_undatable`](crate::catchup::session_finder::FilteredSessions::dropped_undatable); always 0
    /// when `full` is set, since a full catch-up applies no watermark.
    /// Test: `generate_catchup_json_reports_undatable_drop_count`.
    pub undatable_sessions_dropped: usize,
}

impl CatchupJson {
    /// Fold another project's digest into this one.
    ///
    /// Why: `session_context_catchup --all-projects` merges a digest per
    /// project, and every field has to merge — including
    /// `undatable_sessions_dropped`, which SUMS rather than concatenating. The
    /// caller previously hand-rolled three `extend` calls plus a `+=`, where
    /// forgetting the `+=` would drop the receipt for every project after the
    /// first and leave the suite green (#5072).
    /// What: appends `sessions` / `recent_commits` / `recent_memory` and adds
    /// `undatable_sessions_dropped`, saturating.
    /// Test: `absorb_sums_dropped_counts_and_concatenates_the_rest`.
    pub fn absorb(&mut self, other: CatchupJson) {
        self.sessions.extend(other.sessions);
        self.recent_commits.extend(other.recent_commits);
        self.recent_memory.extend(other.recent_memory);
        self.undatable_sessions_dropped = self
            .undatable_sessions_dropped
            .saturating_add(other.undatable_sessions_dropped);
    }
}

/// Project a filter outcome into the two [`CatchupJson`] fields it feeds.
///
/// Why: the withheld count has to reach the caller, and nothing else pins that
/// it does — an undatable session is unreachable through the filesystem once
/// both [`PausedSession`] arms fall back to mtime, so no end-to-end test can
/// drive the count non-zero. Replacing the count with a literal `0` here would
/// otherwise leave the whole suite green while the receipt silently stopped
/// working, which is the same fail-open class #5072 is about. This is the seam
/// that makes the wire testable.
/// What: maps `kept` through [`paused_session_to_json`] and returns
/// `dropped_undatable` alongside it, unchanged.
/// Test: `sessions_payload_propagates_dropped_count`.
fn sessions_payload(filtered: FilteredSessions) -> (Vec<PausedSessionJson>, usize) {
    (
        filtered.kept.iter().map(paused_session_to_json).collect(),
        filtered.dropped_undatable,
    )
}

/// Generate a structured (JSON) catch-up digest for the given options.
///
/// Why: the `session_context_catchup` MCP tool needs typed fields, not a
/// rendered markdown block — this is [`super::generate_catchup_context`]
/// restructured to build [`CatchupJson`] instead of a `String`, reusing the
/// exact same three sources (paused sessions, git commits, palace drawers) and
/// the exact same watermark-filtering logic.
/// What: mirrors [`super::generate_catchup_context`]'s watermark load /
/// per-source collection, but maps each source into structured values instead
/// of markdown lines. Never persists anything — like `generate_catchup_context`,
/// advancing the watermark is exclusively [`super::run_catchup`]'s job, and
/// this function has no equivalent wrapper: callers that need JSON MUST NOT
/// advance the watermark (the `session_context_catchup` MCP tool is a
/// manual-peek operation, same contract as `tm session catchup`).
/// Test: `generate_catchup_json_returns_structured_fields`,
/// `generate_catchup_json_respects_watermark`.
pub async fn generate_catchup_json(opts: &CatchupOptions) -> CatchupJson {
    generate_catchup_json_in(opts, None).await
}

/// [`generate_catchup_json`] with the framework state root supplied by the
/// caller.
///
/// Why (#4323): the watermark READ resolves `~/.trusty-mpm/projects/` from the
/// home directory, so a test against a temp project still consulted the
/// operator's real state dir. Same seam as
/// [`super::generate_catchup_context_in`]; this function still persists nothing.
/// What: identical to [`generate_catchup_json`] except that `state_root`
/// replaces the `.trusty-mpm` framework root; `None` is the production
/// home-relative default.
/// Test: `generate_catchup_json_respects_watermark`.
pub async fn generate_catchup_json_in(
    opts: &CatchupOptions,
    state_root: Option<&std::path::Path>,
) -> CatchupJson {
    // #5811: an unresolvable palace used to become the shared literal
    // `"unknown-project"`, so this read a watermark another project had written
    // and reported "nothing new" for activity that was genuinely new. With no
    // palace: apply NO watermark (nothing is suppressed) and skip the drawer
    // source, which has no palace to query.
    let palace_id = match derive_palace_id_for(&opts.project_dir) {
        Ok(id) => Some(id),
        Err(e) => {
            eprintln!(
                "catchup: warning: palace resolution failed ({e}); \
                 reporting full history and omitting recent memory"
            );
            None
        }
    };

    let watermark: Option<DateTime<Utc>> = match (opts.full, palace_id.as_deref()) {
        (false, Some(id)) => load_catchup_state_in(id, state_root).map(|s| s.last_catchup_at),
        _ => None,
    };

    // #5072: shared fail-closed predicate — see `filter_sessions_since`.
    let (sessions, undatable_sessions_dropped) = match find_paused_sessions(&opts.project_dir) {
        Ok(found) => sessions_payload(filter_sessions_since(found, watermark)),
        Err(e) => {
            eprintln!("catchup: warning: could not scan paused sessions: {e}");
            (Vec::new(), 0)
        }
    };

    let recent_commits = if opts.include_git {
        git_commits_since(&opts.project_dir, watermark)
            .into_iter()
            .take(opts.git_limit)
            .collect()
    } else {
        Vec::new()
    };

    let recent_memory = if let (true, Some(palace_id)) = (opts.include_palace, palace_id.as_deref())
    {
        match fetch_recent_palace_drawers(
            &opts.memory_socket,
            palace_id,
            opts.drawer_limit,
            watermark,
        )
        .await
        {
            Some(drawers) => drawers
                .iter()
                .map(|d| RecentMemoryJson {
                    title: d.title.clone(),
                    tags: d.tags.clone(),
                })
                .collect(),
            None => Vec::new(),
        }
    } else {
        Vec::new()
    };

    CatchupJson {
        sessions,
        recent_commits,
        recent_memory,
        undatable_sessions_dropped,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::catchup::CatchupOptions;
    use crate::catchup::state::{CatchupState, save_catchup_state_in};
    use std::fs;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn init_git_repo(tmp: &TempDir) {
        let p = tmp.path();
        std::process::Command::new("git")
            .arg("-C")
            .arg(p)
            .args(["init"])
            .output()
            .unwrap();
        std::process::Command::new("git")
            .arg("-C")
            .arg(p)
            .args(["config", "user.email", "t@t.com"])
            .output()
            .unwrap();
        std::process::Command::new("git")
            .arg("-C")
            .arg(p)
            .args(["config", "user.name", "T"])
            .output()
            .unwrap();
        fs::write(p.join("README.md"), b"test").unwrap();
        std::process::Command::new("git")
            .arg("-C")
            .arg(p)
            .args(["add", "."])
            .output()
            .unwrap();
        std::process::Command::new("git")
            .arg("-C")
            .arg(p)
            .args(["commit", "-m", "init"])
            .output()
            .unwrap();
    }

    #[tokio::test]
    async fn generate_catchup_json_returns_structured_fields() {
        let tmp = TempDir::new().unwrap();
        init_git_repo(&tmp);

        // Also seed a native trusty-mpm paused session so the sessions array
        // is exercised, not just commits.
        let sessions_dir = tmp.path().join(".trusty-mpm").join("sessions");
        fs::create_dir_all(&sessions_dir).unwrap();
        fs::write(
            sessions_dir.join("session-20260627-100000.md"),
            "## Summary\nDid the thing.\n\n## Next Steps\nShip it.\n",
        )
        .unwrap();

        let opts = CatchupOptions {
            project_dir: tmp.path().to_path_buf(),
            memory_socket: std::path::PathBuf::from("/nonexistent/catchup-test.sock"),
            include_git: true,
            include_palace: true,
            git_limit: 50,
            drawer_limit: 15,
            full: true,
        };

        let json = generate_catchup_json(&opts).await;

        assert_eq!(json.sessions.len(), 1, "fixture snapshot should be found");
        assert_eq!(json.sessions[0].format, "trusty-mpm");
        assert_eq!(json.sessions[0].summary, "Did the thing.");
        assert_eq!(json.sessions[0].next_steps.as_deref(), Some("Ship it."));
        assert!(
            json.sessions[0].source_file.is_some(),
            "trusty-mpm sessions carry a source_file"
        );

        assert!(
            json.recent_commits.iter().any(|c| c.msg == "init"),
            "commit summary should be structured, not prose: {:?}",
            json.recent_commits
        );

        // Palace daemon unreachable (fail-open) → empty, not an error.
        assert!(json.recent_memory.is_empty());
    }

    #[tokio::test]
    async fn generate_catchup_json_respects_watermark() {
        let tmp = TempDir::new().unwrap();
        init_git_repo(&tmp);

        // A far-future watermark should exclude every commit/session.
        let palace_id = derive_palace_id_for(tmp.path()).expect("a temp dir resolves to a palace");
        let state = CatchupState {
            last_catchup_at: "2099-01-01T00:00:00Z".parse().unwrap(),
            palace_id: palace_id.clone(),
            last_git_sha: None,
        };
        // #4323: `state` is the framework state root, NOT the project dir — this
        // test used to write a `2099-01-01` watermark into the operator's real
        // `~/.trusty-mpm/projects/t-tmpXXXX/`, where it outlived the tempdir.
        let state_root = tmp.path().join("state");
        save_catchup_state_in(&palace_id, &state, Some(&state_root)).unwrap();

        let opts = CatchupOptions {
            project_dir: tmp.path().to_path_buf(),
            memory_socket: std::path::PathBuf::from("/nonexistent/catchup-test.sock"),
            include_git: true,
            include_palace: false,
            git_limit: 50,
            drawer_limit: 15,
            // full=false → the watermark above must apply.
            full: false,
        };

        let json = generate_catchup_json_in(&opts, Some(&state_root)).await;
        assert!(
            json.recent_commits.is_empty(),
            "future watermark should exclude all commits: {:?}",
            json.recent_commits
        );
    }

    /// Why: issue #5072 — the live `session_context_catchup` call on
    /// `bobmatnyc/trusty-tools` returned exactly one session, the hand-written
    /// `session-20260730-bounce.md`, with every field empty or null, while
    /// dozens of well-formed newer snapshots sat in the same directory. The
    /// watermark filter admitted the bounce file precisely BECAUSE its
    /// timestamp could not be derived (`is_none_or` treats an unknown key as
    /// "newer than the watermark"), and dropped every snapshot whose timestamp
    /// could be. The result was an inverted digest: only the record that could
    /// not be dated survived.
    /// What: reproduces that directory shape — one well-formed dated snapshot
    /// plus one undated hand-written file — behind a far-future watermark. No
    /// session is newer than 2099, so the digest must be empty. Before the fix
    /// it contained the undated file.
    /// Test: itself.
    #[tokio::test]
    async fn generate_catchup_json_excludes_undatable_session_behind_watermark() {
        let tmp = TempDir::new().unwrap();
        init_git_repo(&tmp);

        let sessions_dir = tmp.path().join(".trusty-mpm").join("sessions");
        fs::create_dir_all(&sessions_dir).unwrap();
        fs::write(
            sessions_dir.join("session-20260806-211305.md"),
            "## Summary\nReal work.\n\n## Next Steps\nShip it.\n",
        )
        .unwrap();
        // Hand-written snapshot: the filename carries no parseable
        // `YYYYMMDD-HHMMSS`, and the body uses none of the parsed section
        // headers — so every field would render empty if it leaked through.
        fs::write(
            sessions_dir.join("session-20260730-bounce.md"),
            "# Session snapshot — pre-daemon-bounce\n\n## What landed this leg\n- stuff\n",
        )
        .unwrap();

        let palace_id = derive_palace_id_for(tmp.path()).expect("a temp dir resolves to a palace");
        // #4323: watermark under the tempdir, not the operator's real state dir.
        let state_root = tmp.path().join("state");
        save_catchup_state_in(
            &palace_id,
            &CatchupState {
                last_catchup_at: "2099-01-01T00:00:00Z".parse().unwrap(),
                palace_id: palace_id.clone(),
                last_git_sha: None,
            },
            Some(&state_root),
        )
        .unwrap();

        let opts = CatchupOptions {
            project_dir: tmp.path().to_path_buf(),
            memory_socket: std::path::PathBuf::from("/nonexistent/catchup-test.sock"),
            include_git: false,
            include_palace: false,
            git_limit: 50,
            drawer_limit: 15,
            full: false,
        };

        let json = generate_catchup_json_in(&opts, Some(&state_root)).await;
        assert!(
            json.sessions.is_empty(),
            "a snapshot with no derivable timestamp must not survive a watermark \
             that every datable snapshot fails: {:?}",
            json.sessions
                .iter()
                .map(|s| s.source_file.clone())
                .collect::<Vec<_>>()
        );
        // Both files are datable — the hand-written one by its mtime — so
        // nothing was withheld; they simply predate 2099.
        assert_eq!(json.undatable_sessions_dropped, 0);
    }

    /// Why: the withheld count is a receipt, not diagnostics — the watermark
    /// advances past a withheld session and never returns for it, so a caller
    /// seeing an empty `sessions` array must be able to tell "nothing paused"
    /// from "sessions existed and could not be dated" (#5072).
    /// What: seeds a claude-mpm session whose recorded `paused_at` is
    /// unparseable AND whose mtime is unreadable — achieved by deleting the
    /// file after load is impossible, so this asserts the plumbing instead: a
    /// datable-but-too-old corpus reports 0, proving the count tracks undatable
    /// exclusions specifically rather than every filtered-out session.
    /// Test: itself, with `filter_sessions_since_reports_dropped_count` pinning
    /// the counting rule directly.
    #[tokio::test]
    async fn generate_catchup_json_reports_undatable_drop_count() {
        let tmp = TempDir::new().unwrap();
        init_git_repo(&tmp);
        let sessions_dir = tmp.path().join(".trusty-mpm").join("sessions");
        fs::create_dir_all(&sessions_dir).unwrap();
        fs::write(
            sessions_dir.join("session-20260101-000000.md"),
            "## Summary\nOld.\n",
        )
        .unwrap();

        let palace_id = derive_palace_id_for(tmp.path()).expect("a temp dir resolves to a palace");
        // #4323: watermark under the tempdir, not the operator's real state dir.
        let state_root = tmp.path().join("state");
        save_catchup_state_in(
            &palace_id,
            &CatchupState {
                last_catchup_at: "2099-01-01T00:00:00Z".parse().unwrap(),
                palace_id: palace_id.clone(),
                last_git_sha: None,
            },
            Some(&state_root),
        )
        .unwrap();

        let opts = CatchupOptions {
            project_dir: tmp.path().to_path_buf(),
            memory_socket: std::path::PathBuf::from("/nonexistent/catchup-test.sock"),
            include_git: false,
            include_palace: false,
            git_limit: 50,
            drawer_limit: 15,
            full: false,
        };

        let json = generate_catchup_json_in(&opts, Some(&state_root)).await;
        assert!(json.sessions.is_empty());
        assert_eq!(
            json.undatable_sessions_dropped, 0,
            "a merely-too-old session is filtered, not withheld — the count \
             must not conflate the two"
        );
    }

    fn claude_session(resume: &str) -> PausedSession {
        use crate::catchup::mpm_session::ClaudeMpmSession;
        PausedSession::ClaudeMpm {
            session: ClaudeMpmSession {
                resume_instructions: Some(resume.to_string()),
                ..Default::default()
            },
        }
    }

    /// Why: #5072 — the withheld count must reach `CatchupJson`, and no
    /// end-to-end test can prove it does: an undatable session is unreachable
    /// through the filesystem once both `PausedSession` arms fall back to
    /// mtime, so replacing the count with a literal `0` at the call site left
    /// the whole suite green. This pins the wire itself.
    /// What: a non-zero `dropped_undatable` survives the projection unchanged,
    /// alongside the mapped sessions.
    /// Test: itself.
    #[test]
    fn sessions_payload_propagates_dropped_count() {
        let (sessions, dropped) = sessions_payload(FilteredSessions {
            kept: vec![claude_session("a"), claude_session("b")],
            dropped_undatable: 7,
        });
        assert_eq!(sessions.len(), 2);
        assert_eq!(
            dropped, 7,
            "the withheld count must not be reset in transit"
        );
    }

    /// Why: `--all-projects` merges one digest per project, and the withheld
    /// count SUMS where every other field concatenates. Hand-rolling that
    /// merge is how a receipt gets dropped for every project after the first
    /// (#5072).
    /// What: two digests fold into one with concatenated arrays and an added
    /// count.
    /// Test: itself.
    #[test]
    fn absorb_sums_dropped_counts_and_concatenates_the_rest() {
        let mut a = CatchupJson {
            sessions: vec![paused_session_to_json(&claude_session("a"))],
            recent_memory: vec![RecentMemoryJson {
                title: "t1".into(),
                tags: vec![],
            }],
            undatable_sessions_dropped: 2,
            ..Default::default()
        };
        a.absorb(CatchupJson {
            sessions: vec![paused_session_to_json(&claude_session("b"))],
            recent_memory: vec![RecentMemoryJson {
                title: "t2".into(),
                tags: vec![],
            }],
            undatable_sessions_dropped: 3,
            ..Default::default()
        });
        assert_eq!(a.sessions.len(), 2);
        assert_eq!(a.recent_memory.len(), 2);
        assert_eq!(
            a.undatable_sessions_dropped, 5,
            "withheld counts sum across projects, never overwrite"
        );
    }

    #[test]
    fn paused_session_to_json_maps_trusty_mpm_fields() {
        let session = PausedSession::TrustyMpm {
            path: PathBuf::from("/tmp/session-1.md"),
            paused_at: None,
            summary: "Summary text".to_string(),
            git_context: Some("branch: main".to_string()),
            in_progress: Some("doing X".to_string()),
            next_steps: Some("do Y".to_string()),
            tmux_window: Some("main:2:@7".to_string()),
        };
        let json = paused_session_to_json(&session);
        assert_eq!(json.format, "trusty-mpm");
        assert_eq!(json.summary, "Summary text");
        assert_eq!(json.git_context.as_deref(), Some("branch: main"));
        assert_eq!(json.tmux_window.as_deref(), Some("main:2:@7"));
        assert_eq!(json.source_file.as_deref(), Some("/tmp/session-1.md"));
    }

    #[test]
    fn paused_session_to_json_maps_claude_mpm_fields() {
        use crate::catchup::mpm_session::ClaudeMpmSession;
        let session = ClaudeMpmSession {
            resume_instructions: Some("Resume from step 3".to_string()),
            todos: Some(vec!["todo 1".to_string()]),
            open_questions: Some(vec!["q1".to_string()]),
            git_context: Some("branch: main".to_string()),
            ..Default::default()
        };
        let json = paused_session_to_json(&PausedSession::ClaudeMpm { session });
        assert_eq!(json.format, "claude-mpm");
        assert_eq!(json.summary, "Resume from step 3");
        assert_eq!(json.in_progress.as_deref(), Some("todo 1"));
        assert_eq!(json.next_steps.as_deref(), Some("q1"));
        assert!(json.tmux_window.is_none());
        assert!(json.source_file.is_none());
    }
}