dv-review 0.95.18

A terminal diff viewer for reviewing GitHub PRs: Helix keys, rust-analyzer, inline review comments, and Claude Code reviews
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
//! Replacements: PRs Claude drafts locally to replace others (low-effort ones, say), kept
//! unpublished until you've reviewed them. Each is a branch `dv/replace-N` (N: the first PR it
//! replaces) in a worktree `<repo>-replace-N`, and a record in dv's directory,
//! `replacements/N.json`: the PRs it replaces, its base, and Claude's drafts of its title and
//! description and of the note closing the originals. A new PR (replacing nothing: what you
//! asked for) is the same, as `dv/new-K` in `<repo>-new-K`, its record keeping your request.
use anyhow::{Context, Result};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};

/// Something you asked of a replacement's drafts (`a` on one, or for a redraft).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Request {
    pub text: String,
    /// What you want of Claude: `"ask"` (an answer; nothing changed), `"change"` (made in its
    /// drafts or code); empty: as it reads.
    pub want: String,
    /// The draft it's about: `"description"`, `"closing note"`; empty: the whole.
    pub on: String,
    /// Claude's answer: what it did about it, or (a question) its answer. Claude writes it.
    pub answer: String,
}

/// What dv puts for an answer when a redraft took a request in without one (Claude didn't
/// say): done, not to ask again. Shown as dv's note, not as Claude's.
pub const NO_ANSWER: &str = "_(redrafted with it)_";

impl Request {
    /// A redraft has taken it in: Claude has answered it (one rule, whatever Claude did to the
    /// record's order).
    pub fn done(&self) -> bool {
        !self.answer.trim().is_empty()
    }
}

/// A PR a replacement replaces, as it was when the replacement was drafted.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Original {
    pub number: u64,
    pub title: String,
    pub author: String,
    pub url: String,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Record {
    /// The first PR it replaces: its name (`dv/replace-N`, `<repo>-replace-N`, `N.json`).
    pub id: u64,
    pub replaces: Vec<Original>,
    /// The branch it's based on (the originals'), on origin.
    pub base: String,
    /// Claude's drafts: the PR's title and description, and the note for closing the originals.
    pub title: String,
    pub body: String,
    pub closing_note: String,
    /// The Claude Code session that drafted it, to carry on in.
    pub session: String,
    /// Its PR, once published (a draft).
    pub published: Option<u64>,
    /// The originals closed (with the note) since.
    pub closed: Vec<u64>,
    /// A new PR's: what you asked it to do (a replacement's is what it replaces).
    pub task: String,
    /// What you've asked of its drafts, oldest first.
    pub asks: Vec<Request>,
    /// How many of `asks` the draft under way was given (the rest wait for the next).
    pub taking: usize,
    /// When its last draft (that went through) read the originals' reviews (unix seconds; 0:
    /// not known): reviews changed since go to a redraft.
    pub drafted_at: u64,
}

impl Record {
    /// What to draft it again from: the PRs it replaces, or (a new PR) itself.
    pub fn ids(&self) -> Vec<u64> {
        match self.replaces.is_empty() {
            true => vec![self.id],
            false => self.replaces.iter().map(|o| o.number).collect(),
        }
    }

    /// Claude has drafted it (so drafting it again carries on, in the same session).
    pub fn drafted(&self) -> bool {
        !self.title.is_empty() || !self.body.is_empty()
    }

    /// What Claude's doing on it, from any dv: its draft (`draft`: "drafting"), a run or a pane
    /// on it from its view; its claims (`claude::rep_key`), the one rule.
    pub fn at_work(&self) -> Option<String> {
        crate::claude::at_work(&crate::claude::rep_key(self.id), None, None)
    }
}

/// New PRs' ids start here (`new_id`), above any PR number: new PR K is `NEW + K`.
const NEW: u64 = 1 << 40;

/// Whether `id` is a new PR's (not a replacement's).
pub fn is_new(id: u64) -> bool {
    id >= NEW
}

/// Its name: its branch's (`dv/<name>`) and its worktree's (`<repo>-<name>`).
pub fn name(id: u64) -> String {
    match is_new(id) {
        true => format!("new-{}", id - NEW),
        false => format!("replace-{id}"),
    }
}

/// How it's said: "#N" (the PR a replacement replaces first) or "new K".
pub fn shown(id: u64) -> String {
    match is_new(id) {
        true => format!("new {}", id - NEW),
        false => format!("#{id}"),
    }
}

/// What it is, in words: "the replacement of #N" or "new PR K".
pub fn label(id: u64) -> String {
    match is_new(id) {
        true => format!("new PR {}", id - NEW),
        false => format!("the replacement of #{id}"),
    }
}

pub fn branch(id: u64) -> String {
    format!("dv/{}", name(id))
}

/// The replacement (or new PR) checked out here, by its branch.
pub fn current() -> Option<u64> {
    let b = crate::diff::git(&["branch", "--show-current"]).ok()?;
    let b = b.trim();
    match b.strip_prefix("dv/new-") {
        Some(k) => k.parse::<u64>().ok().map(|k| NEW + k),
        None => b.strip_prefix("dv/replace-")?.parse().ok(),
    }
}

/// The replacement PR `pr` is (published as it), however it's checked out; no PR (GitHub not
/// asked, or not answering): the one checked out here, by its branch.
pub fn here(pr: Option<u64>) -> Option<Record> {
    match pr {
        Some(n) => all().into_iter().find(|r| r.published == Some(n)),
        None => load(current()?).ok(),
    }
}

