bashkit 0.20.1

Awesomely fast virtual sandbox with bash and file system
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
#[cfg(feature = "jq")]
use bashkit::ExecOptions;
use bashkit::{
    Bash, Builtin, BuiltinContext, Error, ExecResult, ExecutionBudget, ExecutionLimits,
    LimitExceeded, SessionLimits, async_trait,
};
use std::path::Path;
use std::sync::{Arc, Mutex};

fn assert_budget_exhausted(result: bashkit::Result<bashkit::ExecResult>) {
    assert!(
        matches!(
            result,
            Err(Error::ResourceLimit(LimitExceeded::ExecutionBudget(_)))
        ),
        "expected shared execution budget exhaustion, got {result:?}"
    );
}

#[tokio::test]
/// TM-DOS-111: the `$(<file)` fast path is still an executed command.
async fn command_substitution_file_read_respects_command_limit() {
    let limits = ExecutionLimits::new().max_commands(1);
    let mut bash = Bash::builder().limits(limits).build();
    bash.fs()
        .write_file(Path::new("/f"), b"data")
        .await
        .unwrap();

    let result = bash.exec(": \"$(</f)\"").await;
    assert!(
        matches!(
            result,
            Err(Error::ResourceLimit(LimitExceeded::MaxCommands(1)))
        ),
        "expected command limit exhaustion, got {result:?}"
    );
}

#[tokio::test]
/// TM-DOS-111: shortcut commands count toward the cumulative session limit.
async fn command_substitution_file_read_respects_session_command_limit() {
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_commands(100))
        .session_limits(
            SessionLimits::new()
                .max_total_commands(1)
                .max_exec_calls(100),
        )
        .build();
    bash.fs()
        .write_file(Path::new("/f"), b"data")
        .await
        .unwrap();

    let error = bash.exec(": \"$(</f)\"").await.unwrap_err().to_string();
    assert!(error.contains("session command limit"), "{error}");
}

#[tokio::test]
/// TM-DOS-111: the shortcut consumes the same shared work unit as a command.
async fn command_substitution_file_read_respects_work_limit() {
    let limits = ExecutionLimits::new()
        .max_commands(100)
        .max_work_units(1)
        .max_aggregate_input_bytes(1_000);
    let mut bash = Bash::builder().limits(limits).build();
    bash.fs()
        .write_file(Path::new("/f"), b"data")
        .await
        .unwrap();

    assert_budget_exhausted(bash.exec(": \"$(</f)\"").await);
}

#[tokio::test]
/// TM-DOS-111: file-backed substitution text is a live intermediate.
async fn command_substitution_file_read_respects_live_byte_limit() {
    let limits = ExecutionLimits::new()
        .max_commands(100)
        .max_work_units(10_000)
        .max_live_intermediate_bytes(4);
    let mut bash = Bash::builder().limits(limits).build();
    bash.fs()
        .write_file(Path::new("/f"), b"12345")
        .await
        .unwrap();

    assert_budget_exhausted(bash.exec(": \"$(</f)\"").await);
}

#[tokio::test]
/// TM-DOS-111: sibling substitutions cannot each reuse the full live budget.
async fn command_substitution_file_reads_share_live_byte_limit() {
    let limits = ExecutionLimits::new()
        .max_commands(100)
        .max_work_units(10_000)
        .max_live_intermediate_bytes(10);
    let mut bash = Bash::builder().limits(limits).build();
    bash.fs().write_file(Path::new("/f"), b"123").await.unwrap();

    assert_budget_exhausted(bash.exec(": \"$(</f)$(</f)$(</f)\"").await);
}

#[tokio::test]
/// TM-DOS-096: nested parsers/interpreters must share aggregate work.
async fn nested_command_substitutions_cannot_refresh_work_budget() {
    let limits = ExecutionLimits::new()
        .max_commands(100)
        .max_work_units(6)
        .max_aggregate_input_bytes(1_000);
    let mut bash = Bash::builder().limits(limits).build();

    assert_budget_exhausted(bash.exec("echo $(echo $(echo $(echo nested)))").await);
}

