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
//! Spec Kitty integration — `kitty-specs/` artifact support for tix.
//!
//! When the repo contains a `kitty-specs/` directory (typed Spec Kitty
//! missions, surface: missions + work packages + decisions), tix can browse
//! missions, their work packages (tasks), and decision records, and
//! link/unlink `Issue`s to a mission + work package (writing the `mission` /
//! `task` `Option<String>` fields on the issue).
//!
//! Real on-disk layout (frozen from `git show HEAD:kitty-specs/...` ground
//! truth):
//! ```text
//! kitty-specs/<slug>/
//!   meta.json            mission metadata (mission_slug, friendly_name,
//!                        purpose_tldr, purpose_context, target_branch,
//!                        status_phase, mission_number, mission_type)
//!   status.json          summary (lane counts) + work_packages
//!                        { "work_packages": { "WP01": { lane, agent, ... } } }
//!   tasks/WP*.md         per-WP task docs (YAML frontmatter)
//!   decisions/index.json { "entries": [{ decision_id, input_key,
//!                           final_answer, ... }] }
//!   decisions/DM-*.md    per-decision records
//! ```
//!
//! Tolerant duplicate-key handling: Spec Kitty's JSONL writer occasionally
//! writes a work package with BOTH a structural `"agent": null` and a claimed
//! `"agent": "<name>"` key in the same object. serde_json rejects duplicate
//! object keys, so we collapse duplicates to the LAST occurrence **within the
//! same enclosing object** before strict deserialization. The clean real
//! artifact (`issue-tracker-tui-01M27PTN/status.json`) has ONE agent per
//! work package — the collapse must be a NO-OP there.

use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::error::{Result, TixError};
use crate::model::Issue;

/// Byte offset just past the colon-start of a `key` occurrence at `key_start`.
fn colon_offset(raw: &str, key_start: usize, key: &str) -> usize {
    let seg = &raw[key_start..];
    let after_key = key.len();
    seg[after_key..]
        .find(':')
        .map(|c| key_start + after_key + c)
        .unwrap_or(key_start)
}

/// Brace depth of `raw` (ignoring braces inside quoted strings).
fn brace_depth(raw: &str) -> i64 {
    let mut depth = 0i64;
    let mut in_str = false;
    let mut esc = false;
    for ch in raw.chars() {
        if in_str {
            if esc {
                esc = false;
            } else if ch == '\\' {
                esc = true;
            } else if ch == '"' {
                in_str = false;
            }
        } else {
            match ch {
                '"' => in_str = true,
                '{' => depth += 1,
                '}' => depth -= 1,
                _ => {}
            }
        }
    }
    depth
}

/// Byte offset just past the value of the key starting at `key_start`, i.e.
/// the position past the trailing `,` / `}` / newline boundary.
fn key_value_end(raw: &str, key_start: usize) -> usize {
    let colon = colon_offset(raw, key_start, "\"agent\"");
    let mut i = colon + 1;
    while i < raw.len() && (raw[i..].starts_with(' ') || raw[i..].starts_with('\n')) {
        i += 1;
    }
    let mut in_str = false;
    let mut esc = false;
    let mut depth = 0i64;
    let mut end = raw.len();
    let mut seen = false;
    let chars = raw[i..].char_indices();
    for (j, ch) in chars {
        let pos = i + j;
        if in_str {
            if esc {
                esc = false;
            } else if ch == '\\' {
                esc = true;
            } else if ch == '"' {
                in_str = false;
                seen = true;
                end = pos + 1;
            }
            continue;
        }
        match ch {
            '"' => {
                in_str = true;
                end = pos + 1;
            }
            '{' | '[' => {
                depth += 1;
                end = pos + 1;
            }
            '}' | ']' => {
                if depth == 0 {
                    end = pos;
                    break;
                }
                depth -= 1;
                end = pos + 1;
            }
            ',' | '\n' => {
                if depth == 0 {
                    if seen {
                        end = pos;
                    } else {
                        end = pos + 1;
                    }
                    break;
                }
            }
            c if c.is_whitespace() => {}
            _ => {
                seen = true;
                end = pos + 1;
            }
        }
    }
    end
}

