myco 0.1.1

Multi-host coding agent CLI (local in-process + SSH remotes)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
//! Conversation session persistence and metadata.
//!
//! Sessions live under `~/.myco/session/{shard}/{id}.json` (plus a sibling
//! `.history` for readline). Schema is intentionally breaking vs earlier WIP
//! files: only [`SESSION_FILE_VERSION`] is accepted.

mod agent;
mod transcript;

pub use agent::{
    Agent, AgentEvent, AgentInteractionError, EventSink, NullEventSink, TraceContext,
    uuid_simple_hex,
};
pub use transcript::{
    SECTION_RULE, USER_RULE, format_tool_invocation, print_session_history, write_session_history,
};

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use chrono::{DateTime, Utc};
use uuid::Uuid;

use crate::generative_model::{Message, Model};

/// On-disk session schema version. Older files are rejected (WIP break).
pub const SESSION_FILE_VERSION: u32 = 2;
pub const RECENT_SESSION_LIMIT: usize = 10;
pub const SESSION_LIST_SNIPPET: usize = 48;
pub const MAX_TITLE_CHARS: usize = 120;
pub const MAX_SCRATCHPAD_BYTES: usize = 64 * 1024;

/// Full conversation session document.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Session {
    pub version: u32,
    pub id: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub model: String,
    pub messages: Vec<Message>,
    /// Short human label; agent/CLI maintained.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Associated PRs / worktrees (any repo / host).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub links: Vec<SessionLink>,
    /// Per-session markdown scratchpad.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub scratchpad: String,
}

/// Structured association stored on a session.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SessionLink {
    GitHubPr {
        url: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        repo: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        number: Option<u32>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        note: Option<String>,
    },
    Worktree {
        /// Harness host name (`local`, `devbox`, …).
        host: String,
        /// Absolute path on that host.
        path: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        branch: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        note: Option<String>,
    },
}

/// Lightweight row for `/sessions` and `session_meta list`.
#[derive(Debug, Clone)]
pub struct SessionListEntry {
    pub id: String,
    pub path: PathBuf,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub model: String,
    pub message_count: usize,
    pub title: Option<String>,
    pub snippet: String,
    pub link_counts: LinkCounts,
}

#[derive(Debug, Clone, Copy, Default)]
pub struct LinkCounts {
    pub prs: usize,
    pub worktrees: usize,
}

impl LinkCounts {
    pub fn from_links(links: &[SessionLink]) -> Self {
        let mut c = Self::default();
        for link in links {
            match link {
                SessionLink::GitHubPr { .. } => c.prs += 1,
                SessionLink::Worktree { .. } => c.worktrees += 1,
            }
        }
        c
    }

    pub fn is_empty(self) -> bool {
        self.prs == 0 && self.worktrees == 0
    }
}

/// Shared handle so the CLI and `session_meta` tool mutate the same live session.
#[derive(Clone)]
pub struct ActiveSession {
    inner: Arc<Mutex<Session>>,
}

impl ActiveSession {
    pub fn new(session: Session) -> Self {
        Self {
            inner: Arc::new(Mutex::new(session)),
        }
    }

    pub fn replace(&self, session: Session) {
        let mut guard = self.lock();
        *guard = session;
    }

    pub fn snapshot(&self) -> Session {
        self.lock().clone()
    }

    pub fn id(&self) -> String {
        self.lock().id.clone()
    }

    pub fn with<R>(&self, f: impl FnOnce(&Session) -> R) -> R {
        f(&self.lock())
    }

    pub fn with_mut<R>(&self, f: impl FnOnce(&mut Session) -> R) -> R {
        f(&mut self.lock())
    }

    /// Update messages from the agent and persist when they changed (or `force`).
    pub fn persist_messages(&self, messages: &[Message], force: bool) -> Result<(), String> {
        let mut session = self.lock();
        if force || messages.len() != session.messages.len() {
            session.messages = messages.to_vec();
            session.touch();
            session.save()?;
        }
        Ok(())
    }

