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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
#[allow(clippy::wildcard_imports)]
use super::*;

/// `view_apply` (T031): read-only apply — plan, issue set, board summary, active
/// marker, and diagnostics. Writes nothing (C-005).
pub(super) fn view_apply(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(args, &["view"]) {
        return Ok(value);
    }
    let reference = req_string(args, "view")?;
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    // Read the board and the category resolution *before* the service takes the
    // mutable borrow of the config — the same order `commands::views::run` uses.
    let board = ctx.config.default_config().clone();
    let resolution = crate::workflow::active_resolution(&ctx.config).1;
    let mut service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);

    let detail = match service.show(&reference) {
        Ok(detail) => detail,
        Err(refusal) => return Ok(view_refusal_result(&refusal)),
    };
    // The marker is installed after a successful resolve and is informational:
    // nothing on disk changes and live filters are never overwritten (C-006).
    if let Err(refusal) = service.mark_active(&reference, Some(ViewSurface::Mcp)) {
        return Ok(view_refusal_result(&refusal));
    }
    let corpus = match Corpus::build(store) {
        Ok(corpus) => corpus,
        Err(error) => return Ok(error_result(error.to_string())),
    };
    let result = match service.apply(&reference, &board, &corpus, &resolution) {
        Ok(result) => result,
        Err(refusal) => return Ok(view_refusal_result(&refusal)),
    };
    let marker = service.active();

    Ok(success_result(
        view_apply_text(detail.view(), detail.plan(), &result),
        json!({
            "view_id": detail.view().id.as_str(),
            "name": detail.view().name,
            "scope": scope_value(&detail.view().scope),
            "resolution": detail.view().scope.resolution(&ctx.projects).as_str(),
            "plan": plan_value(detail.plan()),
            "active": marker.map(marker_value),
            "issues": result.issue_numbers(),
            "count": result.issue_numbers().len(),
            "board": board_summary_value(result.board()),
            "diagnostics": result
                .diagnostics()
                .iter()
                .map(diagnostic_value)
                .collect::<Vec<_>>(),
        }),
    ))
}

/// `view_create` (T030): a new definition under a freshly allocated stable id.
pub(super) fn view_create(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(
        args,
        &[
            "name",
            "scope",
            "project",
            "owner",
            "shared_with",
            "filter",
            "sort",
            "group",
            "hide_columns",
            "show_mismatch",
        ],
    ) {
        return Ok(value);
    }
    let name = req_string(args, "name")?;
    let scope_args = view_scope_args(args)?;
    let plan_args = view_plan_args(args)?;
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    let mut service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);

    let scope = match cmd_views::build_scope(&scope_args) {
        Ok(scope) => scope,
        Err(refusal) => return Ok(view_refusal_result(&refusal)),
    };
    let plan = match cmd_views::plan_from_args(store, &plan_args) {
        Ok(plan) => plan,
        Err(error) => return Ok(view_filter_rejection(&error)),
    };
    match service.create(ViewDefinition::new(name, scope, plan)) {
        Ok(outcome) => {
            let audit = outcome.audit().cloned();
            let id = outcome.into_value();
            Ok(success_result(
                format!("Created {id}"),
                view_accepted_value("accepted", "create", &id, &service, &ctx.projects, audit),
            ))
        }
        Err(error) => Ok(view_write_result(&error)),
    }
}

/// `view_delete` (T030): the **definition only**, and only under a deliberate
/// confirmation (C-005).
pub(super) fn view_delete(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(args, &["view", "confirm"]) {
        return Ok(value);
    }
    let reference = req_string(args, "view")?;
    if args.get("confirm").and_then(Value::as_bool) != Some(true) {
        return Ok(view_rejection(
            DELETE_CONFIRMATION.to_string(),
            &[ViewDiagnostic::new(
                ViewDiagnosticKind::InvalidView,
                DELETE_CONFIRMATION,
            )
            .with_field("confirm")
            .with_remedy(
                "pass `confirm: true` to acknowledge that only the saved definition is removed",
            )],
        ));
    }
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    let mut service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);

    match service.delete(&reference, DeleteConfirmed::confirmed()) {
        Ok(outcome) => {
            let audit = outcome.audit().cloned();
            let removed = outcome.into_value();
            let view = removed.view();
            let plan = ViewPlan::from_toml(&view.plan).ok();
            let mut text = format!("Deleted {}", view.id);
            if removed.marker_cleared() {
                text.push_str("\nactive-marker: cleared");
            }
            Ok(success_result(
                text,
                json!({
                    "status": "accepted",
                    "operation": "delete",
                    "view": view_value(view, plan.as_ref(), &[], &ctx.projects),
                    "marker_cleared": removed.marker_cleared(),
                    "audit": audit.as_ref().map(audit_value),
                }),
            ))
        }
        Err(error) => Ok(view_write_result(&error)),
    }
}

