tix-tracker 0.10.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
//! `tix import --target speckit`: mirror a local **GitHub Spec Kit** project
//! onto the tix board.
//!
//! Spec Kit (`specify-cli`) writes its artifacts into the repository: a
//! `.specify/` project root, feature directories under `specs/NNN-<name>/`
//! (`tasks.md` carrying `- [ ] T001 ...` task lines), bug reports under
//! `.specify/bugs/<slug>/`, and idea assessments under
//! `.specify/assessments/<slug>/`. Unlike the `glab`/`linear-cli` targets,
//! there is no remote and no subprocess: everything is local Markdown, so this
//! module reads the tree directly and writes tix issues through the same
//! [`crate::commands::create::create`] core the CLI and MCP use.
//!
//! ## What it creates
//!
//! - One **parent** issue per feature (`specs/NNN-<name>/`) — `files` records
//!   the feature directory.
//! - One **child** issue per `T0xx` task in the feature's `tasks.md`, with
//!   `parent:` set to the feature issue — `files` records
//!   `specs/NNN-<name>/tasks.md#T0xx`.
//! - One issue per bug directory and per assessment directory — `files` records
//!   the directory.
//!
//! Every created issue carries the [`LABEL`] label.
//!
//! ## Idempotency
//!
//! The source artifact path recorded in an issue's `files` field is the
//! identity. Before creating anything this module builds a
//! `source path -> issue number` map from every existing issue (archived ones
//! included), and an artifact whose key already appears is skipped. A second
//! run therefore creates nothing; the per-artifact keys are distinct
//! (`specs/x` for the feature, `specs/x/tasks.md#T001` for a task), so a
//! feature and its tasks never collide on the same key.
//!
//! ## Relationship to `/speckit.taskstoissues`
//!
//! Spec Kit's own `taskstoissues` command targets GitHub only. This is the tix
//! equivalent, and the AGENTS.md section generated by `tix init-agents` points
//! agents at it (see `docs/spec-kit-integration.md`).

use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Path, PathBuf};

use crate::commands::create;
use crate::config::Config;
use crate::error::{Result, TixError};
use crate::model::Status;
use crate::storage::Store;
use crate::triage::import_policy::{self, ImportPolicy};

/// The label every mirrored issue carries, so `tix list` can separate Spec Kit
/// work from the rest of the board.
pub const LABEL: &str = "speckit";

/// One `tasks.md` task line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Task {
    /// The task id, e.g. `T001`.
    pub id: String,
    /// The description after the id and any `[P]` / `[USn]` tags.
    pub description: String,
    /// The original line, stripped of leading/trailing whitespace.
    pub raw: String,
    /// Whether the checkbox was checked (`- [x]`) when the task was read.
    pub done: bool,
}

/// One feature directory under `specs/`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Feature {
    /// Repository-relative directory, e.g. `specs/003-user-auth`.
    pub dir: String,
    /// The directory basename, e.g. `003-user-auth`.
    pub name: String,
    /// Repository-relative `tasks.md`, e.g. `specs/003-user-auth/tasks.md`.
    pub tasks_path: String,
    /// The parsed tasks (empty when the feature has no `tasks.md` yet).
    pub tasks: Vec<Task>,
}

/// A bug or assessment directory mirrored as a single issue.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Artifact {
    /// Repository-relative directory, e.g. `.specify/bugs/login-crash`.
    pub dir: String,
    /// The directory basename, e.g. `login-crash`.
    pub slug: String,
    /// The concatenated report Markdown.
    pub body: String,
}

/// Everything `discover` found in one Spec Kit project root.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SpecKitArtifacts {
    pub features: Vec<Feature>,
    pub bugs: Vec<Artifact>,
    pub assessments: Vec<Artifact>,
}

/// What one mirror run created and skipped.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MirrorReport {
    /// Parent issues created.
    pub features: usize,
    /// Child task issues created.
    pub tasks: usize,
    /// Bug issues created.
    pub bugs: usize,
    /// Assessment issues created.
    pub assessments: usize,
    /// Artifacts already mirrored (key present on an existing issue).
    pub skipped: usize,
}

