saya-cli 0.4.1

Database-aware AI agent for the terminal: full-screen TUI, schema discovery, and bounded read-only SQL over PostgreSQL, MySQL, SQLite, DuckDB, and Snowflake.
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
//! Tests for the `workspace_edit` tool's `append` variant: offset-checked
//! chunked writes over the same atomic commit the `replace` variant uses.
//! Append is a range replace — an empty range at EOF with a positional
//! precondition — so every refusal here leaves the file byte-identical, and
//! every mismatch reports the current size the model resumes from.

use std::{fs, path::PathBuf, sync::Arc};

use super::*;
use saya_agent::ToolExecutor;
use saya_harness::workspace::Workspace;

use super::database_tools::WORKSPACE_EDIT_MAX_BYTES;

/// A sandbox workspace under the OS temp dir, removed on drop. The root sits
/// one level down (`outer/ws`) so a `..` escape has a real target to name.
struct Sandbox {
    outer: PathBuf,
    ws: Workspace,
}

impl Sandbox {
    fn new(label: &str) -> Self {
        let outer =
            std::env::temp_dir().join(format!("saya-wsappend-{label}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&outer);
        fs::create_dir_all(outer.join("ws")).expect("sandbox directory must create");
        let ws = Workspace::open(&outer.join("ws")).expect("workspace root must open");
        Self { outer, ws }
    }

    fn ws_root(&self) -> PathBuf {
        self.outer.join("ws")
    }

    /// Database tools with the sandbox workspace attached and no connections —
    /// a workspace-only run has no selected profile.
    fn tools(&self) -> DatabaseTools {
        DatabaseTools::with_registry(
            crate::connection::ConnectionRegistry::new("primary"),
            100,
            true,
            None,
        )
        .with_workspace(Some(Arc::new(self.ws.clone())))
    }
}

impl Drop for Sandbox {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.outer);
    }
}

/// An offset mismatch refuses, writes nothing, and reports the current size —
/// that read-back is what lets the model resume from the right place rather
/// than guess.
#[tokio::test]
async fn an_offset_mismatch_writes_nothing_and_reports_the_size() {
    let sandbox = Sandbox::new("offset-mismatch");
    sandbox
        .ws
        .write("log.txt", b"chunk-one;")
        .expect("seed write must succeed");
    let before = fs::read(sandbox.ws_root().join("log.txt")).expect("seed file must exist");
    let tools = sandbox.tools();
    let error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "log.txt",
                "offset": 3,
                "chunk": "chunk-two;",
            }),
        )
        .await
        .expect_err("a stale offset must refuse, not append");
    let text = error.to_string();
    assert!(
        text.contains("10"),
        "the refusal must report the current size so the model can resume, got: {text}"
    );
    assert!(
        text.contains("digest:") || text.contains("digest"),
        "the refusal must carry the current digest for the resume precondition, got: {text}"
    );
    assert_eq!(
        fs::read(sandbox.ws_root().join("log.txt")).expect("file must survive"),
        before,
        "a refused append leaves the file byte-identical"
    );
}

/// Q1: a matching offset with a contradictory `expected_size` refuses and
/// writes nothing. The schema promises the size guard, so the append arm
/// must honour it like the replace arm does — not silently ignore it.
#[tokio::test]
async fn an_expected_size_mismatch_refuses_an_append_without_writing() {
    let sandbox = Sandbox::new("expected-size");
    sandbox
        .ws
        .write("log.txt", b"chunk-one;")
        .expect("seed write must succeed");
    let before = fs::read(sandbox.ws_root().join("log.txt")).expect("seed file must exist");
    let tools = sandbox.tools();
    let error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "log.txt",
                "offset": 10,
                "chunk": "chunk-two;",
                "expected_size": 3,
            }),
        )
        .await
        .expect_err("a contradictory expected_size must refuse, not append");
    let saya_agent::ToolError::WorkspaceEditMoved { current_size, .. } = error else {
        panic!("a contradictory expected_size must refuse with the moved error, got: {error}");
    };
    assert_eq!(current_size, 10);
    assert_eq!(
        fs::read(sandbox.ws_root().join("log.txt")).expect("file must survive"),
        before,
        "a refused append leaves the file byte-identical"
    );
}

