codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
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
//! Merge drivers: configurable per-file conflict resolution (subprocess drivers,
//! syntax-aware guards) used by the merge engine in `merge.rs`.

use crate::error::Result;
use crate::resolution::{ConflictInfo, ResolutionCache};
use super::objects::{Tree, TreeEntry};
use super::manager::VcsManager;

impl VcsManager {
    /// Find the configured merge driver command for a path (first glob match).
    pub(super) fn merge_driver_for(&self, path: &str) -> Option<&String> {
        if self.merge_drivers.is_empty() {
            return None;
        }
        self.merge_drivers
            .iter()
            .find(|(pattern, _)| glob_match(pattern, path))
            .map(|(_, cmd)| cmd)
    }

    /// Resolve conflicts via the resolution cache, then configured merge
    /// drivers (TODO Round 13: pluggable, syntax-aware merging à la mergiraf).
    ///
    /// All-or-nothing: every conflict must resolve or the merge falls through
    /// to first-class conflicts (consistent with the previous cache-only
    /// behavior). Driver resolutions are recorded into `cache` so identical
    /// future conflicts auto-resolve — callers must persist the cache.
    /// Returns (final_entries, fully_resolved, driver_resolved_paths).
    pub(super) fn resolve_conflicts_via_cache_and_drivers(
        &self,
        conflicts: &[ConflictInfo],
        merged_entries: &[TreeEntry],
        base_tree: &Tree,
        cache: &mut ResolutionCache,
    ) -> Result<(Vec<TreeEntry>, bool, Vec<String>)> {
        let mut final_entries = merged_entries.to_vec();
        let mut resolved = true;
        let mut driver_resolved = Vec::new();

        for conflict in conflicts {
            if let Some(resolved_blob) = cache
                .get(&conflict.path, &conflict.our_blob, &conflict.their_blob)
                .map(|s| s.to_string())
            {
                final_entries.retain(|e: &TreeEntry| e.name != conflict.path);
                final_entries.push(TreeEntry {
                    mode: 0o100644,
                    name: conflict.path.clone(),
                    id: resolved_blob,
                });
                continue;
            }

            let driver = match self.merge_driver_for(&conflict.path) {
                Some(cmd) => cmd.clone(),
                None => {
                    resolved = false;
                    break;
                }
            };

            let base_blob = base_tree
                .entries
                .iter()
                .find(|e| e.name == conflict.path)
                .map(|e| e.id.clone());

            match self.run_merge_driver(
                &driver,
                &conflict.path,
                base_blob.as_deref(),
                &conflict.our_blob,
                &conflict.their_blob,
            )? {
                Some(resolved_blob) => {
                    // JSON guard: a driver must not silently create duplicate
                    // keys (line-merging JSON corrupts data this way — mergiraf
                    // flags it; so do we).
                    if conflict.path.ends_with(".json")
                        && let Some(dup) =
                            json_duplicate_key(&self.repo.read_blob(&resolved_blob)?.content)
                    {
                        warn!(
                            "Merge driver resolved '{}' but produced duplicate key '{}' — keeping the conflict",
                            conflict.path, dup
                        );
                        resolved = false;
                        break;
                    }
                    cache.set(&conflict.path, &conflict.our_blob, &conflict.their_blob, &resolved_blob);
                    driver_resolved.push(conflict.path.clone());
                    final_entries.retain(|e: &TreeEntry| e.name != conflict.path);
                    final_entries.push(TreeEntry {
                        mode: 0o100644,
                        name: conflict.path.clone(),
                        id: resolved_blob,
                    });
                }
                None => {
                    resolved = false;
                    break;
                }
            }
        }

        Ok((final_entries, resolved, driver_resolved))
    }