impl MirrorReport {
    /// Total issues created across every area.
    #[must_use]
    pub fn created(&self) -> usize {
        self.features + self.tasks + self.bugs + self.assessments
    }

    /// The one-line stdout report.
    #[must_use]
    pub fn summary(&self) -> String {
        format!(
            "imported {} issue(s) from Spec Kit: {} feature(s), {} task(s), {} bug(s), \
             {} assessment(s); {} already mirrored\n",
            self.created(),
            self.features,
            self.tasks,
            self.bugs,
            self.assessments,
            self.skipped
        )
    }
}

/// The stdout report for a mirror run — the single writer for both the CLI
/// (`run`) and the string core (`import_core`), so they cannot drift.
#[must_use]
pub fn report_text(report: &MirrorReport) -> String {
    if report.created() == 0 && report.skipped == 0 {
        "nothing to import\n".to_string()
    } else if report.created() == 0 {
        format!("nothing to import ({} already mirrored)\n", report.skipped)
    } else {
        report.summary()
    }
}

/// Resolve the Spec Kit project root from the current directory: the directory
/// holding `tix.toml`, which is also where `.specify/` lives.
fn resolve_root() -> Result<PathBuf> {
    let cwd = std::env::current_dir()?;
    Config::project_root(&cwd).ok_or_else(|| {
        TixError::InvalidInput(
            "no tix.toml found from the current directory — run `tix import --target speckit` \
             from the project root"
                .to_string(),
        )
    })
}

/// The import core for `--target speckit`: return the stdout report as a
/// `String`, mirroring the remote-import core so the CLI and MCP share it.
pub fn import_core(config: &Config, store: &Store, policy: ImportPolicy) -> Result<String> {
    let root = resolve_root()?;
    let report = mirror(config, store, &root, policy)?;
    Ok(report_text(&report))
}

/// Mirror the Spec Kit project rooted at `root`, writing created issues through
/// `store`. `out` receives the report.
pub fn run(
    config: &Config,
    store: &Store,
    root: &Path,
    policy: ImportPolicy,
    out: &mut dyn Write,
) -> Result<MirrorReport> {
    let report = mirror(config, store, root, policy)?;
    out.write_all(report_text(&report).as_bytes())?;
    Ok(report)
}

/// The mirror core: discover the artifacts and create the missing issues.
pub fn mirror(
    config: &Config,
    store: &Store,
    root: &Path,
    policy: ImportPolicy,
) -> Result<MirrorReport> {
    let artifacts = discover(root)?;

    // The landing column: the import policy decides it exactly as it does for a
    // remote import — the "requested" column is the board's first column, which
    // is where `create` puts a new issue when no status is named.
    let router = import_policy::resolve(config, policy)?;
    let requested = config
        .default_config()
        .columns
        .first()
        .cloned()
        .unwrap_or_else(|| "todo".to_string());
    let landed = router.place(LABEL, &requested).landed;

    // Identity map: every source path already recorded by an issue (archived
    // included) -> that issue's number. Distinct keys per artifact kind keep a
    // feature and its tasks from colliding.
    let mut known: BTreeMap<String, u32> = BTreeMap::new();
    for issue in store.list_all()? {
        for file in &issue.files {
            known.entry(file.clone()).or_insert(issue.number);
        }
    }

    let mut report = MirrorReport::default();

    for feature in &artifacts.features {
        let parent_number = match known.get(&feature.dir).copied() {
            Some(number) => {
                report.skipped += 1;
                number
            }
            None => {
                let body = format!(
                    "Mirrored from Spec Kit feature `{dir}`.\n\nTasks source: `{tasks}`.",
                    dir = feature.dir,
                    tasks = feature.tasks_path,
                );
                let issue = create_mirror(
                    config,
                    store,
                    &feature.name,
                    &body,
                    &landed,
                    &feature.dir,
                    None,
                )?;
                known.insert(feature.dir.clone(), issue.number);
                report.features += 1;
                issue.number
            }
        };

        for task in &feature.tasks {
            let key = format!("{}#{}", feature.tasks_path, task.id);
            if known.contains_key(&key) {
                report.skipped += 1;
                continue;
            }
            let title = if task.description.is_empty() {
                task.id.clone()
            } else {
                format!("{}: {}", task.id, task.description)
            };
            let body = format!(
                "Spec Kit task `{id}` from `{path}`.\n\n```text\n{raw}\n```",
                id = task.id,
                path = feature.tasks_path,
                raw = task.raw,
            );
            let parent = parent_number.to_string();
            let issue = create_mirror(config, store, &title, &body, &landed, &key, Some(&parent))?;
            known.insert(key, issue.number);
            report.tasks += 1;
        }
    }

    for (artifacts, counter) in [
        (&artifacts.bugs, &mut report.bugs),
        (&artifacts.assessments, &mut report.assessments),
    ] {
        for artifact in artifacts {
            if known.contains_key(&artifact.dir) {
                report.skipped += 1;
                continue;
            }
            let title = artifact.slug.clone();
            let issue = create_mirror(
                config,
                store,
                &title,
                &artifact.body,
                &landed,
                &artifact.dir,
                None,
            )?;
            known.insert(artifact.dir.clone(), issue.number);
            *counter += 1;
        }
    }

    Ok(report)
}

