llman 0.0.69

A tool for managing LLM application rules(prompts) ...
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
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
use crate::sdd::shared::constants::LLMANSPEC_DIR_NAME;
use crate::sdd::shared::discovery::{extract_archived_change_id, list_specs, resolve_change_dir};
use crate::sdd::shared::tasks;
use crate::sdd::spec::validation::{ChangeStage, determine_stage};
use anyhow::{Result, anyhow};
use serde::Serialize;
use std::path::Path;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Format {
    Toon,
    Json,
}

#[derive(Debug)]
pub struct StatusArgs {
    pub target: Option<String>,
    pub json: bool,
    pub format: Option<String>,
}

impl StatusArgs {
    fn resolved_format(&self) -> Format {
        if self.json {
            return Format::Json;
        }
        match self.format.as_deref() {
            Some("json") => Format::Json,
            Some("toon") | None => Format::Toon,
            // Invalid format is caught in run() before resolved_format() is called
            Some(_) => Format::Toon,
        }
    }
}

#[derive(Debug, Serialize)]
struct StatusJson {
    #[serde(rename = "activeChanges")]
    active_changes: usize,
    draft: usize,
    designed: usize,
    full: usize,
    #[serde(rename = "pendingValidation")]
    pending_validation: usize,
    specs: usize,
}

#[derive(Debug, Serialize)]
struct SingleChangeJson {
    change: String,
    stage: String,
    priority: String,
    #[serde(rename = "completedTasks")]
    completed_tasks: usize,
    #[serde(rename = "totalTasks")]
    total_tasks: usize,
    #[serde(rename = "nextAction")]
    next_action: String,
    #[serde(rename = "specsLanded")]
    specs_landed: bool,
    #[serde(rename = "skipSpecsLanding")]
    skip_specs_landing: bool,
    #[serde(rename = "readyToImplement")]
    ready_to_implement: bool,
    /// r112: true when the target was resolved via a prefix match.
    #[serde(rename = "matchedViaPrefix")]
    matched_via_prefix: bool,
}

// ── Target resolution ──

#[derive(Clone)]
struct ChangeInfo {
    name: String,
    dir_name: String, // full directory name (for archives: with date prefix)
    is_archived: bool,
    stage: ChangeStage,
    tasks_done: usize,
    tasks_total: usize,
    priority: usize, // 0 = no prefix, otherwise parsed from c<N>-
    specs_landed: bool,
    skip_specs_landing: bool,
    ready_to_implement: bool,
}

fn extract_priority(dir_name: &str) -> usize {
    // Look for c<N>- prefix
    if dir_name.starts_with('c') || dir_name.starts_with('C') {
        let rest = &dir_name[1..];
        let num_end = rest.chars().take_while(|c| c.is_ascii_digit()).count();
        if num_end > 0
            && rest.as_bytes().get(num_end) == Some(&b'-')
            && let Ok(n) = rest[..num_end].parse::<usize>()
        {
            return n;
        }
    }
    0
}

/// Collect all active changes with their metadata.
/// Propagates discovery errors (r127 duplicate leaf ids, etc.).
fn collect_active_changes(root: &Path) -> Result<Vec<ChangeInfo>> {
    let mut result = Vec::new();

    for loc in crate::sdd::shared::discovery::discover_changes(root)? {
        let change_dir = loc.abs_dir(root);
        let stage = determine_stage(&change_dir);
        let (done, total) = parse_task_counts(&change_dir);
        let landing = crate::sdd::change::specs_landing::evaluate_specs_landing(root, &change_dir);
        result.push(ChangeInfo {
            dir_name: loc.id.clone(),
            name: loc.id.clone(),
            is_archived: false,
            stage,
            tasks_done: done,
            tasks_total: total,
            priority: extract_priority(&loc.id),
            specs_landed: landing.specs_landed,
            skip_specs_landing: landing.skip_specs_landing,
            ready_to_implement: landing.ready_to_implement,
        });
    }

    Ok(result)
}