/// `view_duplicate` (T030): copy under a new stable id, carrying the source's
/// scope, plan, and preserved extensions verbatim.
pub(super) fn view_duplicate(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(args, &["view", "name"]) {
        return Ok(value);
    }
    let reference = req_string(args, "view")?;
    let name = opt_string(args, "name")?;
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    let mut service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);

    match service.duplicate(&reference, name.as_deref()) {
        Ok(outcome) => {
            let audit = outcome.audit().cloned();
            let id = outcome.into_value();
            Ok(success_result(
                format!("Duplicated {id}"),
                view_accepted_value("accepted", "duplicate", &id, &service, &ctx.projects, audit),
            ))
        }
        Err(error) => Ok(view_write_result(&error)),
    }
}

/// `view_list` (T029): the registry in declaration order, as `tix view list`
/// renders it, plus each entry's normalized plan, extensions, and diagnostics.
pub(super) fn view_list(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(args, &["scope"]) {
        return Ok(value);
    }
    let scope = match opt_string(args, "scope")? {
        Some(raw) => match cmd_views::parse_scope_kind(&raw) {
            Ok(kind) => Some(kind),
            Err(error) => return Ok(error_result(error.to_string())),
        },
        None => None,
    };
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    let service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);

    let mut rows = Vec::new();
    let mut entries = Vec::new();
    for view in service.list() {
        if scope.is_some_and(|kind| view.scope.kind != kind) {
            continue;
        }
        rows.push(format!(
            "{}\t{}\t{}\t{}",
            view.id,
            view.name,
            cmd_views::scope_label(&view.scope),
            view.scope.resolution(&ctx.projects),
        ));
        entries.push(match service.show(view.id.as_str()) {
            Ok(detail) => view_value(
                detail.view(),
                Some(detail.plan()),
                detail.diagnostics(),
                &ctx.projects,
            ),
            // A stored plan this build cannot interpret is listed (the CLI lists
            // it too) with its refusal's diagnostics rather than silently dropped.
            Err(refusal) => view_value(&view, None, refusal.diagnostics(), &ctx.projects),
        });
    }
    let mut text = String::new();
    for row in &rows {
        text.push_str(row);
        text.push('\n');
    }
    Ok(success_result(text, json!({ "views": entries })))
}

/// `view_share` (T030/FR-003): replace the explicit scope metadata, keeping the
/// name and plan. Scope stays metadata — no account, no permission (C-003).
pub(super) fn view_share(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(args, &["view", "scope", "project", "owner", "shared_with"])
    {
        return Ok(value);
    }
    let reference = req_string(args, "view")?;
    let scope_args = view_scope_args(args)?;
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    let mut service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);

    let detail = match service.show(&reference) {
        Ok(detail) => detail,
        Err(refusal) => return Ok(view_refusal_result(&refusal)),
    };
    let name = detail.view().name.clone();
    let plan = detail.plan().clone();
    let scope = match cmd_views::build_scope(&scope_args) {
        Ok(scope) => scope,
        Err(refusal) => return Ok(view_refusal_result(&refusal)),
    };
    match service.update(&reference, ViewDefinition::new(name, scope, plan)) {
        Ok(outcome) => {
            let no_op = outcome.is_noop();
            let audit = outcome.audit().cloned();
            let id = outcome.into_value();
            let (status, word) = if no_op {
                ("no-op", "Unchanged")
            } else {
                ("accepted", "Shared")
            };
            Ok(success_result(
                format!("{word} {id}"),
                view_accepted_value(status, "share", &id, &service, &ctx.projects, audit),
            ))
        }
        Err(error) => Ok(view_write_result(&error)),
    }
}

/// `view_show` (T029): one definition — id, name, scope, normalized plan,
/// preserved extensions, and diagnostics.
pub(super) fn view_show(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(args, &["view"]) {
        return Ok(value);
    }
    let reference = req_string(args, "view")?;
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    let service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);
    match service.show(&reference) {
        Ok(detail) => Ok(success_result(
            view_show_text(
                detail.view(),
                detail.plan(),
                &ctx.projects,
                detail.diagnostics(),
            ),
            view_value(
                detail.view(),
                Some(detail.plan()),
                detail.diagnostics(),
                &ctx.projects,
            ),
        )),
        Err(refusal) => Ok(view_refusal_result(&refusal)),
    }
}