/// Create one mirrored issue through the shared create core, so defaults,
/// validation, the entry stamp and the parent History entry are exactly those
/// of `tix create`.
fn create_mirror(
    config: &Config,
    store: &Store,
    title: &str,
    body: &str,
    landed: &str,
    source: &str,
    parent: Option<&str>,
) -> Result<crate::model::Issue> {
    create::create(
        config,
        store,
        title,
        Some(body),
        Some(Status::new(landed.to_string())),
        None,         // priority
        None,         // assignee
        Some(LABEL),  // labels
        Some(source), // files
        None,         // estimate
        None,         // cycles (create applies the default)
        None,         // milestones
        None,         // reviewer
        None,         // start_date
        None,         // due_date
        parent,       // parent
        None,         // related_issues
        None,         // type
    )
}

/// Read a Spec Kit project root into the artifacts to mirror.
pub fn discover(root: &Path) -> Result<SpecKitArtifacts> {
    let specify = root.join(".specify");
    if !specify.is_dir() {
        return Err(TixError::InvalidInput(format!(
            "no `.specify/` directory at {} — `tix import --target speckit` needs a Spec Kit \
             project root",
            root.display()
        )));
    }

    let active = active_feature_dir(root);
    let mut feature_dirs: BTreeMap<String, PathBuf> = BTreeMap::new();
    for (name, path) in subdirs(&root.join("specs"))? {
        let rel = format!("specs/{name}");
        let is_active = active.as_deref() == Some(rel.as_str());
        if path.join("tasks.md").is_file() || is_active {
            feature_dirs.insert(rel, path);
        }
    }
    if let Some(active) = active.as_deref() {
        let path = root.join(active);
        if path.is_dir() {
            feature_dirs.entry(active.to_string()).or_insert(path);
        }
    }

    let mut features = Vec::new();
    for (dir, path) in feature_dirs {
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_else(|| dir.clone());
        let tasks_path = format!("{dir}/tasks.md");
        let tasks = match std::fs::read_to_string(path.join("tasks.md")) {
            Ok(markdown) => parse_tasks(&markdown),
            Err(_) => Vec::new(),
        };
        features.push(Feature {
            dir,
            name,
            tasks_path,
            tasks,
        });
    }

    let bugs = collect_artifacts(&specify, "bugs")?;
    let assessments = collect_artifacts(&specify, "assessments")?;

    Ok(SpecKitArtifacts {
        features,
        bugs,
        assessments,
    })
}