    /// Set title if currently unset, from the first user line. Returns true if set.
    pub fn maybe_auto_title_from_user_text(&self, text: &str) -> Result<bool, String> {
        let mut session = self.lock();
        if session.title.is_some() {
            return Ok(false);
        }
        if let Some(title) = auto_title_from_text(text) {
            session.title = Some(title);
            session.touch();
            session.save()?;
            return Ok(true);
        }
        Ok(false)
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Session> {
        self.inner.lock().unwrap_or_else(|e| e.into_inner())
    }
}

impl Session {
    pub fn new(model: Model) -> Self {
        let now = Utc::now();
        Self {
            version: SESSION_FILE_VERSION,
            id: uuid_simple_hex(Uuid::new_v4()),
            created_at: now,
            updated_at: now,
            model: model.to_string(),
            messages: Vec::new(),
            title: None,
            links: Vec::new(),
            scratchpad: String::new(),
        }
    }

    pub fn touch(&mut self) {
        self.updated_at = Utc::now();
    }

    pub fn json_path(&self) -> PathBuf {
        session_file_path(&self.id, "json")
    }

    pub fn history_path(&self) -> PathBuf {
        session_file_path(&self.id, "history")
    }

    pub fn save(&self) -> Result<(), String> {
        let path = self.json_path();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|e| e.to_string())?;
        }
        let json = serde_json::to_vec_pretty(self).map_err(|e| e.to_string())?;
        atomically_write(&path, &json)
    }

    pub fn load(path: &Path) -> Result<Self, String> {
        let data = fs::read(path).map_err(|e| format!("read {}: {e}", path.display()))?;
        let session: Session =
            serde_json::from_slice(&data).map_err(|e| format!("parse {}: {e}", path.display()))?;
        if session.version != SESSION_FILE_VERSION {
            return Err(format!(
                "unsupported session version {} in {} (expected {SESSION_FILE_VERSION}; \
                 old WIP sessions are not migrated)",
                session.version,
                path.display()
            ));
        }
        if session.id.is_empty() {
            return Err(format!("session file {} has empty id", path.display()));
        }
        Ok(session)
    }

    pub fn load_by_id_or_prefix(id_or_prefix: &str) -> Result<Self, String> {
        let id = resolve_session_id(id_or_prefix)?;
        Self::load(&session_file_path(&id, "json"))
    }

    pub fn set_title(&mut self, title: Option<String>) -> Result<(), String> {
        self.title = match title {
            None => None,
            Some(t) => Some(normalize_title(&t)?),
        };
        Ok(())
    }

    pub fn set_scratchpad(&mut self, text: String) -> Result<(), String> {
        if text.len() > MAX_SCRATCHPAD_BYTES {
            return Err(format!(
                "scratchpad too large ({} bytes; max {MAX_SCRATCHPAD_BYTES})",
                text.len()
            ));
        }
        self.scratchpad = text;
        Ok(())
    }

    /// Insert or update a link (dedup by PR URL or worktree host+path).
    pub fn upsert_link(&mut self, mut link: SessionLink) -> Result<(), String> {
        validate_link(&link)?;
        match &mut link {
            SessionLink::GitHubPr {
                url, repo, number, ..
            } => {
                let url_key = normalize_pr_url(url)?;
                let (parsed_repo, parsed_num) = parse_pr_fields(&url_key);
                *url = url_key.clone();
                if repo.is_none() {
                    *repo = parsed_repo;
                }
                if number.is_none() {
                    *number = parsed_num;
                }
                if let Some(existing) = self.links.iter_mut().find_map(|l| match l {
                    SessionLink::GitHubPr { url, .. } if urls_equal(url, &url_key) => Some(l),
                    _ => None,
                }) {
                    *existing = link;
                } else {
                    self.links.push(link);
                }
            }
            SessionLink::Worktree { host, path, .. } => {
                *host = host.trim().to_string();
                *path = path.trim().to_string();
                let host_key = host.clone();
                let path_key = path.clone();
                if let Some(existing) = self.links.iter_mut().find_map(|l| match l {
                    SessionLink::Worktree { host, path, .. }
                        if host == &host_key && path == &path_key =>
                    {
                        Some(l)
                    }
                    _ => None,
                }) {
                    *existing = link;
                } else {
                    self.links.push(link);
                }
            }
        }
        Ok(())
    }

    pub fn remove_link_at(&mut self, index: usize) -> Result<SessionLink, String> {
        if index >= self.links.len() {
            return Err(format!(
                "link index {index} out of range ({} links)",
                self.links.len()
            ));
        }
        Ok(self.links.remove(index))
    }

    pub fn remove_link_matching(
        &mut self,
        url: Option<&str>,
        host: Option<&str>,
        path: Option<&str>,
    ) -> Result<SessionLink, String> {
        let idx = self
            .links
            .iter()
            .position(|l| match l {
                SessionLink::GitHubPr {
                    url: existing_url, ..
                } => url.map(|u| urls_equal(existing_url, u)).unwrap_or(false),
                SessionLink::Worktree {
                    host: h, path: p, ..
                } => {
                    let host_ok = host.map(|x| x == h.as_str()).unwrap_or(false);
                    let path_ok = path.map(|x| x == p.as_str()).unwrap_or(true);
                    host_ok && path_ok
                }
            })
            .ok_or_else(|| "no matching link".to_string())?;
        Ok(self.links.remove(idx))
    }
}

