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

/// `time_add`: one create, through the shared service.
pub(super) fn time_add(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Some(refusal) = time_arguments(args, TIME_ADD_ARGS) {
        return Ok(refusal);
    }
    let issue = selector(args, "issue")?;
    let minutes = req_i64(args, "minutes")?;
    let author = req_string(args, "author")?;
    let mut entry = NewTimeEntry::new(minutes, author);
    if let Some(date) = opt_string(args, "date")? {
        entry = entry.on(date);
    }
    if let Some(note) = opt_string(args, "note")? {
        entry = entry.with_note(note);
    }
    let request = time_request(args, TimeMutationRequest::create(issue, entry))?;
    time_mutation(store, &request)
}

/// `time_delete`: remove one entry from the current projection, under a confirmation.
///
/// The confirmation is checked **first**, before the store is read, exactly as the CLI
/// checks `--confirm` — so an unconfirmed delete touches nothing at all, and the
/// refusal is the CLI's own sentence.
pub(super) fn time_delete(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Some(refusal) = time_arguments(args, TIME_DELETE_ARGS) {
        return Ok(refusal);
    }
    if args.get("confirm").and_then(Value::as_bool) != Some(true) {
        return Ok(time_input_refusal(
            cmd_time::TIME_DELETE_CONFIRMATION.to_string(),
        ));
    }
    let issue = selector(args, "issue")?;
    let entry_id = req_string(args, "entry")?;
    let request = TimeMutationRequest::delete(
        issue,
        entry_id,
        opt_string(args, "reason")?.unwrap_or_default(),
    );
    let request = time_request(args, request)?;
    time_mutation(store, &request)
}

/// `time_edit`: one correction, naming only the fields the caller replaced.
pub(super) fn time_edit(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Some(refusal) = time_arguments(args, TIME_EDIT_ARGS) {
        return Ok(refusal);
    }
    let issue = selector(args, "issue")?;
    let entry_id = req_string(args, "entry")?;
    // `clap` refuses these pairs before the CLI's adapter runs, so the MCP refuses
    // them too: accepting the pair would accept a call the CLI rejects.
    let named = |key: &str| args.get(key).is_some_and(|value| !value.is_null());
    if named("date") && named("clear_date") {
        return Ok(time_input_refusal(time_edit_conflict("date", "clear_date")));
    }
    if named("note") && named("clear_note") {
        return Ok(time_input_refusal(time_edit_conflict("note", "clear_note")));
    }
    let mut change = TimeEntryEdit::new();
    if let Some(minutes) = opt_i64(args, "minutes")? {
        change = change.duration(minutes);
    }
    if let Some(date) = opt_string(args, "date")? {
        change = change.date(date);
    }
    if opt_bool(args, "clear_date")?.unwrap_or(false) {
        change = change.clear_date();
    }
    if let Some(note) = opt_string(args, "note")? {
        change = change.note(note);
    }
    if opt_bool(args, "clear_note")?.unwrap_or(false) {
        change = change.clear_note();
    }
    if let Some(author) = opt_string(args, "author")? {
        change = change.author(author);
    }
    let request = TimeMutationRequest::edit(
        issue,
        entry_id,
        change,
        opt_string(args, "reason")?.unwrap_or_default(),
    );
    let request = time_request(args, request)?;
    time_mutation(store, &request)
}