/// `view_status` (T031): the saved plan against a live plan assembled from the
/// plan arguments here, field by field. Read-only, informational (C-006).
pub(super) fn view_status(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(
        args,
        &[
            "view",
            "filter",
            "sort",
            "group",
            "hide_columns",
            "show_mismatch",
        ],
    ) {
        return Ok(value);
    }
    let reference = opt_string(args, "view")?;
    let live_args = view_plan_args(args)?;
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    let service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);

    let live = match cmd_views::plan_from_args(store, &live_args) {
        Ok(plan) => plan,
        Err(error) => return Ok(view_filter_rejection(&error)),
    };
    let (divergence, view) = match &reference {
        Some(reference) => match service.show(reference) {
            Ok(detail) => {
                let divergence = ViewDivergence::between(detail.plan(), &live);
                (divergence, Some(detail))
            }
            Err(refusal) => return Ok(view_refusal_result(&refusal)),
        },
        // No reference is no saved plan to compare: the service's explicit
        // "no active view" diagnostic, never a silent `in_sync: true`.
        None => (ViewDivergence::missing_marker(&live), None),
    };

    let mut text = String::new();
    if let Some(detail) = &view {
        text.push_str(&format!(
            "id: {}\nname: {}\n",
            detail.view().id,
            detail.view().name
        ));
    }
    text.push_str(&format!("in-sync: {}\n", divergence.in_sync()));
    for difference in divergence.differences() {
        text.push_str(&format!(
            "difference: {} saved={} live={}\n",
            difference.field(),
            difference.saved().unwrap_or("(unset)"),
            difference.live().unwrap_or("(unset)"),
        ));
    }
    for diagnostic in divergence.diagnostics() {
        text.push_str(&format!(
            "diagnostic: {}\n",
            cmd_views::render_diagnostic(diagnostic)
        ));
    }

    Ok(success_result(
        text,
        json!({
            "in_sync": divergence.in_sync(),
            // The identity the comparison is about: the named view, exactly as
            // `tix view status <id>` prints it. A comparison with no reference
            // has no id, which is a fact about the request, not an omission.
            "view_id": view.as_ref().map(|detail| detail.view().id.as_str()),
            "saved_plan": divergence.saved_plan().map(plan_value),
            "live_plan": plan_value(divergence.live_plan()),
            "differences": divergence
                .differences()
                .iter()
                .map(|difference| json!({
                    "field": difference.field(),
                    "saved": difference.saved(),
                    "live": difference.live(),
                }))
                .collect::<Vec<_>>(),
            "diagnostics": divergence
                .diagnostics()
                .iter()
                .map(diagnostic_value)
                .collect::<Vec<_>>(),
        }),
    ))
}

/// `view_update` (T030): merge semantics — only the named fields change, so a
/// rename cannot drop the plan and an unnamed plan field survives.
pub(super) fn view_update(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if let Err(value) = view_arguments(
        args,
        &[
            "view",
            "name",
            "filter",
            "sort",
            "group",
            "hide_columns",
            "show_mismatch",
        ],
    ) {
        return Ok(value);
    }
    let reference = req_string(args, "view")?;
    let name = opt_string(args, "name")?;
    let plan_args = view_plan_args(args)?;
    let mut ctx = match view_context(store) {
        Ok(ctx) => ctx,
        Err(value) => return Ok(value),
    };
    let mut service = ViewService::new(&mut ctx.config, &ctx.projects, &ctx.path);

    let detail = match service.show(&reference) {
        Ok(detail) => detail,
        Err(refusal) => return Ok(view_refusal_result(&refusal)),
    };
    let new_name = name.unwrap_or_else(|| detail.view().name.clone());
    let scope = detail.view().scope.clone();
    let plan = if plan_args.is_any() {
        match cmd_views::overlay_plan_args(store, detail.plan(), &plan_args) {
            Ok(plan) => plan,
            Err(error) => return Ok(view_filter_rejection(&error)),
        }
    } else {
        detail.plan().clone()
    };

    match service.update(&reference, ViewDefinition::new(new_name, scope, plan)) {
        Ok(outcome) => {
            let no_op = outcome.is_noop();
            let audit = outcome.audit().cloned();
            let id = outcome.into_value();
            let (status, word) = if no_op {
                ("no-op", "Unchanged")
            } else {
                ("accepted", "Updated")
            };
            Ok(success_result(
                format!("{word} {id}"),
                view_accepted_value(status, "update", &id, &service, &ctx.projects, audit),
            ))
        }
        Err(error) => Ok(view_write_result(&error)),
    }
}

