sara-tasks 1.5.2

Sara — folder-aware task manager
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
use std::sync::Mutex;

use rmcp::ServerHandler;
use rusqlite::Connection;

use crate::commands;
use crate::infrastructure::config::Config;
use crate::infrastructure::db;
use crate::infrastructure::model::Task;

use super::server::{CwdGuard, SaraServer};

// cwd is process-global; serialize the tests that mutate it.
static CWD_LOCK: Mutex<()> = Mutex::new(());

fn server_with(conn: Connection) -> SaraServer {
    SaraServer::new(conn, Config::default())
}

fn seed_task(conn: &Connection, project: &str, desc: &str) {
    let mut t = Task::new(desc.to_string(), project.to_string());
    db::insert_task(conn, &mut t).expect("insert task");
}

#[test]
fn exposes_the_agent_loop_tools() {
    let names: Vec<String> = SaraServer::all_router()
        .list_all()
        .iter()
        .map(|t| t.name.to_string())
        .collect();
    assert_eq!(names.len(), 44, "expected 44 tools, got {names:?}");
    for expected in [
        // read
        "list",
        "info",
        "next",
        "steps",
        "verify",
        "recall",
        "feedback",
        "plan_show",
        "tags",
        "projects",
        // mutate (create / guide)
        "add",
        "step_done",
        "annotate",
        "plan_import",
        "check",
        "step_undone",
        "step_remove",
        "assignment",
        "rationale",
        "attach",
        "learn",
        "forget",
        "promote",
        "relearn",
        // completion / edit / lifecycle
        "done",
        "link",
        "unlink",
        "denotate",
        "dep",
        "validate",
        "modify",
        "resolve",
        "record_run",
        "start",
        "stop",
        "move_task",
        // memory maintenance
        "consolidate",
        "reflect",
        "diagnose_memories",
        "reindex_embeddings",
    ] {
        assert!(
            names.iter().any(|n| n == expected),
            "missing tool `{expected}` in {names:?}"
        );
    }
}

/// Folder awareness is the server's core contract: it is long-running and has no
/// per-call working directory, so EVERY tool must accept `project_path` to name
/// the target repo. A hand-written params struct that omits it compiles fine and
/// registers fine — it just silently operates on the launch dir forever.
#[test]
fn every_tool_accepts_project_path() {
    let missing: Vec<String> = SaraServer::all_router()
        .list_all()
        .iter()
        .filter(|t| {
            let props = t
                .input_schema
                .get("properties")
                .and_then(|v| v.as_object())
                .cloned()
                .unwrap_or_default();
            !props.contains_key("project_path")
        })
        .map(|t| t.name.to_string())
        .collect();

    assert!(
        missing.is_empty(),
        "these tools cannot be pointed at a project — add `project_path` to their \
         params struct: {missing:?}"
    );
}

#[test]
fn get_info_advertises_sara_tools_and_instructions() {
    let server = server_with(db::open_in_memory_for_test());
    let info = server.get_info();
    assert_eq!(info.server_info.name, "sara");
    assert!(
        info.capabilities.tools.is_some(),
        "tools capability missing"
    );
    assert!(
        info.instructions
            .as_deref()
            .unwrap_or_default()
            .contains("project_path"),
        "instructions should mention project_path"
    );
}

#[test]
fn cwd_guard_sets_and_restores_working_dir() {
    let _lock = CWD_LOCK.lock().unwrap();
    let start = std::env::current_dir().unwrap();
    let tmp = std::env::temp_dir().canonicalize().unwrap();
    {
        let _g = CwdGuard::enter(Some(tmp.to_str().unwrap())).unwrap();
        assert_eq!(
            std::env::current_dir().unwrap().canonicalize().unwrap(),
            tmp
        );
    }
    assert_eq!(std::env::current_dir().unwrap(), start, "cwd not restored");

    // None / empty leaves cwd untouched.
    {
        let _g = CwdGuard::enter(None).unwrap();
        assert_eq!(std::env::current_dir().unwrap(), start);
    }
}