    /// Run a merge driver subprocess for one conflicting file. Returns the
    /// resolved blob id, or `None` when the driver cannot resolve (non-zero
    /// exit, spawn failure, or no result written). Driver failure never fails
    /// the merge itself — it falls back to first-class conflicts.
    fn run_merge_driver(
        &self,
        template: &str,
        path: &str,
        base_blob: Option<&str>,
        our_blob: &str,
        their_blob: &str,
    ) -> Result<Option<String>> {
        static DIR_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let dir = std::env::temp_dir().join(format!(
            "codetree-merge-{}-{}",
            std::process::id(),
            DIR_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
        ));
        if std::fs::create_dir_all(&dir).is_err() {
            return Ok(None);
        }

        let base_p = dir.join("base");
        let ours_p = dir.join("ours");
        let theirs_p = dir.join("theirs");
        let result_p = dir.join("result");

        let setup = (|| -> Result<()> {
            let base_content = match base_blob {
                Some(b) => self.repo.read_blob(&b.to_string())?.content,
                None => Vec::new(),
            };
            std::fs::write(&base_p, base_content)?;
            std::fs::write(&ours_p, self.repo.read_blob(&our_blob.to_string())?.content)?;
            std::fs::write(&theirs_p, self.repo.read_blob(&their_blob.to_string())?.content)?;
            Ok(())
        })();
        if setup.is_err() {
            let _ = std::fs::remove_dir_all(&dir);
            return Ok(None);
        }

        // Shell-quote each path, then substitute into the template.
        let q = |p: &std::path::Path| format!("'{}'", p.to_string_lossy().replace('\'', "'\\''"));
        let cmd = template
            .replace("%base", &q(&base_p))
            .replace("%ours", &q(&ours_p))
            .replace("%theirs", &q(&theirs_p))
            .replace("%result", &q(&result_p));

        info!("Merge driver for '{}': {}", path, cmd);
        let outcome = match std::process::Command::new("sh").arg("-c").arg(&cmd).output() {
            Ok(out) if out.status.success() => match std::fs::read(&result_p) {
                Ok(content) => Ok(Some(self.repo.write_blob(&content)?)),
                Err(_) => Ok(None), // succeeded but wrote no result
            },
            _ => Ok(None), // non-zero exit or spawn failure → cannot resolve
        };

        let _ = std::fs::remove_dir_all(&dir);
        outcome
    }

}

// ── Merge driver helpers ────────────────────────────────────────

/// Minimal glob matcher for driver patterns: `*` (any), `prefix*`,
/// `*suffix`, `prefix*suffix`, or exact match. No regex dependency
/// (same shape as the revset `branches(pattern)` matcher).
fn glob_match(pattern: &str, path: &str) -> bool {
    if pattern == "*" {
        return true;
    }
    if let Some(prefix) = pattern.strip_suffix('*') {
        return path.starts_with(prefix);
    }
    if let Some(suffix) = pattern.strip_prefix('*') {
        return path.ends_with(suffix);
    }
    if let Some((pre, suf)) = pattern.split_once('*') {
        return path.starts_with(pre)
            && path.ends_with(suf)
            && path.len() >= pre.len() + suf.len();
    }
    pattern == path
}

/// Detect duplicate keys in a JSON document; returns the first duplicated
/// key. Conservative: any parse anomaly (or trailing garbage) returns `None`
/// — the guard must never block a merge on a maybe.
pub(super) fn json_duplicate_key(content: &[u8]) -> Option<String> {
    let mut parser = JsonParser { bytes: content, pos: 0 };
    // A duplicate is reported as soon as it is seen — the rest of the
    // document is irrelevant once the data is provably corrupted.
    parser.parse_value()
}

/// Minimal recursive-descent JSON scanner used only for duplicate-key
/// detection. Not a validator — it bails (returns None) on anything it
/// doesn't understand.
struct JsonParser<'a> {
    bytes: &'a [u8],
    pos: usize,
}

impl<'a> JsonParser<'a> {

    fn skip_ws(&mut self) {
        while self.pos < self.bytes.len()
            && matches!(self.bytes[self.pos], b' ' | b'\t' | b'\n' | b'\r')
        {
            self.pos += 1;
        }
    }

    fn peek(&mut self) -> Option<u8> {
        self.skip_ws();
        self.bytes.get(self.pos).copied()
    }

    fn parse_value(&mut self) -> Option<String> {
        match self.peek()? {
            b'{' => self.parse_object(),
            b'[' => self.parse_array(),
            b'"' => {
                self.parse_string()?;
                None
            }
            b't' => {
                self.expect_lit("true")?;
                None
            }
            b'f' => {
                self.expect_lit("false")?;
                None
            }
            b'n' => {
                self.expect_lit("null")?;
                None
            }
            b'-' | b'0'..=b'9' => {
                self.parse_number();
                None
            }
            _ => None, // unrecognized → don't flag
        }
    }