/// `time_history`: the audit view for one issue (FR-005, T017).
pub(super) fn time_history(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Some(refusal) = time_arguments(args, TIME_HISTORY_ARGS) {
        return Ok(refusal);
    }
    let selector = selector(args, "issue")?;
    let (number, snapshot) = match time_issue_snapshot(store, &selector) {
        Ok(read) => read,
        Err(error) => return Ok(time_refusal(&error)),
    };
    let audit = snapshot.audit(&TimeFilter::new().for_issue(number));
    let current = audit.issues.first().map_or(0, |issue| issue.current);
    let mut lines = vec![
        format!("scope: {}", audit.filter.describe()),
        format!("current: {current}"),
        format!("deleted_count: {}", audit.deleted_count),
        format!("corrected_count: {}", audit.corrected_count),
        "entry\tdeleted_at\tdeleted_by".to_string(),
    ];
    for issue in &audit.issues {
        for deletion in &issue.deletions {
            lines.push(format!(
                "{}\t{}\t{}",
                cmd_time::cell(deletion.entry_id.as_deref()),
                cmd_time::cell(Some(deletion.deleted_at.as_str())),
                cmd_time::cell(Some(deletion.deleted_by.as_str())),
            ));
        }
    }
    let value = json!({
        "scope": audit.filter.describe(),
        "current": current,
        "deleted_count": audit.deleted_count,
        "corrected_count": audit.corrected_count,
        "issues": audit.issues.iter().map(|issue| json!({
            "issue": issue.issue,
            "current": issue.current,
            "corrections": issue.corrections,
            "deletions": issue.deletions.iter().map(|deletion| json!({
                "issue": deletion.issue,
                "entry_id": deletion.entry_id,
                "deleted_at": deletion.deleted_at,
                "deleted_by": deletion.deleted_by,
            })).collect::<Vec<Value>>(),
        })).collect::<Vec<Value>>(),
        "diagnostics": time_diagnostics_value(&audit.diagnostics),
    });
    // The CLI's stdout ends with the last `println!`'s newline; the text is it verbatim.
    Ok(success_result(format!("{}\n", lines.join("\n")), value))
}

/// `time_show`: the issue's current entries and its total.
pub(super) fn time_show(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Some(refusal) = time_arguments(args, TIME_SHOW_ARGS) {
        return Ok(refusal);
    }
    let selector = selector(args, "issue")?;
    let (number, snapshot) = match time_issue_snapshot(store, &selector) {
        Ok(read) => read,
        Err(error) => return Ok(time_refusal(&error)),
    };
    let filter = TimeFilter::new().for_issue(number);
    let total = snapshot.total(&filter);
    let (block, value) = match time_scope_payload(&total) {
        Ok(payload) => payload,
        Err(refusal) => return Ok(error_result(refusal)),
    };
    // The CLI's own table, then the CLI's own scope block: one header line, one
    // tab-separated row per selected entry, and the block.
    let mut lines = vec!["id\tminutes\tdate\tauthor\tnote".to_string()];
    let mut entries = Vec::new();
    for indexed in snapshot.entries() {
        if !filter.selects(indexed.issue, &indexed.entry) {
            continue;
        }
        let entry = &indexed.entry;
        lines.push(format!(
            "{}\t{}\t{}\t{}\t{}",
            entry.id,
            cmd_time::number(entry.minutes()),
            cmd_time::cell(entry.date.as_deref()),
            cmd_time::cell(Some(entry.author.as_str())),
            cmd_time::cell(entry.note.as_deref()),
        ));
        entries.push(time_entry_value(indexed.issue, entry));
    }
    lines.push(block);
    let mut value = value;
    value["entries"] = Value::Array(entries);
    // The CLI prints one line per `println!`, so its stdout ends with a newline; the
    // text channel is that stdout verbatim, which is what the parity cases compare.
    Ok(success_result(format!("{}\n", lines.join("\n")), value))
}