#[test]
fn cwd_guard_rejects_a_relative_project_path() {
    // The server has no per-call cwd, so a relative path would resolve against
    // whatever the previous call left behind — a silent cross-project write.
    let _lock = CWD_LOCK.lock().unwrap();
    let start = std::env::current_dir().unwrap();
    for rel in ["..", ".", "some/sub/dir"] {
        let err = match CwdGuard::enter(Some(rel)) {
            Ok(_) => panic!("relative path {rel:?} must be rejected"),
            Err(e) => e,
        };
        assert!(
            err.to_string().contains("absolute"),
            "error should name the requirement, got: {err}"
        );
    }
    assert_eq!(
        std::env::current_dir().unwrap(),
        start,
        "cwd changed despite rejection"
    );
}

#[test]
fn cwd_guard_errors_on_missing_project_path() {
    let _lock = CWD_LOCK.lock().unwrap();
    let start = std::env::current_dir().unwrap();
    assert!(CwdGuard::enter(Some("/no/such/sara/dir/xyz")).is_err());
    assert_eq!(
        std::env::current_dir().unwrap(),
        start,
        "cwd changed on error"
    );
}

#[test]
fn with_project_runs_closure_against_the_connection() {
    let server = server_with(db::open_in_memory_for_test());
    seed_task_via(&server, "alpha", "first");
    seed_task_via(&server, "alpha", "second");

    // project_path=None avoids touching process cwd; filter by explicit project.
    let v = server
        .with_project(None, "test", |conn, cfg| {
            commands::list::list_value(conn, cfg, false, Some("alpha"))
        })
        .expect("with_project");
    let tasks = v["tasks"].as_array().expect("tasks array");
    assert_eq!(tasks.len(), 2);
}

fn seed_task_via(server: &SaraServer, project: &str, desc: &str) {
    server
        .with_project(None, "seed", |conn, _cfg| {
            seed_task(conn, project, desc);
            Ok(())
        })
        .expect("seed");
}

/// Seed a task and return its uuid string (for targeting mutate tools).
fn seed_returning(server: &SaraServer, project: &str, desc: &str) -> String {
    server
        .with_project(None, "seed", |conn, _cfg| {
            let mut t = Task::new(desc.to_string(), project.to_string());
            db::insert_task(conn, &mut t)?;
            Ok(t.uuid.to_string())
        })
        .expect("seed")
}

#[test]
fn done_value_marks_task_completed() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "finish me");
    let v = server
        .with_project(None, "done", |conn, cfg| {
            commands::done::done_value(conn, cfg, &uuid, false)
        })
        .expect("done");
    assert_eq!(v["status"], "completed");
    assert_eq!(v["recurrence"], serde_json::Value::Null);
}

#[test]
fn link_value_attaches_a_url() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let v = server
        .with_project(None, "link", |conn, _cfg| {
            commands::annotate::link_value(conn, &uuid, "https://example/pr/1", Some("PR"))
        })
        .expect("link");
    assert_eq!(v["url"], "https://example/pr/1");
}

#[test]
fn dep_on_then_list_reports_the_blocker() {
    let server = server_with(db::open_in_memory_for_test());
    let a = seed_returning(&server, "p", "dependent");
    let b = seed_returning(&server, "p", "blocker");
    server
        .with_project(None, "dep on", |conn, cfg| {
            commands::dep::dep_on_value(conn, cfg, &a, &b)
        })
        .expect("dep on");
    let v = server
        .with_project(None, "dep list", |conn, _cfg| {
            commands::dep::dep_list_value(conn, &a)
        })
        .expect("dep list");
    assert_eq!(v["blocked_by"].as_array().map(|a| a.len()), Some(1));
}

#[test]
fn check_value_adds_a_step() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let v = server
        .with_project(None, "check", |conn, _cfg| {
            commands::guide::check_value(conn, &uuid, "do the thing", None, None, None, None)
        })
        .expect("check");
    assert_eq!(v["kind"], db::STEP_KIND_STEP);
    let steps = server
        .with_project(None, "steps", |conn, _cfg| {
            commands::guide::steps_value(conn, &uuid, None)
        })
        .expect("steps");
    assert_eq!(steps["steps"].as_array().map(|a| a.len()), Some(1));
}