/// After a `"key":` prefix, does the value start with `null` or a string?
fn after_colon_is_nullable_string(raw: &str, key_start: usize, key: &str) -> bool {
    let colon = colon_offset(raw, key_start, key);
    let after = colon + 1;
    let v = after + raw[after..].len() - raw[after..].trim_start_matches(' ').len();
    raw[v..].trim_start().starts_with("null") || raw[v..].trim_start().starts_with('"')
}

/// Tolerant deduplication of object keys: collapse duplicate `key` occurrences
/// to the LAST value **within the same enclosing brace scope** (the enclosing
/// object). Keys of *sibling* objects are never treated as duplicates.
pub fn collapse_dup_key(raw: &str, key: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    let mut i = 0;
    while i < raw.len() {
        let rest = &raw[i..];
        // find the next occurrence of `key`
        let Some(j) = rest.find(key) else {
            out.push_str(&raw[i..]);
            break;
        };
        let key_start = i + j;
        // Is this a KEY position (preceded by `{`, `,`, `\n`, `]` or start)?
        let before = raw[..key_start].trim_end();
        let is_key_pos = before.is_empty()
            || before.ends_with('{')
            || before.ends_with(',')
            || before.ends_with('\n')
            || before.ends_with('[');
        if !is_key_pos || !after_colon_is_nullable_string(raw, key_start, key) {
            out.push_str(&raw[i..key_start + key.len()]);
            i = key_start + key.len();
            continue;
        }
        // brace depth of the enclosing object: everything from the nearest `{`
        // to here counts as "this object"
        let enc_depth = brace_depth(&raw[..key_start]);
        let seg_end = key_value_end(raw, key_start);
        // scan forward within the SAME object for a LATER occurrence of key at
        // key-position; stop the moment the enclosing object closes (depth <
        // enc) because siblings can never be duplicates of this key.
        let mut has_later = false;
        let mut scan = seg_end;
        let mut scan_depth = enc_depth;
        let mut in_s = false;
        let mut esc = false;
        'scan: while scan < raw.len() {
            let ch = raw[scan..].chars().next().unwrap();
            if in_s {
                if esc {
                    esc = false;
                } else if ch == '\\' {
                    esc = true;
                } else if ch == '"' {
                    in_s = false;
                }
                scan += ch.len_utf8();
                continue;
            }
            match ch {
                '"' => in_s = true,
                '{' => scan_depth += 1,
                '}' => {
                    scan_depth -= 1;
                    if scan_depth < enc_depth {
                        break 'scan;
                    }
                }
                _ => {}
            }
            if scan_depth == enc_depth && raw[scan..].starts_with(key) {
                let before2 = raw[..scan].trim_end();
                let is_key_pos2 = before2.is_empty()
                    || before2.ends_with('{')
                    || before2.ends_with(',')
                    || before2.ends_with('\n');
                if is_key_pos2 && after_colon_is_nullable_string(raw, scan, key) {
                    has_later = true;
                    break 'scan;
                }
            }
            scan += ch.len_utf8();
        }
        if has_later {
            // a later same-object occurrence exists: this one is a duplicate —
            // drop it, but keep everything BEFORE this key EXCEPT the separator
            // comma right before it (the surviving LAST member re-adds its own
            // leading comma from the separator that followed this value, so we
            // resume right AT that comma). If this was the object's FIRST member
            // (no leading comma), fully drop it and skip past its own comma.
            let pfx = &raw[i..key_start];
            let trimmed = pfx.trim_end();
            if trimmed.ends_with(',') {
                out.push_str(&pfx[..trimmed.len() - 1]);
                i = seg_end;
            } else {
                out.push_str(pfx);
                i = seg_end + 1;
            }
        } else {
            out.push_str(&raw[i..seg_end]);
            i = seg_end;
        }
    }
    out
}

/// Collapse duplicate `"agent"` keys to the LAST value within the same object.
/// Used before strict `serde_json` deserialization of Spec Kitty artifacts.
pub fn collapse_dup_agent(raw: &str) -> String {
    collapse_dup_key(raw, "\"agent\"")
}

/// Detect `kitty-specs/` at `repo_root`.
pub fn detect(repo_root: &Path) -> Option<PathBuf> {
    let p = repo_root.join("kitty-specs");
    if p.is_dir() { Some(p) } else { None }
}

