aethershell 1.6.0

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
//! End-to-end tests for the safety core wired into effecting builtins.
//!
//! These exercise the real `bi_rm` dispatch path (not just the policy engine in
//! isolation) to prove that the guard is actually wired in: agent mode gates
//! destructive ops behind approval and the workspace jail, while human mode is
//! unchanged.

use aethershell::safety;
use aethershell::value::Value;

// Env is process-global and tests run in parallel threads — serialize them.
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Acquire the env lock, recovering from poisoning so that a panic in one test
/// cannot cascade and mask the real failure in every other test.
fn lock() -> std::sync::MutexGuard<'static, ()> {
    ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner())
}

fn clear() {
    for k in [
        "AETHER_MODE",
        "AETHER_AGENT",
        "AETHER_POLICY",
        "AETHER_APPROVE",
        "AETHER_APPROVE_ALL",
        "AETHER_WORKSPACE",
        "AETHER_AUDIT_LOG",
        "AETHER_MAX_OPS",
        "AETHER_MAX_FILES",
        "AETHER_MAX_PROCS",
        "AETHER_TIMEOUT_MS",
        "AETHER_RBAC_CONFIG",
        "AETHER_PRINCIPAL",
    ] {
        std::env::remove_var(k);
    }
    // Reset process-global safety state so tests can't contaminate each other.
    safety::set_principal(None);
    safety::clear_rbac_manager();
    safety::governor_reset();
}

/// A unique workspace dir + an audit log redirected into it.
fn fresh_workspace(tag: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!("ae_safety_it_{}_{}", tag, std::process::id()));
    let _ = std::fs::create_dir_all(&dir);
    std::env::set_var("AETHER_WORKSPACE", &dir);
    std::env::set_var(
        "AETHER_AUDIT_LOG",
        dir.join("audit.log").to_string_lossy().to_string(),
    );
    dir
}

fn token_from_error(err: &anyhow::Error) -> String {
    let rendered = format!("{}", err);
    let json: serde_json::Value =
        serde_json::from_str(&rendered).expect("safety error should render as JSON");
    json["error"]["approval"]["token"]
        .as_str()
        .expect("needs-approval error carries an approval token")
        .to_string()
}