#[test]
fn verify_value_rejects_step_zero() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    server
        .with_project(None, "check", |conn, _cfg| {
            commands::guide::check_value(conn, &uuid, "step one", None, None, None, None)
        })
        .expect("check");
    // step is 1-based: 0 must error, not silently return step 1.
    let zero = server.with_project(None, "verify", |conn, _cfg| {
        commands::guide::verify_value(conn, &uuid, Some(0))
    });
    assert!(zero.is_err(), "verify_value(step=0) should error");
    // step 1 is valid.
    let one = server.with_project(None, "verify", |conn, _cfg| {
        commands::guide::verify_value(conn, &uuid, Some(1))
    });
    assert!(one.is_ok(), "verify_value(step=1) should succeed");
}

#[test]
fn modify_value_sets_priority_and_requires_a_field() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let v = server
        .with_project(None, "modify", |conn, cfg| {
            commands::modify::modify_value(
                conn,
                cfg,
                &uuid,
                None,
                Some("H"),
                None,
                false,
                &[],
                false,
                None,
                false,
                None,
                false,
            )
        })
        .expect("modify");
    assert_eq!(v["priority"], "H");

    // No field flags → must error, never open the TUI.
    let empty = server.with_project(None, "modify-empty", |conn, cfg| {
        commands::modify::modify_value(
            conn,
            cfg,
            &uuid,
            None,
            None,
            None,
            false,
            &[],
            false,
            None,
            false,
            None,
            false,
        )
    });
    assert!(empty.is_err(), "modify with no fields should error");
}

#[test]
fn step_undone_then_remove_edit_the_checklist() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    server
        .with_project(None, "check", |conn, _cfg| {
            commands::guide::check_value(conn, &uuid, "step one", None, None, None, None)
        })
        .expect("check");
    // done → undone flips it back to not-done.
    server
        .with_project(None, "done", |conn, _cfg| {
            commands::guide::step_done_value(conn, &uuid, 1, None, None)
        })
        .expect("step_done");
    let undone = server
        .with_project(None, "undone", |conn, _cfg| {
            commands::guide::step_undone_value(conn, &uuid, 1, None)
        })
        .expect("step_undone");
    assert_eq!(undone["done"], false);
    // remove drops the item.
    let removed = server
        .with_project(None, "remove", |conn, _cfg| {
            commands::guide::step_remove_value(conn, &uuid, 1, None)
        })
        .expect("step_remove");
    assert_eq!(removed["removed"], "step one");
    let steps = server
        .with_project(None, "steps", |conn, _cfg| {
            commands::guide::steps_value(conn, &uuid, None)
        })
        .expect("steps");
    assert_eq!(steps["steps"].as_array().map(|a| a.len()), Some(0));
}

#[test]
fn assignment_and_rationale_set_guide_text() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let a = server
        .with_project(None, "assignment", |conn, _cfg| {
            commands::guide::assignment_value(conn, &uuid, "build the thing")
        })
        .expect("assignment");
    assert_eq!(a["assignment"], "build the thing");
    let r = server
        .with_project(None, "rationale", |conn, _cfg| {
            commands::guide::rationale_value(conn, &uuid, "because reasons")
        })
        .expect("rationale");
    assert_eq!(r["rationale"], "because reasons");
}

#[test]
fn attach_value_records_a_file_and_an_anchor() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let file = server
        .with_project(None, "attach", |conn, _cfg| {
            commands::annotate::attach_value(conn, &uuid, "src/main.rs", None, None, None, None)
        })
        .expect("attach file");
    assert_eq!(file["kind"], "file");
    let anchor = server
        .with_project(None, "attach anchor", |conn, _cfg| {
            commands::annotate::attach_value(
                conn,
                &uuid,
                "src/lib.rs",
                Some("core logic"),
                None,
                Some("10:20"),
                None,
            )
        })
        .expect("attach anchor");
    assert_eq!(anchor["kind"], "anchor");
    assert_eq!(anchor["line_start"], 10);
    assert_eq!(anchor["line_end"], 20);
}