/// Collect every `<base>/<slug>/` directory as one artifact, sorted by slug.
fn collect_artifacts(specify: &Path, base: &str) -> Result<Vec<Artifact>> {
    let mut out = Vec::new();
    for (slug, path) in subdirs(&specify.join(base))? {
        out.push(Artifact {
            dir: format!(".specify/{base}/{slug}"),
            body: read_markdown_dir(&path)?,
            slug,
        });
    }
    Ok(out)
}

/// The active feature directory recorded by `/speckit.specify` in
/// `.specify/feature.json` (`{ "feature_directory": "specs/003-..." }`).
fn active_feature_dir(root: &Path) -> Option<String> {
    let raw = std::fs::read_to_string(root.join(".specify/feature.json")).ok()?;
    let value: serde_json::Value = serde_json::from_str(&raw).ok()?;
    let dir = value
        .get("feature_directory")?
        .as_str()?
        .trim()
        .trim_end_matches('/');
    if dir.is_empty() {
        None
    } else {
        Some(dir.to_string())
    }
}

/// Direct child directories of `dir`, sorted by name, hidden ones skipped.
fn subdirs(dir: &Path) -> Result<Vec<(String, PathBuf)>> {
    let mut out = Vec::new();
    if !dir.is_dir() {
        return Ok(out);
    }
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        if name.starts_with('.') {
            continue;
        }
        out.push((name, entry.path()));
    }
    out.sort_by(|a, b| a.0.cmp(&b.0));
    Ok(out)
}

/// Concatenate the `.md` files of a directory (sorted by name) into one body,
/// each under its filename heading.
fn read_markdown_dir(dir: &Path) -> Result<String> {
    let mut files = Vec::new();
    if dir.is_dir() {
        for entry in std::fs::read_dir(dir)? {
            let path = entry?.path();
            if path.extension().and_then(|e| e.to_str()) == Some("md") {
                files.push(path);
            }
        }
    }
    files.sort();
    let mut out = String::new();
    for path in files {
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();
        if !out.is_empty() {
            out.push('\n');
        }
        out.push_str(&format!("## {name}\n\n"));
        out.push_str(&std::fs::read_to_string(&path)?);
        if !out.ends_with('\n') {
            out.push('\n');
        }
    }
    Ok(out)
}

/// Parse the task lines of a `tasks.md`.
///
/// The strict checklist format is `- [ ] T001 [P] [US1] Description` (Spec
/// Kit's task-generation rule). Only lines whose first token after the
/// checkbox is a `T`-numbered id are tasks; prose and headings are ignored.
#[must_use]
pub fn parse_tasks(markdown: &str) -> Vec<Task> {
    let mut tasks = Vec::new();
    for line in markdown.lines() {
        let trimmed = line.trim();
        let (done, rest) = if let Some(rest) = trimmed.strip_prefix("- [ ]") {
            (false, rest)
        } else if let Some(rest) = trimmed
            .strip_prefix("- [x]")
            .or_else(|| trimmed.strip_prefix("- [X]"))
        {
            (true, rest)
        } else {
            continue;
        };
        let rest = rest.trim_start();
        let mut parts = rest.splitn(2, char::is_whitespace);
        let id = parts.next().unwrap_or("");
        if !is_task_id(id) {
            continue;
        }
        let mut description = parts.next().unwrap_or("").trim_start();
        loop {
            let current = description.trim_start();
            if let Some(stripped) = current.strip_prefix("[P]") {
                description = stripped;
            } else if let Some(stripped) = strip_story_tag(current) {
                description = stripped;
            } else {
                description = current;
                break;
            }
        }
        tasks.push(Task {
            id: id.to_string(),
            description: description.trim().to_string(),
            raw: trimmed.to_string(),
            done,
        });
    }
    tasks
}

/// A task id is `T` followed by at least one ASCII digit (`T001`).
fn is_task_id(token: &str) -> bool {
    token.len() >= 2 && token.starts_with('T') && token[1..].bytes().all(|b| b.is_ascii_digit())
}

