tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use crate::config::Config;
use crate::error::{Result, TixError, render_diagnostics};
use crate::hierarchy::{self, HierarchyIndex};
use crate::model::{HistoryEventKind, Issue, Status, TransitionDecision};
use crate::relationships::{
    CanonicalEdge, Diagnostic, IssueView, RelationKind, Relationship, RelationshipGraph,
};
use crate::slug::slugify;

mod epics;
mod lifecycle;
mod parent;
mod projects;
mod query;
mod relations;
mod status;

pub struct Store {
    pub issues_dir: PathBuf,
    pub config: Config,
}

/// The outcome of one relationship mutation.
///
/// A typed relationship is a **single directed edge**, so a mutation normally
/// writes exactly one issue file — the one whose frontmatter owns the canonical
/// edge. `written` is `None` when the mutation was a no-op (an
/// already-present edge, or an absent edge on remove), which is what makes
/// "an idempotent re-apply appends no second History event" checkable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelationshipOutcome {
    /// The issue whose file was written, if any.
    pub written: Option<Issue>,
    /// The relationship the mutation concerned, in canonical form.
    pub relationship: Relationship,
    /// Whether a file was actually written.
    pub changed: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IssueSelector {
    Number(u32),
    Ref(crate::id::IssueRef),
    Filename(String),
    Slug(String),
}

/// Result of `Store::add_asset`: the relative markdown link inserted into the
/// body and the actual written file name (collision-resolved).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssetAdded {
    pub link: String,
    pub written_name: String,
}

