io-harness 0.16.1

Run an AI agent from a typed task contract to a verified result: provider-agnostic and embeddable in-process, with a layered permission boundary, execution-based verification inside a sandbox, durable resume for unattended runs, contained sub-agents, an MCP client, and a full SQLite trace.
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
//! Git through the full loop: what the agent can reach, and what it cannot.
//!
//! The unit tests in `src/tools/git.rs` prove the argv builder refuses what it
//! should. These prove an agent actually reaches it — that a staged path passes
//! the path policy on the real path, that the repository's own hooks do not run
//! under the agent, and that a run ends as a commit a human can read.
//!
//! Every test that needs a real `git` skips cleanly when there is none, because
//! git is a runtime capability here and not a build dependency.

use std::sync::atomic::{AtomicUsize, Ordering};

use io_harness::policy::Policy;
use io_harness::provider::{CompletionRequest, CompletionResponse, ToolCall};
use io_harness::{run_with, Provider, Store, TaskContract, Verification};
use serde_json::json;

struct Script {
    steps: Vec<Vec<ToolCall>>,
    at: AtomicUsize,
}

impl Script {
    fn new(steps: Vec<Vec<ToolCall>>) -> Self {
        Self {
            steps,
            at: AtomicUsize::new(0),
        }
    }
}

impl Provider for Script {
    async fn complete(&self, _req: CompletionRequest) -> io_harness::Result<CompletionResponse> {
        let i = self.at.fetch_add(1, Ordering::SeqCst);
        Ok(CompletionResponse {
            tool_calls: self.steps.get(i).cloned().unwrap_or_default(),
            ..Default::default()
        })
    }
}

fn call(name: &str, args: serde_json::Value) -> ToolCall {
    ToolCall {
        name: name.into(),
        arguments: args,
    }
}

/// Run a git command directly, for arranging and for asserting. Never the thing
/// under test.
fn git(dir: &std::path::Path, args: &[&str]) -> std::process::Output {
    std::process::Command::new("git")
        .args(args)
        .current_dir(dir)
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_AUTHOR_NAME", "Fixture")
        .env("GIT_AUTHOR_EMAIL", "fixture@example.invalid")
        .env("GIT_COMMITTER_NAME", "Fixture")
        .env("GIT_COMMITTER_EMAIL", "fixture@example.invalid")
        .output()
        .expect("git should be runnable once `have_git` said so")
}

fn have_git() -> bool {
    std::process::Command::new("git")
        .arg("--version")
        .output()
        .is_ok()
}

/// A real repository with one commit already in it, a tracked file, and a
/// secret the policy will deny.
fn repo() -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    let p = dir.path();
    std::fs::create_dir_all(p.join("private")).unwrap();
    std::fs::write(p.join("README.md"), "hello\n").unwrap();
    std::fs::write(p.join("private/key.txt"), "secret\n").unwrap();
    git(p, &["init", "--initial-branch=main"]);
    git(p, &["add", "README.md"]);
    git(p, &["commit", "-m", "first"]);
    dir
}

fn contract(dir: &tempfile::TempDir, steps: u32) -> TaskContract {
    TaskContract::workspace(
        "record your work as a commit",
        dir.path(),
        Verification::WorkspaceFileContains {
            file: "README.md".into(),
            needle: "never satisfied".into(),
        },
    )
    .with_max_steps(steps)
}

fn store(dir: &tempfile::TempDir) -> Store {
    Store::open(dir.path().join("trace.db")).unwrap()
}

async fn drive(
    dir: &tempfile::TempDir,
    steps: Vec<Vec<ToolCall>>,
    policy: &Policy,
    store: &Store,
) -> io_harness::RunResult {
    let n = steps.len() as u32 + 1;
    run_with(
        &contract(dir, n),
        &Script::new(steps),
        store,
        policy,
        &io_harness::approve::ApproveAll,
    )
    .await
    .unwrap()
}

/// The log as one string, for asserting on what was committed.
fn log(dir: &std::path::Path) -> String {
    String::from_utf8_lossy(&git(dir, &["log", "--oneline"]).stdout).into_owned()
}

// ------------------------------------------------------------------- F12

