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

/// `bulk_capabilities` (T037): the portable projection, verbatim.
///
/// A tool rather than a field on the other two because `surface-parity.md` says the
/// remote projection "may report representability" — and a client that has to infer
/// it by trial and error is doing the parity work this mission exists to remove. The
/// payload is [`bulk::metadata::capabilities_json`] itself, so a client sees exactly
/// what the schema was generated from and the two cannot disagree.
pub(super) fn bulk_capabilities(_config: &Config, _store: &Store, _args: &Value) -> ToolOutcome {
    let caps = bulk::metadata::capabilities_json();
    let mut lines = vec!["Bulk operations available in this build:".to_string()];
    for op in bulk::metadata::BulkOperation::ALL {
        lines.push(format!(
            "  {} — {} [{}]",
            op.as_str(),
            op.summary(),
            op.availability().replace('_', " ")
        ));
    }
    lines.push("Patch fields:".to_string());
    for field in bulk::metadata::PATCH_FIELDS {
        lines.push(format!(
            "  {} — {}{}",
            field.name,
            field.summary,
            if field.clearable { " (clearable)" } else { "" }
        ));
    }
    lines.push(format!(
        "Outcome statuses: {}",
        bulk::metadata::OUTCOME_STATUSES.join(", ")
    ));
    lines.push("Selection grammar:".to_string());
    for line in bulk::metadata::SELECTION_GRAMMAR {
        lines.push(format!("  {line}"));
    }
    Ok(success_result(lines.join("\n"), caps))
}