// ---------------------------------------------------------------------------
// Paths / listing / resolve
// ---------------------------------------------------------------------------

pub fn myco_home() -> Result<PathBuf, String> {
    if let Ok(root) = std::env::var("MYCO_HOME") {
        let p = PathBuf::from(root);
        if !p.as_os_str().is_empty() {
            return Ok(p);
        }
    }
    dirs::home_dir()
        .map(|h| h.join(".myco"))
        .ok_or_else(|| "could not resolve home directory".into())
}

pub fn session_root() -> Result<PathBuf, String> {
    Ok(myco_home()?.join("session"))
}

pub fn session_file_path(id: &str, ext: &str) -> PathBuf {
    let shard = &id[..2.min(id.len())];
    match session_root() {
        Ok(root) => root.join(shard).join(format!("{id}.{ext}")),
        Err(_) => PathBuf::from(format!(".myco/session/{shard}/{id}.{ext}")),
    }
}

pub fn atomically_write(path: &Path, content: &[u8]) -> Result<(), String> {
    let mut file = atomic_write_file::AtomicWriteFile::options()
        .open(path)
        .map_err(|e| e.to_string())?;
    file.write_all(content).map_err(|e| e.to_string())?;
    file.commit().map_err(|e| e.to_string())?;
    Ok(())
}

pub fn list_sessions(limit: usize) -> Result<Vec<SessionListEntry>, String> {
    let root = session_root()?;
    if !root.exists() {
        return Ok(Vec::new());
    }

    let mut metas = Vec::new();
    for path in iter_session_json_files(&root)? {
        match session_list_entry_from_path(&path) {
            Ok(entry) => metas.push(entry),
            Err(_) => continue, // skip corrupt / wrong-version files
        }
    }

    metas.sort_by_key(|m| std::cmp::Reverse(m.updated_at));
    if limit > 0 {
        metas.truncate(limit);
    }
    Ok(metas)
}

/// List every readable session (no limit). Wrong-version files are omitted.
pub fn list_all_sessions() -> Result<Vec<SessionListEntry>, String> {
    list_sessions(0)
}

fn session_list_entry_from_path(path: &Path) -> Result<SessionListEntry, String> {
    // Prefer full parse so version is enforced; fall back is not used for wrong version.
    let session = Session::load(path)?;
    let snippet = first_user_text_from_messages(&session.messages).unwrap_or_default();
    Ok(SessionListEntry {
        id: session.id,
        path: path.to_path_buf(),
        created_at: session.created_at,
        updated_at: session.updated_at,
        model: session.model,
        message_count: session.messages.len(),
        title: session.title,
        snippet,
        link_counts: LinkCounts::from_links(&session.links),
    })
}