// Disclosures raised by writes, drained by whichever surface is presenting.
//
// A disclosure is something the user must be told that is not an error: the removal of the
// retired `links:` key, or a mention reconciliation that declined to touch a malformed target
// file. It is queued rather than printed so every surface can render it in its own channel —
// stderr for the CLI, the MCP result payload for a tool call, the status line for the TUI.
//
// Thread-local rather than process-global: a CLI and an MCP request each drain their own, and a
// process-global queue made concurrent callers — and the test suite, which runs in parallel —
// see each other's disclosures.
thread_local! {
    static WRITE_DISCLOSURES: std::cell::RefCell<Vec<String>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// Queue a disclosure for the presenting surface to render.
pub(crate) fn push_disclosure(message: String) {
    WRITE_DISCLOSURES.with(|queue| queue.borrow_mut().push(message));
}

/// A mention reconciliation declined to touch a target file, naming the reason.
pub(crate) fn mention_disclosure(message: String) {
    push_disclosure(message);
}

/// Record that a write removed the retired `links:` key from `filename`.
/// `pub(crate)` so the surface drains in `app` and `mcp` can be tested against
/// a raised disclosure. Production code reaches it only through `Store::update`.
pub(crate) fn retired_key_disclosure(filename: &str) {
    push_disclosure(format!(
        "remove `links:` by hand to silence \u{2014} {filename} (retired by \
         C-001; never read as typed data, no migration)"
    ));
}

/// Take everything queued since the last drain.
pub fn take_disclosures() -> Vec<String> {
    WRITE_DISCLOSURES.with(|queue| std::mem::take(&mut *queue.borrow_mut()))
}

// A bounded journal of issue-file writes made through this store.
//
// The TUI's in-process writes used to re-read and parse the whole issue tree
// just to learn about the one file the store had already written. The journal
// closes that gap without changing the external-edit watcher: `refresh_corpus`
// drains it into the same `FsDelta` path the watcher uses.
//
// Thread-local for the same reason as the disclosure queue: a CLI and an MCP
// request each run on their own thread, and the test suite runs tests in
// parallel. The journal is bounded. A long-lived MCP thread can write more than
// the journal retains, but exceeding the bound switches the next refresh to the
// full-rebuild fallback instead of growing without limit.
const ISSUE_WRITE_JOURNAL_LIMIT: usize = 4096;

#[derive(Debug, Default)]
struct IssueWriteJournal {
    changed: BTreeSet<PathBuf>,
    removed: BTreeSet<PathBuf>,
    overflowed: bool,
}

/// How the next in-process corpus refresh should get its changes.
#[derive(Debug)]
pub(crate) enum InternalIssueWrites {
    /// No issue file was written through this thread's store.
    None,
    /// The exact paths to apply through the existing incremental reader.
    Delta(crate::watcher::FsDelta),
    /// More paths were written than the journal retains; rebuild from disk.
    Overflow,
}

thread_local! {
    static ISSUE_WRITE_JOURNAL: std::cell::RefCell<IssueWriteJournal> =
        std::cell::RefCell::new(IssueWriteJournal::default());
}

/// Record one issue-file write or removal for the next in-process refresh.
///
/// Paths are store-relative, matching `Issue::filename` and `FsDelta`. A later
/// observation wins: writing then moving one file leaves only the destination
/// as changed and the source as removed.
pub(crate) fn journal_issue_change(path: &Path, present: bool) {
    if !is_issue_rel_path(path) {
        return;
    }
    ISSUE_WRITE_JOURNAL.with(|journal| {
        let mut journal = journal.borrow_mut();
        if journal.overflowed {
            return;
        }
        if present {
            journal.removed.remove(path);
            journal.changed.insert(path.to_path_buf());
        } else {
            journal.changed.remove(path);
            journal.removed.insert(path.to_path_buf());
        }
        if journal.changed.len() + journal.removed.len() > ISSUE_WRITE_JOURNAL_LIMIT {
            journal.changed.clear();
            journal.removed.clear();
            journal.overflowed = true;
        }
    });
}

/// Drain the paths written since the last in-process refresh.
pub(crate) fn take_internal_issue_writes() -> InternalIssueWrites {
    ISSUE_WRITE_JOURNAL.with(|journal| {
        let mut journal = journal.borrow_mut();
        if journal.overflowed {
            *journal = IssueWriteJournal::default();
            return InternalIssueWrites::Overflow;
        }
        if journal.changed.is_empty() && journal.removed.is_empty() {
            return InternalIssueWrites::None;
        }
        let changed = std::mem::take(&mut journal.changed);
        let removed = std::mem::take(&mut journal.removed);
        InternalIssueWrites::Delta(crate::watcher::FsDelta {
            changed: changed.into_iter().collect(),
            removed: removed.into_iter().collect(),
        })
    })
}

// A command-level write journal, active only inside a transaction (tix #1541,
// decision option 2; closes the `tix edit` window in #1302).
//
// Thread-local for the same reason the disclosure queue is: a CLI and an MCP
// request each run on their own thread, and the test suite runs tests in
// parallel, so a process-global stack would let one caller's rollback undo
// another's writes.
//
// The journal is a **stack of undo records taken before each mutation**, not a
// copy of the tree. That keeps a transaction cheap for the common case (one
// file) while still covering the multi-file writes — `set_relationships`, a
// reassign that moves a file and its asset dir, a status change — that are the
// reason the layer exists.
thread_local! {
    static WRITE_JOURNAL: std::cell::RefCell<Option<Vec<Undo>>> =
        const { std::cell::RefCell::new(None) };
}

/// One filesystem change a transaction can undo, recorded **before** it happens.
enum Undo {
    /// `path` held `before` (or did not exist in the `None` case) before a
    /// write or a delete. Undone by restoring the bytes, or removing a file the
    /// transaction created.
    Write {
        path: PathBuf,
        before: Option<Vec<u8>>,
    },
    /// `from` was renamed to `to`. Undone by renaming it back. Used for the
    /// file **and** its `<slug>-assets/` directory, so a reassign is one unit.
    Move { from: PathBuf, to: PathBuf },
}

/// Record `path`'s pre-image, once, if a transaction is active.
///
/// The **first** pre-image wins: a file written twice in one transaction must be
/// restored to the state it had before the transaction, not before the second
/// write — otherwise rolling back after two writes would leave the first write's
/// content behind.
///
/// `pub(crate)` because the mention store writes outside the issues directory and must
/// participate in the same journal: a command whose `Store::transaction` rolls back has to
/// roll its mention files back with its issue files.
pub(crate) fn journal_record_write(path: &Path) {
    WRITE_JOURNAL.with(|journal| {
        let mut borrow = journal.borrow_mut();
        let Some(entries) = borrow.as_mut() else {
            return;
        };
        if entries
            .iter()
            .any(|undo| matches!(undo, Undo::Write { path: seen, .. } if seen == path))
        {
            return;
        }
        entries.push(Undo::Write {
            path: path.to_path_buf(),
            before: std::fs::read(path).ok(),
        });
    });
}

/// Record a rename, if a transaction is active.
fn journal_record_move(from: &Path, to: &Path) {
    WRITE_JOURNAL.with(|journal| {
        let mut borrow = journal.borrow_mut();
        let Some(entries) = borrow.as_mut() else {
            return;
        };
        entries.push(Undo::Move {
            from: from.to_path_buf(),
            to: to.to_path_buf(),
        });
    });
}

/// Undo every recorded change, newest first.
///
/// Best-effort and infallible by design: a rollback that itself fails must not
/// mask the error that triggered it, so each step ignores its own I/O result and
/// the caller still returns the original error.
fn rollback(entries: Vec<Undo>) {
    for entry in entries.into_iter().rev() {
        match entry {
            Undo::Write { path, before } => match before {
                Some(bytes) => {
                    let _ = std::fs::write(&path, bytes);
                }
                None => {
                    let _ = std::fs::remove_file(&path);
                }
            },
            Undo::Move { from, to } => {
                let _ = std::fs::rename(&to, &from);
            }
        }
    }
}

/// The identity recorded as the `actor` of a History event.
///
/// Falls back to `unknown` rather than failing a mutation, so a repository with
/// no configured git identity can still record an audit trail.
///
/// Public because the blocked-move guard (WP04) records its own History event
/// outside the storage layer — the acknowledgement is a *policy* decision, not a
/// storage step. Duplicating the git-identity resolution in the command layer
/// would give the audit trail two definitions of "who acted", which is the kind
/// of drift an audit trail exists to prevent.
pub fn actor_identity() -> String {
    crate::assignee::git_identity()
        .map(|id| id.to_string())
        .unwrap_or_else(|| "unknown".to_string())
}

/// A request to move an issue to a column, through the seam.
///
/// WP03 T013. A struct rather than a positional list because the three arguments
/// are all `Option`-shaped and adjacent: `(Some(commit), None, None)` is a mistake
/// waiting to happen at a call site, and the field names are what stop it.
///
/// ## Deliberately absent
///
/// **No `actor`.** The seam records the identity itself through
/// [`actor_identity`], so a caller cannot attribute a decision to somebody else
/// and the audit trail keeps one definition of "who acted". Passing an actor in
/// would make the attribution a choice of the caller, which is exactly the thing
/// an audit trail must not be.
///
/// **No `updated`.** The seam bumps it, on exactly the transitions that change
/// something. A caller supplying it would be able to write a file whose date says
/// a no-op was an edit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusChange<'a> {
    /// The column to move to. A column the board does not configure is refused
    /// with `unknown_column`; a same-column request is accepted and inert.
    pub column: &'a str,
    /// The commit to record when this move reaches the board's completion column.
    ///
    /// Ignored on a move that does not reach completion, and a previously recorded
    /// commit is cleared on a move that *leaves* it. `None` therefore means "record
    /// nothing", which is distinct from "leave the old value alone" — leaving an
    /// issue in its completion column with an unrelated commit is what the clear
    /// exists to prevent.
    pub commit: Option<&'a str>,
    /// Why a policy rule was being overridden, when one was.
    ///
    /// Without a reason the service refuses a transition out of a terminal
    /// category outright, so this is the only way out of `done`. The CLI flag that
    /// supplies it lands in WP04; the seam takes the parameter now so a
    /// half-built seam — one that can refuse but never accept-with-reason — is
    /// never what ships.
    pub override_reason: Option<&'a str>,
}