/// PR `n`'s replacement: its own (of `n` first), else one of several it's in.
pub fn of(n: u64) -> Option<Record> {
    let all: Vec<_> = all().into_iter().filter(|r| r.ids().contains(&n)).collect();
    all.iter().find(|r| r.id == n).or(all.first()).cloned()
}

/// What a draft asked for `prs` drafts (its id first): one any of them is replaced by
/// already is redrafted (with them all). Asked where the id's chosen (what's said, what's
/// busy, its news).
pub fn target(prs: &[u64]) -> Vec<u64> {
    match prs.iter().find_map(|&n| of(n)) {
        Some(r) => std::iter::once(r.id).chain(prs.iter().copied().filter(|&n| n != r.id)).collect(),
        None => prs.to_vec(),
    }
}

/// Whether `prs` are one draft's (a PR no draft replaces is its own): drafted as it, not
/// grouped first.
pub fn one_draft(prs: &[u64]) -> bool {
    let mut ids: Vec<u64> = prs.iter().map(|&n| target(&[n])[0]).collect();
    ids.sort();
    ids.dedup();
    ids.len() <= 1
}

/// Why the draft of `prs` (as `target` has them, its id first) isn't drafted: published, it's
/// a PR like any (Claude asked there); a PR in it is another draft's (one draft each: what it
/// replaces is closed once, by one).
pub fn refused(prs: &[u64]) -> Option<String> {
    let id = *prs.first()?;
    if let Some(n) = load(id).ok().and_then(|r| r.published) {
        return Some(format!("{} is published as #{n}: ask Claude on that PR", label(id)));
    }
    let others = all().into_iter().filter(|r| r.id != id);
    others.into_iter().find_map(|o| prs.iter().find(|n| o.ids().contains(n)).map(|n| format!("#{n} is in {} already: one draft each", label(o.id))))
}

/// Published as PR `n`: Claude's review of the draft (and its session) moved to the PR's, for
/// dv on the PR to carry on with. Once: not over one the PR has.
pub fn adopt_review(n: u64) {
    if let Some(r) = here(Some(n))
        && let (Ok(from), Ok(to)) = (crate::claude::branch_review(&branch(r.id)), crate::claude::path(Some(n)))
    {
        _ = crate::claude::move_review(&from, &to);
    }
}

/// The next new PR's id: one past the last there's a record of.
pub fn new_id() -> u64 {
    all().iter().map(|r| r.id).filter(|&id| is_new(id)).max().map_or(NEW + 1, |m| m + 1)
}

fn dir() -> Result<PathBuf> {
    Ok(crate::claude::dv_dir()?.join("replacements"))
}

pub fn path(id: u64) -> Result<PathBuf> {
    Ok(dir()?.join(format!("{id}.json")))
}

pub fn load(id: u64) -> Result<Record> {
    let p = path(id)?;
    parse(id, &std::fs::read_to_string(&p).with_context(|| format!("reading {}", p.display()))?)
}