/// Load a session by id/prefix, or the most recent when `id_or_prefix` is `None`.
pub fn resolve_and_load_session(id_or_prefix: Option<&str>) -> Result<Session, String> {
    match id_or_prefix {
        Some(id) => Session::load_by_id_or_prefix(id),
        None => {
            let list = list_sessions(1)?;
            let meta = list
                .into_iter()
                .next()
                .ok_or_else(|| "no sessions found under ~/.myco/session".to_string())?;
            Session::load(&meta.path)
        }
    }
}

pub fn resolve_session_id(id_or_prefix: &str) -> Result<String, String> {
    let needle = id_or_prefix.trim().to_ascii_lowercase();
    if needle.is_empty() {
        return Err("empty session id".into());
    }

    if needle.len() == 32 && needle.chars().all(|c| c.is_ascii_hexdigit()) {
        let path = session_file_path(&needle, "json");
        if path.exists() {
            return Ok(needle);
        }
    }

    let root = session_root()?;
    if !root.exists() {
        return Err(format!("no sessions directory at {}", root.display()));
    }

    let mut matches = Vec::new();
    for path in iter_session_json_files(&root)? {
        let stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        if stem == needle || stem.starts_with(&needle) {
            matches.push(stem);
        }
    }

    matches.sort();
    matches.dedup();
    match matches.as_slice() {
        [] => Err(format!("no session matching {id_or_prefix:?}")),
        [one] => Ok(one.clone()),
        many => Err(format!(
            "ambiguous prefix {id_or_prefix:?}; candidates: {}",
            many.iter().take(8).cloned().collect::<Vec<_>>().join(", ")
        )),
    }
}

pub fn iter_session_json_files(root: &Path) -> Result<Vec<PathBuf>, String> {
    let mut paths = Vec::new();
    let shards = fs::read_dir(root).map_err(|e| e.to_string())?;
    for shard_ent in shards {
        let shard_ent = shard_ent.map_err(|e| e.to_string())?;
        let shard_path = shard_ent.path();
        if !shard_path.is_dir() {
            continue;
        }
        let Ok(files) = fs::read_dir(&shard_path) else {
            continue;
        };
        for file_ent in files {
            let Ok(file_ent) = file_ent else { continue };
            let path = file_ent.path();
            if path.extension().and_then(|e| e.to_str()) == Some("json") {
                paths.push(path);
            }
        }
    }
    Ok(paths)
}

// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------

pub fn truncate_snippet(s: &str, max: usize) -> String {
    let one_line: String = s.chars().map(|c| if c == '\n' { ' ' } else { c }).collect();
    if one_line.chars().count() <= max {
        return one_line;
    }
    let trimmed: String = one_line.chars().take(max.saturating_sub(1)).collect();
    format!("{trimmed}…")
}

pub fn auto_title_from_text(text: &str) -> Option<String> {
    let line = text.lines().map(str::trim).find(|l| !l.is_empty())?;
    normalize_title(line).ok()
}

pub fn normalize_title(raw: &str) -> Result<String, String> {
    let one_line: String = raw
        .chars()
        .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    let one_line = one_line.trim().to_string();
    if one_line.is_empty() {
        return Err("title must be non-empty".into());
    }
    if one_line.chars().count() > MAX_TITLE_CHARS {
        let trimmed: String = one_line
            .chars()
            .take(MAX_TITLE_CHARS.saturating_sub(1))
            .collect();
        return Ok(format!("{trimmed}…"));
    }
    Ok(one_line)
}

pub fn first_user_text_from_messages(messages: &[Message]) -> Option<String> {
    for msg in messages {
        if let Message::UserMessage { content } = msg {
            let text: String = content
                .iter()
                .filter_map(|c| match c {
                    crate::generative_model::Content::Text { text } => Some(text.as_str()),
                    _ => None,
                })
                .collect();
            if !text.trim().is_empty() {
                return Some(text);
            }
        }
    }
    None
}