#[tokio::test]
async fn an_agent_stages_its_edits_and_commits_them() {
    if !have_git() {
        return;
    }
    let dir = repo();
    let before = log(dir.path()).lines().count();

    drive(
        &dir,
        vec![
            vec![call(
                "write_file",
                json!({ "path": "NOTES.md", "content": "written by the agent\n" }),
            )],
            vec![call("git_add", json!({ "paths": ["NOTES.md"] }))],
            vec![call("git_commit", json!({ "message": "add notes" }))],
        ],
        &Policy::permissive(),
        &store(&dir),
    )
    .await;

    let log = log(dir.path());
    assert_eq!(
        log.lines().count(),
        before + 1,
        "exactly one new commit: {log}"
    );
    assert!(log.contains("add notes"), "{log}");

    // The file it staged is in the commit, and the one it did not is not.
    let show =
        String::from_utf8_lossy(&git(dir.path(), &["show", "--name-only", "--format="]).stdout)
            .into_owned();
    assert!(show.contains("NOTES.md"), "{show}");
    assert!(!show.contains("key.txt"), "{show}");
}

#[tokio::test]
async fn the_commit_carries_the_contracts_identity_and_not_the_machines() {
    if !have_git() {
        return;
    }
    let dir = repo();
    run_with(
        &contract(&dir, 3).with_commit_identity("Agent Smith", "smith@example.invalid"),
        &Script::new(vec![
            vec![call(
                "write_file",
                json!({ "path": "NOTES.md", "content": "x\n" }),
            )],
            vec![call("git_add", json!({ "paths": ["NOTES.md"] }))],
            vec![call("git_commit", json!({ "message": "attributed" }))],
        ]),
        &store(&dir),
        &Policy::permissive(),
        &io_harness::approve::ApproveAll,
    )
    .await
    .unwrap();

    let who =
        String::from_utf8_lossy(&git(dir.path(), &["log", "-1", "--format=%an <%ae>"]).stdout)
            .into_owned();
    assert!(who.contains("Agent Smith"), "{who}");
    assert!(who.contains("smith@example.invalid"), "{who}");
}

// -------------------------------------------------------------------- F9

#[tokio::test]
async fn staging_a_path_the_policy_denies_for_reading_is_refused() {
    if !have_git() {
        return;
    }
    let dir = repo();
    let store = store(&dir);
    let guarded = Policy::default()
        .layer("base")
        .allow_read("*")
        .allow_write("*")
        .deny_read("private/*");

    let result = drive(
        &dir,
        vec![vec![call(
            "git_add",
            json!({ "paths": ["private/key.txt"] }),
        )]],
        &guarded,
        &store,
    )
    .await;

    // Not merely unreported: the file must be absent from the index.
    let staged =
        String::from_utf8_lossy(&git(dir.path(), &["diff", "--cached", "--name-only"]).stdout)
            .into_owned();
    assert!(
        !staged.contains("key.txt"),
        "a denied file reached the index: {staged}"
    );

    let events = store.events(result.run_id).unwrap();
    let refusal = events
        .iter()
        .find(|e| e.kind == "refusal")
        .expect("the refusal must be in the trace");
    assert_eq!(refusal.act, "read");
    assert_eq!(refusal.target, "private/key.txt");
}

#[tokio::test]
async fn the_same_stage_under_a_permissive_policy_succeeds() {
    // The negative control for the test above: without it, that test would pass
    // against a build where `git_add` never staged anything at all.
    if !have_git() {
        return;
    }
    let dir = repo();
    drive(
        &dir,
        vec![vec![call(
            "git_add",
            json!({ "paths": ["private/key.txt"] }),
        )]],
        &Policy::permissive(),
        &store(&dir),
    )
    .await;

    let staged =
        String::from_utf8_lossy(&git(dir.path(), &["diff", "--cached", "--name-only"]).stdout)
            .into_owned();
    assert!(staged.contains("key.txt"), "{staged}");
}

// -------------------------------------------------------------------- F8

#[tokio::test]
async fn a_repositorys_own_pre_commit_hook_does_not_run_under_the_agent() {
    if !have_git() {
        return;
    }
    let dir = repo();
    let hook = dir.path().join(".git/hooks/pre-commit");
    std::fs::write(
        &hook,
        "#!/bin/sh\ntouch \"$(dirname \"$0\")/../../HOOK_RAN\"\n",
    )
    .unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    drive(
        &dir,
        vec![
            vec![call(
                "write_file",
                json!({ "path": "NOTES.md", "content": "x\n" }),
            )],
            vec![call("git_add", json!({ "paths": ["NOTES.md"] }))],
            vec![call("git_commit", json!({ "message": "no hooks please" }))],
        ],
        &Policy::permissive(),
        &store(&dir),
    )
    .await;

    assert!(
        !dir.path().join("HOOK_RAN").exists(),
        "the repository's own hook must not run under the agent"
    );
    assert!(log(dir.path()).contains("no hooks please"));
}

