brain: Resolve review comments

6ebf50bf131570c0257df03c00aa94049c771fe2
Resolve a comment by its stable ID so completed feedback no longer
appears in the active review. List active comments by default and
select resolved comments with the --resolved flag.

Store the resolution timestamp in the comment record and merge the
update through the existing concurrent comment persistence path.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent e88c425c
crates/brain/src/comments.rs +84 -7
106 106
    records: Vec<CommentRecord>,
107 107
    /// Author name used for newly authored comments.
108 108
    author: String,
109 109
}
110 110
111 +
/// Resolution state selected by the comments command.
112 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
113 +
pub enum CommentState {
114 +
    /// Comments that still require action.
115 +
    Unresolved,
116 +
    /// Comments that have been resolved.
117 +
    Resolved,
118 +
}
119 +
111 120
/// One persisted comment row.
112 121
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
113 122
struct CommentRecord {
114 123
    /// Commit containing the hunk, when recorded by a commit-aware version.
115 124
    commit: Option<Oid>,
127 136
    patch_id: PatchId,
128 137
    /// Occurrence of this patch id within the commit.
129 138
    ordinal: u32,
130 139
    /// Comment body.
131 140
    body: String,
141 +
    /// Unix timestamp when the comment was resolved.
142 +
    resolved: Option<u64>,
132 143
}
133 144
134 145
/// One comment row emitted by the non-interactive comments command.
135 146
#[derive(Serialize)]
136 147
struct CommentOutput<'a> {
186 197
            rows.push_str(&json::to_string(record));
187 198
            rows.push('\n');
188 199
        }
189 200
        rows
190 201
    }
191 -
    /// Writes public comment rows as JSONL, resolving each hunk's current line.
202 +
    /// Writes public comment rows in `state` as JSONL, resolving each hunk's current line.
