ccsm 0.16.1

Context-managed session orchestration for AI coding agents — track, resume, and manage work across sessions
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
/// Which AI coding agent ccsm targets.
///
/// Controls which binary is spawned, which home-level config directories
/// are used, and how session files are found/parsed.
///
/// Detection order:
///   1. `--consumer`/`-C` CLI flag (explicit)
///   2. `CCSM_CONSUMER` env var (`"claude"` or `"pi"`)
///   3. Auto-detect: prefer Pi if its config dir is more recent

use anyhow::Context;
use serde::Deserialize;
use std::path::{Path, PathBuf};

// ── Consumer enum ─────────────────────────────────────────────────

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Consumer {
    /// Claude Code — binary `claude`, config at `~/.claude/`.
    /// Sessions: `~/.claude/sessions/<pid>.json`, transcripts: `~/.claude/projects/<slug>/`.
    Claude,
    /// Pi — binary `pi`, config at `~/.pi/agent/`.
    /// Sessions: `~/.pi/agent/sessions/<slug>/<ts>_<uuid>.jsonl`.
    Pi,
    /// OpenCode — binary `opencode`, config at `~/.config/opencode/`.
    /// Sessions in SQLite at `~/.local/share/opencode/opencode.db`.
    /// No PID-based session files.
    OpenCode,
}

impl Consumer {
    /// Detect the target consumer.  See module docs for order.
    pub fn detect(home: &Path, explicit: Option<&str>) -> Self {
        if let Some(val) = explicit {
            return Self::parse(val).unwrap_or_else(|_| {
                eprintln!("warning: unknown consumer '{val}', falling back to auto-detect");
                Self::auto_detect(home)
            });
        }

        // Env var override
        if let Ok(val) = std::env::var("CCSM_CONSUMER") {
            return Self::parse(&val).unwrap_or_else(|_| {
                eprintln!("warning: CCSM_CONSUMER='{val}' unknown, falling back to auto-detect");
                Self::auto_detect(home)
            });
        }

        Self::auto_detect(home)
    }

    fn auto_detect(home: &Path) -> Self {
        let pi_dir = home.join(".pi").join("agent");
        let claude_dir = home.join(".claude");
        // OpenCode check: look for the SQLite DB
        let opencode_db = home.join(".local").join("share").join("opencode").join("opencode.db");

        let candidates: [(Self, &Path); 3] = [(Self::OpenCode, &opencode_db), (Self::Pi, &pi_dir), (Self::Claude, &claude_dir)];

        let mut found: Vec<(Self, std::time::SystemTime)> = candidates
            .iter()
            .filter(|(_, path)| path.exists())
            .map(|(consumer, path)| {
                let mtime = if path.is_dir() {
                    Self::recent_file(path)
                } else {
                    path.metadata().and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH)
                };
                (*consumer, mtime)
            })
            .collect();

        if found.is_empty() {
            // Fallback: check cwd for project-local config dirs
            if let Ok(cwd) = std::env::current_dir() {
                if cwd.join(".pi").is_dir() {
                    return Self::Pi;
                }
                if cwd.join(".claude").is_dir() {
                    return Self::Claude;
                }
                // Prefer OpenCode on fresh systems
                return Self::OpenCode;
            }
            return Self::OpenCode; // default fallback
        }