#[test]
fn attach_value_tags_a_url_as_link() {
    // PR #58 review: the URL branch delegates to link_value but must still carry a
    // `kind`, so every attach result shape is discriminable (file / anchor / link).
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let v = server
        .with_project(None, "attach url", |conn, _cfg| {
            commands::annotate::attach_value(
                conn,
                &uuid,
                "https://example.com/pr/1",
                None,
                None,
                None,
                None,
            )
        })
        .expect("attach url");
    assert_eq!(v["kind"], "link");
    assert_eq!(v["url"], "https://example.com/pr/1");
}

#[test]
fn start_then_stop_tracks_a_session() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let started = server
        .with_project(None, "start", |conn, cfg| {
            commands::timer::start_value(conn, cfg, &uuid)
        })
        .expect("start");
    assert_eq!(started["started"], true);
    let stopped = server
        .with_project(None, "stop", |conn, cfg| {
            commands::timer::stop_value(conn, cfg, &uuid)
        })
        .expect("stop");
    assert_eq!(stopped["stopped"], true);
    assert!(stopped["session_seconds"].as_i64().is_some());
}

#[test]
fn feedback_and_resolve_round_trip() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    // Seed an open feedback item via a human annotation flagged for revision.
    server
        .with_project(None, "annotate", |conn, _cfg| {
            commands::annotate::annotate_value(
                conn,
                &uuid,
                &["please fix".to_string()],
                None,
                Some("human"),
                None,
                true,
            )
        })
        .expect("annotate");
    let fb = server
        .with_project(None, "feedback", |conn, _cfg| {
            commands::guide::feedback_value(conn, &uuid)
        })
        .expect("feedback");
    let items = fb["open_feedback"].as_array().expect("open_feedback array");
    assert_eq!(items.len(), 1);
    let fb_id = items[0]["id"].as_i64().expect("feedback id");
    let resolved = server
        .with_project(None, "resolve", |conn, _cfg| {
            commands::guide::resolve_value(conn, fb_id, None)
        })
        .expect("resolve");
    assert_eq!(resolved["resolved"], true);
}

#[test]
fn record_run_then_resolve_links_the_run_id() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let run = server
        .with_project(None, "record_run", |conn, _cfg| {
            commands::guide::record_run_value(
                conn,
                &uuid,
                "enrich",
                Some("claude-sonnet-5-thinking-high"),
                Some("cursor"),
                None,
                None,
                None,
                None,
                None,
            )
        })
        .expect("record_run");
    let run_id = run["run_id"].as_i64().expect("run_id");

    server
        .with_project(None, "annotate", |conn, _cfg| {
            commands::annotate::annotate_value(
                conn,
                &uuid,
                &["please fix".to_string()],
                None,
                Some("human"),
                None,
                true,
            )
        })
        .expect("annotate");
    let fb = server
        .with_project(None, "feedback", |conn, _cfg| {
            commands::guide::feedback_value(conn, &uuid)
        })
        .expect("feedback");
    let fb_id = fb["open_feedback"][0]["id"].as_i64().expect("feedback id");

    server
        .with_project(None, "resolve", |conn, _cfg| {
            commands::guide::resolve_value(conn, fb_id, Some(run_id))
        })
        .expect("resolve");

    server
        .with_project(None, "check", |conn, _cfg| {
            let stored: i64 = conn.query_row(
                "SELECT resolved_by_run FROM annotations WHERE id=?1",
                [fb_id],
                |r| r.get(0),
            )?;
            Ok(serde_json::json!({ "resolved_by_run": stored }))
        })
        .map(|v| assert_eq!(v["resolved_by_run"].as_i64(), Some(run_id)))
        .expect("resolved_by_run should be persisted");
}

#[test]
fn plan_show_value_returns_a_briefing() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "solo task");
    let v = server
        .with_project(None, "plan_show", |conn, _cfg| {
            commands::plan::show_value(conn, &uuid)
        })
        .expect("plan_show");
    assert_eq!(v["briefing"].as_array().map(|a| a.len()), Some(1));
}