pub fn format_session_list_line(index: usize, entry: &SessionListEntry) -> String {
    let label = entry
        .title
        .as_deref()
        .filter(|t| !t.is_empty())
        .map(|t| t.to_string())
        .unwrap_or_else(|| truncate_snippet(&entry.snippet, SESSION_LIST_SNIPPET));
    let label = if label.is_empty() {
        "(untitled)".to_string()
    } else {
        label
    };
    let links = if entry.link_counts.is_empty() {
        String::new()
    } else {
        format!(
            "  pr:{} wt:{}",
            entry.link_counts.prs, entry.link_counts.worktrees
        )
    };
    format!(
        "  {:>2}. {}  {}  model={}  msgs={}{}  {}",
        index,
        entry.id,
        entry.updated_at.to_rfc3339(),
        entry.model,
        entry.message_count,
        links,
        label
    )
}

pub fn format_session_detail(session: &Session) -> String {
    let mut out = String::new();
    out.push_str(&format!("id:        {}\n", session.id));
    out.push_str(&format!("path:      {}\n", session.json_path().display()));
    out.push_str(&format!("created:   {}\n", session.created_at.to_rfc3339()));
    out.push_str(&format!("updated:   {}\n", session.updated_at.to_rfc3339()));
    out.push_str(&format!("model:     {}\n", session.model));
    out.push_str(&format!("messages:  {}\n", session.messages.len()));
    out.push_str(&format!(
        "title:     {}\n",
        session
            .title
            .as_deref()
            .filter(|t| !t.is_empty())
            .unwrap_or("(none)")
    ));
    if session.links.is_empty() {
        out.push_str("links:     (none)\n");
    } else {
        out.push_str(&format!("links:     ({})\n", session.links.len()));
        for (i, link) in session.links.iter().enumerate() {
            out.push_str(&format!("  [{i}] {}\n", format_link_one_line(link)));
        }
    }
    if session.scratchpad.is_empty() {
        out.push_str("scratchpad: (empty)\n");
    } else {
        out.push_str(&format!(
            "scratchpad: {} bytes\n---\n{}\n---\n",
            session.scratchpad.len(),
            session.scratchpad
        ));
    }
    out
}

pub fn format_link_one_line(link: &SessionLink) -> String {
    match link {
        SessionLink::GitHubPr {
            url,
            repo,
            number,
            note,
        } => {
            let mut s = format!("pr {url}");
            if let (Some(r), Some(n)) = (repo, number) {
                s = format!("pr {r}#{n} ({url})");
            }
            if let Some(n) = note
                && !n.is_empty()
            {
                s.push_str(&format!(" — {n}"));
            }
            s
        }
        SessionLink::Worktree {
            host,
            path,
            branch,
            note,
        } => {
            let mut s = format!("worktree host={host} path={path}");
            if let Some(b) = branch
                && !b.is_empty()
            {
                s.push_str(&format!(" branch={b}"));
            }
            if let Some(n) = note
                && !n.is_empty()
            {
                s.push_str(&format!(" — {n}"));
            }
            s
        }
    }
}

// ---------------------------------------------------------------------------
// Link validation / PR URL helpers
// ---------------------------------------------------------------------------

fn validate_link(link: &SessionLink) -> Result<(), String> {
    match link {
        SessionLink::GitHubPr { url, .. } => {
            normalize_pr_url(url)?;
            Ok(())
        }
        SessionLink::Worktree { host, path, .. } => {
            if host.trim().is_empty() {
                return Err("worktree host must be non-empty".into());
            }
            let path = path.trim();
            if path.is_empty() {
                return Err("worktree path must be non-empty".into());
            }
            // Allow Unix absolute and Windows drive paths; reject relative.
            let windows_abs = path.len() >= 3 && path.as_bytes()[1] == b':';
            if !path.starts_with('/') && !windows_abs {
                return Err("worktree path must be absolute".into());
            }
            Ok(())
        }
    }
}