impl<'a> StatusChange<'a> {
    /// A plain move: no commit, no override.
    ///
    /// The common case, named so the call site reads as "move it" rather than as
    /// three `None`s.
    pub fn to(column: &'a str) -> Self {
        Self {
            column,
            commit: None,
            override_reason: None,
        }
    }

    /// This request with a commit, for a move that reaches completion.
    pub fn with_commit(mut self, commit: Option<&'a str>) -> Self {
        self.commit = commit;
        self
    }

    /// This request with an override reason, for a move out of a terminal
    /// category.
    pub fn with_override(mut self, reason: Option<&'a str>) -> Self {
        self.override_reason = reason;
        self
    }
}

/// What the seam did (`WP03` T013).
///
/// `written` and `decision` are deliberately redundant. Either alone would do:
/// `written == false` implies `decision.is_none()`, and a decision always implies
/// a write. They are both here because the two questions a caller asks are
/// different — "did anything happen?" and "what gets appended?" — and reading the
/// answer to one off the other is the kind of inference that breaks silently when a
/// fourth outcome is added later.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusOutcome {
    /// The issue as it now stands in the store: the accepted column, the bumped
    /// `updated`, and the appended decision. On an inert no-op this is the issue
    /// exactly as it was.
    pub issue: Issue,
    /// The decision appended to the issue's History, or `None` when nothing was
    /// written.
    pub decision: Option<TransitionDecision>,
    /// Whether the file was written at all.
    ///
    /// `false` for a same-column re-apply and for any path that carries no change.
    /// A refusal is not represented here — it is an `Err`, so "refused" and
    /// "accepted but did nothing" are different types rather than one `Outcome`
    /// with a flag.
    pub written: bool,
}

/// The accepted half of [`crate::workflow::TransitionOutcome`], unpacked.
///
/// WP03. A private struct so the seam's body reads as ordinary code, and so the
/// only way to reach the write is to have destructured the service's `Accepted`
/// variant. The alternative — matching on the enum at each use — is how a future
/// edit ends up handling a new outcome variant once in this function and not at
/// all in the next one.
struct TransitionAccepted {
    changed: bool,
    from: String,
    to: String,
    from_category: crate::workflow::WorkflowCategory,
    to_category: crate::workflow::WorkflowCategory,
    override_reason: Option<String>,
}

impl TransitionAccepted {
    /// The accepted transition, or the diagnostic that refused it.
    fn try_from(
        outcome: crate::workflow::TransitionOutcome,
    ) -> std::result::Result<Self, crate::workflow::WorkflowDiagnostic> {
        match outcome {
            crate::workflow::TransitionOutcome::Accepted {
                changed,
                from,
                to,
                from_category,
                to_category,
                override_reason,
            } => Ok(Self {
                changed,
                from,
                to,
                from_category,
                to_category,
                override_reason,
            }),
            crate::workflow::TransitionOutcome::Rejected(diagnostic) => Err(diagnostic),
        }
    }
}

/// A [`Relationship`] standing for a canonical edge that has no stored row.
///
/// Deliberately local to the storage layer rather than a method on
/// `CanonicalEdge`: the service's surface is owned by WP01 and is not widened
/// from here. The id and display are empty because no row exists to carry them
/// — this value only reports *which* edge a no-op concerned.
fn canonical_placeholder(canonical: &CanonicalEdge) -> Relationship {
    Relationship {
        id: String::new(),
        from: canonical.from,
        to: canonical.to,
        kind: canonical.kind,
        display: String::new(),
    }
}

/// Turn a blocking validation result into the crate error surface.
///
/// The first diagnostic's message is preserved verbatim so the user sees the
/// field-aware text the service produced, prefixed with its diagnostic name
/// (C-004). A blocking result means **no** file was written (SC-005), so this
/// is raised before any mutation.
fn relationship_error(errors: &[Diagnostic]) -> TixError {
    if errors.is_empty() {
        return TixError::InvalidInput("relationship rejected".into());
    }
    TixError::Refused(render_diagnostics(
        "E-tix-relationship",
        errors.iter().map(|d| (d.kind.as_str(), d.message.as_str())),
    ))
}

