newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
use super::*;
use crate::worktree_adoption::{
    tests::{fixture, link},
    WorktreeSession,
};
use crate::Scope;

struct BroadGate;
impl PermissionGate for BroadGate {
    fn ask(&mut self, _: &[PermissionRequest]) -> PermissionDecision {
        PermissionDecision::Allow(Caveats::top())
    }
    fn refresh_caveats(&mut self, _: &Caveats) -> PermissionDecision {
        PermissionDecision::Allow(Caveats::top())
    }
    fn apply_command_retry(&mut self, _: &str, _: &str, _: &Caveats) -> Caveats {
        Caveats::top()
    }
    fn apply_pending_once(&mut self, _: DenialKind, _: &str, _: &Caveats) -> Caveats {
        Caveats::top()
    }
    fn ask_question(&mut self, _: &str) -> HumanQuestionOutcome {
        HumanQuestionOutcome::Unavailable
    }
}

/// #2733: creation parsing recognizes real command input, not child output;
/// a listed, existing, failed, dynamic, or unrelated worktree never adopts.
#[cfg(unix)]
#[test]
fn worktree_adoption_creation_requires_the_command_and_verified_metadata() {
    let (_temp, policy, _) = fixture(false);
    let root = policy.worktree.parent().unwrap().join("main");
    let command = format!(
        "cd '{}' && git worktree add -b task '{}' 2>&1 | tail -5",
        root.display(),
        policy.worktree.display()
    );
    let args = serde_json::json!({"command":command});
    let candidate = creation(
        "run_command",
        &args,
        root.to_str().unwrap(),
        &Caveats::top(),
    )
    .unwrap();
    assert!(candidate.verify().is_none());
    let candidate = creation(
        "run_command",
        &args,
        root.to_str().unwrap(),
        &Caveats::top(),
    )
    .unwrap();
    link(&policy);
    assert!(candidate.verify().is_some());
    assert!(creation(
        "run_command",
        &args,
        root.to_str().unwrap(),
        &Caveats::top()
    )
    .is_none());
    for cmd in [
        "echo 'git worktree add /tmp/fake'",
        "git worktree list",
        "git worktree add $DEST",
        "cd other && git worktree add task",
    ] {
        assert!(
            creation(
                "run_command",
                &serde_json::json!({"command":cmd}),
                root.to_str().unwrap(),
                &Caveats::top()
            )
            .is_none(),
            "{cmd}"
        );
    }
}

/// #2733: a broad held/once grant cannot restore original-root authority.
#[test]
fn worktree_adoption_clamps_refresh_retry_and_build_requests() {
    let (_temp, policy, _) = fixture(true);
    let original = policy.worktree.parent().unwrap().parent().unwrap();
    let mut inner = BroadGate;
    let mut gate = Guard {
        policy: &policy,
        inner: Some(&mut inner),
    };
    for decision in [gate.refresh_caveats(&Caveats::top()), gate.ask(&[])] {
        let PermissionDecision::Allow(c) = decision else {
            panic!("allowed attenuated grant")
        };
        assert!(!crate::caveats::permits_path(
            &c.fs_write,
            original.to_str().unwrap()
        ));
    }
    let c = gate.apply_pending_once(DenialKind::Exec, "python3", &Caveats::top());
    assert!(!crate::caveats::permits_path(
        &c.fs_write,
        original.to_str().unwrap()
    ));
    let c = gate.apply_command_retry("bash script.sh", "/ws", &Caveats::top());
    assert!(!crate::caveats::permits_path(
        &c.fs_write,
        original.to_str().unwrap()
    ));
    for kind in [DenialKind::FsWrite, DenialKind::Build] {
        let request = PermissionRequest {
            kind,
            target: original.to_string_lossy().into_owned(),
            ..request_fixture()
        };
        assert!(matches!(
            gate.ask_with_caveats(&Caveats::top(), &[request]),
            PermissionDecision::Deny
        ));
    }
}

fn request_fixture() -> PermissionRequest {
    PermissionRequest {
        tool: "test".into(),
        kind: DenialKind::FsWrite,
        target: "unused".into(),
        reason: "fixture".into(),
        harness_bound: true,
    }
}