/// `bulk_preview` / `bulk_apply` (T036): the shared plan and apply, projected to JSON.
#[allow(clippy::too_many_lines)]
pub(super) fn bulk_run(store: &Store, args: &Value, apply: bool) -> ToolOutcome {
    if apply {
        // C-004. Checked **before** anything is resolved, so a client that forgot the
        // confirmation gets the refusal without having paid for a 10,000-issue plan.
        match opt_bool(args, "confirm") {
            Ok(Some(true)) => {}
            Ok(_) => {
                return Ok(error_result(
                    "confirm is required and must be true — a batch apply writes files \
                     and appends History, so nothing is written without it (C-004). Call \
                     bulk_preview first; it is read-only."
                        .to_string(),
                ));
            }
            Err(()) => return Err(()),
        }
    }
    // An absent or non-string `operation` is a **protocol** error (`-32602`), the
    // same treatment `req_string` gives every other required argument. A well-formed
    // but unknown operation is a **tool** result, because the client sent well-formed
    // JSON and deserves a message it can read rather than a protocol failure.
    let operation_raw = match req_string(args, "operation") {
        Ok(raw) => raw,
        Err(()) => return Err(()),
    };
    let operation_raw = operation_raw.trim().to_string();
    if let Err(problem) = bulk::metadata::check_operation(&operation_raw) {
        return Ok(error_result(problem.to_string()));
    }
    let operation = bulk::metadata::BulkOperation::from_name(&operation_raw)
        .expect("check_operation accepted it, so from_name did too");
    // Whether the build can **perform** it is decided at the apply, not here: the
    // refusal has to name every selected issue, and that needs the plan. Refusing at
    // the request boundary would produce a message about a mission with no issue in
    // it — the one thing WP05's CLI explicitly avoids.
    // The helpers return a finished `ToolOutcome` on refusal, so this is one `?`:
    // a protocol error stays a protocol error and a refusal stays a tool result,
    // because the helper already chose which.
    // The helpers return a **finished** `ToolOutcome` on refusal, so this `?` cannot
    // flatten the two kinds: `Err(())` stays a protocol error and
    // `Ok(error_result(..))` comes back as a tool result, because the helper already
    // chose which and the handler returns it untouched.
    let (request, flags) = match (bulk_request(args), bulk_flags(args)) {
        (Ok(request), Ok(flags)) => (request, flags),
        // The **first** refusal wins. Running both and reporting the second would let
        // a client see a schema complaint about a field when the real problem is that
        // it named two selection grammars.
        (Err(outcome), _) | (_, Err(outcome)) => return outcome,
    };

    let selection = match cmd_bulk::resolve(store, &request) {
        Ok(selection) => selection,
        Err(e) => return Ok(error_result(crate::error::render_error(&e))),
    };
    let patch = match operation {
        bulk::metadata::BulkOperation::Edit => match flags.to_patch() {
            Ok(patch) => patch,
            Err(e) => return Ok(error_result(crate::error::render_error(&e))),
        },
        bulk::metadata::BulkOperation::Link | bulk::metadata::BulkOperation::Unlink => {
            let target = opt_string(args, "target")?;
            let Some(target) = target.filter(|t| !t.trim().is_empty()) else {
                return Ok(error_result(
                    "a pair needs a target — `target` is required for link and unlink".to_string(),
                ));
            };
            // The kind is resolved **once**, through the relationship service's own
            // parser, exactly as the CLI's `run_pair` does. A missing or unknown kind
            // is therefore the service's message and not this handler's, which is the
            // parity `surface-parity.md` asks for. Resolving it per issue would report
            // the same refusal ten times for a ten-issue batch.
            let kind =
                match crate::commands::link::require_kind(opt_string(args, "type")?.as_deref()) {
                    Ok(kind) => kind,
                    Err(e) => return Ok(error_result(crate::error::render_error(&e))),
                };
            // Per selected issue: `from` is a single issue in the relationship
            // vocabulary, so a batch is a set of edges rather than one edge with a
            // compound endpoint. The same rule the TUI follows.
            //
            // And each is planned and applied on its own, so a mixed result is a set
            // of per-item statuses rather than one verdict for the batch (C-005).
            let mut outcomes: Vec<PairRow> = Vec::new();
            for issue in selection.issues() {
                let op = if operation == bulk::metadata::BulkOperation::Unlink {
                    bulk::RelationshipOp::unlink(issue.number.to_string(), target.clone(), kind)
                } else {
                    bulk::RelationshipOp::link(issue.number.to_string(), target.clone(), kind)
                };
                let one = bulk::Selection::from_issues(
                    vec![issue.clone()],
                    bulk::SelectionSource::Explicit,
                    bulk::SelectionScope::Active,
                );
                let per_item = cmd_bulk::build(
                    store,
                    one,
                    bulk::IssuePatch {
                        relationship: Some(op),
                        ..bulk::IssuePatch::default()
                    },
                )
                .map(|mut plan| {
                    plan.confirmation = apply.then(|| bulk::Confirmation::issue(&plan));
                    plan
                });
                match per_item {
                    // A pair is planned and applied per item, so a mixed result is a
                    // set of per-item statuses rather than one verdict for the batch
                    // (C-005). A preview reports what each pair *would* do, from the
                    // plan it built and nothing else — which is what keeps a preview
                    // read-only (C-004).
                    Ok(plan) if apply => match bulk::apply_pair(store, &plan) {
                        Ok(outcome) => outcomes.push(PairRow {
                            number: issue.number,
                            title: issue.title.clone(),
                            status: outcome.status(),
                            line: outcome.as_line(),
                            files: outcome.files().to_vec(),
                        }),
                        // A write that failed is a **failed** status with the error
                        // attached, not a refusal: the attempt happened. The diagnostic
                        // is built rather than invented — `field: "target"` and
                        // `issue:` are the plan's own, so a client sees the same shape
                        // a field apply produces.
                        Err(e) => outcomes.push(PairRow {
                            number: issue.number,
                            title: issue.title.clone(),
                            status: "failed",
                            line: format!(
                                "#{} {} -> failed (target): {e}",
                                issue.number, issue.title
                            ),
                            files: Vec::new(),
                        }),
                    },
                    Ok(plan) => {
                        let (status, line) =
                            match plan.items.first().and_then(|i| i.diagnostic.as_ref()) {
                                Some(d) => ("rejected", d.message.clone()),
                                None if plan
                                    .items
                                    .first()
                                    .is_some_and(bulk::plan::ItemPlan::is_actionable) =>
                                {
                                    (
                                        "applied",
                                        format!("#{} {} -> would apply", issue.number, issue.title),
                                    )
                                }
                                None => (
                                    "no-op",
                                    format!(
                                        "#{} {} -> already in that state",
                                        issue.number, issue.title
                                    ),
                                ),
                            };
                        outcomes.push(PairRow {
                            number: issue.number,
                            title: issue.title.clone(),
                            status,
                            line,
                            files: Vec::new(),
                        });
                    }
                    Err(e) => outcomes.push(PairRow {
                        number: issue.number,
                        title: issue.title.clone(),
                        status: "rejected",
                        line: format!("#{} {} -> refused: {e}", issue.number, issue.title),
                        files: Vec::new(),
                    }),
                }
            }
            // No batch `ApplyReport` is built here, and deliberately: a pair apply has
            // its own outcome type because a pair writes **two** files, so forcing it
            // into `ApplyReport` would produce a report whose `write_failures` is
            // always empty and whose `Applied` carries one filename for two writes.
            // `PairRow` is the projection — one row per selected issue, `status` from
            // the same vocabulary — and it is what both the text and the JSON read.
            let applied = outcomes.iter().filter(|r| r.status == "applied").count();
            let no_op = outcomes.iter().filter(|r| r.status == "no-op").count();
            let rejected = outcomes.iter().filter(|r| r.status == "rejected").count();
            let failed = outcomes.iter().filter(|r| r.status == "failed").count();
            let structured = json!({
                "applied": applied,
                "no_op": no_op,
                "rejected": rejected,
                "failed": failed,
                "operation": operation.as_str(),
                "outcomes": outcomes.iter().map(|r| json!({
                    "number": r.number,
                    "title": r.title,
                    "status": r.status,
                    "line": r.line,
                    // Both ends, because a pair is two named endpoints and a report
                    // that names one of them is a flattened write with extra steps.
                    "files": r.files,
                })).collect::<Vec<_>>(),
            });
            let mut text = format!(
                "{} issue(s) selected for {}\n",
                outcomes.len(),
                operation.as_str()
            );
            for row in &outcomes {
                text.push_str(&format!("{}\n", row.line));
            }
            text.push_str(&format!(
                "\n{applied} applied, {rejected} refused, {no_op} no-op, {failed} failed\n"
            ));
            return Ok(success_result(text, structured));
        }
        bulk::metadata::BulkOperation::Archive => bulk::IssuePatch {
            archive: Some(bulk::ArchiveRequest::archive()),
            ..bulk::IssuePatch::default()
        },
    };
    let plan = match cmd_bulk::build(store, selection, patch) {
        Ok(plan) => plan,
        Err(e) => return Ok(error_result(crate::error::render_error(&e))),
    };
    if !apply {
        return Ok(success_result(
            cmd_bulk::render_plan(&plan, cmd_bulk::Mode::Preview),
            bulk_plan_value(&plan, false),
        ));
    }
    // The apply-time refusal seam (`check_applicable`) now admits every operation —
    // `archive` delegates to the store's archive service — so a performability refusal
    // no longer exists to report here. The malformed-operation refusal still lives at
    // the boundary (`check_operation`, above), where no plan exists to name.
    let mut confirmed = plan.clone();
    confirmed.confirmation = Some(bulk::Confirmation::issue(&plan));
    // The archive direction goes through the store's archive service via the same
    // `apply_archive` the CLI uses; every other operation is the field path. Both
    // return the shared `ApplyReport`, so the JSON projection and the text are shared
    // (surface parity) rather than two descriptions of the same batch.
    let report = match operation {
        bulk::metadata::BulkOperation::Archive => match bulk::apply_archive(store, &confirmed) {
            Ok(report) => report,
            Err(e) => return Ok(error_result(crate::error::render_error(&e))),
        },
        _ => match bulk::apply_fields(store, &confirmed, &crate::storage::actor_identity(), None) {
            Ok(report) => report,
            Err(e) => return Ok(error_result(crate::error::render_error(&e))),
        },
    };
    let structured = bulk_report_value(&report, &confirmed);
    let text = cmd_bulk::render_report(&report, &confirmed, cmd_bulk::Mode::Apply);
    Ok(success_result(text, structured))
}