/// `time_total`: the scope's shared total, and optionally its breakdown (FR-003).
pub(super) fn time_total(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Some(refusal) = time_arguments(args, TIME_TOTAL_ARGS) {
        return Ok(refusal);
    }
    // The selector is resolved first, before anything is read: `tix time total <ISSUE>`
    // takes the same selector and refuses an unresolvable one the same way. An issue
    // that resolves but is **archived** is `total`'s own refusal — the snapshot is the
    // project's active enumeration, so it deliberately does not hold it — and it is the
    // CLI's, rendered by the shared owner rather than re-worded here.
    let selected = match opt_selector(args, "issue")? {
        Some(raw) => match store.resolve_issue(&raw) {
            Ok(issue) if issue.archived => {
                return Ok(time_refusal(&cmd_time::archived_refusal(&issue, &raw)));
            }
            Ok(issue) => Some(issue.number),
            Err(error) => return Ok(time_refusal(&error)),
        },
        None => None,
    };
    // The breakdown is the CLI's own parse, so an unknown `by` word is refused in the
    // CLI's sentence.
    let breakdown = match cmd_time::parse_breakdown(opt_string(args, "by")?.as_deref()) {
        Ok(breakdown) => breakdown,
        Err(error) => return Ok(time_refusal(&error)),
    };
    let mut filter = TimeFilter::new();
    if let Some(number) = selected {
        filter = filter.for_issue(number);
    }
    if let Some(assignee) = opt_string(args, "assignee")? {
        filter = filter.for_assignee(assignee);
    }
    if let Some(from) = opt_string(args, "from")? {
        filter = filter.since(from);
    }
    if let Some(to) = opt_string(args, "to")? {
        filter = filter.until(to);
    }
    if opt_bool(args, "audit")?.unwrap_or(false) {
        filter = filter.including_deleted();
    }
    // One snapshot over the project's active issues — the enumeration `tix list`,
    // `tix capacity` and `tix time total` share — so no two blocks can count a
    // different membership.
    let snapshot = match store.list() {
        Ok(issues) => TimeSnapshot::of(&issues),
        Err(error) => return Ok(time_refusal(&error)),
    };
    let scope = snapshot.total(&filter);
    let (mut text, mut value) = match time_scope_payload(&scope) {
        Ok(payload) => payload,
        Err(refusal) => return Ok(error_result(refusal)),
    };
    if let Some(breakdown) = breakdown {
        let groups = match breakdown {
            cmd_time::Breakdown::Issue => snapshot.by_issue(&filter),
            cmd_time::Breakdown::Assignee => snapshot.by_assignee(&filter),
            cmd_time::Breakdown::Date => snapshot.by_date(&filter),
        };
        let mut values = Vec::with_capacity(groups.len());
        for group in &groups {
            // A breakdown of a scope that already answered cannot be refused — the
            // groups partition the same selection — but the arm keeps a shared change
            // from silently emitting an unrefused, unlabelled group.
            let (block, group_value) = match time_scope_payload(group) {
                Ok(payload) => payload,
                Err(refusal) => return Ok(error_result(refusal)),
            };
            // The scope block, a blank line, then the group — as the CLI prints them.
            text.push_str("\n\n");
            text.push_str(&block);
            values.push(group_value);
        }
        value["groups"] = Value::Array(values);
    }
    // The CLI's stdout ends with the last `println!`'s newline; the text is it verbatim.
    Ok(success_result(format!("{}\n", text), value))
}

pub(super) fn dispatch(
    config: &Config,
    store: &Store,
    name: &str,
    arguments: &Value,
) -> Option<ToolOutcome> {
    match name {
        "time_show" => Some(time_show(config, store, arguments)),
        "time_history" => Some(time_history(config, store, arguments)),
        "time_total" => Some(time_total(config, store, arguments)),
        "time_add" => Some(time_add(config, store, arguments)),
        "time_edit" => Some(time_edit(config, store, arguments)),
        "time_delete" => Some(time_delete(config, store, arguments)),
        _ => None,
    }
}

/// The arguments each time tool declares.
///
/// The schemas promise `additionalProperties: false` and nothing below a schema
/// enforces it, so this is the boundary that has to hold: a key outside the list is
/// refused by name ([`time_arguments`]), which is also how a `timer`, a `timezone` or
/// a `billing` payload is answered (C-009) instead of being silently ignored.
pub(super) const TIME_SHOW_ARGS: &[&str] = &["issue"];
pub(super) const TIME_HISTORY_ARGS: &[&str] = &["issue"];
pub(super) const TIME_TOTAL_ARGS: &[&str] = &["issue", "assignee", "from", "to", "audit", "by"];
pub(super) const TIME_ADD_ARGS: &[&str] = &[
    "issue",
    "minutes",
    "date",
    "author",
    "note",
    "actor",
    "timestamp",
    "reason",
];
pub(super) const TIME_EDIT_ARGS: &[&str] = &[
    "issue",
    "entry",
    "minutes",
    "date",
    "clear_date",
    "note",
    "clear_note",
    "author",
    "reason",
    "actor",
    "timestamp",
];
pub(super) const TIME_DELETE_ARGS: &[&str] =
    &["issue", "entry", "reason", "confirm", "actor", "timestamp"];

