sara-tasks 1.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
use rmcp::handler::server::wrapper::Parameters;
use rmcp::{tool, tool_router};

use crate::commands;

use super::params::*;
use super::server::{SaraServer, mcp_err, ok_json};

#[tool_router(router = read_router, vis = "pub(crate)")]
impl SaraServer {
    #[tool(
        description = "List pending tasks for a project (or all projects).",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn list(&self, Parameters(p): Parameters<ListParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp list", |conn, cfg| {
                commands::list::list_value(conn, cfg, p.all.unwrap_or(false), p.project.as_deref())
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Full task guide as JSON: description, steps, acceptance, notes, links, freshness, open feedback. When Strong memories (strength>=2.0) matching the task's description or tags exist, a `similar_work` array is included automatically — check it before starting.",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn info(&self, Parameters(p): Parameters<IdParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp info", |conn, _cfg| {
                commands::info::guide_value(conn, &p.id)
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "The execution cursor: the first not-done step of a task.",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn next(&self, Parameters(p): Parameters<IdParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp next", |conn, _cfg| {
                commands::guide::next_value(conn, &p.id)
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Ordered steps of a task (optionally only up to step `until`).",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn steps(&self, Parameters(p): Parameters<StepsParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp steps", |conn, _cfg| {
                commands::guide::steps_value(conn, &p.id, p.until)
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Read-only: the verification commands + acceptance criteria for a task (does NOT run them).",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn verify(&self, Parameters(p): Parameters<VerifyParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp verify", |conn, _cfg| {
                commands::guide::verify_value(conn, &p.id, p.step)
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Cross-task keyword search over descriptions, notes, and code anchors, plus exact --tag/--project lookups and --files filter over learned memories. Returns `confidence` (high/medium/none) and a `caveat` string — always read these: `none` with a caveat means FTS found nothing but that does NOT mean no similar work exists (literal keyword search only, no stemming or semantics). Set `spread: true` to also radiate across the memory graph and return associatively-related memories (sharing no keyword) in an `associative` array. Also returns a `patterns` array: recurring problem-solving patterns (canonical memories the hits belong to, with prior-application `instances`) — when present, prefer turning a pattern's `text` into a task via `add` (using it as the step guide) over re-deriving the solution, then `learn` the outcome and link it `derived_from` the canonical.",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn recall(&self, Parameters(p): Parameters<RecallParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp recall", |conn, cfg| {
                commands::recall::recall_value(
                    conn,
                    cfg,
                    &p.query,
                    p.tag.as_deref().unwrap_or(&[]),
                    p.project.as_deref().unwrap_or(&[]),
                    p.files.as_deref().unwrap_or(&[]),
                    p.limit.unwrap_or(10),
                    p.spread.unwrap_or(false),
                )
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "List a task's open human feedback (items awaiting a response).",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn feedback(&self, Parameters(p): Parameters<IdParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp feedback", |conn, _cfg| {
                commands::guide::feedback_value(conn, &p.id)
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Dependency-ordered briefing for a task: each task's full guide in dependency order (the task plus everything it is blocked by).",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn plan_show(&self, Parameters(p): Parameters<IdParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp plan_show", |conn, _cfg| {
                commands::plan::show_value(conn, &p.id)
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "List all tag vocabulary with usage counts across active memories.",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn tags(&self, Parameters(p): Parameters<TagsParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp tags", |conn, _cfg| {
                let counts = crate::infrastructure::db::list_tags_with_counts(conn)?;
                Ok(serde_json::json!(
                    counts
                        .into_iter()
                        .map(|(tag, count)| serde_json::json!({ "tag": tag, "count": count }))
                        .collect::<Vec<_>>()
                ))
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Browse all saved memories newest-first with strength labels (Strong/Linked/Weak). Use to audit what recall trusts or to find a memory label for `forget`.",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn memories(&self, Parameters(p): Parameters<MemoriesParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp memories", |conn, _cfg| {
                let items = crate::infrastructure::db::list_memories(conn)?;
                let strengths = crate::infrastructure::db::item_strengths(conn, &items);
                let rows: Vec<serde_json::Value> = items
                    .iter()
                    .map(|m| {
                        let strength = strengths.get(&m.uuid).copied().unwrap_or(1.0);
                        let label = format!(
                            "{}{}",
                            m.kind.chars().next().unwrap_or('m'),
                            m.display_id.unwrap_or(0)
                        );
                        let strength_label = if strength >= 2.0 {
                            "Strong"
                        } else if strength >= 1.5 {
                            "Linked"
                        } else {
                            "Weak"
                        };
                        let files = crate::infrastructure::db::get_item_files(conn, &m.uuid)
                            .unwrap_or_default();
                        serde_json::json!({
                            "label": label,
                            "title": m.title,
                            "body": m.body,
                            "strength": strength,
                            "strength_label": strength_label,
                            "tags": m.tags,
                            "files": files,
                            "created": m.created.to_rfc3339(),
                            "modified": m.modified.to_rfc3339(),
                        })
                    })
                    .collect();
                Ok(serde_json::json!({ "memories": rows }))
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "List all known projects with their metadata, task counts, and last activity.",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn projects(&self, Parameters(p): Parameters<ProjectsParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp projects", |conn, _cfg| {
                let names = crate::infrastructure::db::project_names(conn)?;
                let mut rows = Vec::with_capacity(names.len());
                for name in names {
                    let profile = crate::infrastructure::db::get_project(conn, &name)?;
                    let stats = crate::infrastructure::db::project_stats(conn, &name)?;
                    let last = crate::infrastructure::db::project_last_activity(conn, &name)?;
                    rows.push(serde_json::json!({
                        "name": name,
                        "goal": profile.as_ref().and_then(|p| p.goal.as_deref()),
                        "stack": profile.as_ref().and_then(|p| p.stack.as_deref()),
                        "pending": stats.pending,
                        "done": stats.completed_total,
                        "last_activity": last.map(|d| d.to_rfc3339()),
                    }));
                }
                Ok(serde_json::Value::Array(rows))
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Create a typed directed link between two memories. \
        Relations: `supersedes` (new replaces old; old shows ⚠ superseded-by in recall), \
        `similar_to` (bidirectional affinity), `derived_from` (this was built on top of that), \
        `used_in` (memory references a context/file). \
        The superseding memory surfaces alongside the stale one in recall output. \
        Use this to invalidate outdated memories rather than deleting them.",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    fn link_memory(&self, Parameters(p): Parameters<LinkMemoryParams>) -> Result<String, String> {
        let v = self
            .with_project(
                p.project_path.as_deref(),
                "mcp link_memory",
                |conn, _cfg| {
                    commands::link_memory::link_memory_value(
                        conn,
                        &p.from,
                        &p.relation,
                        &p.to,
                        p.weight.unwrap_or(1.0),
                    )
                },
            )
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Remove a typed directed link between two memories.",
        annotations(
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    fn unlink_memory(
        &self,
        Parameters(p): Parameters<UnlinkMemoryParams>,
    ) -> Result<String, String> {
        let v = self
            .with_project(
                p.project_path.as_deref(),
                "mcp unlink_memory",
                |conn, _cfg| commands::link_memory::unlink_value(conn, &p.from, &p.relation, &p.to),
            )
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Evaluate and optionally archive low-value memories. \
        Three signals: (1) superseded — has incoming `supersedes` edge, \
        (2) provisional + old — auto-generated on `done` but not reviewed within `provisional_days`, \
        (3) weak + old — no task link and older than `weak_days`. \
        Set dry_run=true (default) to preview without archiving. Set dry_run=false to apply. \
        Archived memories are NOT deleted — they can be inspected via direct DB query.",
        annotations(
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    fn prune_memories(
        &self,
        Parameters(p): Parameters<PruneMemoriesParams>,
    ) -> Result<String, String> {
        use crate::commands::prune_memories::{DEFAULT_PROVISIONAL_DAYS, DEFAULT_WEAK_DAYS};
        let v = self
            .with_project(
                p.project_path.as_deref(),
                "mcp prune_memories",
                |conn, _cfg| {
                    crate::commands::prune_memories::prune_value(
                        conn,
                        p.weak_days.unwrap_or(DEFAULT_WEAK_DAYS),
                        p.provisional_days.unwrap_or(DEFAULT_PROVISIONAL_DAYS),
                        p.dry_run.unwrap_or(true),
                    )
                },
            )
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Hebbian consolidation: sweep the last `window_days` of recall \
        history and set a `co_activated` synapse between every pair of memories that \
        fired together (recalled within `bucket_secs` of each other), weighted by how \
        often they co-fired. The learned wiring is recomputed from the window on each \
        run, so it is idempotent and synapses whose co-firings have aged out decay \
        away. This is what makes related memories surface together in future recalls, \
        so run it periodically. Returns the number of synapses in the learned wiring.",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    fn consolidate(&self, Parameters(p): Parameters<ConsolidateParams>) -> Result<String, String> {
        let v = self
            .with_project(
                p.project_path.as_deref(),
                "mcp consolidate",
                |conn, _cfg| {
                    let reinforced = crate::infrastructure::memory::graph::consolidate(
                        conn,
                        p.window_days.unwrap_or(30),
                        chrono::Duration::seconds(p.bucket_secs.unwrap_or(5)),
                        p.delta.unwrap_or(0.1),
                        p.max_bucket.unwrap_or(5),
                    )?;
                    Ok(serde_json::json!({ "reinforced": reinforced }))
                },
            )
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Reflect over the memory graph: cluster memories that keep \
        firing together but are not yet tidied, and nominate a canonical memory per \
        cluster. Read-only by default — returns the proposal so you can review it. \
        Pass apply=true to create the proposed `derived_from` edges (each \
        non-canonical member -> the canonical one); links that would trip the \
        cycle guard are skipped and reported.",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    fn reflect(&self, Parameters(p): Parameters<ReflectParams>) -> Result<String, String> {
        let min_weight = p
            .min_weight
            .unwrap_or(crate::commands::reflect::DEFAULT_MIN_WEIGHT);
        let max_cluster = p
            .max_cluster
            .unwrap_or(crate::commands::reflect::DEFAULT_MAX_CLUSTER);
        let v = self
            .with_project(p.project_path.as_deref(), "mcp reflect", |conn, _cfg| {
                if p.apply.unwrap_or(false) {
                    commands::reflect::apply_value(conn, min_weight, max_cluster)
                } else {
                    commands::reflect::reflect_value(conn, min_weight, max_cluster)
                }
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Health report for the memory graph: surfaces unlinked pairs that \
        both co-occur (shared file or identical tag set) AND are semantically close, \
        worst-first by cosine. Read-only — archives nothing. Use it to decide what to \
        `relearn`, `forget` or `prune_memories`.",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn diagnose_memories(
        &self,
        Parameters(p): Parameters<DiagnoseMemoriesParams>,
    ) -> Result<String, String> {
        let threshold = p
            .threshold
            .unwrap_or(commands::diagnose_memories::DEFAULT_CONFLICT_THRESHOLD);
        let v = self
            .with_project(
                p.project_path.as_deref(),
                "mcp diagnose_memories",
                |conn, _cfg| {
                    commands::diagnose_memories::diagnose_value(
                        conn,
                        threshold,
                        p.project.as_deref(),
                        p.limit,
                    )
                },
            )
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Read-only health report for the memory store, run it before \
        trusting recall. Checks embedding coverage, orphaned memory links, \
        near-duplicate pairs, superseded-but-active memories, the provisional review \
        backlog, and decay outliers. Each check returns status ok|warn|info, a count, \
        a summary, and the `fix` command to run. `healthy` is false when any check warns.",
        annotations(read_only_hint = true, open_world_hint = false)
    )]
    fn doctor(&self, Parameters(p): Parameters<DoctorParams>) -> Result<String, String> {
        let v = self
            .with_project(p.project_path.as_deref(), "mcp doctor", |conn, _cfg| {
                commands::doctor::doctor_value(conn)
            })
            .map_err(mcp_err)?;
        ok_json(v)
    }

    #[tool(
        description = "Rebuild the semantic embedding index over all memories. \
        Needed after bulk imports, or when `recall`'s semantic pass is missing \
        memories that are obviously relevant. Returns the number embedded.",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    fn reindex_embeddings(
        &self,
        Parameters(p): Parameters<ReindexEmbeddingsParams>,
    ) -> Result<String, String> {
        let v = self
            .with_project(
                p.project_path.as_deref(),
                "mcp reindex_embeddings",
                |conn, _cfg| {
                    let embedded = crate::infrastructure::memory::embedding::reindex_all(conn)?;
                    Ok(serde_json::json!({ "embedded": embedded }))
                },
            )
            .map_err(mcp_err)?;
        ok_json(v)
    }
}