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
//! The CLI adapter for the stable-ID template registry (WP04; mission
//! `issue-form-templates-01M3C76V`).
//!
//! This module parses and renders — it owns **no** validation, **no** issue
//! writing, and **no** template grammar of its own:
//!
//! - `tix template …` (management) is a thin wrapper over
//!   [`crate::templates::TemplateService`], the sibling of the saved-views
//!   service (`src/commands/view.rs`). Every accepted mutation is the service's;
//!   every refusal is a field-aware config error the service already produces;
//! - `tix create --template …` calls the **shared create core**
//!   ([`crate::commands::create::create`]) after the pure resolver turns the
//!   template plus the user's normal create flags into one normal create
//!   request. There is no second writer (C-001/C-007/NFR-002).
//!
//! # What stays out of here
//!
//! The resolver never reads `stdin` or launches an editor, and the create core
//! never reads `stdin` (C-005), so the template path is non-interactive by
//! construction: a missing required prompt is a diagnostic, never a prompt.
//! `--title` is therefore required on the template path — a template that
//! defaults a title must supply it, because there is no prompt to fall back to.
//!
//! # Management persistence
//!
//! Management reads and writes the registry in the project's `tix.toml`
//! through the existing atomic [`crate::config::Config::save`]. The loaded
//! config is **not** absolutized — it is saved back exactly as loaded except
//! for the registry the operation changed, so an unrelated path in the file
//! round-trips byte-for-byte.

use std::fmt::Write as _;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};

use crate::cli::TemplateAction;
use crate::commands::create;
use crate::commands::parse_csv_list;
use crate::config::Config;
use crate::error::{Result, TixError};
use crate::storage::Store;
use crate::templates::registry::{
    CREATE_FIELDS, PromptKind, ReferenceKind, TemplateDefaults, TemplatePrompt, TemplateReference,
    TemplateScope,
};
use crate::templates::resolver::{
    CreateRequest, TemplateInput, TemplateResolution, TemplateSelection, resolve,
};
use crate::templates::{
    DeleteConfirmed, TemplateDefinition, TemplateDetail, TemplateService, TemplateWriteError,
};

// ---------------------------------------------------------------------------
// `tix template …` — management
// ---------------------------------------------------------------------------

/// Run one `tix template` subcommand against the project's `tix.toml`.
///
/// The config is loaded fresh here rather than through `commands::dispatch`
/// because a mutation needs a **mutable** [`Config`] and the file path it came
/// from; `dispatch` sees neither. Routing happens in [`crate::cli::run`] before
/// the store is opened, so the read-only and write subcommands share one
/// resolution and a project with no `tix.toml` fails with the same guidance as
/// the TUI.
pub fn run(cwd: &Path, action: &TemplateAction) -> Result<()> {
    let (mut config, path) = load_management_config(cwd)?;

    match action {
        TemplateAction::List => {
            let service = TemplateService::new(&mut config, &path);
            print!("{}", render_list(&service.list()));
            Ok(())
        }
        TemplateAction::Show { reference } => {
            let service = TemplateService::new(&mut config, &path);
            print!("{}", render_detail(&service.show(reference)?));
            Ok(())
        }
        TemplateAction::Create {
            id,
            name,
            scope,
            defaults,
            prompts,
            references,
        } => {
            let definition = definition_for_create(
                name.as_deref(),
                scope.as_deref(),
                defaults,
                prompts,
                references,
            )?;
            let mut service = TemplateService::new(&mut config, &path);
            let outcome = service
                .create(id, definition)
                .map_err(TemplateWriteError::into_inner)?;
            println!("created template `{}`", outcome.value());
            Ok(())
        }
        TemplateAction::Update {
            reference,
            name,
            scope,
            defaults,
            prompts,
            references,
        } => {
            let definition = definition_for_update(
                name.as_deref(),
                scope.as_deref(),
                defaults,
                prompts,
                references,
            )?;
            let mut service = TemplateService::new(&mut config, &path);
            let outcome = service
                .update(reference, definition)
                .map_err(TemplateWriteError::into_inner)?;
            if outcome.is_noop() {
                println!("unchanged template `{}`", outcome.value());
            } else {
                println!("updated template `{}`", outcome.value());
            }
            Ok(())
        }
        TemplateAction::Duplicate {
            reference,
            id,
            name,
        } => {
            let mut service = TemplateService::new(&mut config, &path);
            let outcome = service
                .duplicate(reference, id.as_deref(), name.as_deref())
                .map_err(TemplateWriteError::into_inner)?;
            println!(
                "duplicated template `{reference}` as `{}`",
                outcome.value().id()
            );
            Ok(())
        }
        TemplateAction::Delete { reference, yes } => {
            confirm_delete(reference, *yes)?;
            let mut service = TemplateService::new(&mut config, &path);
            let outcome = service
                .delete(reference, DeleteConfirmed::confirmed())
                .map_err(TemplateWriteError::into_inner)?;
            println!("deleted template `{}`", outcome.value().id());
            Ok(())
        }
    }
}