#[tokio::test]
/// TM-DOS-096: changing builtin subsystems in a pipeline cannot refresh input.
async fn mixed_pipeline_consumers_share_aggregate_input_budget() {
    let limits = ExecutionLimits::new()
        .max_commands(100)
        .max_work_units(10_000)
        .max_aggregate_input_bytes(80);
    let mut bash = Bash::builder().limits(limits).build();

    assert_budget_exhausted(
        bash.exec("printf 12345678901234567890 | cat | awk '{print}' | rg 1")
            .await,
    );
}

#[tokio::test]
/// TM-DOS-116: awk close/reopen cycles must not recycle getline input budget.
async fn awk_getline_close_cannot_recycle_input_budget() {
    use bashkit::FileSystem;
    use bashkit::InMemoryFs;
    use std::path::Path;

    let fs = Arc::new(InMemoryFs::new());
    // Exactly the per-file cap: reopening it used to make each 10 MB load
    // disappear from accounting as soon as close() dropped the cache entry.
    fs.write_file(Path::new("/tmp/data"), &vec![b'x'; 10_000_000])
        .await
        .unwrap();
    let limits = ExecutionLimits::new()
        .max_commands(100)
        .max_work_units(30_000_000)
        .max_aggregate_input_bytes(15_000_000);
    let mut bash = Bash::builder().fs(fs).limits(limits).build();

    assert_budget_exhausted(
        bash.exec(
            r#"awk 'BEGIN { for (i = 0; i < 2; i++) { getline x < "/tmp/data"; close("/tmp/data") } }'"#,
        )
        .await,
    );
}

#[tokio::test]
/// TM-DOS-096: the first exhaustion poisons all later descendants.
async fn a_poisoned_budget_stops_later_pipeline_stages() {
    let limits = ExecutionLimits::new()
        .max_commands(100)
        .max_work_units(8)
        .max_aggregate_input_bytes(10_000);
    let mut bash = Bash::builder().limits(limits).build();

    let result = bash
        .exec("printf first | awk '{print}'; echo must-not-run")
        .await;
    assert_budget_exhausted(result);
}

#[tokio::test]
async fn separate_host_requests_receive_fresh_budgets() {
    let limits = ExecutionLimits::new()
        .max_work_units(8)
        .max_aggregate_input_bytes(1_000);
    let mut bash = Bash::builder().limits(limits).build();

    assert_eq!(bash.exec("true").await.unwrap().exit_code, 0);
    assert_eq!(bash.exec("true").await.unwrap().exit_code, 0);
}

#[derive(Clone)]
struct CaptureBoundary(Arc<Mutex<Option<ExecutionBudget>>>);

#[async_trait]
impl Builtin for CaptureBoundary {
    async fn execute(&self, ctx: BuiltinContext<'_>) -> bashkit::Result<ExecResult> {
        *self.0.lock().unwrap() = ctx
            .execution_budget()
            .and_then(|budget| budget.try_with(Clone::clone).ok());
        Ok(ExecResult::ok("captured\n"))
    }
}

#[tokio::test]
/// TM-ISO-027: a request boundary closes even when a host retains a clone.
async fn completed_request_rejects_late_work() {
    let captured = Arc::new(Mutex::new(None));
    let mut bash = Bash::builder()
        .builtin("capture", Box::new(CaptureBoundary(captured.clone())))
        .build();

    assert_eq!(bash.exec("capture").await.unwrap().stdout, "captured\n");
    let old = captured.lock().unwrap().take().unwrap();
    assert_eq!(
        old.check().unwrap_err().to_string(),
        "execution budget exhausted: request closed"
    );
    assert_eq!(
        old.consume_work(1).unwrap_err().to_string(),
        "execution budget exhausted: request closed"
    );

    assert_eq!(bash.exec("echo reused").await.unwrap().stdout, "reused\n");
    assert_eq!(
        old.check().unwrap_err().to_string(),
        "execution budget exhausted: request closed"
    );
}

