tix-tracker 0.12.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
#[allow(clippy::wildcard_imports)]
use super::*;

/// `capacity_calculate --scope <KIND> --id <REFERENCE>`: the shared DTO and its findings.
///
/// There is no arithmetic here: the values are the ones
/// [`crate::commands::capacity::calculation_for`] derived — the same entry point the CLI
/// calls — and an absent one is `null` (text `-`), never `0`. Read-only (C-006).
pub(super) fn capacity_calculate(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    let scope = req_string(args, "scope")?;
    let reference = req_string(args, "id")?;
    let warnings = opt_bool(args, "warnings")?.unwrap_or(false);
    let kind = match cmd_capacity::parse_scope_kind(&scope) {
        Ok(kind) => kind,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    // The CLI's own gate, in its own order: `tix capacity calculate` parses `--scope`
    // and then refuses a blank or padded `--id` by name, before it reads anything, so
    // this surface cannot turn an empty reference into a plausible *unconfigured* scope.
    // `capacity show` and `capacity snapshot` are deliberately **not** gated this way
    // (and so call no gate here): the CLI does not gate them either, and a reference
    // nothing answers to is its own `not_found` there — gating them here would make the
    // two surfaces refuse the same input with different kinds.
    let reference = match cmd_capacity::required("--id", &reference) {
        Ok(reference) => reference.to_string(),
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let (config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let calculation = match cmd_capacity::calculation_for(&config, &root, store, kind, &reference) {
        Ok(calculation) => calculation,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let mut text = cmd_capacity::calculation_text(&calculation);
    let findings = capacity_findings_text(&calculation.diagnostics, warnings);
    if !findings.is_empty() {
        text.push('\n');
        text.push_str(&findings);
        text.push('\n');
    }
    Ok(success_result(
        text,
        capacity_calculation_value(&calculation),
    ))
}

/// `capacity_list`: every configured entry, in declaration order.
///
/// The text is the CLI's `tix capacity list` output exactly, so the two surfaces are
/// byte-comparable; the structure carries the same columns as typed values. Read-only:
/// the configuration is loaded, never saved (C-006).
pub(super) fn capacity_list(_config: &Config, store: &Store, _args: &Value) -> ToolOutcome {
    let (config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let mut text = String::from("id\tscope\treference\tdisplay\tcapacity\tunit\tenabled\n");
    let mut entries = Vec::new();
    for (id, entry) in config.capacity.iter() {
        // A loaded section is validated, so every entry names exactly one scope.
        let Some(kind) = entry.scope_kind() else {
            continue;
        };
        let reference = entry.scope_id().unwrap_or_default();
        let display = cmd_capacity::scope_label(kind, reference, &index);
        text.push_str(&format!(
            "{id}\t{kind}\t{reference}\t{display}\t{ceiling}\t{unit}\t{enabled}\n",
            kind = kind.as_str(),
            ceiling = cmd_capacity::number(entry.capacity),
            unit = entry.unit.as_deref().unwrap_or("-"),
            enabled = entry.enabled,
        ));
        entries.push(capacity_entry_value(id, kind, entry, &index));
    }
    let count = entries.len();
    Ok(success_result(
        text,
        json!({ "entries": entries, "entry_count": count }),
    ))
}

/// `capacity_show <REFERENCE>`: one entry, by the scope the reference resolves to.
pub(super) fn capacity_show(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    let reference = req_string(args, "reference")?;
    let scope = opt_string(args, "scope")?;
    let (config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let wanted = match scope
        .as_deref()
        .map(cmd_capacity::parse_scope_kind)
        .transpose()
    {
        Ok(wanted) => wanted,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let (id, kind, entry) = match cmd_capacity::one_entry(&config, wanted, &reference, &index) {
        Ok(found) => found,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let entry_reference = entry.scope_id().unwrap_or_default();
    let text = format!(
        "id: {id}\nscope: {kind}\nreference: {reference}\ndisplay: {display}\n\
         capacity: {capacity}\nunit: {unit}\nenabled: {enabled}\n",
        kind = kind.as_str(),
        reference = entry_reference,
        display = cmd_capacity::scope_label(kind, entry_reference, &index),
        capacity = cmd_capacity::number(entry.capacity),
        unit = entry.unit.as_deref().unwrap_or("-"),
        enabled = entry.enabled,
    );
    Ok(success_result(
        text,
        capacity_entry_value(id, kind, entry, &index),
    ))
}

/// `capacity_snapshot <CYCLE>`: a closed cycle's immutable capacity evidence, plus the
/// close/reopen/edit `## History` summaries.
///
/// A pure read through the existing immutable snapshot store and the WP04 reader. A
/// cycle with no snapshot at all is a refusal (the tool asked for something that is not
/// there); a snapshot that carries no capacity payload — written before this mission — is
/// `evidence: none`, a value and never an error, so a legacy record stays readable. The
/// evidence is never recomputed: it is the payload the close wrote (NFR-002).
pub(super) fn capacity_snapshot(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    let reference = req_string(args, "cycle")?;
    let warnings = opt_bool(args, "warnings")?.unwrap_or(false);
    let (config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let cycle_id = match resolve_cycle(&index, &reference) {
        CycleReference::Generated { id, .. } => id,
        CycleReference::Legacy { .. } => {
            return Ok(cycle_schedule_failure(&crate::error::TixError::NotFound(
                format!(
                    "cycle `{reference}` is a hand-written cycle and has no generated snapshot; \
                     `tix capacity snapshot` reads the evidence a generated cycle's close \
                     captured"
                ),
            )));
        }
        CycleReference::Unknown { .. } => {
            return Ok(cycle_schedule_failure(&crate::error::TixError::NotFound(
                format!(
                    "no cycle `{reference}` resolves to a record, so there is no snapshot to read"
                ),
            )));
        }
    };
    let snapshots = CycleSnapshotStore::new(&root);
    let Some(stored) = (match snapshots.read(&cycle_id) {
        Ok(stored) => stored,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    }) else {
        return Ok(cycle_schedule_failure(&crate::error::TixError::NotFound(
            format!(
                "cycle `{cycle_id}` has no snapshot: it has not been closed, or its snapshot was \
                 removed"
            ),
        )));
    };
    let evidence = match CapacitySnapshot::from_cycle_snapshot(&stored) {
        Ok(evidence) => evidence,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let history = match capacity_history(&root, &cycle_id) {
        Ok(history) => history,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let snapshot_path = format!(
        "docs/cycle_snapshots/{filename}",
        filename = CycleSnapshotStore::filename_for(&cycle_id)
    );
    let mut text = format!("cycle: {cycle_id}\nsnapshot: {snapshot_path}\n");
    let structured = match evidence {
        None => {
            text.push_str("evidence: none\n");
            json!({
                "cycle_id": cycle_id.as_str(),
                "snapshot_path": snapshot_path,
                "evidence": "none",
                "capacity": Value::Null,
                "history": history,
            })
        }
        Some(evidence) => {
            text.push_str("evidence: present\n");
            text.push_str(&cmd_capacity::evidence_text(&evidence));
            let findings = capacity_findings_text(&evidence.diagnostics, warnings);
            if !findings.is_empty() {
                text.push('\n');
                text.push_str(&findings);
                text.push('\n');
            }
            json!({
                "cycle_id": cycle_id.as_str(),
                "snapshot_path": snapshot_path,
                "evidence": "present",
                "capacity": capacity_evidence_value(&evidence),
                "history": history,
            })
        }
    };
    Ok(success_result(text, structured))
}

pub(super) fn dispatch(
    config: &Config,
    store: &Store,
    name: &str,
    arguments: &Value,
) -> Option<ToolOutcome> {
    match name {
        "capacity_list" => Some(capacity_list(config, store, arguments)),
        "capacity_show" => Some(capacity_show(config, store, arguments)),
        "capacity_calculate" => Some(capacity_calculate(config, store, arguments)),
        "capacity_snapshot" => Some(capacity_snapshot(config, store, arguments)),
        _ => None,
    }
}

/// One configured entry as the CLI's `list`/`show` columns.
///
/// An absent ceiling or unit is `null` in the structure (text `-`), never `0` (C-004).
/// The `display` is the resolved identity, so a stable id and a name are visibly one
/// scope.
pub(super) fn capacity_entry_value(
    id: &str,
    kind: CapacityScopeKind,
    entry: &CapacityEntry,
    index: &ScheduleIndex,
) -> Value {
    let reference = entry.scope_id().unwrap_or_default();
    json!({
        "id": id,
        "scope": kind.as_str(),
        "reference": reference,
        "display": cmd_capacity::scope_label(kind, reference, index),
        "capacity": entry.capacity,
        "unit": entry.unit,
        "enabled": entry.enabled,
    })
}

/// The resolved scope in the wire vocabulary, shared by a calculation and a finding.
pub(super) fn capacity_scope_value(scope: &CapacityScope) -> Value {
    json!({
        "kind": scope.kind.as_str(),
        "reference": scope.reference,
        "display": scope.display,
    })
}

/// One shared finding: the kind, the scope, the numbers, the unit, the issues, and the
/// actionable `reason`/`remedy` pair (C-006/#1643). Every absent number is `null`.
pub(super) fn capacity_warning_value(warning: &CapacityWarning) -> Value {
    json!({
        "kind": warning.kind.as_str(),
        "scope": capacity_scope_value(&warning.scope),
        "issues": warning.issues,
        "current": warning.current,
        "limit": warning.limit,
        "overflow": warning.overflow,
        "unit": warning.unit,
        "reason": warning.reason,
        "remedy": warning.remedy,
    })
}

/// The shared calculation as values: every DTO field, absent values `null` (never `0`).
pub(super) fn capacity_calculation_value(calculation: &CapacityCalculation) -> Value {
    json!({
        "scope": capacity_scope_value(&calculation.scope),
        "state": calculation.state().as_str(),
        "capacity": calculation.capacity,
        "unit": calculation.unit,
        "committed": calculation.committed,
        "completed": calculation.completed,
        "remaining": calculation.remaining,
        "overflow": calculation.overflow,
        "utilization": calculation.utilization,
        "counted_issues": calculation.counted_issues,
        "uncounted_issues": calculation.uncounted_issues,
        "unestimated_issues": calculation.unestimated_issues,
        "over_capacity": calculation.is_over_capacity(),
        "source": {
            "issues": calculation.source.issues,
            "units": calculation.source.units,
        },
        "diagnostics": calculation
            .diagnostics
            .iter()
            .map(capacity_warning_value)
            .collect::<Vec<_>>(),
    })
}

/// The immutable close evidence as values — the DTO's own fields, absent `null`.
pub(super) fn capacity_evidence_value(evidence: &CapacitySnapshot) -> Value {
    json!({
        "snapshot_id": evidence.snapshot_id,
        "cycle_id": evidence.cycle_id,
        "closed_at": evidence.closed_at,
        "closed_by": evidence.closed_by,
        "scope": capacity_scope_value(&evidence.scope),
        "state": evidence.state.as_str(),
        "capacity": evidence.capacity,
        "unit": evidence.unit,
        "committed": evidence.committed,
        "completed": evidence.completed,
        "remaining": evidence.remaining,
        "overflow": evidence.overflow,
        "utilization": evidence.utilization,
        "counted_issues": evidence.counted_issues,
        "uncounted_issues": evidence.uncounted_issues,
        "unestimated_issues": evidence.unestimated_issues,
        "source": {
            "issues": evidence.source.issues,
            "units": evidence.source.units,
        },
        "diagnostics": evidence
            .diagnostics
            .iter()
            .map(capacity_warning_value)
            .collect::<Vec<_>>(),
    })
}

/// The rendered findings, under the CLI's own policy: a finding about an estimate or a
/// reference explains why a total is short, so it always renders; the overflow report is
/// the opt-in half, added only when `warnings` is asked for. The shared
/// [`CapacityWarning::render`] owns the sentence, so MCP never words a warning of its own.
pub(super) fn capacity_findings_text(diagnostics: &[CapacityWarning], warnings: bool) -> String {
    diagnostics
        .iter()
        .filter(|warning| warnings || !matches!(warning.kind, CapacityWarningKind::Overflow))
        .map(CapacityWarning::render)
        .collect::<Vec<_>>()
        .join("\n")
}

/// The capacity-affecting `## History` entries of the generated cycle's own record,
/// oldest first — the audit trail C-008 asks a reader to be able to see.
///
/// The record's log is the one place a close, a reopen and a closed-cycle capacity edit
/// are recorded; this filters it to those three kinds and returns each entry's kind, its
/// timestamp, its actor and the one-line `detail` the library wrote. It reads only: it
/// appends nothing, reorders nothing and rewrites nothing.
pub(super) fn capacity_history(root: &Path, cycle_id: &GeneratedCycleId) -> TixResult<Vec<Value>> {
    let store = CycleStore::new(root);
    let records = RecordStore::new(store.dir()).list::<crate::cycle_store::CycleRecord>()?;
    for file in records {
        let Ok(Some(cycle)) = GeneratedCycle::from_record(&file.value) else {
            continue;
        };
        if cycle.id != *cycle_id {
            continue;
        }
        let (history, _) = History::parse_front(&file.body);
        return Ok(history
            .events()
            .into_iter()
            .filter(|event| capacity_history_kind(event.kind))
            .map(|event| {
                json!({
                    "kind": event.kind.as_str(),
                    "timestamp": event.timestamp.clone(),
                    "actor": event.actor.clone(),
                    "detail": event.detail.clone(),
                })
            })
            .collect());
    }
    Ok(Vec::new())
}

/// Whether a `## History` kind is one of the capacity-affecting cycle events the snapshot
/// tool reports: the close and the reopen.
pub(super) fn capacity_history_kind(kind: HistoryEventKind) -> bool {
    matches!(
        kind,
        HistoryEventKind::CycleClosed | HistoryEventKind::CycleReopened
    )
}

// ---------------------------------------------------------------------------
// WP06 (mission `per-issue-time-tracking-01M3C9A4`) — the time tools
// ---------------------------------------------------------------------------
//
// Six tools, one per `tix time` verb: three reads (`time_show`, `time_history`,
// `time_total`) and three mutations (`time_add`, `time_edit`, `time_delete`). The
// reads answer from [`TimeSnapshot`]'s DTOs and write nothing; the mutations call
// [`apply_time`] and own no writer. Nothing below sums a minute, validates an entry,
// resolves a period or reads a `## History` grammar — that is the point of WP06, and
// `tests/mcp.rs`'s `parity_time_*` cases compare these handlers with the CLI's own
// output, including the CLI's stderr for a refusal, so a second rule or a second
// wording fails the suite rather than shipping.
//
// The *bytes* are not assembled here: every renderer a parity case compares is
// [`cmd_time`]'s own — the refusal block ([`cmd_time::refusal_blocks`]), the scope block
// ([`cmd_time::scope_block`]), the `-`-mark formatters ([`cmd_time::number`],
// [`cmd_time::cell`]), the breakdown vocabulary and its refusal
// ([`cmd_time::parse_breakdown`]), the unconfirmed-delete sentence
// ([`cmd_time::TIME_DELETE_CONFIRMATION`]), the four mutation sentences
// ([`cmd_time::mutation_sentence`]) and `time_total`'s archived-selector refusal
// ([`cmd_time::archived_refusal`]), so a later edit to the CLI's rendering reaches both
// surfaces or neither. What remains here is the *line layout* of a read — one header line
// and one tab-separated row per entry or deletion — and the row layout is all that is
// left to keep in step, which the byte-for-byte parity cases do.