192 203
    pub fn write_jsonl(
193 204
        &self,
194 205
        mut writer: impl io::Write,
206 +
        state: CommentState,
195 207
        line_for: impl Fn(&PatchId, u32) -> Option<u32>,
196 208
    ) -> io::Result<()> {
197 -
        for record in &self.records {
209 +
        for record in self.records.iter().filter(|record| {
210 +
            matches!(
211 +
                (state, record.resolved),
212 +
                (CommentState::Unresolved, None) | (CommentState::Resolved, Some(_))
213 +
            )
214 +
        }) {
198 215
            let output = CommentOutput {
199 216
                id: &record.id,
200 217
                author: &record.author,
201 218
                timestamp: record.timestamp,
202 219
                heading: &record.heading,
231 248
    /// Returns the number of comments attached to one patch occurrence.
232 249
    pub fn matching_count(&self, commit: Oid, patch_id: &PatchId, ordinal: u32) -> usize {
233 250
        self.records
234 251
            .iter()
235 252
            .filter(|record| {
236 -
                record.patch_id == *patch_id
253 +
                record.resolved.is_none()
254 +
                    && record.patch_id == *patch_id
237 255
                    && record.ordinal == ordinal
238 256
                    && record.commit.is_none_or(|stored| stored == commit)
239 257
            })
240 258
            .count()
241 259
    }
243 261
    /// Returns comments attached exactly to `target`, in storage order.
244 262
    fn matching(&self, target: &CommentTarget) -> Vec<Comment> {
245 263
        self.records
246 264
            .iter()
247 265
            .filter(|record| {
248 -
                record.patch_id == target.patch_id
266 +
                record.resolved.is_none()
267 +
                    && record.patch_id == target.patch_id
249 268
                    && record.ordinal == target.ordinal
250 269
                    && record.commit.is_none_or(|commit| commit == target.commit)
251 270
            })
252 271
            .map(Comment::from)
253 272
            .collect()
294 313
            commit: Some(target.commit),
295 314
            path: target.path.clone(),
296 315
            patch_id: target.patch_id.clone(),
297 316
            ordinal: target.ordinal,
298 317
            body,
318 +
            resolved: None,
299 319
        };
300 320
        let comment = Comment::from(&record);
301 321
        self.records.push(record);
302 322
303 323
        comment
310 330
        };
311 331
        record.body = body;
312 332
        true
313 333
    }
314 334
335 +
    /// Resolves the comment with `id`.
336 +
    pub fn resolve(&mut self, id: &CommentId) -> bool {
337 +
        let Some(record) = self.records.iter_mut().find(|record| record.id == *id) else {
338 +
            return false;
339 +
        };
340 +
        if record.resolved.is_some() {
341 +
            return true;
342 +
        }
343 +
        record.resolved = Some(
344 +
            SystemTime::now()
345 +
                .duration_since(UNIX_EPOCH)
346 +
                .unwrap_or_default()
347 +
                .as_secs(),
348 +
        );
349 +
        true
350 +
    }
351 +
315 352
    /// Deletes the comment with `id`.
316 353
    fn delete(&mut self, id: &CommentId) -> bool {
317 354
        let Some(index) = self.records.iter().position(|record| record.id == *id) else {
318 355
            return false;
319 356
        };
604 641
        let store = ReviewComments::parse("").unwrap();
605 642
        let comments = Comments::new(&store, targets);
606 643
        (store, comments)
607 644
    }
608 645
646 +
    #[test]
647 +
    fn output_selects_comment_resolution_state() {
648 +
        let mut store = ReviewComments::parse(
649 +
            "{\"id\":1,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":null,\"patch_id\":\"p\",\"ordinal\":0,\"body\":\"open\"}\n{\"id\":2,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":null,\"patch_id\":\"p\",\"ordinal\":0,\"body\":\"done\",\"resolved\":2}",
650 +
        )
651 +
        .unwrap();
652 +
653 +
        let mut output = Vec::new();
654 +
        store
655 +
            .write_jsonl(&mut output, CommentState::Unresolved, |_, _| None)
656 +
            .unwrap();
657 +
        assert!(
658 +
            String::from_utf8(output)
659 +
                .unwrap()
660 +
                .contains(r#""body":"open""#)
661 +
        );
662 +
663 +
        let mut output = Vec::new();
664 +
        store
665 +
            .write_jsonl(&mut output, CommentState::Resolved, |_, _| None)
666 +
            .unwrap();
667 +
        assert!(
668 +
            String::from_utf8(output)
669 +
                .unwrap()
670 +
                .contains(r#""body":"done""#)
671 +
        );
672 +
673 +
        assert!(store.resolve(&CommentId::from(1)));
674 +
        assert_eq!(
675 +
            store.matching_count(
676 +
                "1111111111111111111111111111111111111111".parse().unwrap(),
677 +
                &PatchId::from("p".to_owned()),
678 +
                0,
679 +
            ),
680 +
            0
681 +
        );
682 +
    }
683 +
609 684
    #[test]
610 685
    fn comment_id_serializes_as_number() {
611 686
        let id = CommentId::from(7);
612 687
613 688
        assert_eq!(json::to_string(&id), "7");
630 705
        )
631 706
        .unwrap();
632 707
633 708
        let mut output = Vec::new();
634 709
        store
635 -
            .write_jsonl(&mut output, |patch_id, ordinal| {
636 -
                (patch_id.as_str() == "p" && ordinal == 0).then_some(12)
637 -
            })
710 +
            .write_jsonl(
711 +
                &mut output,
712 +
                CommentState::Unresolved,
713 +
                |patch_id, ordinal| (patch_id.as_str() == "p" && ordinal == 0).then_some(12),
714 +
            )
638 715
            .unwrap();
639 716
        assert_eq!(
640 717
            String::from_utf8(output).unwrap(),
641 718
            "{\"id\":7,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":\"src/main.rs\",\"line\":12,\"patchId\":\"p\",\"ordinal\":0,\"body\":\"old\"}\n"
642 719
        );
crates/brain/src/error.rs +3 -0
24 24
    Parse(DecodeError),
25 25
    /// Highlighting asset setup failed, carrying the backend message.
26 26
    Highlight(String),
27 27
    /// The command-line arguments were invalid, carrying a usage message.
28 28
    Usage(String),
29 +
    /// A requested comment id does not exist in the selected review.
30 +
    CommentNotFound(u64),
29 31
    /// The review range contained no changes to review.
30 32
    Empty,
31 33
}
32 34
33 35
impl From<io::Error> for Error {
74 76
                f.write_str("stored review state is invalid; reset the review to continue")
75 77
            }
76 78
            Self::Parse(error) => write!(f, "{error}"),
77 79
            Self::Highlight(error) => write!(f, "{error}"),
78 80
            Self::Usage(message) => write!(f, "{message}"),
81 +
            Self::CommentNotFound(id) => write!(f, "comment {id} was not found"),
79 82
            Self::Empty => write!(f, "no changes to review between base and target"),
80 83
        }
81 84
    }
82 85
}
83 86
crates/brain/src/main.rs +119 -20
37 37
use rustik_tui_termion as tui_termion;
38 38
39 39
use backend::{
40 40
    BrainStatus, BrainStatusBaseState, BrainStatusHead, BrainStatusState, CommentStatus,
41 41
};
42 -
use comments::ReviewComments;
42 +
use comments::{CommentId, CommentState, ReviewComments};
43 43
use error::Error;
44 44
45 45
/// Terminal backend used by the interactive viewer.
46 46
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
47 47
49 49
const STARTUP_SPINNER_INTERVAL: Duration = Duration::from_millis(80);
50 50
/// Startup spinner animation frames.
51 51
const STARTUP_SPINNER_FRAMES: &[char] = &['|', '/', '-', '\\'];
52 52
53 53
/// Command-line usage text.
54 -
const USAGE: &str = "usage: brain [status [--all]]\n       brain status <base> <target>\n       brain comments [<base>] <target>\n       brain [--reset|--rebase] diff [<base>] <target>";
54 +
const USAGE: &str = "usage: brain [status [--all]]\n       brain status <base> <target>\n       brain comments [--resolved] [<base>] <target>\n       brain resolve <comment-id> [<base>] <target>\n       brain [--reset|--rebase] diff [<base>] <target>";
55 55
/// Default output width used when terminal width is unknown.
56 56
const DEFAULT_STATUS_WIDTH: usize = 140;
57 57
/// Marker shown for approved review state: โœ”.
58 58
const APPROVED_STATUS_ICON: char = 'โœ”';
59 59
/// Marker shown for in-review state: โ—.
105 105
                        None => Some(Command::Status {
106 106
                            scope: StatusScope::Reviews,
107 107
                        }),