/// Collect all archived changes with their metadata
fn collect_archived_changes(root: &Path) -> Vec<ChangeInfo> {
    let archive_dir = root
        .join(LLMANSPEC_DIR_NAME)
        .join("changes")
        .join("archive");
    let mut result = Vec::new();

    let entries = match std::fs::read_dir(&archive_dir) {
        Ok(e) => e,
        Err(_) => return result,
    };

    for entry in entries.flatten() {
        if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
            continue;
        }
        let dir_name = entry.file_name().to_string_lossy().to_string();
        if dir_name.starts_with('.') {
            continue;
        }
        // Extract the change id (after date prefix)
        let name = extract_archived_change_id(&dir_name).unwrap_or_else(|| dir_name.clone());
        let priority = extract_priority(&name);
        let change_dir = entry.path();
        // For archived changes, we still check stage from the artifacts present
        let stage = determine_stage(&change_dir);
        let (done, total) = parse_task_counts(&change_dir);
        result.push(ChangeInfo {
            dir_name,
            name,
            is_archived: true,
            stage,
            tasks_done: done,
            tasks_total: total,
            priority,
            specs_landed: false,
            skip_specs_landing: false,
            ready_to_implement: false,
        });
    }

    result
}

fn parse_task_counts(change_dir: &Path) -> (usize, usize) {
    let tasks_path = change_dir.join("tasks.md");
    if let Ok(Some(report)) = tasks::parse_tasks_file(&tasks_path) {
        (report.completed, report.total())
    } else {
        (0, 0)
    }
}

/// Resolve TARGET to either a unique ChangeInfo or a list of matches.
enum TargetResult {
    /// `via_prefix` is true when the target was a unique prefix rather than an
    /// exact match (used for the r112 hint + JSON `matchedViaPrefix` field).
    Single {
        info: ChangeInfo,
        via_prefix: bool,
    },
    Multiple(Vec<ChangeInfo>),
    None,
}

fn resolve_target(root: &Path, target: &str) -> Result<TargetResult> {
    use crate::sdd::shared::match_utils::{PrefixOutcome, prefix_resolve};

    let active = collect_active_changes(root)?;
    let archived = collect_archived_changes(root);

    // Resolution shares the same "exact > prefix" core as discovery::resolve_change_id
    // (cli spec r112). Status additionally treats multi-match as a legitimate
    // Multiple result rather than an error, and preserves dir_name exact match
    // for archived entries (full date-prefixed name).

    // Helper: map a matched id back to its ChangeInfo(s). Archived entries match
    // on either the change-id portion (name) or the full dir_name (with date).
    fn collect_matches(pool: &[ChangeInfo], target: &str, matched_ids: &[&str]) -> Vec<ChangeInfo> {
        pool.iter()
            .filter(|c| {
                matched_ids.contains(&c.name.as_str())
                    || matched_ids.contains(&c.dir_name.as_str())
                    // exact dir_name match (e.g. full archived date-prefixed name)
                    || c.dir_name == target
            })
            .cloned()
            .collect()
    }

    // 1) Exact / prefix match against active changes (active takes priority)
    let active_ids: Vec<String> = active.iter().map(|c| c.name.clone()).collect();
    match prefix_resolve(target, &active_ids) {
        PrefixOutcome::Single { id, via_prefix } => {
            if let Some(ci) = active.iter().find(|c| c.name == id || c.dir_name == target) {
                // `via_prefix` is authoritative from prefix_resolve; a dir_name
                // exact match (c.dir_name == target) is never a prefix match.
                let via_prefix = via_prefix && ci.dir_name != target;
                return Ok(TargetResult::Single {
                    info: ci.clone(),
                    via_prefix,
                });
            }
        }
        PrefixOutcome::Multiple(ids) => {
            let mut m = collect_matches(&active, target, &ids);
            m.sort_by_key(|c| c.priority);
            return Ok(TargetResult::Multiple(m));
        }
        PrefixOutcome::None => {}
    }

    // 2) Exact / prefix match against archived changes
    let archived_ids: Vec<String> = archived.iter().map(|c| c.name.clone()).collect();
    match prefix_resolve(target, &archived_ids) {
        PrefixOutcome::Single { id, via_prefix } => {
            if let Some(ci) = archived
                .iter()
                .find(|c| c.name == id || c.dir_name == target)
            {
                let via_prefix = via_prefix && ci.dir_name != target;
                return Ok(TargetResult::Single {
                    info: ci.clone(),
                    via_prefix,
                });
            }
        }
        PrefixOutcome::Multiple(ids) => {
            let mut m = collect_matches(&archived, target, &ids);
            m.sort_by_key(|c| c.priority);
            return Ok(TargetResult::Multiple(m));
        }
        PrefixOutcome::None => {}
    }

    // 3) No match — per cli spec r112, MUST NOT fall back to substring contains.
    Ok(TargetResult::None)
}