#[tokio::test]
/// TM-ISO-027: independently executing shells never share lifecycle state.
async fn concurrent_requests_have_independent_boundaries() {
    let left = Arc::new(Mutex::new(None));
    let right = Arc::new(Mutex::new(None));
    let mut left_bash = Bash::builder()
        .builtin("capture", Box::new(CaptureBoundary(left.clone())))
        .build();
    let mut right_bash = Bash::builder()
        .builtin("capture", Box::new(CaptureBoundary(right.clone())))
        .build();

    let (left_result, right_result) = tokio::join!(
        left_bash.exec("capture; echo left"),
        right_bash.exec("capture; echo right")
    );
    assert_eq!(left_result.unwrap().stdout, "captured\nleft\n");
    assert_eq!(right_result.unwrap().stdout, "captured\nright\n");
    let left = left.lock().unwrap().take().unwrap();
    let right = right.lock().unwrap().take().unwrap();
    assert_eq!(
        left.check().unwrap_err().to_string(),
        "execution budget exhausted: request closed"
    );
    assert_eq!(
        right.check().unwrap_err().to_string(),
        "execution budget exhausted: request closed"
    );
}

#[cfg(feature = "jq")]
#[tokio::test]
/// TM-DOS-096: jq generator work is charged to the host request.
async fn jq_generator_consumes_shared_work_budget() {
    let limits = ExecutionLimits::new()
        .max_work_units(500)
        .max_aggregate_input_bytes(100_000);
    let mut bash = Bash::builder().limits(limits).build();

    assert_budget_exhausted(bash.exec("jq -n 'range(0; 10000)'").await);
}

#[cfg(feature = "jq")]
#[tokio::test]
/// TM-DOS-100: jq must reserve normalized input before control expansion.
async fn jq_control_normalization_respects_live_memory_budget() {
    let limits = ExecutionLimits::new()
        .max_work_units(10_000)
        .max_aggregate_input_bytes(10_000)
        .max_live_intermediate_bytes(8);
    let mut bash = Bash::builder().limits(limits).build();

    assert_budget_exhausted(
        bash.exec_with_options("jq -c .", ExecOptions::new().stdin("\"a\n\""))
            .await,
    );
}

#[cfg(feature = "jq")]
#[tokio::test]
/// TM-DOS-110: stream preprocessing must obey the intermediate limit even for empty.
async fn jq_stream_long_key_respects_memory_limit() {
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(32_768))
        .build();
    let input = format!("{{\"{}\":[null,null]}}", "k".repeat(65_536));
    bash.fs()
        .write_file(Path::new("/input.json"), input.as_bytes())
        .await
        .unwrap();
    let result = bash.exec("jq --stream empty /input.json").await.unwrap();
    assert_eq!(result.exit_code, 5);
    assert!(
        result
            .stderr
            .contains("value size limit (32768 bytes) exceeded"),
        "{}",
        result.stderr
    );
    assert!(result.stdout.is_empty());
    assert_eq!(
        bash.exec("echo recovered").await.unwrap().stdout,
        "recovered\n"
    );
}

#[cfg(feature = "jq")]
#[tokio::test]
/// TM-DOS-110: slurping events retains them and must meter their bodies.
async fn jq_stream_slurp_respects_memory_limit() {
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(65_536))
        .build();
    let input = format!(
        "{{\"{}\":[{}]}}",
        "k".repeat(1024),
        vec!["null"; 2000].join(",")
    );
    let result = bash
        .exec_with_options("jq --stream --slurp empty", ExecOptions::new().stdin(input))
        .await
        .unwrap();
    assert_eq!(result.exit_code, 5);
    assert!(
        result
            .stderr
            .contains("value size limit (65536 bytes) exceeded"),
        "{}",
        result.stderr
    );
    assert!(result.stdout.is_empty());
}

