sara-tasks 0.8.0

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
use anyhow::Result;
use rusqlite::Connection;
use serde_json::json;

use crate::infrastructure::config::Config;
use crate::infrastructure::db;

/// Resolve the git HEAD for the task's project, if it lives in a repo.
fn project_head(conn: &Connection, project: &str) -> Option<String> {
    let proj = db::get_project(conn, project).ok().flatten()?;
    let path = proj.path?;
    crate::infrastructure::git::head_commit(std::path::Path::new(&path))
}

fn kind_arg(kind: Option<&str>) -> &str {
    match kind {
        Some("acceptance") => db::STEP_KIND_ACCEPTANCE,
        _ => db::STEP_KIND_STEP,
    }
}

/// Structured form of the execution cursor (first not-done step). Shared by the
/// `--json` CLI path and the MCP `next` tool so there is a single serializer.
pub fn next_value(conn: &Connection, id: &str) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let steps = db::get_steps(conn, &task.uuid, db::STEP_KIND_STEP)?;
    let next = steps.iter().enumerate().find(|(_, s)| !s.done);
    Ok(match next {
        Some((i, s)) => json!({
            "task": task.id,
            "index": i + 1,
            "total": steps.len(),
            "text": s.text,
            "intent": s.intent,
            "verify_cmd": s.verify_cmd,
            "source": s.source,
        }),
        None => json!({ "task": task.id, "done": true, "total": steps.len() }),
    })
}

/// `sara next` — the execution cursor: first not-done step.
pub fn next(conn: &Connection, _cfg: &Config, id: &str, as_json: bool) -> Result<()> {
    if as_json {
        println!("{}", serde_json::to_string_pretty(&next_value(conn, id)?)?);
        return Ok(());
    }

    let task = db::resolve_task(conn, id)?;
    let steps = db::get_steps(conn, &task.uuid, db::STEP_KIND_STEP)?;
    let next = steps.iter().enumerate().find(|(_, s)| !s.done);

    match next {
        Some((i, s)) => {
            println!("Next step {}/{}: {}", i + 1, steps.len(), s.text);
            if let Some(intent) = &s.intent {
                println!("  intent: {intent}");
            }
            if let Some(v) = &s.verify_cmd {
                println!("  verify: {v}");
            }
        }
        None if steps.is_empty() => println!("No steps defined for task {}.", task.id.unwrap_or(0)),
        None => println!("All steps complete for task {}.", task.id.unwrap_or(0)),
    }
    Ok(())
}

/// Structured form of the ordered steps. Shared by the `--json` CLI path and the
/// MCP `steps` tool.
pub fn steps_value(conn: &Connection, id: &str, until: Option<usize>) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let mut steps = db::get_steps(conn, &task.uuid, db::STEP_KIND_STEP)?;
    if let Some(n) = until {
        steps.truncate(n);
    }
    let arr: Vec<_> = steps
        .iter()
        .enumerate()
        .map(|(i, s)| {
            json!({
                "index": i + 1,
                "text": s.text,
                "intent": s.intent,
                "done": s.done,
                "source": s.source,
                "verify_cmd": s.verify_cmd,
                "result": s.result,
            })
        })
        .collect();
    Ok(json!({ "task": task.id, "steps": arr }))
}

/// `sara steps [--until N]` — ordered steps for incremental execution.
pub fn steps(
    conn: &Connection,
    _cfg: &Config,
    id: &str,
    until: Option<usize>,
    as_json: bool,
) -> Result<()> {
    if as_json {
        println!(
            "{}",
            serde_json::to_string_pretty(&steps_value(conn, id, until)?)?
        );
        return Ok(());
    }

    let task = db::resolve_task(conn, id)?;
    let mut steps = db::get_steps(conn, &task.uuid, db::STEP_KIND_STEP)?;
    if let Some(n) = until {
        steps.truncate(n);
    }

    if steps.is_empty() {
        println!("No steps defined for task {}.", task.id.unwrap_or(0));
        return Ok(());
    }
    for (i, s) in steps.iter().enumerate() {
        let mark = if s.done { "[x]" } else { "[ ]" };
        let badge = if s.source == "ai" { " (ai)" } else { "" };
        println!("{} {}. {}{}", mark, i + 1, s.text, badge);
        if let Some(intent) = &s.intent {
            println!("      {intent}");
        }
    }
    Ok(())
}