/// Normalize a GitHub PR reference to an https URL.
///
/// Accepts:
/// - `https://github.com/org/repo/pull/123`
/// - `http://github.com/org/repo/pull/123`
/// - `github.com/org/repo/pull/123`
/// - `org/repo#123` / `org/repo/pull/123`
pub fn normalize_pr_url(raw: &str) -> Result<String, String> {
    let s = raw.trim();
    if s.is_empty() {
        return Err("PR url must be non-empty".into());
    }

    // org/repo#123
    if let Some((repo, num)) = s.split_once('#')
        && repo.contains('/')
        && !repo.contains("://")
        && num.chars().all(|c| c.is_ascii_digit())
    {
        let num: u32 = num
            .parse()
            .map_err(|_| format!("invalid PR number in {s:?}"))?;
        if num == 0 {
            return Err("PR number must be > 0".into());
        }
        return Ok(format!("https://github.com/{repo}/pull/{num}"));
    }

    let mut url = s.to_string();
    if url.starts_with("github.com/") {
        url = format!("https://{url}");
    }
    if url.starts_with("http://") {
        url = format!("https://{}", &url["http://".len()..]);
    }

    // org/repo/pull/123
    if !url.contains("://")
        && let Some((repo, rest)) = url.split_once("/pull/")
        && repo.contains('/')
        && rest.chars().all(|c| c.is_ascii_digit())
    {
        url = format!("https://github.com/{repo}/pull/{rest}");
    }

    let rest = url.strip_prefix("https://github.com/").ok_or_else(|| {
        format!("PR url must be a github.com pull request URL or org/repo#N (got {raw:?})")
    })?;
    let parts: Vec<&str> = rest.trim_end_matches('/').split('/').collect();
    // org/repo/pull/N
    if parts.len() >= 4
        && parts[2] == "pull"
        && let Ok(n) = parts[3].parse::<u32>()
        && n > 0
    {
        return Ok(format!(
            "https://github.com/{}/{}/pull/{n}",
            parts[0], parts[1]
        ));
    }
    Err(format!(
        "PR url must be a github.com pull request URL or org/repo#N (got {raw:?})"
    ))
}

pub fn parse_pr_fields(url: &str) -> (Option<String>, Option<u32>) {
    let Ok(norm) = normalize_pr_url(url) else {
        return (None, None);
    };
    let rest = norm.trim_start_matches("https://github.com/");
    let parts: Vec<&str> = rest.split('/').collect();
    if parts.len() >= 4 && parts[2] == "pull" {
        let repo = format!("{}/{}", parts[0], parts[1]);
        let number = parts[3].parse().ok();
        return (Some(repo), number);
    }
    (None, None)
}

