car-server-core 0.47.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Merge-back: deliver the worktree's changes to the repository.
//!
//! Two destinations, by session kind:
//! - **Raw repo** ([`publish_branch`]): the worktree gets one squash commit
//!   (authored as `car-coder` — honest attribution) and the only thing that
//!   touches the user's repository is `git branch car/coder/<id> <commit>`.
//!   Branches are shared across worktrees, so this never disturbs the user's
//!   checkout, index, or any existing ref; reverting is `git branch -D`.
//! - **Managed project** ([`commit_to_main`]): the project is fully CAR-owned,
//!   so there is no separate "user working tree" to protect — approve commits
//!   straight to the project's `main` (fast-forward only). The non-dev sees
//!   "Saved", not a branch to merge; reverting is ordinary git history.

use std::path::Path;

use super::contract::OutcomeContract;

/// Stage all worktree changes and create the CAR-Coder commit. Returns the new
/// commit SHA. Errors when the worktree has nothing to commit. Shared by both
/// delivery paths.
fn commit_worktree(
    worktree: &Path,
    intent: &str,
    contract: &OutcomeContract,
) -> Result<String, String> {
    let status = git(worktree, &["status", "--porcelain"])?;
    if status.trim().is_empty() {
        return Err("no changes to deliver — the worktree is clean".to_string());
    }
    git(worktree, &["add", "-A"])?;

    let subject: String = {
        let s = intent.trim().replace('\n', " ");
        if s.len() > 72 {
            let mut end = 69;
            while !s.is_char_boundary(end) {
                end -= 1;
            }
            format!("{}...", &s[..end])
        } else {
            s
        }
    };
    let body = format!(
        "Authored by CAR Coder.\n\nIntent:\n{}\n\nOutcome contract (all checks passed):\n{}",
        intent.trim(),
        contract.render()
    );
    git(
        worktree,
        &[
            "-c",
            "user.name=car-coder",
            "-c",
            "user.email=coder@parslee.ai",
            "commit",
            "-m",
            &subject,
            "-m",
            &body,
        ],
    )?;
    Ok(git(worktree, &["rev-parse", "HEAD"])?.trim().to_string())
}

/// Result of a publish: the branch name to merge from.
pub fn publish_branch(
    repo: &Path,
    worktree: &Path,
    short_id: &str,
    intent: &str,
    contract: &OutcomeContract,
) -> Result<String, String> {
    let commit = commit_worktree(worktree, intent, contract)?;
    let branch = format!("car/coder/{short_id}");
    // `git branch` (no checkout) in the original repo: refs are shared with
    // the worktree, so this is pure bookkeeping — no working-tree effects.
    git(repo, &["branch", &branch, &commit])?;
    Ok(branch)
}

/// Deliver to a managed project's `main`. The worktree was checked out detached
/// at `main`'s tip, so its commit is a direct descendant — a fast-forward
/// updates both the `main` ref and the project's checkout. **ff-only**: if
/// `main` moved since the session started (something committed underneath us),
/// this errors instead of rebasing or forcing, preserving the guarantee that
/// the diff the user approved is exactly what lands. Returns the commit SHA.
pub fn commit_to_main(
    repo: &Path,
    worktree: &Path,
    intent: &str,
    contract: &OutcomeContract,
) -> Result<String, String> {
    let commit = commit_worktree(worktree, intent, contract)?;
    git(repo, &["merge", "--ff-only", &commit]).map_err(|e| {
        format!("could not fast-forward the project's main branch (it moved since the session started): {e}")
    })?;
    Ok(commit)
}

/// The staged diff as the approval surface needs it.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct StagedDiff {
    /// `git diff --cached --stat`, never truncated — it is small, and it is the
    /// one view that stays complete however large the patch gets.
    pub stat: String,
    /// The patch, tail-capped to the configured budget.
    pub patch: String,
    /// Whether `patch` is a tail rather than the whole thing. Carried as a
    /// field, not just the `…[truncated]…` marker inside the string, so a UI can
    /// say so without string-matching (car#706).
    pub truncated: bool,
    /// Size of the untruncated patch, so the surface can report how much was
    /// withheld.
    pub full_bytes: usize,
    /// Every repo-relative path the diff touches, sorted and deduped — for
    /// contract-overlap disclosure and the changed-file summary at the gate.
    ///
    /// Includes BOTH endpoints of a rename. See [`parse_name_status_z`] for why
    /// the destination alone is not an honest answer.
    pub changed_paths: Vec<String>,
}

