Skip to main content

tix/triage/
decision.rs

1//! The triage decision service: accept, decline, duplicate, defer.
2//!
3//! Mission `triage-inbox-review-flow-01M3C600`, WP03 (T012–T016). One typed
4//! request in, either one append-only `History` event intent out or a refusal —
5//! and **nothing else**. The service never opens, reads or writes a file:
6//! [`DecisionService::apply`] takes `&Issue` and returns a *clone* carrying the
7//! decision, so a rejected or repeated decision cannot have side effects that
8//! someone would have to undo (data-model §3, contract `decision-history.md`).
9//!
10//! What it deliberately does **not** do:
11//!
12//! - **No second workflow.** Every status target goes through
13//!   [`crate::workflow::validate_transition`]; the completion and terminal rules
14//!   are #183's and are not restated here (C-002).
15//! - **No second History log.** A decision is one line in the existing
16//!   `## History` section, rendered by [`crate::triage::history`] (C-004).
17//! - **No destructive outcome.** Decline moves to the configured `canceled`
18//!   column; duplicate returns a typed relation and never merges, deletes or
19//!   moves a file (C-003, C-006). Merging is issue 189's.
20//!
21//! ## Order of checks
22//!
23//! The refusal order is fixed and each step is observable, because two
24//! refusals that both apply must always produce the *same* one:
25//!
26//! 1. required fields — [`Refusal::missing_reason`], [`Refusal::missing_actor`];
27//! 2. the requested target — [`Refusal::missing_target`],
28//!    [`Refusal::invalid_duplicate_target`], [`Refusal::unknown_issue`];
29//! 3. idempotence — [`DecisionOutcome::NoOp`];
30//! 4. queue membership — [`Refusal::not_in_triage`] or
31//!    [`Refusal::already_decided`];
32//! 5. the shared transition policy — [`Refusal::from_workflow`] (which surfaces
33//!    #183's `unknown_column` / `invalid_transition` unchanged).
34//!
35//! Step 3 before step 4 is load-bearing: declining twice is a no-op **even
36//! though the first decline took the issue out of the inbox**, so the
37//! idempotence question has to be asked before "is it still queued?". Step 2
38//! before both means a malformed request is refused identically whatever the
39//! issue happens to look like — a typo is not a state-dependent error.
40
41use std::fmt;
42use std::str::FromStr;
43
44use crate::config::Config;
45use crate::error::{Result, TixError};
46use crate::model::{HistoryEvent, HistoryEventKind, Issue, Status};
47use crate::relationships::{CanonicalEdge, RelationKind, Relationship};
48use crate::triage::history::{self, TriageDecisionRecord};
49use crate::triage::inbox::InboxScope;
50use crate::triage::record_entry;
51use crate::workflow::{self, DiagnosticKind, TransitionOutcome, WorkflowDiagnostic};
52
53/// This service's fallible type: a [`Refusal`] is the only failure it produces.
54///
55/// Deliberately not [`crate::error::Result`]. A refusal carries a *contract*
56/// diagnostic name and an issue identity, and collapsing it into a bare
57/// [`TixError`] at the boundary where it is raised would mean the CLI, TUI and
58/// MCP surfaces (NFR-003) each had to re-derive which condition was hit from
59/// prose. [`Refusal`] converts with `?`/`Into` when a surface wants the crate's
60/// error type.
61type DecisionResult<T> = std::result::Result<T, Refusal>;
62
63/// The four decisions (data-model §3, `kind`).
64///
65/// A closed set with no "other": there is no automatic decision path (C-008),
66/// so every decision is one of these four, named explicitly by the caller.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68pub enum DecisionKind {
69    /// Move into the normal workflow: `--to`, or `[triage].accepted_status`.
70    Accept,
71    /// Move to the configured declined column. Never delete, never archive.
72    Decline,
73    /// Record a typed `duplicates` relation against another issue.
74    Duplicate,
75    /// Stay in the inbox with a refreshed entry time.
76    Defer,
77}
78
79impl DecisionKind {
80    /// The canonical lowercase spelling used on the CLI and in messages.
81    #[must_use]
82    pub fn as_str(self) -> &'static str {
83        match self {
84            DecisionKind::Accept => "accept",
85            DecisionKind::Decline => "decline",
86            DecisionKind::Duplicate => "duplicate",
87            DecisionKind::Defer => "defer",
88        }
89    }
90
91    /// The `## History` kind an applied decision of this kind appends.
92    ///
93    /// The mapping lives here rather than at each call site so that "which
94    /// history entry does this decision write?" has one answer — the service
95    /// asks it to compare against the last recorded decision, and a test asks it
96    /// to assert the event that landed.
97    #[must_use]
98    pub fn event_kind(self) -> HistoryEventKind {
99        match self {
100            DecisionKind::Accept => HistoryEventKind::TriageAccepted,
101            DecisionKind::Decline => HistoryEventKind::TriageDeclined,
102            DecisionKind::Duplicate => HistoryEventKind::TriageDuplicated,
103            DecisionKind::Defer => HistoryEventKind::TriageDeferred,
104        }
105    }
106
107    /// Whether this decision refuses to proceed without a reason.
108    ///
109    /// **Decline, duplicate and defer require one; accept does not.** The
110    /// contract says decline/duplicate/defer "require a reason" and that accept
111    /// "records a reason when supplied", and data-model §3 repeats the split —
112    /// so an accept with no reason produces an event whose `reason` field is
113    /// absent rather than a refusal. Whether *the CLI* insists on `--reason` for
114    /// accept is the surface's own spelling question (contract `cli-surface.md`
115    /// defers the reason rules to `decision-history.md`), not a rule about what
116    /// a decision is.
117    #[must_use]
118    pub fn requires_reason(self) -> bool {
119        !matches!(self, DecisionKind::Accept)
120    }
121}
122
123impl fmt::Display for DecisionKind {
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        f.write_str(self.as_str())
126    }
127}
128
129impl FromStr for DecisionKind {
130    type Err = TixError;
131
132    /// Parse a decision name. Unknown names are rejected rather than coerced:
133    /// guessing between `decline` and `defer` on a batch would apply a decision
134    /// nobody chose.
135    fn from_str(s: &str) -> Result<Self> {
136        match s.trim().to_ascii_lowercase().as_str() {
137            "accept" => Ok(DecisionKind::Accept),
138            "decline" => Ok(DecisionKind::Decline),
139            "duplicate" => Ok(DecisionKind::Duplicate),
140            "defer" => Ok(DecisionKind::Defer),
141            other => Err(TixError::InvalidInput(format!(
142                "unknown triage decision `{other}` — expected accept, decline, \
143                 duplicate, or defer"
144            ))),
145        }
146    }
147}
148
149/// A typed decision request (data-model §3).
150///
151/// Everything a decision needs to be judged **without** touching the filesystem:
152/// the decision itself, who made it, when, and the optional targets. The issue
153/// under decision is not a field — it is the `issue` argument of
154/// [`DecisionService::apply`], because one batch decision is applied to many
155/// issues and a request that embedded its subject would have to be rebuilt per
156/// item (contract `decision-history.md`, §Batch behavior).
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct TriageDecision {
159    /// Which decision this is.
160    pub kind: DecisionKind,
161    /// The recorded reason, verbatim. Required for decline, duplicate and
162    /// defer; see [`DecisionKind::requires_reason`].
163    pub reason: String,
164    /// Who decided. Required: an audit entry with no actor is worse than no
165    /// entry (contract §Required reason and actor).
166    pub actor: String,
167    /// The duplicate target's issue number, for a duplicate decision.
168    pub target_issue: Option<u32>,
169    /// The accept target column (`--to`). Absent means "the configured
170    /// `[triage].accepted_status`".
171    pub target_status: Option<String>,
172    /// The decision time, RFC 3339. Supplied rather than read from the clock so
173    /// a batch stamps every event identically and a test is deterministic.
174    pub timestamp: String,
175}
176
177impl TriageDecision {
178    /// A decision with no optional target and an explicit timestamp.
179    ///
180    /// The timestamp is a parameter rather than a default for the same reason
181    /// [`crate::triage::inbox::collect`] takes `today`: a service that reads the
182    /// wall clock cannot be tested against a pinned time, and a batch would
183    /// otherwise hand `now()` to a loop that runs it once per item.
184    #[must_use]
185    pub fn new(
186        kind: DecisionKind,
187        timestamp: impl Into<String>,
188        actor: impl Into<String>,
189        reason: impl Into<String>,
190    ) -> Self {
191        Self {
192            kind,
193            reason: reason.into(),
194            actor: actor.into(),
195            target_issue: None,
196            target_status: None,
197            timestamp: timestamp.into(),
198        }
199    }
200}
201
202/// How the caller resolved the duplicate target's identity.
203///
204/// The service validates *identities*; resolving a selector (`--of some title`)
205/// against the store is the caller's job, because that is the part that needs
206/// the files. This enum carries the outcome of that resolution so the service
207/// can still name the failure itself — a duplicate decision's diagnostics are
208/// the contract's, not the caller's, and "matched three issues" is one of them.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub enum DuplicateTarget<'a> {
211    /// The selector resolved to exactly one issue.
212    Resolved(&'a Issue),
213    /// The selector resolved to no issue at all.
214    Unknown,
215    /// The selector matched more than one issue, so no single identity exists.
216    Ambiguous,
217}
218
219/// What a decision plans to do, decided before any state is read.
220///
221/// The intermediate between "what was asked for" and "what will change" exists
222/// so that steps 2 and 3 of the order can be answered *before* step 5 validates
223/// the move: idempotence has to be judged on the resolved target (an accept
224/// whose `--to` equals the current column is a no-op), and a duplicate's
225/// relation needs its target's title, which only the resolution has.
226#[derive(Debug, Clone, PartialEq, Eq)]
227enum Plan {
228    /// Move to this column, once #183 accepts the transition.
229    Move(String),
230    /// Create this typed relation; the issue's column does not change.
231    Duplicate {
232        target_number: u32,
233        target_title: String,
234    },
235}
236
237/// Why a decision was refused, and for which issue (contract §Diagnostics).
238///
239/// One struct rather than an enum of refusals: the contract fixes a *stable set
240/// of names* (`missing_reason`, `unknown_issue`, `unknown_column`,
241/// `invalid_transition`, `invalid_duplicate_target`, `not_in_triage`,
242/// `already_decided`, `write_failed` — "include", so the list is a vocabulary
243/// and not a closed set) and a message, and a surface that matches on eight
244/// variants gains nothing over one that matches on the name string it has to
245/// render anyway. The names are pinned by tests, which is what makes them
246/// stable.
247///
248/// Item identity reaches a surface through the refusal's own message (or the
249/// batch line that prefixes it with `#<n>`), not through a stored field: the
250/// three accessors that once exposed it had no caller, and NFR-003's "same kind
251/// **and item identity**" is checked where a user sees it (tix #1495).
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct Refusal {
254    kind: &'static str,
255    message: String,
256}
257
258impl Refusal {
259    /// Build a refusal directly. Public so a caller that resolves the *input*
260    /// (a selector that matched nothing, a malformed batch flag) reports the
261    /// same contract name the service would.
262    #[must_use]
263    pub fn new(kind: &'static str, message: impl Into<String>) -> Self {
264        Self {
265            kind,
266            message: message.into(),
267        }
268    }
269
270    /// A required reason is absent (`missing_reason`).
271    fn missing_reason(issue: u32, kind: DecisionKind) -> Self {
272        Self::new(
273            "missing_reason",
274            format!("`#{issue}` {kind} requires a reason"),
275        )
276    }
277
278    /// No actor was supplied (`missing_actor`).
279    fn missing_actor(issue: u32) -> Self {
280        Self::new(
281            "missing_actor",
282            format!(
283                "`#{issue}` needs an actor: a triage decision is never recorded \
284                 anonymously"
285            ),
286        )
287    }
288
289    /// Accept was given neither `--to` nor `[triage].accepted_status`
290    /// (`missing_target`).
291    ///
292    /// The contract's stable list does not spell this name out, and no other
293    /// name fits: `unknown_column` would claim a column was named when none was,
294    /// and `invalid_transition` would claim #183 refused a move it was never
295    /// asked about. "Stable kinds *include*" makes the list non-exhaustive, so
296    /// the vocabulary grows by one rather than borrowing a name that lies.
297    fn missing_target(issue: u32) -> Self {
298        Self::new(
299            "missing_target",
300            format!(
301                "`#{issue}` accept has no target column: pass `--to`, or set \
302                 `[triage].accepted_status`"
303            ),
304        )
305    }
306
307    /// The duplicate target is structurally wrong: absent, a self link, or
308    /// ambiguous (`invalid_duplicate_target`).
309    fn invalid_duplicate_target(message: impl Into<String>) -> Self {
310        Self::new("invalid_duplicate_target", message)
311    }
312
313    /// The requested identity resolves to no issue (`unknown_issue`).
314    fn unknown_issue(message: impl Into<String>) -> Self {
315        Self::new("unknown_issue", message)
316    }
317
318    /// `--of` matched more than one issue.
319    fn ambiguous() -> Self {
320        Self::invalid_duplicate_target(
321            "`--of` matched more than one issue; name the duplicate target by \
322             its number",
323        )
324    }
325
326    /// The issue is not in the triage inbox (`not_in_triage`).
327    fn not_in_triage(issue: u32) -> Self {
328        Self::new(
329            "not_in_triage",
330            format!(
331                "`#{issue}` is not in the triage inbox: decisions are made from \
332                 the queue, and this issue is in a normal column"
333            ),
334        )
335    }
336
337    /// The issue already carries a triage decision (`already_decided`).
338    ///
339    /// Told apart from [`Self::not_in_triage`] by whether the file records a
340    /// decision at all: an issue that never was triaged and sits in a normal
341    /// column was simply never queued, while one that left the queue *with* a
342    /// decision has used its triage review. Changing it again is a normal status
343    /// change (`tix move`), which is where that belongs.
344    fn already_decided(issue: u32) -> Self {
345        Self::new(
346            "already_decided",
347            format!(
348                "`#{issue}` already carries a triage decision and has left the \
349                 inbox; change it with a normal status command instead"
350            ),
351        )
352    }
353
354    /// A refusal from #183's transition service, passed through with its own
355    /// name (`unknown_column`, `invalid_transition`).
356    ///
357    /// The workflow diagnostic is **not** re-interpreted: #183 owns what a legal
358    /// transition is (C-002), so the only thing done here is translating its
359    /// [`DiagnosticKind`] into this contract's spelling — and two of the seven
360    /// workflow kinds are the only ones `validate_transition` can produce. Every
361    /// other refusal it could ever be handed — the terminal lock, adjacency, the
362    /// completion guard — is one thing to a triage caller: the move is against
363    /// policy, which is the contract's `invalid_transition`.
364    fn from_workflow(diagnostic: &WorkflowDiagnostic) -> Self {
365        let kind = match diagnostic.kind {
366            DiagnosticKind::UnknownColumn => "unknown_column",
367            _ => "invalid_transition",
368        };
369        Self::new(
370            kind,
371            format!("{}: {}", diagnostic.subject, diagnostic.message),
372        )
373    }
374}
375
376impl fmt::Display for Refusal {
377    /// `kind: message`, rendered by the crate's one refusal renderer so a
378    /// message that already leads with its kind is not prefixed twice.
379    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380        f.write_str(&crate::error::render_diagnostics([(
381            self.kind,
382            self.message.as_str(),
383        )]))
384    }
385}
386
387impl From<Refusal> for TixError {
388    /// Refusals reach surfaces that take the crate's error type as
389    /// `invalid input`, the variant WP01 and WP02 already use for triage
390    /// validation failures — no new variant, and no new name in
391    /// [`crate::workflow::DiagnosticKind`], whose `ALL` stays at seven.
392    fn from(refusal: Refusal) -> Self {
393        TixError::InvalidInput(refusal.to_string())
394    }
395}
396
397/// The result of one applied decision: the updated issue and the event intent
398/// (data-model §4).
399///
400/// The issue is a **clone the caller still has to write** — the service hands
401/// back what *would* be on disk, and storage performs the write. That is the
402/// whole filesystem-free claim: every rejection and every no-op returns before
403/// this variant exists, so "did anything change?" is answerable from the return
404/// value alone.
405///
406/// `Applied` is far larger than `NoOp`, which trips `clippy::large_enum_variant`
407/// — and boxing would add an allocation to a value that is *moved*, not copied,
408/// on the only path that constructs it. The size comes from `Issue`, which the
409/// service clones by necessity (see [`DecisionService::apply`]): the caller must
410/// be able to discard the result without having given anything up.
411#[allow(clippy::large_enum_variant)]
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub enum DecisionOutcome {
414    /// One decision applied: exactly one event, appended to the issue's own
415    /// History (NFR-002).
416    Applied {
417        /// The issue as the decision leaves it: status moved, entry metadata
418        /// updated, and `event` appended to its History.
419        issue: Issue,
420        /// The event intent. Always the *last* entry of `issue.history` —
421        /// one applied decision produces exactly one event, and there is no
422        /// second copy of it anywhere.
423        event: HistoryEvent,
424        /// The typed relation a duplicate decision creates. `None` for the
425        /// other three: only a duplicate adds an edge, and it adds no file
426        /// change at all (C-006).
427        relation: Option<Relationship>,
428    },
429    /// Already satisfied: no mutation, no event, no write (contract
430    /// §Idempotence and append-only behavior).
431    NoOp,
432}
433
434impl DecisionOutcome {
435    /// Whether this outcome changed nothing.
436    #[must_use]
437    pub fn is_noop(&self) -> bool {
438        matches!(self, DecisionOutcome::NoOp)
439    }
440}
441
442/// The decision service: one validated inbox configuration plus the caller's
443/// duplicate-target resolution.
444///
445/// Built once per command and reused across a batch, so a selection of fifty
446/// issues is validated against one scope rather than fifty.
447pub struct DecisionService<'a> {
448    /// The config `validate_transition` needs; also the source of
449    /// `[triage].accepted_status` and `[triage].declined_status`.
450    config: &'a Config,
451    /// The inbox: membership, and the board's category resolution.
452    scope: InboxScope,
453    /// The optional accept target from `[triage]`.
454    accepted_status: Option<String>,
455    /// The required decline target from `[triage]`.
456    declined_status: String,
457    /// How the caller resolved `--of`.
458    target: DuplicateTarget<'a>,
459}
460
461impl<'a> DecisionService<'a> {
462    /// Build a service over an already-resolved inbox scope.
463    ///
464    /// `scope` comes from the caller rather than from `config` because the
465    /// caller needs the same `Option<InboxScope>` answer for every `tix triage`
466    /// subcommand — "does this project have an inbox at all?" is the first thing
467    /// `list` asks too, and resolving it twice would give two chances to
468    /// disagree.
469    ///
470    /// The one thing checked here is the decline column, and it is checked once
471    /// rather than on every decision: a service that cannot name the column a
472    /// decline would move to has no business accepting a decline, and failing at
473    /// construction means no issue in a batch is decided before the defect shows.
474    pub fn new(
475        config: &'a Config,
476        scope: InboxScope,
477        target: DuplicateTarget<'a>,
478    ) -> DecisionResult<Self> {
479        let declined_status = config
480            .triage
481            .as_ref()
482            .and_then(|triage| triage.declined_status.clone())
483            .ok_or_else(|| {
484                Refusal::new(
485                    "unknown_column",
486                    "`[triage].declined_status` names no column, so a decline \
487                     would have nowhere to go",
488                )
489            })?;
490        let accepted_status = config
491            .triage
492            .as_ref()
493            .and_then(|t| t.accepted_status.clone());
494        Ok(Self {
495            config,
496            scope,
497            accepted_status,
498            declined_status,
499            target,
500        })
501    }
502
503    /// Apply one decision to one issue.
504    ///
505    /// Returns the issue *as it would be written*, plus the event intent — or a
506    /// refusal, or [`DecisionOutcome::NoOp`]. The input is borrowed, so a
507    /// rejected decision provably cannot have modified it, and the caller decides
508    /// whether and when to write (contract §Diagnostics: the service produces a
509    /// refusal, the surface reports it).
510    pub fn apply(
511        &self,
512        issue: &Issue,
513        request: &TriageDecision,
514    ) -> DecisionResult<DecisionOutcome> {
515        // 1 — required fields, before the issue is looked at: a missing reason
516        // is refused the same way whatever the queue happens to contain.
517        check_required(issue, request)?;
518
519        // 2 — the target, resolved and validated against the issue's identity.
520        let plan = self.plan(issue, request)?;
521
522        // 3 — idempotence, before membership: declining twice is a no-op even
523        // though the first decline left the inbox.
524        if is_noop(issue, request, &plan) {
525            return Ok(DecisionOutcome::NoOp);
526        }
527
528        // 4 — still in the queue?
529        if !self.scope.matches(issue) {
530            return Err(if history::has_triage_decision(issue) {
531                Refusal::already_decided(issue.number)
532            } else {
533                Refusal::not_in_triage(issue.number)
534            });
535        }
536
537        let prior_state = issue.status.display().to_string();
538        let mut updated = issue.clone();
539
540        // 5 — the one transition evaluation. Nothing below re-derives a rule.
541        let (result, relation) = match plan {
542            Plan::Move(column) => {
543                let outcome = workflow::validate_transition(
544                    issue,
545                    &column,
546                    &self.scope.resolution,
547                    self.config,
548                    None,
549                );
550                let to = match outcome {
551                    TransitionOutcome::Accepted { to, .. } => to,
552                    TransitionOutcome::Rejected(diagnostic) => {
553                        return Err(Refusal::from_workflow(&diagnostic));
554                    }
555                };
556                updated.status = Status::new(&to);
557                (to, None)
558            }
559            Plan::Duplicate {
560                target_number,
561                target_title,
562            } => {
563                // The relation, not a file operation: the intent is returned and
564                // storage writes it. No merge, no delete, no move (C-006).
565                let relation = Relationship::new(
566                    issue.number,
567                    target_number,
568                    RelationKind::Duplicates,
569                    &target_title,
570                );
571                let result = format!("{} #{}", relation.kind, relation.to);
572                (result, Some(relation))
573            }
574        };
575
576        // Entry metadata (data-model §2). A defer re-enters, so the wait
577        // restarts; a decision that *takes the issue out of the queue* leaves no
578        // stamp behind, because a stamp that measures a queue the issue is no
579        // longer in would age it wrongly the moment it came back — and the
580        // honest answer to "when did it enter?" is then "unknown", not a date
581        // that measures something else (research R4). The test is against the
582        // updated issue, so a decline that is configured to land in an inbox
583        // column keeps its stamp: it never left.
584        match request.kind {
585            DecisionKind::Defer => {
586                record_entry(&mut updated, &request.timestamp, Some("defer"));
587            }
588            DecisionKind::Accept | DecisionKind::Decline if !self.scope.matches(&updated) => {
589                updated.entered_at = None;
590                updated.source = None;
591            }
592            _ => {}
593        }
594
595        let record = TriageDecisionRecord::new(
596            &request.timestamp,
597            &request.actor,
598            request.kind.event_kind(),
599            prior_state,
600            result,
601            Some(request.reason.clone()),
602            request.target_issue,
603            crate::triage::entry_source(&updated).map(str::to_string),
604        );
605        let event = record.to_event();
606        updated.history.append(event.clone());
607
608        Ok(DecisionOutcome::Applied {
609            issue: updated,
610            event,
611            relation,
612        })
613    }
614
615    /// Resolve what this decision would change, and refuse it if it cannot
616    /// (step 2 of the order).
617    fn plan(&self, issue: &Issue, request: &TriageDecision) -> DecisionResult<Plan> {
618        match request.kind {
619            DecisionKind::Accept => {
620                // `--to` wins when given; `[triage].accepted_status` is the
621                // configured fallback; neither is a refusal rather than a guess.
622                // A blank `--to` is treated as absent, because a flag that
623                // carried only whitespace did not name a column.
624                let named = request
625                    .target_status
626                    .as_deref()
627                    .map(str::trim)
628                    .filter(|target| !target.is_empty())
629                    .map(str::to_string);
630                named
631                    .or_else(|| self.accepted_status.clone())
632                    .map(Plan::Move)
633                    .ok_or_else(|| Refusal::missing_target(issue.number))
634            }
635            DecisionKind::Decline => Ok(Plan::Move(self.declined_status.clone())),
636            DecisionKind::Defer => Ok(Plan::Move(self.scope.deferred_status.clone())),
637            DecisionKind::Duplicate => {
638                let target = self.resolve_duplicate(issue, request)?;
639                Ok(Plan::Duplicate {
640                    target_number: target.number,
641                    target_title: target.title.clone(),
642                })
643            }
644        }
645    }
646
647    /// Validate `--of` and return the issue it names (T014).
648    ///
649    /// The self-link test goes through [`CanonicalEdge`] rather than comparing
650    /// two numbers, so "is this a self link?" is the same question the
651    /// relationship service asks of an authored edge and has one answer. The
652    /// target itself is only ever *read*: this service creates a relation
653    /// intent, never a file operation.
654    fn resolve_duplicate(
655        &self,
656        issue: &Issue,
657        request: &TriageDecision,
658    ) -> DecisionResult<&'a Issue> {
659        // Ambiguity first: it is the only refusal about the *selector* rather
660        // than the target, and reporting "you gave no target" to someone who
661        // supplied one that matched three issues sends them looking for a flag
662        // they already used.
663        if let DuplicateTarget::Ambiguous = self.target {
664            return Err(Refusal::ambiguous());
665        }
666        let asked = request.target_issue.ok_or_else(|| {
667            Refusal::invalid_duplicate_target(format!(
668                "`#{}` is a duplicate decision with no target (`--of`)",
669                issue.number
670            ))
671        })?;
672        if CanonicalEdge::new(issue.number, asked, RelationKind::Duplicates).is_self_link() {
673            return Err(Refusal::invalid_duplicate_target(format!(
674                "`#{asked}` cannot be a duplicate of itself"
675            )));
676        }
677        match self.target {
678            DuplicateTarget::Resolved(target) if target.number == asked => Ok(target),
679            DuplicateTarget::Resolved(target) => Err(Refusal::unknown_issue(format!(
680                "`--of` resolved to `#{}`, but `#{asked}` was asked for",
681                target.number
682            ))),
683            DuplicateTarget::Unknown => {
684                Err(Refusal::unknown_issue(format!("`#{asked}` does not exist")))
685            }
686            // Unreachable: `Ambiguous` returns above. Written as a real arm
687            // rather than `unreachable!()` so the match stays total and a
688            // future reordering cannot introduce a panic.
689            DuplicateTarget::Ambiguous => Err(Refusal::ambiguous()),
690        }
691    }
692}
693
694/// Step 3: whether this decision is already satisfied, so nothing is changed
695/// and no event is appended.
696///
697/// Two different questions with one answer each, because "already done" means
698/// different things for a decision that moves an issue and one that records an
699/// edge:
700///
701/// - **duplicate**: the canonical `duplicates` edge already exists. The reason
702///   is deliberately ignored — an edge is an edge, and re-declaring the same
703///   duplicate with a sharper justification is a comment, not a second relation.
704/// - **move**: the issue is already in the target column **and** the most recent
705///   decision recorded is this kind with this reason. The History half matters
706///   for `defer`, where the column does not change at all: a first defer must
707///   refresh the entry and append, and an identical repeat must do neither. It
708///   also means a *changed* reason on an unchanged column is a new decision,
709///   which is quickstart §7's rule.
710///
711/// The consequence worth naming: an issue moved into the target column by a
712/// plain `tix move`, whose last triage decision happens to be this kind and
713/// reason, reads as a no-op. The requested final state and reason both hold, so
714/// nothing would change — and inventing an event to mark the difference would be
715/// the log recording a decision the user did not make.
716///
717/// A free function for the same reason as [`check_required`]: it reads nothing
718/// from the service, and the plan it is handed already carries the resolved
719/// target.
720fn is_noop(issue: &Issue, request: &TriageDecision, plan: &Plan) -> bool {
721    match plan {
722        Plan::Duplicate { target_number, .. } => {
723            let wanted = CanonicalEdge::new(issue.number, *target_number, RelationKind::Duplicates);
724            issue
725                .relationships
726                .iter()
727                .any(|relation| relation.canonical() == wanted)
728        }
729        Plan::Move(column) => {
730            if !issue.status.is(column) {
731                return false;
732            }
733            history::last_decision(issue).is_some_and(|record| {
734                record.is_same_decision(request.kind.event_kind(), Some(request.reason.as_str()))
735            })
736        }
737    }
738}
739
740/// Step 1: the fields every decision must carry (contract §Required reason and
741/// actor).
742///
743/// A free function rather than a method because it reads nothing from the
744/// service — and a check that ignores `self` but takes `&self` says the opposite
745/// about where the rule lives.
746fn check_required(issue: &Issue, request: &TriageDecision) -> DecisionResult<()> {
747    if request.kind.requires_reason() && request.reason.trim().is_empty() {
748        return Err(Refusal::missing_reason(issue.number, request.kind));
749    }
750    if request.actor.trim().is_empty() {
751        return Err(Refusal::missing_actor(issue.number));
752    }
753    // One decision is one `## History` **line**, and the grammar is line-based: a
754    // newline in the reason or the actor ends the line and starts another, which the
755    // next reader parses as a second event. That is a forged audit entry, written by
756    // the decision the user is making:
757    //
758    //     $ tix triage decline 1 --reason $'no budget\n- 2026-10-01T09:00:00Z — root — triage_accepted — triage -> done'
759    //     # two events in ## History; the second one is a lie
760    //
761    // Refused rather than stripped: a reason silently altered on the way to the
762    // audit trail is the same class of problem in a quieter colour — the file would
763    // no longer record what the user decided.
764    //
765    // Checked here, at the one boundary every surface crosses (the CLI's two
766    // spellings, the TUI's modal, the MCP tools), because this is the rule about what
767    // a decision *is*. The pre-existing `--reason` on `tix move`/`tix edit` shares
768    // this predicate now (tix #1493); a multi-line **comment body** is deliberately
769    // not guarded, because a comment lives in its own document section rather than
770    // on a `## History` line.
771    if request.reason.chars().any(is_line_break) {
772        return Err(Refusal::new(
773            "invalid_reason",
774            format!(
775                "`#{}` {} has a line break in its reason; a reason is written to one \
776                 History line, so a line break would look like a second decision",
777                issue.number, request.kind
778            ),
779        ));
780    }
781    if request.actor.chars().any(is_line_break) {
782        return Err(Refusal::new(
783            "invalid_actor",
784            format!(
785                "`#{}` has a line break in its actor; the actor is written to one History \
786                 line, so a line break would look like a second decision",
787                issue.number
788            ),
789        ));
790    }
791    Ok(())
792}
793
794/// A character that ends a `## History` line, or would move the cursor within one.
795///
796/// `\n` and `\r` are the forging vector; `\u{85}` (NEL), `\u{2028}` (line separator)
797/// and `\u{2029}` (paragraph separator) are the same thing in other encodings, and a
798/// bare `\t` is left alone because it cannot start a new entry.
799///
800/// **Shared with the other line-writing seam.** `tix move --reason` and
801/// `tix edit --status … --reason` render their override reason into the same
802/// line-based grammar, so they refuse through this predicate too rather than
803/// carrying a second copy of the character set (tix #1493). A multi-line
804/// **comment body** is deliberately not guarded: a comment is written to its own
805/// document section, not to a `## History` line, so many lines there are the
806/// point rather than a forgery.
807pub fn is_line_break(c: char) -> bool {
808    matches!(c, '\n' | '\r' | '\u{85}' | '\u{2028}' | '\u{2029}')
809}