108 108
                    };
109 109
                }
110 -
                Value(command_name) if command_name == "comments" || command_name == "diff" => {
111 -
                    let first = parse_revision("target", parser.value()?)?;
112 -
                    let (base, target) = match parser.next()? {
113 -
                        Some(Value(target)) => {
114 -
                            let target = parse_revision("target", target)?;
115 -
                            (Some(first), target)
110 +
                Value(command_name) if command_name == "comments" => {
111 +
                    let state = match parser.next()? {
112 +
                        Some(Long("resolved")) => CommentState::Resolved,
113 +
                        Some(Value(first)) => {
114 +
                            let (base, target) = parse_range(first, &mut parser)?;
115 +
                            command = Some(Command::Comments {
116 +
                                base,
117 +
                                target,
118 +
                                state: CommentState::Unresolved,
119 +
                            });
120 +
                            continue;
116 121
                        }
117 -
                        Some(_) => return Err(Error::Usage(USAGE.to_owned())),
118 -
                        None => (None, first),
122 +
                        _ => return Err(Error::Usage(USAGE.to_owned())),
119 123
                    };
120 -
121 -
                    command = Some(if command_name == "comments" {
122 -
                        Command::Comments { base, target }
123 -
                    } else {
124 -
                        Command::Diff { base, target }
124 +
                    let first = parser.value()?;
125 +
                    let (base, target) = parse_range(first, &mut parser)?;
126 +
                    command = Some(Command::Comments {
127 +
                        base,
128 +
                        target,
129 +
                        state,
125 130
                    });
126 131
                }
132 +
                Value(command_name) if command_name == "resolve" => {
133 +
                    let id = parser
134 +
                        .value()?
135 +
                        .to_str()
136 +
                        .and_then(|value| value.parse::<u64>().ok())
137 +
                        .map(CommentId::from)
138 +
                        .ok_or_else(|| Error::Usage(USAGE.to_owned()))?;
139 +
                    let first = parser.value()?;
140 +
                    let (base, target) = parse_range(first, &mut parser)?;
141 +
                    command = Some(Command::Resolve { id, base, target });
142 +
                }
143 +
                Value(command_name) if command_name == "diff" => {
144 +
                    let first = parser.value()?;
145 +
                    let (base, target) = parse_range(first, &mut parser)?;
146 +
                    command = Some(Command::Diff { base, target });
147 +
                }
127 148
                Value(value) => {
128 149
                    let value = value.to_string_lossy();
129 150
                    return Err(Error::Usage(format!("unknown command: {value}\n{USAGE}")));
130 151
                }
131 152
                _ => return Err(Error::Usage(USAGE.to_owned())),
157 178
        /// Exclusive lower bound of the reviewed range.
158 179
        base: Rev,
159 180
        /// Inclusive upper bound of the reviewed range.
160 181
        target: Rev,
161 182
    },
162 -
    /// Print the comments for the review of `base..target`.
183 +
    /// Print comments with the selected resolution state for `base..target`.
163 184
    Comments {
164 185
        /// Exclusive lower bound of the reviewed range, when supplied.
165 186
        base: Option<Rev>,
166 187
        /// Inclusive upper bound of the reviewed range.
167 188
        target: Rev,
189 +
        /// Resolution state included in the output.
190 +
        state: CommentState,
191 +
    },
192 +
    /// Resolve one comment in the review of `base..target`.
193 +
    Resolve {
194 +
        /// Stable local comment id.
195 +
        id: CommentId,
196 +
        /// Exclusive lower bound of the reviewed range, when supplied.
197 +
        base: Option<Rev>,
198 +
        /// Inclusive upper bound of the reviewed range.
199 +
        target: Rev,
168 200
    },
169 201
    /// Review the commits in `base..target`.
170 202
    Diff {
171 203
        /// Exclusive lower bound of the reviewed range, when supplied.
172 204
        base: Option<Rev>,
395 427
fn run(args: Vec<OsString>) -> Result<(), Error> {
396 428
    let args = Args::parse(args)?;
397 429
    match args.command {
398 430
        Command::Status { scope } => run_status(scope),
399 431
        Command::RangeStatus { base, target } => run_range_status(base, target),
400 -
        Command::Comments { base, target } => run_comments(base, target),
432 +
        Command::Comments {
433 +
            base,
434 +
            target,
435 +
            state,
436 +
        } => run_comments(base, target, state),
437 +
        Command::Resolve { id, base, target } => run_resolve(id, base, target),
401 438
        Command::Diff { base, target } => run_diff(args.state, base, target),
402 439
    }
403 440
}
404 441
405 -
/// Prints the selected review's comments as JSONL.
406 -
fn run_comments(base: Option<Rev>, target: Rev) -> Result<(), Error> {
442 +
/// Prints comments with the selected resolution state as JSONL.
443 +
fn run_comments(base: Option<Rev>, target: Rev, state: CommentState) -> Result<(), Error> {
407 444
    let cwd = env::current_dir()?;
408 445
    let base = match base {
409 446
        Some(base) => base,
410 447
        None => backend::branch_base(&cwd, &target)?,
411 448
    };
433 470
            }
434 471
        }
435 472
    }
436 473
437 474
    let stdout = io::stdout();
438 -
    comments.write_jsonl(stdout.lock(), |patch_id, ordinal| {
475 +
    comments.write_jsonl(stdout.lock(), state, |patch_id, ordinal| {
439 476
        lines
440 477
            .get(patch_id)
441 478
            .and_then(|occurrences| occurrences.get(&ordinal))
442 479
            .copied()
443 480
    })?;
444 481
445 482
    Ok(())
446 483
}
447 484
485 +
/// Resolves one comment in the selected review.
486 +
fn run_resolve(id: CommentId, base: Option<Rev>, target: Rev) -> Result<(), Error> {
487 +
    let cwd = env::current_dir()?;
488 +
    let base = match base {
489 +
        Some(base) => base,
490 +
        None => backend::branch_base(&cwd, &target)?,
491 +
    };
492 +
    let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
493 +
    let brain = backend.brain()?;
494 +
    let persisted = brain.read_comments()?;
495 +
    let previous = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?;
496 +
    let mut updated = previous.clone();
497 +
    if !updated.resolve(&id) {
498 +
        return Err(Error::CommentNotFound(id.as_u64()));
499 +
    }
500 +
    brain.merge_comments(&previous, &updated)?;
501 +
    Ok(())
502 +
}
503 +
448 504
/// Loads the review range and runs the interactive diff session.
449 505
fn run_diff(state: ReviewStateLoad, base: Option<Rev>, target: Rev) -> Result<(), Error> {
450 506
    let cwd = env::current_dir()?;
451 507
    let mut terminal = open_terminal()?;
452 508
    terminal.clear()?;
690 746
        })
691 747
        .filter(|width| *width > 0)
692 748
        .unwrap_or(DEFAULT_STATUS_WIDTH)
693 749
}
694 750
751 +
/// Parses the optional base and required target revisions following a command.
752 +
fn parse_range(first: OsString, parser: &mut lexopt::Parser) -> Result<(Option<Rev>, Rev), Error> {
753 +
    let first = parse_revision("target", first)?;
754 +
    match parser.next()? {
755 +
        Some(Value(target)) => {
756 +
            let target = parse_revision("target", target)?;
757 +
            Ok((Some(first), target))
758 +
        }
759 +
        Some(_) => Err(Error::Usage(USAGE.to_owned())),
760 +
        None => Ok((None, first)),
761 +
    }
762 +
}
763 +
695 764
/// Parses one revision argument for the `diff` command.
696 765
fn parse_revision(name: &str, value: OsString) -> Result<Rev, Error> {
697 766
    let value = value
698 767
        .to_str()
699 768
        .ok_or_else(|| Error::Usage(format!("{name} revision must be valid UTF-8")))?;
782 851
            Args {
783 852
                state: ReviewStateLoad::Existing,
784 853
                command: Command::Comments {
785 854
                    base: None,
786 855
                    target: Rev::try_from("feature").unwrap(),
856 +
                    state: CommentState::Unresolved,
787 857
                },
788 858
            }
789 859
        );
790 860
791 861
        let parsed = Args::parse(args(&["comments", "main", "HEAD"])).unwrap();
792 862
        assert_eq!(
793 863
            parsed.command,
794 864
            Command::Comments {
795 865
                base: Some(Rev::try_from("main").unwrap()),
796 866
                target: Rev::try_from("HEAD").unwrap(),
867 +
                state: CommentState::Unresolved,
868 +
            }
869 +
        );
870 +
    }
871 +
872 +
    #[test]
873 +
    fn parses_resolved_comments_command() {
874 +
        let parsed = Args::parse(args(&["comments", "--resolved", "main", "HEAD"])).unwrap();
875 +
876 +
        assert_eq!(
877 +
            parsed.command,
878 +
            Command::Comments {
879 +
                base: Some(Rev::try_from("main").unwrap()),
880 +
                target: Rev::try_from("HEAD").unwrap(),
881 +
                state: CommentState::Resolved,
882 +
            }
883 +
        );
884 +
    }
885 +
886 +
    #[test]
887 +
    fn parses_resolve_command() {
888 +
        let parsed = Args::parse(args(&["resolve", "7", "main", "HEAD"])).unwrap();
889 +
890 +
        assert_eq!(
891 +
            parsed.command,
892 +
            Command::Resolve {
893 +
                id: CommentId::from(7),
894 +
                base: Some(Rev::try_from("main").unwrap()),
895 +
                target: Rev::try_from("HEAD").unwrap(),
797 896
            }
798 897
        );
799 898
    }
800 899
801 900
    #[test]