// ── Guide-tool ergonomics: tolerate the vocabulary the tools emit ────────────
// The MCP guide tools return {task, step_id, index} but historically required
// {id, n}. Agents faithfully round-trip the emitted names and hit
// "failed to deserialize parameters: missing field `id`". These tests pin the
// tolerant contract: aliases (task/task_id -> id, index -> n), string-or-number
// ids, step_id addressing, and check returning the new item's position.
use super::params::{CheckParams, StepDoneParams, StepEditParams};

#[test]
fn step_done_params_accept_task_and_index_aliases() {
    // A model round-tripping a step_done/step_undone response: {task, index}.
    let p: StepDoneParams = serde_json::from_value(serde_json::json!({ "task": 14, "index": 1 }))
        .expect("{task,index} must deserialize into StepDoneParams");
    assert_eq!(p.id, "14");
    assert_eq!(p.n, Some(1));
}

#[test]
fn step_done_params_accept_string_id_and_step_id() {
    // A model round-tripping a check response: {task, step_id}.
    let p: StepDoneParams =
        serde_json::from_value(serde_json::json!({ "task": "14", "step_id": 1614 }))
            .expect("{task,step_id} must deserialize into StepDoneParams");
    assert_eq!(p.id, "14");
    assert_eq!(p.step_id, Some(1614));
}

#[test]
fn step_edit_params_accept_index_and_step_id_aliases() {
    let by_index: StepEditParams =
        serde_json::from_value(serde_json::json!({ "task": 14, "index": 2 }))
            .expect("{task,index} must deserialize into StepEditParams");
    assert_eq!(by_index.id, "14");
    assert_eq!(by_index.n, Some(2));
    let by_step_id: StepEditParams =
        serde_json::from_value(serde_json::json!({ "id": "14", "step_id": 99 }))
            .expect("{id,step_id} must deserialize into StepEditParams");
    assert_eq!(by_step_id.step_id, Some(99));
}

#[test]
fn check_params_accept_task_alias_as_number() {
    let p: CheckParams =
        serde_json::from_value(serde_json::json!({ "task": 14, "text": "criterion" }))
            .expect("{task,text} must deserialize into CheckParams");
    assert_eq!(p.id, "14");
    assert_eq!(p.text, "criterion");
}

#[test]
fn check_value_returns_the_new_items_position() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    let first = server
        .with_project(None, "check", |conn, _cfg| {
            commands::guide::check_value(conn, &uuid, "a", None, None, None, None)
        })
        .expect("check");
    assert_eq!(first["index"].as_u64(), Some(1), "first step is position 1");
    let second = server
        .with_project(None, "check", |conn, _cfg| {
            commands::guide::check_value(conn, &uuid, "b", None, None, None, None)
        })
        .expect("check");
    assert_eq!(
        second["index"].as_u64(),
        Some(2),
        "second step is position 2"
    );
}

#[test]
fn step_done_by_step_id_ticks_the_right_item() {
    let server = server_with(db::open_in_memory_for_test());
    let uuid = seed_returning(&server, "p", "task");
    // Add two acceptance criteria; capture the second one's step_id.
    server
        .with_project(None, "check", |conn, _cfg| {
            commands::guide::check_value(conn, &uuid, "c1", None, Some("acceptance"), None, None)
        })
        .expect("check c1");
    let c2 = server
        .with_project(None, "check", |conn, _cfg| {
            commands::guide::check_value(conn, &uuid, "c2", None, Some("acceptance"), None, None)
        })
        .expect("check c2");
    let step_id = c2["step_id"].as_i64().expect("check returns step_id");
    // Tick by rowid (what the agent had in hand) — must land on criterion #2.
    let done = server
        .with_project(None, "done", |conn, _cfg| {
            commands::guide::step_done_by_id_value(conn, step_id, Some("proved"))
        })
        .expect("step_done_by_id");
    assert_eq!(done["kind"], db::STEP_KIND_ACCEPTANCE);
    assert_eq!(done["index"].as_u64(), Some(2));
    assert_eq!(done["done"], true);
}