pub(super) fn dispatch(
    config: &Config,
    store: &Store,
    name: &str,
    arguments: &Value,
) -> Option<ToolOutcome> {
    match name {
        "bulk_preview" => Some(bulk_run(store, arguments, false)),
        "bulk_apply" => Some(bulk_run(store, arguments, true)),
        "bulk_capabilities" => Some(bulk_capabilities(config, store, arguments)),
        _ => None,
    }
}

/// The `PatchFlags` a batch request carries, read from the shared field names.
///
/// Reads **only** names the projection lists, and the schema's `additionalProperties:
/// false` is what stops anything else arriving. The check is repeated here anyway,
/// because a schema is documentation a client may ignore and this is the boundary
/// that has to hold (C-008: an unlisted field mutation is an escalation trigger).
///
/// The error type is [`ToolOutcome`], so a malformed argument and a refused request
/// are different **types** rather than two spellings of the same one: `Err(())` is a
/// `-32602` and `Ok(error_result(..))` is a tool result. Getting that wrong is the
/// difference between an agent reading "name exactly one of --select, --filter or
/// --search" and an agent seeing a protocol failure with no explanation.
pub(super) fn bulk_flags(args: &Value) -> ToolOutcome2<cmd_bulk::PatchFlags> {
    let mut flags = cmd_bulk::PatchFlags::default();
    for (key, slot) in [
        ("status", &mut flags.status),
        ("priority", &mut flags.priority),
        ("assignee", &mut flags.assignee),
        ("labels", &mut flags.labels),
        ("start-date", &mut flags.start_date),
        ("due-date", &mut flags.due_date),
        ("estimate", &mut flags.estimate),
        ("cycles", &mut flags.cycles),
        ("milestones", &mut flags.milestones),
    ] {
        if let Err(problem) = bulk::metadata::check_field(key) {
            return Err(refuse(problem.to_string()));
        }
        let value = opt_string(args, key).map_err(|()| proto())?;
        // A blank value is **absent**, exactly as the CLI treats `--estimate ""`:
        // `Unchanged`, never `Clear` and never `Set("")`. WP06 found that rule the
        // hard way and it is the one thing an MCP client is most likely to get wrong.
        *slot = value.filter(|v| !v.trim().is_empty());
    }
    if let Some(clear) = opt_string(args, "clear").map_err(|()| proto())? {
        let field = clear.trim().to_string();
        if !field.is_empty() {
            if let Err(problem) = bulk::metadata::check_field(&field) {
                return Err(refuse(problem.to_string()));
            }
            if !cmd_bulk::PatchFlags::is_clearable(&field) {
                return Err(refuse(format!(
                    "cannot clear '{field}' — clearable fields: {}",
                    bulk::metadata::clearable_field_names().join(", ")
                )));
            }
            flags.clear = vec![field];
        }
    }
    Ok(flags)
}

