Skip to main content

openmoat_core/
attribution.rs

1//! Agent provenance for commits (ADR-056): which files of a commit an agent
2//! session wrote, and, where the record allows, which added lines.
3//!
4//! Pure: the CLI reads the audit log's record of each session's writes
5//! (ADR-039) and the commit from git, and passes both in. A write is matched
6//! to a file of the commit by its content hashes, which the hook recorded when
7//! it decided the call:
8//!
9//! - [`Evidence::Lines`]: the write turned the parent's content into the
10//!   committed content, so every added line of the file is the session's.
11//! - [`Evidence::Content`]: the committed content is what the write left; the
12//!   person may have written some of it before.
13//! - [`Evidence::Touched`]: the session wrote the file after the parent commit
14//!   and before this one; what the file holds may have changed since.
15//!
16//! What the hook never saw (a script that writes files, an editor) is not here,
17//! so a commit with no record is not shown to be a person's.
18
19mod hunks;
20mod note;
21
22use std::collections::BTreeMap;
23
24use serde::{Deserialize, Serialize};
25
26use crate::engine::UntrustedKind;
27
28pub use hunks::added_lines;
29pub use note::{AuditHead, Discrepancy, EventHash, NOTE_FORMAT, Note, NoteFormat, compare};
30
31/// A write recorded this long after a commit's time still counts toward it:
32/// git keeps whole seconds, the audit log milliseconds.
33pub const CLOCK_SLACK_MS: i64 = 2_000;
34
35/// Lines of the committed file, from 1, both ends included.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct LineRange {
39    /// The first line.
40    pub start: u32,
41    /// The last line.
42    pub end: u32,
43}
44
45impl LineRange {
46    /// How many lines it covers.
47    #[must_use]
48    pub fn len(self) -> u32 {
49        self.end.saturating_sub(self.start).saturating_add(1)
50    }
51
52    /// Never: a range holds at least its first line.
53    #[must_use]
54    pub fn is_empty(self) -> bool {
55        false
56    }
57}
58
59/// The untrusted content a session had read before it wrote.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(deny_unknown_fields)]
62pub struct Untrusted {
63    /// Where it came from.
64    pub kind: UntrustedKind,
65    /// What it was, as the audit log has it (redacted): `fetch docs.rs`.
66    pub source: String,
67}
68
69/// One session's newest recorded write of a file, as the caller found it.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct AgentWrite {
72    /// The file, relative to the repository, `/`-separated.
73    pub path: String,
74    /// The host's id.
75    pub host: String,
76    /// The host's session id, as the audit log has it.
77    pub session: String,
78    /// The audit event of the call that wrote it.
79    pub event: i64,
80    /// When that call was recorded (ms since the epoch).
81    pub ts_ms: i64,
82    /// The content hash the write left, when the hook knew it.
83    pub sha256: Option<String>,
84    /// The content hash before it (`""`: no file), when the hook knew it.
85    pub before: Option<String>,
86    /// What untrusted content the session had read before the write.
87    pub untrusted: Option<Untrusted>,
88}
89
90/// A file a commit changes.
91#[derive(Debug, Clone, PartialEq, Eq, Default)]
92pub struct ChangedFile {
93    /// The file, relative to the repository, `/`-separated.
94    pub path: String,
95    /// The content hash at the parent (`""`: no file there); `None` when not
96    /// known (too large, not a regular file).
97    pub before: Option<String>,
98    /// The content hash at the commit, as [`ChangedFile::before`].
99    pub after: Option<String>,
100    /// The lines the commit adds to it.
101    pub added: Vec<LineRange>,
102}
103
104/// The commit being attributed.
105#[derive(Debug, Clone, Copy)]
106pub struct Commit<'a> {
107    /// The first parent's committer time (ms); `None` for a root commit.
108    pub parent_ms: Option<i64>,
109    /// The commit's committer time (ms).
110    pub commit_ms: i64,
111    /// What it changes.
112    pub files: &'a [ChangedFile],
113}
114
115/// How strongly a write is tied to a committed file.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
117#[serde(rename_all = "kebab-case")]
118pub enum Evidence {
119    /// The write made the commit's whole change to the file.
120    Lines,
121    /// The committed content is what the write left.
122    Content,
123    /// The session wrote the file after the parent commit.
124    Touched,
125}
126
127impl Evidence {
128    /// The spelling notes and reports use.
129    #[must_use]
130    pub fn as_str(self) -> &'static str {
131        match self {
132            Self::Lines => "lines",
133            Self::Content => "content",
134            Self::Touched => "touched",
135        }
136    }
137}
138
139/// A file of a commit an agent session wrote.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct FileRecord {
143    /// The file, relative to the repository.
144    pub path: String,
145    /// The host's id.
146    pub host: String,
147    /// The session, as the audit log has it.
148    pub session: String,
149    /// The audit event of the write.
150    pub event: i64,
151    /// When it was recorded (ms since the epoch).
152    pub ts_ms: i64,
153    /// How the write is tied to the file.
154    pub evidence: Evidence,
155    /// The added lines that are the session's: all of them for
156    /// [`Evidence::Lines`], none claimed otherwise.
157    #[serde(default, skip_serializing_if = "Vec::is_empty")]
158    pub lines: Vec<LineRange>,
159    /// What untrusted content the session had read before the write.
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub untrusted: Option<Untrusted>,
162}
163
164impl FileRecord {
165    /// How many added lines are claimed.
166    #[must_use]
167    pub fn line_count(&self) -> u64 {
168        self.lines.iter().map(|r| u64::from(r.len())).sum()
169    }
170}
171
172/// The files of `commit` the recorded `writes` account for, ordered by path,
173/// then event: for each session, its newest write of the file up to the
174/// commit's time, matched by content, else by time after the parent commit.
175#[must_use]
176pub fn attribute(commit: &Commit<'_>, writes: &[AgentWrite]) -> Vec<FileRecord> {
177    let until = commit.commit_ms.saturating_add(CLOCK_SLACK_MS);
178    let mut out = Vec::new();
179    for file in commit.files {
180        // one write per session: the newest up to the commit
181        let mut newest: BTreeMap<(&str, &str), &AgentWrite> = BTreeMap::new();
182        for write in writes
183            .iter()
184            .filter(|w| w.path == file.path && w.ts_ms <= until)
185        {
186            let slot = newest
187                .entry((write.host.as_str(), write.session.as_str()))
188                .or_insert(write);
189            if write.event > slot.event {
190                *slot = write;
191            }
192        }
193        for write in newest.into_values() {
194            if let Some(evidence) = evidence(commit, file, write) {
195                out.push(FileRecord {
196                    path: file.path.clone(),
197                    host: write.host.clone(),
198                    session: write.session.clone(),
199                    event: write.event,
200                    ts_ms: write.ts_ms,
201                    evidence,
202                    lines: if evidence == Evidence::Lines {
203                        file.added.clone()
204                    } else {
205                        Vec::new()
206                    },
207                    untrusted: write.untrusted.clone(),
208                });
209            }
210        }
211    }
212    out.sort_by(|a, b| (&a.path, a.event).cmp(&(&b.path, b.event)));
213    out
214}
215
216fn evidence(commit: &Commit<'_>, file: &ChangedFile, write: &AgentWrite) -> Option<Evidence> {
217    let after = file.after.as_deref().filter(|h| !h.is_empty());
218    if let (Some(after), Some(wrote)) = (after, write.sha256.as_deref())
219        && after == wrote
220    {
221        let whole = file.before.is_some() && file.before == write.before;
222        return Some(if whole {
223            Evidence::Lines
224        } else {
225            Evidence::Content
226        });
227    }
228    let after_parent = commit.parent_ms.is_none_or(|parent| write.ts_ms > parent);
229    after_parent.then_some(Evidence::Touched)
230}
231
232/// What one session wrote across the commits of a change, for a review.
233#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
234pub struct SessionSummary {
235    /// The host's id.
236    pub host: String,
237    /// The session.
238    pub session: String,
239    /// How many distinct files it wrote.
240    pub files: usize,
241    /// How many added lines are its own ([`Evidence::Lines`]).
242    pub lines: u64,
243    /// The untrusted content it had read before its first write that had
244    /// read any, if one had.
245    #[serde(skip_serializing_if = "Option::is_none")]
246    pub untrusted: Option<Untrusted>,
247    /// The commits it wrote in.
248    pub commits: usize,
249}
250
251/// One summary per session over `notes`, ordered by host, then session.
252#[must_use]
253pub fn summarise(notes: &[Note]) -> Vec<SessionSummary> {
254    type Acc<'a> = (
255        std::collections::BTreeSet<&'a str>,
256        u64,
257        Option<(i64, &'a Untrusted)>,
258        std::collections::BTreeSet<&'a str>,
259    );
260    let mut by: BTreeMap<(&str, &str), Acc<'_>> = BTreeMap::new();
261    for note in notes {
262        for file in &note.files {
263            let acc = by
264                .entry((file.host.as_str(), file.session.as_str()))
265                .or_default();
266            acc.0.insert(file.path.as_str());
267            acc.1 = acc.1.saturating_add(file.line_count());
268            if let Some(untrusted) = &file.untrusted
269                && acc.2.is_none_or(|(event, _)| file.event < event)
270            {
271                acc.2 = Some((file.event, untrusted));
272            }
273            acc.3.insert(note.commit.as_str());
274        }
275    }
276    by.into_iter()
277        .map(
278            |((host, session), (files, lines, untrusted, commits))| SessionSummary {
279                host: host.to_owned(),
280                session: session.to_owned(),
281                files: files.len(),
282                lines,
283                untrusted: untrusted.map(|(_, u)| u.clone()),
284                commits: commits.len(),
285            },
286        )
287        .collect()
288}
289
290#[cfg(test)]
291mod tests;