/// Mark step `n` done and return a structured record of the change. Shared by the
/// CLI `step done` command and the MCP `step_done` tool (which cannot print).
pub fn step_done_value(
    conn: &Connection,
    id: &str,
    n: usize,
    result: Option<&str>,
    kind: Option<&str>,
) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let kind = kind_arg(kind);
    let step_id = db::step_id_by_index(conn, &task.uuid, kind, n)?;
    let commit = project_head(conn, &task.project);
    db::set_step_done(conn, step_id, true, result, commit.as_deref())?;
    Ok(json!({
        "task": task.id,
        "uuid": task.uuid.to_string(),
        "kind": kind,
        "index": n,
        "done": true,
        "commit": commit,
    }))
}

/// `sara step done <id> <n>` — record completion of a step.
pub fn step_done(
    conn: &Connection,
    _cfg: &Config,
    id: &str,
    n: usize,
    result: Option<&str>,
    kind: Option<&str>,
) -> Result<()> {
    let v = step_done_value(conn, id, n, result, kind)?;
    let commit_suffix = v
        .get("commit")
        .and_then(|c| c.as_str())
        .map(|c| format!(" @ {c}"))
        .unwrap_or_default();
    println!(
        "Marked {} {} of task {} done{}.",
        v.get("kind").and_then(|k| k.as_str()).unwrap_or("step"),
        n,
        v.get("task").and_then(|t| t.as_i64()).unwrap_or(0),
        commit_suffix
    );
    Ok(())
}

/// Reopen step `n` and return a structured record. Print-free core shared by the
/// CLI `step undone` command and the MCP `step_undone` tool.
pub fn step_undone_value(
    conn: &Connection,
    id: &str,
    n: usize,
    kind: Option<&str>,
) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let kind = kind_arg(kind);
    let step_id = db::step_id_by_index(conn, &task.uuid, kind, n)?;
    db::set_step_done(conn, step_id, false, None, None)?;
    Ok(json!({
        "task": task.id,
        "uuid": task.uuid.to_string(),
        "kind": kind,
        "index": n,
        "done": false,
    }))
}

/// `sara step undone <id> <n>` — reopen a step.
pub fn step_undone(
    conn: &Connection,
    _cfg: &Config,
    id: &str,
    n: usize,
    kind: Option<&str>,
) -> Result<()> {
    let v = step_undone_value(conn, id, n, kind)?;
    println!(
        "Reopened {} {} of task {}.",
        v["kind"].as_str().unwrap_or("step"),
        n,
        v["task"].as_i64().unwrap_or(0)
    );
    Ok(())
}

/// Delete checklist item `n` and return a structured record. Print-free core
/// shared by the CLI `step remove` command and the MCP `step_remove` tool.
pub fn step_remove_value(
    conn: &Connection,
    id: &str,
    n: usize,
    kind: Option<&str>,
) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let kind = kind_arg(kind);
    let steps = db::get_steps(conn, &task.uuid, kind)?;
    // Indices are 1-based: reject 0 rather than letting it fall through to item 1.
    let idx = n
        .checked_sub(1)
        .ok_or_else(|| anyhow::anyhow!("{kind} index is 1-based; got 0"))?;
    let item = steps
        .get(idx)
        .ok_or_else(|| anyhow::anyhow!("No {kind} #{n} on this task"))?;
    let text = item.text.clone();
    db::delete_step(conn, item.id)?;
    Ok(json!({
        "task": task.id,
        "uuid": task.uuid.to_string(),
        "kind": kind,
        "index": n,
        "removed": text,
    }))
}

/// `sara step remove <id> <N> [--kind acceptance]` — delete a checklist item.
pub fn step_remove(
    conn: &Connection,
    _cfg: &Config,
    id: &str,
    n: usize,
    kind: Option<&str>,
) -> Result<()> {
    let v = step_remove_value(conn, id, n, kind)?;
    println!(
        "Removed {} {} of task {}: {}",
        v["kind"].as_str().unwrap_or("step"),
        n,
        v["task"].as_i64().unwrap_or(0),
        v["removed"].as_str().unwrap_or_default()
    );
    Ok(())
}

/// Add a checklist step (or acceptance criterion) to a task's guide, returning a
/// structured record. Print-free core shared by the CLI `check` command and the
/// MCP `check` tool.
pub fn check_value(
    conn: &Connection,
    id: &str,
    text: &str,
    intent: Option<&str>,
    kind: Option<&str>,
    source: Option<&str>,
    verify: Option<&str>,
) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let kind = kind_arg(kind);
    let source = source.unwrap_or("human");
    let step_id = db::add_step(conn, &task.uuid, text, intent, kind, source, verify)?;
    Ok(json!({
        "task": task.id,
        "uuid": task.uuid.to_string(),
        "kind": kind,
        "text": text,
        "step_id": step_id,
    }))
}

