dpc-tau-ext-shell 0.2.1

A minimal Unix-first coding agent.
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
use std::sync as path_std_sync;

use super::*;

fn args(limit: CborValue) -> CborValue {
    CborValue::Map(vec![
        (
            CborValue::Text("pattern".to_owned()),
            CborValue::Text("*".to_owned()),
        ),
        (CborValue::Text("limit".to_owned()), limit),
    ])
}

fn find_request(limit: usize) -> FindRequest {
    FindRequest {
        pattern: "*".to_owned(),
        path: PathBuf::from("."),
        limit,
        display_args: "fixture".to_owned(),
    }
}

fn map_text<'a>(result: &'a CborValue, field: &str) -> Option<&'a str> {
    let CborValue::Map(entries) = result else {
        return None;
    };
    entries.iter().find_map(|(key, value)| match (key, value) {
        (CborValue::Text(key), CborValue::Text(value)) if key == field => Some(value.as_str()),
        _ => None,
    })
}

fn map_int(result: &CborValue, field: &str) -> Option<i64> {
    let CborValue::Map(entries) = result else {
        return None;
    };
    entries.iter().find_map(|(key, value)| match (key, value) {
        (CborValue::Text(key), CborValue::Integer(value)) if key == field => {
            i128::from(*value).try_into().ok()
        }
        _ => None,
    })
}

fn map_bool(result: &CborValue, field: &str) -> Option<bool> {
    let CborValue::Map(entries) = result else {
        return None;
    };
    entries.iter().find_map(|(key, value)| match (key, value) {
        (CborValue::Text(key), CborValue::Bool(value)) if key == field => Some(*value),
        _ => None,
    })
}

fn fixed_width_paths(count: usize, suffix: &str) -> Vec<String> {
    (0..count)
        .map(|index| format!("{index:03}{suffix}"))
        .collect()
}

/// Ensures find rejects wrong-typed limits instead of silently using the
/// default result cap.
#[test]
fn find_rejects_wrong_type_limit() {
    let err = run_find(&args(CborValue::Text("10".to_owned())))
        .expect_err("string limit should be rejected");

    assert_eq!(err.message, "argument `limit` must be an integer");
}

/// Ensures find rejects wrong-typed paths instead of searching the default
/// directory.
#[test]
fn find_rejects_wrong_type_path() {
    let args = CborValue::Map(vec![
        (
            CborValue::Text("pattern".to_owned()),
            CborValue::Text("*".to_owned()),
        ),
        (
            CborValue::Text("path".to_owned()),
            CborValue::Integer(1.into()),
        ),
    ]);

    let err = run_find(&args).expect_err("integer path should be rejected");

    assert_eq!(err.message, "argument `path` must be a string");
}

/// Ensures find converts the decoded UTF-8 root once, preserving both the
/// current-directory default and the existing display text.
#[test]
fn find_parse_retains_typed_root_and_display() {
    let omitted = parse_find_request(&CborValue::Map(vec![(
        CborValue::Text("pattern".to_owned()),
        CborValue::Text("*.rs".to_owned()),
    )]))
    .expect("omitted path parses");
    assert_eq!(omitted.path, PathBuf::from("."));
    assert_eq!(omitted.display_args, "*.rs in .");

    let explicit_path = "./search-root/suffix";
    let explicit = parse_find_request(&CborValue::Map(vec![
        (
            CborValue::Text("pattern".to_owned()),
            CborValue::Text("*.rs".to_owned()),
        ),
        (
            CborValue::Text("path".to_owned()),
            CborValue::Text(explicit_path.to_owned()),
        ),
    ]))
    .expect("explicit path parses");
    assert_eq!(explicit.path, PathBuf::from(explicit_path));
    assert_eq!(explicit.display_args, "*.rs in ./search-root/suffix");
}

/// Ensures find rejects non-positive limits instead of coercing them to a
/// surprising positive default.
#[test]
fn find_rejects_non_positive_limit() {
    let err =
        run_find(&args(CborValue::Integer(0.into()))).expect_err("zero limit should be rejected");

    assert_eq!(err.message, "limit must be >= 1");
}

