sara-tasks 1.0.0

Sara — folder-aware task manager
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
use anyhow::Result;
use rusqlite::Connection;

use crate::infrastructure::config::Config;
use crate::infrastructure::db;
use crate::infrastructure::model::Task;

use super::types::{
    BranchOverlap, Detail, EDIT_FIELDS, EditState, Focusable, GraphNode, NOTE_KINDS, TaskTree,
};

/// Safety caps applied while *fetching* the task tree — generous enough that
/// "compact vs expanded" (the render-time caps below) is almost always the
/// real limit a user hits, not this one.
const TREE_FETCH_MAX_DEPTH: usize = 6;
const TREE_FETCH_MAX_NODES: usize = 40;
/// Direct children per node kept when fetching; the rest are counted in
/// `hidden_children` rather than dropped silently.
const TREE_FETCH_MAX_CHILDREN: usize = 8;

/// Render-time caps for the *compact* (default) task tree — how many levels
/// and siblings-per-node show before the 'd' expand toggle is needed. The
/// tree is always fetched at the deeper `TREE_FETCH_*` bounds above, so
/// toggling expand is instant (no re-query).
pub(super) const TREE_COMPACT_DEPTH: usize = 2;
pub(super) const TREE_COMPACT_CHILDREN: usize = 4;

pub(super) fn load_detail(conn: &Connection, cfg: &Config, task: Task) -> Result<Detail> {
    let resolve_ids = |uuids: Vec<uuid::Uuid>| -> Vec<String> {
        uuids
            .iter()
            .filter_map(|u| {
                db::get_task_by_uuid_prefix(conn, &u.to_string()[..8])
                    .ok()
                    .flatten()
            })
            .map(|t| format!("[{}] {}", t.id.unwrap_or(0), t.description))
            .collect()
    };

    let sourced = db::get_task_files_sourced(conn, &task.uuid)?;
    let mut manual_files = vec![];
    let mut suggested_files = vec![];
    for (path, source) in sourced {
        if source == db::SOURCE_SUGGESTED {
            suggested_files.push(path);
        } else {
            manual_files.push(path);
        }
    }

    let project_root = db::get_project(conn, &task.project)?
        .and_then(|p| p.path)
        .map(std::path::PathBuf::from);

    // Branch snapshot and overlap detection (pure stored-data, no live git).
    let branch = db::get_task_branch(conn, &task.uuid);
    let overlaps = compute_overlaps(conn, &task, &branch);

    // Similar tasks (shared tags, same project)
    let similar =
        db::similar_tasks(conn, &task.uuid, &task.project, &task.tags).unwrap_or_default();

    // Checklist
    let checklist = db::get_checklist(conn, &task.uuid).unwrap_or_default();

    // Urgency breakdown
    let blockers = db::get_blockers(conn, &task.uuid).unwrap_or_default();
    let blocking_tasks = db::get_blocking(conn, &task.uuid).unwrap_or_default();
    let urgency_breakdown = Some(db::compute_urgency_breakdown(
        &task,
        &cfg.urgency,
        !blockers.is_empty(),
        blocking_tasks.len(),
    ));

    // Activity heatmap for the project (last 16 weeks)
    let activity = db::activity_counts(conn, 16 * 7, Some(&task.project)).unwrap_or_default();

    // Project stats
    let stats = db::project_stats(conn, &task.project).ok();

    let guide = db::get_guide_fields(conn, &task.uuid).unwrap_or_default();
    let anchors = db::get_task_anchors(conn, &task.uuid).unwrap_or_default();
    let ai_runs = db::get_ai_runs(conn, &task.uuid).unwrap_or_default();
    let head_commit = project_root
        .as_ref()
        .and_then(|p| crate::infrastructure::git::head_commit(p));
    let project_commands = db::get_project_commands(conn, &task.project).unwrap_or_default();
    let tree = build_task_tree(conn, task.uuid);

    Ok(Detail {
        depends_on_ids: dep_ids(conn, &blockers),
        blocked_by: resolve_ids(blockers.clone()),
        blocking: resolve_ids(blocking_tasks.clone()),
        manual_files,
        suggested_files,
        links: db::get_links(conn, &task.uuid)?,
        annotations: db::get_annotations(conn, &task.uuid)?,
        history: db::get_history(conn, &task.uuid)?,
        project_root,
        branch,
        overlaps,
        similar,
        checklist,
        urgency_breakdown,
        activity,
        stats,
        guide,
        anchors,
        ai_runs,
        head_commit,
        project_commands,
        tree,
        task,
    })
}