fn urls_equal(a: &str, b: &str) -> bool {
    match (normalize_pr_url(a), normalize_pr_url(b)) {
        (Ok(x), Ok(y)) => x == y,
        _ => a.trim() == b.trim(),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generative_model::{Content, Message};
    use std::time::Duration;

    fn temp_session_root() -> PathBuf {
        std::env::temp_dir().join(format!(
            "myco-session-unit-{}",
            uuid_simple_hex(Uuid::new_v4())
        ))
    }

    #[test]
    fn normalize_pr_url_variants() {
        assert_eq!(
            normalize_pr_url("https://github.com/foo/bar/pull/12").unwrap(),
            "https://github.com/foo/bar/pull/12"
        );
        assert_eq!(
            normalize_pr_url("foo/bar#99").unwrap(),
            "https://github.com/foo/bar/pull/99"
        );
        assert_eq!(
            normalize_pr_url("github.com/foo/bar/pull/3").unwrap(),
            "https://github.com/foo/bar/pull/3"
        );
        assert!(normalize_pr_url("https://gitlab.com/x/y/merge_requests/1").is_err());
    }

    #[test]
    fn title_normalization() {
        assert_eq!(normalize_title("  hello   world  ").unwrap(), "hello world");
        assert!(normalize_title("   ").is_err());
        let long = "x".repeat(200);
        let t = normalize_title(&long).unwrap();
        assert!(t.chars().count() <= MAX_TITLE_CHARS);
        assert!(t.ends_with('…'));
    }

    #[test]
    fn link_dedup_pr_and_worktree() {
        let mut s = Session::new(Model::ClaudeHaiku45);
        s.upsert_link(SessionLink::GitHubPr {
            url: "foo/bar#1".into(),
            repo: None,
            number: None,
            note: Some("a".into()),
        })
        .unwrap();
        s.upsert_link(SessionLink::GitHubPr {
            url: "https://github.com/foo/bar/pull/1".into(),
            repo: Some("foo/bar".into()),
            number: Some(1),
            note: Some("b".into()),
        })
        .unwrap();
        assert_eq!(s.links.len(), 1);
        match &s.links[0] {
            SessionLink::GitHubPr { note, .. } => assert_eq!(note.as_deref(), Some("b")),
            _ => panic!("expected pr"),
        }

        s.upsert_link(SessionLink::Worktree {
            host: "local".into(),
            path: "/tmp/wt".into(),
            branch: Some("feat/x".into()),
            note: None,
        })
        .unwrap();
        s.upsert_link(SessionLink::Worktree {
            host: "local".into(),
            path: "/tmp/wt".into(),
            branch: Some("feat/y".into()),
            note: Some("upd".into()),
        })
        .unwrap();
        assert_eq!(s.links.len(), 2);
        match &s.links[1] {
            SessionLink::Worktree { branch, note, .. } => {
                assert_eq!(branch.as_deref(), Some("feat/y"));
                assert_eq!(note.as_deref(), Some("upd"));
            }
            _ => panic!("expected worktree"),
        }
    }

    #[test]
    fn session_file_roundtrip_v2() {
        let dir = temp_session_root();
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("sess.json");

        let mut session = Session {
            version: SESSION_FILE_VERSION,
            id: "aabbccddeeff00112233445566778899".into(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            model: "claude-opus-4-8".into(),
            messages: vec![Message::UserMessage {
                content: vec![Content::Text {
                    text: "hello".into(),
                }],
            }],
            title: Some("hello session".into()),
            links: vec![SessionLink::Worktree {
                host: "local".into(),
                path: "/tmp/x".into(),
                branch: None,
                note: None,
            }],
            scratchpad: "notes".into(),
        };
        session.updated_at = session.created_at + Duration::from_secs(1);

        let json = serde_json::to_vec_pretty(&session).unwrap();
        fs::write(&path, &json).unwrap();

        let loaded = Session::load(&path).unwrap();
        assert_eq!(loaded.id, session.id);
        assert_eq!(loaded.title.as_deref(), Some("hello session"));
        assert_eq!(loaded.scratchpad, "notes");
        assert_eq!(loaded.links.len(), 1);
        assert_eq!(loaded.messages.len(), 1);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn reject_wrong_version() {
        let dir = temp_session_root();
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("old.json");
        fs::write(
            &path,
            br#"{"version":1,"id":"aa","created_at":"2020-01-01T00:00:00Z","updated_at":"2020-01-01T00:00:00Z","model":"x","messages":[]}"#,
        )
        .unwrap();
        let err = Session::load(&path).unwrap_err();
        assert!(err.contains("unsupported session version"), "{err}");
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn active_session_auto_title_once() {
        let dir = temp_session_root();
        // SAFETY: test-only env override; serial unit tests.
        unsafe {
            std::env::set_var("MYCO_HOME", &dir);
        }
        let s = ActiveSession::new(Session::new(Model::ClaudeHaiku45));
        assert!(
            s.maybe_auto_title_from_user_text("First line\n\nmore")
                .unwrap()
        );
        assert_eq!(s.snapshot().title.as_deref(), Some("First line"));
        assert!(!s.maybe_auto_title_from_user_text("Second").unwrap());
        assert_eq!(s.snapshot().title.as_deref(), Some("First line"));
        let _ = fs::remove_dir_all(&dir);
        unsafe {
            std::env::remove_var("MYCO_HOME");
        }
    }

    #[test]
    fn scratchpad_cap() {
        let mut s = Session::new(Model::ClaudeHaiku45);
        let big = "a".repeat(MAX_SCRATCHPAD_BYTES + 1);
        assert!(s.set_scratchpad(big).is_err());
        s.set_scratchpad("ok".into()).unwrap();
        assert_eq!(s.scratchpad, "ok");
    }
}