/// The sentence a contradictory edit is refused with.
///
/// `clap` refuses `--date` beside `--clear-date` (and `--note` beside `--clear-note`)
/// before `commands::time` ever runs, and a `clap` usage block is not a sentence two
/// surfaces can share. This is therefore the one refusal the two spell differently,
/// and it exists because accepting the pair would accept a call the CLI rejects.
pub(super) fn time_edit_conflict(field: &str, clear: &str) -> String {
    format!(
        "a time edit names `{field}` once: pass either `{field}` (the replacement value) or \
         `{clear}` (remove it), never both — nothing was written"
    )
}

/// Refuse any argument a time tool does not declare.
///
/// The declared model is closed (C-002, C-009): a duration in whole minutes, an
/// optional `YYYY-MM-DD` calendar date, an author and an optional note. Silently
/// ignoring `{"timer": true}` is how a client comes to believe it started one — and
/// how a timezone, an overlap policy or a billing rate would arrive by accident — so
/// an undeclared key is refused by name, with the reason and the remedy.
pub(super) fn time_arguments(args: &Value, allowed: &[&str]) -> Option<Value> {
    let object = args.as_object()?;
    let unknown: Vec<&str> = object
        .keys()
        .map(String::as_str)
        .filter(|key| !allowed.contains(key))
        .collect();
    if unknown.is_empty() {
        return None;
    }
    let listed = unknown
        .iter()
        .map(|key| format!("`{key}`"))
        .collect::<Vec<String>>()
        .join(", ");
    let verb = if unknown.len() == 1 { "is" } else { "are" };
    Some(error_result(format!(
        "invalid input: {listed} {verb} not a field of this tool. The time model is one duration in \
         whole minutes plus an optional `YYYY-MM-DD` calendar date, an author and an optional note \
         (C-002): there is no timer, no start/stop state, no timezone conversion, no overlap rule \
         and no billing, payroll or invoicing field, and this surface has none either."
    )))
}

/// The refusal a shared `tix` error renders as, verbatim.
///
/// [`crate::error::render_error`] is the crate's one error renderer, so a sentence this
/// surface shares with the CLI — the missing confirmation, an unknown `--by`
/// dimension, an unresolvable selector — reaches an agent as the bytes the CLI writes
/// to stderr.
pub(super) fn time_refusal(error: &crate::error::TixError) -> Value {
    error_result(crate::error::render_error(error))
}

/// The shared sentence for a caller's invalid input.
pub(super) fn time_input_refusal(sentence: String) -> Value {
    time_refusal(&crate::error::TixError::InvalidInput(sentence))
}

/// The summed minutes as a JSON number, or `null` when the scope counted nothing.
///
/// The shared accumulator holds an `i128` and every counted minute is at or above zero
/// ([`TimeEntry::minutes`] refuses a negative one), so `u64` is always wide enough for
/// a real store. A sum that somehow is not is refused rather than rounded, wrapped or
/// reported as `null`: a value the payload has and cannot type is not a value it may
/// quietly drop, and a silent `null` here would read as "nothing was counted".
pub(super) fn time_minutes_value(minutes: Option<i128>) -> std::result::Result<Value, String> {
    match minutes {
        None => Ok(Value::Null),
        Some(minutes) => u64::try_from(minutes)
            .map(|minutes| Value::Number(minutes.into()))
            .map_err(|_| {
                format!(
                    "internal error: the counted total is {minutes} minutes, which is not a number \
                     this payload can carry; the text channel carries it, and nothing was written"
                )
            }),
    }
}