/// A durable, exclusive claim on one issue number.
///
/// ## Why this exists (#1352, part 2)
///
/// [`Store::resolve_next_number`] reads the directory, takes `max(number)`, and adds
/// one. That is a **hint**, not an allocation: nothing serialises read-then-write
/// across processes, so two `tix create` runs that reach it together both get the
/// same answer and both write an issue with that number.
///
/// Measured with 24 concurrent `tix create` subprocesses with distinct titles:
///
/// ```text
/// files: 24   distinct numbers: 8
///   5 × number: 7    4 × number: 4    4 × number: 6    3 × number: 3
///   3 × number: 5    2 × number: 0    2 × number: 1    1 × number: 2
/// ```
///
/// 16 of 24 issues shared a number with another file. After that every
/// number-addressed operation — `tix view 0`, `tix move 0`, `tix edit 0`,
/// `tix link 0 X`, `tix delete 0` — silently addresses an arbitrary one of several
/// issues, which is arguably worse than the clobber it accompanies.
///
/// It needs **two** processes (an agent's `tix mcp` plus a human's `tix`), which is
/// why it is rarer and why spacing the calls out appears to fix it. There is no
/// intra-process race: `src/mcp/mod.rs` handles one message to completion before
/// reading the next, the TUI is a single event loop, and `Store` is `&self`.
///
/// ## Why a claim ledger and not a lockfile
///
/// The obvious fix is a lock file held across resolve-and-write, and it was rejected
/// because **a lock can be lost**: a process that crashes while holding it leaves the
/// next create to break the lock on a timeout, and breaking a lock on a timeout also
/// breaks it for a process that is merely slow. Every lock-staleness heuristic trades
/// mutual exclusion for liveness, and this is the one property that must not be
/// traded.
///
/// A claim ledger cannot lose mutual exclusion. The claim is a zero-byte file created
/// with `O_EXCL`, and a process that dies holding one leaves an **orphan claim** —
/// an allocated-but-unused number, never a lost lock. A burned number is a gap, and
/// this system already produces gaps deliberately: reusing a number requires deleting
/// every higher-numbered issue first, and deleting an issue leaves its number free.
/// So the failure mode of the fix matches the existing, documented behaviour of the
/// allocator rather than introducing a new one.
///
/// The cost is one hidden marker file per created issue. That is real, and it is the
/// price of not needing a lease timeout. The markers live **beside** the issues
/// directory rather than inside it, so nothing that reads `docs/issues/` — a glob, a
/// script, a test counting segments — ever sees them; see [`claims_dir`].
struct NumberClaim {
    path: PathBuf,
    /// Whether this claim must be released on drop. `false` once the issue file
    /// exists, at which point the file — not the marker — is the authority for the
    /// number.
    armed: bool,
}

impl NumberClaim {
    /// The directory holding one marker per claimed number.
    const DIR: &'static str = ".tix-numbers";

    /// Claim `start`, or the next free number at or above it.
    ///
    /// `start` comes from [`Store::resolve_next_number`] and is already past every
    /// number any issue file claims, so the first candidate is normally free and the
    /// loop runs once. The loop exists for the concurrent case, and the climb is
    /// bounded so a corrupt ledger produces an error rather than an unbounded scan.
    fn acquire(issues_dir: &Path, start: u32) -> Result<Self> {
        const MAX_ATTEMPTS: u32 = 10_000;
        let dir = claims_dir(issues_dir);
        std::fs::create_dir_all(&dir)?;
        let mut number = start;
        for _ in 0..MAX_ATTEMPTS {
            let path = dir.join(format!("{number}.claim"));
            match std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&path)
            {
                Ok(_) => {
                    return Ok(Self { path, armed: true });
                }
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                    number += 1;
                }
                Err(e) => return Err(TixError::Io(e)),
            }
        }
        Err(TixError::Io(std::io::Error::new(
            std::io::ErrorKind::AlreadyExists,
            format!(
                "no free issue number at or above {start} after {MAX_ATTEMPTS} attempts; \
                 {} is probably corrupt",
                dir.display()
            ),
        )))
    }

    /// The number this claim holds.
    fn number(&self) -> Option<u32> {
        self.path.file_stem()?.to_str()?.parse::<u32>().ok()
    }

    /// Free a number that is no longer in use.
    ///
    /// Called by [`Store::delete`], so the ledger does not permanently reserve the
    /// number of a deleted issue. Best-effort: if the ledger directory is missing or
    /// the removal fails, the create path simply climbs past the stale claim — which
    /// costs a number but never hands the same number to two issues.
    fn release_number(issues_dir: &Path, number: u32) {
        let _ = std::fs::remove_file(claims_dir(issues_dir).join(format!("{number}.claim")));
    }

    /// Give the number back, so a create that failed after claiming it does not burn
    /// one. Idempotent, and a no-op for an already-committed claim.
    fn release(&mut self) {
        if self.armed {
            let _ = std::fs::remove_file(&self.path);
            self.armed = false;
        }
    }

    /// Keep the claim permanently, because the issue file for it now exists.
    ///
    /// Without this, `Drop` would release the marker and the whole mechanism would
    /// be a no-op — which is exactly what happened the first time this was written.
    /// The `Drop` backstop below is for frames that *never reach* a commit, so it
    /// must be disarmed deliberately on the success path rather than left to run
    /// unconditionally.
    fn commit(&mut self) {
        self.armed = false;
    }
}