/// Which direction a hop in the task tree walks: "← blocked by" follows
/// depends_on edges (any status, so completed blockers still show, crossed
/// out); "blocks →" follows the reverse (what depends on this).
#[derive(Clone, Copy)]
enum TreeDir {
    Blockers,
    Dependents,
}

/// Build the full task-relationship tree for `root`: every blocker
/// recursively (blockers-of-blockers, …) and every dependent recursively
/// (dependents-of-dependents, …), each bounded by `TREE_FETCH_MAX_DEPTH`/
/// `_CHILDREN`/`_NODES` so a pathologically large or cyclic-looking DAG can't
/// blow up the fetch. Rendered compactly by default; 'd' expands to these
/// full bounds without a re-query (see `TREE_COMPACT_*`).
pub(super) fn build_task_tree(conn: &Connection, root: uuid::Uuid) -> TaskTree {
    let flags = db::link_flags_by_task(conn).unwrap_or_default();
    let mut up_visited = std::collections::HashSet::from([root]);
    let mut up_budget = TREE_FETCH_MAX_NODES;
    let (blockers, blockers_hidden) = build_tree_level(
        conn,
        root,
        TreeDir::Blockers,
        1,
        &mut up_visited,
        &mut up_budget,
        &flags,
    );
    let mut down_visited = std::collections::HashSet::from([root]);
    let mut down_budget = TREE_FETCH_MAX_NODES;
    let (dependents, dependents_hidden) = build_tree_level(
        conn,
        root,
        TreeDir::Dependents,
        1,
        &mut down_visited,
        &mut down_budget,
        &flags,
    );
    TaskTree {
        blockers,
        blockers_hidden,
        dependents,
        dependents_hidden,
    }
}

/// Fetch one level's worth of neighbors (any status) and recurse into each,
/// returning `(children, hidden_count)` where `hidden_count` is how many
/// direct neighbors of `parent` exist beyond `TREE_FETCH_MAX_CHILDREN` — the
/// caller attaches that to the `GraphNode` it's building for `parent` (or,
/// at the top level, to the tree itself) so the render layer can show a
/// "+N more" leaf without a synthetic placeholder node.
fn build_tree_level(
    conn: &Connection,
    parent: uuid::Uuid,
    dir: TreeDir,
    depth: usize,
    visited: &mut std::collections::HashSet<uuid::Uuid>,
    budget: &mut usize,
    flags: &std::collections::HashMap<String, db::LinkFlags>,
) -> (Vec<GraphNode>, usize) {
    if depth > TREE_FETCH_MAX_DEPTH {
        return (Vec::new(), 0);
    }
    let neighbors = match dir {
        // All-status (not just pending) so completed neighbors still show,
        // crossed out — `get_blockers` is pending-only (it feeds urgency).
        TreeDir::Blockers => db::get_dependency_uuids(conn, &parent).unwrap_or_default(),
        TreeDir::Dependents => db::get_blocking(conn, &parent).unwrap_or_default(),
    };
    let hidden = neighbors.len().saturating_sub(TREE_FETCH_MAX_CHILDREN);
    let mut out = Vec::new();
    for u in neighbors.into_iter().take(TREE_FETCH_MAX_CHILDREN) {
        if *budget == 0 {
            break;
        }
        // A node reachable via more than one path (diamond in the DAG) is
        // shown once, at its first occurrence — re-expanding it again lower
        // down would risk exponential blowup for no new information.
        if !visited.insert(u) {
            continue;
        }
        let Some(t) = db::get_task_by_uuid_prefix(conn, &u.to_string()[..8])
            .ok()
            .flatten()
        else {
            continue;
        };
        *budget -= 1;
        let (children, hidden_children) =
            build_tree_level(conn, u, dir, depth + 1, visited, budget, flags);
        out.push(GraphNode {
            uuid: u,
            id: t.id,
            status: t.status,
            badge: flags.get(&u.to_string()).copied(),
            description: t.description,
            children,
            hidden_children,
        });
    }
    (out, hidden)
}