#[cfg(feature = "jq")]
#[tokio::test]
/// Shared keys and lazy events keep many leaves below a small live limit.
async fn jq_stream_many_leaves_fit_small_memory_limit() {
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(65_536))
        .build();
    let input = format!(
        "{{\"{}\":[{}]}}",
        "k".repeat(1024),
        vec!["null"; 2000].join(",")
    );
    let result = bash
        .exec_with_options(
            "jq -nc --stream 'reduce inputs as $event (0; . + 1)'",
            ExecOptions::new().stdin(input),
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0, "{}", result.stderr);
    assert_eq!(result.stdout, "2002\n");
}

#[cfg(feature = "jq")]
#[tokio::test]
/// Non-emitting filters must charge traversal, beyond input normalization.
async fn jq_stream_empty_consumes_shared_work_budget() {
    let input = format!("[{}]", vec!["null"; 1000].join(","));
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_work_units(input.len() as u64 + 500))
        .build();
    assert_budget_exhausted(
        bash.exec_with_options("jq --stream empty", ExecOptions::new().stdin(input))
            .await,
    );
}

#[cfg(feature = "python")]
#[tokio::test]
/// TM-DOS-096: separate Python entries cannot each claim a fresh VM allowance.
async fn repeated_python_entries_share_runtime_admission_budget() {
    let limits = ExecutionLimits::new()
        .max_work_units(1_500_000)
        .max_aggregate_input_bytes(100_000);
    let mut bash = Bash::builder()
        .limits(limits)
        .python()
        .env("BASHKIT_ALLOW_INPROCESS_PYTHON", "1")
        .build();

    assert_budget_exhausted(
        bash.exec("python -c 'print(1)'; python -c 'print(2)'")
            .await,
    );
}

#[cfg(feature = "typescript")]
#[tokio::test]
/// TM-DOS-096: separate TypeScript entries cannot refresh allocation fuel.
async fn repeated_typescript_entries_share_runtime_admission_budget() {
    let limits = ExecutionLimits::new()
        .max_work_units(1_500_000)
        .max_aggregate_input_bytes(100_000);
    let mut bash = Bash::builder().limits(limits).typescript().build();

    assert_budget_exhausted(bash.exec("ts -c '1 + 1'; ts -c '2 + 2'").await);
}

#[cfg(feature = "sqlite")]
#[tokio::test]
/// TM-DOS-096: SQLite VM steps consume the request's remaining work.
async fn sqlite_steps_consume_shared_work_budget() {
    let limits = ExecutionLimits::new()
        .max_work_units(600)
        .max_aggregate_input_bytes(100_000);
    let mut bash = Bash::builder()
        .limits(limits)
        .sqlite()
        .env("BASHKIT_ALLOW_INPROCESS_SQLITE", "1")
        .build();

    let sql = "SELECT 1;".repeat(400);
    assert_budget_exhausted(bash.exec(&format!("sqlite :memory: '{sql}'")).await);
}

#[cfg(feature = "sqlite")]
#[tokio::test]
/// TM-SQL-014: work done inside a single `Statement::step()` is charged too.
///
/// The rows of this recursive CTE are swallowed by the aggregate, so the query
/// never returns from its first step. Without the VM progress handler the
/// request would spin forever with the budget untouched.
async fn unbounded_recursive_cte_consumes_shared_work_budget() {
    let limits = ExecutionLimits::new()
        .max_work_units(2_000)
        .max_aggregate_input_bytes(100_000);
    let mut bash = Bash::builder()
        .limits(limits)
        .sqlite()
        .env("BASHKIT_ALLOW_INPROCESS_SQLITE", "1")
        .build();

    assert_budget_exhausted(
        bash.exec(
            "sqlite :memory: 'WITH RECURSIVE r(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM r) \
             SELECT count(*) FROM r;'",
        )
        .await,
    );
}