impl Drop for NumberClaim {
    /// A claim still armed when the `Store::create` frame unwinds — a `write`
    /// error, or a panic — is released, so a failed create does not leak a number.
    /// The `is_err` branch in `create` releases on the ordinary path; this is the
    /// backstop for the paths that never reach it.
    fn drop(&mut self) {
        self.release();
    }
}

impl std::fmt::Debug for NumberClaim {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NumberClaim")
            .field("path", &self.path)
            .field("armed", &self.armed)
            .finish()
    }
}

impl PartialEq for NumberClaim {
    fn eq(&self, other: &Self) -> bool {
        self.path == other.path
    }
}
impl Eq for NumberClaim {}

/// The outcome of a hierarchy write, mirroring [`RelationshipOutcome`] so a
/// surface handles both with the same shape.
#[derive(Debug, Clone)]
pub struct ParentOutcome {
    /// The child as written, or `None` when the mutation was a no-op.
    ///
    /// `None` for a no-op, matching [`RelationshipOutcome`]: a retried command must
    /// not pad the audit trail, and a `changed: true` that wrote nothing is a lie.
    /// A caller that needs the current state reads [`Self::parent`], which is
    /// reported either way — the same split `RelationshipOutcome` uses for
    /// `relationship`.
    pub written: Option<Issue>,
    /// The child's parent after the call.
    pub parent: Option<u32>,
    /// The event appended to `## History`, or `None` for a no-op.
    ///
    /// `None` for a no-op is the point: a retried command must not pad the
    /// audit trail, and a `changed: true` that wrote nothing is a lie.
    pub event: Option<crate::hierarchy::ParentEvent>,
    /// Whether anything was written.
    pub changed: bool,
}

/// The outcome of one project association mutation (mission
/// `first-class-projects-01M3BYBW`, WP03).
///
/// Shaped like [`ParentOutcome`]: `written` is `None` for a no-op and the current
/// list is reported either way, so a caller that needs the state does not have to
/// re-read to learn it, and a `changed: false` is never paired with a write.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectAssociationOutcome {
    /// The issue whose file was written, or `None` when the mutation was a no-op.
    pub written: Option<Issue>,
    /// The issue's association list after the call, exactly as the service
    /// returned it.
    pub project_ids: Vec<String>,
    /// The History event appended, or `None` for a no-op.
    pub event: Option<crate::projects::ProjectEvent>,
    /// Whether anything was written.
    pub changed: bool,
}

/// One entry of a bulk association run (WP03).
///
/// One entry per input selector, in input order, so a refusal is observable
/// beside the rest rather than aborting them (contract `project-service.md` §3).
/// It derives only `Debug` because [`TixError`] is neither `Clone` nor `PartialEq`.
#[derive(Debug)]
pub struct BulkAssociationOutcome {
    /// The selector exactly as the caller wrote it.
    pub selector: String,
    /// The change, or the refusal, for that selector.
    pub outcome: Result<ProjectAssociationOutcome>,
}

/// The outcome of one epic reference mutation (mission
/// `epics-work-items-01M3BYW4`, WP03).
///
/// Shaped like [`ProjectAssociationOutcome`]: `written` is `None` for a no-op and
/// the current list is reported either way, so a caller that needs the state does
/// not have to re-read to learn it, and a `changed: false` is never paired with a
/// write.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicReferenceOutcome {
    /// The issue whose file was written, or `None` when the mutation was a no-op.
    pub written: Option<Issue>,
    /// The issue's reference list after the call, exactly as the service returned
    /// it.
    pub epic_ids: Vec<String>,
    /// The History event appended, or `None` for a no-op.
    pub event: Option<crate::epics::EpicEvent>,
    /// Whether anything was written.
    pub changed: bool,
}

/// One entry of a bulk reference run (WP03).
///
/// One entry per input selector, in input order, so a refusal is observable
/// beside the rest rather than aborting them (`contracts/epic-service.md` §5).
/// It derives only `Debug` because [`TixError`] is neither `Clone` nor `PartialEq`.
#[derive(Debug)]
pub struct BulkReferenceOutcome {
    /// The selector exactly as the caller wrote it.
    pub selector: String,
    /// The change, or the refusal, for that selector.
    pub outcome: Result<EpicReferenceOutcome>,
}

impl Store {
    /// File counts at or above this fan the scan's read+parse across threads.
    /// Below it a serial loop is faster than the thread setup, so a small
    /// repository keeps the boring path.
    const PARALLEL_SCAN_THRESHOLD: usize = 256;
    /// Upper bound on scan threads. The work is read- and YAML-parse-bound;
    /// unbounded fan-out adds scheduling cost without throughput.
    const PARALLEL_SCAN_THREADS: usize = 8;

