omh 0.1.0

Launch any coding harness, in a sandbox, with your setup already there.
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
//! Carry-in.
//!
//! A git worktree holds only tracked files, so an agent lands somewhere with no
//! `.env`, no certs, no local config — a checkout that cannot run the app it is
//! supposed to work on. `carry_in` names what to copy across.
//!
//! It is deliberately an allowlist, because **this is the only path by which a
//! secret reaches the agent**. Carrying everything gitignored would sweep in
//! every credential you happen to have lying around.
//!
//! Copy, not symlink: a symlink's target would have to resolve inside the
//! sandbox, which would mean mounting your main checkout — exposing the
//! uncommitted work the worktree model exists to protect.

use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Copied,
    /// The source changed since it was carried.
    Refreshed,
    Unchanged,
    /// Listed but not present in the checkout.
    Missing,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Carried {
    pub path: String,
    pub action: Action,
}

/// A pattern names something inside the repo, and nothing else.
///
/// `carry_in` is read from a *committed* layer, so a malicious or careless
/// entry like `../../.ssh` would copy host secrets into a sandbox the agent
/// controls.
pub fn validate_pattern(pattern: &str) -> Result<()> {
    let p = pattern.trim();
    if p.is_empty() {
        anyhow::bail!("an empty carry_in entry names nothing");
    }
    if p.starts_with('/') || p.starts_with('~') {
        anyhow::bail!("carry_in is relative to the repository: `{pattern}`");
    }
    if Path::new(p)
        .components()
        .any(|c| matches!(c, std::path::Component::ParentDir))
    {
        anyhow::bail!("carry_in cannot reach outside the repository: `{pattern}`");
    }
    Ok(())
}

/// Copy the listed paths from the checkout into the worktree.
pub fn apply(repo: &Path, worktree: &Path, patterns: &[String]) -> Result<Vec<Carried>> {
    // Validate everything before copying anything: a list with one bad entry
    // should not half-apply.
    for pattern in patterns {
        validate_pattern(pattern)?;
    }

    let mut out = Vec::new();
    for pattern in patterns {
        let rel = pattern.trim().trim_end_matches('/');
        let src = repo.join(rel);
        let dst = worktree.join(rel);
        let action = if !src.exists() {
            Action::Missing
        } else if src.is_dir() {
            copy_dir(&src, &dst)?
        } else {
            copy_file(&src, &dst)?
        };
        out.push(Carried {
            path: pattern.clone(),
            action,
        });
    }

    exclude(worktree, patterns)?;
    Ok(out)
}

/// The checkout is the source of truth for carried files — they are yours, not
/// the agent's — so a changed source replaces the copy.
fn copy_file(src: &Path, dst: &Path) -> Result<Action> {
    let incoming = std::fs::read(src).with_context(|| format!("reading {}", src.display()))?;
    if std::fs::read(dst)
        .map(|existing| existing == incoming)
        .unwrap_or(false)
    {
        return Ok(Action::Unchanged);
    }
    let existed = dst.exists();
    if let Some(parent) = dst.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(dst, incoming).with_context(|| format!("writing {}", dst.display()))?;
    Ok(if existed {
        Action::Refreshed
    } else {
        Action::Copied
    })
}

fn copy_dir(src: &Path, dst: &Path) -> Result<Action> {
    std::fs::create_dir_all(dst)?;
    let mut action = Action::Unchanged;
    for entry in std::fs::read_dir(src)?.flatten() {
        let from = entry.path();
        let to = dst.join(entry.file_name());
        let result = if from.is_dir() {
            copy_dir(&from, &to)?
        } else {
            copy_file(&from, &to)?
        };
        // The directory as a whole is as changed as its most-changed member.
        if result != Action::Unchanged && action == Action::Unchanged {
            action = result;
        }
    }
    Ok(action)
}

/// Where a worktree's private ignore rules live.
///
/// Two traps here, both found empirically. `<worktree>/.git` is a *file*
/// pointing at the admin directory, not a directory — and git reads
/// `info/exclude` from the **common** git dir, not the per-worktree one, so
/// writing to `.git/worktrees/<id>/info/exclude` silently does nothing.
///
/// Consequence worth naming: this file is shared with the main checkout. It is
/// never committed, and carried paths are untracked there by definition, so the
/// effect is invisible — but it is not scoped to the worktree.
pub fn exclude_path(worktree: &Path) -> Option<PathBuf> {
    let out = std::process::Command::new("git")
        .current_dir(worktree)
        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let dir = String::from_utf8_lossy(&out.stdout).trim().to_string();
    Some(PathBuf::from(dir).join("info/exclude"))
}