/// The selection request, built by the **shared** builder so the refusal is the
/// CLI's message rather than this handler's.
pub(super) fn bulk_request(args: &Value) -> ToolOutcome2<cmd_bulk::SelectionRequest> {
    let selectors = opt_string(args, "select").map_err(|()| proto())?;
    let filter = opt_string(args, "filter").map_err(|()| proto())?;
    let search = opt_string(args, "search").map_err(|()| proto())?;
    let scope = match opt_string(args, "scope").map_err(|()| proto())?.as_deref() {
        None | Some("") => bulk::SelectionScope::Active,
        // The scope names the CLI's `--scope` accepts, spelled the same way. A wrong
        // name is refused rather than silently becoming `Active`, because the two
        // non-default scopes are how a user reaches archived issues and defaulting
        // would quietly narrow their request.
        Some("all") => bulk::SelectionScope::ActiveAndArchived,
        Some("archived") => bulk::SelectionScope::ArchivedOnly,
        Some(other) => {
            return Err(refuse(format!(
                "unknown scope '{other}' — `active` (default), `all` (active and \
                 archived), or `archived`"
            )));
        }
    };
    let selectors = selectors
        .map(|raw| raw.split(',').map(str::to_string).collect::<Vec<_>>())
        .unwrap_or_default();
    // The **shared** builder, so a client that names zero or two grammars reads the
    // CLI's own message rather than a schema's.
    cmd_bulk::SelectionRequest::new(&selectors, filter.as_deref(), search.as_deref(), scope)
        .map_err(|e| refuse(e.to_string()))
}