    fn parse_object(&mut self) -> Option<String> {
        self.pos += 1; // consume '{'
        let mut keys = std::collections::HashSet::new();
        if self.peek()? == b'}' {
            self.pos += 1;
            return None;
        }
        loop {
            if self.peek()? != b'"' {
                return None;
            }
            let key = self.parse_string()?;
            if self.peek()? != b':' {
                return None;
            }
            self.pos += 1;
            if keys.contains(&key) {
                return Some(key);
            }
            keys.insert(key);
            if let Some(dup) = self.parse_value() {
                return Some(dup);
            }
            match self.peek()? {
                b',' => self.pos += 1,
                b'}' => {
                    self.pos += 1;
                    return None;
                }
                _ => return None,
            }
        }
    }

    fn parse_array(&mut self) -> Option<String> {
        self.pos += 1; // consume '['
        if self.peek()? == b']' {
            self.pos += 1;
            return None;
        }
        loop {
            if let Some(dup) = self.parse_value() {
                return Some(dup);
            }
            match self.peek()? {
                b',' => self.pos += 1,
                b']' => {
                    self.pos += 1;
                    return None;
                }
                _ => return None,
            }
        }
    }

    /// Read a JSON string. Escapes are decoded only enough for consistent
    /// key comparison (`\uXXXX` is skipped, not decoded — identical inputs
    /// still compare equal, which is all dup detection needs).
    fn parse_string(&mut self) -> Option<String> {
        self.pos += 1; // consume '"'
        let mut out = String::new();
        loop {
            let b = *self.bytes.get(self.pos)?;
            self.pos += 1;
            match b {
                b'"' => return Some(out),
                b'\\' => {
                    let esc = *self.bytes.get(self.pos)?;
                    self.pos += 1;
                    if esc == b'u' {
                        if self.pos + 4 > self.bytes.len() {
                            return None;
                        }
                        self.pos += 4;
                    } else {
                        out.push(esc as char);
                    }
                }
                _ => out.push(b as char),
            }
        }
    }

    fn expect_lit(&mut self, lit: &str) -> Option<()> {
        if self.bytes[self.pos..].starts_with(lit.as_bytes()) {
            self.pos += lit.len();
            Some(())
        } else {
            None
        }
    }

    fn parse_number(&mut self) {
        while self.pos < self.bytes.len()
            && matches!(self.bytes[self.pos], b'0'..=b'9' | b'-' | b'+' | b'.' | b'e' | b'E')
        {
            self.pos += 1;
        }
    }
}

#[cfg(test)]
mod merge_driver_tests {
    use super::*;

    #[test]

    fn test_glob_match() {
        assert!(glob_match("*.json", "config.json"));
        assert!(glob_match("*.json", "src/config.json"));
        assert!(!glob_match("*.json", "config.toml"));
        assert!(glob_match("src/*", "src/main.rs"));
        assert!(!glob_match("src/*", "lib/main.rs"));
        assert!(glob_match("src/*.rs", "src/main.rs"));
        assert!(!glob_match("src/*.rs", "src/main.toml"));
        assert!(glob_match("*", "anything/x"));
        assert!(glob_match("exact.txt", "exact.txt"));
        assert!(!glob_match("exact.txt", "other.txt"));
    }

    #[test]

    fn test_json_duplicate_key() {
        assert_eq!(json_duplicate_key(br#"{"a":1,"b":2}"#), None);
        assert_eq!(json_duplicate_key(br#"{"a":1,"a":2}"#).as_deref(), Some("a"));
        // the silent line-merge corruption: same key added at both ends
        assert_eq!(
            json_duplicate_key(br#"{"k":"ours","a":1,"k":"theirs"}"#).as_deref(),
            Some("k")
        );
        // nested objects
        assert_eq!(json_duplicate_key(br#"{"x":{"y":1,"y":2}}"#).as_deref(), Some("y"));
        // arrays of objects
        assert_eq!(
            json_duplicate_key(br#"[{"a":1},{"a":1,"a":2}]"#).as_deref(),
            Some("a")
        );
        // escapes decode consistently
        assert_eq!(
            json_duplicate_key(br#"{"a\"b":1,"a\"b":2}"#).as_deref(),
            Some("a\"b")
        );
        // invalid JSON / trailing garbage → None (never blocks on a maybe)
        assert_eq!(json_duplicate_key(br#"{"a":}"#), None);
        assert_eq!(json_duplicate_key(br#"not json"#), None);
        assert_eq!(json_duplicate_key(br#"{"a":1} trailing"#), None);
        assert_eq!(json_duplicate_key(br#""scalar""#), None);
        assert_eq!(json_duplicate_key(b""), None);
    }

}