/// Load the project config and the `tix.toml` path it was read from.
///
/// Strict, like the TUI and `tix mcp`: a management command with no repository
/// to manage fails with the contract's guidance rather than silently writing a
/// new file.
fn load_management_config(cwd: &Path) -> Result<(Config, PathBuf)> {
    let root = Config::project_root(cwd)
        .ok_or_else(|| TixError::Config("no tix.toml found — run \"tix init\" first".into()))?;
    let config = Config::load(&root)?;
    Ok((config, root.join("tix.toml")))
}

/// Mirror `tix cycle delete` / `tix milestone delete`: `--yes` or a piped
/// stdin confirms, a bare TTY invocation asks.
fn confirm_delete(reference: &str, yes: bool) -> Result<()> {
    let mut confirmed = yes || !std::io::stdin().is_terminal();
    if !confirmed {
        eprint!("Delete template '{reference}'? [y/N] ");
        let mut line = String::new();
        std::io::stdin()
            .read_line(&mut line)
            .map_err(TixError::Io)?;
        confirmed = line.trim().eq_ignore_ascii_case("y");
    }
    if !confirmed {
        return Err(TixError::InvalidInput(format!(
            "deletion of template `{reference}` was not confirmed"
        )));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// definition building (flags → service types)
// ---------------------------------------------------------------------------

/// The definition a `create` supplies: name/scope default, flags add data.
fn definition_for_create(
    name: Option<&str>,
    scope: Option<&str>,
    defaults: &[String],
    prompts: &[String],
    references: &[String],
) -> Result<TemplateDefinition> {
    // An omitted scope is the documented `repository` default for a *new*
    // template; the registry persists no `scope` key for it.
    let scope = match scope {
        Some(raw) => parse_scope(raw)?,
        None => TemplateScope::repository(),
    };
    let mut definition = match name {
        Some(name) => TemplateDefinition::new(name, scope),
        None => TemplateDefinition::unnamed(scope),
    };
    if !defaults.is_empty() {
        definition = definition.with_defaults(build_defaults(defaults)?);
    }
    if !prompts.is_empty() {
        definition = definition.with_prompts(build_prompts(prompts)?);
    }
    if !references.is_empty() {
        definition = definition.with_references(build_references(references)?);
    }
    Ok(definition)
}

/// The definition an `update` supplies: **only** the flags given are set.
///
/// This is what makes `tix template update bug --name "…"` a rename: an absent
/// scope/defaults/prompts/references argument leaves the stored value exactly
/// as it was (C-002). A definition with no flags at all is a no-op the service
/// reports as unchanged.
fn definition_for_update(
    name: Option<&str>,
    scope: Option<&str>,
    defaults: &[String],
    prompts: &[String],
    references: &[String],
) -> Result<TemplateDefinition> {
    let mut definition = match (name, scope) {
        (Some(name), Some(raw)) => TemplateDefinition::new(name, parse_scope(raw)?),
        (Some(name), None) => TemplateDefinition::rename(name),
        (None, Some(raw)) => TemplateDefinition::unnamed(parse_scope(raw)?),
        (None, None) => TemplateDefinition::default(),
    };
    // Supplying any `--default`/`--prompt`/`--reference` **replaces** that whole
    // block; an absent flag leaves it untouched. That is the service's
    // `Option`-per-block contract and the only behaviour that makes a rename a
    // rename.
    if !defaults.is_empty() {
        definition = definition.with_defaults(build_defaults(defaults)?);
    }
    if !prompts.is_empty() {
        definition = definition.with_prompts(build_prompts(prompts)?);
    }
    if !references.is_empty() {
        definition = definition.with_references(build_references(references)?);
    }
    Ok(definition)
}

/// `--scope repository` | `board:<name>` | `team:<label>`.
fn parse_scope(raw: &str) -> Result<TemplateScope> {
    raw.parse::<TemplateScope>().map_err(TixError::InvalidInput)
}

/// Fold repeated `--default FIELD=VALUE` into one defaults block.
///
/// The value is taken verbatim after the first `=` (so a comma-containing list
/// value survives), and list fields are split with the same CSV rule the create
/// core applies.
fn build_defaults(specs: &[String]) -> Result<TemplateDefaults> {
    let mut defaults = TemplateDefaults::default();
    for spec in specs {
        let Some((field, value)) = spec.split_once('=') else {
            return Err(TixError::InvalidInput(format!(
                "--default `{spec}` must be `FIELD=VALUE`"
            )));
        };
        let field = field.trim();
        let value = value.trim().to_string();
        match field {
            "title" => defaults.title = Some(value),
            "body" => defaults.body = Some(value),
            "status" => defaults.status = Some(value),
            "priority" => defaults.priority = Some(value),
            "assignee" => defaults.assignee = Some(value),
            "labels" => defaults.labels = parse_csv_list(&value),
            "files" => defaults.files = parse_csv_list(&value),
            "estimate" => defaults.estimate = Some(value),
            "cycles" => defaults.cycles = parse_csv_list(&value),
            "milestones" => defaults.milestones = parse_csv_list(&value),
            "reviewer" => defaults.reviewer = Some(value),
            "start_date" => defaults.start_date = Some(value),
            "due_date" => defaults.due_date = Some(value),
            "parent" => defaults.parent = Some(value),
            "related_issues" => defaults.related_issues = parse_csv_list(&value),
            "type" => defaults.type_ = Some(value),
            other => {
                return Err(TixError::InvalidInput(format!(
                    "`{other}` is not a create field; expected one of {}",
                    CREATE_FIELDS.join(", ")
                )));
            }
        }
    }
    Ok(defaults)
}

/// `--prompt key=<field>[,kind=<kind>][,required=<bool>][,default=<v>][,label=<l>][,options_ref=<src>]`.
fn build_prompts(specs: &[String]) -> Result<Vec<TemplatePrompt>> {
    specs.iter().map(|spec| parse_prompt(spec)).collect()
}

fn parse_prompt(raw: &str) -> Result<TemplatePrompt> {
    let mut key: Option<String> = None;
    let mut label: Option<String> = None;
    let mut kind = PromptKind::Text;
    let mut required = false;
    let mut default: Option<String> = None;
    let mut options_ref: Option<String> = None;

    for (name, value) in split_attributes(raw, "--prompt")? {
        match name {
            "key" => key = Some(value.to_string()),
            "kind" => kind = parse_prompt_kind(value)?,
            "required" => required = parse_bool(value, "--prompt required")?,
            "default" => default = Some(value.to_string()),
            "label" => label = Some(value.to_string()),
            "options_ref" => options_ref = Some(value.to_string()),
            other => {
                return Err(TixError::InvalidInput(format!(
                    "unknown --prompt attribute `{other}`; expected key, kind, required, \
                     default, label or options_ref"
                )));
            }
        }
    }

    let key = key.ok_or_else(|| {
        TixError::InvalidInput("--prompt requires `key=<create field>`".to_string())
    })?;
    Ok(TemplatePrompt {
        key,
        label,
        kind,
        required,
        default,
        options_ref,
    })
}

/// `--reference kind=<kind>,value=<v>[,required=<bool>]`.
fn build_references(specs: &[String]) -> Result<Vec<TemplateReference>> {
    specs.iter().map(|spec| parse_reference(spec)).collect()
}

fn parse_reference(raw: &str) -> Result<TemplateReference> {
    let mut kind: Option<ReferenceKind> = None;
    let mut value: Option<String> = None;
    let mut required = false;

    for (name, raw_value) in split_attributes(raw, "--reference")? {
        match name {
            "kind" => kind = Some(parse_reference_kind(raw_value)?),
            "value" => value = Some(raw_value.to_string()),
            "required" => required = parse_bool(raw_value, "--reference required")?,
            other => {
                return Err(TixError::InvalidInput(format!(
                    "unknown --reference attribute `{other}`; expected kind, value or required"
                )));
            }
        }
    }

    let kind = kind
        .ok_or_else(|| TixError::InvalidInput("--reference requires `kind=<kind>`".to_string()))?;
    let value = value.ok_or_else(|| {
        TixError::InvalidInput("--reference requires `value=<value>`".to_string())
    })?;
    Ok(TemplateReference {
        kind,
        value,
        required,
    })
}

/// Split a `key=value,key=value` flag into trimmed pairs.
///
/// Strict on purpose: a token without `=` is a usage error naming the flag
/// rather than a silently ignored typo, and a repeated attribute is the last
/// one wins only because the grammar cannot express a list here.
fn split_attributes<'a>(raw: &'a str, flag: &str) -> Result<Vec<(&'a str, &'a str)>> {
    let mut out = Vec::new();
    for token in raw.split(',') {
        let token = token.trim();
        if token.is_empty() {
            continue;
        }
        let Some((name, value)) = token.split_once('=') else {
            return Err(TixError::InvalidInput(format!(
                "{flag} attribute `{token}` must be `key=value`"
            )));
        };
        out.push((name.trim(), value.trim()));
    }
    Ok(out)
}

fn parse_bool(raw: &str, what: &str) -> Result<bool> {
    match raw {
        "true" => Ok(true),
        "false" => Ok(false),
        other => Err(TixError::InvalidInput(format!(
            "{what} must be `true` or `false`, got `{other}`"
        ))),
    }
}

/// `PromptKind` has no `FromStr` (WP01 owns the type), so the CLI spells its
/// own parse and the round-trip is pinned by a test.
fn parse_prompt_kind(raw: &str) -> Result<PromptKind> {
    match raw {
        "text" => Ok(PromptKind::Text),
        "select" => Ok(PromptKind::Select),
        "multi-select" => Ok(PromptKind::MultiSelect),
        "date" => Ok(PromptKind::Date),
        other => Err(TixError::InvalidInput(format!(
            "unknown prompt kind `{other}`; expected text, select, multi-select or date"
        ))),
    }
}

fn parse_reference_kind(raw: &str) -> Result<ReferenceKind> {
    match raw {
        "label" => Ok(ReferenceKind::Label),
        "assignee" => Ok(ReferenceKind::Assignee),
        "file" => Ok(ReferenceKind::File),
        "cycle" => Ok(ReferenceKind::Cycle),
        "milestone" => Ok(ReferenceKind::Milestone),
        "relationship" => Ok(ReferenceKind::Relationship),
        other => Err(TixError::InvalidInput(format!(
            "unknown reference kind `{other}`; expected label, assignee, file, cycle, \
             milestone or relationship"
        ))),
    }
}

// ---------------------------------------------------------------------------
// rendering
// ---------------------------------------------------------------------------

/// `id\tname\tscope`, one row per stored definition, in declaration order.
///
/// Returns the text rather than printing it so the MCP surface renders the
/// identical bytes (`surface-parity.md` §Equivalence) — the CLI's rendering is
/// the shared one, not a second spelling kept in step by hand.
pub fn render_list(details: &[TemplateDetail]) -> String {
    let mut out = String::new();
    for detail in details {
        let _ = writeln!(
            out,
            "{}\t{}\t{}",
            detail.id(),
            detail.display_name(),
            detail.scope()
        );
    }
    out
}

/// A structured `key: value` block, so a script can read defaults, prompts,
/// references and preserved metadata without reaching into `tix.toml`.
///
/// The keys are stable and dotted; a section is absent when it is empty. The
/// template ID is `id` and the display name is `name`, never conflated.
///
/// Returns the text rather than printing it so the MCP surface renders the
/// identical bytes (`surface-parity.md` §Equivalence).
pub fn render_detail(detail: &TemplateDetail) -> String {
    let mut out = String::new();
    let _ = writeln!(out, "id: {}", detail.id());
    let _ = writeln!(out, "name: {}", detail.display_name());
    let _ = writeln!(out, "scope: {}", detail.scope());
    out.push_str(&render_defaults(detail.defaults()));
    for (index, prompt) in detail.prompts().iter().enumerate() {
        let _ = writeln!(out, "prompt[{index}].key: {}", prompt.key);
        if let Some(label) = &prompt.label {
            let _ = writeln!(out, "prompt[{index}].label: {label}");
        }
        let _ = writeln!(
            out,
            "prompt[{index}].kind: {}",
            prompt_kind_str(prompt.kind)
        );
        let _ = writeln!(out, "prompt[{index}].required: {}", prompt.required);
        if let Some(default) = &prompt.default {
            let _ = writeln!(out, "prompt[{index}].default: {default}");
        }
        if let Some(options_ref) = &prompt.options_ref {
            let _ = writeln!(out, "prompt[{index}].options_ref: {options_ref}");
        }
    }
    for (index, reference) in detail.references().iter().enumerate() {
        let _ = writeln!(
            out,
            "reference[{index}].kind: {}",
            reference_kind_str(reference.kind)
        );
        let _ = writeln!(out, "reference[{index}].value: {}", reference.value);
        let _ = writeln!(out, "reference[{index}].required: {}", reference.required);
    }
    // Unknown metadata is **data**: shown, never interpreted. Rendering it is
    // how "preserved" is visible without a second schema (C-006).
    for (key, value) in detail.extensions().iter() {
        let _ = writeln!(out, "unknown.{key}: {value}");
    }
    out
}

/// Defaults in [`CREATE_FIELDS`] order, so the block is deterministic.
fn render_defaults(defaults: &TemplateDefaults) -> String {
    let mut out = String::new();
    for (field, value) in [
        ("title", defaults.title.as_deref()),
        ("body", defaults.body.as_deref()),
        ("status", defaults.status.as_deref()),
        ("priority", defaults.priority.as_deref()),
        ("assignee", defaults.assignee.as_deref()),
        ("estimate", defaults.estimate.as_deref()),
        ("reviewer", defaults.reviewer.as_deref()),
        ("start_date", defaults.start_date.as_deref()),
        ("due_date", defaults.due_date.as_deref()),
        ("parent", defaults.parent.as_deref()),
        ("type", defaults.type_.as_deref()),
    ] {
        if let Some(value) = value {
            let _ = writeln!(out, "defaults.{field}: {value}");
        }
    }
    for (field, values) in [
        ("labels", &defaults.labels),
        ("files", &defaults.files),
        ("cycles", &defaults.cycles),
        ("milestones", &defaults.milestones),
        ("related_issues", &defaults.related_issues),
    ] {
        if !values.is_empty() {
            let _ = writeln!(out, "defaults.{field}: {}", values.join(", "));
        }
    }
    out
}

fn prompt_kind_str(kind: PromptKind) -> &'static str {
    match kind {
        PromptKind::Text => "text",
        PromptKind::Select => "select",
        PromptKind::MultiSelect => "multi-select",
        PromptKind::Date => "date",
    }
}