#[tokio::test]
async fn cdpath_candidate_respects_live_byte_limit() {
    let limits = ExecutionLimits::new().max_live_intermediate_bytes(256);
    let mut bash = Bash::builder()
        .env("CDPATH", ":".repeat(256))
        .limits(limits)
        .build();
    // Bounded reproduction: the old collector allocates only about 25 KiB.
    assert_budget_exhausted(bash.exec(&format!("cd {}", "x".repeat(64))).await);
    assert_eq!(bash.exec("pwd").await.unwrap().exit_code, 0);
}

#[tokio::test]
async fn cdpath_search_respects_work_limit() {
    let limits = ExecutionLimits::new().max_work_units(64);
    let mut bash = Bash::builder()
        .env("CDPATH", ":".repeat(256))
        .limits(limits)
        .build();
    assert_budget_exhausted(bash.exec("cd missing").await);
}

#[tokio::test]
async fn cdpath_script_assignment_cannot_bypass_live_byte_limit() {
    let limits = ExecutionLimits::new().max_live_intermediate_bytes(1_024);
    let mut bash = Bash::builder().limits(limits).build();
    let script = format!("CDPATH={}\ncd {}", ":".repeat(256), "x".repeat(64));
    assert_budget_exhausted(bash.exec(&script).await);
}

#[tokio::test]
async fn cdpath_releases_failed_candidate_workspace() {
    let limits = ExecutionLimits::new().max_live_intermediate_bytes(1_024);
    let mut bash = Bash::builder()
        .env("CDPATH", ":".repeat(256))
        .limits(limits)
        .build();
    let result = bash.exec("cd missing").await.unwrap();
    assert_eq!(result.exit_code, 1);
    assert!(result.stderr.contains("No such file or directory"));
}

#[tokio::test]
async fn cdpath_stops_at_first_hit_under_small_budgets() {
    let limits = ExecutionLimits::new()
        .max_live_intermediate_bytes(1_024)
        .max_work_units(64);
    let mut bash = Bash::builder()
        .env("CDPATH", format!("/tmp:{}", "missing:".repeat(1_024)))
        .limits(limits)
        .build();
    bash.fs()
        .mkdir(Path::new("/tmp/target"), false)
        .await
        .unwrap();
    let result = bash.exec("cd target; pwd").await.unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout, "/tmp/target\n/tmp/target\n");
}

#[tokio::test]
async fn cdpath_search_yields_to_cancellation() {
    use std::sync::atomic::Ordering;
    let mut bash = Bash::builder().env("CDPATH", ":".repeat(1_024)).build();
    let token = bash.cancellation_token();
    let cancel = async {
        for _ in 0..3 {
            tokio::task::yield_now().await;
        }
        token.store(true, Ordering::Relaxed);
    };
    let (result, ()) = tokio::join!(bash.exec("cd missing"), cancel);
    assert!(
        result.is_err(),
        "search completed without observing cancellation"
    );
    assert!(result.unwrap_err().to_string().contains("cancelled"));
}

#[tokio::test]
async fn indexed_array_pending_values_share_live_byte_limit() {
    for assignment in [
        "a=([0]=$v [0]=$v [0]=$v [0]=$v)",
        "declare -a a=([0]=$v [0]=$v [0]=$v [0]=$v)",
        "a+=([0]=$v [0]=$v [0]=$v [0]=$v)",
        "a=(\"$v\" \"$v\" \"$v\" \"$v\")",
        "a=(\"$v\"{1..4})",
        "a=([0]=$v$v$v)",
    ] {
        let mut bash = Bash::builder()
            .limits(ExecutionLimits::new().max_live_intermediate_bytes(8_192))
            .build();
        bash.exec(&format!("v='{}'; a=(original)", "x".repeat(4_096)))
            .await
            .unwrap();
        assert_budget_exhausted(bash.exec(assignment).await);
        assert_eq!(
            bash.exec("echo ${a[0]}").await.unwrap().stdout,
            "original\n"
        );
        assert_eq!(bash.exec("echo reused").await.unwrap().stdout, "reused\n");
    }
}