/// A Spec Kitty mission directory.
#[derive(Debug, Clone)]
pub struct Mission {
    pub slug: String,
    pub dir: PathBuf,
}

/// List mission directories under `kitty-specs/`, sorted by slug.
pub fn missions(specs_root: &Path) -> Result<Vec<Mission>> {
    let mut out = Vec::new();
    for entry in fs::read_dir(specs_root)
        .map_err(|e| TixError::Kitty(format!("cannot list {}: {e}", specs_root.display())))?
    {
        let entry = entry.map_err(|e| TixError::Kitty(format!("entry: {e}")))?;
        let path = entry.path();
        if path.is_dir() {
            if let Some(slug) = path.file_name().and_then(|s| s.to_str()) {
                out.push(Mission {
                    slug: slug.to_string(),
                    dir: path,
                });
            }
        }
    }
    out.sort_by(|a, b| a.slug.cmp(&b.slug));
    Ok(out)
}

/// Mission metadata (`meta.json`).
#[derive(Debug, Clone, Default, Deserialize)]
pub struct MissionMeta {
    #[serde(default, rename = "mission_slug")]
    pub mission_slug: String,
    #[serde(default, rename = "friendly_name")]
    pub friendly_name: String,
    #[serde(default, rename = "purpose_tldr")]
    pub purpose_tldr: String,
    #[serde(default, rename = "purpose_context")]
    pub purpose_context: String,
    #[serde(default, rename = "target_branch")]
    pub target_branch: String,
    #[serde(default, rename = "status_phase")]
    pub status_phase: String,
    #[serde(default, rename = "mission_number")]
    pub mission_number: String,
    #[serde(default, rename = "mission_type")]
    pub mission_type: String,
}

/// Mission status (`status.json`).
#[derive(Debug, Clone, Default, Deserialize)]
pub struct MissionStatus {
    #[serde(default, rename = "mission_slug")]
    pub mission_slug: String,
    #[serde(default)]
    pub summary: StatusSummary,
    #[serde(default, rename = "work_packages")]
    pub work_packages: indexmap::IndexMap<String, WorkPackage>,
}

/// A single work package (`status.json` → `work_packages.<id>`).
#[derive(Debug, Clone, Default, Deserialize)]
pub struct WorkPackage {
    #[serde(default)]
    pub lane: Option<String>,
    #[serde(default)]
    pub agent: Option<String>,
    #[serde(default, rename = "agent_profile")]
    pub agent_profile: Option<String>,
    #[serde(default, rename = "agent_profile_version")]
    pub agent_profile_version: Option<String>,
    #[serde(default, rename = "force_count")]
    pub force_count: u64,
    #[serde(default, rename = "last_event_id")]
    pub last_event_id: Option<String>,
    #[serde(default, rename = "last_transition_at")]
    pub last_transition_at: Option<String>,
    #[serde(default)]
    pub model: Option<String>,
    #[serde(default)]
    pub notes: Vec<String>,
}

/// Lane-count summary (`status.json` → `summary`).
#[derive(Debug, Clone, Default, Deserialize)]
pub struct StatusSummary {
    #[serde(default)]
    pub todo: u32,
    #[serde(default, rename = "in_progress")]
    pub in_progress: u32,
    #[serde(default, rename = "in_review")]
    pub in_review: u32,
    #[serde(default, rename = "for_review")]
    pub for_review: u32,
    #[serde(default)]
    pub done: u32,
    #[serde(default)]
    pub approved: u32,
    #[serde(default)]
    pub blocked: u32,
    #[serde(default)]
    pub canceled: u32,
    #[serde(default)]
    pub planned: u32,
    #[serde(default)]
    pub claimed: u32,
}

impl Mission {
    /// `meta.json`, read + parse (no dup collapse needed for meta today).
    pub fn meta(&self) -> Result<Option<MissionMeta>> {
        let p = self.dir.join("meta.json");
        if !p.exists() {
            return Ok(None);
        }
        let raw = fs::read_to_string(&p)
            .map_err(|e| TixError::Kitty(format!("cannot read {}: {e}", p.display())))?;
        serde_json::from_str(&raw)
            .map(Some)
            .map_err(|e| TixError::Kitty(format!("{}: invalid meta.json: {e}", p.display())))
    }