/// #2733: actual file-tool dispatch refuses stray writes before permission
/// prompts, retains reads, and accepts the same path after explicit lift.
#[cfg(unix)]
#[tokio::test]
async fn worktree_adoption_guards_file_dispatch_across_calls_and_lift() {
    let (_temp, policy, _) = fixture(false);
    link(&policy);
    let original = policy.worktree.parent().unwrap().join("main");
    std::fs::write(original.join("source.rs"), "before").unwrap();
    let session = WorktreeSession::default();
    session.adopt(policy.clone());
    for name in ["write_file", "edit_file", "delete_file"] {
        let args = serde_json::json!({"path":"source.rs", "content":"after", "old_string":"before", "new_string":"after"});
        let output = call(name, &args, &original, &session).await;
        assert!(
            output.contains("original checkout is read-only"),
            "{output}"
        );
        assert!(output.contains(policy.worktree.to_str().unwrap()));
        assert_eq!(
            std::fs::read_to_string(original.join("source.rs")).unwrap(),
            "before"
        );
    }
    let read = call(
        "read_file",
        &serde_json::json!({"path":"source.rs"}),
        &original,
        &session,
    )
    .await;
    assert!(read.contains("before"), "{read}");
    session.lift();
    let output = call(
        "edit_file",
        &serde_json::json!({"path":"source.rs", "old_string":"before", "new_string":"after"}),
        &original,
        &session,
    )
    .await;
    assert_eq!(
        std::fs::read_to_string(original.join("source.rs")).unwrap(),
        "after",
        "{output}"
    );
}

async fn call(
    name: &str,
    args: &serde_json::Value,
    original: &Path,
    session: &WorktreeSession,
) -> String {
    let mut display = crate::agentic::display::ToolDisplay::new(Vec::new(), false, 80, 20, false);
    let mut gate = BroadGate;
    let mut c = Caveats::top();
    c.fs_write = Scope::only([original.to_string_lossy().into_owned()]);
    execute(
        &mut display,
        name,
        args,
        original.to_str().unwrap(),
        false,
        20,
        &c,
        &mut crate::agentic::NoMcp,
        ToolCollaborators {
            worktree_session: Some(session),
            permission_gate: Some(&mut gate),
            ..Default::default()
        },
        false,
        PromptDisposition::Act,
    )
    .await
}