/// Ensures find reports only the requested number of matches while still
/// detecting the sentinel match needed to add the user-visible limit
/// notice.
#[test]
fn find_limit_bounds_collected_matches() {
    let tempdir = tempfile::TempDir::new().expect("tempdir");
    for name in ["alpha.txt", "beta.txt", "gamma.txt"] {
        std::fs::write(tempdir.path().join(name), "x").expect("write file");
    }
    let args = CborValue::Map(vec![
        (
            CborValue::Text("pattern".to_owned()),
            CborValue::Text("*.txt".to_owned()),
        ),
        (
            CborValue::Text("path".to_owned()),
            CborValue::Text(tempdir.path().display().to_string()),
        ),
        (
            CborValue::Text("limit".to_owned()),
            CborValue::Integer(1.into()),
        ),
    ]);

    let result = run_find(&args).expect("find").result;
    let CborValue::Map(entries) = &result else {
        panic!("expected result map");
    };
    let output = entries
        .iter()
        .find_map(|(key, value)| match (key, value) {
            (CborValue::Text(key), CborValue::Text(value)) if key == "output" => Some(value),
            _ => None,
        })
        .expect("output");
    let matches: i64 = entries
        .iter()
        .find_map(|(key, value)| match (key, value) {
            (CborValue::Text(key), CborValue::Integer(value)) if key == "matches" => {
                i128::from(*value).try_into().ok()
            }
            _ => None,
        })
        .expect("matches");
    let limit_reached = entries.iter().any(|(key, value)| {
        matches!(
            (key, value),
            (CborValue::Text(key), CborValue::Bool(true)) if key == "limit_reached"
        )
    });

    assert_eq!(
        output.lines().take_while(|line| !line.is_empty()).count(),
        1
    );
    assert_eq!(matches, 1);
    assert!(limit_reached);
    assert!(output.contains("1 results limit reached"));
    assert_eq!(map_bool(&result, "truncated"), None);
    assert_eq!(map_text(&result, "full_output_path"), None);
    assert_eq!(map_bool(&result, "saved_output_unavailable"), None);
}

/// Ensures large caller limits cannot force collection far beyond the
/// documented display cap before final output truncation.
#[test]
fn find_rejects_limit_above_output_cap() {
    let err = run_find(&args(CborValue::Integer(
        (MAX_FIND_LIMIT as i64 + 1).into(),
    )))
    .expect_err("limit over cap");

    assert_eq!(err.message, format!("limit must be <= {MAX_FIND_LIMIT}"));
}

/// Ensures max-limit notices do not suggest limits that argument parsing
/// rejects.
#[test]
fn find_max_limit_notice_asks_to_refine() {
    let notice = limit_reached_notice(MAX_FIND_LIMIT);

    assert!(notice.contains("Maximum limit reached"));
    assert!(!notice.contains(&format!("limit={}", MAX_FIND_LIMIT * 2)));
}

/// Ensures find observes cancellation before starting traversal through the
/// cancellable tool path.
#[test]
fn find_cancellable_stops_on_early_cancel_request() {
    let tempdir = tempfile::TempDir::new().expect("tempdir");
    std::fs::write(tempdir.path().join("alpha.txt"), "x").expect("write file");
    let args = CborValue::Map(vec![
        (
            CborValue::Text("pattern".to_owned()),
            CborValue::Text("*.txt".to_owned()),
        ),
        (
            CborValue::Text("path".to_owned()),
            CborValue::Text(tempdir.path().display().to_string()),
        ),
    ]);
    let (cancel_tx, cancel_rx) = path_std_sync::mpsc::channel();
    cancel_tx.send(()).expect("send cancel");

    let result = run_find_cancellable(&args, Some(&cancel_rx)).expect("find result");

    assert!(matches!(result, CancellableToolRun::Cancelled));
}

/// Ensures active find traversal checks cancellation between walked
/// entries, so a running search has a deterministic path to stop before
/// the whole tree has been visited.
#[test]
fn find_collect_stops_when_cancelled_during_traversal() {
    let tempdir = tempfile::TempDir::new().expect("tempdir");
    std::fs::write(tempdir.path().join("alpha.txt"), "x").expect("write alpha");
    std::fs::write(tempdir.path().join("beta.txt"), "x").expect("write beta");
    let request = FindRequest {
        pattern: "*.txt".to_owned(),
        path: tempdir.path().to_owned(),
        limit: DEFAULT_FIND_LIMIT,
        display_args: "test".to_owned(),
    };
    let search = prepare_find_search(&request).expect("search");
    let mut checks = 0usize;

    let result = collect_find_matches(&search, &mut || {
        checks += 1;
        1 < checks
    })
    .expect("find collection");

    assert!(result.is_none());
}

