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
//! Native trusty-mpm session-pause snapshot writer (MCP `session_context_pause`
//! tool).
//!
//! Why: `/tm-session-pause` used to shell out to write the snapshot markdown
//! file and append the pause log line by hand. No reusable Rust writer existed
//! — [`crate::catchup::session_finder`] only ever *reads* the format. This
//! module is the write side, built to emit EXACTLY the section shape
//! [`crate::catchup::session_finder::find_paused_sessions`] already parses, so
//! a session this module writes round-trips through the existing reader
//! unchanged.
//! What: [`write_pause_snapshot`] writes `session-YYYYMMDD-HHMMSS.md` under
//! `<project_dir>/.trusty-mpm/sessions/<session-id>/` and appends the matching
//! `pause` line to `sessions-log.jsonl` via
//! [`crate::catchup::session_log::append_entry`], recording the snapshot path
//! relative to the store root so the log stays the attribution index for both
//! the per-session and the pre-#5272 flat layout.
//! Test: `write_pause_snapshot_round_trips_through_reader`,
//! `write_pause_snapshot_omits_empty_sections`,
//! `write_pause_snapshot_appends_log_entry`,
//! `write_pause_snapshot_writes_under_session_dir`,
//! `write_pause_snapshot_falls_back_to_root_for_unsafe_id`.

use std::path::{Path, PathBuf};

use chrono::Utc;

use crate::catchup::git::capture_git_status;
use crate::catchup::session_log::{self, SessionLogEntry};

/// Input fields for a single pause snapshot.
///
/// Why: groups everything the `session_context_pause` MCP tool receives from
/// its caller so [`write_pause_snapshot`] takes one argument instead of a long
/// parameter list.
/// What: `session_id` keys the append-only log entry; `summary` is required
/// prose; `completed`/`in_progress`/`next_steps` are optional bullet lists;
/// `tmux_window` is the `session_name:window_index:window_id` string (omitted
/// entirely from the file when `None`, matching the reader's back-compat
/// contract for snapshots that predate the field).
/// Test: exercised by every `write_pause_snapshot_*` test.
#[derive(Debug, Clone)]
pub struct PauseSnapshotInput<'a> {
    /// Stable id for the originating session (keys the append-only log).
    pub session_id: &'a str,
    /// The `## Summary` section body (required, non-empty by caller contract).
    pub summary: &'a str,
    /// The `## Completed` section's bullet items.
    pub completed: &'a [String],
    /// The `## In Progress` section's bullet items.
    pub in_progress: &'a [String],
    /// The `## Next Steps` section's bullet items.
    pub next_steps: &'a [String],
    /// The `## Tmux Window` section body, when captured inside tmux.
    pub tmux_window: Option<&'a str>,
}

/// Result of a successful pause-snapshot write.
///
/// Why: the MCP tool returns both the path and the timestamp it used, so the
/// caller (and the PM transcript) can reference the exact snapshot filename.
/// What: `snapshot_path` is the absolute path written; `timestamp` is the UTC
/// instant used to derive the filename and the log entry.
/// Test: exercised by every `write_pause_snapshot_*` test.
#[derive(Debug, Clone)]
pub struct PauseSnapshotOutcome {
    /// Absolute path of the written `session-*.md` file.
    pub snapshot_path: PathBuf,
    /// The UTC instant the filename/log entry were derived from.
    pub timestamp: chrono::DateTime<Utc>,
}

/// Render one `## <Header>` section from a bullet list, or `None` when empty.
///
/// Why: [`session_finder::extract_section`](crate::catchup::session_finder)
/// treats an empty section as absent; mirroring that here keeps back-compat
/// snapshots (predating a given section) indistinguishable from "nothing to
/// report this pause".
/// What: joins `items` as `- <item>` lines under `## <header>`; returns `None`
/// for an empty slice so the caller can skip the section entirely.
/// Test: `write_pause_snapshot_omits_empty_sections`.
fn render_bullet_section(header: &str, items: &[String]) -> Option<String> {
    if items.is_empty() {
        return None;
    }
    let mut out = format!("## {header}\n");
    for item in items {
        out.push_str("- ");
        out.push_str(item);
        out.push('\n');
    }
    Some(out)
}