/// One shared finding: the kind, what it is about, the reason and the remedy.
///
/// Every field is the DTO's own, and `scope`/`entry` is the DTO's own invariant
/// (`is_scope_finding`): a finding about an entry always names it.
pub(super) fn time_diagnostic_value(finding: &TimeDiagnostic) -> Value {
    json!({
        "kind": finding.kind.as_str(),
        "issue": finding.issue,
        "entry_id": finding.entry_id,
        "field": finding.field,
        "reason": finding.reason,
        "remedy": finding.remedy,
        "scope": if finding.is_scope_finding() { "scope" } else { "entry" },
    })
}

/// Every finding, in the DTO's own order (scope findings first, then per entry).
pub(super) fn time_diagnostics_value(findings: &[TimeDiagnostic]) -> Value {
    Value::Array(findings.iter().map(time_diagnostic_value).collect())
}

/// One current entry as the DTO's own fields.
///
/// The preserved metadata goes into a **nested** `extensions` object rather than being
/// flattened beside the typed fields. A flattened bag is how a preserved key comes to
/// shadow a projected one — the defect a sibling mission's review found, where a client
/// could no longer read back the document the tool had written — and an entry's
/// preserved keys are untyped by definition, so the payload keeps them apart.
/// `duration_minutes`, `date` and `note` are `null` when the entry carries none: a
/// malformed entry stays readable and never reads as zero minutes.
pub(super) fn time_entry_value(issue: u32, entry: &TimeEntry) -> Value {
    json!({
        "issue": issue,
        "id": entry.id,
        "duration_minutes": entry.duration_minutes,
        "date": entry.date,
        "author": entry.author,
        "note": entry.note,
        "extensions": yaml_map_value(entry.extensions.as_map()),
    })
}

/// One total as values: the DTO's fields, nothing recomputed.
///
/// `total_minutes` and `deleted_count` are `null` when the DTO says so — the first when
/// nothing was counted (never `0`), the second unless the filter asked for audit
/// context, because an unrequested count and a zero count are different facts.
pub(super) fn time_total_value(total: &TimeTotal) -> std::result::Result<Value, String> {
    Ok(json!({
        "group": total.group.label(),
        "scope": total.filter.describe(),
        "state": total.state().as_str(),
        "total_minutes": time_minutes_value(total.total_minutes)?,
        "entry_count": total.entry_count,
        "malformed_count": total.malformed_count,
        "undated_count": total.undated_count,
        "is_partial": total.is_partial(),
        "deleted_count": total.deleted_count,
        "diagnostics": time_diagnostics_value(&total.diagnostics),
    }))
}

/// One scope's text and structure, or the refusal that has neither.
///
/// A `state` of `invalid_filter` or `unknown_issue` is a **refusal, not an answer**:
/// no entry was evaluated, so there is no total to report, and the findings say what
/// to fix. That is the CLI's own rule (it exits 2 on the same two states), and the
/// refusal *bytes* are the CLI's own too — [`cmd_time::refusal_blocks`] is the one owner
/// of that block, so an agent reading an error result reads the CLI's stderr.
pub(super) fn time_scope_payload(
    total: &TimeTotal,
) -> std::result::Result<(String, Value), String> {
    if matches!(
        total.state(),
        TimeTotalState::InvalidFilter | TimeTotalState::UnknownIssue
    ) {
        return Err(cmd_time::refusal_blocks(&total.diagnostics));
    }
    Ok((cmd_time::scope_block(total), time_total_value(total)?))
}

/// The issue a time read is about, indexed on its own.
///
/// The crate's own selector grammar resolves it (`store.resolve_issue`), so an
/// archived or otherwise off-view issue is still readable by the selector that names
/// it — exactly as `tix time show` reads it — and the snapshot holds that one issue.
pub(super) fn time_issue_snapshot(store: &Store, selector: &str) -> TixResult<(u32, TimeSnapshot)> {
    let issue = store.resolve_issue(selector)?;
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));
    Ok((issue.number, snapshot))
}

/// What an applied mutation did, in the vocabulary the payload and the CLI's sentence
/// both use.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum TimeMutationStatus {
    /// A create.
    Created,
    /// A correction that changed something.
    Updated,
    /// A request that asked for exactly what was already there.
    Unchanged,
    /// A deletion.
    Deleted,
}

