tincan-cli 0.3.2

Preserve development plans, decisions, learnings, and progress in workspace-local Markdown
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
use crate::branding;
use crate::cli::{self, Command, JournalArgs, RecordArgs};
use crate::git;
use crate::model::{DecisionStatus, Kind, Record};
use crate::skill::{self, InstallOutcome};
use crate::store;
use crate::util::display_path;
use crate::workspace;
use chrono::{Local, SecondsFormat};
use uuid::Uuid;

pub fn run(command: Result<Command, String>) -> Result<(), String> {
    let command = command?;
    let notify_about_skill_update = !matches!(command, Command::SkillInstall { .. });
    let result = match command {
        Command::Help => {
            branding::print();
            print!("{}", cli::help());
            Ok(())
        }
        Command::Version => {
            println!("tincan {}", env!("CARGO_PKG_VERSION"));
            Ok(())
        }
        Command::Init { repo } => init(repo),
        Command::Summary { repo, verbose } => summary(repo, verbose),
        Command::Record(args) => record(args),
        Command::Journal(args) => journal(args),
        Command::Plan { repo } => plan(repo),
        Command::Resume { repo } => resume(repo),
        Command::Search { repo, query } => search(repo, &query),
        Command::Show { repo, id } => show(repo, &id),
        Command::Changes { repo } => changes(repo),
        Command::SkillInstall { path, force } => install_skill(path, force),
    };
    if result.is_ok() && notify_about_skill_update {
        skill::notify_if_update_available();
    }
    result
}

fn install_skill(path: Option<std::path::PathBuf>, force: bool) -> Result<(), String> {
    branding::print();
    let roots = match path {
        Some(path) => vec![path],
        None => {
            let detected = skill::detect_roots();
            if detected.is_empty() {
                return Err(
                    "no supported Agent Skills destination was detected; pass `--path <skills-directory>`"
                        .to_string(),
                );
            }
            let Some(selected) = skill::choose_interactively(&detected)? else {
                println!("Skill installation cancelled.");
                return Ok(());
            };
            selected
        }
    };

    let outcomes = skill::install_many(&roots, force)?;
    let mut installed = false;
    for outcome in outcomes {
        match outcome {
            InstallOutcome::Installed(path) => {
                installed = true;
                println!(
                    "Installed Tincan skill at {}",
                    skill::display_user_path(&path)
                );
            }
            InstallOutcome::AlreadyCurrent(path) => {
                println!(
                    "Tincan skill is already current at {}",
                    skill::display_user_path(&path)
                );
            }
        }
    }
    if installed {
        println!("Restart or reload the agent harness to discover it.");
    }
    Ok(())
}

fn init(path: std::path::PathBuf) -> Result<(), String> {
    let root = workspace::target(&path)?;
    let excluded = git::protect_workspace(&root)?;
    let tincan = store::initialize(&root)?;
    branding::print();
    println!("Initialized Tincan at {}", display_path(&tincan));
    match excluded {
        Some(true) => println!("Kept .tincan private through Git's local exclude file."),
        Some(false) => println!(".tincan is already excluded from Git locally."),
        None => {
            println!("This workspace is outside Git; nested repositories cannot track .tincan.")
        }
    }
    Ok(())
}

fn summary(path: std::path::PathBuf, verbose: bool) -> Result<(), String> {
    let root = workspace::find(&path)?;
    let documents = store::scan(&root)?;
    let groups = [
        ("Decisions", "decision"),
        ("Learnings", "learning"),
        ("Journals", "journal"),
    ];
    for (label, kind) in groups {
        print_summary_count(label, kind, &documents);
    }
    if verbose {
        for (label, kind) in groups {
            print_summary_details(label, kind, &root, &documents);
        }
    }
    Ok(())
}

fn print_summary_count(label: &str, kind: &str, documents: &[store::Document]) {
    let count = documents
        .iter()
        .filter(|document| document.kind == kind)
        .count();
    let padded_label = format!("{label:<9}");
    println!("{} {count}", branding::section(&padded_label));
}

fn print_summary_details(
    label: &str,
    kind: &str,
    root: &std::path::Path,
    documents: &[store::Document],
) {
    let matching: Vec<_> = documents
        .iter()
        .filter(|document| document.kind == kind)
        .collect();
    if matching.is_empty() {
        return;
    }
    println!();
    println!("{}", branding::section(label));
    for document in matching {
        let relative = document.path.strip_prefix(root).unwrap_or(&document.path);
        println!(
            "  {}  {}",
            branding::heading(&document.heading),
            branding::path(&display_path(relative))
        );
    }
}