/// Write a pause snapshot for `project_dir` and append its log entry.
///
/// Why: the single write-side entry point for `session_context_pause` — keeps
/// the markdown shape and the log append atomic-ish (write-then-append, same
/// order the bash skill used) and in one auditable place.
/// What: creates `<project_dir>/.trusty-mpm/sessions/<session-id>/` if needed,
/// captures git status via [`capture_git_status`] for the `## Git Context`
/// section, writes `session-<UTC timestamp>.md` with `## Summary` (always
/// present, even if `input.summary` is empty — the caller contract requires a
/// non-empty summary) followed by `## Completed` / `## In Progress` /
/// `## Next Steps` / `## Git Context` / `## Tmux Window`, each omitted when it
/// would be empty, then appends a `pause` [`SessionLogEntry`] whose `snapshot`
/// is the new file's path RELATIVE to the store root. Returns the resolved
/// absolute path and timestamp.
///
/// #5272: a session id that cannot be a directory name (see
/// [`session_log::session_dir_name`]) writes flat at the store root instead,
/// with a warning — mangling it into a safe name would let two ids share one
/// directory, which is the crosstalk this change exists to remove. Attribution
/// is unaffected either way: the log line, not the location, is what
/// [`session_log::resolve_session_snapshot`] reads.
/// Test: `write_pause_snapshot_round_trips_through_reader`,
/// `write_pause_snapshot_omits_empty_sections`,
/// `write_pause_snapshot_appends_log_entry`,
/// `write_pause_snapshot_writes_under_session_dir`,
/// `write_pause_snapshot_falls_back_to_root_for_unsafe_id`.
pub fn write_pause_snapshot(
    project_dir: &Path,
    input: &PauseSnapshotInput<'_>,
) -> anyhow::Result<PauseSnapshotOutcome> {
    let sessions_dir = project_dir.join(".trusty-mpm").join("sessions");

    let now = Utc::now();
    let basename = format!("session-{}.md", now.format("%Y%m%d-%H%M%S"));
    // #5272: snapshots live under `sessions/<session-id>/` so the store is
    // partitioned by owner, not just indexed by it.
    let relative = match session_log::session_dir_name(input.session_id) {
        Some(dir) => format!("{dir}/{basename}"),
        None => {
            tracing::warn!(
                session_id = input.session_id,
                "session id is not usable as a directory name; writing the pause \
                 snapshot flat at the store root (attribution still comes from \
                 sessions-log.jsonl)"
            );
            basename
        }
    };
    let snapshot_path = sessions_dir.join(&relative);
    if let Some(parent) = snapshot_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let git = capture_git_status(project_dir);
    let mut git_context = String::new();
    if let Some(branch) = &git.branch {
        git_context.push_str(&format!("Branch: {branch}\n"));
    }
    if let Some(commit) = &git.last_commit {
        git_context.push_str(&format!("Last commit: {commit}\n"));
    }
    if let Some(summary) = &git.uncommitted_summary {
        git_context.push_str(&format!("Uncommitted changes: {summary}\n"));
    }

    let mut md = format!(
        "# Session Pause - {}\n\n## Summary\n{}\n\n",
        now.to_rfc3339(),
        input.summary
    );
    if let Some(section) = render_bullet_section("Completed", input.completed) {
        md.push_str(&section);
        md.push('\n');
    }
    if let Some(section) = render_bullet_section("In Progress", input.in_progress) {
        md.push_str(&section);
        md.push('\n');
    }
    if let Some(section) = render_bullet_section("Next Steps", input.next_steps) {
        md.push_str(&section);
        md.push('\n');
    }
    if !git_context.is_empty() {
        md.push_str("## Git Context\n");
        md.push_str(&git_context);
        md.push('\n');
    }
    if let Some(win) = input.tmux_window.filter(|w| !w.is_empty()) {
        md.push_str("## Tmux Window\n");
        md.push_str(win);
        md.push('\n');
    }

    std::fs::write(&snapshot_path, md)?;

    session_log::append_entry(
        &sessions_dir,
        &SessionLogEntry {
            session_id: input.session_id.to_string(),
            event: session_log::EVENT_PAUSE.to_string(),
            snapshot: relative,
            timestamp: now.to_rfc3339(),
        },
    )?;

    Ok(PauseSnapshotOutcome {
        snapshot_path,
        timestamp: now,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::catchup::session_finder::{PausedSession, find_paused_sessions};
    use tempfile::TempDir;

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

    #[test]
    fn write_pause_snapshot_round_trips_through_reader() {
        let tmp = TempDir::new().unwrap();
        init_git_repo(tmp.path());

        let input = PauseSnapshotInput {
            session_id: "s1",
            summary: "Did the thing.",
            completed: &["step 1".to_string()],
            in_progress: &["step 2".to_string()],
            next_steps: &["step 3".to_string()],
            tmux_window: Some("main:2:@7"),
        };
        let outcome = write_pause_snapshot(tmp.path(), &input).unwrap();
        assert!(outcome.snapshot_path.exists());

        let sessions = find_paused_sessions(tmp.path()).unwrap();
        assert_eq!(sessions.len(), 1);
        match &sessions[0] {
            PausedSession::TrustyMpm {
                summary,
                in_progress,
                next_steps,
                tmux_window,
                git_context,
                ..
            } => {
                assert_eq!(summary, "Did the thing.");
                assert_eq!(in_progress.as_deref(), Some("- step 2"));
                assert_eq!(next_steps.as_deref(), Some("- step 3"));
                assert_eq!(tmux_window.as_deref(), Some("main:2:@7"));
                assert!(
                    git_context
                        .as_deref()
                        .is_some_and(|g| g.contains("Branch:")),
                    "git context should be present: {git_context:?}"
                );
            }
            other => panic!("expected TrustyMpm variant, got {other:?}"),
        }
    }

    #[test]
    fn write_pause_snapshot_omits_empty_sections() {
        let tmp = TempDir::new().unwrap();
        init_git_repo(tmp.path());

        let input = PauseSnapshotInput {
            session_id: "s1",
            summary: "Just a summary.",
            completed: &[],
            in_progress: &[],
            next_steps: &[],
            tmux_window: None,
        };
        let outcome = write_pause_snapshot(tmp.path(), &input).unwrap();
        let content = std::fs::read_to_string(&outcome.snapshot_path).unwrap();
        assert!(!content.contains("## Completed"));
        assert!(!content.contains("## In Progress"));
        assert!(!content.contains("## Next Steps"));
        assert!(!content.contains("## Tmux Window"));
        // Git Context still renders because it's a real repo.
        assert!(content.contains("## Git Context"));
    }

    #[test]
    fn write_pause_snapshot_appends_log_entry() {
        let tmp = TempDir::new().unwrap();
        init_git_repo(tmp.path());

        let input = PauseSnapshotInput {
            session_id: "s-log",
            summary: "Summary.",
            completed: &[],
            in_progress: &[],
            next_steps: &[],
            tmux_window: None,
        };
        let outcome = write_pause_snapshot(tmp.path(), &input).unwrap();
        let sessions_dir = tmp.path().join(".trusty-mpm").join("sessions");
        let entries = session_log::read_log(&sessions_dir);
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].session_id, "s-log");
        assert_eq!(entries[0].event, session_log::EVENT_PAUSE);
        // #5272: the log records the path relative to the store root, not a
        // bare basename, so one containment-checked join serves both layouts.
        assert_eq!(
            sessions_dir.join(&entries[0].snapshot),
            outcome.snapshot_path
        );
    }

    /// Why: #5272 — the store is partitioned by owner, and the log entry must
    /// record the path relative to the store root so resolution stays a single
    /// containment-checked join across both layouts.
    /// What: the file lands under `sessions/<session-id>/`, the log entry names
    /// `<session-id>/<basename>`, and the pair round-trips back through
    /// `resolve_session_snapshot` to the same path.
    /// Test: itself.
    #[test]
    fn write_pause_snapshot_writes_under_session_dir() {
        let tmp = TempDir::new().unwrap();
        let id = "7bd5c27a-475b-41df-9e9f-a6f630801717";
        let input = PauseSnapshotInput {
            session_id: id,
            summary: "Summary.",
            completed: &[],
            in_progress: &[],
            next_steps: &[],
            tmux_window: None,
        };
        let outcome = write_pause_snapshot(tmp.path(), &input).unwrap();
        let sessions_dir = tmp.path().join(".trusty-mpm").join("sessions");
        assert_eq!(
            outcome.snapshot_path.parent().unwrap(),
            sessions_dir.join(id),
            "snapshot belongs to its session's directory"
        );

        let entries = session_log::read_log(&sessions_dir);
        assert_eq!(entries.len(), 1);
        let basename = outcome.snapshot_path.file_name().unwrap().to_str().unwrap();
        assert_eq!(entries[0].snapshot, format!("{id}/{basename}"));

        assert_eq!(
            session_log::resolve_session_snapshot(&sessions_dir, id, "md").as_ref(),
            Some(&outcome.snapshot_path),
        );
        assert_eq!(
            session_log::resolve_session_snapshot(&sessions_dir, "someone-else", "md"),
            None,
        );
    }

    /// Why: #5272 — an id that cannot be a directory name is never mangled into
    /// one, because two ids collapsing onto one directory is the crosstalk this
    /// change removes. The pause still succeeds and stays attributable.
    /// What: a `/`-bearing id writes flat at the store root and resolves for
    /// itself through the log, and for no one else.
    /// Test: itself.
    #[test]
    fn write_pause_snapshot_falls_back_to_root_for_unsafe_id() {
        let tmp = TempDir::new().unwrap();
        let id = "weird/id";
        let input = PauseSnapshotInput {
            session_id: id,
            summary: "Summary.",
            completed: &[],
            in_progress: &[],
            next_steps: &[],
            tmux_window: None,
        };
        let outcome = write_pause_snapshot(tmp.path(), &input).unwrap();
        let sessions_dir = tmp.path().join(".trusty-mpm").join("sessions");
        assert_eq!(outcome.snapshot_path.parent().unwrap(), sessions_dir);
        assert_eq!(
            session_log::resolve_session_snapshot(&sessions_dir, id, "md").as_ref(),
            Some(&outcome.snapshot_path),
        );
        assert_eq!(
            session_log::resolve_session_snapshot(&sessions_dir, "other", "md"),
            None,
        );
    }

    #[test]
    fn write_pause_snapshot_nonrepo_still_writes() {
        // No git init at all — capture_git_status fails-open to all-None, and
        // the snapshot must still write (no Git Context section).
        let tmp = TempDir::new().unwrap();
        let input = PauseSnapshotInput {
            session_id: "s1",
            summary: "Summary.",
            completed: &[],
            in_progress: &[],
            next_steps: &[],
            tmux_window: None,
        };
        let outcome = write_pause_snapshot(tmp.path(), &input).unwrap();
        let content = std::fs::read_to_string(&outcome.snapshot_path).unwrap();
        assert!(!content.contains("## Git Context"));
    }
}