/// Verification/execution commands an executor should run, gathered from the
/// project record (setup/test/lint/run) and the task's `meta_json` grab-bag
/// (e.g. task-specific test_cmd / lint_cmd). Returns (scope, label, command).
pub(super) fn verification_rows(d: &Detail) -> Vec<(&'static str, String, String)> {
    let mut rows: Vec<(&'static str, String, String)> = Vec::new();
    let pc = &d.project_commands;
    for (label, cmd) in [
        ("setup", &pc.setup_cmd),
        ("test", &pc.test_cmd),
        ("lint", &pc.lint_cmd),
        ("run", &pc.run_cmd),
    ] {
        if let Some(c) = cmd.as_deref().filter(|s| !s.trim().is_empty()) {
            rows.push(("project", label.to_string(), c.to_string()));
        }
    }
    // Task-level commands from the meta_json grab-bag (render any "*_cmd" key).
    if let Some(meta) = d
        .guide
        .meta_json
        .as_deref()
        .and_then(|m| serde_json::from_str::<serde_json::Value>(m).ok())
        && let Some(obj) = meta.as_object()
    {
        for (k, v) in obj {
            if let Some(s) = v.as_str().filter(|s| !s.trim().is_empty()) {
                let label = k.strip_suffix("_cmd").unwrap_or(k).to_string();
                rows.push(("task", label, s.to_string()));
            }
        }
    }
    rows
}

/// Whether the guide is stale (validated against a different commit than HEAD).
pub(super) fn guide_is_stale(d: &Detail) -> bool {
    match (&d.head_commit, &d.guide.validated_commit) {
        (Some(h), Some(v)) => h != v,
        (Some(_), None) => false,
        _ => false,
    }
}

/// Annotations of a given kind (findings, constraints, …) authored on the task.
pub(super) fn notes_of_kind<'a>(
    d: &'a Detail,
    kind: &str,
) -> Vec<&'a crate::infrastructure::db::Annotation> {
    d.annotations.iter().filter(|a| a.kind == kind).collect()
}

/// All typed notes in render order (finding, constraint, assumption, …).
pub(super) fn typed_notes(d: &Detail) -> Vec<&crate::infrastructure::db::Annotation> {
    let mut out = Vec::new();
    for kind in NOTE_KINDS {
        for n in notes_of_kind(d, kind) {
            out.push(n);
        }
    }
    out
}

/// Resolve dependency uuids to their display IDs (skips tasks without an id).
pub(super) fn dep_ids(conn: &Connection, uuids: &[uuid::Uuid]) -> Vec<i64> {
    uuids
        .iter()
        .filter_map(|u| {
            db::get_task_by_uuid_prefix(conn, &u.to_string()[..8])
                .ok()
                .flatten()
        })
        .filter_map(|t| t.id)
        .collect()
}

/// Resolve dependency uuids to "[id] description" labels.
fn dep_labels(conn: &Connection, uuids: &[uuid::Uuid]) -> Vec<String> {
    uuids
        .iter()
        .filter_map(|u| {
            db::get_task_by_uuid_prefix(conn, &u.to_string()[..8])
                .ok()
                .flatten()
        })
        .map(|t| format!("[{}] {}", t.id.unwrap_or(0), t.description))
        .collect()
}