#[tokio::test]
async fn tilde_expansion_repeated_directories_respect_live_budget() {
    // Safe reproducer: at most 24 KiB of expansion, admitted by retained limits.
    for (name, tilde) in [("HOME", "~"), ("PWD", "~+"), ("OLDPWD", "~-")] {
        for (command, suffix) in [
            ("x=a", ""),
            ("export x=a", ""),
            ("echo x=a", ""),
            ("x[0]=a", ""),
            ("declare -a x=([0]=a", ")"),
            ("echo x=a", "\"\""),
        ] {
            let limits = ExecutionLimits::new().max_live_intermediate_bytes(8_192);
            let mut bash = Bash::builder().limits(limits).build();
            let script = format!(
                "export {name}='{}'; {command}{}{suffix}",
                "d".repeat(1_024),
                format!(":{tilde}").repeat(24)
            );
            assert_budget_exhausted(bash.exec(&script).await);
            let recovered = bash.exec("echo recovered").await.unwrap();
            assert_eq!(recovered.stdout, "recovered\n");
        }
    }
}

#[tokio::test]
async fn indexed_array_pending_keys_share_live_byte_limit() {
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(8_192))
        .build();
    // Leading zeroes keep every subscript valid and small.
    bash.exec(&format!("k='{}'", "0".repeat(4_096)))
        .await
        .unwrap();
    assert_budget_exhausted(bash.exec("a=([$k]=x [$k]=y [$k]=z)").await);
}

#[tokio::test]
async fn indexed_array_pending_storage_is_released_between_assignments() {
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(8_192))
        .build();
    let result = bash
        .exec(&format!(
            "v='{}'; a=([0]=$v); a=([0]=$v); a=([0]=$v); echo ${{#a[0]}}",
            "x".repeat(4_096)
        ))
        .await
        .unwrap();
    assert_eq!(result.stdout, "4096\n");
}

#[tokio::test]
async fn indexed_array_budget_preserves_expansion_order() {
    let script = "a=(old); a=([0]=1+2 [a[0]]=$a [0]+=x); printf '%s\\n' \"${a[0]}\" \"${a[3]}\"; a+=([0]=new [1]=$a); printf '%s\\n' \"${a[1]}\"";
    let expected = std::process::Command::new("bash")
        .args(["--noprofile", "--norc", "-c", script])
        .output()
        .unwrap();
    assert!(expected.status.success());
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(8_192))
        .build();
    let result = bash.exec(script).await.unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout.as_bytes(), expected.stdout);
    assert_eq!(result.stderr.as_bytes(), expected.stderr);
}

#[tokio::test]
async fn tilde_expansion_charges_copied_bytes_as_work() {
    let limits = ExecutionLimits::new().max_work_units(5_000);
    let mut bash = Bash::builder().limits(limits).build();
    bash.exec(&format!("HOME='{}'", "d".repeat(1_024)))
        .await
        .unwrap();
    assert_budget_exhausted(bash.exec(&format!("x=a{}", ":~".repeat(24))).await);
}

#[tokio::test]
async fn tilde_expansion_single_directory_and_operands_respect_live_budget() {
    for command in ["x=~", "echo ~", "echo ${unset:-~}", "echo ${unset:=~}"] {
        let limits = ExecutionLimits::new().max_live_intermediate_bytes(512);
        let mut bash = Bash::builder().limits(limits).build();
        bash.exec(&format!("HOME='{}'", "d".repeat(1_024)))
            .await
            .unwrap();
        assert_budget_exhausted(bash.exec(command).await);
    }
}

#[tokio::test]
async fn tilde_expansion_retains_sibling_assignment_leases() {
    let limits = ExecutionLimits::new().max_live_intermediate_bytes(3_072);
    let mut bash = Bash::builder().limits(limits).build();
    bash.exec(&format!("HOME='{}'", "d".repeat(1_024)))
        .await
        .unwrap();
    assert_budget_exhausted(bash.exec("x=~/\"\":~/\"\":~/").await);
}

