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 // The **value** form, plain: `kind: message`, and no prefix when the message
381 // already leads with its kind. This is a stored message the batch embeds in
382 // an item outcome, not a terminal block — the rustc-style rendering happens
383 // once, at the boundary, in `From<Refusal> for TixError`.
384 if self.message.starts_with(self.kind) {
385 f.write_str(&self.message)
386 } else {
387 write!(f, "{}: {}", self.kind, self.message)
388 }
389 }
390}
391
392impl From<Refusal> for TixError {
393 /// A refusal becomes a rendered block: the one place a refusal is turned into
394 /// something a surface prints, so its rustc-style header is produced exactly
395 /// once, here, rather than by every caller that happens to `to_string()` it.
396 fn from(refusal: Refusal) -> Self {
397 TixError::Refused(crate::error::render_diagnostics(
398 "E-tix-triage",
399 [(refusal.kind, refusal.message.as_str())],
400 ))
401 }
402}
403
404/// The result of one applied decision: the updated issue and the event intent
405/// (data-model §4).
406///
407/// The issue is a **clone the caller still has to write** — the service hands
408/// back what *would* be on disk, and storage performs the write. That is the
409/// whole filesystem-free claim: every rejection and every no-op returns before
410/// this variant exists, so "did anything change?" is answerable from the return
411/// value alone.
412///
413/// `Applied` is far larger than `NoOp`, which trips `clippy::large_enum_variant`
414/// — and boxing would add an allocation to a value that is *moved*, not copied,
415/// on the only path that constructs it. The size comes from `Issue`, which the
416/// service clones by necessity (see [`DecisionService::apply`]): the caller must
417/// be able to discard the result without having given anything up.
418#[allow(clippy::large_enum_variant)]
419#[derive(Debug, Clone, PartialEq, Eq)]
420pub enum DecisionOutcome {
421 /// One decision applied: exactly one event, appended to the issue's own
422 /// History (NFR-002).
423 Applied {
424 /// The issue as the decision leaves it: status moved, entry metadata
425 /// updated, and `event` appended to its History.
426 issue: Issue,
427 /// The event intent. Always the *last* entry of `issue.history` —
428 /// one applied decision produces exactly one event, and there is no
429 /// second copy of it anywhere.
430 event: HistoryEvent,
431 /// The typed relation a duplicate decision creates. `None` for the
432 /// other three: only a duplicate adds an edge, and it adds no file
433 /// change at all (C-006).
434 relation: Option<Relationship>,
435 },
436 /// Already satisfied: no mutation, no event, no write (contract
437 /// §Idempotence and append-only behavior).
438 NoOp,
439}
440
441impl DecisionOutcome {
442 /// Whether this outcome changed nothing.
443 #[must_use]
444 pub fn is_noop(&self) -> bool {
445 matches!(self, DecisionOutcome::NoOp)
446 }
447}
448
449/// The decision service: one validated inbox configuration plus the caller's
450/// duplicate-target resolution.
451///
452/// Built once per command and reused across a batch, so a selection of fifty
453/// issues is validated against one scope rather than fifty.
454pub struct DecisionService<'a> {
455 /// The config `validate_transition` needs; also the source of
456 /// `[triage].accepted_status` and `[triage].declined_status`.
457 config: &'a Config,
458 /// The inbox: membership, and the board's category resolution.
459 scope: InboxScope,
460 /// The optional accept target from `[triage]`.
461 accepted_status: Option<String>,
462 /// The required decline target from `[triage]`.
463 declined_status: String,
464 /// How the caller resolved `--of`.
465 target: DuplicateTarget<'a>,
466}
467
468impl<'a> DecisionService<'a> {
469 /// Build a service over an already-resolved inbox scope.
470 ///
471 /// `scope` comes from the caller rather than from `config` because the
472 /// caller needs the same `Option<InboxScope>` answer for every `tix triage`
473 /// subcommand — "does this project have an inbox at all?" is the first thing
474 /// `list` asks too, and resolving it twice would give two chances to
475 /// disagree.
476 ///
477 /// The one thing checked here is the decline column, and it is checked once
478 /// rather than on every decision: a service that cannot name the column a
479 /// decline would move to has no business accepting a decline, and failing at
480 /// construction means no issue in a batch is decided before the defect shows.
481 pub fn new(
482 config: &'a Config,
483 scope: InboxScope,
484 target: DuplicateTarget<'a>,
485 ) -> DecisionResult<Self> {
486 let declined_status = config
487 .triage
488 .as_ref()
489 .and_then(|triage| triage.declined_status.clone())
490 .ok_or_else(|| {
491 Refusal::new(
492 "unknown_column",
493 "`[triage].declined_status` names no column, so a decline \
494 would have nowhere to go",
495 )
496 })?;
497 let accepted_status = config
498 .triage
499 .as_ref()
500 .and_then(|t| t.accepted_status.clone());
501 Ok(Self {
502 config,
503 scope,
504 accepted_status,
505 declined_status,
506 target,
507 })
508 }
509
510 /// Apply one decision to one issue.
511 ///
512 /// Returns the issue *as it would be written*, plus the event intent — or a
513 /// refusal, or [`DecisionOutcome::NoOp`]. The input is borrowed, so a
514 /// rejected decision provably cannot have modified it, and the caller decides
515 /// whether and when to write (contract §Diagnostics: the service produces a
516 /// refusal, the surface reports it).
517 pub fn apply(
518 &self,
519 issue: &Issue,
520 request: &TriageDecision,
521 ) -> DecisionResult<DecisionOutcome> {
522 // 1 — required fields, before the issue is looked at: a missing reason
523 // is refused the same way whatever the queue happens to contain.
524 check_required(issue, request)?;
525
526 // 2 — the target, resolved and validated against the issue's identity.
527 let plan = self.plan(issue, request)?;
528
529 // 3 — idempotence, before membership: declining twice is a no-op even
530 // though the first decline left the inbox.
531 if is_noop(issue, request, &plan) {
532 return Ok(DecisionOutcome::NoOp);
533 }
534
535 // 4 — still in the queue?
536 if !self.scope.matches(issue) {
537 return Err(if history::has_triage_decision(issue) {
538 Refusal::already_decided(issue.number)
539 } else {
540 Refusal::not_in_triage(issue.number)
541 });
542 }
543
544 let prior_state = issue.status.display().to_string();
545 let mut updated = issue.clone();
546
547 // 5 — the one transition evaluation. Nothing below re-derives a rule.
548 let (result, relation) = match plan {
549 Plan::Move(column) => {
550 let outcome = workflow::validate_transition(
551 issue,
552 &column,
553 &self.scope.resolution,
554 self.config,
555 None,
556 );
557 let to = match outcome {
558 TransitionOutcome::Accepted { to, .. } => to,
559 TransitionOutcome::Rejected(diagnostic) => {
560 return Err(Refusal::from_workflow(&diagnostic));
561 }
562 };
563 updated.status = Status::new(&to);
564 (to, None)
565 }
566 Plan::Duplicate {
567 target_number,
568 target_title,
569 } => {
570 // The relation, not a file operation: the intent is returned and
571 // storage writes it. No merge, no delete, no move (C-006).
572 let relation = Relationship::new(
573 issue.number,
574 target_number,
575 RelationKind::Duplicates,
576 &target_title,
577 );
578 let result = format!("{} #{}", relation.kind, relation.to);
579 (result, Some(relation))
580 }
581 };
582
583 // Entry metadata (data-model §2). A defer re-enters, so the wait
584 // restarts; a decision that *takes the issue out of the queue* leaves no
585 // stamp behind, because a stamp that measures a queue the issue is no
586 // longer in would age it wrongly the moment it came back — and the
587 // honest answer to "when did it enter?" is then "unknown", not a date
588 // that measures something else (research R4). The test is against the
589 // updated issue, so a decline that is configured to land in an inbox
590 // column keeps its stamp: it never left.
591 match request.kind {
592 DecisionKind::Defer => {
593 record_entry(&mut updated, &request.timestamp, Some("defer"));
594 }
595 DecisionKind::Accept | DecisionKind::Decline if !self.scope.matches(&updated) => {
596 updated.entered_at = None;
597 updated.source = None;
598 }
599 _ => {}
600 }
601
602 let record = TriageDecisionRecord::new(
603 &request.timestamp,
604 &request.actor,
605 request.kind.event_kind(),
606 prior_state,
607 result,
608 Some(request.reason.clone()),
609 request.target_issue,
610 crate::triage::entry_source(&updated).map(str::to_string),
611 );
612 let event = record.to_event();
613 updated.history.append(event.clone());
614
615 Ok(DecisionOutcome::Applied {
616 issue: updated,
617 event,
618 relation,
619 })
620 }
621
622 /// Resolve what this decision would change, and refuse it if it cannot
623 /// (step 2 of the order).
624 fn plan(&self, issue: &Issue, request: &TriageDecision) -> DecisionResult<Plan> {
625 match request.kind {
626 DecisionKind::Accept => {
627 // `--to` wins when given; `[triage].accepted_status` is the
628 // configured fallback; neither is a refusal rather than a guess.
629 // A blank `--to` is treated as absent, because a flag that
630 // carried only whitespace did not name a column.
631 let named = request
632 .target_status
633 .as_deref()
634 .map(str::trim)
635 .filter(|target| !target.is_empty())
636 .map(str::to_string);
637 named
638 .or_else(|| self.accepted_status.clone())
639 .map(Plan::Move)
640 .ok_or_else(|| Refusal::missing_target(issue.number))
641 }
642 DecisionKind::Decline => Ok(Plan::Move(self.declined_status.clone())),
643 DecisionKind::Defer => Ok(Plan::Move(self.scope.deferred_status.clone())),
644 DecisionKind::Duplicate => {
645 let target = self.resolve_duplicate(issue, request)?;
646 Ok(Plan::Duplicate {
647 target_number: target.number,
648 target_title: target.title.clone(),
649 })
650 }
651 }
652 }
653
654 /// Validate `--of` and return the issue it names (T014).
655 ///
656 /// The self-link test goes through [`CanonicalEdge`] rather than comparing
657 /// two numbers, so "is this a self link?" is the same question the
658 /// relationship service asks of an authored edge and has one answer. The
659 /// target itself is only ever *read*: this service creates a relation
660 /// intent, never a file operation.
661 fn resolve_duplicate(
662 &self,
663 issue: &Issue,
664 request: &TriageDecision,
665 ) -> DecisionResult<&'a Issue> {
666 // Ambiguity first: it is the only refusal about the *selector* rather
667 // than the target, and reporting "you gave no target" to someone who
668 // supplied one that matched three issues sends them looking for a flag
669 // they already used.
670 if let DuplicateTarget::Ambiguous = self.target {
671 return Err(Refusal::ambiguous());
672 }
673 let asked = request.target_issue.ok_or_else(|| {
674 Refusal::invalid_duplicate_target(format!(
675 "`#{}` is a duplicate decision with no target (`--of`)",
676 issue.number
677 ))
678 })?;
679 if CanonicalEdge::new(issue.number, asked, RelationKind::Duplicates).is_self_link() {
680 return Err(Refusal::invalid_duplicate_target(format!(
681 "`#{asked}` cannot be a duplicate of itself"
682 )));
683 }
684 match self.target {
685 DuplicateTarget::Resolved(target) if target.number == asked => Ok(target),
686 DuplicateTarget::Resolved(target) => Err(Refusal::unknown_issue(format!(
687 "`--of` resolved to `#{}`, but `#{asked}` was asked for",
688 target.number
689 ))),
690 DuplicateTarget::Unknown => {
691 Err(Refusal::unknown_issue(format!("`#{asked}` does not exist")))
692 }
693 // Unreachable: `Ambiguous` returns above. Written as a real arm
694 // rather than `unreachable!()` so the match stays total and a
695 // future reordering cannot introduce a panic.
696 DuplicateTarget::Ambiguous => Err(Refusal::ambiguous()),
697 }
698 }
699}
700
701/// Step 3: whether this decision is already satisfied, so nothing is changed
702/// and no event is appended.
703///
704/// Two different questions with one answer each, because "already done" means
705/// different things for a decision that moves an issue and one that records an
706/// edge:
707///
708/// - **duplicate**: the canonical `duplicates` edge already exists. The reason
709/// is deliberately ignored — an edge is an edge, and re-declaring the same
710/// duplicate with a sharper justification is a comment, not a second relation.
711/// - **move**: the issue is already in the target column **and** the most recent
712/// decision recorded is this kind with this reason. The History half matters
713/// for `defer`, where the column does not change at all: a first defer must
714/// refresh the entry and append, and an identical repeat must do neither. It
715/// also means a *changed* reason on an unchanged column is a new decision,
716/// which is quickstart §7's rule.
717///
718/// The consequence worth naming: an issue moved into the target column by a
719/// plain `tix move`, whose last triage decision happens to be this kind and
720/// reason, reads as a no-op. The requested final state and reason both hold, so
721/// nothing would change — and inventing an event to mark the difference would be
722/// the log recording a decision the user did not make.
723///
724/// A free function for the same reason as [`check_required`]: it reads nothing
725/// from the service, and the plan it is handed already carries the resolved
726/// target.
727fn is_noop(issue: &Issue, request: &TriageDecision, plan: &Plan) -> bool {
728 match plan {
729 Plan::Duplicate { target_number, .. } => {
730 let wanted = CanonicalEdge::new(issue.number, *target_number, RelationKind::Duplicates);
731 issue
732 .relationships
733 .iter()
734 .any(|relation| relation.canonical() == wanted)
735 }
736 Plan::Move(column) => {
737 if !issue.status.is(column) {
738 return false;
739 }
740 history::last_decision(issue).is_some_and(|record| {
741 record.is_same_decision(request.kind.event_kind(), Some(request.reason.as_str()))
742 })
743 }
744 }
745}
746
747/// Step 1: the fields every decision must carry (contract §Required reason and
748/// actor).
749///
750/// A free function rather than a method because it reads nothing from the
751/// service — and a check that ignores `self` but takes `&self` says the opposite
752/// about where the rule lives.
753fn check_required(issue: &Issue, request: &TriageDecision) -> DecisionResult<()> {
754 if request.kind.requires_reason() && request.reason.trim().is_empty() {
755 return Err(Refusal::missing_reason(issue.number, request.kind));
756 }
757 if request.actor.trim().is_empty() {
758 return Err(Refusal::missing_actor(issue.number));
759 }
760 // One decision is one `## History` **line**, and the grammar is line-based: a
761 // newline in the reason or the actor ends the line and starts another, which the
762 // next reader parses as a second event. That is a forged audit entry, written by
763 // the decision the user is making:
764 //
765 // $ tix triage decline 1 --reason $'no budget\n- 2026-10-01T09:00:00Z — root — triage_accepted — triage -> done'
766 // # two events in ## History; the second one is a lie
767 //
768 // Refused rather than stripped: a reason silently altered on the way to the
769 // audit trail is the same class of problem in a quieter colour — the file would
770 // no longer record what the user decided.
771 //
772 // Checked here, at the one boundary every surface crosses (the CLI's two
773 // spellings, the TUI's modal, the MCP tools), because this is the rule about what
774 // a decision *is*. The pre-existing `--reason` on `tix move`/`tix edit` shares
775 // this predicate now (tix #1493); a multi-line **comment body** is deliberately
776 // not guarded, because a comment lives in its own document section rather than
777 // on a `## History` line.
778 if request.reason.chars().any(is_line_break) {
779 return Err(Refusal::new(
780 "invalid_reason",
781 format!(
782 "`#{}` {} has a line break in its reason; a reason is written to one \
783 History line, so a line break would look like a second decision",
784 issue.number, request.kind
785 ),
786 ));
787 }
788 if request.actor.chars().any(is_line_break) {
789 return Err(Refusal::new(
790 "invalid_actor",
791 format!(
792 "`#{}` has a line break in its actor; the actor is written to one History \
793 line, so a line break would look like a second decision",
794 issue.number
795 ),
796 ));
797 }
798 Ok(())
799}
800
801/// A character that ends a `## History` line, or would move the cursor within one.
802///
803/// `\n` and `\r` are the forging vector; `\u{85}` (NEL), `\u{2028}` (line separator)
804/// and `\u{2029}` (paragraph separator) are the same thing in other encodings, and a
805/// bare `\t` is left alone because it cannot start a new entry.
806///
807/// **Shared with the other line-writing seam.** `tix move --reason` and
808/// `tix edit --status … --reason` render their override reason into the same
809/// line-based grammar, so they refuse through this predicate too rather than
810/// carrying a second copy of the character set (tix #1493). A multi-line
811/// **comment body** is deliberately not guarded: a comment is written to its own
812/// document section, not to a `## History` line, so many lines there are the
813/// point rather than a forgery.
814pub fn is_line_break(c: char) -> bool {
815 matches!(c, '\n' | '\r' | '\u{85}' | '\u{2028}' | '\u{2029}')
816}