agentstatedeveloper-cli 1.4.9

asd CLI — command-line interface for AgentStateDeveloper
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
//! `asd checklist <query>` — structured pre-edit checklist.
//!
//! Builds on `investigate` entry-point search and ledger invariants to produce
//! an action-oriented list: files to inspect, invariants to preserve, tests to
//! run, known hazards, and effects to verify.
//!
//! Default output is Markdown; pass `--json` for machine-readable JSON.

use std::collections::{HashSet, VecDeque};

use anyhow::Result;
use clap::Args;
use serde_json::{Value, json};

use agentstatedeveloper_core::{
    AsgEffectStore, AsgFeedbackStore, AsgIndexStore, AsgLedgerStore, EffectStore, Engine,
    FeedbackStore, FtsFilters, IndexStore, LedgerKind, LedgerStore, apply_feedback_adjustments,
    classify_layer_sym, derive_cold_hints, estimate_tokens, find_candidates, git_dirty_files,
    intent_focus, load_layer_overrides, parse_intent, parse_query, propose_test_path,
    resolve_scope, stale_warning, symbol_tier, trim_for_agent,
};

use crate::commands::graph::build_id_map;
use crate::config::Config;

#[derive(Debug, Args)]
pub struct ChecklistArgs {
    /// Natural-language or keyword query (same as `asd investigate`).
    pub query: String,

    /// Inject active task context to enrich the search query.
    /// When absent, CTXONE_PLAN / CTXONE_TASK env vars are read automatically.
    #[arg(long)]
    pub task_context: Option<String>,

    /// Number of top entry-point symbols to analyse (default: 10).
    #[arg(long, default_value = "10")]
    pub depth: usize,

    /// Filter by symbol kind.
    #[arg(long)]
    pub kind: Option<String>,

    /// Filter by language.
    #[arg(long)]
    pub language: Option<String>,

    /// Include test-file symbols as entry-point candidates.
    #[arg(long)]
    pub include_tests: bool,

    /// Suppress the stale-index warning.
    #[arg(long)]
    pub quiet: bool,

    /// Emit JSON instead of Markdown.
    #[arg(long)]
    pub json: bool,

    /// Adjust checklist framing for a specific intent.
    /// Values: bugfix, feature, refactor, test, architecture, ui.
    #[arg(long)]
    pub intent: Option<String>,

    /// Caller BFS depth for finding affected tests (default: 2).
    #[arg(long, default_value = "2")]
    pub test_depth: usize,

    /// Emit token-budgeted JSON for LLM consumption (implies --json).
    #[arg(long)]
    pub agent: bool,

    /// Token budget when --agent is set (default: 8000).
    #[arg(long, default_value = "8000")]
    pub agent_budget: usize,

    /// Comma-separated terms to exclude. Also supports inline minus-prefix
    /// syntax in the query, e.g. "drift playhead -sample -waveform".
    #[arg(long)]
    pub exclude: Option<String>,

    /// Comma-separated glob patterns to restrict results to specific paths.
    #[arg(long)]
    pub paths: Option<String>,

    /// Named scope alias from .asd/scopes.toml, e.g. --scope drift-pad.
    #[arg(long)]
    pub scope: Option<String>,
}