impl TimeMutationStatus {
    /// The stable spelling the payload carries.
    const fn as_str(self) -> &'static str {
        match self {
            Self::Created => "created",
            Self::Updated => "updated",
            Self::Unchanged => "unchanged",
            Self::Deleted => "deleted",
        }
    }
}

/// Fold the shared attribution onto a request: who, when, why.
///
/// `actor` and `timestamp` are the service's own seams and are optional — `None` means
/// the crate's git identity and its own clock, exactly as the CLI's flags leave them.
/// `reason` is **not** validated here: the service requires one for an edit and a
/// delete and refuses a blank one by name, so the requirement keeps one owner rather
/// than two.
pub(super) fn time_request(
    args: &Value,
    request: TimeMutationRequest,
) -> std::result::Result<TimeMutationRequest, ()> {
    let mut request = request;
    if let Some(actor) = opt_string(args, "actor")? {
        request = request.by(actor);
    }
    if let Some(timestamp) = opt_string(args, "timestamp")? {
        request = request.at(timestamp);
    }
    if let Some(reason) = opt_string(args, "reason")? {
        request.attribution.reason = Some(reason);
    }
    Ok(request)
}

/// Apply one mutation through the shared service and answer with its own outcome.
///
/// The text is the CLI's own sentence for the same mutation; the structure carries the
/// service's outcome: the status, the stable id, the prior and new values (the
/// [`TimeEntry`] DTO's own fields, `null` for the side a mutation does not have) and
/// the **one** History event that was appended — `null` for the no-op an unchanged
/// request is, which is the only case that writes nothing (C-003, NFR-002).
pub(super) fn time_mutation(store: &Store, request: &TimeMutationRequest) -> ToolOutcome {
    let applied = match apply_time(store, request) {
        Ok(applied) => applied,
        Err(error) => return Ok(time_refusal(&error)),
    };
    let outcome = &applied.outcome;
    let number = applied.issue.number;
    let status = if !outcome.changed {
        TimeMutationStatus::Unchanged
    } else if outcome.before.is_none() {
        TimeMutationStatus::Created
    } else if outcome.after.is_some() {
        TimeMutationStatus::Updated
    } else {
        TimeMutationStatus::Deleted
    };
    // The CLI's own sentence, from the CLI's one owner: a human reading either surface
    // reads the same thing (C-006).
    let text = cmd_time::mutation_sentence(&applied);
    let structured = json!({
        "status": status.as_str(),
        "issue": number,
        "entry_id": outcome.entry_id,
        "changed": outcome.changed,
        "before": outcome.before.as_ref().map(|entry| time_entry_value(number, entry)),
        "after": outcome.after.as_ref().map(|entry| time_entry_value(number, entry)),
        "history": applied.event().map(|event| json!({
            "kind": event.kind.as_str(),
            "actor": event.actor,
            "timestamp": event.timestamp,
            "detail": event.detail,
        })),
    });
    Ok(success_result(format!("{text}\n"), structured))
}

// ---------------------------------------------------------------------------
// WP07 (mission `burndown-scope-analytics-01M3C9J1`) — the analytics tools
// ---------------------------------------------------------------------------
//
// Four tools over the shared burndown/scope-analytics surface: the closed
// vocabularies and formulas (`analytics_metadata`), the daily count/estimate series
// (`analytics_burndown`), the read-only end-date forecast (`analytics_projection`)
// and the deterministic chart document (`analytics_export`).
//
// Nothing below folds a day, converts an estimate, resolves a period or serializes a
// document of its own. [`cmd_analytics`]'s report builders are the CLI's three verbs'
// own builders, so `content` is `tix analytics …`'s stdout byte for byte, and the
// document those builders returned **is** the `structuredContent`: a value the record
// cannot support stays `null` there (and `-` in the text), never a `0` (C-005), and a
// request-level refusal is [`crate::error::render_error`]'s block — the same bytes the
// CLI writes to stderr and exits non-zero with.