io-harness 0.10.0

A Rust agent harness: run an AI agent from a typed task contract to a verified result. Provider-agnostic (OpenRouter, Anthropic, OpenAI), multi-file edits with grep/find over a workspace, budgets, retry, full trace, resumable runs, execution-based verification, a layered permission policy with a human-approval gate, contained sub-agent composition, an OS-native/OS-neutral execution sandbox (macOS sandbox-exec, Linux namespaces, portable floor everywhere; Windows is the floor with a wall-clock cap only) that isolates model-produced code per run, durable checkpoint/resume for unattended runs, an MCP client (stdio and streamable HTTP) whose tools reach the agent beside the built-ins, a deny-by-default network egress policy, budget-aware context assembly that compacts superseded observations and re-reads what a later write invalidated, and durable cross-run memory keyed to the workspace. Embeddable in-process.
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
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
//! Workspace-scoped tools: grep, find, read_file, write_file — all confined to
//! one root directory.
//!
//! 0.1/0.2 scoped the agent to exactly one file. 0.3 gives it a repository: it
//! greps and finds to locate what to change, reads what it found, and writes
//! several files. Every path the model supplies is resolved relative to `root`
//! and refused if it escapes — an absolute path or a `..` climbing above the
//! root is an error, so the agent cannot touch files outside the workspace.

use std::path::{Component, Path, PathBuf};

use regex::Regex;

use crate::error::{Error, Result};
use crate::policy::{Act, Effect, Policy, Verdict};

/// Directory names never walked by grep/find — build output and VCS metadata,
/// which the agent should never search or edit.
// ponytail: fixed ignore list; honor .gitignore instead if the agent starts
// searching real build trees (open question in the 0.3.0 contract).
const IGNORE_DIRS: &[&str] = &[".git", "target", "node_modules"];

/// A workspace rooted at one directory. All operations stay under `root`, and
/// every path is additionally checked against a [`Policy`] before it is read or
/// written — in this layer, not in the system prompt, so a model that ignores
/// its instructions still cannot act outside the policy.
#[derive(Debug, Clone)]
pub struct Workspace {
    root: PathBuf,
    policy: Policy,
}

/// One grep hit: file relative to the root, 1-based line number, and the line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Match {
    /// Path relative to the workspace root, `/`-separated.
    pub path: String,
    /// 1-based line number.
    pub line: u32,
    /// The matching line's text.
    pub text: String,
}