fn reference_kind_str(kind: ReferenceKind) -> &'static str {
    match kind {
        ReferenceKind::Label => "label",
        ReferenceKind::Assignee => "assignee",
        ReferenceKind::File => "file",
        ReferenceKind::Cycle => "cycle",
        ReferenceKind::Milestone => "milestone",
        ReferenceKind::Relationship => "relationship",
    }
}

// ---------------------------------------------------------------------------
// `tix create --template` — template-aware creation
// ---------------------------------------------------------------------------

/// The normal create flags a template selection is merged with.
///
/// It mirrors `tix create`'s arguments one-for-one — the same
/// comma-separated string shape the create core takes — so a surface cannot
/// name a field the create model does not understand.
#[derive(Debug, Default, Clone, Copy)]
pub struct CreateFields<'a> {
    pub title: Option<&'a str>,
    pub body: Option<&'a str>,
    pub status: Option<&'a str>,
    pub priority: Option<&'a str>,
    pub assignee: Option<&'a str>,
    pub labels: Option<&'a str>,
    pub files: Option<&'a str>,
    pub estimate: Option<&'a str>,
    pub cycles: Option<&'a str>,
    pub milestones: Option<&'a str>,
    pub reviewer: Option<&'a str>,
    pub start_date: Option<&'a str>,
    pub due_date: Option<&'a str>,
    pub parent: Option<&'a str>,
    pub related_issues: Option<&'a str>,
    pub type_: Option<&'a str>,
}