pub(super) fn dispatch(
    config: &Config,
    store: &Store,
    name: &str,
    arguments: &Value,
) -> Option<ToolOutcome> {
    match name {
        "view_list" => Some(view_list(config, store, arguments)),
        "view_show" => Some(view_show(config, store, arguments)),
        "view_create" => Some(view_create(config, store, arguments)),
        "view_update" => Some(view_update(config, store, arguments)),
        "view_duplicate" => Some(view_duplicate(config, store, arguments)),
        "view_delete" => Some(view_delete(config, store, arguments)),
        "view_share" => Some(view_share(config, store, arguments)),
        "view_apply" => Some(view_apply(config, store, arguments)),
        "view_status" => Some(view_status(config, store, arguments)),
        _ => None,
    }
}

/// The accepted half of a view mutation (T030): its status, the resulting
/// record, and the audit event when one was emitted.
pub(super) fn view_accepted_value(
    status: &str,
    operation: &str,
    id: &ViewId,
    service: &ViewSvc<'_>,
    projects: &BTreeSet<String>,
    audit: Option<ViewAuditEvent>,
) -> Value {
    let view = match service.show(id.as_str()) {
        Ok(detail) => view_value(
            detail.view(),
            Some(detail.plan()),
            detail.diagnostics(),
            projects,
        ),
        Err(refusal) => json!({
            "id": id.as_str(),
            "diagnostics": refusal.diagnostics().iter().map(diagnostic_value).collect::<Vec<_>>(),
        }),
    };
    json!({
        "status": status,
        "operation": operation,
        "view": view,
        "audit": audit.as_ref().map(audit_value),
    })
}

/// A **rejected** view operation: the CLI's exact error text, plus the ordered
/// diagnostics the shared registry produced.
///
/// `isError: true` like every other domain failure. Unlike the issue tools, the
/// diagnostics are also structured: `surface-parity.md` asks every surface to
/// expose the same diagnostics, and an agent must be able to act on `field`
/// without parsing prose (T030).
pub(super) fn view_refusal_result(refusal: &ViewRefusal) -> Value {
    view_rejection(refusal.render(), refusal.diagnostics())
}

/// A rejection with an explicit diagnostic list.
pub(super) fn view_rejection(text: String, diagnostics: &[ViewDiagnostic]) -> Value {
    json!({
        "content": [{ "type": "text", "text": text }],
        "structuredContent": {
            "status": "rejected",
            "diagnostics": diagnostics.iter().map(diagnostic_value).collect::<Vec<_>>(),
        },
        "isError": true,
    })
}

/// A view **write** that was refused (nothing written) or failed for an
/// infrastructure reason (the atomic save did not complete). The registry keeps
/// the two apart and so does this projection.
pub(super) fn view_write_result(error: &ViewWriteError) -> Value {
    match error {
        ViewWriteError::Refused(refusal) => view_refusal_result(refusal),
        ViewWriteError::Failed(failure) => json!({
            "content": [{ "type": "text", "text": failure.to_string() }],
            "structuredContent": { "status": "failed", "diagnostics": [] },
            "isError": true,
        }),
    }
}

/// A plan the **existing grammar** refused while it was being assembled: an
/// unknown `category:`/`scope:` token, an unresolvable `parent:` selector.
///
/// The message is the resolver's own, verbatim — the same text
/// `tix view create --filter …` prints — and it is given the plan's own
/// `invalid_filter` kind and `plan.filter` field so a client can act on it
/// structurally rather than by reading the sentence.
pub(super) fn view_filter_rejection(error: &crate::error::TixError) -> Value {
    let diagnostic = ViewDiagnostic::new(ViewDiagnosticKind::InvalidFilter, error.to_string())
        .with_field("plan.filter");
    view_rejection(error.to_string(), &[diagnostic])
}

/// The structured diagnostics, one shape for every view tool.
pub(super) fn diagnostic_value(diagnostic: &ViewDiagnostic) -> Value {
    json!({
        "kind": diagnostic.kind().as_str(),
        "field": diagnostic.field(),
        "message": diagnostic.message(),
        "remedy": diagnostic.remedy(),
        "view_id": diagnostic.view_id().map(ViewId::as_str),
    })
}

