codescout 0.14.0

High-performance coding agent toolkit MCP server
Documentation
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
use crate::librarian::catalog::augmentation;
use crate::librarian::tools::gather::{gather_all, GatherSource};
use crate::librarian::tools::{RecoverableError, ToolContext};
use anyhow::Result;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashMap;

#[derive(Deserialize)]
struct Args {
    id: String,
}

fn read_body(ctx: &ToolContext, artifact_id: &str) -> Result<Option<String>> {
    let cat = ctx.catalog.lock();
    let row = match crate::librarian::catalog::artifact::get(&cat, artifact_id)? {
        Some(r) => r,
        None => return Ok(None),
    };
    let full_path = row.abs_path.clone();
    match std::fs::read_to_string(&full_path) {
        Ok(s) => Ok(Some(s)),
        Err(_) => Ok(None),
    }
}
pub async fn call(ctx: &ToolContext, args: Value) -> Result<Value> {
    let a: Args = serde_json::from_value(args)?;

    let aug_row = {
        let cat = ctx.catalog.lock();
        augmentation::get(&cat, &a.id)?
    };

    let aug = aug_row.ok_or_else(|| {
        RecoverableError::new(format!(
            "no augmentation for artifact '{}' — call artifact_augment first",
            a.id
        ))
    })?;

    let params: Value = serde_json::from_str(&aug.params).unwrap_or_else(|_| json!({}));
    let sources: Vec<GatherSource> = params
        .get("gather_from")
        .and_then(|g| serde_json::from_value(g.clone()).ok())
        .unwrap_or_default();

    let (results, warnings) = gather_all(&sources, ctx, aug.last_refreshed_at.as_deref()).await?;

    let mut context: HashMap<String, Value> = HashMap::new();
    for r in results {
        context
            .entry(r.source_key.clone())
            .and_modify(|existing| {
                if let (Value::Array(a), Value::Array(b)) = (existing, &r.data) {
                    a.extend(b.clone());
                }
            })
            .or_insert(r.data);
    }

    // Goal-tracker injection (Yak variant (b)): if this artifact's params
    // describe a goal-tracker (has `acceptance_signals` AND `children`),
    // synthesize `deterministic_child_statuses` by running
    // `goal_aggregation::child_status_pure` on each linked child. The LLM
    // reads ground truth from context rather than re-deriving rule 1.
    let is_goal_tracker = params.is_object()
        && params.get("acceptance_signals").is_some()
        && params.get("children").is_some();
    if is_goal_tracker {
        let children_tuples: Vec<(String, String, String)> = params
            .get("children")
            .and_then(|c| c.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|c| {
                        let id = c.get("id")?.as_str()?.to_string();
                        let aid = c.get("artifact_id")?.as_str()?.to_string();
                        let arch = c
                            .get("archetype")
                            .and_then(|a| a.as_str())
                            .unwrap_or("")
                            .to_string();
                        Some((id, aid, arch))
                    })
                    .collect()
            })
            .unwrap_or_default();
        if !children_tuples.is_empty() {
            let parent_signals: Vec<crate::librarian::tools::goal_aggregation::AcceptanceSignal> =
                params
                    .get("acceptance_signals")
                    .and_then(|s| serde_json::from_value(s.clone()).ok())
                    .unwrap_or_default();
            let det = crate::librarian::tools::gather::gather_goal_children(
                ctx,
                &children_tuples,
                &parent_signals,
            )?;
            context.insert("deterministic_child_statuses".to_string(), det.clone());

            // D5 — compute refresh_meta deterministically from prior + fresh state.
            use crate::librarian::tools::goal_aggregation::{
                child_status_from_str, compute_refresh_meta, ChildStatus, RefreshMeta,
            };
            let prior_refresh_meta: Option<RefreshMeta> = params
                .get("refresh_meta")
                .and_then(|m| serde_json::from_value(m.clone()).ok());
            let prior_child_statuses: Vec<(String, ChildStatus)> = params
                .get("children")
                .and_then(|c| c.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|c| {
                            let id = c.get("id")?.as_str()?.to_string();
                            let status = c
                                .get("status")
                                .and_then(|s| s.as_str())
                                .map(child_status_from_str)
                                .unwrap_or(ChildStatus::Unknown);
                            Some((id, status))
                        })
                        .collect()
                })
                .unwrap_or_default();
            let fresh_child_statuses: Vec<(String, ChildStatus)> = det
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|entry| {
                            let id = entry.get("child_id")?.as_str()?.to_string();
                            let status = entry
                                .get("status")
                                .and_then(|s| s.as_str())
                                .map(child_status_from_str)
                                .unwrap_or(ChildStatus::Unknown);
                            Some((id, status))
                        })
                        .collect()
                })
                .unwrap_or_default();
            let orphan_children: Vec<String> = det
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|entry| {
                            let basis = entry.get("basis").and_then(|b| b.as_str()).unwrap_or("");
                            if basis == "child unreachable" {
                                entry
                                    .get("child_id")
                                    .and_then(|c| c.as_str())
                                    .map(String::from)
                            } else {
                                None
                            }
                        })
                        .collect()
                })
                .unwrap_or_default();
            let commits_since_last = context
                .get("git_log")
                .and_then(|g| g.as_array())
                .map(|a| a.len() as u64)
                .unwrap_or(0);
            let refresh_meta = compute_refresh_meta(
                prior_refresh_meta.as_ref(),
                &prior_child_statuses,
                &fresh_child_statuses,
                orphan_children,
                chrono::Utc::now(),
                None,
                commits_since_last,
            );
            context.insert(
                "refresh_meta".to_string(),
                serde_json::to_value(&refresh_meta).unwrap_or(serde_json::Value::Null),
            );
        }
    }

    if !warnings.is_empty() {
        context.insert("warnings".to_string(), json!(warnings));
    }

    let current_body = read_body(ctx, &a.id)?;

    let mut hints: Vec<String> = Vec::new();
    for (key, val) in &context {
        if key == "warnings" {
            continue;
        }
        if let Some(arr) = val.as_array() {
            hints.push(format!("{} items gathered from {key}", arr.len()));
        }
    }

    let mut out = json!({
        "artifact_id": a.id,
        "prompt": aug.prompt,
        "params": params,
        "current_body": current_body,
        "context": context,
        "last_refreshed_at": aug.last_refreshed_at,
        "hints": hints,
    });
    if aug.append_mode {
        out["append_mode"] = json!(true);
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::librarian::catalog::Catalog;
    use crate::librarian::tools::Tool;
    use crate::librarian::workspace::{Root, WorkspaceConfig};
    use std::sync::Arc;
    use tempfile::TempDir;

    fn mk_ctx(tmp_root: std::path::PathBuf) -> ToolContext {
        ToolContext {
            catalog: Arc::new(parking_lot::Mutex::new(Catalog::open_in_memory().unwrap())),
            workspace: Arc::new(WorkspaceConfig {
                roots: vec![Root {
                    name: "r".into(),
                    path: tmp_root,
                }],
                ignore: vec![],
                rules: vec![],
                umbrellas: vec![],
            }),
            rules: Arc::new(vec![]),
            embedding: None,
            current_project: None,
        }
    }

    #[tokio::test]
    async fn refresh_includes_append_mode_hint_when_set() {
        let tmp = TempDir::new().unwrap();
        let ctx = mk_ctx(tmp.path().to_path_buf());

        let v = crate::librarian::tools::create::call(
            &ctx,
            serde_json::json!({
                "repo": "r",
                "rel_path": "hint_test.md",
                "kind": "spec",
                "title": "hint test",
                "body": "body",
            }),
        )
        .await
        .unwrap();
        let id = v["id"].as_str().unwrap().to_string();

        crate::librarian::tools::augment::ArtifactAugment
            .call(
                &ctx,
                serde_json::json!({
                    "id": id,
                    "prompt": "track",
                    "append_mode": true,
                }),
            )
            .await
            .unwrap();

        let result = call(&ctx, serde_json::json!({"id": id})).await.unwrap();
        assert_eq!(result["append_mode"], serde_json::json!(true));
    }

    #[tokio::test]
    async fn refresh_injects_deterministic_child_statuses_for_goal_tracker() {
        use crate::librarian::catalog::artifact::{upsert as art_upsert, ArtifactRow};
        use crate::librarian::catalog::augmentation::{upsert as aug_upsert, AugmentationRow};

        let tmp = TempDir::new().unwrap();
        let ctx = mk_ctx(tmp.path().to_path_buf());

        // Helper closures (avoid module-private dependencies for sample data).
        let mk_art = |id: &str| ArtifactRow {
            id: id.to_string(),
            abs_path: std::path::PathBuf::from(format!("/test/{id}.md")),
            kind: "tracker".to_string(),
            status: "active".to_string(),
            title: Some(id.to_string()),
            owners: vec![],
            tags: vec![],
            topic: None,
            time_scope: None,
            source: None,
            created_at: 0,
            updated_at: 0,
            file_mtime: 0,
            file_sha256: "x".to_string(),
            confidence: 1.0,
        };
        let mk_aug = |aid: &str, params_json: &str| AugmentationRow {
            artifact_id: aid.to_string(),
            prompt: "p".to_string(),
            params: params_json.to_string(),
            last_refreshed_at: None,
            refresh_count: 0,
            created_at: "2026-01-01T00:00:00.000Z".to_string(),
            updated_at: "2026-01-01T00:00:00.000Z".to_string(),
            render_template: None,
            params_schema: None,
            append_mode: false,
            history_cap: None,
        };

        // Two children: a failure_table (all-pass → done) and a task_list (empty → pending).
        {
            let cat = ctx.catalog.lock();
            art_upsert(&cat, &mk_art("child-a")).unwrap();
            aug_upsert(
                &cat,
                &mk_aug("child-a", r#"{"failures":[{"id":"F-1","status":"pass"}]}"#),
            )
            .unwrap();
            art_upsert(&cat, &mk_art("child-b")).unwrap();
            aug_upsert(&cat, &mk_aug("child-b", r#"{"tasks":[]}"#)).unwrap();

            // Parent goal: structurally a goal-tracker (has acceptance_signals + children).
            art_upsert(&cat, &mk_art("goal-1")).unwrap();
            let goal_params = serde_json::json!({
                "criterion": "All children done",
                "status": "active",
                "acceptance_signals": [],
                "children": [
                    {"id": "C-1", "artifact_id": "child-a", "title": "A",
                     "archetype": "failure_table", "status": "in-progress"},
                    {"id": "C-2", "artifact_id": "child-b", "title": "B",
                     "archetype": "task_list", "status": "pending"}
                ]
            });
            aug_upsert(&cat, &mk_aug("goal-1", &goal_params.to_string())).unwrap();
        }

        let result = call(&ctx, serde_json::json!({"id": "goal-1"}))
            .await
            .unwrap();

        // The context should carry deterministic_child_statuses with both children resolved.
        let det = &result["context"]["deterministic_child_statuses"];
        assert!(
            det.is_array(),
            "deterministic_child_statuses missing or not array: {result:#}"
        );
        let arr = det.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        assert_eq!(arr[0]["child_id"], "C-1");
        assert_eq!(arr[0]["status"], "done");
        assert_eq!(arr[0]["basis"], "deterministic");
        assert_eq!(arr[1]["child_id"], "C-2");
        assert_eq!(arr[1]["status"], "pending");
    }

    #[tokio::test]
    async fn refresh_skips_deterministic_injection_for_non_goal_tracker() {
        use crate::librarian::catalog::artifact::{upsert as art_upsert, ArtifactRow};
        use crate::librarian::catalog::augmentation::{upsert as aug_upsert, AugmentationRow};

        let tmp = TempDir::new().unwrap();
        let ctx = mk_ctx(tmp.path().to_path_buf());

        // A regular task_list tracker — has children-shaped params but no acceptance_signals.
        // Should NOT trigger goal-tracker injection.
        let mk_art = |id: &str| ArtifactRow {
            id: id.to_string(),
            abs_path: std::path::PathBuf::from(format!("/test/{id}.md")),
            kind: "tracker".to_string(),
            status: "active".to_string(),
            title: None,
            owners: vec![],
            tags: vec![],
            topic: None,
            time_scope: None,
            source: None,
            created_at: 0,
            updated_at: 0,
            file_mtime: 0,
            file_sha256: "x".to_string(),
            confidence: 1.0,
        };
        {
            let cat = ctx.catalog.lock();
            art_upsert(&cat, &mk_art("plain")).unwrap();
            aug_upsert(
                &cat,
                &AugmentationRow {
                    artifact_id: "plain".to_string(),
                    prompt: "p".to_string(),
                    params: r#"{"tasks":[{"id":"T-1","status":"done"}]}"#.to_string(),
                    last_refreshed_at: None,
                    refresh_count: 0,
                    created_at: "2026-01-01T00:00:00.000Z".to_string(),
                    updated_at: "2026-01-01T00:00:00.000Z".to_string(),
                    render_template: None,
                    params_schema: None,
                    append_mode: false,
                    history_cap: None,
                },
            )
            .unwrap();
        }

        let result = call(&ctx, serde_json::json!({"id": "plain"}))
            .await
            .unwrap();
        assert!(
            result["context"]["deterministic_child_statuses"].is_null()
                || !result["context"]
                    .as_object()
                    .unwrap()
                    .contains_key("deterministic_child_statuses"),
            "non-goal tracker should not receive deterministic_child_statuses: {result:#}"
        );
    }

    #[tokio::test]
    async fn refresh_injects_refresh_meta_with_status_deltas_for_goal_tracker() {
        // D5: prior children statuses differ from kernel verdict → deltas surface.
        use crate::librarian::catalog::artifact::{upsert as art_upsert, ArtifactRow};
        use crate::librarian::catalog::augmentation::{upsert as aug_upsert, AugmentationRow};

        let tmp = TempDir::new().unwrap();
        let ctx = mk_ctx(tmp.path().to_path_buf());

        let mk_art = |id: &str| ArtifactRow {
            id: id.to_string(),
            abs_path: std::path::PathBuf::from(format!("/test/{id}.md")),
            kind: "tracker".to_string(),
            status: "active".to_string(),
            title: None,
            owners: vec![],
            tags: vec![],
            topic: None,
            time_scope: None,
            source: None,
            created_at: 0,
            updated_at: 0,
            file_mtime: 0,
            file_sha256: "x".to_string(),
            confidence: 1.0,
        };
        let mk_aug = |aid: &str, params: &str| AugmentationRow {
            artifact_id: aid.to_string(),
            prompt: "p".to_string(),
            params: params.to_string(),
            last_refreshed_at: None,
            refresh_count: 0,
            created_at: "2026-01-01T00:00:00.000Z".to_string(),
            updated_at: "2026-01-01T00:00:00.000Z".to_string(),
            render_template: None,
            params_schema: None,
            append_mode: false,
            history_cap: None,
        };

        {
            let cat = ctx.catalog.lock();
            art_upsert(&cat, &mk_art("child-a")).unwrap();
            aug_upsert(
                &cat,
                &mk_aug("child-a", r#"{"tasks":[{"id":"T-1","status":"done"}]}"#),
            )
            .unwrap();
            art_upsert(&cat, &mk_art("child-b")).unwrap();
            aug_upsert(
                &cat,
                &mk_aug("child-b", r#"{"failures":[{"id":"F-1","status":"pass"}]}"#),
            )
            .unwrap();
            art_upsert(&cat, &mk_art("goal-1")).unwrap();
            // Prior state: child-a was "in-progress", child-b "active".
            // Kernel will compute child-a=done (task all done), child-b=done (clean).
            let goal_params = serde_json::json!({
                "criterion": "Two children resolve",
                "status": "active",
                "acceptance_signals": [],
                "children": [
                    {"id": "C-1", "artifact_id": "child-a", "title": "A",
                     "archetype": "task_list", "status": "in-progress"},
                    {"id": "C-2", "artifact_id": "child-b", "title": "B",
                     "archetype": "failure_table", "status": "active"}
                ]
            });
            aug_upsert(&cat, &mk_aug("goal-1", &goal_params.to_string())).unwrap();
        }

        let result = call(&ctx, serde_json::json!({"id": "goal-1"}))
            .await
            .unwrap();
        let meta = &result["context"]["refresh_meta"];
        assert!(meta.is_object(), "refresh_meta missing: {result:#}");
        let deltas = meta["children_status_delta"].as_array().unwrap();
        assert_eq!(deltas.len(), 2, "expected 2 deltas: {meta:#}");
        // Both C-1 and C-2 transition to done.
        let to_vals: Vec<&str> = deltas.iter().filter_map(|d| d["to"].as_str()).collect();
        assert!(to_vals.iter().all(|s| *s == "done"));
        assert_eq!(meta["unchanged_refreshes"], 0);
        assert_eq!(meta["commit_count_since_last"], 0);
    }

    #[tokio::test]
    async fn refresh_injects_refresh_meta_unchanged_when_kernel_matches_prior() {
        // D5: kernel verdict matches prior children[].status verbatim → no deltas,
        // unchanged_refreshes increments from prior (or 1 if no prior).
        use crate::librarian::catalog::artifact::{upsert as art_upsert, ArtifactRow};
        use crate::librarian::catalog::augmentation::{upsert as aug_upsert, AugmentationRow};

        let tmp = TempDir::new().unwrap();
        let ctx = mk_ctx(tmp.path().to_path_buf());
        let mk_art = |id: &str| ArtifactRow {
            id: id.to_string(),
            abs_path: std::path::PathBuf::from(format!("/test/{id}.md")),
            kind: "tracker".to_string(),
            status: "active".to_string(),
            title: None,
            owners: vec![],
            tags: vec![],
            topic: None,
            time_scope: None,
            source: None,
            created_at: 0,
            updated_at: 0,
            file_mtime: 0,
            file_sha256: "x".to_string(),
            confidence: 1.0,
        };
        let mk_aug = |aid: &str, params: &str| AugmentationRow {
            artifact_id: aid.to_string(),
            prompt: "p".to_string(),
            params: params.to_string(),
            last_refreshed_at: None,
            refresh_count: 0,
            created_at: "2026-01-01T00:00:00.000Z".to_string(),
            updated_at: "2026-01-01T00:00:00.000Z".to_string(),
            render_template: None,
            params_schema: None,
            append_mode: false,
            history_cap: None,
        };
        {
            let cat = ctx.catalog.lock();
            art_upsert(&cat, &mk_art("c-done")).unwrap();
            aug_upsert(
                &cat,
                &mk_aug("c-done", r#"{"tasks":[{"id":"T-1","status":"done"}]}"#),
            )
            .unwrap();
            art_upsert(&cat, &mk_art("c-done-2")).unwrap();
            aug_upsert(
                &cat,
                &mk_aug("c-done-2", r#"{"tasks":[{"id":"T-2","status":"done"}]}"#),
            )
            .unwrap();
            art_upsert(&cat, &mk_art("goal-x")).unwrap();
            // Prior already records both as done; prior refresh_meta has unchanged=4.
            let goal_params = serde_json::json!({
                "criterion": "stable",
                "status": "active",
                "acceptance_signals": [],
                "refresh_meta": {
                    "last_refresh_at": "2026-05-16T12:00:00Z",
                    "unchanged_refreshes": 4,
                    "children_status_delta": [],
                    "commit_count_since_last": 0
                },
                "children": [
                    {"id": "C-1", "artifact_id": "c-done", "title": "A",
                     "archetype": "task_list", "status": "done"},
                    {"id": "C-2", "artifact_id": "c-done-2", "title": "B",
                     "archetype": "task_list", "status": "done"}
                ]
            });
            aug_upsert(&cat, &mk_aug("goal-x", &goal_params.to_string())).unwrap();
        }

        let result = call(&ctx, serde_json::json!({"id": "goal-x"}))
            .await
            .unwrap();
        let meta = &result["context"]["refresh_meta"];
        assert_eq!(meta["children_status_delta"].as_array().unwrap().len(), 0);
        assert_eq!(meta["unchanged_refreshes"], 5);
    }
}