/// Several chunks reassemble byte-exact: the same content written in one go
/// and written chunk by chunk (each at the size the previous chunk left)
/// land identical, and each result carries `{ path, size, digest }` for the
/// caller to verify what landed.
#[tokio::test]
async fn a_chunked_write_reassembles_byte_exact() {
    let sandbox = Sandbox::new("chunked");
    let tools = sandbox.tools();
    let whole = "alpha;beta;gamma;delta;";
    // One-go baseline.
    let one_go = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "one-go.txt",
                "offset": 0,
                "chunk": whole,
            }),
        )
        .await
        .expect("offset 0 on an absent path creates the file");
    // Chunked: each chunk names the size the previous chunk left.
    let mut offset = 0u64;
    for chunk in ["alpha;", "beta;", "gamma;", "delta;"] {
        let result = tools
            .execute(
                "workspace_edit",
                serde_json::json!({
                    "path": "chunked.txt",
                    "offset": offset,
                    "chunk": chunk,
                }),
            )
            .await
            .unwrap_or_else(|error| {
                panic!("chunk {chunk:?} at offset {offset} must land: {error}")
            });
        assert_eq!(result["path"], "chunked.txt");
        offset = result["size"]
            .as_u64()
            .expect("the result carries the new size");
        assert!(
            result["digest"]
                .as_str()
                .is_some_and(|digest| digest.len() == 64),
            "the result carries the digest of what landed"
        );
    }
    assert_eq!(
        fs::read(sandbox.ws_root().join("chunked.txt")).expect("file must exist"),
        fs::read(sandbox.ws_root().join("one-go.txt")).expect("baseline must exist"),
        "chunked writes reassemble byte-exact against the one-go write"
    );
    assert_eq!(one_go["size"], offset, "both land the same size");
    assert_eq!(
        one_go["digest"],
        tools
            .execute(
                "workspace_edit",
                serde_json::json!({
                    "path": "chunked.txt",
                    "offset": offset,
                    "chunk": "",
                }),
            )
            .await
            .expect("an empty final chunk at EOF must land")["digest"],
        "identical bytes hash identical"
    );
}

/// A truncated tool-call argument never parses, so nothing lands. This pins
/// the claim through the append path: a `chunk` cut mid-JSON (an unterminated
/// string, the shape a capped streaming assembler hands over) fails argument
/// parsing before validation runs, and the file is absent afterwards.
#[tokio::test]
async fn a_truncated_argument_lands_nothing() {
    let sandbox = Sandbox::new("truncated");
    let tools = sandbox.tools();
    // The wire's raw fragment never becomes a `Value`: the assembly that
    // turns streamed deltas into tool calls rejects it, exactly as the
    // providers do on a capped response.
    let raw = r#"{"path": "cut.txt", "offset": 0, "chunk": "abc"#;
    assert!(
        serde_json::from_str::<serde_json::Value>(raw).is_err(),
        "a truncated argument must not parse"
    );
    // And one step up: the executor's own validation rejects a non-object
    // before any filesystem contact.
    let error = tools
        .execute("workspace_edit", serde_json::json!("not-an-object"))
        .await
        .expect_err("a non-object argument must be rejected before any write");
    assert_eq!(error, saya_agent::ToolError::ArgumentsNotObject);
    assert!(
        !sandbox.ws_root().join("cut.txt").exists(),
        "a truncated argument lands nothing: the file is never created"
    );
}

/// Offset 0 on an absent path creates the file, and the result carries
/// `{ path, size, digest }` so the caller can verify what landed.
#[tokio::test]
async fn append_at_offset_zero_creates_the_file() {
    let sandbox = Sandbox::new("create");
    let tools = sandbox.tools();
    assert!(!sandbox.ws_root().join("fresh.txt").exists());
    let result = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "fresh.txt",
                "offset": 0,
                "chunk": "first bytes;",
            }),
        )
        .await
        .expect("offset 0 on an absent path must create");
    assert_eq!(result["path"], "fresh.txt");
    assert_eq!(result["size"], 12u64);
    assert!(
        result["digest"]
            .as_str()
            .is_some_and(|digest| digest.len() == 64),
        "the result carries the sha256 hex digest of what landed"
    );
    assert_eq!(
        fs::read(sandbox.ws_root().join("fresh.txt")).expect("file must exist"),
        b"first bytes;",
        "the created file holds exactly the chunk"
    );
}

/// The guard also applies when appending to an existing file: a chunk that
/// introduces the marker onto a file that had none is refused, and nothing
/// is appended.
#[tokio::test]
async fn append_to_an_existing_file_refuses_a_chunk_with_the_marker() {
    let sandbox = Sandbox::new("append-marker");
    let seed = b"line one;";
    sandbox
        .ws
        .write("log.txt", seed)
        .expect("seed write must succeed");
    let tools = sandbox.tools();
    tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "log.txt",
                "offset": seed.len() as u64,
                "chunk": " leaked: [redacted]",
            }),
        )
        .await
        .expect_err("an appended chunk holding the marker must be refused");
    assert_eq!(
        fs::read(sandbox.ws_root().join("log.txt")).expect("file must survive"),
        seed,
        "a refused append leaves the file byte-identical"
    );
}

/// The redaction-placeholder guard applies to append-creates-a-new-file the
/// same way it applies to `workspace_write`: a brand-new file starts at 0
/// markers, so a first chunk holding the literal marker is refused and no
/// file is created.
#[tokio::test]
async fn append_creating_a_new_file_with_the_marker_is_refused() {
    let sandbox = Sandbox::new("create-marker");
    let tools = sandbox.tools();
    tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "fresh.txt",
                "offset": 0,
                "chunk": "leaked: [redacted]",
            }),
        )
        .await
        .expect_err("a new file's first chunk holding the marker must be refused");
    assert!(
        !sandbox.ws_root().join("fresh.txt").exists(),
        "a refused append must leave no file behind"
    );
}

/// A chunk over the bound refuses whole — never truncated — and leaves no
/// partial append behind.
#[tokio::test]
async fn an_over_bound_chunk_refuses_whole() {
    let sandbox = Sandbox::new("over-bound");
    sandbox
        .ws
        .write("log.txt", b"seed;")
        .expect("seed write must succeed");
    let tools = sandbox.tools();
    let oversized = "a".repeat(WORKSPACE_EDIT_MAX_BYTES + 1);
    let error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "log.txt",
                "offset": 5,
                "chunk": oversized,
            }),
        )
        .await
        .expect_err("over the bound must be refused whole");
    match error {
        saya_agent::ToolError::WorkspaceEditTooLarge { limit, found, .. } => {
            assert_eq!(limit, WORKSPACE_EDIT_MAX_BYTES);
            assert_eq!(found, WORKSPACE_EDIT_MAX_BYTES + 1);
        }
        other => panic!("expected a typed over-bound refusal, got: {other}"),
    }
    assert_eq!(
        fs::read(sandbox.ws_root().join("log.txt")).expect("file must survive"),
        b"seed;",
        "a refused append leaves the file byte-identical"
    );
    // The boundary case: exactly the bound is a legal chunk.
    let exact = "a".repeat(WORKSPACE_EDIT_MAX_BYTES);
    let result = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "log.txt",
                "offset": 5,
                "chunk": exact,
            }),
        )
        .await
        .expect("a chunk exactly at the bound must be accepted");
    assert_eq!(result["path"], "log.txt");
    assert_eq!(result["size"], 5 + WORKSPACE_EDIT_MAX_BYTES as u64);
}

/// Append and replace share one write path, asserted structurally, not by
/// comment: a stale offset against a moved file refuses with the same typed
/// shape the replace half's precondition race produces — the harness's own
/// size check re-surfaced with the current size — because both commit
/// through `commit_splice`/`Workspace::patch_range`. A second write path
/// would refuse differently (or succeed); this pins that it cannot.
#[tokio::test]
async fn append_and_replace_share_one_write_path() {
    let sandbox = Sandbox::new("one-path");
    sandbox
        .ws
        .write("shared.txt", b"anchor here\n")
        .expect("seed write must succeed");
    let tools = sandbox.tools();
    // The append half's everyday mismatch: offset names a size the file no
    // longer has.
    let append_error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "shared.txt",
                "offset": 3,
                "chunk": "tail;",
            }),
        )
        .await
        .expect_err("a stale offset must refuse");
    let saya_agent::ToolError::WorkspaceAppendOffset {
        expected_offset,
        current_size,
        current_digest,
        ..
    } = append_error
    else {
        panic!("a stale offset must refuse with the typed offset error, got: {append_error}");
    };
    assert_eq!(expected_offset, 3);
    assert_eq!(current_size, 12);
    assert_eq!(current_digest.len(), 64);
    // The replace half's equivalent: a stale `expected_size` precondition.
    let replace_error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "shared.txt",
                "old_text": "anchor",
                "new_text": "ANCHOR",
                "expected_size": 3,
            }),
        )
        .await
        .expect_err("a stale precondition must refuse");
    let saya_agent::ToolError::WorkspaceEditMoved { current_size, .. } = replace_error else {
        panic!("a stale precondition must refuse with the moved error, got: {replace_error}");
    };
    assert_eq!(current_size, 12, "both halves report the same current size");
    // Both bounds are the same constant, by construction not coincidence:
    // the append half's chunk bound IS the replace half's bound.
    assert_eq!(
        WORKSPACE_EDIT_MAX_BYTES,
        super::database_tools::WORKSPACE_WRITE_MAX_BYTES,
        "one bound for every write-shaped byte the tool accepts"
    );
    assert_eq!(
        fs::read(sandbox.ws_root().join("shared.txt")).expect("file must survive"),
        b"anchor here\n",
        "both refusals leave the file byte-identical"
    );
}

/// The redaction contract holds for the append half: results and errors
/// carry sizes, offsets and digests — never file content. A secret-shaped
/// sentinel planted in the file must never appear in any payload.
#[tokio::test]
async fn an_append_error_payload_never_carries_file_content() {
    let sandbox = Sandbox::new("append-sentinel");
    let sentinel = "token=SENTINEL-9d2b4e-must-never-leak";
    let seed = format!("header line\n{sentinel}\nfooter line\n");
    sandbox
        .ws
        .write("notes.md", seed.as_bytes())
        .expect("seed write must succeed");
    let tools = sandbox.tools();
    let error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "notes.md",
                "offset": 1,
                "chunk": "tail;",
            }),
        )
        .await
        .expect_err("a stale offset must refuse");
    let text = error.to_string();
    assert!(
        !text.contains("SENTINEL-9d2b4e"),
        "an offset-mismatch refusal must not carry file content: {text}"
    );
    let result = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "notes.md",
                "offset": seed.len(),
                "chunk": "tail;",
            }),
        )
        .await
        .expect("the correct offset must append");
    let rendered = result.to_string();
    assert!(
        !rendered.contains("SENTINEL-9d2b4e"),
        "an append result must not carry file content: {rendered}"
    );
    assert!(
        !rendered.contains(&seed),
        "an append result carries size+digest, never the bytes: {rendered}"
    );
}

/// H1 reproduction (must fail before the fix): an existing but unreadable
/// file appended at offset 0 must refuse and leave the bytes byte-identical.
/// The probe must not classify a permission refusal as absence and take the
/// create branch.
#[cfg(unix)]
#[tokio::test]
async fn append_to_an_unreadable_file_refuses_and_preserves_bytes() {
    use std::os::unix::fs::PermissionsExt as _;
    let sandbox = Sandbox::new("h1-unreadable");
    let target = sandbox.ws_root().join("secret.txt");
    sandbox
        .ws
        .write("secret.txt", b"do-not-destroy;")
        .expect("seed write must succeed");
    let before = fs::read(&target).expect("seed file must exist");
    fs::set_permissions(&target, fs::Permissions::from_mode(0o000)).expect("chmod 000 must apply");
    let tools = sandbox.tools();
    let outcome = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "secret.txt",
                "offset": 0,
                "chunk": "attacker bytes;",
            }),
        )
        .await;
    fs::set_permissions(&target, fs::Permissions::from_mode(0o644))
        .expect("chmod restore must apply");
    assert!(
        outcome.is_err(),
        "appending at offset 0 to an existing but unreadable file must refuse, not create"
    );
    assert_eq!(
        fs::read(&target).expect("file must survive"),
        before,
        "a refused append leaves the file byte-identical"
    );
}

/// Mixed halves are a validation error, never a guess: `old_text` with
/// `chunk`, or half of one variant, is rejected before any filesystem
/// contact, and a mistyped `offset`/`chunk` names its own error.
#[tokio::test]
async fn append_rejects_mixed_and_mistyped_arguments() {
    let sandbox = Sandbox::new("append-mixed");
    sandbox
        .ws
        .write("notes.md", b"unchanged")
        .expect("seed write must succeed");
    let tools = sandbox.tools();
    let before = fs::read(sandbox.ws_root().join("notes.md")).expect("seed file must exist");
    let error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({
                "path": "notes.md",
                "old_text": "a",
                "new_text": "b",
                "offset": 0,
                "chunk": "c",
            }),
        )
        .await
        .expect_err("mixed halves must be rejected at validation");
    assert_eq!(error, saya_agent::ToolError::UnsupportedProperty);
    let error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({"path": "notes.md", "offset": 0}),
        )
        .await
        .expect_err("half an append must be rejected at validation");
    assert_eq!(error, saya_agent::ToolError::ChunkNotString);
    let error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({"path": "notes.md", "offset": "zero", "chunk": "c"}),
        )
        .await
        .expect_err("a non-integer offset must be rejected at validation");
    assert_eq!(error, saya_agent::ToolError::OffsetNotUint);
    let error = tools
        .execute(
            "workspace_edit",
            serde_json::json!({"path": "notes.md", "offset": 0, "chunk": 7}),
        )
        .await
        .expect_err("a non-string chunk must be rejected at validation");
    assert_eq!(error, saya_agent::ToolError::ChunkNotString);
    assert_eq!(
        fs::read(sandbox.ws_root().join("notes.md")).expect("file must survive"),
        before,
        "missing and mixed variants are rejected before mutation"
    );
}