/// `sara verify [--step N] [--run]` — surface/run verification commands.
pub fn verify(
    conn: &Connection,
    _cfg: &Config,
    id: &str,
    step: Option<usize>,
    run: bool,
) -> Result<()> {
    let task = db::resolve_task(conn, id)?;
    let steps = db::get_steps(conn, &task.uuid, db::STEP_KIND_STEP)?;
    let acceptance = db::get_steps(conn, &task.uuid, db::STEP_KIND_ACCEPTANCE)?;
    let meta = db::get_guide_fields(conn, &task.uuid)?.meta_json;

    let mut cmds: Vec<String> = vec![];

    if let Some(n) = step {
        let idx = n
            .checked_sub(1)
            .ok_or_else(|| anyhow::anyhow!("step index is 1-based; got 0"))?;
        if let Some(s) = steps.get(idx) {
            if let Some(v) = &s.verify_cmd {
                cmds.push(v.clone());
            } else {
                println!("Step {n} has no verify command.");
            }
        } else {
            anyhow::bail!("No step #{n}");
        }
    } else {
        for s in steps.iter().chain(acceptance.iter()) {
            if let Some(v) = &s.verify_cmd {
                cmds.push(v.clone());
            }
        }
        // Project/task-level test + lint commands from meta_json.
        if let Some(meta) = meta
            .as_deref()
            .and_then(|m| serde_json::from_str::<serde_json::Value>(m).ok())
        {
            for key in ["test_cmd", "lint_cmd"] {
                if let Some(c) = meta.get(key).and_then(|v| v.as_str()) {
                    cmds.push(c.to_string());
                }
            }
        }
    }

    if !acceptance.is_empty() && step.is_none() {
        println!("Acceptance criteria:");
        for (i, a) in acceptance.iter().enumerate() {
            let mark = if a.done { "[x]" } else { "[ ]" };
            println!("  {} {}. {}", mark, i + 1, a.text);
        }
    }

    if cmds.is_empty() {
        println!("No verification commands found.");
        return Ok(());
    }

    let working_dir = db::get_project(conn, &task.project)
        .ok()
        .flatten()
        .and_then(|p| p.path);

    for cmd in &cmds {
        if run {
            println!("$ {cmd}");
            let mut command = std::process::Command::new("sh");
            command.arg("-c").arg(cmd);
            if let Some(dir) = &working_dir {
                command.current_dir(dir);
            }
            let status = command.status();
            match status {
                Ok(s) if s.success() => println!("  ok: passed"),
                Ok(s) => println!("  exited with {}", s.code().unwrap_or(-1)),
                Err(e) => println!("  failed to run: {e}"),
            }
        } else {
            println!("{cmd}");
        }
    }
    Ok(())
}

/// Read-only structured verification view for the MCP `verify` tool: the
/// verification commands (step + acceptance `verify_cmd`s and project-level
/// test/lint commands) plus the acceptance criteria. Unlike the CLI `verify`,
/// this NEVER executes anything — the agent runs the returned commands itself.
pub fn verify_value(conn: &Connection, id: &str, step: Option<usize>) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let steps = db::get_steps(conn, &task.uuid, db::STEP_KIND_STEP)?;
    let acceptance = db::get_steps(conn, &task.uuid, db::STEP_KIND_ACCEPTANCE)?;
    let meta = db::get_guide_fields(conn, &task.uuid)?.meta_json;

    let mut cmds: Vec<String> = vec![];
    if let Some(n) = step {
        // Indices are 1-based: reject 0 rather than silently returning step 1.
        let idx = n
            .checked_sub(1)
            .ok_or_else(|| anyhow::anyhow!("step index is 1-based; got 0"))?;
        let s = steps
            .get(idx)
            .ok_or_else(|| anyhow::anyhow!("No step #{n}"))?;
        if let Some(v) = &s.verify_cmd {
            cmds.push(v.clone());
        }
    } else {
        for s in steps.iter().chain(acceptance.iter()) {
            if let Some(v) = &s.verify_cmd {
                cmds.push(v.clone());
            }
        }
        if let Some(meta) = meta
            .as_deref()
            .and_then(|m| serde_json::from_str::<serde_json::Value>(m).ok())
        {
            for key in ["test_cmd", "lint_cmd"] {
                if let Some(c) = meta.get(key).and_then(|v| v.as_str()) {
                    cmds.push(c.to_string());
                }
            }
        }
    }

    let acc: Vec<_> = acceptance
        .iter()
        .enumerate()
        .map(|(i, a)| {
            json!({
                "index": i + 1,
                "text": a.text,
                "done": a.done,
                "verify_cmd": a.verify_cmd,
            })
        })
        .collect();

    Ok(json!({ "task": task.id, "commands": cmds, "acceptance": acc }))
}