/// Current value shown (and pre-filled when editing) for the "Depends on" field:
/// the task's pending blocker IDs, space-separated.
pub(super) fn depends_on_display(d: &Detail) -> String {
    d.depends_on_ids
        .iter()
        .map(|i| i.to_string())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Apply an edited "Depends on" value: reconcile the task's pending dependency
/// edges with the IDs the user typed (space/comma separated). Adds and removes
/// edges as needed, then refreshes urgency and reloads dependency detail.
/// Returns a human-readable error (kept on screen) if a token can't be resolved
/// or the change would be invalid (self/cycle).
pub(super) fn reconcile_dependencies(
    conn: &Connection,
    cfg: &Config,
    detail: &mut Detail,
    value: &str,
) -> std::result::Result<(), String> {
    let task_uuid = detail.task.uuid;

    let tokens: Vec<&str> = value
        .split(|c: char| c == ',' || c.is_whitespace())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect();

    let mut desired: Vec<uuid::Uuid> = Vec::new();
    for tok in &tokens {
        let t = db::resolve_task(conn, tok).map_err(|_| format!("no task '{tok}'"))?;
        if t.uuid == task_uuid {
            return Err("a task cannot depend on itself".into());
        }
        if !desired.contains(&t.uuid) {
            desired.push(t.uuid);
        }
    }

    let current = db::get_blockers(conn, &task_uuid).unwrap_or_default();

    for u in &current {
        if !desired.contains(u) {
            db::remove_dependency(conn, &task_uuid, u).map_err(|e| e.to_string())?;
        }
    }
    for u in &desired {
        if !current.contains(u) {
            db::add_dependency(conn, &task_uuid, u).map_err(|e| e.to_string())?;
        }
    }

    db::refresh_urgency(conn, &cfg.urgency, &task_uuid).ok();
    for u in current.iter().chain(desired.iter()) {
        db::refresh_urgency(conn, &cfg.urgency, u).ok();
    }

    reload_dep_detail(conn, cfg, detail);
    Ok(())
}

/// Refresh the dependency-derived parts of the detail view after an edit.
pub(super) fn reload_dep_detail(conn: &Connection, cfg: &Config, detail: &mut Detail) {
    let uuid = detail.task.uuid;
    let blockers = db::get_blockers(conn, &uuid).unwrap_or_default();
    let blocking = db::get_blocking(conn, &uuid).unwrap_or_default();
    detail.depends_on_ids = dep_ids(conn, &blockers);
    detail.blocked_by = dep_labels(conn, &blockers);
    detail.blocking = dep_labels(conn, &blocking);
    if let Some(t) = db::get_task_by_uuid_prefix(conn, &uuid.to_string()[..8])
        .ok()
        .flatten()
    {
        detail.task.urgency = t.urgency;
    }
    detail.urgency_breakdown = Some(db::compute_urgency_breakdown(
        &detail.task,
        &cfg.urgency,
        !blockers.is_empty(),
        blocking.len(),
    ));
    detail.history = db::get_history(conn, &uuid).unwrap_or_default();
    // Dependency edits reshape the task tree.
    detail.tree = build_task_tree(conn, uuid);
}

pub(super) fn compute_overlaps(
    conn: &Connection,
    task: &Task,
    branch_rec: &Option<db::BranchRecord>,
) -> Vec<BranchOverlap> {
    let my_files: std::collections::HashSet<String> = branch_rec
        .as_ref()
        .and_then(|b| b.files.as_ref())
        .map(|fs| fs.iter().cloned().collect())
        .unwrap_or_default();

    if my_files.is_empty() {
        return vec![];
    }

    let others =
        db::branched_pending_in_project(conn, &task.project, &task.uuid).unwrap_or_default();

    let mut result = vec![];
    for (id, desc, other_rec) in others {
        let other_files: std::collections::HashSet<String> = other_rec
            .files
            .as_ref()
            .map(|fs| fs.iter().cloned().collect())
            .unwrap_or_default();
        let mut shared: Vec<String> = my_files.intersection(&other_files).cloned().collect();
        if !shared.is_empty() {
            shared.sort();
            result.push(BranchOverlap {
                id,
                description: desc,
                branch: other_rec.branch,
                shared_files: shared,
            });
        }
    }
    result
}

/// Ordered list of focusable items — matches on-screen render order so ↑/↓ feels natural.
/// Screen order: metadata fields → typed notes (findings/constraints/…) → links →
///               manual files → anchors → checklist → task-level comments.
pub(super) fn focusables(d: &Detail, show_notes: bool) -> Vec<Focusable> {
    let mut v: Vec<Focusable> = EDIT_FIELDS.iter().map(|f| Focusable::Field(*f)).collect();
    // Typed notes appear right after the metadata block in the TUI. Only
    // "risk" notes and (when toggled) the rest are actually on screen, so
    // only those are focusable — a hidden row shouldn't be selectable.
    for (i, note) in typed_notes(d).iter().enumerate() {
        if show_notes || note.kind == "risk" {
            v.push(Focusable::Note(i));
        }
    }
    for i in 0..d.links.len() {
        v.push(Focusable::Link(i));
    }
    for f in d.manual_files.iter().chain(d.suggested_files.iter()) {
        v.push(Focusable::File(f.clone()));
    }
    for i in 0..d.anchors.len() {
        v.push(Focusable::Anchor(i));
    }
    for i in 0..d.checklist.len() {
        v.push(Focusable::Checklist(i));
    }
    // Task-level comments (anchor-threaded ones are shown inline under their element).
    let comment_count = d
        .annotations
        .iter()
        .filter(|a| a.kind == "comment" && a.target_kind.as_deref() != Some("anchor"))
        .count();
    for i in 0..comment_count {
        v.push(Focusable::Comment(i));
    }
    v
}

/// Index in the focusable list of the checklist row with the given item id.
pub(super) fn checklist_focus_index(d: &Detail, show_notes: bool, item_id: i64) -> Option<usize> {
    focusables(d, show_notes).iter().position(|f| match f {
        Focusable::Checklist(i) => d.checklist.get(*i).map(|c| c.id) == Some(item_id),
        _ => false,
    })
}

/// Move the focused checklist step up/down within its kind, keeping the cursor
/// on the moved row. No-op when the focus is not a checklist item or the row is
/// already at its section boundary.
pub(super) fn reorder_focused_step(
    conn: &Connection,
    st: &mut EditState,
    current: &Option<Focusable>,
    up: bool,
) {
    let Some(Focusable::Checklist(i)) = current else {
        return;
    };
    let Some(id) = st.detail.checklist.get(*i).map(|c| c.id) else {
        return;
    };
    if db::move_step(conn, id, up).unwrap_or(false) {
        st.detail.checklist = db::get_checklist(conn, &st.detail.task.uuid).unwrap_or_default();
        if let Some(p) = checklist_focus_index(&st.detail, st.show_notes, id) {
            st.selected = p;
        }
    }
}

/// Find the task's PR URL, if any: the first *link* that points at a GitHub
/// pull request, else the first PR URL mentioned inside an annotation's text
/// (agents often note the PR in a comment before/instead of linking it).
pub(super) fn find_pr_url(d: &Detail) -> Option<String> {
    pr_url_from(&d.links, &d.annotations)
}

fn pr_url_from(links: &[db::Link], annotations: &[db::Annotation]) -> Option<String> {
    if let Some(link) = links.iter().find(|l| db::is_pr_link(&l.url)) {
        return Some(link.url.clone());
    }
    annotations.iter().find_map(|a| {
        a.text
            .split_whitespace()
            .map(|tok| tok.trim_matches(|c: char| !c.is_alphanumeric() && c != '/'))
            .find(|tok| db::is_pr_link(tok))
            .map(str::to_string)
    })
}

/// Open a URL in the OS default browser (non-blocking). Adds a scheme for
/// bare `www.` style links.
pub(super) fn open_url(raw: &str) {
    let url = if raw.starts_with("www.") {
        format!("https://{raw}")
    } else {
        raw.to_string()
    };
    let cmd = if cfg!(target_os = "macos") {
        "open"
    } else if cfg!(target_os = "windows") {
        "explorer"
    } else {
        "xdg-open"
    };
    let _ = std::process::Command::new(cmd)
        .arg(&url)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn();
}

/// Pick the user's terminal editor: $VISUAL, then $EDITOR, then the first of
/// nvim/vim/nano that exists on PATH.
pub(super) fn editor_command() -> String {
    if let Ok(v) = std::env::var("VISUAL")
        && !v.trim().is_empty()
    {
        return v;
    }
    if let Ok(v) = std::env::var("EDITOR")
        && !v.trim().is_empty()
    {
        return v;
    }
    for candidate in ["nvim", "vim", "nano", "vi"] {
        if std::process::Command::new("which")
            .arg(candidate)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
        {
            return candidate.to_string();
        }
    }
    "vi".to_string()
}

/// Launch the editor on `path`, inheriting stdio so it takes over the terminal.
/// The caller is responsible for suspending/resuming the TUI around this.
pub(super) fn open_in_editor(path: &std::path::Path) -> std::io::Result<()> {
    // $EDITOR may contain args (e.g. "code -w"); split on whitespace.
    let editor = editor_command();
    let mut parts = editor.split_whitespace();
    let bin = parts.next().unwrap_or("vi");
    let mut cmd = std::process::Command::new(bin);
    cmd.args(parts).arg(path);
    cmd.status().map(|_| ())
}

/// Edit `initial` in the user's $EDITOR via a tempfile, the same pattern
/// `git commit` uses for commit messages: write, shell out, block until
/// exit, read back. The caller is responsible for suspending/resuming the
/// TUI around this (same contract as `open_in_editor`).
///
/// Returns `Ok(None)` — treat as "no change" — if the editor exited
/// non-zero, or the file's trimmed content is unchanged (so simply saving
/// without editing, or trimming trailing-newline noise a lot of editors add
/// on write, never triggers a spurious update).
pub(super) fn edit_text_via_external_editor(initial: &str) -> std::io::Result<Option<String>> {
    let path = std::env::temp_dir().join(format!("sara-edit-{}.md", uuid::Uuid::new_v4()));
    std::fs::write(&path, initial)?;

    let editor = editor_command();
    let mut parts = editor.split_whitespace();
    let bin = parts.next().unwrap_or("vi");
    let status = std::process::Command::new(bin)
        .args(parts)
        .arg(&path)
        .status();

    let result = match status {
        Ok(s) if s.success() => match std::fs::read_to_string(&path) {
            Ok(edited) if edited.trim() != initial.trim() => Some(edited),
            _ => None,
        },
        _ => None,
    };
    let _ = std::fs::remove_file(&path);
    Ok(result)
}

/// The (target_kind, target_id) a comment would anchor to given the focused item.
pub(super) fn comment_target(
    d: &Detail,
    focus: &Option<Focusable>,
) -> (Option<String>, Option<String>) {
    match focus {
        Some(Focusable::Checklist(i)) => {
            if let Some(item) = d.checklist.get(*i) {
                let kind = if item.kind == db::STEP_KIND_ACCEPTANCE {
                    "acceptance"
                } else {
                    "step"
                };
                return (Some(kind.to_string()), Some(item.id.to_string()));
            }
            (None, None)
        }
        Some(Focusable::Anchor(i)) => {
            if let Some(anchor) = d.anchors.get(*i) {
                return (Some("anchor".to_string()), Some(anchor.path.clone()));
            }
            (None, None)
        }
        Some(Focusable::File(path)) => (Some("anchor".to_string()), Some(path.clone())),
        Some(Focusable::Note(i)) => {
            if let Some(note) = typed_notes(d).get(*i) {
                return (Some("note".to_string()), Some(note.id.to_string()));
            }
            (None, None)
        }
        Some(Focusable::Comment(i)) => {
            // Replying to a comment: anchor to the note itself.
            let comments: Vec<&crate::infrastructure::db::Annotation> = d
                .annotations
                .iter()
                .filter(|a| a.kind == "comment")
                .collect();
            if let Some(a) = comments.get(*i) {
                return (Some("note".to_string()), Some(a.id.to_string()));
            }
            (None, None)
        }
        _ => (None, None),
    }
}

/// Open feedback annotations anchored to the focused element (most recent first).
pub(super) fn feedback_for_focus<'a>(
    d: &'a Detail,
    focus: &Option<Focusable>,
) -> Vec<&'a crate::infrastructure::db::Annotation> {
    // When the cursor is ON a comment, r/x act on that comment directly.
    if let Some(Focusable::Comment(i)) = focus {
        let comments: Vec<&crate::infrastructure::db::Annotation> = d
            .annotations
            .iter()
            .filter(|a| a.kind == "comment")
            .collect();
        return comments
            .get(*i)
            .copied()
            .map(|a| vec![a])
            .unwrap_or_default();
    }
    let (tk, tid) = comment_target(d, focus);
    let mut v: Vec<&crate::infrastructure::db::Annotation> = d
        .annotations
        .iter()
        .filter(|a| {
            a.kind == "comment" && a.status == "open" && a.target_kind == tk && a.target_id == tid
        })
        .collect();
    v.reverse();
    v
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use std::sync::{Mutex, OnceLock};

    // Mutating $EDITOR/$VISUAL is process-wide state, so serialize the tests
    // that touch it (same pattern as infrastructure::config's HOME tests).
    static TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    fn test_lock() -> std::sync::MutexGuard<'static, ()> {
        TEST_LOCK.get_or_init(|| Mutex::new(())).lock().unwrap()
    }

    /// Write an executable shell script standing in for $EDITOR. Unix-only:
    /// Windows can't exec a shebang script directly, and `edit_text_via_external_editor`
    /// itself is platform-agnostic (just Command::new + args), so only the
    /// *test harness* needs the unix gate, not the feature.
    #[cfg(unix)]
    fn fake_editor(name: &str, body: &str) -> std::path::PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let path = std::env::temp_dir().join(format!(
            "sara-fake-editor-{name}-{}-{}",
            std::process::id(),
            uuid::Uuid::new_v4()
        ));
        let mut f = std::fs::File::create(&path).unwrap();
        writeln!(f, "#!/bin/sh").unwrap();
        writeln!(f, "{body}").unwrap();
        drop(f);
        let mut perms = std::fs::metadata(&path).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).unwrap();
        path
    }

    #[cfg(unix)]
    fn with_editor<F: FnOnce()>(script: &std::path::Path, f: F) {
        let _guard = test_lock();
        let old_editor = std::env::var("EDITOR").ok();
        let old_visual = std::env::var("VISUAL").ok();
        unsafe {
            std::env::set_var("EDITOR", script);
            std::env::remove_var("VISUAL");
        }
        f();
        unsafe {
            match old_editor {
                Some(v) => std::env::set_var("EDITOR", v),
                None => std::env::remove_var("EDITOR"),
            }
            match old_visual {
                Some(v) => std::env::set_var("VISUAL", v),
                None => std::env::remove_var("VISUAL"),
            }
        }
        let _ = std::fs::remove_file(script);
    }

    #[cfg(unix)]
    #[test]
    fn external_editor_returns_edited_content_when_changed() {
        let script = fake_editor("changed", "echo 'edited text' > \"$1\"");
        with_editor(&script, || {
            let result = edit_text_via_external_editor("original text").unwrap();
            assert_eq!(result, Some("edited text\n".to_string()));
        });
    }

    #[cfg(unix)]
    #[test]
    fn external_editor_returns_none_when_unchanged() {
        let script = fake_editor("unchanged", ": leave the file as-is");
        with_editor(&script, || {
            let result = edit_text_via_external_editor("same text").unwrap();
            assert_eq!(result, None);
        });
    }

    #[cfg(unix)]
    #[test]
    fn external_editor_returns_none_when_editor_exits_nonzero() {
        let script = fake_editor("fails", "echo 'should be ignored' > \"$1\"\nexit 1");
        with_editor(&script, || {
            let result = edit_text_via_external_editor("original").unwrap();
            assert_eq!(result, None);
        });
    }

    #[cfg(unix)]
    #[test]
    fn external_editor_cleans_up_its_tempfile() {
        let marker = std::env::temp_dir().join(format!(
            "sara-test-marker-{}-{}",
            std::process::id(),
            uuid::Uuid::new_v4()
        ));
        let script = fake_editor("cleanup", &format!("echo \"$1\" > {}", marker.display()));
        with_editor(&script, || {
            let _ = edit_text_via_external_editor("x").unwrap();
        });
        let tempfile_path = std::fs::read_to_string(&marker).unwrap().trim().to_string();
        assert!(!std::path::Path::new(&tempfile_path).exists());
        let _ = std::fs::remove_file(&marker);
    }

    fn link(url: &str) -> db::Link {
        db::Link {
            id: 1,
            url: url.to_string(),
            label: None,
            entry: chrono::Utc::now(),
        }
    }

    fn note(text: &str) -> db::Annotation {
        db::Annotation {
            id: 1,
            text: text.to_string(),
            entry: chrono::Utc::now(),
            kind: "comment".to_string(),
            author: "human".to_string(),
            target_kind: None,
            target_id: None,
            status: "open".to_string(),
            request_revision: false,
            resolved_by_run: None,
        }
    }

    #[test]
    fn pr_url_prefers_pr_link_over_issue_link() {
        let links = vec![
            link("https://github.com/o/r/issues/7"),
            link("https://github.com/o/r/pull/42"),
        ];
        assert_eq!(
            pr_url_from(&links, &[]),
            Some("https://github.com/o/r/pull/42".to_string())
        );
    }

    #[test]
    fn pr_url_falls_back_to_annotation_text() {
        let notes = vec![
            note("just a plain comment"),
            note("opened PR (https://github.com/o/r/pull/58), awaiting review."),
        ];
        assert_eq!(
            pr_url_from(&[], &notes),
            Some("https://github.com/o/r/pull/58".to_string())
        );
    }

    #[test]
    fn pr_url_is_none_without_any_pr_reference() {
        let links = vec![link("https://github.com/o/r/issues/7")];
        let notes = vec![note("see https://github.com/o/r/issues/7 for context")];
        assert_eq!(pr_url_from(&links, &notes), None);
    }
}