/// Protects find output from path line injection by escaping control
/// characters before rendering file names as one logical record per line.
#[test]
fn find_escapes_control_characters_in_paths() {
    let tempdir = tempfile::TempDir::new().expect("tempdir");
    std::fs::write(tempdir.path().join("line\nbreak.txt"), "x").expect("write file");
    let args = CborValue::Map(vec![
        (
            CborValue::Text("pattern".to_owned()),
            CborValue::Text("*.txt".to_owned()),
        ),
        (
            CborValue::Text("path".to_owned()),
            CborValue::Text(tempdir.path().display().to_string()),
        ),
    ]);

    let result = run_find(&args).expect("find").result;
    let CborValue::Map(entries) = result else {
        panic!("expected result map");
    };
    let output = entries
        .iter()
        .find_map(|(key, value)| match (key, value) {
            (CborValue::Text(key), CborValue::Text(value)) if key == "output" => Some(value),
            _ => None,
        })
        .expect("output");

    assert_eq!(output, "line\\nbreak.txt");
}
/// Ensures a result-limit notice that causes the visible budget overflow
/// rerenders whole records, reports exact native totals, and saves the original
/// selected records rather than a notice or sentinel.
#[test]
fn find_notice_overflow_preserves_whole_records_and_exact_artifact() {
    let matches = fixed_width_paths(101, &"x".repeat(98));
    let selected = matches[..100].to_vec();
    let full_output = selected.join("\n");
    assert_eq!(full_output.len(), 10_199);

    let rendered = render_find_output(find_request(100), matches).result;
    let output = map_text(&rendered, "output").expect("output");
    let visible_records = output
        .split_once("\n\n[")
        .expect("notices")
        .0
        .lines()
        .collect::<Vec<_>>();

    assert!(output.len() <= MAX_OUTPUT_BYTES);
    assert!(output.contains("100 results limit reached"));
    assert!(output.contains("10 KiB/2000 line visible output limit reached."));
    assert!(visible_records.iter().all(|record| {
        *record == "(truncated)" || selected.iter().any(|selected| selected == record)
    }));
    assert_eq!(map_int(&rendered, "matches"), Some(100));
    assert_eq!(map_bool(&rendered, "limit_reached"), Some(true));
    assert_eq!(map_bool(&rendered, "truncated"), Some(true));
    assert_eq!(map_int(&rendered, "total_lines"), Some(100));
    assert_eq!(map_int(&rendered, "total_bytes"), Some(10_199));

    if let Some(path) = map_text(&rendered, "full_output_path") {
        assert_eq!(
            std::fs::read_to_string(path).expect("saved find output"),
            full_output
        );
    } else {
        assert_eq!(map_bool(&rendered, "saved_output_unavailable"), Some(true));
    }
}

/// Ensures the same 10,199-byte selected records remain unchanged when no
/// sentinel requires a result-limit notice.
#[test]
fn find_native_output_at_notice_boundary_fits_without_sentinel() {
    let matches = fixed_width_paths(100, &"x".repeat(98));
    let expected = matches.join("\n");

    let rendered = render_find_output(find_request(100), matches).result;

    assert_eq!(map_text(&rendered, "output"), Some(expected.as_str()));
    assert_eq!(map_bool(&rendered, "limit_reached"), None);
    assert_eq!(map_bool(&rendered, "truncated"), None);
    assert_eq!(map_text(&rendered, "full_output_path"), None);
}

/// Ensures records that already exceed the native cap are rerendered from the
/// originals after both notices are known, with honest recovery metadata.
#[test]
fn find_preexisting_overflow_preserves_native_recovery_output() {
    let matches = fixed_width_paths(101, &"x".repeat(118));
    let expected = matches[..100].join("\n");
    assert!(MAX_OUTPUT_BYTES < expected.len());

    let rendered = render_find_output(find_request(100), matches).result;
    let output = map_text(&rendered, "output").expect("output");

    assert!(output.len() <= MAX_OUTPUT_BYTES);
    assert!(output.contains("100 results limit reached"));
    assert!(output.contains("10 KiB/2000 line visible output limit reached."));
    assert_eq!(map_bool(&rendered, "truncated"), Some(true));
    assert_eq!(
        map_int(&rendered, "total_bytes"),
        Some(expected.len() as i64)
    );
    if let Some(path) = map_text(&rendered, "full_output_path") {
        assert_eq!(
            std::fs::read_to_string(path).expect("saved find output"),
            expected
        );
    } else {
        assert_eq!(map_bool(&rendered, "saved_output_unavailable"), Some(true));
    }
}

/// Ensures notice budgeting never cuts a multibyte pathname at a UTF-8
/// boundary or fabricates a partial logical record.
#[test]
fn find_notice_overflow_preserves_multibyte_record_boundaries() {
    let matches = fixed_width_paths(101, &"é".repeat(49));
    let selected = matches[..100].to_vec();
    assert_eq!(selected.join("\n").len(), 10_199);

    let rendered = render_find_output(find_request(100), matches).result;
    let output = map_text(&rendered, "output").expect("output");
    let visible_records = output
        .split_once("\n\n[")
        .expect("notices")
        .0
        .lines()
        .collect::<Vec<_>>();

    assert!(output.len() <= MAX_OUTPUT_BYTES);
    assert!(visible_records.iter().all(|record| {
        *record == "(truncated)" || selected.iter().any(|selected| selected == record)
    }));
    assert_eq!(map_bool(&rendered, "truncated"), Some(true));
}