/// The scope family and its metadata (scope is data, never an identity).
pub(super) fn scope_value(scope: &ViewScope) -> Value {
    json!({
        "kind": scope.kind.as_str(),
        "project_id": scope.project_id,
        "owner": scope.owner,
        "shared_with": scope.shared_with,
        "extensions": json_table(&scope.extensions),
    })
}

/// The normalized plan in the **persisted** `[plan]` shape, so the plan a client
/// sees is the plan a round trip stores (C-007/NFR-002).
pub(super) fn plan_value(plan: &ViewPlan) -> Value {
    json_table(&plan.to_toml())
}

/// A TOML table as JSON, or `null` when a value has no JSON spelling.
pub(super) fn json_table(table: &toml::Table) -> Value {
    serde_json::to_value(table).unwrap_or(Value::Null)
}

/// One accepted mutation's audit event.
pub(super) fn audit_value(event: &ViewAuditEvent) -> Value {
    json!({
        "mutation": event.kind().as_str(),
        "view_id": event.view_id().as_str(),
        "view_name": event.view_name(),
    })
}

/// The active marker as a DTO (informational provenance only).
pub(super) fn marker_value(marker: &ActiveViewMarker) -> Value {
    json!({
        "view_id": marker.view_id().as_str(),
        "source": marker.source().map(ViewSurface::as_str),
        "applied_at": marker.applied_at(),
        "applied_plan": plan_value(marker.applied_plan()),
    })
}

/// The applied board as a summary: one count per visible and hidden column, and
/// the mismatched pseudo-column. Derived from the shared `BoardState` the filter
/// path built — never re-counted from the corpus.
pub(super) fn board_summary_value(board: &crate::ui::board::BoardState) -> Value {
    json!({
        "columns": board.columns.iter().map(board_column_value).collect::<Vec<_>>(),
        "hidden": board.hidden.iter().map(board_column_value).collect::<Vec<_>>(),
        "mismatch": board.mismatch.cards.len(),
    })
}

pub(super) fn board_column_value(column: &crate::ui::board::BoardColumn) -> Value {
    json!({ "name": column.name, "count": column.cards.len() })
}

// -- text mirrors ---------------------------------------------------------

/// `tix view show`'s stdout, byte for byte.
pub(super) fn view_show_text(
    view: &SavedView,
    plan: &ViewPlan,
    projects: &BTreeSet<String>,
    diagnostics: &[ViewDiagnostic],
) -> String {
    let mut out = format!(
        "id: {}\nname: {}\nscope: {}\nresolution: {}\n",
        view.id,
        view.name,
        cmd_views::scope_label(&view.scope),
        view.scope.resolution(projects),
    );
    for line in cmd_views::plan_lines(plan) {
        out.push_str(&line);
        out.push('\n');
    }
    for diagnostic in diagnostics {
        out.push_str(&format!(
            "diagnostic: {}\n",
            cmd_views::render_diagnostic(diagnostic)
        ));
    }
    out
}

/// `tix view apply`'s stdout, byte for byte.
pub(super) fn view_apply_text(
    view: &SavedView,
    plan: &ViewPlan,
    result: &ViewApplyResult,
) -> String {
    let mut out = format!(
        "id: {}\nname: {}\nscope: {}\n",
        view.id,
        view.name,
        cmd_views::scope_label(&view.scope),
    );
    for line in cmd_views::plan_lines(plan) {
        out.push_str(&line);
        out.push('\n');
    }
    out.push_str(&format!("active: {}\n", view.id));
    out.push_str(&format!(
        "issues: {}\n",
        cmd_views::join_numbers(result.issue_numbers())
    ));
    out.push_str(&format!("count: {}\n", result.issue_numbers().len()));
    for diagnostic in result.diagnostics() {
        out.push_str(&format!(
            "diagnostic: {}\n",
            cmd_views::render_diagnostic(diagnostic)
        ));
    }
    out
}

// ---------------------------------------------------------------------------
// WP08 / T038-T042 - the recurring tools
// ---------------------------------------------------------------------------
//
// The MCP peer of `tix recurring`, over the same services and - through
// `cmd_recurring` - the same resolver and the same date context. MCP owns no
// scheduler, no rule parser, no series writer and no second clock: the arguments
// are read, `SeriesIndex::build` indexes what the store already holds, and
// `detect`, `generate` and `apply_lifecycle` make every decision. A mutation
// needs `confirm: true`, exactly as the CLI needs `--yes`, and every one of them
// returns the shared outcome vocabulary (`created`/`no-op`/`rejected`,
// `applied`/`no-op`/`rejected`) rather than a surface-specific word (T040).