impl CreateFields<'_> {
    /// The resolver's input shape: the same fields, owned, with the TOML-style
    /// `type` key mapped onto the Rust field. Public so every surface feeds the
    /// shared resolver the identical shape.
    #[must_use]
    pub fn to_input(self) -> TemplateInput {
        TemplateInput {
            title: self.title.map(str::to_string),
            body: self.body.map(str::to_string),
            status: self.status.map(str::to_string),
            priority: self.priority.map(str::to_string),
            assignee: self.assignee.map(str::to_string),
            labels: self.labels.map(str::to_string),
            files: self.files.map(str::to_string),
            estimate: self.estimate.map(str::to_string),
            cycles: self.cycles.map(str::to_string),
            milestones: self.milestones.map(str::to_string),
            reviewer: self.reviewer.map(str::to_string),
            start_date: self.start_date.map(str::to_string),
            due_date: self.due_date.map(str::to_string),
            parent: self.parent.map(str::to_string),
            related_issues: self.related_issues.map(str::to_string),
            type_: self.type_.map(str::to_string),
        }
    }
}

/// Resolve `template_id`/`scope` plus `fields` into one create request and hand
/// it to the shared create core.
///
/// Failure is total: the resolver returns **every** diagnostic and no request,
/// and this function writes nothing — no issue file, no template/config save.
/// The diagnostics are rendered onto one `InvalidInput`, so the process exits
/// `1` with stdout untouched and every missing field named (FR-004/C-005).
///
/// The template ID is provenance: it is printed to **stderr** so `Created
/// <file>` on stdout keeps the exact shape every script already parses, while
/// the selected ID and scope stay visible (FR-005).
pub fn create_from_template(
    config: &Config,
    store: &Store,
    template_id: &str,
    scope: Option<&str>,
    fields: &CreateFields<'_>,
) -> Result<()> {
    let selection = selection_for(template_id, scope)?;
    let resolution = resolve(config, &selection, &fields.to_input());

    if !resolution.is_ok() {
        return Err(resolution_error(&resolution));
    }

    let template_id = resolution.template_id().to_string();
    let scope = resolution.scope().to_string();
    let request = resolution
        .into_request()
        .expect("a successful resolution always carries a request");
    eprintln!("using template `{template_id}` at scope `{scope}`");
    let issue = apply_request(config, store, &request)?;
    println!("Created {}", issue.filename);
    Ok(())
}