    /// `status.json`, read + collapse duplicate `agent` keys + strict parse.
    pub fn status(&self) -> Result<Option<MissionStatus>> {
        let p = self.dir.join("status.json");
        if !p.exists() {
            return Ok(None);
        }
        let raw = fs::read_to_string(&p)
            .map_err(|e| TixError::Kitty(format!("cannot read {}: {e}", p.display())))?;
        let raw = collapse_dup_agent(&raw);
        serde_json::from_str(&raw)
            .map(Some)
            .map_err(|e| TixError::Kitty(format!("{}: invalid status.json: {e}", p.display())))
    }
}

/// Link an `Issue` to a Spec Kitty mission + optional work package.
pub fn link(issue: &mut Issue, mission: &str, task: Option<&str>) {
    issue.mission = Some(mission.to_string());
    issue.task = task.map(|t| t.to_string());
}

/// Remove the Spec Kitty mission/work-package link from an `Issue`.
pub fn unlink(issue: &mut Issue) {
    issue.mission = None;
    issue.task = None;
}

/// Human-facing link label (`mission/task` or bare `mission`).
pub fn render_link(issue: &Issue) -> String {
    match (&issue.mission, &issue.task) {
        (Some(m), Some(t)) => format!("{m}/{t}"),
        (Some(m), None) => m.clone(),
        (None, _) => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;

    #[test]
    fn parses_real_mission_status() {
        let specs = detect(Path::new(env!("CARGO_MANIFEST_DIR")))
            .expect("kitty-specs/ must exist at crate root");
        let missions = missions(&specs).expect("list missions");
        assert!(!missions.is_empty(), "no missions detected");
        let mut checked = 0;
        let mut wps = 0;
        for mission in &missions {
            let status = mission.status().expect("parse real status.json");
            if let Some(status) = status {
                assert!(
                    !status.work_packages.is_empty(),
                    "{}: no work packages",
                    mission.slug
                );
                for (wp, pkg) in &status.work_packages {
                    assert!(
                        !pkg.lane.as_deref().unwrap_or_default().is_empty(),
                        "{} {wp}: empty lane",
                        mission.slug
                    );
                    wps += 1;
                }
                checked += 1;
            }
        }
        assert!(
            checked >= 2,
            "expected >= 2 missions with status.json (got {checked})"
        );
        assert!(
            wps >= 9,
            "expected >= 9 work packages across missions (got {wps})"
        );
    }

    #[test]
    fn collapse_noop_on_issue_tracker_clean_artifacts() {
        // WP03 duplicates: the clean now kanban-config has a real
        // same-object dup; issue-tracker-tui has ONE agent per WP (no dup) —
        // collapse on the raw structural string must be a NO-OP there.
    }

    #[test]
    fn collapse_keeps_last_same_object_dup() {
        let raw =
            r#"{"work_packages":{"WP03":{"lane":"in_review","agent":null,"agent":"opencode"}}}"#;
        let out = collapse_dup_agent(raw);
        assert_eq!(
            out,
            r#"{"work_packages":{"WP03":{"lane":"in_review","agent":"opencode"}}}"#
        );
        // the trailing-separator comma edge: raw next keeps its leading
        // separator only if a same-object sibling key actually follows it —
        // otherwise the survivor must supply its OWN leading comma or we get
        // `"in_review" ",` (double separator / stray comma).
        let raw2 = r#"{"work_packages":{"WP03":{"lane":"in_review","agent":"opencode"}}}"#;
        assert_eq!(collapse_dup_agent(raw2), raw2);
    }

    #[test]
    fn collapse_first_object_member_dup_drops_comma() {
        // the FINAL winner is the FIRST member (no preceding comma): when we
        // drop the earlier holder we must NOT leave a stray `{ ,` — the
        // surviving LAST member carries its own leading separator.
        let raw =
            r#"{"work_packages":{"WP03":{"agent":null,"agent":"opencode","lane":"in_review"}}}"#;
        assert_eq!(
            collapse_dup_agent(raw),
            r#"{"work_packages":{"WP03":{"agent":"opencode","lane":"in_review"}}}"#
        );
    }
}