fn parse(id: u64, text: &str) -> Result<Record> {
    let v: Value = serde_json::from_str(text)?;
    let s = |v: &Value| v.as_str().unwrap_or("").to_owned();
    let replaces = v["replaces"].as_array().map(Vec::as_slice).unwrap_or(&[]);
    Ok(Record {
        id,
        replaces: replaces
            .iter()
            .map(|o| Original { number: o["number"].as_u64().unwrap_or(0), title: s(&o["title"]), author: s(&o["author"]), url: s(&o["url"]) })
            .collect(),
        base: s(&v["base"]),
        title: s(&v["title"]),
        body: s(&v["body"]),
        closing_note: s(&v["closing_note"]),
        session: s(&v["session"]),
        published: v["published"].as_u64(),
        closed: v["closed"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(),
        task: s(&v["task"]),
        asks: v["asks"].as_array().into_iter().flatten().map(|a| Request {
                    text: s(&a["text"]),
                    want: s(&a["want"]),
                    on: s(&a["on"]),
                    // (Records from before answers: taken in, unanswered.)
                    answer: match (s(&a["answer"]), a["done"] == true) {
                        (ans, true) if ans.trim().is_empty() => NO_ANSWER.into(),
                        (ans, _) => ans,
                    },
                }).collect(),
        taking: v["taking"].as_u64().unwrap_or(0) as usize,
        drafted_at: v["drafted_at"].as_u64().unwrap_or(0),
    })
}

fn to_json(r: &Record) -> String {
    let replaces: Vec<Value> =
        r.replaces.iter().map(|o| json!({ "number": o.number, "title": o.title, "author": o.author, "url": o.url })).collect();
    let v = json!({
        "replaces": replaces, "base": r.base, "title": r.title, "body": r.body,
        "closing_note": r.closing_note, "session": r.session, "published": r.published, "closed": r.closed,
        "task": r.task,
        "asks": r.asks.iter().map(|a| json!({ "text": a.text, "want": a.want, "on": a.on, "answer": a.answer })).collect::<Vec<_>>(), "taking": r.taking, "drafted_at": r.drafted_at,
    });
    serde_json::to_string_pretty(&v).unwrap_or_default() + "\n"
}

/// Change replacement `id`'s record as it is now (Claude may have written to it, another dv
/// asked for something): load, `f`, save, quickly, so nothing written meanwhile is lost.
/// `f`'s answer, and the record as saved.
fn update<T>(id: u64, f: impl FnOnce(&mut Record) -> Result<T>) -> Result<(T, Record)> {
    let mut r = match path(id)?.exists() {
        true => load(id)?,
        false => Record { id, ..Record::default() },
    };
    let out = f(&mut r)?;
    save(&r)?;
    Ok((out, r))
}

pub fn save(r: &Record) -> Result<()> {
    let p = path(r.id)?;
    std::fs::create_dir_all(p.parent().context("no dir")?)?;
    Ok(std::fs::write(p, to_json(r))?)
}

/// When any replacement's record last changed (or one came or went), to notice it.
pub fn changed() -> Option<std::time::SystemTime> {
    let d = dir().ok()?;
    let entries = std::fs::read_dir(&d).ok()?.flatten().filter_map(|e| e.metadata().ok()?.modified().ok());
    entries.chain(std::fs::metadata(&d).ok()?.modified().ok()).max()
}

/// Every replacement in this repo, by number.
pub fn all() -> Vec<Record> {
    let Ok(entries) = dir().and_then(|d| Ok(std::fs::read_dir(d)?)) else { return vec![] };
    let mut out: Vec<Record> = entries
        .flatten()
        .filter_map(|e| e.file_name().to_str()?.strip_suffix(".json")?.parse().ok())
        .filter_map(|id| load(id).ok())
        .collect();
    out.sort_by_key(|r| r.id);
    out
}

/// Set up a replacement of `prs` (the first names it) from the repo at `root`: what it replaces
/// and its base in its record (`draft` has marked it, and sets its session), and its branch,
/// from the originals' base, in its worktree. Returns the worktree.
fn prepare(asked: &[u64], root: &Path) -> Result<PathBuf> {
    let id = *asked.first().context("no PR to replace")?;
    // All it replaces already (drafted or not), and what's asked now with them (a redraft
    // asked from one of them doesn't drop the others).
    let mut prs = load(id).ok().map_or(vec![], |r| r.ids());
    prs.extend(asked.iter().filter(|n| !prs.contains(n)).collect::<Vec<_>>());
    let mut originals = vec![];
    let mut bases: Vec<(u64, String)> = vec![];
    for &n in &prs {
        let p = crate::gh::pr(Some(n))?;
        bases.push((n, p.base));
        originals.push(Original { number: n, title: p.title, author: p.author, url: p.url });
    }
    // One replacement can only target one branch.
    if let Some((n, b)) = bases.iter().find(|b| b.1 != bases[0].1) {
        anyhow::bail!("#{} targets {}, #{n} targets {b}: one replacement can't replace both", bases[0].0, bases[0].1);
    }
    let base = bases.first().map(|b| b.1.clone()).unwrap_or_default();
    let (old, r) = update(id, |r| {
        let old = std::mem::replace(&mut r.base, base);
        r.replaces = originals;
        Ok(old)
    })?;
    let dir = worktree(&r, root)?;
    // Carrying on: from the base as it is now (the originals retargeted: from the old one's,
    // its commits not taken along), if that goes cleanly; else `Space g` rebases it there.
    let from = (!old.is_empty() && old != r.base).then_some(old);
    _ = rebase(&r, &dir, from.as_deref());
    Ok(dir)
}

/// Draft `r`'s worktree from the repo at `root`: there, or made again on its branch (its
/// work), or on a new branch from its base.
pub fn worktree(r: &Record, root: &Path) -> Result<PathBuf> {
    let git = |args: &[&str]| crate::diff::git(&[&["-C", &root.to_string_lossy()], args].concat());
    let dir = crate::worktree_dir_named(root, &name(r.id))?;
    if dir.exists() {
        crate::ensure_worktree_of(&dir, root)?;
        return Ok(dir);
    }
    // (One whose directory was deleted, not removed: still registered, in the way.)
    _ = git(&["worktree", "prune"]);
    _ = git(&["fetch", "-q", &crate::diff::remote(), &r.base]);
    let (b, d) = (branch(r.id), dir.to_string_lossy().into_owned());
    match git(&["rev-parse", "--verify", "-q", &format!("refs/heads/{b}")]) {
        Ok(_) => git(&["worktree", "add", &d, &b])?,
        Err(_) => git(&["worktree", "add", "-b", &b, &d, &crate::diff::remote_branch(&r.base)])?,
    };
    Ok(dir)
}

/// Set up a new PR doing `task` from the repo at `root`: its record, and its branch from the
/// repo's default branch (on its remote), in its worktree. Its id.
pub fn create_new(task: &str, root: &Path) -> Result<u64> {
    let git = |args: &[&str]| crate::diff::git(&[&["-C", &root.to_string_lossy()], args].concat());
    let base = crate::diff::default_branch();
    // (Not one whose branch or worktree is still there: an earlier new PR's, its record gone.)
    let taken = |id: u64| {
        let dir = crate::worktree_dir_named(root, &name(id)).is_ok_and(|d| d.exists());
        dir || git(&["rev-parse", "--verify", "-q", &format!("refs/heads/{}", branch(id))]).is_ok()
    };
    let id = (new_id()..).find(|&id| !taken(id)).context("no new PR id free")?;
    let r = Record { id, base, task: task.trim().to_owned(), ..Record::default() }; // its session: `draft`
    worktree(&r, root)?;
    save(&r)?;
    Ok(id)
}

/// A new PR's worktree, to draft it (again): its branch brought up to its base.
fn prepare_new(id: u64, root: &Path) -> Result<PathBuf> {
    let r = load(id)?;
    let dir = worktree(&r, root)?;
    _ = rebase(&r, &dir, None); // carrying on: from its base as it is now, if that goes cleanly
    Ok(dir)
}

/// Bring replacement `r`'s branch (in `dir`) up to its base on origin: fetch, then rebase onto
/// it (from base `from`, if it was another). A rebase that conflicts is undone, and said so.
pub fn rebase(r: &Record, dir: &Path, from: Option<&str>) -> Result<()> {
    let git = |args: &[&str]| crate::diff::git(&[&["-C", &dir.to_string_lossy()], args].concat());
    let onto = crate::diff::remote_branch(&r.base);
    git(&["fetch", "-q", &crate::diff::remote(), &r.base])?;
    // Its base was another (`from`): only its own commits, from where it left that one.
    let fork = from.and_then(|f| git(&["merge-base", "HEAD", &crate::diff::remote_branch(f)]).ok()).map(|f| f.trim().to_owned());
    let res = match &fork {
        Some(f) => git(&["rebase", "-q", "--onto", &onto, f]),
        None => git(&["rebase", "-q", &onto]),
    };
    if let Err(e) = res {
        _ = git(&["rebase", "--abort"]);
        anyhow::bail!("it doesn't rebase cleanly onto {onto} ({e:#}): Space g → Rebase onto {onto}, Claude resolves the conflicts");
    }
    Ok(())
}

/// Which of Claude's reviews of the originals a draft's prompt carries: all (a first draft: a
/// new session), or those changed since its last draft ended (a redraft: its session has the
/// rest), none if that's not known.
#[derive(Clone)]
pub enum Reviews {
    All,
    /// Changed since then, and the originals new to it (theirs not seen at all).
    Since(Option<std::time::SystemTime>, Vec<u64>),
}

/// Claude's reviews of the PRs `r` replaces, from dv (its own and the user's words, not the
/// PRs'), for a replacement to start from what they found: each as of the commit it reviewed.
fn reviews_of(r: &Record, which: Reviews) -> String {
    let changed = |n: u64, p: &std::path::Path| match &which {
        Reviews::All => true,
        Reviews::Since(_, new) if new.contains(&n) => true,
        Reviews::Since(t, _) => t.as_ref().copied().zip(std::fs::metadata(p).and_then(|m| m.modified()).ok()).is_some_and(|(t, m)| m > t),
    };
    let reviews: Vec<String> = r
        .replaces
        .iter()
        .filter_map(|o| {
            let path = crate::claude::path(Some(o.number)).ok().filter(|p| changed(o.number, p))?;
            let review = crate::claude::load(&path).ok()??;
            let text = crate::claude::review_brief(&review);
            let head = review.head.get(..8).unwrap_or(&review.head);
            (!text.is_empty()).then(|| format!("<review pr=\"{}\" of=\"{head}\">\n{text}\n</review>", o.number))
        })
        .collect();
    match reviews.is_empty() {
        true => String::new(),
        false => format!(
            "\n\nYour reviews in dv of what it replaces{}, with the user's replies (what you and the user found wrong: \
             start from that, and make the changes the user asked for there; their questions were answered there, \
             not asks of the draft; each review is of the commit it names, which may have moved on since, so check \
             its lines against `gh pr diff`):\n{}",
            if matches!(which, Reviews::All) { "" } else { " (changed since your last draft: as they are now)" },
            reviews.join("\n")
        ),
    }
}

/// What Claude is asked, to draft (or redraft) replacement `r`. Your notes on the repo come
/// with it, to read: a draft reads untrusted PRs, so it gets no access to them (nor to dv's
/// other files), only to its record.
pub fn prompt(r: &Record, extra: &str, reviews: Reviews) -> String {
    let prs: Vec<String> = r.replaces.iter().map(|o| format!("#{}", o.number)).collect();
    let now = crate::claude::now();
    let notes = crate::claude::notes_path().ok().and_then(|p| std::fs::read_to_string(p).ok()).unwrap_or_default();
    let notes = match notes.trim() {
        "" => String::new(),
        n => format!("\n\nThe user's notes on this repo (read-only here; follow them):\n<notes>\n{n}\n</notes>"),
    };
    let p = match is_new(r.id) {
        // What it's to do is the user's request (in `dv replace-info` too); `extra`, if any, is
        // more, for carrying on.
        true => format!(
            "Use the dv-review skill to draft a new PR doing what the user asks (its section 6: \"Draft a replacement or a new PR\"). \
             First run `dv replace-info`. (It's {now} now.){notes}\n\nThe user asks:\n{}",
            r.task
        ),
        false => format!(
            "Use the dv-review skill to draft a replacement for PR {} (its section 6: \"Draft a replacement or a new PR\"). \
             First run `dv replace-info`. (It's {now} now.){notes}{}",
            prs.join(", "),
            reviews_of(r, reviews)
        ),
    };
    // What you asked of its drafts that no redraft has taken in yet: in the record, to answer.
    let want = |w: &str| match w {
        "ask" => " (ask: answer it; change nothing)",
        "change" => " (change: make it)",
        _ => "",
    };
    let asks: Vec<String> = r.asks.iter().enumerate().filter(|(_, a)| !a.done()).map(|(i, a)| format!("`asks[{i}]`{}: {}", want(&a.want), a.text.trim())).collect();
    let p = match asks.is_empty() {
        true => p,
        false => format!(
            "{p}\n\nThe user asks of your drafts (the record's `asks`): do what each says it wants (ask: only answer it, \
             changing nothing; change: make the change; neither said: as it reads), and write what you did, or your answer, \
             in a sentence or few, in its `\"answer\"` (in the record; the user reads it beside your drafts).\n\n{}",
            asks.join("\n\n")
        ),
    };
    crate::claude::with_instructions(&p, extra)
}

/// Whether what you write for draft `id` is asked of it (as its drafts' asks, or a new PR's
/// instructions with its task), not your instructions for replacements' first drafts.
pub fn redrafts(id: u64) -> bool {
    is_new(id) || drafted(id)
}

/// Whether replacement `id` has drafts (`Record::drafted`).
pub fn drafted(id: u64) -> bool {
    load(id).is_ok_and(|r| r.drafted())
}

/// Ask Claude about replacement `id`'s drafts (`on`: the one it's about, or ""; `want`: see
/// `Request`): kept in its record (shown beside it), for its next redraft to take in.
pub fn ask(id: u64, text: &str, on: &str, want: &str) -> Result<()> {
    update(id, |r| {
        r.asks.push(Request { text: text.trim().to_owned(), on: on.to_owned(), want: want.to_owned(), ..Request::default() });
        Ok(())
    })
    .map(drop)
}

/// Have Claude draft a replacement for `prs` with a dv of its own (`dv replace`), in the
/// background: it carries on if this dv quits. Its output goes to a log in the temp dir.
pub fn spawn(prs: &[u64]) -> Result<()> {
    use std::os::unix::process::CommandExt;
    let log = std::env::temp_dir().join(format!("dv-replace-{}.log", prs[0]));
    std::process::Command::new(crate::self_exe())
        .arg("replace")
        .args(prs.iter().map(u64::to_string))
        .stdin(std::process::Stdio::null())
        .stdout(std::fs::File::create(&log)?)
        .stderr(std::fs::File::create(log.with_extension("err"))?)
        .process_group(0) // not this terminal's: closing it doesn't stop the draft
        .spawn()?;
    Ok(())
}

/// The directory a draft may write to (its record): `--add-dir`.
pub fn writable() -> Result<PathBuf> {
    dir()
}

/// Draft replacement `prs` with Claude, in its worktree, in the foreground of this thread:
/// what it took ("12 turns, $0.40"). `extra`: what you wrote for it just now: your
/// instructions for a first draft (none: your last ones for replacements); for one drafted
/// already, asked of its drafts (as `ask`).
pub fn draft(prs: &[u64], root: &Path, extra: &str, prepared: impl FnOnce()) -> Result<String> {
    let prs = &target(prs)[..];
    let id = *prs.first().context("no PR to replace")?;
    // Under way first, before the slow setting up: others (dv list, another dv) see it, and
    // don't start another. Its claim, held while it drafts (this process's: let go as it ends,
    // however); what's read of it after (no other draft's between).
    let _claim = crate::claude::claim(&crate::claude::rep_key(id), "drafting", None)?.map_err(|w| anyhow::anyhow!("Claude is {w} on {} already", label(id)))?;
    let existed = path(id)?.exists();
    anyhow::ensure!(existed || !is_new(id), "no new PR {}", label(id));
    // When its last draft ended: reviews of the originals changed since go to a redraft. (Not
    // said, a record from before: the last time it was written.)
    let last = match load(id).map(|r| r.drafted_at).unwrap_or(0) {
        0 => std::fs::metadata(path(id)?).and_then(|m| m.modified()).ok(),
        s => Some(std::time::UNIX_EPOCH + std::time::Duration::from_secs(s)),
    };
    let mut added = vec![];
    let ((first, fresh), _) = update(id, |r| {
        // (Checked as it's marked: nothing written for one refused.)
        if let Some(why) = refused(prs) {
            anyhow::bail!(why);
        }
        // What it replaces, said at once (`prepare` fills them in): another draft asked
        // meanwhile sees them.
        for &n in prs.iter().filter(|_| !is_new(id)) {
            if !r.replaces.iter().any(|o| o.number == n) {
                r.replaces.push(Original { number: n, ..Original::default() });
                added.push(n);
            }
        }
        if r.drafted() && !extra.trim().is_empty() {
            r.asks.push(Request { text: extra.trim().to_owned(), ..Request::default() });
        }
        // A first draft: a session of its own (one that failed before may have made the last
        // one, which Claude Code won't start again).
        let first = !r.drafted();
        // A session of its own afresh, too, once Claude Code no longer has its last one (it
        // cleans old ones up): carrying on there fails, every time.
        let fresh = first || !crate::claude::session_exists(&r.session);
        if fresh {
            r.session = crate::claude::new_session_id();
        }
        Ok((first, fresh))
    })?;
    // Under way (claimed, marked): then its turn among Claude's runs from this dv (two at a
    // time), waited for.
    let _slot = crate::batch::Slot::take();
    let saved;
    let extra = match extra.trim() {
        "" if first && !is_new(id) => {
            saved = crate::claude::instructions("replace");
            saved.as_str()
        }
        e => e,
    };
    let (mut set_up, mut started) = (false, 0);
    // What it was given of what you asked (by text and draft: Claude may reorder the record).
    let mut given: Vec<(String, String)> = vec![];
    // (A panic in it: a failure, the record's mark off all the same, not "drafting" for good.)
    let res = crate::batch::guarded(|| {
        let dir = match prs {
            [id] if is_new(*id) => prepare_new(*id, root)?,
            _ => prepare(prs, root)?,
        };
        set_up = true;
        // What you've asked of it so far goes in its prompt: those are what it takes in.
        let (r, _) = update(id, |r| {
            r.taking = r.asks.len();
            Ok(r.clone())
        })?;
        // (The reviews it's given are read now: changes after go to the next.)
        started = crate::claude::now_secs() as u64;
        given = r.asks.iter().filter(|a| !a.done()).map(|a| (a.text.clone(), a.on.clone())).collect();
        // (A new session has seen none of the reviews.)
        let which = if fresh { Reviews::All } else { Reviews::Since(last, added.clone()) };
        run_claude(&r, &dir, fresh, if first { extra } else { "" }, which, prepared)
    });
    // Claude has written to the record meanwhile (its answers): the mark comes off; a change
    // it was given and made (it finished) without saying so is done all the same, not asked
    // again and again.
    _ = update(id, |now| {
        now.taking = 0;
        if res.is_ok() {
            now.drafted_at = started;
        }
        // Not set up (a PR not there, or on another base): what it was to take in, not.
        if !set_up {
            now.replaces.retain(|o| !added.contains(&o.number));
        }
        let was_given = |a: &Request| given.iter().any(|(t, on)| *t == a.text && *on == a.on);
        for a in now.asks.iter_mut().filter(|a| res.is_ok() && a.want != "ask" && !a.done() && was_given(a)) {
            a.answer = NO_ANSWER.into();
        }
        Ok(())
    });
    // Not set up (PRs on different bases, one that isn't there): no record left of it.
    if !set_up && !existed {
        _ = std::fs::remove_file(path(id)?);
    }
    res
}

/// `first`: its first draft (a new session; else it carries on in its own).
fn run_claude(r: &Record, dir: &Path, first: bool, extra: &str, which: Reviews, prepared: impl FnOnce()) -> Result<String> {
    prepared();
    let session = match first {
        true => ["--session-id".to_owned(), r.session.clone()],
        false => ["--resume".to_owned(), r.session.clone()],
    };
    let log = std::env::temp_dir().join(format!("dv-claude-replace-{}-{}.log", std::process::id(), r.id));
    let st = crate::claude::claude_command(crate::claude::Work::Replace, &prompt(r, extra, which), dir, &session, crate::claude::REPLACE_TOOLS, Some(&writable()?))
        .stdin(std::process::Stdio::null())
        .stdout(std::fs::File::create(&log)?)
        .stderr(std::fs::File::create(log.with_extension("err"))?)
        .status()
        .context("is Claude Code (`claude`) installed?")?;
    let v: Value = std::fs::read_to_string(&log).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
    if !st.success() || v["is_error"] != false {
        anyhow::bail!("Claude stopped ({st}): see {}", log.display());
    }
    Ok(format!("{} turns, ${:.2}", v["num_turns"].as_u64().unwrap_or(0), v["total_cost_usd"].as_f64().unwrap_or(0.0)))
}

/// The remote replacement branches are pushed to (`git config dv.replaceRemote`): not origin,
/// but yours (a fork). `None` until it's set.
pub fn remote() -> Option<String> {
    crate::diff::git(&["config", "--get", "dv.replaceRemote"]).ok().map(|r| r.trim().to_owned()).filter(|r| !r.is_empty())
}

pub fn set_remote(name: &str) -> Result<()> {
    crate::diff::git(&["config", "dv.replaceRemote", name]).map(drop)
}

/// The remotes it could be (all but origin).
pub fn remote_choices() -> Vec<(String, String)> {
    let names = crate::diff::git(&["remote"]).unwrap_or_default();
    names
        .lines()
        .filter(|n| *n != crate::diff::remote())
        .map(|n| (n.to_owned(), crate::diff::git(&["remote", "get-url", n]).unwrap_or_default().trim().to_owned()))
        .collect()
}

/// The GitHub owner of a remote's repo, from its URL (`git@github.com:owner/repo.git`,
/// `https://github.com/owner/repo`).
fn owner(url: &str) -> Option<&str> {
    let path = url.split_once("github.com")?.1.trim_start_matches([':', '/']);
    path.split('/').next().filter(|o| !o.is_empty())
}

/// Publish replacement `r` (checked out in `dir`) as a draft PR (ready for review once CI
/// passes), with `title` and `body` (what
/// you made of Claude's drafts): rebase it onto its base as it is on origin now, push it to
/// your replacements remote, then open the PR (from there, into origin's repo). Its number.
pub fn publish(r: &mut Record, dir: &Path, title: &str, body: &str, own: Option<&str>) -> Result<u64> {
    // Not under Claude at it (a redraft from another dv, since you asked; a pane, but `own`'s
    // session's, the asker's to mind): its claim, held while publishing; the record as it is now.
    let _claim = crate::claude::claim(&crate::claude::rep_key(r.id), "publishing it", own)?.map_err(|w| anyhow::anyhow!("Claude is {w} on {}: publish it once it's done", label(r.id)))?;
    *r = load(r.id)?;
    anyhow::ensure!(r.published.is_none(), "already published, as #{}", r.published.unwrap_or(0));
    let remote = remote().context("no remote for replacement branches (dv.replaceRemote)")?;
    rebase(r, dir, None)?;
    let b = branch(r.id);
    let url = crate::diff::git(&["remote", "get-url", &remote])?;
    let owner = owner(url.trim()).with_context(|| format!("{remote} ({}) isn't a GitHub repo", url.trim()))?;
    crate::diff::git(&["-C", &dir.to_string_lossy(), "push", "-q", "-f", "-u", &remote, &format!("{b}:refs/heads/{b}")])?;
    let n = crate::gh::create_pr(&r.base, &format!("{owner}:{b}"), title, body)?;
    *r = update(r.id, |r| {
        (r.published, r.title, r.body) = (Some(n), title.to_owned(), body.to_owned());
        Ok(())
    })?
    .1;
    Ok(n)
}

/// The closing note, with the replacement's PR where Claude left `{replacement}` (or, if it
/// didn't, said at the end).
pub fn note(r: &Record) -> String {
    let link = r.published.map_or("the replacement".to_owned(), |n| format!("#{n}"));
    match r.closing_note.contains("{replacement}") {
        true => r.closing_note.replace("{replacement}", &link),
        false => format!("{}\n\nSuperseded by {link}.", r.closing_note.trim_end()).trim_start().to_owned(),
    }
}

/// Close the originals not closed yet, each with `note`: what was closed (an error stops at
/// the PR it's about, keeping those before).
pub fn close_originals(r: &mut Record, note: &str) -> Result<String> {
    // (Its PR closed, not merged: it replaces nothing now, "superseded by" it would be false.)
    if let Some(n) = r.published
        && crate::gh::pr_state(n).ok().flatten().as_deref() == Some("CLOSED")
    {
        anyhow::bail!("#{n} (it was published as) is closed: what it replaces isn't superseded");
    }
    let (mut done, mut already) = (vec![], vec![]);
    let list = |ns: &[u64]| ns.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ");
    for n in r.replaces.iter().map(|o| o.number).filter(|n| !r.closed.contains(n)).collect::<Vec<_>>() {
        // (Merged or closed already, by someone else: done, not closed again; gh can't close a
        // merged one.)
        match crate::gh::pr_state(n).ok().flatten().is_none_or(|s| s == "OPEN") {
            true => match crate::gh::close(n, Some(note)) {
                Ok(_) => done.push(n),
                Err(e) if done.is_empty() => return Err(e.context(format!("closing #{n}"))),
                Err(e) => return Err(e.context(format!("closing #{n} ({} closed, with the note)", list(&done)))),
            },
            false => already.push(n),
        }
        // (Into the record as it is now: what's been written to it meanwhile stays.)
        *r = update(r.id, |r| {
            if !r.closed.contains(&n) {
                r.closed.push(n);
            }
            Ok(())
        })?
        .1;
    }
    Ok(match (done.is_empty(), already.is_empty()) {
        (false, true) => format!("closed {}, with the note", list(&done)),
        (true, false) => format!("{} closed or merged already", list(&already)),
        (false, false) => format!("closed {}, with the note ({} closed or merged already)", list(&done), list(&already)),
        (true, true) => "nothing to close".into(),
    })
}

/// Remove replacement `id`: its worktree (not with local changes) and its record. Its branch
/// stays, renamed, in case there's something on it you want.
pub fn remove(id: u64, root: &Path) -> Result<String> {
    // Not while Claude's at it (a draft, a run, a pane): its claim, held while removing.
    let _claim = crate::claude::claim(&crate::claude::rep_key(id), "removing it", None)?.map_err(|w| anyhow::anyhow!("Claude is {w} on {}: remove it once it's done", label(id)))?;
    let dir = crate::worktree_dir_named(root, &name(id))?;
    // Nor under Claude at work in its checkout on any key (published, its PR's).
    if let Some(w) = crate::claude::at_work_in(&dir, None) {
        anyhow::bail!("Claude is {w} in {}: remove it once it's done", dir.display());
    }
    if dir.exists() {
        crate::ensure_worktree_of(&dir, root)?;
        crate::diff::git(&["-C", &root.to_string_lossy(), "worktree", "remove", &dir.to_string_lossy()]).map_err(|e| {
            match format!("{e:#}").contains("modified or untracked") {
                true => e.context(format!("{} has local changes: commit or discard them first", dir.display())),
                false => e,
            }
        })?;
    }
    _ = std::fs::remove_file(path(id)?);
    // Its branch kept under another name: a draft of it again starts afresh, from its base,
    // not on what was removed.
    let (b, kept) = (branch(id), format!("{}-removed-{}", branch(id), crate::claude::now_secs()));
    if crate::diff::git(&["-C", &root.to_string_lossy(), "branch", "-m", &b, &kept]).is_err() {
        return Ok(format!("removed {}", label(id)));
    }
    // (Claude's review of it, its session, what you saw: with the branch, not left for the next
    // draft by this name.)
    if let (Ok(from), Ok(to)) = (crate::claude::branch_review(&b), crate::claude::branch_review(&kept)) {
        _ = crate::claude::move_review(&from, &to);
    }
    Ok(format!("removed {}; kept its branch as {kept} (`git branch -D {kept}` deletes it)", label(id)))
}

/// The issue a new PR's task is to fix: its first line's "Fix #N" (as an issue's "Draft a PR
/// fixing it" writes it).
pub fn fixes(task: &str) -> Option<u64> {
    let first = task.lines().next()?.trim();
    let rest = first.get(..5).filter(|p| p.eq_ignore_ascii_case("fix #")).map(|_| &first[5..])?;
    rest.split(|c: char| !c.is_ascii_digit()).next()?.parse().ok()
}

#[test]
fn a_drafts_task_names_the_issue_it_fixes() {
    assert_eq!(fixes("Fix #2217: KeychainTxOutIndex returns stale entries\n\nFrom triaging it: …"), Some(2217));
    assert_eq!(fixes("fix #12"), Some(12));
    assert_eq!(fixes("Refactor the index (see #12)"), None);
    assert_eq!(fixes(""), None);
}

/// The issues and PRs `text` names (`#N`), once each, in order.
fn mentioned(text: &str) -> Vec<u64> {
    let mut out = vec![];
    for w in text.split(|c: char| !c.is_ascii_alphanumeric() && c != '#') {
        if let Some(n) = w.strip_prefix('#').and_then(|n| n.parse().ok()).filter(|n| !out.contains(n)) {
            out.push(n);
        }
    }
    out
}

#[test]
fn issues_mentioned() {
    assert_eq!(mentioned("Fix #9: the panic (see #12, #9 and x#3; not #a)"), [9, 12]);
}

/// `dv replace-info`: what Claude needs to draft the replacement checked out here.
pub fn info() -> Result<()> {
    let id = current().context("not on a replacement's branch (dv/replace-N) or a new PR's (dv/new-K)")?;
    let r = load(id)?;
    let base = crate::diff::merge_base(Some(&crate::diff::remote_branch(&r.base)))?;
    match is_new(id) {
        true => {
            println!("record: {}    (write title and body here)", path(id)?.display());
            println!("task: {}", r.task.replace('\n', "\n      "));
            // dv's triage of the issues it names (`gh issue view N --comments` has the rest).
            let dir = crate::claude::dv_dir()?.join("reviews");
            for n in mentioned(&r.task) {
                let f = dir.join(format!("issue-{n}.json"));
                if f.exists() {
                    println!("triage of #{n}: {}    (yours, from triaging it earlier)", f.display());
                }
            }
        }
        false => println!("record: {}    (write title, body and closing_note here)", path(id)?.display()),
    }
    for o in &r.replaces {
        println!("replaces: #{} {} (@{}) {}", o.number, o.title, o.author, o.url);
    }
    println!("branch: {}    (commit your work here; never push)", branch(id));
    println!("base: {base}    ({}: `git diff {base}` is what dv shows)", crate::diff::remote_branch(&r.base));
    println!("notes: the user's notes on this repo are in your prompt (read-only for a replacement)");
    Ok(())
}

#[test]
fn records_round_trip() {
    let r = Record {
        id: 12,
        replaces: vec![Original { number: 12, title: "fix it".into(), author: "bot".into(), url: "u".into() }, Original { number: 15, ..Original::default() }],
        base: "master".into(),
        title: "Fix it properly".into(),
        body: "Replaces #12 and #15.\n\nFixes #9.".into(),
        closing_note: "Thanks! Handled in the replacement.".into(),
        session: "s".into(),
        published: Some(20),
        closed: vec![12],
        task: String::new(),
        asks: vec![
            Request { text: "shorter title".into(), want: "change".into(), on: "description".into(), answer: "Done.".into() },
            Request { text: "mention #9".into(), ..Request::default() },
        ],
        taking: 1,
        drafted_at: 1_800_000_000,
    };
    assert_eq!(parse(12, &to_json(&r)).unwrap(), r);
    // Only what no redraft has taken in yet is asked again.
    assert!(prompt(&r, "", Reviews::All).ends_with("`asks[1]`: mention #9") && !prompt(&r, "", Reviews::All).contains("asks[0]"));
    // As Claude may leave it: fields missing are empty.
    let bare = parse(3, r#"{ "replaces": [{ "number": 3 }], "base": "main" }"#).unwrap();
    assert_eq!((bare.replaces[0].number, bare.title.as_str(), bare.base.as_str()), (3, "", "main"));
    assert!(prompt(&r, "keep the old API", Reviews::All).contains("PR #12, #15") && prompt(&r, "keep the old API", Reviews::All).ends_with("The user adds:\nkeep the old API"));
    let r = Record { closing_note: "Thanks! See {replacement}.".into(), ..r };
    assert_eq!(note(&r), "Thanks! See #20.");
    assert_eq!(note(&Record { published: None, ..r.clone() }), "Thanks! See the replacement.");
    // Without the placeholder, the link goes at the end.
    assert_eq!(note(&Record { closing_note: "Thanks!".into(), ..r.clone() }), "Thanks!\n\nSuperseded by #20.");
    assert_eq!(owner("git@github.com:evan/diffview.git"), Some("evan"));
    assert_eq!(owner("https://github.com/evan/diffview"), Some("evan"));
    assert_eq!(owner("/srv/git/x.git"), None);
}

#[test]
fn new_prs() {
    let id = NEW + 3;
    assert!(is_new(id) && !is_new(2390));
    assert_eq!((name(id), branch(id), shown(id), label(id)), ("new-3".into(), "dv/new-3".into(), "new 3".into(), "new PR 3".into()));
    assert_eq!((name(12), branch(12), shown(12)), ("replace-12".into(), "dv/replace-12".into(), "#12".into()));
    // Its record: no PRs it replaces, its task kept; the prompt asks for a new PR doing it.
    let r = parse(id, r#"{ "base": "master", "task": "Fix #9: the panic on empty input" }"#).unwrap();
    assert!(r.replaces.is_empty() && r.task.starts_with("Fix #9"));
    assert_eq!(parse(id, &to_json(&r)).unwrap(), r);
    let p = prompt(&r, "", Reviews::All);
    assert!(p.contains("draft a new PR") && p.ends_with("Fix #9: the panic on empty input"), "{p}");
}