    /// The mention store, or `None` when `[mentions] enabled = false`.
    ///
    /// One constructor for every call site — the write seam, the TUI's indicator and the CLI's
    /// `tix mentions` — so "disabled" cannot mean different things in different places: no
    /// store, no scan, no write.
    ///
    /// The directory resolves against the **project root**, the same rule `issues_dir` follows,
    /// so a `tix` run from a subdirectory reads and writes the same files.
    pub fn mention_store(&self) -> Option<crate::mentions::store::MentionStore> {
        if !self.config.mentions.enabled {
            return None;
        }
        let dir = self.config.mentions.resolve_dir(&self.issues_dir);
        Some(crate::mentions::store::MentionStore::new(dir))
    }

    /// Reconcile `issue`'s mentions into the store, best-effort.
    ///
    /// Called from every method that persists issue content ([`Store::create`],
    /// [`Store::update`] — which `Store::set_status` reaches — and the clearing side of
    /// [`Store::delete`]), so no surface can write an issue without its mentions being
    /// reconciled. It never fails the write: a problem is raised as a disclosure and the issue
    /// write stands.
    fn reconcile_mentions(&self, issue: &Issue, file: &str) {
        let Some(store) = self.mention_store() else {
            return;
        };
        // A legacy issue with no `id:` falls back to its path, which is stable for as long as
        // the issue is not moved — the same best-effort the model makes everywhere else.
        let id = issue.id.as_deref().unwrap_or(file);
        store.reconcile(crate::mentions::IssueContent {
            id,
            number: issue.number,
            file,
            title: &issue.title,
            body: &issue.body,
        });
    }

    /// Drop every stored mention for the issue with `id`, best-effort.
    fn clear_mentions(&self, id: &str) {
        let Some(store) = self.mention_store() else {
            return;
        };
        if let Err(e) = store.clear_issue(id) {
            crate::storage::mention_disclosure(format!("mentions: {e} (left untouched)"));
        }
    }

    // -- T008 — hierarchy writes ------------------------------------------
    //
    // Validate-then-write, exactly as `link` does it. The service owns the rule
    // and produces the History event; this layer performs the write. A blocking
    // result writes nothing and appends nothing (contract §4, SC-004).

    // -- WP03 — project associations ---------------------------------------
    //
    // Validate-then-write, exactly as `link` and the parent operations do it.
    // `crate::projects` is the single owner of membership, uniqueness, and
    // reference rules; this layer performs the write the service authorised and
    // holds **no project rule of its own**. It applies the list the service
    // returned, verbatim, and appends the one event the service produced.

    // -- WP03 — epic references --------------------------------------------
    //
    // Validate-then-write, exactly as `link`, the parent operations, and the
    // project associations do it. `crate::epics` is the single owner of
    // reference rules; this layer performs the write the service authorised and
    // holds **no epic rule of its own**. It applies the list the service
    // returned, verbatim, and appends the one event the service produced.
}

/// Whether a **relative** path is one [`Store::scan`] would index as an issue
/// file, at any depth (issue #10 follow-up; configurable layout).
///
/// A path is an issue file when every component is a normal name, no component
/// is a `.tix-tmp-*` temp dir or a `<slug>-assets/` dir, and the final component
/// ends in `.md`. Depth is unbounded so the incremental corpus matches a full
/// rebuild under any `[layout]` template.
pub(crate) fn is_issue_rel_path(rel: &Path) -> bool {
    let mut file_name: Option<&std::ffi::OsStr> = None;
    for component in rel.components() {
        match component {
            std::path::Component::Normal(segment) => {
                let Some(s) = segment.to_str() else {
                    return false;
                };
                if s.starts_with(".tix-tmp-") || s.ends_with("-assets") {
                    return false;
                }
                file_name = Some(segment);
            }
            std::path::Component::CurDir => {}
            // RootDir, ParentDir, Prefix: not a store-relative issue path.
            _ => return false,
        }
    }
    file_name.is_some_and(|name| name.to_string_lossy().ends_with(".md"))
}

/// Validate an issue filename. A filename is either a legacy flat basename
/// (`2026-05-10-fix-login.md`) or a grouped path with exactly one assignee
/// segment prefix (`alice/2026-05-10-fix-login.md`, C-008/C-010).
///
/// Refused in all cases: NUL bytes, backslashes, the `..` component, empty
/// components (leading/trailing/double slashes), absolute / leading-slash
/// paths, and nesting deeper than one segment. Every refusal is a hard
/// [`TixError::InvalidInput`] raised before any filesystem touch.
fn validate_filename(filename: &str) -> Result<()> {
    if filename.is_empty() {
        return Err(TixError::InvalidInput(format!(
            "filename must not be empty: {filename:?}"
        )));
    }
    if filename.starts_with('/') {
        return Err(TixError::InvalidInput(format!(
            "filename must be relative (no leading `/`): {filename}"
        )));
    }
    if filename.contains('\\') {
        return Err(TixError::InvalidInput(format!(
            "filename must not contain backslashes: {filename}"
        )));
    }
    if filename.contains("..") {
        return Err(TixError::InvalidInput(format!(
            "filename must not contain `..`: {filename}"
        )));
    }
    if filename.contains('\0') {
        return Err(TixError::InvalidInput(format!(
            "filename must not contain NUL: {filename}"
        )));
    }
    if filename.split('/').any(|component| component.is_empty()) {
        return Err(TixError::InvalidInput(format!(
            "filename path components must not be empty: {filename}"
        )));
    }
    Ok(())
}