pub fn run(cfg: &Config, args: ChecklistArgs) -> Result<()> {
    if !args.quiet {
        if let Some(warn) = stale_warning(&cfg.db_path, 3600) {
            eprintln!("{warn}");
        }
    }
    let intent = args.intent.as_deref().and_then(parse_intent).unwrap_or("");
    let layer_overrides = load_layer_overrides(&cfg.db_path);
    let engine = Engine::open_sqlite(&cfg.db_path)?;
    let index_store = AsgIndexStore::from_engine(&engine);
    let ledger_store = AsgLedgerStore::from_engine(&engine);
    let effect_store = AsgEffectStore::from_engine(&engine);
    let id_map = build_id_map(&engine);

    let (mut tokens, mut exclusions) = parse_query(&args.query);
    if let Some(ref excl) = args.exclude {
        for term in excl
            .split(',')
            .map(|t| t.trim().to_lowercase())
            .filter(|t| !t.is_empty())
        {
            exclusions.push(term);
        }
    }
    // Auto-load CTX context from env vars if --task-context not provided.
    let auto_ctx_plan = std::env::var("CTXONE_PLAN").ok().filter(|s| !s.is_empty());
    let auto_ctx_task = std::env::var("CTXONE_TASK").ok().filter(|s| !s.is_empty());
    let ctx_text = args.task_context.clone().or_else(|| {
        let parts: Vec<&str> = [auto_ctx_plan.as_deref(), auto_ctx_task.as_deref()]
            .iter()
            .filter_map(|x| *x)
            .collect();
        if parts.is_empty() {
            None
        } else {
            Some(parts.join(" "))
        }
    });
    if let Some(ref ctx) = ctx_text {
        let (ctx_tokens, _) = parse_query(ctx);
        for t in ctx_tokens {
            if !tokens.contains(&t) {
                tokens.push(t);
            }
        }
    }
    if tokens.is_empty() {
        if args.json {
            println!("{}", json!({"query": args.query, "items": {}}));
        } else {
            println!(
                "# Pre-edit checklist: {}\n\nNo matching symbols.",
                args.query
            );
        }
        return Ok(());
    }

    let mut paths_filter: Vec<String> = Vec::new();
    if let Some(ref scope) = args.scope {
        paths_filter.extend(resolve_scope(scope, &cfg.db_path));
    }
    if let Some(ref paths) = args.paths {
        paths_filter.extend(
            paths
                .split(',')
                .map(|p| p.trim().to_string())
                .filter(|p| !p.is_empty()),
        );
    }
    let filters = FtsFilters {
        kind: args.kind.as_deref().map(|k| k.to_lowercase()),
        language: args.language.as_deref().map(|l| l.to_lowercase()),
        include_tests: args.include_tests,
        tests_only: false,
        exclude_terms: exclusions,
        paths_filter,
        exclude_paths: Vec::new(),
        exclude_languages: Vec::new(),
    };

    let mut candidates = find_candidates(
        &engine,
        &args.query,
        &tokens,
        &filters,
        &ledger_store,
        &index_store,
        args.depth,
    );

    // Apply durable feedback adjustments (Useful/Noisy/WrongLayer verdicts).
    let feedback_store = AsgFeedbackStore::from_engine(&engine);
    let feedback_verdicts = feedback_store
        .flat_verdicts(&engine.ref_name)
        .unwrap_or_default();
    apply_feedback_adjustments(
        &engine,
        &index_store,
        &args.query,
        &mut candidates,
        &feedback_verdicts,
    );

    // --- Files to inspect -------------------------------------------------
    let mut files_to_inspect: Vec<Value> = Vec::new();
    let mut seen_files: HashSet<String> = HashSet::new();

    // --- Invariants, hazards, effects, notes ------------------------------
    let mut invariants: Vec<Value> = Vec::new();
    let mut hazards: Vec<Value> = Vec::new();
    let mut effects_list: Vec<Value> = Vec::new();
    let mut seen_inv: HashSet<String> = HashSet::new();

    // --- Affected tests (BFS from each entry point) -----------------------
    let mut test_rows: Vec<Value> = Vec::new();
    let mut seen_tests: HashSet<String> = HashSet::new();

    for (_score, qname) in &candidates {
        let sym = match index_store.get_symbol_by_qname(&engine.ref_name, qname) {
            Ok(Some(s)) => s,
            _ => continue,
        };
        let tier = symbol_tier(&sym.file);
        let layer = classify_layer_sym(&sym.file, &sym.qname, tier, &layer_overrides);

        // Files to inspect.
        if seen_files.insert(sym.file.clone()) {
            files_to_inspect.push(json!({
                "file": sym.file,
                "qname": sym.qname,
                "layer": layer,
                "line": sym.start.line,
            }));
        }

        // Ledger entries.
        let entries = ledger_store
            .list_entries(&engine.ref_name, &sym.symbol_id)
            .unwrap_or_default();
        for entry in &entries {
            let key = entry.summary.clone();
            match entry.kind {
                LedgerKind::Invariant => {
                    if seen_inv.insert(key) {
                        invariants.push(json!({
                            "summary": entry.summary,
                            "source": sym.qname,
                            "body": entry.body,
                        }));
                    }
                }
                LedgerKind::Hazard => {
                    hazards.push(json!({
                        "summary": entry.summary,
                        "source": sym.qname,
                        "body": entry.body,
                    }));
                }
                _ => {}
            }
        }

        // Effects.
        if let Ok(Some(decl)) = effect_store.get_effects(&engine.ref_name, &sym.symbol_id) {
            for eff in &decl.declared {
                let key = format!("{:?}", eff.effect);
                effects_list.push(json!({
                    "category": key,
                    "source": sym.qname,
                }));
            }
        }

        // Affected tests via BFS.
        let mut visited: HashSet<String> = HashSet::new();
        let mut queue: VecDeque<(String, usize)> = VecDeque::new();
        visited.insert(sym.symbol_id.clone());
        queue.push_back((sym.symbol_id.clone(), 0));
        while let Some((sid, depth)) = queue.pop_front() {
            if depth >= args.test_depth {
                continue;
            }
            let callers = index_store
                .get_callers(&engine.ref_name, &sid)
                .unwrap_or_default();
            for caller_id in callers {
                if visited.contains(&caller_id) {
                    continue;
                }
                visited.insert(caller_id.clone());
                if let Some(s) = id_map.get(&caller_id) {
                    if symbol_tier(&s.file) == 2 && seen_tests.insert(s.qname.clone()) {
                        test_rows.push(json!({
                            "qname": s.qname,
                            "file": s.file,
                            "line": s.start.line,
                        }));
                    }
                    if depth + 1 < args.test_depth {
                        queue.push_back((caller_id, depth + 1));
                    }
                }
            }
        }
    }

    // Deduplicate effects by category+source.
    effects_list.dedup_by(|a, b| {
        a.get("category").and_then(Value::as_str) == b.get("category").and_then(Value::as_str)
            && a.get("source").and_then(Value::as_str) == b.get("source").and_then(Value::as_str)
    });

    let focus = intent_focus(intent);

    // --- Staleness + test-gap -------------------------------------------
    let dirty = git_dirty_files();
    let stale_symbols: Vec<&str> = files_to_inspect
        .iter()
        .filter_map(|v| v.get("file").and_then(Value::as_str))
        .filter(|f| dirty.contains(*f))
        .collect();
    let test_gap = test_rows.is_empty();
    let proposed_test_path = test_gap
        .then(|| {
            files_to_inspect
                .first()
                .and_then(|v| v.get("file").and_then(Value::as_str))
                .map(propose_test_path)
        })
        .flatten();
    let suggested_test_coverage: Vec<String> = if test_gap {
        let mut hints: Vec<String> = invariants
            .iter()
            .filter_map(|inv| inv.get("summary").and_then(Value::as_str))
            .map(|s| s.to_string())
            .collect();
        for eff in &effects_list {
            if let Some(cat) = eff.get("category").and_then(Value::as_str) {
                let hint = format!("verify {} after change", cat.to_lowercase());
                if !hints.contains(&hint) {
                    hints.push(hint);
                }
            }
        }
        // Cold-start fallback: if no recorded invariants, derive hints from
        // the top candidate symbol's own name, signature, and doc comment.
        if invariants.is_empty() {
            if let Some((_, qname)) = candidates.first() {
                if let Ok(Some(sym)) = index_store.get_symbol_by_qname(&engine.ref_name, qname) {
                    for h in
                        derive_cold_hints(&sym.qname, sym.signature.as_deref(), sym.doc.as_deref())
                    {
                        if !hints.contains(&h) {
                            hints.push(h);
                        }
                    }
                }
            }
        }
        hints
    } else {
        vec![]
    };

    // Scenario tests: invariants with constraint language are directly actionable
    // test scenarios and are emitted regardless of test_gap.
    const CONSTRAINT_WORDS: &[&str] = &[
        "must",
        "never",
        "shall",
        "always",
        "only",
        "cannot",
        "no ",
        "not ",
        "require",
        "ensure",
        "prevent",
        "guarantee",
        "invariant",
        "forbidden",
    ];
    let scenario_tests: Vec<String> = invariants
        .iter()
        .filter_map(|inv| inv.get("summary").and_then(Value::as_str))
        .filter(|s| {
            let sl = s.to_lowercase();
            CONSTRAINT_WORDS.iter().any(|w| sl.contains(w))
        })
        .map(|s| s.to_string())
        .collect();

    // T-004: task-close proof suggestions — what to record in the ledger before
    // closing the task that produced this checklist.
    let task_close_suggestions: Vec<Value> = {
        let mut suggestions: Vec<Value> = Vec::new();
        // For each invariant: suggest confirming it still holds — phrased naturally.
        for inv in invariants.iter().take(4) {
            let source = inv.get("source").and_then(Value::as_str).unwrap_or("");
            let summary = inv.get("summary").and_then(Value::as_str).unwrap_or("");
            if !source.is_empty() && !summary.is_empty() {
                // Trim leading constraint words for a more natural read.
                let core = summary.trim_start_matches(|c: char| !c.is_alphabetic());
                let core = ["must ", "never ", "shall ", "always ", "cannot ", "only "]
                    .iter()
                    .fold(core, |s, prefix| s.strip_prefix(prefix).unwrap_or(s));
                suggestions.push(json!({
                    "action": "ledger_append",
                    "kind": "proof",
                    "symbol": source,
                    "suggested_summary": format!("confirm {} still holds after this change", core.trim()),
                }));
            }
        }
        // For hazards: note whether the hazard was avoided.
        for h in hazards.iter().take(2) {
            let source = h.get("source").and_then(Value::as_str).unwrap_or("");
            let summary = h.get("summary").and_then(Value::as_str).unwrap_or("");
            if !source.is_empty() && !summary.is_empty() {
                suggestions.push(json!({
                    "action": "ledger_append",
                    "kind": "validation_scenario",
                    "symbol": source,
                    "suggested_summary": format!("check that '{}' was not introduced by this change", summary),
                }));
            }
        }
        // For effects: confirm the side-effect behaviour is still correct.
        for eff in effects_list.iter().take(2) {
            let source = eff.get("source").and_then(Value::as_str).unwrap_or("");
            let cat = eff.get("category").and_then(Value::as_str).unwrap_or("");
            if !source.is_empty() && !cat.is_empty() {
                suggestions.push(json!({
                    "action": "ledger_append",
                    "kind": "proof",
                    "symbol": source,
                    "suggested_summary": format!("{} behaviour is still correct after this change", cat.to_lowercase()),
                }));
            }
        }
        suggestions
    };

    if args.agent || args.json {
        let ctx_context_val = match (auto_ctx_plan.as_deref(), auto_ctx_task.as_deref()) {
            (None, None) => Value::Null,
            _ => json!({ "plan": auto_ctx_plan, "task": auto_ctx_task }),
        };
        let out = json!({
            "query": args.query,
            "ctx_context": ctx_context_val,
            "intent": if intent.is_empty() { Value::Null } else { json!(intent) },
            "focus": if focus.is_empty() { Value::Null } else { json!(focus) },
            "files_to_inspect": files_to_inspect,
            "invariants_to_preserve": invariants,
            "tests_to_run": test_rows,
            "test_gap": test_gap,
            "proposed_test_path": proposed_test_path,
            "suggested_test_coverage": suggested_test_coverage,
            "scenario_tests": scenario_tests,
            "stale_symbols": stale_symbols,
            "known_hazards": hazards,
            "effects_to_verify": effects_list,
            "task_close_suggestions": task_close_suggestions,
        });
        let out = if args.agent {
            let max_list = (args.agent_budget / 500).max(3).min(20);
            let trimmed = trim_for_agent(&out, max_list);
            let json_str = serde_json::to_string_pretty(&trimmed)?;
            let token_est = estimate_tokens(&json_str);
            let mut v = trimmed;
            if let Some(obj) = v.as_object_mut() {
                obj.insert("token_estimate".into(), json!(token_est));
            }
            v
        } else {
            out
        };
        println!("{}", serde_json::to_string_pretty(&out)?);
    } else {
        print_markdown(
            &args.query,
            intent,
            focus,
            &files_to_inspect,
            &invariants,
            &test_rows,
            test_gap,
            proposed_test_path.as_deref(),
            &suggested_test_coverage,
            &stale_symbols,
            &hazards,
            &effects_list,
            &task_close_suggestions,
        );
    }
    Ok(())
}