/// Hide the rules omh stages into the worktree. Left untracked, the agent is
/// invited to commit omh's own staging onto the session branch.
pub fn hide_staged_rules(worktree: &Path) -> Result<()> {
    exclude(
        worktree,
        &["CLAUDE.md".to_string(), "AGENTS.md".to_string()],
    )
}

/// Keep carried files out of the agent's `git status`, so they never show up as
/// untracked noise or get committed onto the session branch.
fn exclude(worktree: &Path, patterns: &[String]) -> Result<()> {
    let Some(path) = exclude_path(worktree) else {
        // A scratch directory has no git at all; nothing to keep clean.
        return Ok(());
    };
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut body = std::fs::read_to_string(&path).unwrap_or_default();
    for pattern in patterns {
        let line = pattern.trim();
        if body.lines().any(|l| l.trim() == line) {
            continue;
        }
        if !body.is_empty() && !body.ends_with('\n') {
            body.push('\n');
        }
        body.push_str(line);
        body.push('\n');
    }
    std::fs::write(&path, body).with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

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

    fn repo(files: &[(&str, &str)]) -> (tempfile::TempDir, PathBuf, PathBuf) {
        let d = tempfile::tempdir().unwrap();
        let repo = d.path().join("repo");
        let worktree = d.path().join("wt");
        std::fs::create_dir_all(repo.join(".git/info")).unwrap();
        std::fs::create_dir_all(&worktree).unwrap();
        for (name, body) in files {
            let p = repo.join(name);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(p, body).unwrap();
        }
        (d, repo, worktree)
    }

    fn carry(repo: &Path, wt: &Path, list: &[&str]) -> Vec<Carried> {
        let owned: Vec<String> = list.iter().map(|s| s.to_string()).collect();
        apply(repo, wt, &owned).unwrap()
    }

    // ── copying ─────────────────────────────────────────────────────────────

    #[test]
    fn a_listed_file_reaches_the_worktree() {
        let (_d, repo, wt) = repo(&[(".env.local", "SECRET=1")]);
        let out = carry(&repo, &wt, &[".env.local"]);

        assert_eq!(
            std::fs::read_to_string(wt.join(".env.local")).unwrap(),
            "SECRET=1"
        );
        assert_eq!(out[0].action, Action::Copied);
    }

    #[test]
    fn a_listed_directory_is_carried_whole() {
        let (_d, repo, wt) = repo(&[("certs/dev.pem", "cert"), ("certs/nested/ca.pem", "ca")]);
        carry(&repo, &wt, &["certs/"]);

        assert_eq!(
            std::fs::read_to_string(wt.join("certs/dev.pem")).unwrap(),
            "cert"
        );
        assert_eq!(
            std::fs::read_to_string(wt.join("certs/nested/ca.pem")).unwrap(),
            "ca"
        );
    }

    /// A `.env` you thought you were carrying and are not is exactly the
    /// failure that wastes an hour inside the sandbox.
    #[test]
    fn a_listed_path_that_does_not_exist_is_reported() {
        let (_d, repo, wt) = repo(&[]);
        let out = carry(&repo, &wt, &[".env.local"]);
        assert_eq!(out[0].action, Action::Missing);
        assert_eq!(out[0].path, ".env.local");
    }

    #[test]
    fn nothing_listed_carries_nothing() {
        let (_d, repo, wt) = repo(&[(".env", "x")]);
        assert!(carry(&repo, &wt, &[]).is_empty());
        assert!(!wt.join(".env").exists());
    }

    // ── re-running ──────────────────────────────────────────────────────────

    #[test]
    fn an_unchanged_file_is_not_copied_again() {
        let (_d, repo, wt) = repo(&[(".env", "A=1")]);
        carry(&repo, &wt, &[".env"]);
        let out = carry(&repo, &wt, &[".env"]);
        assert_eq!(out[0].action, Action::Unchanged);
    }

    /// The checkout is the source of truth for these files — they are yours,
    /// not the agent's.
    #[test]
    fn a_changed_source_refreshes_the_copy() {
        let (_d, repo, wt) = repo(&[(".env", "A=1")]);
        carry(&repo, &wt, &[".env"]);
        std::fs::write(repo.join(".env"), "A=2").unwrap();

        let out = carry(&repo, &wt, &[".env"]);
        assert_eq!(out[0].action, Action::Refreshed);
        assert_eq!(std::fs::read_to_string(wt.join(".env")).unwrap(), "A=2");
    }

    // ── the agent's git status ──────────────────────────────────────────────

    /// A **real** git worktree, because that is where this broke: `.git` in a
    /// worktree is a *file* pointing at the admin directory, not a directory,
    /// so writing `<worktree>/.git/info/exclude` silently does nothing.
    fn worktree_repo() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let d = tempfile::tempdir().unwrap();
        let repo = d.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        let git = |args: &[&str]| {
            std::process::Command::new("git")
                .current_dir(&repo)
                .args(args)
                .output()
                .unwrap()
        };
        git(&["init", "-q", "-b", "main"]);
        git(&["config", "user.email", "t@e.com"]);
        git(&["config", "user.name", "t"]);
        git(&["commit", "-q", "--allow-empty", "-m", "root"]);
        let wt = d.path().join("wt");
        git(&[
            "worktree",
            "add",
            "-q",
            wt.to_str().unwrap(),
            "-b",
            "omh/s01",
        ]);
        std::fs::write(repo.join(".env.local"), "SECRET").unwrap();
        (d, repo, wt)
    }

    fn status(wt: &Path) -> String {
        let out = std::process::Command::new("git")
            .current_dir(wt)
            .args(["status", "--short"])
            .output()
            .unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned()
    }

    /// Carried files must not appear as untracked, or the agent commits your
    /// `.env` onto the session branch.
    #[test]
    fn carried_paths_are_hidden_from_the_agents_git_status() {
        let (_d, repo, wt) = worktree_repo();
        carry(&repo, &wt, &[".env.local"]);

        assert!(wt.join(".env.local").exists(), "carried");
        assert!(
            !status(&wt).contains(".env.local"),
            "must not be untracked noise:\n{}",
            status(&wt)
        );
    }

    #[test]
    fn excluding_twice_does_not_duplicate_entries() {
        let (_d, repo, wt) = worktree_repo();
        carry(&repo, &wt, &[".env.local"]);
        carry(&repo, &wt, &[".env.local"]);
        assert!(!status(&wt).contains(".env.local"));
    }

    #[test]
    fn an_existing_exclude_file_is_preserved() {
        let (_d, repo, wt) = worktree_repo();
        let path = exclude_path(&wt).unwrap();
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, "*.swp\n").unwrap();
        carry(&repo, &wt, &[".env.local"]);

        let body = std::fs::read_to_string(&path).unwrap();
        assert!(
            body.contains("*.swp"),
            "the user's rules must survive: {body}"
        );
    }

    /// omh writes CLAUDE.md and AGENTS.md into the worktree itself; left
    /// untracked, the agent is invited to commit omh's staging onto the branch.
    #[test]
    fn omhs_own_staged_files_are_hidden_too() {
        let (_d, _repo, wt) = worktree_repo();
        std::fs::write(wt.join("CLAUDE.md"), "rules").unwrap();
        std::fs::write(wt.join("AGENTS.md"), "rules").unwrap();

        hide_staged_rules(&wt).unwrap();
        let st = status(&wt);
        assert!(!st.contains("CLAUDE.md"), "got:\n{st}");
        assert!(!st.contains("AGENTS.md"), "got:\n{st}");
    }

    // ── escaping the repo ───────────────────────────────────────────────────

    #[test]
    fn ordinary_patterns_are_accepted() {
        for p in [".env", ".env.local", "certs/", "config/local.toml"] {
            validate_pattern(p).unwrap_or_else(|e| panic!("{p}: {e}"));
        }
    }

    /// `carry_in` lives in a committed layer, so a careless entry would copy
    /// host secrets into a sandbox the agent controls.
    #[test]
    fn a_pattern_cannot_escape_the_checkout() {
        for p in [
            "../secrets",
            "../../.ssh",
            "a/../../b",
            "/etc/passwd",
            "~/.ssh",
        ] {
            assert!(validate_pattern(p).is_err(), "`{p}` must be rejected");
        }
    }

    #[test]
    fn an_escaping_pattern_copies_nothing() {
        let (_d, repo, wt) = repo(&[]);
        let owned = vec!["../../.ssh".to_string()];
        assert!(
            apply(&repo, &wt, &owned).is_err(),
            "must refuse, not silently skip"
        );
    }
}