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
//! Append-only version log of file mutations.
//!
//! Every successful write through the host's `version_record` op lands here
//! with a monotonic sequence number. Agents call `changes_since(seq)`
//! to catch up between turns without re-reading every file, and the seq
//! numbers let higher-level tooling spot "agent fighting itself" loops
//! before they cause damage.
//!
//! Per-file history is capped at [`HISTORY_LIMIT`] entries so an agent
//! that thrashes one path doesn't blow up the log indefinitely. The seq
//! counter itself is global.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Maximum number of entries kept per path. Older entries roll off the
/// front in FIFO order.
pub const HISTORY_LIMIT: usize = 200;
/// Edit-classification for one record. The string forms ride out to Harn
/// scripts and the cross-repo schema so callers can switch on them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EditOp {
/// Mark a snapshot/checkpoint, not a content change.
Snapshot,
/// Whole-file write.
Write,
/// Targeted line-range replacement.
ReplaceRange,
/// Insertion after a specified line.
InsertAfter,
/// Targeted line-range deletion.
DeleteRange,
/// Patch/diff application.
Patch,
/// File deletion.
Delete,
}
impl EditOp {
/// String form used by the Harn host bridge.
pub fn as_str(self) -> &'static str {
match self {
EditOp::Snapshot => "snapshot",
EditOp::Write => "write",
EditOp::ReplaceRange => "replace_range",
EditOp::InsertAfter => "insert_after",
EditOp::DeleteRange => "delete_range",
EditOp::Patch => "patch",
EditOp::Delete => "delete",
}
}
/// Parse from the string form; returns `None` for unknown variants so
/// the caller can decide whether to default to `Write` or to error.
pub fn parse(raw: &str) -> Option<Self> {
Some(match raw {
"snapshot" => EditOp::Snapshot,
"write" => EditOp::Write,
"replace_range" => EditOp::ReplaceRange,
"insert_after" => EditOp::InsertAfter,
"delete_range" => EditOp::DeleteRange,
"patch" => EditOp::Patch,
"delete" => EditOp::Delete,
_ => return None,
})
}
}
/// One entry in the per-file history.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct VersionEntry {
/// Globally monotonic sequence number.
pub seq: u64,
/// Agent that recorded the edit.
pub agent_id: u64,
/// Wall-clock ms since the Unix epoch.
pub timestamp_ms: i64,
/// Edit classification.
pub op: EditOp,
/// Post-edit content hash (or `0` if not applicable, e.g. `Delete`).
pub hash: u64,
/// Post-edit byte size.
pub size: u64,
}
/// Public denormalised form returned by `changes_since`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChangeRecord {
/// Workspace-relative path the edit was attributed to.
pub path: String,
/// Globally monotonic sequence number.
pub seq: u64,
/// Agent id that recorded the edit.
pub agent_id: u64,
/// Edit classification.
pub op: EditOp,
/// Post-edit hash.
pub hash: u64,
/// Post-edit size.
pub size: u64,
/// Wall-clock ms since the Unix epoch.
pub timestamp_ms: i64,
}
/// Append-only log keyed by path. Both forward query patterns —
/// "everything since X" and "the latest entry for this path" — are
/// served from the same map.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct VersionLog {
/// Latest assigned sequence number. Monotonically increases.
#[serde(default)]
pub current_seq: u64,
/// Per-path history, newest-last; capped at [`HISTORY_LIMIT`] entries.
#[serde(default)]
pub history: HashMap<String, Vec<VersionEntry>>,
}
impl VersionLog {
/// Construct an empty log.
pub fn new() -> Self {
Self::default()
}
/// Record one edit. Returns the assigned seq, which is what the host
/// builtin echoes back to the caller.
pub fn record(
&mut self,
path: impl Into<String>,
agent_id: u64,
op: EditOp,
hash: u64,
size: u64,
timestamp_ms: i64,
) -> u64 {
self.current_seq = self.current_seq.saturating_add(1);
let entry = VersionEntry {
seq: self.current_seq,
agent_id,
timestamp_ms,
op,
hash,
size,
};
let path = path.into();
let list = self.history.entry(path).or_default();
list.push(entry);
if list.len() > HISTORY_LIMIT {
let drop = list.len() - HISTORY_LIMIT;
list.drain(0..drop);
}
self.current_seq
}
/// Every change record with `seq > since`, ordered by seq ascending.
/// `limit` (when present) keeps the *most recent* `limit` entries.
pub fn changes_since(&self, since: u64, limit: Option<usize>) -> Vec<ChangeRecord> {
let mut out: Vec<ChangeRecord> = Vec::new();
for (path, entries) in &self.history {
for entry in entries {
if entry.seq > since {
out.push(ChangeRecord {
path: path.clone(),
seq: entry.seq,
agent_id: entry.agent_id,
op: entry.op,
hash: entry.hash,
size: entry.size,
timestamp_ms: entry.timestamp_ms,
});
}
}
}
out.sort_by_key(|r| r.seq);
if let Some(limit) = limit {
if out.len() > limit {
let start = out.len() - limit;
out = out.split_off(start);
}
}
out
}
/// Latest entry recorded for `path`, or `None` if untracked.
pub fn last_entry(&self, path: &str) -> Option<&VersionEntry> {
self.history.get(path).and_then(|v| v.last())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn record_assigns_monotonic_seqs() {
let mut log = VersionLog::new();
let s1 = log.record("a.rs", 1, EditOp::Write, 10, 5, 100);
let s2 = log.record("b.rs", 1, EditOp::Write, 11, 5, 110);
let s3 = log.record("a.rs", 2, EditOp::Write, 12, 5, 120);
assert_eq!((s1, s2, s3), (1, 2, 3));
assert_eq!(log.current_seq, 3);
}
#[test]
fn changes_since_returns_sorted_records() {
let mut log = VersionLog::new();
log.record("a.rs", 1, EditOp::Write, 1, 1, 100);
log.record("b.rs", 2, EditOp::Write, 2, 2, 110);
log.record("a.rs", 3, EditOp::Patch, 3, 3, 120);
let changes = log.changes_since(1, None);
let seqs: Vec<u64> = changes.iter().map(|c| c.seq).collect();
assert_eq!(seqs, vec![2, 3]);
}
#[test]
fn changes_since_respects_limit_and_keeps_most_recent() {
let mut log = VersionLog::new();
for i in 1..=5 {
log.record("a.rs", 1, EditOp::Write, i, i, i as i64);
}
let limited = log.changes_since(0, Some(2));
let seqs: Vec<u64> = limited.iter().map(|c| c.seq).collect();
assert_eq!(seqs, vec![4, 5]);
}
#[test]
fn history_caps_at_history_limit() {
let mut log = VersionLog::new();
for i in 0..(HISTORY_LIMIT + 50) {
log.record("a.rs", 1, EditOp::Write, i as u64, 0, 0);
}
let entries = log.history.get("a.rs").unwrap();
assert_eq!(entries.len(), HISTORY_LIMIT);
// Front of the list rolled off — the very first record is gone.
assert!(entries.first().unwrap().seq > 1);
}
#[test]
fn edit_op_round_trips_through_str_form() {
for op in [
EditOp::Snapshot,
EditOp::Write,
EditOp::ReplaceRange,
EditOp::InsertAfter,
EditOp::DeleteRange,
EditOp::Patch,
EditOp::Delete,
] {
assert_eq!(EditOp::parse(op.as_str()), Some(op));
}
assert_eq!(EditOp::parse("unknown"), None);
}
}