impl Workspace {
    /// Root the workspace at `root`, enforcing nothing beyond the root itself.
    /// This is the 0.3.0 behaviour and what a caller who passes no policy gets.
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            policy: Policy::permissive(),
        }
    }

    /// Root the workspace at `root` and enforce `policy` on every path.
    pub fn with_policy(root: impl Into<PathBuf>, policy: Policy) -> Self {
        Self {
            root: root.into(),
            policy,
        }
    }

    /// The workspace root.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// The policy this workspace enforces.
    pub fn policy(&self) -> &Policy {
        &self.policy
    }

    /// Evaluate `act` against a workspace-relative path, returning the strictest
    /// verdict across every form that path can take.
    ///
    /// A symlink is checked by its own path *and* by its resolved target, so a
    /// link sitting inside an allowed directory but pointing at a denied file is
    /// refused — the target fails even though the link's own path passes.
    pub fn check_path(&self, act: Act, rel: &str) -> Verdict {
        let mut worst = self.policy.check(act, &normalize(rel));

        // The canonical form, when it differs and still lands inside the root.
        if let Ok(abs) = self.resolve(rel) {
            if let Ok(canon) = abs.canonicalize() {
                let root_canon = self
                    .root
                    .canonicalize()
                    .unwrap_or_else(|_| self.root.clone());
                if let Ok(rel_canon) = canon.strip_prefix(&root_canon) {
                    let rel_canon = rel_canon.to_string_lossy().replace('\\', "/");
                    let v = self.policy.check(act, &rel_canon);
                    if v.effect > worst.effect {
                        worst = v;
                    }
                } else {
                    // Resolves outside the root: a symlink escape, refused
                    // regardless of what the policy says about the link itself.
                    return Verdict {
                        effect: Effect::Deny,
                        rule: Some("<resolves outside workspace root>".into()),
                        layer: None,
                    };
                }
            }
        }
        worst
    }

    /// Refuse the action if the policy denies it, as a typed [`Error::Refused`].
    fn enforce(&self, act: Act, rel: &str) -> Result<()> {
        let v = self.check_path(act, rel);
        if v.effect == Effect::Deny {
            return Err(Error::Refused {
                act: format!("{act:?}").to_lowercase(),
                target: rel.to_string(),
                rule: v.rule,
                layer: v.layer,
            });
        }
        Ok(())
    }

    /// Resolve a model-supplied relative path under the root, refusing absolute
    /// paths and any `..` that climbs above the root.
    pub fn resolve(&self, rel: &str) -> Result<PathBuf> {
        let p = Path::new(rel);
        if p.is_absolute() {
            return Err(escape(rel));
        }
        let mut out = self.root.clone();
        for comp in p.components() {
            match comp {
                Component::Normal(c) => out.push(c),
                Component::CurDir => {}
                Component::ParentDir => {
                    // Pop, then require we are still inside the root.
                    if !out.pop() || !out.starts_with(&self.root) {
                        return Err(escape(rel));
                    }
                }
                Component::RootDir | Component::Prefix(_) => return Err(escape(rel)),
            }
        }
        Ok(out)
    }

    /// Search every text file under the root for `pattern` (a regex; a plain
    /// substring is a valid regex). `path_glob`, if given, limits the search to
    /// files whose relative path matches the glob.
    pub fn grep(&self, pattern: &str, path_glob: Option<&str>) -> Result<Vec<Match>> {
        let re = Regex::new(pattern).map_err(|e| Error::Config(format!("bad grep regex: {e}")))?;
        let glob = path_glob.map(glob_to_regex).transpose()?;
        let mut out = Vec::new();
        for file in self.walk() {
            if let Some(g) = &glob {
                if !g.is_match(&file) {
                    continue;
                }
            }
            // A denied file contributes no matches, so its contents cannot be
            // exfiltrated into the model's context through a search.
            if self.check_path(Act::Read, &file).effect == Effect::Deny {
                continue;
            }
            // Non-UTF-8 / binary files just don't match; skip quietly.
            let Ok(content) = std::fs::read_to_string(self.root.join(&file)) else {
                continue;
            };
            for (i, line) in content.lines().enumerate() {
                if re.is_match(line) {
                    out.push(Match {
                        path: file.clone(),
                        line: (i + 1) as u32,
                        text: line.to_string(),
                    });
                }
            }
        }
        Ok(out)
    }

    /// List files under the root whose name or relative path matches the glob
    /// (`*` any run, `?` one char). `*.rs` matches by basename; `src/*.rs` by
    /// relative path.
    pub fn find(&self, name_glob: &str) -> Result<Vec<String>> {
        let re = glob_to_regex(name_glob)?;
        Ok(self
            .walk()
            .into_iter()
            .filter(|file| {
                let base = Path::new(file)
                    .file_name()
                    .and_then(|s| s.to_str())
                    .unwrap_or(file);
                (re.is_match(base) || re.is_match(file))
                    // A denied path is not even named back to the model.
                    && self.check_path(Act::Read, file).effect != Effect::Deny
            })
            .collect())
    }

    /// Read a file under the root. A missing file reads as empty, so the agent
    /// can create it (matching the 0.1/0.2 `FsTool` behaviour). A path the
    /// policy denies is refused before anything is read.
    pub fn read_file(&self, rel: &str) -> Result<String> {
        let abs = self.resolve(rel)?;
        self.enforce(Act::Read, rel)?;
        Ok(std::fs::read_to_string(abs).unwrap_or_default())
    }

    /// Write a file under the root, creating parent directories. A path the
    /// policy denies is refused before anything is written.
    pub fn write_file(&self, rel: &str, content: &str) -> Result<()> {
        let abs = self.resolve(rel)?;
        self.enforce(Act::Write, rel)?;
        if let Some(parent) = abs.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(abs, content)?;
        Ok(())
    }

    /// All files under the root, relative and `/`-separated, sorted, skipping
    /// [`IGNORE_DIRS`]. Synchronous walk — fine for local repos.
    // ponytail: blocking std::fs walk on the async runtime; wrap in
    // spawn_blocking if it is ever pointed at a huge tree.
    fn walk(&self) -> Vec<String> {
        let mut out = Vec::new();
        let mut stack = vec![self.root.clone()];
        while let Some(dir) = stack.pop() {
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in entries.flatten() {
                let Ok(ft) = entry.file_type() else { continue };
                let name = entry.file_name();
                if ft.is_dir() {
                    if !IGNORE_DIRS.contains(&name.to_string_lossy().as_ref()) {
                        stack.push(entry.path());
                    }
                } else if ft.is_file() {
                    if let Ok(rel) = entry.path().strip_prefix(&self.root) {
                        out.push(rel.to_string_lossy().replace('\\', "/"));
                    }
                }
            }
        }
        out.sort();
        out
    }
}