/// One selected issue's pair outcome, as a surface reports it.
///
/// A **projection**, not an apply type. A pair writes two files and a field edit
/// writes one, so there is no single `ItemOutcome` that describes both honestly —
/// and the point of the row is that the *status word* is the shared part, not the
/// payload.
pub(super) struct PairRow {
    number: u32,
    title: String,
    /// From `PairOutcome::status` or one of the plan-side words above; the same
    /// vocabulary `ItemOutcome::status` uses.
    status: &'static str,
    line: String,
    /// Both ends for a pair, empty for a refusal or a no-op.
    files: Vec<String>,
}

/// The plan as JSON: selection order, proposed changes, paths, diagnostics.
///
/// Every field `surface-parity.md` §1 lists, and nothing invented — a key here that
/// the CLI does not print is a second contract.
pub(super) fn bulk_plan_value(plan: &bulk::plan::BatchPlan, applied: bool) -> Value {
    json!({
        "applied": applied,
        "selection": plan.selection.issues().iter()
            .map(|i| json!({ "number": i.number, "title": i.title }))
            .collect::<Vec<_>>(),
        "items": plan.items.iter().map(|item| json!({
            "number": item.number,
            "title": item.title,
            "status": item.status(),
            "changes": item.changes.iter()
                .map(|(field, change)| {
                    // `as_from_to` rather than a match here, so a `Clear` and a
                    // `NoChange` project the same way on every surface.
                    let (from, to) = change.as_from_to();
                    json!({ "field": field, "from": from, "to": to })
                })
                .collect::<Vec<_>>(),
            "path_change": item.path_change.as_ref().map(|p| json!({
                "from": p.from,
                "to": p.to,
            })),
            "history": item.history.iter()
                .map(|h| json!({ "kind": h.kind, "detail": h.detail }))
                .collect::<Vec<_>>(),
            "diagnostic": item.diagnostic.as_ref().map(|d| json!({
                "issue": d.issue,
                "field": d.field,
                "message": d.message,
            })),
        })).collect::<Vec<_>>(),
    })
}

/// The report as JSON: exactly one outcome per selected issue (NFR-002).
pub(super) fn bulk_report_value(report: &bulk::ApplyReport, plan: &bulk::plan::BatchPlan) -> Value {
    let titles: Vec<(u32, String)> = plan
        .items
        .iter()
        .map(|i| (i.number, i.title.clone()))
        .collect();
    json!({
        "applied": report.applied(),
        "no_op": report.noop(),
        "rejected": report.rejected(),
        "failed": report.failed(),
        "outcomes": report.outcomes.iter().map(|(number, outcome)| {
            let title = titles.iter().find(|(n, _)| n == number)
                .map(|(_, t)| t.as_str()).unwrap_or("");
            json!({
                "number": number,
                "title": title,
                // The shared vocabulary word, from `ItemOutcome::status` — not a
                // re-derived string, or NFR-003 would be a claim about this handler.
                "status": outcome.status(),
                "line": outcome.as_line(*number, title),
            })
        }).collect::<Vec<_>>(),
    })
}