/// #2733: ground command-observation and positive-scope unit tests in real
/// Git creation and actual interpreter writes under the native kernel fence.
#[cfg(unix)]
#[tokio::test]
#[ignore = "requires native kernel confinement, git and python3"]
async fn worktree_adoption_native_creation_and_interpreter_fence() {
    assert!(crate::confined_exec::kernel_fs_fence_available());
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().join("main");
    let target = temp.path().join("task");
    std::fs::create_dir(&root).unwrap();
    for args in [
        vec!["init", "-q", "-b", "main"],
        vec![
            "-c",
            "commit.gpgsign=false",
            "commit",
            "--allow-empty",
            "-qm",
            "fixture",
        ],
    ] {
        let output =
            crate::agentic::tools::tests::git_shell_grant::hermetic_git(&root, temp.path())
                .args(args)
                .output()
                .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    let session = WorktreeSession::default();
    let mut c = Caveats::top();
    c.net = Scope::none();
    c.fs_write = Scope::only([temp.path().to_string_lossy().into_owned()]);
    let outcome = std::sync::OnceLock::new();
    let mut display = crate::agentic::display::ToolDisplay::new(Vec::new(), false, 80, 20, false);
    let output = execute(
        &mut display,
        "run_command",
        &serde_json::json!({"command":format!("git worktree add -b task '{}'", target.display())}),
        root.to_str().unwrap(),
        false,
        20,
        &c,
        &mut crate::agentic::NoMcp,
        ToolCollaborators {
            worktree_session: Some(&session),
            execution: Some(&outcome),
            ..Default::default()
        },
        false,
        PromptDisposition::Act,
    )
    .await;
    let adopted = session
        .snapshot()
        .unwrap_or_else(|| panic!("not adopted: {output}"));
    assert_eq!(adopted.worktree, target.canonicalize().unwrap());
    for (dir, expected) in [(&root, false), (&target, true)] {
        let outcome = std::sync::OnceLock::new();
        let command = format!(
            "python3 -c \"from pathlib import Path; Path('{}').write_text('probe')\"",
            dir.join("probe").display()
        );
        let output = execute(
            &mut display,
            "run_command",
            &serde_json::json!({"command":command, "cwd":target}),
            root.to_str().unwrap(),
            false,
            20,
            &c,
            &mut crate::agentic::NoMcp,
            ToolCollaborators {
                worktree_session: Some(&session),
                execution: Some(&outcome),
                ..Default::default()
            },
            false,
            PromptDisposition::Act,
        )
        .await;
        assert_eq!(dir.join("probe").exists(), expected, "{output}");
    }
    let outcome = std::sync::OnceLock::new();
    let output = execute(
        &mut display,
        "run_command",
        &serde_json::json!({"command":"git add probe", "cwd":target}),
        root.to_str().unwrap(),
        false,
        20,
        &c,
        &mut crate::agentic::NoMcp,
        ToolCollaborators {
            worktree_session: Some(&session),
            execution: Some(&outcome),
            ..Default::default()
        },
        false,
        PromptDisposition::Act,
    )
    .await;
    assert_eq!(
        outcome.get(),
        Some(&crate::ExecOutcome::Passed),
        "task Git metadata writes must remain usable: {output}"
    );
}

/// #2733: a same-invocation Python write cannot run before adoption takes effect.
#[test]
fn worktree_adoption_creation_is_an_execution_boundary() {
    for cmd in [
        "git worktree add ../task -b task; python3 mutate.py",
        "git worktree add ../task; echo stray > source.rs",
    ] {
        assert!(!creation_batch_is_read_only_after_add(
            &serde_json::json!({"command":cmd}),
            crate::ShellEngine::Brush
        ));
    }
    assert!(creation_batch_is_read_only_after_add(
        &serde_json::json!({"command":"git worktree add -b task ../task 2>&1; echo ready; pwd; git branch --show-current"}),
        crate::ShellEngine::Brush
    ));
}

/// #2733: an injected policy cannot authorize dispatch where its Git metadata
/// cannot be verified. Windows keeps the existing fail-closed runtime boundary.
#[cfg(not(unix))]
#[tokio::test]
async fn worktree_adoption_unverifiable_policy_refuses_dispatch() {
    let (temp, policy, _) = fixture(false);
    link(&policy);
    let original = temp.path().join("main");
    std::fs::write(original.join("source.rs"), "sentinel").unwrap();
    let session = WorktreeSession::default();
    session.adopt(policy);
    for name in ["read_file", "write_file", "delete_file"] {
        let text = call(
            name,
            &serde_json::json!({"path":"source.rs", "content":"changed"}),
            &original,
            &session,
        )
        .await;
        assert!(text.contains("capability denied"), "{text}");
        assert_eq!(
            std::fs::read_to_string(original.join("source.rs")).unwrap(),
            "sentinel"
        );
    }
}

/// #2813 reg2-A: absent/already-used adoption state must not send a nested
/// worktree creation through to a child and discover the ref fence by EPERM.
#[tokio::test]
async fn worktree_creation_2813_requires_an_available_adoption_session() {
    // #2813: cargo test runs alongside bypass fixtures on Windows. Pin the
    // governed mode under their shared lock; do not inherit a sibling's yolo.
    let _env = crate::agentic::tools::disable_ocap_tests::env_lock().await;
    let _ocap = crate::agentic::tools::disable_ocap_tests::EnvVar::unset("NEWT_DISABLE_OCAP");
    let (_temp, policy, _) = fixture(false);
    link(&policy);
    let root = policy.worktree.parent().unwrap().join("main");
    let session = WorktreeSession::default();
    session.adopt(policy.clone());
    for active in [None, Some(&session)] {
        let mut presentation =
            crate::agentic::display::ToolDisplay::new(Vec::new(), false, 80, 20, false);
        let outcome = std::sync::OnceLock::new();
        let source = format!("cd '{}' && git worktree add -b agentic-refactor-wt agentic-refactor-wt main 2>&1 | tail -5", root.display());
        let caveats = Caveats {
            exec: Scope::none(),
            ..Caveats::top()
        };
        let text = execute(
            &mut presentation,
            "run_command",
            &serde_json::json!({"command":source}),
            root.to_str().unwrap(),
            false,
            20,
            &caveats,
            &mut crate::agentic::NoMcp,
            ToolCollaborators {
                worktree_session: active,
                execution: Some(&outcome),
                ..Default::default()
            },
            false,
            PromptDisposition::Act,
        )
        .await;
        assert!(
            text.contains("standalone literal command")
                && text.contains("git worktree add -b <new-branch> <path> [<start>]"),
            "creation fell through admission: {text}"
        );
        assert_eq!(outcome.get(), Some(&crate::ExecOutcome::Denied));
        assert!(!root.join("agentic-refactor-wt").exists());
    }
}