/// Strip a leading `[USn]` story tag, if present.
fn strip_story_tag(text: &str) -> Option<&str> {
    let text = text.strip_prefix("[US")?;
    let end = text.find(']')?;
    if !text[..end].bytes().all(|b| b.is_ascii_digit()) || end == 0 {
        return None;
    }
    Some(&text[end + 1..])
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn parse_tasks_reads_the_checklist_format() {
        let md = "\
# Tasks

## Phase 1: Setup

- [ ] T001 Create project structure
- [x] T002 [P] Add dependencies in Cargo.toml
- [ ] T003 [US1] [P] Implement the login form in src/login.rs
- Not a task line
- [ ] no id here
- [X] T004 Done one
";
        let tasks = parse_tasks(md);
        assert_eq!(tasks.len(), 4);
        assert_eq!(tasks[0].id, "T001");
        assert_eq!(tasks[0].description, "Create project structure");
        assert!(!tasks[0].done);
        assert_eq!(tasks[1].id, "T002");
        assert_eq!(tasks[1].description, "Add dependencies in Cargo.toml");
        assert!(tasks[1].done);
        assert_eq!(tasks[2].id, "T003");
        assert_eq!(
            tasks[2].description,
            "Implement the login form in src/login.rs"
        );
        assert_eq!(tasks[3].id, "T004");
        assert!(tasks[3].done);
    }

    #[test]
    fn discover_reads_features_bugs_and_assessments() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::create_dir_all(root.join(".specify/memory")).unwrap();
        fs::write(
            root.join(".specify/feature.json"),
            r#"{ "feature_directory": "specs/004-empty" }"#,
        )
        .unwrap();
        // Feature with tasks.
        fs::create_dir_all(root.join("specs/003-user-auth")).unwrap();
        fs::write(
            root.join("specs/003-user-auth/tasks.md"),
            "- [ ] T001 Do the thing\n- [ ] T002 [P] Do another\n",
        )
        .unwrap();
        // Active-only feature with no tasks.md yet.
        fs::create_dir_all(root.join("specs/004-empty")).unwrap();
        fs::write(root.join("specs/004-empty/spec.md"), "# spec\n").unwrap();
        // A non-feature dir that must be ignored.
        fs::create_dir_all(root.join("specs/notes")).unwrap();
        // Bug + assessment.
        fs::create_dir_all(root.join(".specify/bugs/login-crash")).unwrap();
        fs::write(
            root.join(".specify/bugs/login-crash/assess.md"),
            "## Assessment\n\nboom\n",
        )
        .unwrap();
        fs::create_dir_all(root.join(".specify/assessments/offline-mode")).unwrap();
        fs::write(
            root.join(".specify/assessments/offline-mode/decide.md"),
            "go\n",
        )
        .unwrap();

        let artifacts = discover(root).unwrap();
        let names: Vec<&str> = artifacts.features.iter().map(|f| f.dir.as_str()).collect();
        // 004 is the active feature but has no tasks.md; 003 has tasks; notes is ignored.
        assert!(names.contains(&"specs/003-user-auth"));
        assert!(names.contains(&"specs/004-empty"));
        assert!(!names.contains(&"specs/notes"));
        let feature = artifacts
            .features
            .iter()
            .find(|f| f.dir == "specs/003-user-auth")
            .unwrap();
        assert_eq!(feature.tasks.len(), 2);
        assert_eq!(feature.tasks_path, "specs/003-user-auth/tasks.md");
        assert_eq!(artifacts.bugs.len(), 1);
        assert_eq!(artifacts.bugs[0].dir, ".specify/bugs/login-crash");
        assert!(artifacts.bugs[0].body.contains("## assess.md"));
        assert!(artifacts.bugs[0].body.contains("boom"));
        assert_eq!(artifacts.assessments.len(), 1);
        assert_eq!(artifacts.assessments[0].slug, "offline-mode");
    }

    #[test]
    fn discover_without_specify_is_an_invalid_input_error() {
        let tmp = TempDir::new().unwrap();
        let err = discover(tmp.path()).unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "{err}");
        assert!(err.to_string().contains(".specify/"));
    }
}