/// Split a validated relative filename into `(segment, basename)`. Legacy
/// flat filenames have an empty segment (`("", "2026-05-10-x.md")`), grouped
/// ones carry exactly one segment (`("alice", "2026-05-10-x.md")`). [`None`]
/// for anything that survived a bad path shape.
/// The `number:` field of an issue file's frontmatter, without a full parse.
///
/// `Store::delete` needs the number of the issue it is removing so it can free that
/// number's claim, and it needs it *before* the file is gone. A full `Issue` parse
/// would be the obvious way, but this sits on the delete path and only needs one
/// scalar, so a scoped scan is enough — and it cannot fail on an issue that would
/// fail to load, which keeps `delete`'s existing "removes the file" contract
/// (#1352) independent of frontmatter validity.
///
/// The scan stops at the closing `---` so a `number:` in the **body** cannot be
/// mistaken for the field.
fn frontmatter_number(text: &str) -> Option<u32> {
    let mut lines = text.lines();
    // The opening delimiter. A file that does not start with one has no frontmatter.
    if lines.next()?.trim() != "---" {
        return None;
    }
    for line in lines {
        let line = line.trim_end();
        // The closing delimiter ends the frontmatter, so a `number:` after it is
        // body text and must not be mistaken for the field.
        if line == "---" {
            return None;
        }
        if let Some(rest) = line.strip_prefix("number:") {
            return rest.trim().parse().ok();
        }
    }
    None
}

/// The directory holding one marker per claimed number.
///
/// **A sibling of the issues directory, not a child of it.** `docs/issues/` is the
/// tool's source of truth: people hand-edit it, script against it, and glob it, and
/// its contents are committed. Adding an internal directory inside it changes what
/// every one of those consumers sees — a test helper that counts segments, a `for`
/// loop over `docs/issues/*`, a CI check — for machinery no reader should have to
/// know about. Beside it, `docs/issues/` contains exactly what it did before.
///
/// Derived from the configured `issues_dir` rather than hardcoded, so a repo that
/// points `issues_dir` somewhere else still gets a ledger beside that.
fn claims_dir(issues_dir: &Path) -> PathBuf {
    issues_dir
        .parent()
        .unwrap_or(issues_dir)
        .join(NumberClaim::DIR)
}

fn split_relative(filename: &str) -> Option<(String, String)> {
    let mut parts = filename.rsplitn(2, '/');
    let basename = parts.next()?;
    let segment = parts.next().unwrap_or("");
    Some((segment.to_string(), basename.to_string()))
}

/// Flip the archived marker on a store-relative issue filename.
///
/// `alice/2026-01-01-x.md` → `alice/.2026-01-01-x.md` when `archive` is true,
/// and the inverse when false. Only the basename's leading dot changes; the
/// segment stays put, so the file never moves between directories. `None` when
/// the name is already in the requested state.
fn flip_archived(filename: &str, archive: bool) -> Option<String> {
    let (segment, basename) = split_relative(filename)?;
    let flipped = if archive {
        if basename.starts_with('.') {
            return None;
        }
        format!(".{basename}")
    } else {
        basename.strip_prefix('.')?.to_string()
    };
    Some(if segment.is_empty() {
        flipped
    } else {
        format!("{segment}/{flipped}")
    })
}

/// The first free `<stem>.md` / `<stem>-1.md` / `<stem>-2.md` … name in
/// `dir` (deterministic existence probe). Never returns an existing name.
fn resolve_target_name(dir: &Path, stem: &str) -> String {
    let mut candidate = format!("{stem}.md");
    let mut i = 1u32;
    while dir.join(&candidate).exists() {
        candidate = format!("{stem}-{i}.md");
        i += 1;
    }
    candidate
}

/// The slug used for the asset dir: the issue filename stem minus any leading
/// date and id components.
///
/// New schema is `YYYY-MM-DD-<id>-<slug>` (`2026-09-13-A1B2C3D4-fix-login-bug` →
/// `fix-login-bug`); legacy is `YYYY-MM-DD-<slug>`; an earlier new-schema order
/// was `<id>-YYYY-MM-DD-<slug>`. All three are handled so the asset directory is
/// the same human slug regardless of which name a file carries. When neither
/// component is present the stem is used as-is.
fn slug_from_stem(stem: &str) -> String {
    let stem = strip_leading_id(stem);
    let stem = strip_date_prefix(stem);
    strip_leading_id(stem).to_string()
}

/// Strip a leading 8-character issue id and its separator, if present.
fn strip_leading_id(stem: &str) -> &str {
    match stem.split_once('-') {
        Some((head, rest)) if crate::id::is_issue_id(head) => rest,
        _ => stem,
    }
}

/// Strip a leading `YYYY-MM-DD-` date prefix, if present.
fn strip_date_prefix(stem: &str) -> &str {
    let bytes = stem.as_bytes();
    if stem.len() > 10 && bytes[4] == b'-' && bytes[7] == b'-' && bytes[10] == b'-' {
        &stem[11..]
    } else {
        stem
    }
}