        // Return the one with most recent activity
        found.sort_by(|a, b| b.1.cmp(&a.1));
        found.into_iter().next().unwrap().0
    }

    /// Find the most recent modification time in a directory tree (2 levels deep).
    fn recent_file(dir: &Path) -> std::time::SystemTime {
        let mut latest = std::time::UNIX_EPOCH;
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                if let Ok(meta) = entry.metadata() {
                    if let Ok(mtime) = meta.modified() {
                        if mtime > latest {
                            latest = mtime;
                        }
                    }
                }
                // Check one level deeper for session dirs
                if entry.path().is_dir() {
                    if let Ok(sub) = std::fs::read_dir(entry.path()) {
                        for sub_entry in sub.flatten() {
                            if let Ok(meta) = sub_entry.metadata() {
                                if let Ok(mtime) = meta.modified() {
                                    if mtime > latest {
                                        latest = mtime;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        latest
    }

    fn parse(s: &str) -> anyhow::Result<Self> {
        match s.to_lowercase().as_str() {
            "claude" => Ok(Self::Claude),
            "pi" => Ok(Self::Pi),
            "opencode" | "open-code" | "oc" => Ok(Self::OpenCode),
            other => anyhow::bail!("unknown consumer '{other}'. Expected: claude, pi, opencode"),
        }
    }

    pub fn is_claude(&self) -> bool {
        matches!(self, Self::Claude)
    }

    pub fn is_pi(&self) -> bool {
        matches!(self, Self::Pi)
    }

    pub fn is_opencode(&self) -> bool {
        matches!(self, Self::OpenCode)
    }

    // ── Binary ────────────────────────────────────────────────────

    /// The CLI binary to spawn for `resume`.
    pub fn binary(self) -> &'static str {
        match self {
            Self::Claude => "claude",
            Self::Pi => "pi",
            Self::OpenCode => "opencode",
        }
    }

    /// The config subdirectory under `$HOME`.
    pub fn home_config_dir(self) -> &'static str {
        match self {
            Self::Claude => ".claude",
            Self::Pi => ".pi",
            Self::OpenCode => ".config/opencode",
        }
    }

    /// Data directory for session storage (e.g. SQLite DB).
    /// Only meaningful for OpenCode; Claude/Pi store sessions elsewhere.
    pub fn data_dir(self) -> &'static str {
        match self {
            Self::OpenCode => ".local/share/opencode",
            _ => "",
        }
    }

    // ── Project slug ────────────────────────────────────────────

    /// Derive the project slug used by this agent to namespace session data.
    /// Claude: all non-alphanumeric → `-`, raw, e.g. `-home-user-my-project-`
    /// Pi:     collapsed, stripped, wrapped in `--...--`, e.g. `--home-user-my-project--`
    pub fn project_slug(self, workspace: &Path) -> String {
        match self {
            Self::Claude => {
                workspace
                    .to_string_lossy()
                    .chars()
                    .map(|c| if c.is_alphanumeric() { c } else { '-' })
                    .collect()
            }
            Self::Pi => {
                let base = slugify_path(workspace);
                format!("--{}--", base)
            }
            Self::OpenCode => {
                // Deterministic path-based slug for ccsm matching
                workspace
                    .to_string_lossy()
                    .chars()
                    .map(|c| if c.is_alphanumeric() { c } else { '-' })
                    .collect()
            }
        }
    }

    // ── Session directories ──────────────────────────────────────

    /// Directory containing live session files (Claude: PID-based JSON, Pi: workspace dirs).
    pub fn sessions_dir(self, home: &Path) -> PathBuf {
        match self {
            Self::Claude => home.join(".claude").join("sessions"),
            Self::Pi => home.join(".pi").join("agent").join("sessions"),
            Self::OpenCode => home.join(".local").join("share").join("opencode"),
        }
    }

    /// Directory containing transcript/session data for a project slug.
    pub fn projects_dir(self, home: &Path, slug: &str) -> PathBuf {
        match self {
            Self::Claude => home.join(".claude").join("projects").join(slug),
            Self::Pi => home.join(".pi").join("agent").join("sessions").join(slug),
            Self::OpenCode => home.join(".local").join("share").join("opencode"),
        }
    }

    /// Like `projects_dir` but computes the correct slug from the workspace path.
    pub fn projects_dir_for(self, home: &Path, workspace: &Path) -> PathBuf {
        self.projects_dir(home, &self.project_slug(workspace))
    }

    /// Path to a live session file for a given PID (Claude only; Pi doesn't use PID files).
    pub fn live_session_file(self, home: &Path, pid: u32) -> Option<PathBuf> {
        match self {
            Self::Claude => {
                Some(home.join(self.home_config_dir()).join("sessions").join(format!("{pid}.json")))
            }
            Self::Pi | Self::OpenCode => None,
        }
    }

    /// For Claude: direct transcript path by session UUID.
    /// For Pi: search by UUID in the workspace slug directory.
    pub fn find_session_file(self, home: &Path, slug: &str, session_id: &str) -> Option<PathBuf> {
        match self {
            Self::Claude => {
                let path = self.projects_dir(home, slug).join(format!("{session_id}.jsonl"));
                if path.exists() { Some(path) } else { None }
            }
            Self::Pi => {
                let dir = self.projects_dir(home, slug);
                if !dir.is_dir() {
                    return None;
                }
                // Pi files: <timestamp>_<uuid>.jsonl — search for uuid substring
                if let Ok(entries) = std::fs::read_dir(&dir) {
                    for entry in entries.flatten() {
                        let path = entry.path();
                        if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                            if name.contains(session_id) && name.ends_with(".jsonl") {
                                return Some(path);
                            }
                        }
                    }
                }
                None
            }
            Self::OpenCode => {
                let db_path = opencode_db_path(home);
                if opencode_session_exists(&db_path, session_id) {
                    Some(db_path) // DB file exists — signals "found"
                } else {
                    None
                }
            }
        }
    }

    /// Like `find_session_file` but computes the correct slug from the workspace path.
    pub fn find_session_file_for(self, home: &Path, workspace: &Path, session_id: &str) -> Option<PathBuf> {
        self.find_session_file(home, &self.project_slug(workspace), session_id)
    }

    /// List all session/transcript files for a workspace slug, sorted by filename.
    pub fn list_session_files(self, home: &Path, slug: &str) -> Vec<PathBuf> {
        match self {
            Self::OpenCode => vec![], // No individual transcript files — all in DB
            _ => {
                let dir = self.projects_dir(home, slug);
                if !dir.is_dir() {
                    return vec![];
                }
                let mut files: Vec<PathBuf> = std::fs::read_dir(&dir)
                    .into_iter()
                    .flatten()
                    .filter_map(|e| {
                        let path = e.ok()?.path();
                        if path.extension().is_some_and(|ext| ext == "jsonl") {
                            Some(path)
                        } else {
                            None
                        }
                    })
                    .collect();
                files.sort();
                files
            }
        }
    }

    // ── System prompt format ─────────────────────────────────────

    /// System prompt wrapper tags.
    pub fn system_prompt_tags(self) -> (&'static str, &'static str) {
        ("<system-reminder>", "</system-reminder>")
    }

    /// Constraint line appended to injected scope.
    pub fn constraint_line(self) -> &'static str {
        "CONSTRAINT: Work within this scope. If you need to do something outside it, ask first."
    }
}