// ── TOON output builders ──

fn toon_project_overview(changes: &[ChangeInfo], specs_count: usize) -> String {
    let mut out = String::new();
    out.push_str("kind: llman.sdd.status\n");
    out.push_str(&format!(
        "counts{{active,specs}}:\n  {},{}",
        changes.len(),
        specs_count
    ));
    out.push('\n');

    if !changes.is_empty() {
        out.push_str(&format!(
            "changes[{}]{{name,stage,tasks,next}}:\n",
            changes.len()
        ));
        for c in changes {
            let stage_str = match c.stage {
                ChangeStage::Draft => "draft",
                ChangeStage::Designed => "design",
                ChangeStage::Full => "full",
            };
            let tasks_str = if c.tasks_total > 0 {
                format!("{}/{}", c.tasks_done, c.tasks_total)
            } else {
                "0/0".to_string()
            };
            let next = derive_next_action(c);
            // Quote values that may contain special chars
            let name_quoted = maybe_quote(&c.name);
            let next_quoted = if next.contains(',') || next.contains('"') {
                format!("\"{}\"", next.replace('"', r#"\""#))
            } else if next.is_empty() {
                "".to_string()
            } else {
                next
            };
            out.push_str(&format!(
                "  {},{},{},{},{}",
                name_quoted,
                stage_str,
                tasks_str,
                if c.is_archived { "archived" } else { "active" },
                next_quoted
            ));
            out.push('\n');
        }
    }
    out
}

fn toon_single_change(ci: &ChangeInfo, root: &Path) -> String {
    let mut out = String::new();
    out.push_str("kind: llman.sdd.status\n");

    let stage_str = match ci.stage {
        ChangeStage::Draft => "draft",
        ChangeStage::Designed => "design",
        ChangeStage::Full => "full",
    };

    out.push_str(&format!(
        "change{{name,stage,priority,tasks}}:\n  {},{},{},{}",
        maybe_quote(&ci.name),
        if ci.is_archived {
            "archived"
        } else {
            stage_str
        },
        if ci.priority > 0 {
            format!("c{}", ci.priority)
        } else {
            "-".to_string()
        },
        if ci.tasks_total > 0 {
            format!("{}/{}", ci.tasks_done, ci.tasks_total)
        } else {
            "0/0".to_string()
        },
    ));
    out.push('\n');

    // Legacy archived-change delta-ops display was removed with the delta
    // format; archived changes render through the active branch below.
    // Active: show incomplete tasks
    let change_dir = match resolve_change_dir(root, &ci.dir_name) {
        Ok(p) => p,
        Err(_) => {
            return out;
        }
    };
    if let Ok(Some(report)) = tasks::parse_tasks_file(&change_dir.join("tasks.md")) {
        let incomplete: Vec<_> = report
            .items
            .iter()
            .filter(|t| matches!(t.status, tasks::TaskStatus::Pending))
            .collect();
        if !incomplete.is_empty() {
            out.push_str(&format!("tasks[{}]{{id,title,test}}:\n", incomplete.len()));
            for (i, task) in incomplete.iter().enumerate() {
                let task_id = format!("t{}", i + 1);
                // Try to extract a test command from the task text (look for backtick command)
                let test_cmd = extract_test_command(&task.text);
                out.push_str(&format!(
                    "  {},{},{}\n",
                    task_id,
                    maybe_quote(&task.text),
                    if test_cmd.is_empty() {
                        "".to_string()
                    } else {
                        maybe_quote(&test_cmd)
                    }
                ));
            }
        }
    }

    // next action
    let next = derive_next_action(ci);
    if !next.is_empty() {
        out.push_str(&format!("next: {}\n", maybe_quote(&next)));
    }

    out
}

fn toon_multiple_matches(matches: &[ChangeInfo]) -> String {
    let mut out = String::new();
    out.push_str("kind: llman.sdd.status\n");
    out.push_str(&format!("multiple_matches:\n  count: {}", matches.len()));
    out.push('\n');
    out.push_str(&format!(
        "changes[{}]{{name,type,tasks,priority}}:\n",
        matches.len()
    ));
    for c in matches {
        let tasks_str = if c.tasks_total > 0 {
            format!("{}/{}", c.tasks_done, c.tasks_total)
        } else {
            "0/0".to_string()
        };
        let typ = if c.is_archived { "archived" } else { "active" };
        out.push_str(&format!(
            "  {},{},{},{}\n",
            maybe_quote(&c.dir_name),
            typ,
            tasks_str,
            if c.priority > 0 {
                format!("c{}", c.priority)
            } else {
                "-".to_string()
            }
        ));
    }
    out
}

fn derive_next_action(ci: &ChangeInfo) -> String {
    if ci.is_archived {
        return String::new();
    }
    match ci.stage {
        ChangeStage::Draft => "propose".to_string(),
        ChangeStage::Designed => "start".to_string(),
        ChangeStage::Full => {
            if !ci.ready_to_implement {
                "land-specs".to_string()
            } else if ci.tasks_done < ci.tasks_total {
                format!("impl task {}", ci.tasks_done + 1)
            } else {
                "archive".to_string()
            }
        }
    }
}

fn extract_test_command(task_text: &str) -> String {
    // Look for backtick-wrapped commands in task text
    if let Some(start) = task_text.find('`') {
        let after = &task_text[start + 1..];
        if let Some(end) = after.find('`') {
            return after[..end].to_string();
        }
    }
    String::new()
}

fn maybe_quote(s: &str) -> String {
    if s.is_empty() {
        return "".to_string();
    }
    if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains(':') {
        format!("\"{}\"", s.replace('"', r#"\""#))
    } else {
        s.to_string()
    }
}

// ── JSON output builders ──

fn json_project_overview(changes: &[ChangeInfo], specs_count: usize) -> Result<()> {
    let mut draft = 0;
    let mut designed = 0;
    let mut full = 0;
    let mut pending_validation = 0;

    for c in changes {
        match c.stage {
            ChangeStage::Draft => draft += 1,
            ChangeStage::Designed => designed += 1,
            ChangeStage::Full => {
                full += 1;
                if c.tasks_done < c.tasks_total {
                    pending_validation += 1;
                }
            }
        }
    }

    let status = StatusJson {
        active_changes: changes.len(),
        draft,
        designed,
        full,
        pending_validation,
        specs: specs_count,
    };
    println!("{}", serde_json::to_string_pretty(&status)?);
    Ok(())
}

fn json_single_change(ci: &ChangeInfo, via_prefix: bool) -> Result<()> {
    let stage_str = match ci.stage {
        ChangeStage::Draft => "draft",
        ChangeStage::Designed => "designed",
        ChangeStage::Full => "full",
    };
    let next = derive_next_action(ci);

    if ci.is_archived {
        #[derive(Serialize)]
        struct ArchivedJsonOut {
            change: String,
            status: String,
            archived: bool,
            next_action: String,
            #[serde(rename = "matchedViaPrefix")]
            matched_via_prefix: bool,
        }
        let out = ArchivedJsonOut {
            change: ci.dir_name.clone(),
            status: stage_str.to_string(),
            archived: true,
            next_action: next,
            matched_via_prefix: via_prefix,
        };
        println!("{}", serde_json::to_string_pretty(&out)?);
    } else {
        let out = SingleChangeJson {
            change: ci.name.clone(),
            stage: stage_str.to_string(),
            priority: if ci.priority > 0 {
                format!("c{}", ci.priority)
            } else {
                "-".to_string()
            },
            completed_tasks: ci.tasks_done,
            total_tasks: ci.tasks_total,
            next_action: next,
            specs_landed: ci.specs_landed,
            skip_specs_landing: ci.skip_specs_landing,
            ready_to_implement: ci.ready_to_implement,
            matched_via_prefix: via_prefix,
        };
        println!("{}", serde_json::to_string_pretty(&out)?);
    }
    Ok(())
}

fn json_multiple_matches(matches: &[ChangeInfo]) -> Result<()> {
    #[derive(Serialize)]
    struct MatchItem {
        name: String,
        #[serde(rename = "type")]
        typ: String,
        tasks: String,
        priority: String,
    }
    #[derive(Serialize)]
    struct MultipleJson {
        count: usize,
        matches: Vec<MatchItem>,
    }

    let items: Vec<MatchItem> = matches
        .iter()
        .map(|c| MatchItem {
            name: c.dir_name.clone(),
            typ: if c.is_archived {
                "archived".to_string()
            } else {
                "active".to_string()
            },
            tasks: if c.tasks_total > 0 {
                format!("{}/{}", c.tasks_done, c.tasks_total)
            } else {
                "0/0".to_string()
            },
            priority: if c.priority > 0 {
                format!("c{}", c.priority)
            } else {
                "-".to_string()
            },
        })
        .collect();

    let out = MultipleJson {
        count: matches.len(),
        matches: items,
    };
    println!("{}", serde_json::to_string_pretty(&out)?);
    Ok(())
}

// ── Main entry ──

pub fn run(args: StatusArgs) -> Result<()> {
    let root = Path::new(".");
    let llmanspec_dir = root.join(LLMANSPEC_DIR_NAME);

    if !llmanspec_dir.exists() {
        return Err(anyhow!("llmanspec/ not found. Run `llman sdd init` first."));
    }

    // Validate format if explicitly provided
    if let Some(ref fmt) = args.format
        && fmt != "toon"
        && fmt != "json"
    {
        return Err(anyhow!("Invalid format '{}'. Supported: toon, json", fmt));
    }

    let format = args.resolved_format();

    match &args.target {
        None => {
            // Project-level overview
            let changes = collect_active_changes(root)?;
            let specs_count = list_specs(root).unwrap_or_default().len();
            match format {
                Format::Toon => print!("{}", toon_project_overview(&changes, specs_count)),
                Format::Json => json_project_overview(&changes, specs_count)?,
            }
        }
        Some(target) => {
            let resolved = resolve_target(root, target)?;
            match resolved {
                TargetResult::Single {
                    info: ci,
                    via_prefix,
                } => {
                    // r112: emit the "'input' -> 'resolved' (prefix match)" hint
                    // to stderr for human (TOON) output when the target was a
                    // prefix match. JSON carries the `matchedViaPrefix` field.
                    if via_prefix && format != Format::Json {
                        eprintln!(
                            "{}",
                            t!("sdd.prefix_match_hint", input = target, resolved = ci.name)
                        );
                    }
                    match format {
                        Format::Toon => print!("{}", toon_single_change(&ci, root)),
                        Format::Json => json_single_change(&ci, via_prefix)?,
                    }
                }
                TargetResult::Multiple(matches) => match format {
                    Format::Toon => print!("{}", toon_multiple_matches(&matches)),
                    Format::Json => json_multiple_matches(&matches)?,
                },
                TargetResult::None => {
                    let suggestions = suggest_similar_changes(root, target);
                    return Err(anyhow!(
                        "No change matches '{}'.{}",
                        target,
                        if suggestions.is_empty() {
                            String::new()
                        } else {
                            format!(" Did you mean: {}", suggestions.join(", "))
                        }
                    ));
                }
            }
        }
    }

    Ok(())
}

fn suggest_similar_changes(root: &Path, target: &str) -> Vec<String> {
    let Ok(active) = collect_active_changes(root) else {
        return Vec::new();
    };
    let archived = collect_archived_changes(root);
    let lower = target.to_lowercase();

    let mut names: Vec<String> = active
        .into_iter()
        .chain(archived)
        .map(|c| c.dir_name)
        .filter(|n| {
            let nl = n.to_lowercase();
            // Simple similarity: share at least 3 consecutive chars
            (0..nl.len().saturating_sub(2)).any(|i| {
                let sub = &nl[i..i + 3];
                lower.contains(sub)
            })
        })
        .collect();

    names.sort();
    names.truncate(5);
    names
}