kazam 1.29.3

Local infrastructure for coding agents: context, visibility, durable execution. One Rust binary, no cloud.
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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
pub mod enrich;
pub mod hooks;
pub mod outline;
pub mod research;
pub mod scan;
pub mod types;

use anyhow::{bail, Context, Result};
use clap::Subcommand;
use std::path::Path;

use types::*;

#[derive(Subcommand)]
pub enum Command {
    /// Initialize .kazam/ctx/ (optionally scan files)
    Init {
        /// Run an initial anatomy scan right away
        #[arg(long)]
        scan: bool,
        /// Gitignore .kazam/ for shared repos
        #[arg(long)]
        skunkworks: bool,
    },
    /// Scan project files and update anatomy
    Scan {
        /// Report drift without writing changes
        #[arg(long)]
        check: bool,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Refresh the anatomy: hash-based change, delete, and rename detection,
    /// per-file outlines, and a diff appended to ctx/changes.log
    Refresh {
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Describe files with a local model (whole file, cached globally by content hash)
    Enrich {
        /// Model calls per run; cached descriptions always apply (0 = cache only)
        #[arg(long, default_value = "25")]
        max: usize,
        /// Detach and run at low priority, logging to .kazam/ctx/enrich.log
        #[arg(long)]
        background: bool,
        /// Describe every text file, not just source and docs (default skips
        /// tests, fixtures, data, and build output)
        #[arg(long)]
        all: bool,
        /// OpenAI-compatible chat completions endpoint (mlx_lm.server by default)
        #[arg(long, default_value = enrich::DEFAULT_ENDPOINT)]
        endpoint: String,
        /// Model name sent to the endpoint
        #[arg(long, default_value = enrich::DEFAULT_MODEL)]
        model: String,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Rank files for a task and print a token-budgeted brief with line-cited outlines
    Research {
        /// What you're trying to do, in plain words
        task: String,
        /// Max files in the brief
        #[arg(long, default_value = "8")]
        k: usize,
        /// Approximate token budget for the brief
        #[arg(long, default_value = "2500")]
        budget: usize,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Show context status summary
    Status {
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Update a file's anatomy description (agent-enriched)
    Describe {
        /// Path to the file, relative to the project
        file: String,
        /// What this file actually does
        description: String,
    },
    /// Record a learning
    Learn {
        /// The lesson learned, in one or two sentences
        text: String,
        /// preference, correction, or gotcha
        #[arg(long, default_value = "preference")]
        category: String,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// List all learnings
    Learnings {
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Record a bug encounter
    Bug {
        /// What went wrong, in one or two sentences
        symptom: String,
        /// File path the bug is associated with
        #[arg(long)]
        file: Option<String>,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// List bugs (optionally filtered by file path)
    Bugs {
        /// Only show bugs associated with this file path
        #[arg(long)]
        file: Option<String>,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Resolve a bug with a fix description
    Resolve {
        /// Bug ID
        id: String,
        /// How it was fixed
        #[arg(long)]
        fix: String,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Record a correction (agent got something wrong)
    Correction {
        /// What the agent did wrong
        mistake: String,
        /// What to do instead
        correction: String,
        /// File path the correction is associated with
        #[arg(long)]
        file: Option<String>,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// List all corrections
    Corrections {
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Consolidate stale data (remove old resolved bugs, deduplicate learnings)
    Consolidate {
        /// Only consolidate entries older than this many days
        #[arg(long, default_value = "30")]
        days: u32,
        /// Machine-readable JSON output
        #[arg(long)]
        json: bool,
    },
    /// Manage agent hooks (install/uninstall/status)
    Hooks {
        #[command(subcommand)]
        action: HooksAction,
    },
}

#[derive(Subcommand)]
pub enum HooksAction {
    /// Install hook scripts and register with agent
    Install {
        /// Which agent to register hooks for
        #[arg(long, default_value = "claude")]
        agent: String,
    },
    /// Remove all hooks
    Uninstall,
    /// Show hook installation status
    Status,
}

pub fn run(cmd: Command, project: &Path) -> Result<()> {
    match cmd {
        Command::Init { scan, skunkworks } => cmd_init(project, scan, skunkworks),
        Command::Scan { check, json } => cmd_scan(project, check, json),
        Command::Refresh { json } => cmd_refresh(project, json),
        Command::Enrich {
            max,
            background,
            all,
            endpoint,
            model,
            json,
        } => cmd_enrich(
            project,
            enrich::Options {
                max,
                all,
                endpoint,
                model,
            },
            background,
            json,
        ),
        Command::Research {
            task,
            k,
            budget,
            json,
        } => {
            let hits = research::research(project, &task, k, budget);
            if json {
                json_ok(&hits);
            } else {
                print!("{}", research::render(&task, &hits));
            }
            Ok(())
        }
        Command::Status { json } => cmd_status(project, json),
        Command::Describe { file, description } => cmd_describe(project, &file, &description),
        Command::Learn {
            text,
            category,
            json,
        } => cmd_learn(project, text, &category, json),
        Command::Learnings { json } => cmd_learnings(project, json),
        Command::Bug {
            symptom,
            file,
            json,
        } => cmd_bug(project, symptom, file, json),
        Command::Bugs { file, json } => cmd_bugs(project, file, json),
        Command::Resolve { id, fix, json } => cmd_resolve(project, &id, &fix, json),
        Command::Correction {
            mistake,
            correction,
            file,
            json,
        } => cmd_correction(project, mistake, correction, file, json),
        Command::Corrections { json } => cmd_corrections(project, json),
        Command::Consolidate { days, json } => cmd_consolidate(project, days, json),
        Command::Hooks { action } => match action {
            HooksAction::Install { agent } => {
                let skunkworks = crate::workspace::read_config(project)
                    .map(|c| c.skunkworks)
                    .unwrap_or(false);
                hooks::install(project, &agent, skunkworks)
            }
            HooksAction::Uninstall => hooks::uninstall(project),
            HooksAction::Status => hooks::status(project),
        },
    }
}

fn now() -> String {
    chrono::Local::now().to_rfc3339()
}

fn json_ok<T: serde::Serialize>(data: &T) {
    println!("{}", serde_json::json!({ "ok": true, "data": data }));
}

fn json_err(msg: &str) {
    println!("{}", serde_json::json!({ "ok": false, "error": msg }));
}

/// Internal flat anatomy path used by board, describe, and status commands.
fn anatomy_path(project: &Path) -> std::path::PathBuf {
    crate::workspace::root(project).join("ctx/anatomy.flat.yaml")
}

fn learnings_path(project: &Path) -> std::path::PathBuf {
    crate::workspace::root(project).join("ctx/learnings.yaml")
}

fn bugs_path(project: &Path) -> std::path::PathBuf {
    crate::workspace::root(project).join("ctx/bugs.yaml")
}

fn corrections_path(project: &Path) -> std::path::PathBuf {
    crate::workspace::root(project).join("ctx/corrections.yaml")
}

// ── Commands ─────────────────────────────────────

fn cmd_init(project: &Path, do_scan: bool, skunkworks: bool) -> Result<()> {
    crate::workspace::ensure(project)?;
    if skunkworks {
        crate::workspace::set_skunkworks(project)?;
    }
    if do_scan {
        let store = scan::scan(project)?;
        crate::workspace::write_yaml(&anatomy_path(project), &store)?;
        scan::write_layered(project, &store)?;
        println!(
            "  ✓ .kazam/ctx/ initialized - {} files indexed",
            store.files.len()
        );
    } else {
        println!("  ✓ .kazam/ctx/ initialized");
    }
    if !crate::workspace::hooks_installed(project) {
        println!("  hint: run `kazam ctx hooks install` to wire up agent hooks");
        println!("        or `kazam workspace init` for the full setup");
    }
    Ok(())
}

fn cmd_scan(project: &Path, check: bool, json: bool) -> Result<()> {
    if check {
        let diff = scan::check(project)?;
        if json {
            json_ok(&diff);
        } else if diff.is_empty() {
            println!("  ✓ anatomy up to date");
        } else {
            if !diff.new_files.is_empty() {
                println!("  + {} new files", diff.new_files.len());
                for f in &diff.new_files {
                    println!("    {f}");
                }
            }
            if !diff.deleted_files.is_empty() {
                println!("  - {} deleted files", diff.deleted_files.len());
                for f in &diff.deleted_files {
                    println!("    {f}");
                }
            }
            if !diff.changed_files.is_empty() {
                println!("  ~ {} changed files", diff.changed_files.len());
                for f in &diff.changed_files {
                    println!("    {f}");
                }
            }
        }
    } else {
        let store = scan::scan(project)?;
        // Write flat store (for board.rs + describe + status)
        crate::workspace::write_yaml(&anatomy_path(project), &store)?;
        // Write layered summary (anatomy.tsv) + per-directory files (anatomy/<dir>.tsv)
        scan::write_layered(project, &store)?;
        if json {
            json_ok(&serde_json::json!({ "files": store.files.len() }));
        } else {
            println!("  ✓ scanned {} files", store.files.len());
        }
    }
    Ok(())
}

fn cmd_refresh(project: &Path, json: bool) -> Result<()> {
    crate::workspace::ensure(project)?;
    let (store, diff) = scan::refresh(project)?;
    if json {
        json_ok(&serde_json::json!({ "files": store.files.len(), "diff": diff }));
        return Ok(());
    }
    println!("  ✓ refreshed {} files", store.files.len());
    for (label, list) in [
        ("+", &diff.added),
        ("~", &diff.changed),
        ("-", &diff.deleted),
    ] {
        for f in list.iter() {
            println!("    {label} {f}");
        }
    }
    for (from, to) in &diff.renamed {
        println!("    > {from} -> {to}");
    }
    Ok(())
}

fn cmd_enrich(project: &Path, opts: enrich::Options, background: bool, json: bool) -> Result<()> {
    if background {
        enrich::spawn_background(project, &opts)?;
        if !json {
            println!("  ✓ enrich started in background (log: .kazam/ctx/enrich.log)");
        }
        return Ok(());
    }
    let report = enrich::run(project, &opts)?;
    if json {
        json_ok(&report);
    } else {
        println!(
            "  ✓ enrich: {} from cache, {} described, {} failed, {} remaining ({})",
            report.from_cache, report.described, report.failed, report.remaining, report.backend
        );
    }
    Ok(())
}

fn cmd_status(project: &Path, json: bool) -> Result<()> {
    let anatomy: AnatomyStore =
        crate::workspace::read_yaml(&anatomy_path(project)).unwrap_or(AnatomyStore {
            scanned: String::new(),
            files: vec![],
        });
    let learnings: LearningStore = crate::workspace::read_yaml(&learnings_path(project))
        .unwrap_or(LearningStore { learnings: vec![] });
    let bugs: BugStore =
        crate::workspace::read_yaml(&bugs_path(project)).unwrap_or(BugStore { bugs: vec![] });
    let corrections: CorrectionStore = crate::workspace::read_yaml(&corrections_path(project))
        .unwrap_or(CorrectionStore {
            corrections: vec![],
        });

    let status = CtxStatus {
        total_files: anatomy.files.len(),
        total_tokens: anatomy.files.iter().map(|f| f.tokens).sum(),
        total_reads: anatomy.files.iter().map(|f| f.reads as u64).sum(),
        learnings_count: learnings.learnings.len(),
        bugs_open: bugs.bugs.iter().filter(|b| b.resolved.is_none()).count(),
        bugs_resolved: bugs.bugs.iter().filter(|b| b.resolved.is_some()).count(),
        corrections_count: corrections.corrections.len(),
        last_scan: anatomy.scanned,
    };

    if json {
        json_ok(&status);
    } else {
        println!(
            "  files: {}  tokens: ~{}k",
            status.total_files,
            status.total_tokens / 1000
        );
        println!(
            "  reads: {}  learnings: {}",
            status.total_reads, status.learnings_count
        );
        println!(
            "  bugs: {} open / {} resolved",
            status.bugs_open, status.bugs_resolved
        );
        println!("  corrections: {}", status.corrections_count);
        if !status.last_scan.is_empty() {
            println!("  last scan: {}", status.last_scan);
        }
    }
    Ok(())
}

fn cmd_describe(project: &Path, file: &str, description: &str) -> Result<()> {
    let path = anatomy_path(project);
    let mut store: AnatomyStore = crate::workspace::read_yaml(&path).unwrap_or(AnatomyStore {
        scanned: String::new(),
        files: vec![],
    });

    let entry = store.files.iter_mut().find(|f| f.path == file);
    if let Some(entry) = entry {
        entry.description = Some(description.to_string());
        entry.desc_source = Some(DescSource::Agent);
        crate::workspace::write_yaml(&path, &store)?;

        // Also update the per-directory anatomy TSV file if one exists
        if let Some(slash_pos) = file.rfind('/') {
            let dir = &file[..slash_pos];
            let filename = format!("{}.tsv", dir.replace('/', "--"));
            let dir_file_path = crate::workspace::root(project)
                .join("ctx/anatomy")
                .join(&filename);
            if dir_file_path.exists() {
                let content = std::fs::read_to_string(&dir_file_path)
                    .with_context(|| format!("read {}", dir_file_path.display()))?;
                let mut new_lines: Vec<String> = Vec::new();
                let mut found = false;
                for line in content.lines() {
                    // Skip comment lines and header row unchanged
                    if line.starts_with('#') || line.starts_with("path\t") {
                        new_lines.push(line.to_string());
                        continue;
                    }
                    let mut cols: Vec<&str> = line.splitn(4, '\t').collect();
                    if !cols.is_empty() && cols[0] == file {
                        // Ensure we have at least 4 columns
                        while cols.len() < 4 {
                            cols.push("");
                        }
                        let safe_desc = description.replace('\t', "  ");
                        new_lines.push(format!(
                            "{}\t{}\t{}\t{}",
                            cols[0], cols[1], cols[2], safe_desc
                        ));
                        found = true;
                    } else {
                        new_lines.push(line.to_string());
                    }
                }
                if found {
                    let mut out = new_lines.join("\n");
                    if !out.ends_with('\n') {
                        out.push('\n');
                    }
                    let tmp = dir_file_path.with_extension("tsv.tmp");
                    std::fs::write(&tmp, &out)
                        .with_context(|| format!("write {}", tmp.display()))?;
                    std::fs::rename(&tmp, &dir_file_path)
                        .with_context(|| format!("rename to {}", dir_file_path.display()))?;
                }
            }
        }

        println!("  ✓ updated description for {file}");
    } else {
        bail!("file {file} not found in anatomy - run `kazam ctx scan` first");
    }
    Ok(())
}

fn cmd_learn(project: &Path, text: String, category: &str, json: bool) -> Result<()> {
    crate::workspace::ensure(project)?;
    let cat: LearningCategory = category.parse().map_err(|e: String| anyhow::anyhow!(e))?;
    let learning = Learning {
        id: crate::id::generate(),
        text: text.clone(),
        category: cat,
        created: now(),
    };

    let path = learnings_path(project);
    let mut store: LearningStore =
        crate::workspace::read_yaml(&path).unwrap_or(LearningStore { learnings: vec![] });
    store.learnings.push(learning.clone());
    crate::workspace::write_yaml(&path, &store)?;

    if json {
        json_ok(&learning);
    } else {
        println!("  ✓ learned [{}]: {text}", cat.label());
    }
    Ok(())
}

fn cmd_learnings(project: &Path, json: bool) -> Result<()> {
    let store: LearningStore = crate::workspace::read_yaml(&learnings_path(project))
        .unwrap_or(LearningStore { learnings: vec![] });

    if json {
        json_ok(&store.learnings);
    } else if store.learnings.is_empty() {
        println!("  no learnings recorded");
    } else {
        for l in &store.learnings {
            println!("  [{}] {} - {}", l.category.label(), l.id, l.text);
        }
    }
    Ok(())
}

fn cmd_bug(project: &Path, symptom: String, file: Option<String>, json: bool) -> Result<()> {
    crate::workspace::ensure(project)?;
    let bug = BugEntry {
        id: crate::id::generate(),
        symptom: symptom.clone(),
        file_path: file,
        resolution: None,
        created: now(),
        resolved: None,
    };

    let path = bugs_path(project);
    let mut store: BugStore =
        crate::workspace::read_yaml(&path).unwrap_or(BugStore { bugs: vec![] });
    store.bugs.push(bug.clone());
    crate::workspace::write_yaml(&path, &store)?;

    if json {
        json_ok(&bug);
    } else {
        println!("  ✓ bug {} recorded: {symptom}", bug.id);
    }
    Ok(())
}

fn cmd_bugs(project: &Path, file: Option<String>, json: bool) -> Result<()> {
    let store: BugStore =
        crate::workspace::read_yaml(&bugs_path(project)).unwrap_or(BugStore { bugs: vec![] });

    let bugs: Vec<&BugEntry> = if let Some(ref f) = file {
        store
            .bugs
            .iter()
            .filter(|b| b.file_path.as_deref() == Some(f.as_str()))
            .collect()
    } else {
        store.bugs.iter().collect()
    };

    if json {
        json_ok(&bugs);
    } else if bugs.is_empty() {
        println!("  no bugs recorded");
    } else {
        for b in &bugs {
            let status = if b.resolved.is_some() { "✓" } else { "○" };
            let file_str = b
                .file_path
                .as_deref()
                .map(|f| format!(" [{f}]"))
                .unwrap_or_default();
            println!("  {status} {}{file_str} - {}", b.id, b.symptom);
            if let Some(ref fix) = b.resolution {
                println!("    fix: {fix}");
            }
        }
    }
    Ok(())
}

fn cmd_correction(
    project: &Path,
    mistake: String,
    correction: String,
    file: Option<String>,
    json: bool,
) -> Result<()> {
    crate::workspace::ensure(project)?;
    let entry = Correction {
        id: crate::id::generate(),
        mistake: mistake.clone(),
        correction: correction.clone(),
        file_path: file,
        created: now(),
    };

    let path = corrections_path(project);
    let mut store: CorrectionStore =
        crate::workspace::read_yaml(&path).unwrap_or(CorrectionStore {
            corrections: vec![],
        });
    store.corrections.push(entry.clone());
    crate::workspace::write_yaml(&path, &store)?;

    if json {
        json_ok(&entry);
    } else {
        println!("  ✓ correction {} recorded: {mistake}", entry.id);
    }
    Ok(())
}

fn cmd_corrections(project: &Path, json: bool) -> Result<()> {
    let store: CorrectionStore =
        crate::workspace::read_yaml(&corrections_path(project)).unwrap_or(CorrectionStore {
            corrections: vec![],
        });

    if json {
        json_ok(&store.corrections);
    } else if store.corrections.is_empty() {
        println!("  no corrections recorded");
    } else {
        for c in &store.corrections {
            let file_str = c
                .file_path
                .as_deref()
                .map(|f| format!(" [{f}]"))
                .unwrap_or_default();
            println!("  {} {}{file_str}", c.id, c.mistake);
            println!("    → {}", c.correction);
        }
    }
    Ok(())
}

fn cmd_consolidate(project: &Path, days: u32, json: bool) -> Result<()> {
    let cutoff = chrono::Local::now() - chrono::Duration::days(days as i64);
    let cutoff_str = cutoff.to_rfc3339();

    // Clean resolved bugs older than cutoff
    let bugs_p = bugs_path(project);
    let mut bugs: BugStore =
        crate::workspace::read_yaml(&bugs_p).unwrap_or(BugStore { bugs: vec![] });
    let before_bugs = bugs.bugs.len();
    bugs.bugs.retain(|b| {
        b.resolved
            .as_ref()
            .is_none_or(|r| r.as_str() > cutoff_str.as_str())
    });
    let removed_bugs = before_bugs - bugs.bugs.len();
    crate::workspace::write_yaml(&bugs_p, &bugs)?;

    // Deduplicate learnings
    let learn_p = learnings_path(project);
    let mut learnings: LearningStore =
        crate::workspace::read_yaml(&learn_p).unwrap_or(LearningStore { learnings: vec![] });
    let before_learn = learnings.learnings.len();
    let mut seen = std::collections::HashSet::new();
    learnings.learnings.retain(|l| seen.insert(l.text.clone()));
    let deduped_learn = before_learn - learnings.learnings.len();
    crate::workspace::write_yaml(&learn_p, &learnings)?;

    if json {
        json_ok(&serde_json::json!({
            "removed_bugs": removed_bugs,
            "deduped_learnings": deduped_learn,
        }));
    } else {
        println!(
            "  ✓ consolidated: removed {removed_bugs} resolved bugs, deduped {deduped_learn} learnings"
        );
    }
    Ok(())
}

fn cmd_resolve(project: &Path, id: &str, fix: &str, json: bool) -> Result<()> {
    let path = bugs_path(project);
    let mut store: BugStore =
        crate::workspace::read_yaml(&path).unwrap_or(BugStore { bugs: vec![] });

    let bug = store.bugs.iter_mut().find(|b| b.id == id);
    let Some(bug) = bug else {
        if json {
            json_err(&format!("bug {id} not found"));
        } else {
            bail!("bug {id} not found");
        }
        return Ok(());
    };

    bug.resolution = Some(fix.to_string());
    bug.resolved = Some(now());
    let bug_out = bug.clone();
    crate::workspace::write_yaml(&path, &store)?;

    if json {
        json_ok(&bug_out);
    } else {
        println!("  ✓ resolved {id}: {fix}");
    }
    Ok(())
}