fn print_markdown(
    query: &str,
    intent: &str,
    focus: &str,
    files: &[Value],
    invariants: &[Value],
    tests: &[Value],
    test_gap: bool,
    proposed_test_path: Option<&str>,
    suggested_coverage: &[String],
    stale_symbols: &[&str],
    hazards: &[Value],
    effects: &[Value],
    task_close_suggestions: &[Value],
) {
    println!("# Pre-edit checklist: {query}");
    if !intent.is_empty() {
        println!("\n**Intent:** {intent}  ");
        println!("**Focus:** {focus}");
    }

    println!("\n## Files to inspect");
    if files.is_empty() {
        println!("_(no entry points found)_");
    } else {
        for f in files {
            let file = f.get("file").and_then(Value::as_str).unwrap_or("");
            let qname = f.get("qname").and_then(Value::as_str).unwrap_or("");
            let layer = f.get("layer").and_then(Value::as_str).unwrap_or("");
            let line = f.get("line").and_then(Value::as_u64).unwrap_or(0);
            println!("- [ ] `{file}:{line}` — `{qname}` [{layer}]");
        }
    }

    println!("\n## Invariants to preserve");
    if invariants.is_empty() {
        println!("_(no invariants recorded — add with `asd ledger append --kind invariant`)_");
    } else {
        for inv in invariants {
            let summary = inv.get("summary").and_then(Value::as_str).unwrap_or("");
            let source = inv.get("source").and_then(Value::as_str).unwrap_or("");
            println!("- [ ] {summary} _(from `{source}`)_");
        }
    }

    println!("\n## Tests to run");
    if tests.is_empty() {
        if test_gap {
            println!("_(no test callers found — test gap detected)_");
            if let Some(path) = proposed_test_path {
                println!("_Suggested test file: `{path}`_");
            }
            if !suggested_coverage.is_empty() {
                println!("\n_Suggested behaviours to cover:_");
                for hint in suggested_coverage {
                    println!("- [ ] {hint}");
                }
            }
        } else {
            println!("_(no test callers found within BFS depth)_");
        }
    } else {
        for t in tests {
            let qname = t.get("qname").and_then(Value::as_str).unwrap_or("");
            let file = t.get("file").and_then(Value::as_str).unwrap_or("");
            println!("- [ ] `{qname}` — {file}");
        }
    }

    if !stale_symbols.is_empty() {
        println!("\n## Staleness warning");
        println!(
            "_The following files are modified since the last index — symbol ranges may be stale:_"
        );
        for f in stale_symbols {
            println!("- `{f}`");
        }
    }

    if !hazards.is_empty() {
        println!("\n## Known hazards");
        for h in hazards {
            let summary = h.get("summary").and_then(Value::as_str).unwrap_or("");
            let source = h.get("source").and_then(Value::as_str).unwrap_or("");
            println!("- [ ] {summary} _(from `{source}`)_");
        }
    }

    if !effects.is_empty() {
        println!("\n## Effects to verify");
        let mut seen: HashSet<String> = HashSet::new();
        for e in effects {
            let cat = e.get("category").and_then(Value::as_str).unwrap_or("");
            let src = e.get("source").and_then(Value::as_str).unwrap_or("");
            let key = format!("{cat}:{src}");
            if seen.insert(key) {
                println!("- [ ] `{cat}` — declared by `{src}`");
            }
        }
    }

    if !task_close_suggestions.is_empty() {
        println!("\n## Before closing this task — record in ledger");
        println!("_Run `asd task-close` or `asd ledger append` to capture these:_");
        for s in task_close_suggestions {
            let kind = s.get("kind").and_then(Value::as_str).unwrap_or("");
            let symbol = s.get("symbol").and_then(Value::as_str).unwrap_or("");
            let summary = s
                .get("suggested_summary")
                .and_then(Value::as_str)
                .unwrap_or("");
            println!("- [ ] [{kind}] `{symbol}` — {summary}");
        }
    }
}