fn record(args: RecordArgs) -> Result<(), String> {
    if args.kind != "decision" && !args.supersedes.is_empty() {
        return Err("--supersedes can only be used with a decision".to_string());
    }
    let root = workspace::find(&args.repo)?;
    let kind = Kind::parse(&args.kind)?;
    let id = Uuid::now_v7().to_string();
    let created_at = Local::now().to_rfc3339_opts(SecondsFormat::Secs, true);
    let status = match kind {
        Kind::Decision => Some(DecisionStatus::Active),
        Kind::Learning => None,
        Kind::Journal => unreachable!("journal entries use the journal command"),
    };
    let superseded = store::active_decisions(&root, &args.supersedes)?;
    let record = Record {
        id,
        kind,
        created_at,
        statement: args.statement,
        status,
        files: args.files,
        topics: args.topics,
        evidence: args.evidence,
        related: args.related,
        supersedes: args.supersedes,
        branch: git::branch(&args.repo)?,
    };
    let path = store::write(&root, kind, &record.id, &record.render())?;
    if let Err(error) = store::mark_superseded(&superseded, &record.id) {
        return match std::fs::remove_file(&path) {
            Ok(()) => Err(error),
            Err(cleanup_error) => Err(format!(
                "{error}; also could not remove incomplete replacement {}: {cleanup_error}",
                path.display()
            )),
        };
    }
    println!("Created {}: {}", kind.as_str(), display_path(&path));
    println!("Record ID: {}", record.id);
    println!("Add detailed context directly to the Markdown body when useful.");
    if !superseded.is_empty() {
        println!("Superseded {} earlier decision(s).", superseded.len());
    }
    Ok(())
}

fn journal(args: JournalArgs) -> Result<(), String> {
    let root = workspace::find(&args.repo)?;
    store::require(&root)?;
    let now = Local::now();
    let date = now.format("%Y-%m-%d").to_string();
    let created_at = now.to_rfc3339_opts(SecondsFormat::Secs, true);
    let sections = store::JournalSections {
        done: &args.done,
        decisions: &args.decisions,
        learnings: &args.learnings,
        planned: &args.planned,
        questions: &args.questions,
        next: &args.next,
    };
    let update = store::update_journal(&root, &date, &created_at, sections)?;
    println!("Updated journal: {}", display_path(&update.path));
    if update.added == 0 {
        println!("No new bullets; exact duplicates were already present.");
    } else {
        println!("Added {} bullet(s).", update.added);
    }
    Ok(())
}

fn resume(path: std::path::PathBuf) -> Result<(), String> {
    let root = workspace::find(&path)?;
    let Some((journal_path, content)) = store::latest_journal(&root)? else {
        println!("No journal entries yet.");
        println!("Use `tincan journal --done <text>` as meaningful work develops.");
        return Ok(());
    };
    println!("Latest journal: {}\n", display_path(&journal_path));
    print!("{content}");
    Ok(())
}

fn plan(path: std::path::PathBuf) -> Result<(), String> {
    let root = workspace::find(&path)?;
    let (plan_path, content) = store::read_plan(&root)?;
    println!("Plan: {}\n", display_path(&plan_path));
    print!("{content}");
    Ok(())
}

fn search(path: std::path::PathBuf, query: &str) -> Result<(), String> {
    let root = workspace::find(&path)?;
    let query = query.to_lowercase();
    let mut matches: Vec<_> = store::scan(&root)?
        .into_iter()
        .filter_map(|document| search_rank(&document, &query).map(|rank| (rank, document)))
        .collect();
    matches.sort_by(|left, right| left.0.cmp(&right.0).then(left.1.path.cmp(&right.1.path)));
    if matches.is_empty() {
        println!("No Tincan records matched.");
        return Ok(());
    }
    for (_, document) in matches {
        print_document_summary(&document, Some(&query));
    }
    Ok(())
}

fn show(path: std::path::PathBuf, id: &str) -> Result<(), String> {
    let root = workspace::find(&path)?;
    let document = store::scan(&root)?
        .into_iter()
        .find(|document| document.id == id)
        .ok_or_else(|| format!("no Tincan record found with id {id}"))?;
    print!("{}", store::read_document(&document)?);
    Ok(())
}

fn search_rank(document: &store::Document, query: &str) -> Option<u8> {
    if document.id.to_lowercase() == query {
        return Some(0);
    }
    if document.heading.to_lowercase().contains(query) {
        return Some(1);
    }
    if metadata_text(document).to_lowercase().contains(query) {
        return Some(2);
    }
    document.body.to_lowercase().contains(query).then_some(3)
}

fn metadata_text(document: &store::Document) -> String {
    [
        vec![
            document.id.clone(),
            document.kind.clone(),
            document.status.clone().unwrap_or_default(),
        ],
        document.files.clone(),
        document.topics.clone(),
        document.related.clone(),
        document.supersedes.clone(),
        document.superseded_by.clone(),
    ]
    .concat()
    .join("\n")
}