/// The reloaded repository state one view tool call operates on.
pub(super) struct ViewContext {
    config: Config,
    path: std::path::PathBuf,
    projects: BTreeSet<String>,
}

/// Reload the repository config for one view call.
///
/// The server bootstraps one `Config` for the session, but a saved-view mutation
/// **is** a `tix.toml` write — the registry is that file's `[views]` section, and
/// `ViewService` commits through the existing atomic save. Reloading per call is
/// what makes a `view_create` visible to the next `view_list` in the same
/// session, and it keeps this adapter honest: the registry on disk is the one
/// `tix view` reads and writes, so no surface can hold a private copy (C-007).
pub(super) fn view_context(store: &Store) -> std::result::Result<ViewContext, Value> {
    let path = cmd_views::config_path(store);
    let root = path.parent().unwrap_or_else(|| Path::new("."));
    match Config::load(root) {
        Ok(config) => Ok(ViewContext {
            config,
            path,
            projects: cmd_views::project_directory(),
        }),
        Err(error) => Err(error_result(error.to_string())),
    }
}

/// Refuse any argument this tool does not declare.
///
/// Every view descriptor promises `additionalProperties: false`, and the
/// mission's boundary is that a saved view is a *data* definition: there is no
/// hosted sharing, no host account, and no executable query payload (C-003/
/// C-004/C-009). Silently ignoring an undeclared key is how a client comes to
/// believe it configured `host`/`execute`/`permissions`; refusing it with a
/// field diagnostic is what makes the boundary observable (T030).
pub(super) fn view_arguments(args: &Value, allowed: &[&str]) -> std::result::Result<(), Value> {
    let Some(object) = args.as_object() else {
        return Ok(());
    };
    let unknown: Vec<&str> = object
        .keys()
        .map(String::as_str)
        .filter(|key| !allowed.contains(key))
        .collect();
    if unknown.is_empty() {
        return Ok(());
    }
    let diagnostics: Vec<ViewDiagnostic> = unknown
        .iter()
        .map(|key| {
            ViewDiagnostic::new(
                ViewDiagnosticKind::InvalidView,
                format!("`{key}` is not a field of this tool"),
            )
            .with_field(*key)
            .with_remedy(
                "remove it: a saved view is repository data, and host identity, permissions, \
                 and executable query payloads are not saved-view fields",
            )
        })
        .collect();
    let rendered = ViewRefusal::from_diagnostics(diagnostics.clone()).render();
    Err(view_rejection(rendered, &diagnostics))
}

/// The saved-view scope arguments, read from the same key names the CLI's
/// `ViewScopeArgs` flags have.
pub(super) fn view_scope_args(args: &Value) -> std::result::Result<crate::cli::ViewScopeArgs, ()> {
    Ok(crate::cli::ViewScopeArgs {
        scope: opt_string(args, "scope")?,
        project: opt_string(args, "project")?,
        owner: opt_string(args, "owner")?,
        shared_with: opt_string(args, "shared_with")?,
    })
}

/// The saved-view plan arguments, read from the same key names the CLI's
/// `ViewPlanArgs` flags have, so the two surfaces shape one plan (C-007).
pub(super) fn view_plan_args(args: &Value) -> std::result::Result<crate::cli::ViewPlanArgs, ()> {
    Ok(crate::cli::ViewPlanArgs {
        filter: opt_string(args, "filter")?,
        sort: opt_string(args, "sort")?,
        group: opt_string(args, "group")?,
        hide_columns: opt_string(args, "hide_columns")?,
        show_mismatch: opt_bool(args, "show_mismatch")?,
    })
}

/// One saved view as a surface DTO: identity, scope, normalized plan, preserved
/// extensions, and diagnostics (C-007).
pub(super) fn view_value(
    view: &SavedView,
    plan: Option<&ViewPlan>,
    diagnostics: &[ViewDiagnostic],
    projects: &BTreeSet<String>,
) -> Value {
    json!({
        "id": view.id.as_str(),
        "name": view.name,
        "scope": scope_value(&view.scope),
        "scope_label": cmd_views::scope_label(&view.scope),
        "resolution": view.scope.resolution(projects).as_str(),
        "plan": plan.map(plan_value),
        "extensions": json_table(&view.extensions),
        "diagnostics": diagnostics.iter().map(diagnostic_value).collect::<Vec<_>>(),
    })
}