#[test]
fn rm_in_human_mode_just_works() {
    let _l = lock();
    clear();
    let dir = std::env::temp_dir().join(format!("ae_human_rm_{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("victim.txt");
    std::fs::write(&file, b"bye").unwrap();

    let res =
        aethershell::builtins::bi_rm(vec![Value::Str(file.to_string_lossy().to_string())], None);
    assert!(res.is_ok(), "human-mode rm should succeed: {:?}", res.err());
    assert!(!file.exists(), "file should be gone");
    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn rm_in_agent_mode_requires_then_accepts_approval() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    let dir = fresh_workspace("rm_approve");
    let file = dir.join("victim.txt");
    std::fs::write(&file, b"bye").unwrap();
    let arg = Value::Str(file.to_string_lossy().to_string());

    // First call: blocked, file untouched, structured needs-approval error.
    let err = aethershell::builtins::bi_rm(vec![arg.clone()], None).unwrap_err();
    let rendered = format!("{}", err);
    assert!(rendered.contains("E_NEEDS_APPROVAL"), "got: {rendered}");
    assert!(file.exists(), "file must NOT be deleted before approval");

    // Re-call with the bound token: now it proceeds.
    let token = token_from_error(&err);
    std::env::set_var("AETHER_APPROVE", &token);
    let res = aethershell::builtins::bi_rm(vec![arg], None);
    assert!(res.is_ok(), "approved rm should succeed: {:?}", res.err());
    assert!(!file.exists(), "file should be gone after approval");

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn governor_file_budget_blocks_second_rm_in_agent_mode() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    // Pre-approve so rm proceeds past the approval gate — we want the governor,
    // not approval, to be the thing that stops the second delete.
    std::env::set_var("AETHER_APPROVE_ALL", "1");
    let dir = fresh_workspace("rm_governor");
    safety::governor_reset();
    std::env::set_var("AETHER_MAX_FILES", "1");

    let f1 = dir.join("a.txt");
    let f2 = dir.join("b.txt");
    std::fs::write(&f1, b"a").unwrap();
    std::fs::write(&f2, b"b").unwrap();

    // First delete is within the file budget.
    let r1 = aethershell::builtins::bi_rm(vec![Value::Str(f1.to_string_lossy().to_string())], None);
    assert!(r1.is_ok(), "first rm should succeed: {:?}", r1.err());
    assert!(!f1.exists());

    // Second delete exceeds AETHER_MAX_FILES → E_BUDGET_EXCEEDED, file untouched.
    let err =
        aethershell::builtins::bi_rm(vec![Value::Str(f2.to_string_lossy().to_string())], None)
            .unwrap_err();
    let rendered = format!("{}", err);
    assert!(rendered.contains("E_BUDGET_EXCEEDED"), "got: {rendered}");
    assert!(
        f2.exists(),
        "file must NOT be deleted once the budget is exhausted"
    );

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn rbac_config_loaded_at_startup_authorizes_principal() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    let dir = fresh_workspace("rbac_cfg");

    // A config that grants the `ci` principal the `destructive` effect via a role.
    let cfg = dir.join("rbac.toml");
    std::fs::write(
        &cfg,
        r#"
principal = "ci"
[[role]]
name = "deployer"
permissions = ["effect:destructive"]
[[user]]
id = "ci"
roles = ["deployer"]
"#,
    )
    .unwrap();
    std::env::set_var("AETHER_RBAC_CONFIG", cfg.to_string_lossy().to_string());

    // Boot-time load installs the manager and sets the acting principal.
    safety::init_rbac_from_env();
    assert_eq!(safety::current_principal().as_deref(), Some("ci"));

    // The authorized principal bypasses the approval gate for a destructive rm.
    let file = dir.join("v.txt");
    std::fs::write(&file, b"x").unwrap();
    let res =
        aethershell::builtins::bi_rm(vec![Value::Str(file.to_string_lossy().to_string())], None);
    assert!(
        res.is_ok(),
        "RBAC-authorized principal should bypass approval: {:?}",
        res.err()
    );
    assert!(!file.exists());

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn rm_outside_workspace_is_blocked_in_agent_mode() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    let _dir = fresh_workspace("rm_jail");

    let outside = if cfg!(windows) {
        "C:/Windows/System32/drivers/etc/hosts"
    } else {
        "/etc/hosts"
    };
    let err =
        aethershell::builtins::bi_rm(vec![Value::Str(outside.to_string())], None).unwrap_err();
    let rendered = format!("{}", err);
    assert!(rendered.contains("E_OUTSIDE_WORKSPACE"), "got: {rendered}");

    let _ = std::fs::remove_dir_all(&_dir);
    clear();
}

#[test]
fn approve_builtin_unblocks_guarded_rm_and_audit_verify_passes() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    let dir = fresh_workspace("approve_builtin");
    let file = dir.join("v.txt");
    std::fs::write(&file, b"x").unwrap();
    let arg = Value::Str(file.to_string_lossy().to_string());
    let mut env = aethershell::env::Env::new();

    // Trigger the block via the real guarded builtin, then pull the bound token.
    let err = aethershell::builtins::bi_rm(vec![arg.clone()], None).unwrap_err();
    let token = token_from_error(&err);

    // approve(token) via the dispatch table (proves index 1104 → bi_approve).
    let approved = aethershell::builtins::call("approve", vec![Value::Str(token)], &mut env)
        .expect("approve builtin runs");
    match approved {
        Value::Record(m) => assert_eq!(m.get("approved"), Some(&Value::Bool(true))),
        other => panic!("approve should return a record, got {other:?}"),
    }

    // Now the guarded rm proceeds (in-process grant honored).
    assert!(
        aethershell::builtins::bi_rm(vec![arg], None).is_ok(),
        "rm should succeed after approve()"
    );
    assert!(!file.exists());

    // audit_verify() via the dispatch table (proves index 1105 → bi_audit_verify).
    let verified = aethershell::builtins::call("audit_verify", vec![], &mut env)
        .expect("audit_verify builtin runs");
    match verified {
        Value::Record(m) => assert_eq!(m.get("valid"), Some(&Value::Bool(true))),
        other => panic!("audit_verify should return a record, got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn try_catch_binds_structured_safety_error() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    let dir = fresh_workspace("trycatch");

    // A guarded destructive builtin reached through the evaluator: in agent mode
    // it refuses, and try/catch should bind `e` to a structured Record, not a
    // string — so an agent can branch on `e.error.code`.
    let src = r#"try { db_sqlite_delete("x.db", "t", "1=1") } catch e { e }"#;
    let stmts = aethershell::parser::parse_program(src).expect("parse");
    let mut env = aethershell::env::Env::new();
    let result = aethershell::eval::eval_program(&stmts, &mut env).expect("eval");

    match result {
        Value::Record(m) => match m.get("error") {
            Some(Value::Record(e)) => assert_eq!(
                e.get("code"),
                Some(&Value::Str("E_NEEDS_APPROVAL".to_string())),
                "caught error should carry the stable code"
            ),
            other => panic!("error should be a nested record, got {other:?}"),
        },
        other => panic!("catch should bind a structured record, got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn in_shell_rbac_principal_and_grant_bypass_approval() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    let dir = fresh_workspace("rbac_shell");
    let file = dir.join("v.txt");
    std::fs::write(&file, b"x").unwrap();
    let arg = Value::Str(file.to_string_lossy().to_string());
    let mut env = aethershell::env::Env::new();

    // Configure RBAC entirely through builtins (dispatch indices 1106-1108).
    aethershell::builtins::call("rbac_principal", vec![Value::Str("alice".into())], &mut env)
        .expect("set principal");
    // Before any grant, alice cannot perform destructive ops.
    let can_before = aethershell::builtins::call(
        "rbac_can",
        vec![Value::Str("effect:destructive".into())],
        &mut env,
    )
    .expect("rbac_can");
    assert_eq!(can_before, Value::Bool(false));

    aethershell::builtins::call(
        "rbac_grant",
        vec![
            Value::Str("alice".into()),
            Value::Str("effect:destructive".into()),
        ],
        &mut env,
    )
    .expect("grant");
    let can_after = aethershell::builtins::call(
        "rbac_can",
        vec![Value::Str("effect:destructive".into())],
        &mut env,
    )
    .expect("rbac_can");
    assert_eq!(can_after, Value::Bool(true), "grant should take effect");

    // The guarded destructive op now proceeds for alice without approval.
    assert!(
        aethershell::builtins::bi_rm(vec![arg], None).is_ok(),
        "authorized principal bypasses approval"
    );
    assert!(!file.exists());

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn safety_status_reports_the_operating_envelope() {
    let _l = lock();
    clear();
    let mut env = aethershell::env::Env::new();

    // Human mode: everything allowed.
    let st = aethershell::builtins::call("safety_status", vec![], &mut env).unwrap();
    match st {
        Value::Record(m) => {
            assert_eq!(m.get("mode"), Some(&Value::Str("human".into())));
            assert_eq!(m.get("transaction_active"), Some(&Value::Bool(false)));
            if let Some(Value::Record(p)) = m.get("policy") {
                assert_eq!(p.get("destructive"), Some(&Value::Str("allow".into())));
            } else {
                panic!("policy record missing");
            }
        }
        other => panic!("expected record, got {other:?}"),
    }

    // Agent mode: dangerous classes are gated.
    std::env::set_var("AETHER_MODE", "agent");
    let st = aethershell::builtins::call("safety_status", vec![], &mut env).unwrap();
    match st {
        Value::Record(m) => {
            assert_eq!(m.get("mode"), Some(&Value::Str("agent".into())));
            if let Some(Value::Record(p)) = m.get("policy") {
                assert_eq!(p.get("destructive"), Some(&Value::Str("approve".into())));
                assert_eq!(p.get("exec"), Some(&Value::Str("approve".into())));
                assert_eq!(p.get("privileged"), Some(&Value::Str("deny".into())));
                assert_eq!(p.get("read_local"), Some(&Value::Str("allow".into())));
            } else {
                panic!("policy record missing");
            }
        }
        other => panic!("expected record, got {other:?}"),
    }
    clear();
}

#[test]
fn remote_and_platform_deletes_are_gated_in_agent_mode() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    let dir = fresh_workspace("remote_del");
    let mut env = aethershell::env::Env::new();

    // platform_db_delete and k8s_delete are gated before they touch the db /
    // invoke kubectl — the guard short-circuits in agent mode.
    let pdb = aethershell::builtins::call(
        "platform_db_delete",
        vec![Value::Str("some_key".into())],
        &mut env,
    )
    .unwrap_err();
    assert!(format!("{pdb}").contains("E_NEEDS_APPROVAL"), "got: {pdb}");

    let k8s = aethershell::builtins::call(
        "k8s_delete",
        vec![Value::Str("pod".into()), Value::Str("nginx".into())],
        &mut env,
    )
    .unwrap_err();
    assert!(format!("{k8s}").contains("E_NEEDS_APPROVAL"), "got: {k8s}");

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn audit_tail_returns_recent_decisions() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    let dir = fresh_workspace("tail");

    // A guarded rm without approval writes a `needs_approval` audit entry.
    let target = dir.join("ae_tail_target.txt").to_string_lossy().to_string();
    let _ = aethershell::builtins::bi_rm(vec![Value::Str(target)], None);

    let mut env = aethershell::env::Env::new();
    let tail = aethershell::builtins::call("audit_tail", vec![Value::Int(10)], &mut env).unwrap();
    match tail {
        Value::Array(entries) => {
            assert!(!entries.is_empty(), "audit tail has recent entries");
            let has_rm = entries.iter().any(|e| {
                matches!(e, Value::Record(m) if m.get("builtin") == Some(&Value::Str("rm".into())))
            });
            assert!(has_rm, "the rm decision appears in the audit tail");
        }
        other => panic!("expected array, got {other:?}"),
    }

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn audit_log_is_written_and_verifies_in_agent_mode() {
    let _l = lock();
    clear();
    std::env::set_var("AETHER_MODE", "agent");
    std::env::set_var("AETHER_APPROVE_ALL", "1");
    let dir = fresh_workspace("audit");
    let log = dir.join("audit.log");
    let file = dir.join("a.txt");
    std::fs::write(&file, b"x").unwrap();

    aethershell::builtins::bi_rm(vec![Value::Str(file.to_string_lossy().to_string())], None)
        .expect("approve-all permits rm");

    assert!(log.exists(), "audit log should be written in agent mode");
    let n = safety::verify_audit(&log).expect("audit chain verifies");
    assert!(n >= 1, "at least one audited entry");

    let _ = std::fs::remove_dir_all(&dir);
    clear();
}

#[test]
fn path_jail_applies_only_in_agent_mode() {
    // A path outside the project directory: a normal interactive (human) shell may
    // read it; an agent-mode/sandboxed shell must not.
    let _l = lock();
    clear();
    let outside = std::env::temp_dir();
    let outside = outside.to_str().expect("temp dir is valid UTF-8");

    // Human mode (no AETHER_MODE / AETHER_WORKSPACE): unrestricted, like bash/zsh.
    assert!(
        aethershell::security::validate_read_path(outside).is_ok(),
        "human mode must NOT sandbox to the project directory"
    );

    // Agent mode with a workspace: the same outside path is blocked by the jail.
    std::env::set_var("AETHER_MODE", "agent");
    std::env::set_var(
        "AETHER_WORKSPACE",
        std::env::current_dir()
            .unwrap()
            .to_string_lossy()
            .to_string(),
    );
    assert!(
        aethershell::security::validate_read_path(outside).is_err(),
        "agent mode must jail reads to the workspace"
    );

    clear();
}