/// The first free `<name>` / `<name>-<n>.<ext>` name for an asset in `dir`.
/// When `<name>` is taken the extension is kept and a deterministic
/// numeric suffix is appended (FR-006).
fn resolve_asset_name(dir: &Path, name: &str) -> String {
    if !dir.join(name).exists() {
        return name.to_string();
    }
    let (stem, ext) = match name.rsplit_once('.') {
        Some((s, e)) => (s, format!(".{e}")),
        None => (name, String::new()),
    };
    let mut i = 1u32;
    loop {
        let candidate = format!("{stem}-{i}{ext}");
        if !dir.join(&candidate).exists() {
            return candidate;
        }
        i += 1;
    }
}

/// The first free `<name>` / `<name>-1` / `<name>-2` … directory name in
/// `dir` (mirrors `resolve_target_name` for the `<slug>-assets/` move).
fn resolve_asset_dir_name(dir: &Path, name: &str) -> String {
    let mut candidate = name.to_string();
    let mut i = 1u32;
    while dir.join(&candidate).exists() {
        candidate = format!("{name}-{i}");
        i += 1;
    }
    candidate
}

/// Copy a file atomically into `dir` under `target` (temp + rename, NFR-004).
/// The temp file is cleaned up on failure and never left behind.
fn atomic_copy(dir: &Path, target: &Path, source: &Path) -> Result<()> {
    let pid = std::process::id();
    let nonce = nanos();
    let tmp = dir.join(format!(".tix-tmp-{pid}-{nonce}"));
    let copy_result = (|| -> std::io::Result<()> {
        std::fs::copy(source, &tmp)?;
        let f = std::fs::File::open(&tmp)?;
        f.sync_all()?;
        Ok(())
    })();
    if let Err(e) = copy_result {
        let _ = std::fs::remove_file(&tmp);
        return Err(TixError::Io(e));
    }
    if let Err(e) = std::fs::rename(&tmp, target) {
        let _ = std::fs::remove_file(&tmp);
        return Err(TixError::Io(e));
    }
    Ok(())
}

/// Whether an asset file name is an image by extension (the `![…]` link form).
fn is_image_name(name: &str) -> bool {
    matches!(
        name.rsplit('.')
            .next()
            .unwrap_or("")
            .to_ascii_lowercase()
            .as_str(),
        "png" | "jpg" | "jpeg" | "gif" | "svg" | "webp" | "bmp"
    )
}

/// `pub(crate)` because the mention store writes its own directory through the same primitive:
/// one atomic writer means one place that journals, fsyncs, and renames.
pub(crate) fn atomic_write(dir: &Path, target: &Path, data: &[u8]) -> Result<()> {
    write_file(dir, target, data, Link::Overwrite)
}

/// Write `data` to `target`, refusing to replace an existing file.
///
/// [`atomic_write`] uses `rename`, which replaces the target unconditionally and is
/// therefore the wrong tool for *creating* an issue: a name collision would destroy
/// the file already there. This writes the payload to a temp file, `fsync`s it, and
/// then creates `target` with `hard_link`, which is atomic and fails with
/// `AlreadyExists` if the name is taken. The temp file is removed either way.
///
/// A hard link is the portable way to get `O_EXCL`-style semantics on the final
/// path (it works on unix and Windows and needs no new dependency). The temp file
/// lives in the same directory, so it is always on the same filesystem and the link
/// cannot fail for that reason. If the link is refused for any other reason — a
/// filesystem without hard links, say — it falls back to `rename`, which keeps
/// atomicity but is no longer no-clobber, and the caller's own probe is the
/// remaining protection.
///
/// The directory `fsync` that follows the link is what makes the *name* durable, so
/// it is not skippable on the fallback path either.
fn write_file_new(dir: &Path, target: &Path, data: &[u8]) -> Result<()> {
    write_file(dir, target, data, Link::Exclusive)
}

#[derive(Clone, Copy)]
enum Link {
    Overwrite,
    Exclusive,
}

fn write_file(dir: &Path, target: &Path, data: &[u8], link: Link) -> Result<()> {
    // Every write goes through here, so this is the one place a transaction needs
    // to remember the target's pre-image. A no-op outside a transaction.
    journal_record_write(target);
    let pid = std::process::id();
    let nonce = nanos();
    let tmp = dir.join(format!(".tix-tmp-{pid}-{nonce}"));
    let write_result = (|| -> std::io::Result<()> {
        let mut f = std::fs::File::create(&tmp)?;
        use std::io::Write;
        f.write_all(data)?;
        f.sync_all()?;
        Ok(())
    })();
    if let Err(e) = write_result {
        let _ = std::fs::remove_file(&tmp);
        return Err(TixError::Io(e));
    }
    let link_result = match link {
        Link::Overwrite => std::fs::rename(&tmp, target),
        Link::Exclusive => match std::fs::hard_link(&tmp, target) {
            // The name was taken: the payload is already durable, so only the link
            // failed. `AlreadyExists` is the signal `write_new_issue_file` retries on,
            // so it is propagated rather than flattened into a generic I/O error.
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(e),
            // No hard links on this filesystem. Atomicity survives; the no-clobber
            // guarantee does not, and the caller's probe is what is left.
            Err(_) => std::fs::rename(&tmp, target),
            Ok(()) => {
                let _ = std::fs::remove_file(&tmp);
                Ok(())
            }
        },
    };
    if let Err(e) = link_result {
        let _ = std::fs::remove_file(&tmp);
        return Err(TixError::Io(e));
    }
    let _ = std::fs::File::open(dir).and_then(|f| f.sync_all());
    Ok(())
}

fn nanos() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests;