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
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
use super::{SessionDefaults, load_session};
use crate::{Cli, GlobalOptions};
use saya_store::{FsSessionStore, RedactedMessage, RedactedSession, SessionStore};

fn cli() -> Cli {
    Cli {
        options: GlobalOptions {
            continue_session: true,
            ..Default::default()
        },
        command: None,
    }
}

#[test]
fn v1_session_uses_current_runtime_defaults() {
    let root = std::env::temp_dir().join(format!("saya-v1-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    super::block_on(store.save(RedactedSession {
        version: 1,
        id: "legacy".into(),
        profile_names: vec!["analytics".into()],
        messages: vec![],
        ..Default::default()
    }))
    .unwrap();
    let state = load_session(
        &store,
        &cli(),
        &SessionDefaults {
            provider: "openai_compatible".into(),
            model: "current-model".into(),
            allow_data_sharing: true,
            approval_mode: "read-only".into(),
        },
    )
    .unwrap();
    assert_eq!(state.provider, "openai_compatible");
    assert_eq!(state.model, "current-model");
    assert!(state.allow_data_sharing);
    assert_eq!(state.approval_mode, "read-only");
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn raw_legacy_json_without_version_uses_current_privacy_defaults() {
    let root = std::env::temp_dir().join(format!("saya-raw-v1-{}", std::process::id()));
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("raw.json"),
        r#"{"id":"raw","profile_names":[],"messages":[]}"#,
    )
    .unwrap();
    let state = load_session(
        &FsSessionStore::new(&root),
        &cli(),
        &SessionDefaults {
            provider: "openai".into(),
            model: "runtime-model".into(),
            allow_data_sharing: true,
            approval_mode: "read-only".into(),
        },
    )
    .unwrap();
    assert_eq!(state.provider, "openai");
    assert_eq!(state.model, "runtime-model");
    assert!(state.allow_data_sharing);
    assert_eq!(state.approval_mode, "read-only");
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn v2_session_restores_persisted_settings() {
    let root = std::env::temp_dir().join(format!("saya-v2-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    super::block_on(store.save(RedactedSession {
        version: saya_store::SESSION_VERSION,
        id: "saved".into(),
        provider: "ollama".into(),
        model: "saved-model".into(),
        allow_data_sharing: false,
        approval_mode: "never".into(),
        ..Default::default()
    }))
    .unwrap();
    let state = load_session(
        &store,
        &cli(),
        &SessionDefaults {
            provider: "openai".into(),
            model: "current-model".into(),
            allow_data_sharing: true,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert_eq!(state.provider, "ollama");
    assert_eq!(state.model, "saved-model");
    assert!(!state.allow_data_sharing);
    assert_eq!(state.approval_mode, "never");
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn legacy_messages_migrate_to_one_safe_turn() {
    let root = std::env::temp_dir().join(format!("saya-migrate-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    super::block_on(store.save(RedactedSession {
        version: 1,
        id: "legacy-messages".into(),
        messages: vec![
            RedactedMessage {
                role: "system".into(),
                content: "old command".into(),
            },
            RedactedMessage {
                role: "user".into(),
                content: "question".into(),
            },
            RedactedMessage {
                role: "assistant".into(),
                content: "answer".into(),
            },
        ],
        ..Default::default()
    }))
    .unwrap();
    let state = load_session(
        &store,
        &cli(),
        &SessionDefaults {
            provider: "ollama".into(),
            model: "model".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert_eq!(state.turns.len(), 1);
    assert_eq!(state.provider_history().len(), 2);
    std::fs::remove_dir_all(root).unwrap();
}

/// M0-2: persist with `read-only`, resume with an explicit
/// `--approval-mode never` — the flag must override the persisted mode
/// instead of being silently ignored.
#[test]
fn resume_honors_an_explicit_approval_mode_override() {
    let root = std::env::temp_dir().join(format!("saya-resume-override-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    super::block_on(store.save(RedactedSession {
        version: saya_store::SESSION_VERSION,
        id: "override".into(),
        approval_mode: "read-only".into(),
        ..Default::default()
    }))
    .unwrap();
    let cli = Cli {
        options: GlobalOptions {
            continue_session: true,
            approval_mode: Some("never".into()),
            ..Default::default()
        },
        command: None,
    };
    let mut state = load_session(
        &store,
        &cli,
        &SessionDefaults {
            provider: "openai".into(),
            model: "current-model".into(),
            allow_data_sharing: true,
            approval_mode: "never".into(),
        },
    )
    .unwrap();
    // Loading alone keeps resume continuity: the persisted mode stands...
    assert_eq!(state.approval_mode, "read-only");
    // ...and the loop's resume resolution lets the explicit flag win.
    state.approval_mode =
        super::super::session_loop::resume_approval_mode(&cli.options, &state.approval_mode)
            .unwrap();
    assert_eq!(state.approval_mode, "never");
    std::fs::remove_dir_all(root).unwrap();
}

/// M0-2: resume without the flag keeps the persisted mode (resume
/// continuity).
#[test]
fn resume_without_the_flag_keeps_the_persisted_mode() {
    let root = std::env::temp_dir().join(format!("saya-resume-keep-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    super::block_on(store.save(RedactedSession {
        version: saya_store::SESSION_VERSION,
        id: "keep".into(),
        approval_mode: "read-only".into(),
        ..Default::default()
    }))
    .unwrap();
    let cli = cli();
    let mut state = load_session(
        &store,
        &cli,
        &SessionDefaults {
            provider: "openai".into(),
            model: "current-model".into(),
            allow_data_sharing: true,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert_eq!(state.approval_mode, "read-only");
    // The resume resolution without the flag keeps the persisted mode.
    state.approval_mode =
        super::super::session_loop::resume_approval_mode(&cli.options, &state.approval_mode)
            .unwrap();
    assert_eq!(state.approval_mode, "read-only");
    std::fs::remove_dir_all(root).unwrap();
}

/// A Plan session survives the persist/resume round trip with its posture
/// and its status-line word intact: the user who set Plan is not silently
/// handed write tools on return.
#[test]
fn a_plan_session_resumes_as_plan_with_its_status_word() {
    use saya_agent::AgentMode;
    let root = std::env::temp_dir().join(format!("saya-mode-resume-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    let mut state = crate::SessionState::new("planned", None, "m");
    state.agent_mode = AgentMode::Plan.as_str().into();
    super::block_on(store.save(state.redacted())).unwrap();
    let resumed = load_session(
        &store,
        &cli(),
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert_eq!(resumed.agent_mode, "plan");
    assert_eq!(resumed.agent_mode_parsed(), AgentMode::Plan);
    assert!(
        super::super::session_prompt::status_line(&resumed).contains("mode:plan"),
        "the status line names the resumed posture"
    );
    std::fs::remove_dir_all(root).unwrap();
}

/// A session file written before the mode field existed resumes as Build
/// without error: the default is today's behaviour for every existing
/// session, not a silent read-only session the user never chose. The
/// fixture is raw JSON with no mode key, so deserialization — not struct
/// construction — proves the old record loads.
#[test]
fn a_session_file_without_the_mode_field_resumes_as_build() {
    use saya_agent::AgentMode;
    let root = std::env::temp_dir().join(format!("saya-mode-legacy-{}", std::process::id()));
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("old.json"),
        r#"{"version":2,"id":"old","profile_names":[],"turns":[],"messages":[]}"#,
    )
    .unwrap();
    let state = load_session(
        &FsSessionStore::new(&root),
        &cli(),
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert_eq!(state.agent_mode, "build");
    assert_eq!(state.agent_mode_parsed(), AgentMode::Build);
    assert!(
        super::super::session_prompt::status_line(&state).contains("mode:build"),
        "the old session reads exactly as before"
    );
    std::fs::remove_dir_all(root).unwrap();
}

/// A resumed Plan session starts with an empty grant store: the mode rides
/// the record, and grants still die with the process — the persisted plan
/// posture never re-grants anything.
#[test]
fn a_resumed_plan_session_starts_with_an_empty_grant_store() {
    let state = super::state_from_redacted(
        RedactedSession {
            version: saya_store::SESSION_VERSION,
            id: "planned-grants".into(),
            agent_mode: "plan".into(),
            ..Default::default()
        },
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    );
    assert_eq!(state.agent_mode, "plan");
    let policy = saya_agent::SessionPolicy::new(saya_agent::ApprovalPolicy::Ask);
    assert!(
        policy.grants().is_empty(),
        "a resumed session builds its policy empty, from the mode alone"
    );
}

/// The additive-field rule for session files: a new persisted field stays
/// `#[serde(default)]` at `SESSION_VERSION` 2 — absence deserializes to the
/// old behaviour — so a pre-slice record resumes without error and without
/// the version-skew fallback rewriting its live fields.
#[test]
fn the_mode_is_an_additive_field_at_the_current_session_version() {
    assert_eq!(saya_store::SESSION_VERSION, 2);
    let record: RedactedSession = serde_json::from_str(
        r#"{"version":2,"id":"old","profile_names":[],"turns":[],"messages":[]}"#,
    )
    .expect("a record without the mode field deserializes");
    assert!(
        record.agent_mode.is_empty(),
        "a pre-slice record carries no mode"
    );
}

/// A task list survives the persist/resume round trip identical: the list
/// rides the record the way the mode does, and the resume restores it behind
/// the list's own `validate()` gate.
#[test]
fn a_task_list_round_trips_through_persist_and_resume() {
    use saya_types::{SessionTask, SessionTaskList, TaskStatus};
    let root = std::env::temp_dir().join(format!("saya-tasks-resume-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    let mut state = crate::SessionState::new("tasked", None, "m");
    state.task_list = SessionTaskList::new(vec![
        SessionTask::with_note(
            "profile the tables",
            TaskStatus::InProgress,
            Some("halfway"),
        )
        .unwrap(),
        SessionTask::new("write the report", TaskStatus::Pending).unwrap(),
    ])
    .unwrap();
    super::block_on(store.save(state.redacted())).unwrap();
    let resumed = load_session(
        &store,
        &cli(),
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert_eq!(resumed.task_list, state.task_list);
    std::fs::remove_dir_all(root).unwrap();
}

/// A session file written before the task-list field existed resumes with an
/// empty list: the field is `#[serde(default)]`, so absence deserializes to
/// the starting state. The fixture is raw JSON with no task-list key, so
/// deserialization — not struct construction — proves the old record loads.
#[test]
fn a_session_file_without_the_task_list_field_resumes_empty() {
    let root = std::env::temp_dir().join(format!("saya-tasks-legacy-{}", std::process::id()));
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("old.json"),
        r#"{"version":2,"id":"old","profile_names":[],"turns":[],"messages":[]}"#,
    )
    .unwrap();
    let state = load_session(
        &FsSessionStore::new(&root),
        &cli(),
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert!(
        state.task_list.is_empty(),
        "a pre-slice record resumes with an empty list"
    );
    std::fs::remove_dir_all(root).unwrap();
}

/// A record whose stored list fails `validate()` — hand-edited, or written
/// by an older buggy build — resumes empty rather than failing the session:
/// a corrupt todo list must never make a session unopenable. The fixture is
/// raw JSON with two tasks in progress, so deserialization proves the resume
/// path validates the stored list instead of trusting it.
#[test]
fn a_session_file_with_an_invalid_task_list_resumes_empty_without_error() {
    let root = std::env::temp_dir().join(format!("saya-tasks-invalid-{}", std::process::id()));
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("bad.json"),
        r#"{"version":2,"id":"bad","profile_names":[],"turns":[],"messages":[],"task_list":{"tasks":[{"title":"one","status":"in_progress"},{"title":"two","status":"in_progress"}]}}"#,
    )
    .unwrap();
    let state = load_session(
        &FsSessionStore::new(&root),
        &cli(),
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    )
    .expect("an invalid stored list must not fail the resume");
    assert!(
        state.task_list.is_empty(),
        "an invalid stored list resumes empty"
    );
    std::fs::remove_dir_all(root).unwrap();
}

/// The additive-field rule holds for the task list too: it stays
/// `#[serde(default)]` at `SESSION_VERSION` 2 — absence deserializes to the
/// empty list — so no version bump is owed, exactly the `agent_mode`
/// precedent.
#[test]
fn the_task_list_is_an_additive_field_at_the_current_session_version() {
    assert_eq!(saya_store::SESSION_VERSION, 2);
    let record: RedactedSession = serde_json::from_str(
        r#"{"version":2,"id":"old","profile_names":[],"turns":[],"messages":[]}"#,
    )
    .expect("a record without the task-list field deserializes");
    assert!(
        record.task_list.is_empty(),
        "a pre-slice record carries no tasks"
    );
}

/// An older session file written before the `arguments` and `result_shape`
/// fields existed still loads: the new fields are `#[serde(default)]`, so a
/// tool record carrying only `name` and `status` deserializes with empty
/// arguments and a `None` shape. Old and new session files interoperate.
#[test]
fn an_old_session_file_without_the_new_tool_fields_still_loads() {
    let root = std::env::temp_dir().join(format!("saya-old-tool-{}", std::process::id()));
    std::fs::create_dir_all(&root).unwrap();
    std::fs::write(
        root.join("old.json"),
        r#"{"version":2,"id":"old","profile_names":["analytics"],"turns":[{"user":"q","assistant":"a","database_derived":true,"tools":[{"name":"bounded_sql_query","status":"completed"}]}],"messages":[]}"#,
    )
    .unwrap();
    let state = load_session(
        &FsSessionStore::new(&root),
        &cli(),
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    let tool = &state.turns[0].tools[0];
    assert_eq!(tool.name, "bounded_sql_query");
    assert_eq!(tool.status, "completed");
    assert_eq!(tool.arguments, "", "missing arguments default to empty");
    assert!(
        tool.result_shape.is_none(),
        "missing result_shape defaults to None"
    );
    std::fs::remove_dir_all(root).unwrap();
}

/// The resume pin: a session whose record carries a workspace root re-opens
/// that root on resume, whatever directory the resume happens from — the
/// root follows the record, not the shell. A session written before the
/// workspace existed carries no root and resumes unbound, exactly its old
/// behaviour.
#[test]
fn the_recorded_workspace_root_rides_the_resume() {
    let root = std::env::temp_dir().join(format!("saya-ws-pin-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    super::block_on(store.save(RedactedSession {
        version: saya_store::SESSION_VERSION,
        id: "pinned".into(),
        workspace_root: Some("/projects/saya".into()),
        ..Default::default()
    }))
    .unwrap();
    let state = load_session(
        &store,
        &cli(),
        &SessionDefaults {
            provider: "openai".into(),
            model: "current-model".into(),
            allow_data_sharing: true,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert_eq!(
        state.workspace_root.as_deref(),
        Some("/projects/saya"),
        "the pin follows the record, not the resume cwd"
    );
    // A record written before the workspace existed: no root, unbound.
    super::block_on(store.save(RedactedSession {
        version: saya_store::SESSION_VERSION,
        id: "legacy".into(),
        ..Default::default()
    }))
    .unwrap();
    let legacy = Cli {
        options: GlobalOptions {
            resume: Some("legacy".into()),
            ..Default::default()
        },
        command: None,
    };
    let old = load_session(
        &store,
        &legacy,
        &SessionDefaults {
            provider: "openai".into(),
            model: "current-model".into(),
            allow_data_sharing: true,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert!(
        old.workspace_root.is_none(),
        "no record, no pin: the old session resumes unbound"
    );
    let _ = std::fs::remove_dir_all(root);
}

/// A saved bypass session carries the mode across the resume — the persisted
/// record is the durable activation fact — and the resume path re-prints the
/// activation line for it, so a user returning to the session reads the
/// mode's own words again rather than a bare `approval:bypass` on the bar.
#[test]
fn a_resumed_session_carries_bypass_and_reprints_the_line() {
    let root = std::env::temp_dir().join(format!("saya-bypass-resume-{}", std::process::id()));
    let store = FsSessionStore::new(&root);
    super::block_on(store.save(RedactedSession {
        version: saya_store::SESSION_VERSION,
        id: "bypassed".into(),
        approval_mode: "bypass".into(),
        ..Default::default()
    }))
    .unwrap();
    let state = load_session(
        &store,
        &cli(),
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    )
    .unwrap();
    assert_eq!(state.approval_mode, "bypass", "the record carries the mode");
    // Resume continuity keeps it when no explicit flag overrides, and the
    // activation line fires for exactly this mode.
    let kept =
        super::super::session_loop::resume_approval_mode(&GlobalOptions::default(), "bypass")
            .unwrap();
    assert_eq!(kept, "bypass");
    assert!(
        crate::interactive::session_activation::is_bypass_mode(&state),
        "the resumed session is a bypass session"
    );
    let line = crate::interactive::session_activation::bypass_line(
        &["python3".to_owned()],
        false,
        false,
        &[],
    );
    assert!(
        line.contains("bypass on:") && line.contains("python3"),
        "the line the resume path re-prints is the activation line: {line}"
    );
    std::fs::remove_dir_all(root).unwrap();
}

/// The version-skew direction (DESIGN §7.5): a mode string no binary can
/// parse falls back to `ask` at every parse site — the safe direction — and
/// never into bypass. The parse sites are `unwrap_or(ApprovalPolicy::Ask)`;
/// this pins the fallback's value and the refusal of unknown words, so a
/// typo or a newer mode name degrades to asking, never to running.
#[test]
fn an_unparseable_mode_falls_back_to_ask_never_into_bypass() {
    use saya_agent::ApprovalPolicy;
    assert_eq!(
        ApprovalPolicy::default(),
        ApprovalPolicy::Ask,
        "the mode type's default is the safe direction"
    );
    for unknown in ["bogus", "", "bypass ", "BYPASS", "auto"] {
        assert!(
            unknown.parse::<ApprovalPolicy>().is_err(),
            "`{unknown}` is not a mode: the parse refuses it"
        );
        assert_eq!(
            unknown
                .parse::<ApprovalPolicy>()
                .unwrap_or(ApprovalPolicy::Ask),
            ApprovalPolicy::Ask,
            "the parse sites' fallback is ask, never bypass"
        );
    }
    // A persisted unparseable mode is carried verbatim (resume continuity)
    // and degrades to ask at the parse sites — the state itself never
    // invents a mode.
    let state = super::state_from_redacted(
        RedactedSession {
            version: saya_store::SESSION_VERSION,
            id: "skew".into(),
            approval_mode: "bogus".into(),
            ..Default::default()
        },
        &SessionDefaults {
            provider: "ollama".into(),
            model: "m".into(),
            allow_data_sharing: false,
            approval_mode: "ask".into(),
        },
    );
    assert_eq!(state.approval_mode, "bogus");
    assert!(
        !crate::interactive::session_activation::is_bypass_mode(&state),
        "an unparseable mode is never bypass"
    );
}