/// Set a task's assignment text; print-free core shared by the CLI and MCP tool.
pub fn assignment_value(conn: &Connection, id: &str, text: &str) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    db::set_assignment(conn, &task.uuid, text)?;
    Ok(json!({ "task": task.id, "uuid": task.uuid.to_string(), "assignment": text }))
}

/// `sara assignment <id> <text>`
pub fn assignment(conn: &Connection, id: &str, text: &str) -> Result<()> {
    let v = assignment_value(conn, id, text)?;
    println!(
        "Set assignment for task {}.",
        v["task"].as_i64().unwrap_or(0)
    );
    Ok(())
}

/// Set a task's rationale text; print-free core shared by the CLI and MCP tool.
pub fn rationale_value(conn: &Connection, id: &str, text: &str) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    db::set_rationale(conn, &task.uuid, text)?;
    Ok(json!({ "task": task.id, "uuid": task.uuid.to_string(), "rationale": text }))
}

/// `sara rationale <id> <text>`
pub fn rationale(conn: &Connection, id: &str, text: &str) -> Result<()> {
    let v = rationale_value(conn, id, text)?;
    println!(
        "Set rationale for task {}.",
        v["task"].as_i64().unwrap_or(0)
    );
    Ok(())
}

/// Stamp the guide as validated against the project's current HEAD, returning a
/// structured record. Print-free core shared by the CLI `validate` command and
/// the MCP `validate` tool.
pub fn validate_value(conn: &Connection, id: &str) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let head = project_head(conn, &task.project)
        .ok_or_else(|| anyhow::anyhow!("task's project is not in a git repo"))?;
    db::set_validated(conn, &task.uuid, &head)?;
    Ok(json!({
        "task": task.id,
        "uuid": task.uuid.to_string(),
        "validated_commit": head,
    }))
}

/// `sara validate <id>` — stamp the guide as fresh against current HEAD.
pub fn validate(conn: &Connection, id: &str) -> Result<()> {
    let v = validate_value(conn, id)?;
    println!(
        "Stamped task {} validated @ {}.",
        v["task"].as_i64().unwrap_or(0),
        v["validated_commit"].as_str().unwrap_or_default()
    );
    Ok(())
}

/// Structured form of a task's open feedback. Shared by the `--json` CLI path and
/// the MCP `feedback` tool.
pub fn feedback_value(conn: &Connection, id: &str) -> Result<serde_json::Value> {
    let task = db::resolve_task(conn, id)?;
    let fb = db::get_open_feedback(conn, &task.uuid)?;
    let arr: Vec<_> = fb
        .iter()
        .map(|a| {
            json!({
                "id": a.id,
                "text": a.text,
                "target_kind": a.target_kind,
                "target_id": a.target_id,
                "request_revision": a.request_revision,
            })
        })
        .collect();
    Ok(json!({ "task": task.id, "open_feedback": arr }))
}

/// `sara feedback <id>` — list open human feedback.
pub fn feedback(conn: &Connection, id: &str, as_json: bool) -> Result<()> {
    if as_json {
        println!(
            "{}",
            serde_json::to_string_pretty(&feedback_value(conn, id)?)?
        );
        return Ok(());
    }

    let task = db::resolve_task(conn, id)?;
    let fb = db::get_open_feedback(conn, &task.uuid)?;

    if fb.is_empty() {
        println!("No open feedback for task {}.", task.id.unwrap_or(0));
        return Ok(());
    }
    for a in &fb {
        let target = match (&a.target_kind, &a.target_id) {
            (Some(k), Some(idv)) => format!(" [{k}:{idv}]"),
            _ => String::new(),
        };
        let flag = if a.request_revision { "" } else { "" };
        println!("#{}{}{}: {}", a.id, target, flag, a.text);
    }
    Ok(())
}

/// Resolve a feedback (annotation) item by its id; print-free core shared by the
/// CLI `resolve` command and the MCP `resolve` tool. Errors if no such feedback.
pub fn resolve_value(conn: &Connection, feedback_id: i64) -> Result<serde_json::Value> {
    if !db::resolve_annotation(conn, feedback_id, None)? {
        anyhow::bail!("No feedback with id {feedback_id}");
    }
    Ok(json!({ "feedback_id": feedback_id, "resolved": true }))
}

/// `sara resolve <feedback-id>`
pub fn resolve(conn: &Connection, feedback_id: i64) -> Result<()> {
    resolve_value(conn, feedback_id)?;
    println!("Resolved feedback #{feedback_id}.");
    Ok(())
}