impl std::fmt::Display for Consumer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Claude => write!(f, "claude"),
            Self::Pi => write!(f, "pi"),
            Self::OpenCode => write!(f, "opencode"),
        }
    }
}

// ── Pi Session file reader ─────────────────────────────────────────

/// Minimal representation of a Pi session entry.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum PiSessionEntry {
    Message {
        #[serde(rename = "type")]
        entry_type: String,
        id: Option<String>,
        timestamp: Option<String>,
        message: Option<PiMessage>,
    },
    Other(serde_json::Value),
}

#[derive(Debug, Deserialize)]
pub struct PiMessage {
    pub role: Option<String>,
    #[serde(default)]
    pub content: Option<Vec<PiContentBlock>>,
}

#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub enum PiContentBlock {
    Text { text: String },
    Other(serde_json::Value),
}

/// Metadata extracted from a Pi session file.
#[derive(Debug, Clone, Default)]
pub struct PiSessionMeta {
    pub session_id: String,
    pub name: String,
    pub started_at: u64,
    pub updated_at: Option<u64>,
}

/// Read a Pi session file and extract metadata.
/// Pi session files are JSONL — we read the first few lines to find context.
pub fn read_pi_session_meta(path: &Path) -> anyhow::Result<PiSessionMeta> {
    use std::io::BufRead;

    let file = std::fs::File::open(path)
        .with_context(|| format!("opening Pi session file: {}", path.display()))?;
    let reader = std::io::BufReader::new(file);

    let mut meta = PiSessionMeta::default();

    // Extract UUID from filename: <timestamp>_<uuid>.jsonl
    if let Some(name) = path.file_stem().and_then(|n| n.to_str()) {
        if let Some(uuid_part) = name.split('_').nth(1) {
            meta.session_id = uuid_part.to_string();
        }
    }

    // Read lines to find user messages that might reveal the session name
    for line in reader.lines().flatten().take(200) {
        if let Ok(entry) = serde_json::from_str::<PiSessionEntry>(&line) {
            if let PiSessionEntry::Message {
                message: Some(msg), ..
            } = entry
            {
                if msg.role.as_deref() == Some("user") {
                    if let Some(blocks) = &msg.content {
                        for block in blocks {
                            if let PiContentBlock::Text { text } = block {
                                if meta.name.is_empty() {
                                    if let Some(n) = extract_session_name(text) {
                                        meta.name = n;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(meta)
}

/// Collapse consecutive dashes and strip leading/trailing ones,
/// matching Pi's slugify logic in .pi/extensions/ccsm/index.ts
///   `cwd.replace(/[^a-zA-Z0-9]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "")`
fn slugify_path(path: &Path) -> String {
    // Step 1: replace non-alphanumeric with '-'
    let s: String = path
        .to_string_lossy()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect();
    // Step 2: collapse consecutive dashes
    let mut collapsed = String::with_capacity(s.len());
    let mut prev_was_dash = false;
    for ch in s.chars() {
        if ch == '-' {
            if prev_was_dash {
                continue;
            }
            prev_was_dash = true;
        } else {
            prev_was_dash = false;
        }
        collapsed.push(ch);
    }
    // Step 3: strip leading/trailing dashes
    collapsed.trim_matches('-').to_string()
}

/// Crude extraction of session name from a user prompt.
fn extract_session_name(text: &str) -> Option<String> {
    let triggers = ["work on ", "implement ", "fix ", "add ", "refactor ", "build "];
    let lower = text.to_lowercase();
    for trigger in &triggers {
        if let Some(pos) = lower.find(trigger) {
            let after = &text[pos + trigger.len()..];
            let name = after
                .split(|c: char| c == '.' || c == '!' || c == '?' || c == '\n')
                .next()
                .unwrap_or(after)
                .trim()
                .chars()
                .take(60)
                .collect::<String>();
            if !name.is_empty() {
                return Some(name.to_lowercase().replace(' ', "-"));
            }
        }
    }
    None
}

// ── OpenCode DB helpers ─────────────────────────────────────────────

/// Path to opencode's SQLite session database.
pub fn opencode_db_path(home: &Path) -> PathBuf {
    home.join(".local").join("share").join("opencode").join("opencode.db")
}

/// Check if a session exists in opencode's database.
pub fn opencode_session_exists(db_path: &Path, session_id: &str) -> bool {
    use rusqlite::Connection;
    let conn = match Connection::open(db_path) {
        Ok(c) => c,
        Err(_) => return false,
    };
    conn.query_row(
        "SELECT 1 FROM session WHERE id = ?1",
        [session_id],
        |_| Ok(()),
    )
    .is_ok()
}

/// List all session IDs in opencode's database.
pub fn opencode_list_sessions(db_path: &Path) -> Vec<String> {
    use rusqlite::Connection;
    let conn = match Connection::open(db_path) {
        Ok(c) => c,
        Err(_) => return vec![],
    };
    let mut stmt = match conn.prepare("SELECT id FROM session ORDER BY time_created DESC") {
        Ok(s) => s,
        Err(_) => return vec![],
    };
    stmt.query_map([], |row| row.get::<_, String>(0))
        .into_iter()
        .flatten()
        .filter_map(|r| r.ok())
        .collect()
}

/// Harvest a newly created opencode session ID by polling the DB.
/// Returns the first session with `time_created > before` and matching `directory`.
/// Polls up to ~5s (50 attempts × 100ms).
pub fn opencode_harvest_session(db_path: &Path, directory: &str, before_ts: i64) -> Option<String> {
    use rusqlite::Connection;
    for _ in 0..50 {
        let conn = Connection::open(db_path).ok()?;
        let mut stmt = conn
            .prepare("SELECT id FROM session WHERE directory = ?1 AND time_created > ?2 ORDER BY time_created DESC LIMIT 1")
            .ok()?;
        let result: Option<String> = stmt
            .query_map([directory, &before_ts.to_string()], |row| row.get(0))
            .ok()?
            .filter_map(|r| r.ok())
            .next();
        if result.is_some() {
            return result;
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    None
}

/// Update the title of an opencode session in the DB.
pub fn opencode_update_title(db_path: &Path, session_id: &str, title: &str) -> anyhow::Result<()> {
    use rusqlite::Connection;
    let conn = Connection::open(db_path)
        .map_err(|e| anyhow::anyhow!("failed to open opencode DB: {e}"))?;
    conn.execute(
        "UPDATE session SET title = ?1 WHERE id = ?2",
        [title, session_id],
    )?;
    Ok(())
}

/// Read the title of an opencode session from the DB.
pub fn opencode_get_title(db_path: &Path, session_id: &str) -> Option<String> {
    use rusqlite::Connection;
    let conn = Connection::open(db_path).ok()?;
    conn.query_row(
        "SELECT title FROM session WHERE id = ?1",
        [session_id],
        |row| row.get(0),
    ).ok()
}

/// Update the directory of an opencode session in the DB.
/// Used when a worktree is renamed so the OpenCode session still points to
/// the correct directory for `opencode_latest_session` and `opencode_harvest_session`.
pub fn opencode_update_directory(db_path: &Path, session_id: &str, directory: &str) -> anyhow::Result<()> {
    use rusqlite::Connection;
    let conn = Connection::open(db_path)
        .map_err(|e| anyhow::anyhow!("failed to open opencode DB: {e}"))?;
    conn.execute(
        "UPDATE session SET directory = ?1 WHERE id = ?2",
        [directory, session_id],
    )?;
    Ok(())
}

/// Get the most recent session ID for a directory (non-polling, single check).
pub fn opencode_latest_session(db_path: &Path, directory: &str) -> Option<String> {
    use rusqlite::Connection;
    let conn = Connection::open(db_path).ok()?;
    let mut stmt = conn
        .prepare("SELECT id FROM session WHERE directory = ?1 ORDER BY time_created DESC LIMIT 1")
        .ok()?;
    stmt.query_map([directory], |row| row.get(0))
        .ok()?
        .filter_map(|r| r.ok())
        .next()
}

// ── Tests ──────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_consumer_parse() {
        assert_eq!(Consumer::parse("claude").unwrap(), Consumer::Claude);
        assert_eq!(Consumer::parse("pi").unwrap(), Consumer::Pi);
        assert_eq!(Consumer::parse("opencode").unwrap(), Consumer::OpenCode);
        assert_eq!(Consumer::parse("open-code").unwrap(), Consumer::OpenCode);
        assert_eq!(Consumer::parse("oc").unwrap(), Consumer::OpenCode);
        assert!(Consumer::parse("unknown").is_err());
    }

    #[test]
    fn test_binary_names() {
        assert_eq!(Consumer::Claude.binary(), "claude");
        assert_eq!(Consumer::Pi.binary(), "pi");
        assert_eq!(Consumer::OpenCode.binary(), "opencode");
    }

    #[test]
    fn test_home_config_dirs() {
        assert_eq!(Consumer::Claude.home_config_dir(), ".claude");
        assert_eq!(Consumer::Pi.home_config_dir(), ".pi");
        assert_eq!(Consumer::OpenCode.home_config_dir(), ".config/opencode");
    }

    #[test]
    fn test_is_opencode() {
        assert!(Consumer::OpenCode.is_opencode());
        assert!(!Consumer::Claude.is_opencode());
        assert!(!Consumer::Pi.is_opencode());
    }

    #[test]
    fn test_data_dir() {
        assert_eq!(Consumer::OpenCode.data_dir(), ".local/share/opencode");
        assert_eq!(Consumer::Claude.data_dir(), "");
    }

    #[test]
    fn test_opencode_update_title() {
        use rusqlite::Connection;
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("opencode.db");
        let conn = Connection::open(&db_path).unwrap();
        conn.execute_batch(
            "CREATE TABLE session (id TEXT PRIMARY KEY, title TEXT, directory TEXT, time_created INTEGER);\
             INSERT INTO session (id, title, directory, time_created) VALUES ('ses_test123', 'Greeting', '/tmp', 1000);",
        )
        .unwrap();

        opencode_update_title(&db_path, "ses_test123", "swarm-mcp").unwrap();

        let title: String = conn
            .query_row("SELECT title FROM session WHERE id = 'ses_test123'", [], |r| r.get(0))
            .unwrap();
        assert_eq!(title, "swarm-mcp");
    }

    #[test]
    fn test_opencode_update_title_nonexistent_id_is_noop() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("opencode.db");
        let conn = rusqlite::Connection::open(&db_path).unwrap();
        conn.execute_batch(
            "CREATE TABLE session (id TEXT PRIMARY KEY, title TEXT, directory TEXT, time_created INTEGER);",
        )
        .unwrap();

        // SQLite UPDATE with no matching WHERE is not an error — 0 rows affected.
        assert!(opencode_update_title(&db_path, "ses_nonexistent", "test").is_ok());
    }

    #[test]
    fn test_opencode_update_directory() {
        use rusqlite::Connection;
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("opencode.db");
        let conn = Connection::open(&db_path).unwrap();
        conn.execute_batch(
            "CREATE TABLE session (id TEXT PRIMARY KEY, title TEXT, directory TEXT, time_created INTEGER);\
             INSERT INTO session (id, title, directory, time_created) VALUES ('ses_test123', 'Test', '/tmp/old', 1000);",
        )
        .unwrap();

        opencode_update_directory(&db_path, "ses_test123", "/tmp/new").unwrap();

        let directory: String = conn
            .query_row("SELECT directory FROM session WHERE id = 'ses_test123'", [], |r| r.get(0))
            .unwrap();
        assert_eq!(directory, "/tmp/new");
    }
}