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
//! Which seat wrote each line (#349).
//!
//! Git blame answers "which commit"; this answers "which seat" — you, the
//! navigator, an agent pane, a collab peer. The question it exists for is
//! "did I write this or did the model?", which no commit can answer because
//! a commit records the author of the save, not of the keystrokes.
//!
//! # The invariant that shapes everything here
//!
//! **A line croft did not observe being written is `Unknown`, never guessed.**
//! A provenance overlay that is right most of the time is worse than none: it
//! would be read as fact, and the one line it attributes wrongly is exactly
//! the line someone is arguing about. So every operation below either knows
//! which seat wrote a line or records that it does not, and there is no path
//! that infers a seat from a neighbouring line.
//!
//! That is also why this is a map from line to `Option<Seat>` rather than a
//! map that omits unknown lines: an absent entry and an unknown one must not
//! be the same thing to a caller, or "no record" silently reads as "not
//! attributed to anyone" in one place and "index out of range" in another.
use std::collections::BTreeMap;
/// Who wrote a line.
///
/// Cloned rather than interned: a buffer has a handful of distinct seats and
/// the map is per-buffer, so the sharing an interner would buy is not worth
/// the indirection at the point where the gutter paints.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
pub enum Seat {
/// The person at this croft.
Me,
/// The navigator's streamed suggestion, accepted into the buffer.
Navigator,
/// A coding agent, named by the pane it runs in.
Agent(String),
/// A collab participant, by display name.
Peer(String),
/// Text croft inserted on the user's behalf that no person or agent
/// typed: an accepted LSP completion, an expanded snippet.
///
/// A separate seat rather than `Me`, because "you wrote this" is a claim
/// and a completion body is not one the user made — they chose it from a
/// list, which is a different act from writing it. Attributing generated
/// text to a person is the same class of wrong answer as inheriting a
/// seat from a neighbouring line, and it is the shape most likely to be
/// argued about later.
Generated,
}
impl Seat {
/// The label the inline blame annotation shows.
pub fn label(&self) -> String {
match self {
Seat::Me => String::from("you"),
Seat::Navigator => String::from("navigator"),
Seat::Agent(pane) => format!("agent ({pane})"),
Seat::Peer(name) => name.clone(),
Seat::Generated => String::from("generated"),
}
}
/// The gutter overlay's colour for this seat, one distinct hue per kind
/// so a glance tells the seats apart: blue for you, purple for the
/// navigator, orange for an agent, green for a peer, grey for text that
/// came from a completion or a snippet rather than a person.
pub fn hue(&self) -> (u8, u8, u8) {
match self {
Seat::Me => (0x4e, 0x9a, 0xff),
Seat::Navigator => (0xc0, 0x7c, 0xff),
Seat::Agent(_) => (0xff, 0x9f, 0x40),
Seat::Peer(_) => (0x66, 0xcc, 0x66),
Seat::Generated => (0x8a, 0x8a, 0x8a),
}
}
}
/// Per-buffer line provenance.
///
/// Keyed on 0-based line index. A line with no entry is `Unknown` and stays
/// that way: see the module invariant.
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Provenance {
lines: BTreeMap<usize, Seat>,
}
impl Provenance {
pub fn new() -> Self {
Self::default()
}
/// The seat that wrote `line`, or `None` when croft did not see it
/// written.
pub fn seat(&self, line: usize) -> Option<&Seat> {
self.lines.get(&line)
}
/// Record that `seat` wrote the lines in `range`.
pub fn record(&mut self, range: std::ops::Range<usize>, seat: Seat) {
for line in range {
self.lines.insert(line, seat.clone());
}
}
/// How many lines carry an attribution.
pub fn attributed(&self) -> usize {
self.lines.len()
}
/// Forget every attribution at or beyond `len`.
///
/// The primitive every whole-buffer change needs: after a reload, an
/// undo, or a re-decode, the map may hold keys for lines that no longer
/// exist, and a key past the end is an attribution for a line croft
/// never watched being written. Separate from `splice`, which shifts and
/// never truncates.
///
/// "No key is ever >= `lines.len()`" is the assertable form of this
/// module's invariant, and this is what makes it hold.
pub fn truncate(&mut self, len: usize) {
self.lines.retain(|&line, _| line < len);
}
/// Shift the map for an edit that replaced `removed` lines starting at
/// `at` with `added` new ones.
///
/// The new lines are left UNATTRIBUTED rather than inheriting from
/// whatever sat there: the caller records them against the seat that
/// made the edit, and a caller that forgets leaves them unknown, which
/// is the safe direction. Lines below the edit keep their seats and
/// move; lines inside the removed range are dropped.
pub fn splice(&mut self, at: usize, removed: usize, added: usize) {
let mut next = BTreeMap::new();
for (&line, seat) in &self.lines {
if line < at {
next.insert(line, seat.clone());
} else if line >= at.saturating_add(removed) {
// Below the edit: shifts by the net change. Saturating on
// both sides so an absurd `at` cannot wrap the guard and turn
// the shift into an attribution at ~2^64 — a release build
// would wrap rather than panic, so the guard alone is not
// enough to make the arithmetic safe.
let shifted = (line + added).saturating_sub(removed);
next.insert(shifted, seat.clone());
}
// Inside the removed range: the line is gone, and so is its
// attribution. Nothing is carried onto the replacement.
}
self.lines = next;
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The invariant the whole feature rests on: a line croft did not watch
/// being written is Unknown, and no operation invents a seat for it.
///
/// Asserted as a CONTRAST — an attributed line beside an unattributed
/// one — because "seat(9) is None" passes just as well against a map
/// that attributes nothing at all.
#[test]
fn an_unobserved_line_is_never_attributed() {
let mut p = Provenance::new();
p.record(0..2, Seat::Me);
assert_eq!(p.seat(0), Some(&Seat::Me), "staging: line 0 is attributed");
assert_eq!(p.seat(1), Some(&Seat::Me));
// The line after, and one far beyond the buffer, are both unknown —
// not inherited from the neighbour above.
assert_eq!(p.seat(2), None, "a line nobody wrote must stay unknown");
assert_eq!(p.seat(9_999), None);
}
/// An edit moves the seats below it and drops the ones it replaced.
///
/// The replacement lines are deliberately NOT given the removed lines'
/// seats: the caller records them against whoever made the edit, and a
/// caller that forgets leaves them unknown rather than wrong.
#[test]
fn an_edit_shifts_below_and_drops_what_it_replaced() {
let mut p = Provenance::new();
p.record(0..1, Seat::Me);
p.record(1..2, Seat::Navigator);
p.record(2..3, Seat::Agent(String::from("pane 2")));
// Replace line 1 (the navigator's) with three lines.
p.splice(1, 1, 3);
assert_eq!(p.seat(0), Some(&Seat::Me), "above the edit is untouched");
// The three new lines carry nothing until someone records them.
for line in 1..4 {
assert_eq!(p.seat(line), None, "line {line} was invented, not observed");
}
// The agent's line moved down by the net change (+2).
assert_eq!(
p.seat(4),
Some(&Seat::Agent(String::from("pane 2"))),
"a line below the edit keeps its seat and moves"
);
assert_eq!(p.attributed(), 2, "the replaced line's seat is gone");
}
/// A pure deletion pulls the lines below it up.
#[test]
fn a_deletion_pulls_the_seats_below_it_up() {
let mut p = Provenance::new();
p.record(0..1, Seat::Me);
p.record(3..4, Seat::Peer(String::from("ada")));
p.splice(1, 2, 0);
assert_eq!(p.seat(0), Some(&Seat::Me));
assert_eq!(
p.seat(1),
Some(&Seat::Peer(String::from("ada"))),
"the peer's line moved up into the gap"
);
assert_eq!(p.seat(3), None, "nothing left behind at the old index");
}
/// The shift arithmetic cannot underflow, swept rather than argued.
///
/// `line + added - removed` is a usize expression, so an underflow would
/// panic in debug and wrap in release — the second being the dangerous
/// one, since a wrapped index would attribute a line at some absurd
/// offset instead of crashing. The guard `line >= at + removed` is what
/// makes it safe, and this pins the two together so neither can be
/// changed without the other.
#[test]
fn the_shift_never_underflows_for_any_edit_shape() {
for at in 0..6usize {
for removed in 0..6usize {
for added in 0..6usize {
let mut p = Provenance::new();
// Attribute every line in a window wider than any edit.
p.record(0..12, Seat::Me);
p.splice(at, removed, added);
// Every surviving key is a plausible line index, and the
// count is exactly what the edit implies.
let survivors = p.attributed();
assert_eq!(
survivors,
12 - removed.min(12 - at.min(12)),
"at={at} removed={removed} added={added}"
);
for line in 0..40 {
// Reading any line must not panic, and no seat may
// appear at an index the edit could not produce.
if p.seat(line).is_some() {
assert!(
line < 12 + added,
"seat at {line} after at={at} removed={removed} added={added}"
);
}
}
}
}
}
}
/// Truncation drops exactly the keys past the end and nothing else.
///
/// The assertable form of this module's invariant is "no attributed key
/// is ever >= the buffer's line count", and this is the primitive that
/// makes it hold after a whole-buffer swap.
#[test]
fn truncation_drops_the_keys_past_the_end() {
let mut p = Provenance::new();
p.record(0..5, Seat::Me);
p.truncate(3);
assert_eq!(p.attributed(), 3, "kept exactly the lines that remain");
assert_eq!(p.seat(2), Some(&Seat::Me));
assert_eq!(p.seat(3), None, "a line past the end must be forgotten");
// Truncating to zero forgets everything, which is what a buffer
// replaced wholesale needs.
p.truncate(0);
assert_eq!(p.attributed(), 0);
// Truncating above the highest key is a no-op rather than an error.
p.record(0..2, Seat::Navigator);
p.truncate(99);
assert_eq!(p.attributed(), 2);
}
/// The labels are what the inline annotation shows, so they are part of
/// the interface rather than a debug rendering.
#[test]
fn a_seat_labels_itself_for_the_annotation() {
assert_eq!(Seat::Me.label(), "you");
assert_eq!(Seat::Navigator.label(), "navigator");
assert_eq!(
Seat::Agent(String::from("pane 2")).label(),
"agent (pane 2)"
);
assert_eq!(Seat::Peer(String::from("ada")).label(), "ada");
assert_eq!(Seat::Generated.label(), "generated");
}
/// The hues are the gutter's interface, like the labels: five kinds,
/// five colours, so a glance tells the seats apart.
#[test]
fn every_seat_kind_has_its_own_hue() {
let seats = [
Seat::Me,
Seat::Navigator,
Seat::Agent(String::from("p")),
Seat::Peer(String::from("ada")),
Seat::Generated,
];
let hues: std::collections::BTreeSet<_> = seats.iter().map(Seat::hue).collect();
assert_eq!(hues.len(), seats.len(), "two kinds share a hue: {hues:?}");
}
}