/// The explicit selection a stable ID and an optional scope spelling make.
///
/// An omitted scope is the **explicit** `repository` default, never an implicit
/// inheritance (C-003). Public so the MCP surface builds the identical
/// selection — and gets the identical refusal for a malformed scope — rather
/// than parsing the scope spelling a second time.
pub fn selection_for(template_id: &str, scope: Option<&str>) -> Result<TemplateSelection> {
    let scope = match scope {
        Some(raw) => parse_scope(raw)?,
        None => TemplateScope::repository(),
    };
    Ok(TemplateSelection::new(template_id, scope))
}

/// The one `InvalidInput` a failed resolution produces.
///
/// Public so every surface reports the **identical** failure text: MCP renders
/// this error rather than composing a second copy of the message
/// (`surface-parity.md` §Equivalence).
pub fn resolution_error(resolution: &TemplateResolution) -> TixError {
    let mut message = format!(
        "template `{}` at scope `{}` did not resolve:",
        resolution.template_id(),
        resolution.scope()
    );
    for diagnostic in resolution.diagnostics() {
        message.push_str(&format!(
            "\n  - {}: {}: {}",
            diagnostic.kind(),
            diagnostic.field(),
            diagnostic.message()
        ));
    }
    TixError::InvalidInput(message)
}

/// Destructure a resolved request straight into the shared create core.
///
/// The request's fields are the core's parameters in the same order and shape,
/// which is the whole point of the resolver returning `CreateRequest` rather
/// than a template-shaped object (C-001/NFR-002).
pub fn apply_request(
    config: &Config,
    store: &Store,
    request: &CreateRequest,
) -> Result<crate::model::Issue> {
    create::create(
        config,
        store,
        &request.title,
        request.body.as_deref(),
        request.status.clone(),
        request.priority.clone(),
        request.assignee.as_deref(),
        request.labels.as_deref(),
        request.files.as_deref(),
        request.estimate.as_deref(),
        request.cycles.as_deref(),
        request.milestones.as_deref(),
        request.reviewer.as_deref(),
        request.start_date.as_deref(),
        request.due_date.as_deref(),
        request.parent.as_deref(),
        request.related_issues.as_deref(),
        request.type_.as_deref(),
    )
}