#[tokio::test]
async fn tilde_expansion_preserves_bash_semantics() {
    let script = r#"HOME='/home/test dir'; PWD=/pwd; OLDPWD=/old
x=~:~+/bin:~-/lib:~missing
printf '%s\n' "$x" ~ ~missing
printf '%s\n' x=~:~+:'~'
x='~:~'; printf '%s\n' "$x" '~' \~ '~'$HOME
unset value; printf '%s\n' "${value:-~}" "${value:-'~'}"
x=~/"":~; printf '%s\n' "$x"
"#;
    let expected = std::process::Command::new("bash")
        .env("HOME", "/home/test dir")
        .arg("--noprofile")
        .arg("--norc")
        .arg("-c")
        .arg(script)
        .output()
        .unwrap();
    assert!(expected.status.success());
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(8_192))
        .build();
    let result = bash.exec(script).await.unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.stdout.as_bytes(), expected.stdout);
    assert_eq!(result.stderr.as_bytes(), expected.stderr);
}

#[tokio::test]
async fn indexed_array_empty_pending_items_still_charge_container_storage() {
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(256))
        .build();
    let script = format!("a=({})", "[0]='' ".repeat(64));
    assert_budget_exhausted(bash.exec(&script).await);
}

#[tokio::test]
async fn indexed_array_duplicate_subscripts_remain_valid_at_entry_limit() {
    let mut bash = Bash::builder()
        .memory_limits(bashkit::MemoryLimits::new().max_array_entries(1))
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(8_192))
        .build();
    let result = bash
        .exec(&format!(
            "v='{}'; a=([0]=$v [0]=$v [0]=$v); echo ${{#a[@]}} ${{#a[0]}}",
            "x".repeat(1_024)
        ))
        .await
        .unwrap();
    assert_eq!(result.stdout, "1 1024\n");
}

#[tokio::test]
async fn indexed_array_substitutions_release_consumed_output() {
    let mut bash = Bash::builder()
        .limits(ExecutionLimits::new().max_live_intermediate_bytes(7_168))
        .build();
    bash.exec(&format!("v='{}'", "x".repeat(1_024)))
        .await
        .unwrap();
    let result = bash
        .exec("a=([0]=$(printf %s \"$v\")$(printf %s \"$v\")$(printf %s \"$v\")); echo ${#a[0]}")
        .await
        .unwrap();
    assert_eq!(result.stdout, "3072\n");
}

#[tokio::test]
async fn tilde_expansion_quotes_do_not_resolve_large_directories() {
    let limits = ExecutionLimits::new().max_live_intermediate_bytes(512);
    let mut bash = Bash::builder().limits(limits).build();
    bash.exec(&format!("HOME='{}'", "d".repeat(1_024)))
        .await
        .unwrap();
    let literal = format!("a{}", ":~".repeat(24));
    let actual = bash
        .exec(&format!("x='{literal}'; printf '%s' \"$x\""))
        .await
        .unwrap();
    assert_eq!(actual.stdout, literal);
}

#[tokio::test]
async fn tilde_expansion_assignment_copy_boundary_and_release() {
    for (bytes, succeeds) in [(15, false), (16, true)] {
        let limits = ExecutionLimits::new().max_live_intermediate_bytes(bytes);
        let mut bash = Bash::builder().limits(limits).build();
        bash.exec("HOME=12345678").await.unwrap();
        let result = bash.exec("x=~; y=~").await;
        if succeeds {
            assert_eq!(result.unwrap().exit_code, 0);
            // Declaration leases release: a trivial follow-up still fits the
            // same budget (value assertions live in the semantics test,
            // which runs with a generous budget).
            assert_eq!(bash.exec("echo done").await.unwrap().stdout, "done\n");
        } else {
            assert_budget_exhausted(result);
        }
    }
}