/// Stage everything and collect the diff for the approval UI. Staging is what
/// `publish_branch` would commit anyway, and it makes untracked files visible.
///
/// `patch_cap_bytes` bounds only the patch body. The review surface used to
/// shrink exactly as the risk grew: the cap was a hardcoded 32 KB tail, so on a
/// long session — the regime where the automated check is weakest — the human
/// approved against a partial patch, with the fact of truncation buried in a
/// marker inside the string.
pub fn stage_and_diff(worktree: &Path, patch_cap_bytes: usize) -> Result<StagedDiff, String> {
    git(worktree, &["add", "-A"])?;
    let stat = git(worktree, &["diff", "--cached", "--stat"])?;
    let patch = git(worktree, &["diff", "--cached"])?;
    let names = git(
        worktree,
        &[
            // Redundant insurance, NOT the mechanism: `-z` below already emits
            // raw bytes, so non-ASCII paths arrive unquoted with or without
            // this. It matters only if someone later drops `-z`, at which point
            // paths would come back C-escaped (`café.txt` as the literal
            // `"caf\303\251.txt"`, quotes included) and match nothing.
            "-c",
            "core.quotepath=false",
            "diff",
            "--cached",
            // `--name-status -z`, NOT `--name-only`. Rename detection reports
            // only the DESTINATION under `--name-only`, so
            // `git mv secrets/key.txt public_key.txt` yielded exactly
            // `["public_key.txt"]` and the fact that `secrets/` was touched
            // vanished. Any consumer reasoning about which paths a session
            // affected was being told a rename is a creation. `-z` additionally
            // makes paths NUL-delimited, so a newline in a filename cannot
            // forge an entry.
            "--name-status",
            "-z",
        ],
    )?;
    let changed_paths = parse_name_status_z(&names);
    let full_bytes = patch.len();
    Ok(StagedDiff {
        patch: super::shell_tool::tail(&patch, patch_cap_bytes),
        truncated: full_bytes > patch_cap_bytes,
        full_bytes,
        stat,
        changed_paths,
    })
}

/// Parse `git diff --cached --name-status -z` into every path the diff touches.
///
/// The `-z` stream is a flat run of NUL-terminated fields. Most entries are two
/// fields — a status letter then a path. Rename (`R`) and copy (`C`) entries are
/// three: the status carries a similarity score, then the SOURCE path, then the
/// destination. **Both endpoints are returned**, because a caller asking "what
/// did this session touch" is asking about the source too: a file moved out of a
/// directory is a change to that directory, and reporting only the destination
/// is how `--name-only` made `git mv secrets/key.txt public_key.txt` look like
/// the creation of an unrelated file.
fn parse_name_status_z(raw: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut fields = raw.split('\0').filter(|f| !f.is_empty());
    while let Some(status) = fields.next() {
        // Git's status set is closed — A C D M R T U X B — with `R`/`C`
        // carrying a similarity score (`R100`) and `M` optionally a
        // dissimilarity score under `-B`. Validate rather than assume: if a
        // field that is NOT a status reaches here, the loop reads a path as a
        // status and every subsequent field shifts by one, emitting a list of
        // plausible-looking fictional paths — onto a reviewer's approval screen,
        // as fact. A short list plus a warning is recoverable; silent fiction is
        // not, so bail loudly instead of guessing.
        let bytes = status.as_bytes();
        let well_formed = status.len() <= 4
            && matches!(
                bytes[0],
                b'A' | b'C' | b'D' | b'M' | b'R' | b'T' | b'U' | b'X' | b'B'
            )
            && status[1..].bytes().all(|b| b.is_ascii_digit());
        if !well_formed {
            tracing::warn!(
                status = %status,
                "unexpected field in `git diff --name-status -z`; changed-path list truncated \
                 rather than risk a desynchronized parse"
            );
            break;
        }
        // A rename/copy is followed by two paths rather than one.
        let two_paths = bytes[0] == b'R' || bytes[0] == b'C';
        let Some(first) = fields.next() else {
            tracing::warn!(status = %status, "name-status stream ended mid-entry");
            break;
        };
        out.push(first.to_string());
        if two_paths {
            match fields.next() {
                Some(second) => out.push(second.to_string()),
                // A rename with no destination is a corrupt stream, not an
                // entry to swallow silently.
                None => {
                    tracing::warn!(status = %status, "rename/copy entry missing its destination");
                    break;
                }
            }
        }
    }
    out.sort();
    out.dedup();
    out
}

pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String, String> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .map_err(|e| format!("git {args:?}: {e}"))?;
    if out.status.success() {
        Ok(String::from_utf8_lossy(&out.stdout).into_owned())
    } else {
        Err(format!(
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::coder::contract::ContractCheck;

    fn contract() -> OutcomeContract {
        OutcomeContract {
            description: "x exists".into(),
            checks: vec![ContractCheck {
                name: "exists".into(),
                command: "test -f x.txt".into(),
                expect_exit_zero: true,
                output_contains: None,
                timeout_secs: 10,
            }],
        }
    }

    fn init_repo(dir: &Path) {
        for args in [
            vec!["init", "-q", "-b", "main"],
            vec![
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "commit",
                "-q",
                "--allow-empty",
                "-m",
                "init",
            ],
        ] {
            let out = std::process::Command::new("git")
                .arg("-C")
                .arg(dir)
                .args(&args)
                .output()
                .unwrap();
            assert!(
                out.status.success(),
                "{}",
                String::from_utf8_lossy(&out.stderr)
            );
        }
    }

    #[test]
    fn publishes_branch_without_touching_user_checkout() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);

        // Provision a worktree the way a session does.
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo, wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-merge-test").unwrap();

        std::fs::write(ws.path().join("x.txt"), "made by coder").unwrap();
        let branch = publish_branch(
            repo,
            ws.path(),
            "abc12345",
            "create x.txt with content",
            &contract(),
        )
        .unwrap();
        assert_eq!(branch, "car/coder/abc12345");

        // The branch exists in the user's repo and contains the file…
        let show = git(repo, &["show", &format!("{branch}:x.txt")]).unwrap();
        assert_eq!(show, "made by coder");
        // …attributed to the coder…
        let author = git(repo, &["log", "-1", "--format=%an", &branch]).unwrap();
        assert_eq!(author.trim(), "car-coder");
        // …and the user's checkout is untouched.
        let status = git(repo, &["status", "--porcelain"]).unwrap();
        assert!(status.is_empty(), "user checkout dirtied: {status}");
        assert!(!repo.join("x.txt").exists());
    }

    #[test]
    fn clean_worktree_refuses_to_publish() {
        let repo_dir = tempfile::tempdir().unwrap();
        init_repo(repo_dir.path());
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo_dir.path(), wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-clean-test").unwrap();

        let err =
            publish_branch(repo_dir.path(), ws.path(), "def", "noop", &contract()).unwrap_err();
        assert!(err.contains("no changes"), "{err}");
    }

    #[test]
    fn long_intent_is_truncated_in_subject() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo, wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-long-test").unwrap();
        std::fs::write(ws.path().join("y.txt"), "y").unwrap();

        let long_intent = "a very ".repeat(40) + "long intent";
        let branch = publish_branch(repo, ws.path(), "fff", &long_intent, &contract()).unwrap();
        let subject = git(repo, &["log", "-1", "--format=%s", &branch]).unwrap();
        assert!(subject.trim().len() <= 72);
        assert!(subject.contains("..."));
    }

    #[test]
    fn commit_to_main_fast_forwards_the_checkout() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo, wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-main-test").unwrap();
        std::fs::write(ws.path().join("z.txt"), "managed").unwrap();

        let commit = commit_to_main(repo, ws.path(), "add z", &contract()).unwrap();
        // main fast-forwarded to the commit; the file is in the repo checkout.
        let head = git(repo, &["rev-parse", "HEAD"]).unwrap();
        assert_eq!(head.trim(), commit);
        assert_eq!(
            std::fs::read_to_string(repo.join("z.txt")).unwrap(),
            "managed"
        );
        // No coder branch.
        assert!(git(repo, &["branch", "--list", "car/coder/*"])
            .unwrap()
            .is_empty());
    }

    #[test]
    fn commit_to_main_errors_when_main_moved() {
        let repo_dir = tempfile::tempdir().unwrap();
        let repo = repo_dir.path();
        init_repo(repo);
        let wt_base = tempfile::tempdir().unwrap();
        let config = car_multi::WorkspaceConfig::git_worktree_at(repo, wt_base.path());
        let ws = car_multi::AgentWorkspace::provision(&config, "coder-moved-test").unwrap();
        std::fs::write(ws.path().join("a.txt"), "from session").unwrap();

        // Something commits to main AFTER the worktree was provisioned, so the
        // worktree's commit is no longer a fast-forward of main.
        std::fs::write(repo.join("b.txt"), "concurrent").unwrap();
        for args in [
            vec!["-c", "user.name=t", "-c", "user.email=t@t", "add", "-A"],
            vec![
                "-c",
                "user.name=t",
                "-c",
                "user.email=t@t",
                "commit",
                "-q",
                "-m",
                "concurrent",
            ],
        ] {
            assert!(std::process::Command::new("git")
                .arg("-C")
                .arg(repo)
                .args(&args)
                .output()
                .unwrap()
                .status
                .success());
        }

        let err = commit_to_main(repo, ws.path(), "add a", &contract()).unwrap_err();
        assert!(err.contains("fast-forward"), "{err}");
    }

    // --- Rename-aware, byte-safe changed paths ---------------------------

    /// **The bypass this parser exists to close.** Under `--name-only`, git
    /// reports only a rename's destination, so moving a file OUT of a directory
    /// erased every trace of that directory from the change record. Anything
    /// reasoning about which paths a session touched was told a rename is a
    /// creation.
    #[test]
    fn a_rename_reports_both_endpoints_not_just_the_destination() {
        let paths = parse_name_status_z("R100\0secrets/key.txt\0public_key.txt\0");
        assert!(
            paths.contains(&"secrets/key.txt".to_string()),
            "the source directory must not vanish: {paths:?}"
        );
        assert!(paths.contains(&"public_key.txt".to_string()), "{paths:?}");
        assert_eq!(paths.len(), 2);
    }

    /// A copy carries the same three-field shape as a rename.
    #[test]
    fn a_copy_also_reports_both_endpoints() {
        let paths = parse_name_status_z("C75\0src/a.rs\0src/b.rs\0");
        assert_eq!(paths, vec!["src/a.rs".to_string(), "src/b.rs".to_string()]);
    }

    /// Ordinary two-field entries, and the mixed stream — a rename's extra
    /// field must not desynchronize the ones that follow it.
    #[test]
    fn mixed_entries_stay_in_sync_after_a_rename() {
        let paths = parse_name_status_z("M\0src/a.rs\0R100\0old/x.rs\0new/x.rs\0A\0src/z.rs\0");
        assert_eq!(
            paths,
            vec![
                "new/x.rs".to_string(),
                "old/x.rs".to_string(),
                "src/a.rs".to_string(),
                "src/z.rs".to_string(),
            ]
        );
    }

    /// A newline inside a filename must not be able to forge an entry — the
    /// reason for `-z` over line-splitting.
    #[test]
    fn a_newline_in_a_filename_does_not_forge_an_entry() {
        let paths = parse_name_status_z("A\0we\nird.txt\0");
        assert_eq!(paths, vec!["we\nird.txt".to_string()]);
    }

    #[test]
    fn an_empty_diff_yields_no_paths() {
        assert!(parse_name_status_z("").is_empty());
    }

    /// `T` (type change, e.g. file -> symlink) and `U` (unmerged) are
    /// single-path entries. Verified against real git; pinned here because the
    /// whole parser rests on "only R and C carry two paths".
    #[test]
    fn type_change_and_unmerged_are_single_path_entries() {
        assert_eq!(
            parse_name_status_z("T\0src/link.txt\0M\0src/after.rs\0"),
            vec!["src/after.rs".to_string(), "src/link.txt".to_string()]
        );
        assert_eq!(
            parse_name_status_z("U\0conflict.txt\0"),
            vec!["conflict.txt".to_string()]
        );
    }

    /// **The desync guard.** A field that is not a status means git's format
    /// moved under us; continuing would read paths as statuses and emit
    /// plausible-looking fiction onto a reviewer's approval screen. Bail.
    #[test]
    fn an_unrecognized_status_bails_instead_of_desynchronizing() {
        // `Z9` is not in git's closed status set.
        assert!(parse_name_status_z("Z9\0a.txt\0b.txt\0").is_empty());
        // A well-formed prefix is kept; the garbage tail is dropped, not guessed.
        assert_eq!(
            parse_name_status_z("M\0good.rs\0Z9\0a.txt\0"),
            vec!["good.rs".to_string()]
        );
    }

    /// A rename whose destination field never arrived is a corrupt stream, not
    /// an entry to swallow.
    #[test]
    fn a_rename_missing_its_destination_bails() {
        assert_eq!(
            parse_name_status_z("R100\0only-one.txt\0"),
            vec!["only-one.txt".to_string()]
        );
    }

    /// End-to-end against real git: the rename bypass, reproduced and closed.
    #[test]
    fn stage_and_diff_sees_a_renamed_out_of_directory_source() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path();
        for args in [
            vec!["init", "-q", "."],
            vec!["config", "user.email", "t@t"],
            vec!["config", "user.name", "t"],
        ] {
            git(repo, &args).unwrap();
        }
        std::fs::create_dir(repo.join("secrets")).unwrap();
        std::fs::write(repo.join("secrets/key.txt"), "k").unwrap();
        git(repo, &["add", "-A"]).unwrap();
        git(repo, &["commit", "-qm", "init"]).unwrap();
        std::fs::rename(repo.join("secrets/key.txt"), repo.join("public_key.txt")).unwrap();

        let diff = stage_and_diff(repo, 64 * 1024).unwrap();
        assert!(
            diff.changed_paths.iter().any(|p| p.starts_with("secrets/")),
            "the source directory must appear: {:?}",
            diff.changed_paths
        );
        // Exactly the two endpoints — a parser that emitted status letters as
        // paths would also satisfy the assertion above.
        assert_eq!(
            diff.changed_paths,
            vec!["public_key.txt".to_string(), "secrets/key.txt".to_string()],
            "both endpoints, and nothing else"
        );
    }
}