fn escape(rel: &str) -> Error {
    Error::Config(format!("path escapes workspace: {rel}"))
}

/// A model-supplied path in the `/`-separated, `.`-free form policy globs match
/// against, so `./src/a.rs` and `src/a.rs` are the same target to a rule.
fn normalize(rel: &str) -> String {
    let s = rel.replace('\\', "/");
    let mut out: Vec<&str> = Vec::new();
    for part in s.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                out.pop();
            }
            p => out.push(p),
        }
    }
    out.join("/")
}

/// Compile a glob (`*` any run including `/`, `?` one char) to a regex.
fn glob_to_regex(glob: &str) -> Result<Regex> {
    let mut re = String::from("(?s)^");
    for ch in glob.chars() {
        match ch {
            '*' => re.push_str(".*"),
            '?' => re.push('.'),
            c => re.push_str(&regex::escape(&c.to_string())),
        }
    }
    re.push('$');
    Regex::new(&re).map_err(|e| Error::Config(format!("bad glob: {e}")))
}

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

    /// A small fixture repo: two Rust files under src/, one doc, and an
    /// ignored target/ build artifact.
    fn fixture() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::create_dir_all(root.join("target")).unwrap();
        std::fs::write(root.join("src/a.rs"), "pub fn alpha() -> u32 { 1 }\n").unwrap();
        std::fs::write(
            root.join("src/b.rs"),
            "pub fn beta() -> u32 { 2 }\n// alpha ref\n",
        )
        .unwrap();
        std::fs::write(root.join("README.md"), "# alpha and beta\n").unwrap();
        std::fs::write(root.join("target/junk.rs"), "fn alpha() {}\n").unwrap();
        dir
    }

    #[test]
    fn grep_finds_matches_by_regex_across_files_skipping_ignored() {
        let dir = fixture();
        let ws = Workspace::new(dir.path());
        let hits = ws.grep(r"alpha", None).unwrap();
        // src/a.rs:1, src/b.rs:2, README.md:1 — but NOT target/junk.rs.
        let paths: Vec<_> = hits.iter().map(|m| m.path.as_str()).collect();
        assert!(paths.contains(&"src/a.rs"));
        assert!(paths.contains(&"src/b.rs"));
        assert!(paths.contains(&"README.md"));
        assert!(!paths.iter().any(|p| p.starts_with("target/")));
        // line numbers are 1-based and correct.
        let b = hits.iter().find(|m| m.path == "src/b.rs").unwrap();
        assert_eq!(b.line, 2);
    }

    #[test]
    fn grep_path_glob_restricts_to_matching_files() {
        let dir = fixture();
        let ws = Workspace::new(dir.path());
        let hits = ws.grep("alpha", Some("src/*.rs")).unwrap();
        assert!(hits.iter().all(|m| m.path.starts_with("src/")));
        assert!(!hits.iter().any(|m| m.path == "README.md"));
    }

    #[test]
    fn find_matches_by_basename_and_path_glob() {
        let dir = fixture();
        let ws = Workspace::new(dir.path());
        let rs = ws.find("*.rs").unwrap();
        assert!(rs.contains(&"src/a.rs".to_string()));
        assert!(rs.contains(&"src/b.rs".to_string()));
        assert!(!rs.iter().any(|p| p.starts_with("target/"))); // ignored dir
        let only_a = ws.find("a.rs").unwrap();
        assert_eq!(only_a, vec!["src/a.rs".to_string()]);
    }

    #[test]
    fn resolve_refuses_escapes_but_allows_inner_paths() {
        let dir = fixture();
        let ws = Workspace::new(dir.path());
        assert!(ws.resolve("src/a.rs").is_ok());
        assert!(ws.resolve("src/../README.md").is_ok()); // stays inside
        assert!(ws.resolve("../secret").is_err()); // climbs out
        assert!(ws.resolve("src/../../etc/passwd").is_err()); // climbs out
        #[cfg(unix)]
        assert!(ws.resolve("/etc/passwd").is_err()); // absolute
    }

    /// The policy used across the enforcement tests: src/ is readable and
    /// writable, secrets/ is denied outright.
    fn guarded(root: &Path) -> Workspace {
        Workspace::with_policy(
            root,
            Policy::default()
                .layer("base")
                .allow_read("*")
                .allow_write("src/*")
                .deny_read("secrets/*")
                .deny_write("secrets/*"),
        )
    }

    #[test]
    fn a_denied_write_is_refused_and_the_file_is_untouched() {
        let dir = fixture();
        std::fs::create_dir_all(dir.path().join("secrets")).unwrap();
        std::fs::write(dir.path().join("secrets/key.txt"), "original").unwrap();
        let ws = guarded(dir.path());

        let err = ws.write_file("secrets/key.txt", "stolen").unwrap_err();
        assert!(
            matches!(&err, Error::Refused { rule, layer, .. }
                if rule.as_deref() == Some("secrets/*") && layer.as_deref() == Some("base")),
            "expected an attributable refusal, got {err:?}"
        );
        // Nothing was written.
        assert_eq!(
            std::fs::read_to_string(dir.path().join("secrets/key.txt")).unwrap(),
            "original"
        );
        // An in-policy write still succeeds.
        assert!(ws
            .write_file("src/a.rs", "pub fn alpha() -> u32 { 9 }\n")
            .is_ok());
    }

    #[test]
    fn denied_paths_are_invisible_to_grep_and_find() {
        let dir = fixture();
        std::fs::create_dir_all(dir.path().join("secrets")).unwrap();
        std::fs::write(dir.path().join("secrets/creds.rs"), "alpha token\n").unwrap();
        let ws = guarded(dir.path());

        // grep would otherwise match secrets/creds.rs — it must not appear.
        let hits = ws.grep("alpha", None).unwrap();
        assert!(!hits.iter().any(|m| m.path.starts_with("secrets/")));
        assert!(hits.iter().any(|m| m.path == "src/a.rs"));

        // find must not even name it.
        let found = ws.find("*.rs").unwrap();
        assert!(!found.iter().any(|p| p.starts_with("secrets/")));

        // and a direct read is refused, not silently empty.
        assert!(matches!(
            ws.read_file("secrets/creds.rs"),
            Err(Error::Refused { .. })
        ));
    }

    #[test]
    fn traversal_is_evaluated_on_the_resolved_path_not_the_literal_one() {
        let dir = fixture();
        std::fs::create_dir_all(dir.path().join("secrets")).unwrap();
        std::fs::write(dir.path().join("secrets/key.txt"), "original").unwrap();
        let ws = guarded(dir.path());

        // Lands inside secrets/ after resolution, so the deny still applies.
        assert!(matches!(
            ws.write_file("src/../secrets/key.txt", "stolen"),
            Err(Error::Refused { .. })
        ));
        assert_eq!(
            std::fs::read_to_string(dir.path().join("secrets/key.txt")).unwrap(),
            "original"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_symlink_is_denied_by_its_target_even_when_its_own_path_is_allowed() {
        let dir = fixture();
        std::fs::create_dir_all(dir.path().join("secrets")).unwrap();
        std::fs::write(dir.path().join("secrets/key.txt"), "secret").unwrap();
        // A link that lives in the allowed tree but points into the denied one.
        std::os::unix::fs::symlink(
            dir.path().join("secrets/key.txt"),
            dir.path().join("src/link.rs"),
        )
        .unwrap();
        let ws = guarded(dir.path());

        // src/link.rs passes on its own path; its target does not.
        assert_eq!(
            ws.check_path(Act::Read, "src/link.rs").effect,
            Effect::Deny,
            "a link into a denied path must be refused"
        );
        assert!(matches!(
            ws.read_file("src/link.rs"),
            Err(Error::Refused { .. })
        ));
    }

    #[cfg(unix)]
    #[test]
    fn a_symlink_pointing_outside_the_root_is_refused() {
        let outside = tempfile::tempdir().unwrap();
        std::fs::write(outside.path().join("passwd"), "root:x:0:0").unwrap();
        let dir = fixture();
        std::os::unix::fs::symlink(outside.path().join("passwd"), dir.path().join("src/out.rs"))
            .unwrap();
        let ws = guarded(dir.path());

        assert_eq!(ws.check_path(Act::Read, "src/out.rs").effect, Effect::Deny);
    }

    #[test]
    fn a_workspace_without_a_policy_behaves_exactly_as_0_3_0_did() {
        let dir = fixture();
        std::fs::create_dir_all(dir.path().join("secrets")).unwrap();
        std::fs::write(dir.path().join("secrets/key.txt"), "x").unwrap();
        let ws = Workspace::new(dir.path());

        // No policy means no enforcement — the boundary is opt-in.
        assert!(ws.write_file("secrets/key.txt", "y").is_ok());
        assert!(ws.read_file("secrets/key.txt").is_ok());
        assert!(ws
            .find("*.txt")
            .unwrap()
            .iter()
            .any(|p| p.starts_with("secrets/")));
    }

    #[test]
    fn check_path_agrees_with_what_read_and_write_actually_enforce() {
        let dir = fixture();
        std::fs::create_dir_all(dir.path().join("secrets")).unwrap();
        std::fs::write(dir.path().join("secrets/key.txt"), "x").unwrap();
        let ws = guarded(dir.path());

        for (act, path) in [
            (Act::Read, "src/a.rs"),
            (Act::Read, "secrets/key.txt"),
            (Act::Write, "src/a.rs"),
            (Act::Write, "secrets/key.txt"),
        ] {
            let denied = ws.check_path(act, path).effect == Effect::Deny;
            let refused = match act {
                Act::Read => matches!(ws.read_file(path), Err(Error::Refused { .. })),
                Act::Write => matches!(ws.write_file(path, "x"), Err(Error::Refused { .. })),
                // The workspace only ever performs reads and writes; exec is the
                // verify gate's and net is the connection point's.
                Act::Exec | Act::Net => unreachable!(),
            };
            assert_eq!(denied, refused, "{act:?} {path}");
        }
    }

    #[test]
    fn read_missing_is_empty_then_write_roundtrips_within_root() {
        let dir = fixture();
        let ws = Workspace::new(dir.path());
        assert_eq!(ws.read_file("src/new.rs").unwrap(), "");
        ws.write_file("src/new.rs", "fn n() {}").unwrap();
        assert_eq!(ws.read_file("src/new.rs").unwrap(), "fn n() {}");
        // an escaping write is refused, nothing written outside root.
        assert!(ws.write_file("../evil.rs", "x").is_err());
    }
}