fn print_document_summary(document: &store::Document, query: Option<&str>) {
    let label = document
        .status
        .as_deref()
        .map(|status| format!("{} / {status}", document.kind))
        .unwrap_or_else(|| document.kind.clone());
    println!("{} [{label}]", document.heading);
    println!("  id: {}", document.id);
    if let Some(excerpt) = query.and_then(|query| matching_excerpt(document, query)) {
        println!("  matched: {excerpt}");
    }
    if !document.files.is_empty() {
        println!("  files: {}", document.files.join(", "));
    }
    if !document.topics.is_empty() {
        println!("  topics: {}", document.topics.join(", "));
    }
    if !document.supersedes.is_empty() {
        println!("  supersedes: {}", document.supersedes.join(", "));
    }
    if !document.superseded_by.is_empty() {
        println!("  superseded by: {}", document.superseded_by.join(", "));
    }
    println!("  {}", display_path(&document.path));
}

fn matching_excerpt(document: &store::Document, query: &str) -> Option<String> {
    let query = query.to_lowercase();
    document.body.lines().find_map(|line| {
        let line = line.trim();
        if line.is_empty()
            || line.strip_prefix("# ") == Some(document.heading.as_str())
            || !line.to_lowercase().contains(&query)
        {
            return None;
        }
        let cleaned = line
            .trim_start_matches('#')
            .trim_start_matches(['-', '*'])
            .trim();
        let mut excerpt: String = cleaned.chars().take(120).collect();
        if cleaned.chars().count() > 120 {
            excerpt.push('…');
        }
        Some(excerpt)
    })
}

fn changes(path: std::path::PathBuf) -> Result<(), String> {
    let root = workspace::find(&path)?;
    let Some(changed) = git::workspace_changed_files(&root)? else {
        println!("No Git repositories found in this Tincan workspace.");
        return Ok(());
    };
    if changed.is_empty() {
        println!("No changed files.");
        return Ok(());
    }

    let documents = store::scan(&root)?;
    for file in &changed {
        let related: Vec<_> = documents
            .iter()
            .filter(|document| {
                document
                    .files
                    .iter()
                    .any(|affected| paths_overlap(file, affected))
            })
            .collect();
        if related.is_empty() {
            println!(
                "{}  {}",
                branding::section(file),
                branding::path("no records")
            );
            continue;
        }
        for (index, document) in related.into_iter().enumerate() {
            let relative = document.path.strip_prefix(&root).unwrap_or(&document.path);
            let file_label = if index == 0 { file.as_str() } else { "" };
            println!(
                "{file_label}  {}: {}  {}",
                document.kind,
                branding::heading(&document.heading),
                branding::path(&display_path(relative))
            );
        }
    }
    Ok(())
}

fn paths_overlap(changed: &str, affected: &str) -> bool {
    let changed = changed.trim_matches('/').replace('\\', "/");
    let affected = affected.trim_matches('/').replace('\\', "/");
    changed == affected
        || changed.starts_with(&(affected.clone() + "/"))
        || affected.starts_with(&(changed + "/"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs::{self, OpenOptions};
    use std::io::Write;
    use std::process::Command as ProcessCommand;
    use std::time::{SystemTime, UNIX_EPOCH};

    #[test]
    fn matches_files_and_directories() {
        assert!(paths_overlap("src/feature/a.rs", "src/feature"));
        assert!(paths_overlap("src/feature", "src/feature/a.rs"));
        assert!(!paths_overlap("src/a.rs", "src/b.rs"));
    }

    #[test]
    fn creates_uuid_record_that_remains_searchable_after_body_edits() {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let repo = std::env::temp_dir().join(format!("tincan-uuid-record-{unique}"));
        fs::create_dir_all(&repo).unwrap();
        assert!(
            ProcessCommand::new("git")
                .args(["init", "--quiet"])
                .current_dir(&repo)
                .status()
                .unwrap()
                .success()
        );
        store::initialize(&repo).unwrap();

        record(RecordArgs {
            kind: "learning".to_string(),
            repo: repo.clone(),
            statement: "Paging did not reduce rendering work".to_string(),
            files: vec!["src/gallery.rs".to_string()],
            topics: vec!["performance".to_string()],
            evidence: vec!["Release trace".to_string()],
            related: Vec::new(),
            supersedes: Vec::new(),
        })
        .unwrap();

        let document = store::scan(&repo).unwrap().remove(0);
        assert!(Uuid::parse_str(&document.id).is_ok());
        assert_eq!(
            document.path.file_stem().and_then(|value| value.to_str()),
            Some(document.id.as_str())
        );
        writeln!(
            OpenOptions::new()
                .append(true)
                .open(&document.path)
                .unwrap(),
            "The renderer remained the measured bottleneck."
        )
        .unwrap();

        let edited = store::scan(&repo).unwrap().remove(0);
        assert_eq!(search_rank(&edited, "renderer"), Some(3));
        assert_eq!(
            matching_excerpt(&edited, "renderer").as_deref(),
            Some("The renderer remained the measured bottleneck.")
        );
        fs::remove_dir_all(repo).unwrap();
    }
}