#[cfg(unix)]
#[tokio::test]
async fn the_same_hook_does_fire_under_a_plain_git_commit() {
    // The control for the test above. Without it, "the sentinel is absent" could
    // just mean the hook was never executable in the first place, and the
    // suppression would be proving nothing.
    if !have_git() {
        return;
    }
    use std::os::unix::fs::PermissionsExt as _;
    let dir = repo();
    let hook = dir.path().join(".git/hooks/pre-commit");
    std::fs::write(
        &hook,
        "#!/bin/sh\ntouch \"$(dirname \"$0\")/../../HOOK_RAN\"\n",
    )
    .unwrap();
    std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();

    std::fs::write(dir.path().join("NOTES.md"), "x\n").unwrap();
    git(dir.path(), &["add", "NOTES.md"]);
    git(dir.path(), &["commit", "-m", "plain"]);

    assert!(
        dir.path().join("HOOK_RAN").exists(),
        "the fixture hook must be capable of firing, or the suppression test is vacuous"
    );
}

// ------------------------------------------------------------------- F11

#[tokio::test]
async fn no_git_binary_is_an_observation_and_the_run_carries_on() {
    // Simulated by pointing the workspace at a directory that is not a
    // repository: git runs, fails, and the run must survive it exactly as it
    // would survive a missing binary. The missing-binary path itself is unit
    // tested in src/tools/git.rs, where the program name can be replaced.
    if !have_git() {
        return;
    }
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("README.md"), "hello\n").unwrap();

    let result = drive(
        &dir,
        vec![vec![call("git_status", json!({}))]],
        &Policy::permissive(),
        &store(&dir),
    )
    .await;

    // The run reached its step cap rather than failing: a git that cannot work
    // here is something the model reads and adapts to.
    assert!(
        matches!(
            result.outcome,
            io_harness::RunOutcome::StepCapReached { .. }
        ),
        "{:?}",
        result.outcome
    );
}

#[tokio::test]
async fn a_commit_with_nothing_staged_is_reported_not_fatal() {
    if !have_git() {
        return;
    }
    let dir = repo();
    let result = drive(
        &dir,
        vec![vec![call("git_commit", json!({ "message": "empty" }))]],
        &Policy::permissive(),
        &store(&dir),
    )
    .await;

    assert!(
        matches!(
            result.outcome,
            io_harness::RunOutcome::StepCapReached { .. }
        ),
        "{:?}",
        result.outcome
    );
    assert!(
        !log(dir.path()).contains("empty"),
        "nothing was staged, so nothing should have been committed"
    );
}

// ------------------------------------------------------------------- F10

#[tokio::test]
async fn a_commit_interrupted_before_its_checkpoint_is_not_taken_twice() {
    // A step budget of one is how this suite interrupts a run: it stops with
    // work left, exactly as a crashed process leaves it, and the resume
    // continues under the same run id.
    //
    // A commit is the first genuinely irreversible action this crate can take,
    // and 0.7.0's promise is that one already taken is not taken again. The
    // replayed script asks for the identical commit a second time.
    if !have_git() {
        return;
    }
    let dir = repo();
    let store = store(&dir);
    let before = log(dir.path()).lines().count();

    let script = || {
        Script::new(vec![
            vec![call(
                "write_file",
                json!({ "path": "NOTES.md", "content": "written once\n" }),
            )],
            vec![call("git_add", json!({ "paths": ["NOTES.md"] }))],
            vec![call("git_commit", json!({ "message": "recorded" }))],
            vec![call("git_add", json!({ "paths": ["NOTES.md"] }))],
            vec![call("git_commit", json!({ "message": "recorded" }))],
        ])
    };

    let first = run_with(
        &contract(&dir, 3),
        &script(),
        &store,
        &Policy::permissive(),
        &io_harness::approve::ApproveAll,
    )
    .await
    .unwrap();
    assert_eq!(
        log(dir.path()).lines().count(),
        before + 1,
        "the first run commits once"
    );

    io_harness::resume(&contract(&dir, 6), &script(), &store, first.run_id)
        .await
        .unwrap();

    let log = log(dir.path());
    assert_eq!(
        log.lines().count(),
        before + 1,
        "the resumed run must not commit again: {log}"
    );
    assert_eq!(
        log.matches("recorded").count(),
        1,
        "exactly one commit carries the message: {log}"
    );
}