sirno 0.0.5

Sirno gives project design a semantic intermediate representation.
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
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
//! Request and result types for command callers.

use std::path::PathBuf;
use std::str::FromStr;

use clap::ValueEnum;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::surface::error::CommandError;
use crate::surface::output::{
    diagnostics_from_entry_report, display_path, display_paths, format_gen_link_report,
    format_query_json, query_result_records,
};
use crate::{
    CheckMode, EntryAddress, EntryAddressError, EntryAtom, EntryDirectoryReport,
    EntryStructuralMatcher, GenLinkDirectoryReport, StructuralEdgeSettings, Tide, TideStatus,
    TideWorkitem, UpstreamSettings, WitnessRecord,
};

/// Shared human-or-JSON output renderer.
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
pub enum StructuredOutputFormat {
    /// Print JSON for machine-oriented callers.
    Json,
    /// Print terminal-oriented human text.
    #[default]
    Human,
}

pub(crate) type QueryOutputFormat = StructuredOutputFormat;
pub(crate) type TideOutputFormat = StructuredOutputFormat;

/// Tide status detail selected by command callers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum TideStatusMode {
    /// Show only entry addresses that need review.
    #[default]
    Review,
    /// Show full open workitem statuses.
    Full,
    /// Show full open and resolved workitem statuses.
    All,
}

impl TideStatusMode {
    pub(crate) fn includes_workitems(self) -> bool {
        matches!(self, Self::Full | Self::All)
    }

    pub(crate) fn includes_resolved(self) -> bool {
        matches!(self, Self::All)
    }
}

/// Result of reading or changing the process current working directory.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CwdResult {
    /// Whether the current working directory was read successfully.
    pub ok: bool,
    /// Whether the command changed the current working directory before reading it.
    pub changed: bool,
    /// Current working directory after the command completed.
    pub path: String,
    /// Human-readable summary.
    pub message: String,
}

/// Result of checking canonical comments in `Sirno.toml`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ConfigCommentResult {
    /// Whether the config now has every canonical comment.
    pub ok: bool,
    /// Whether this run rewrote the config file.
    pub changed: bool,
    /// Checked config path.
    pub config_path: String,
    /// Canonical comment texts that were missing before any repair.
    pub missing_comments: Vec<String>,
    /// Human-readable summary.
    pub message: String,
}

/// Request to add or replace one upstream declaration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UpstreamAddRequest {
    /// Glacier domain.
    pub domain: EntryAtom,
    /// Upstream settings to write.
    pub settings: UpstreamSettings,
}

/// Request to crystallize or update glacier domains.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct UpstreamCrystallizeRequest {
    /// Selected glacier domains. Empty means every upstream.
    pub domains: Vec<EntryAtom>,
    /// Use only the existing lock state and cache.
    pub locked: bool,
}

/// Query output column list.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryColumns {
    pub(crate) columns: Vec<QueryColumn>,
}

impl QueryColumns {
    /// Build a column list from explicit query columns.
    pub fn new(columns: Vec<QueryColumn>) -> Self {
        Self { columns }
    }

    /// Return the selected columns in display order.
    pub fn columns(&self) -> &[QueryColumn] {
        &self.columns
    }

    /// Return stable output field labels in display order.
    pub fn labels(&self) -> Vec<String> {
        self.columns.iter().map(|column| column.label().to_owned()).collect()
    }

    /// Return selected structural field columns.
    pub(crate) fn structural_fields(&self) -> impl Iterator<Item = &str> {
        self.columns.iter().filter_map(QueryColumn::structural_field)
    }

    /// Build the default query output columns.
    pub fn default_output() -> Self {
        Self { columns: vec![QueryColumn::Id, QueryColumn::Name] }
    }
}

/// Query column mode requested by a caller.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum QueryColumnSelection {
    /// Select the standard query output columns.
    #[default]
    Default,
    /// Print selectable column names without selecting entries.
    Options,
    /// Select explicit output columns.
    Selected(QueryColumns),
}

impl FromStr for QueryColumns {
    type Err = QueryColumnsParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        if raw.trim().is_empty() {
            return Err(QueryColumnsParseError::Empty);
        }

        let mut columns = Vec::new();
        for raw_column in raw.split(',') {
            let column = raw_column.trim();
            if column.is_empty() {
                return Err(QueryColumnsParseError::EmptyColumn);
            }
            columns.push(column.parse()?);
        }

        Ok(Self { columns })
    }
}

/// One column printable by `sirno query`.
#[derive(Clone, Debug, PartialEq, Eq)]
// sirno:witness:query:begin
pub enum QueryColumn {
    /// Entry address.
    Id,
    /// Human-readable entry name.
    Name,
    /// Markdown path.
    Path,
    /// Short entry desc.
    Desc,
    /// Configured structural metadata field.
    Structural {
        /// Metadata field to read from each entry.
        field: String,
    },
}
// sirno:witness:query:end

impl FromStr for QueryColumn {
    type Err = QueryColumnsParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        match raw {
            | "id" => Ok(Self::Id),
            | "name" => Ok(Self::Name),
            | "path" => Ok(Self::Path),
            | "desc" => Ok(Self::Desc),
            | column => Ok(Self::Structural { field: column.to_owned() }),
        }
    }
}

impl QueryColumn {
    /// Return the stable output field name for this column.
    pub fn label(&self) -> &str {
        match self {
            | Self::Id => "id",
            | Self::Name => "name",
            | Self::Path => "path",
            | Self::Desc => "desc",
            | Self::Structural { field } => field,
        }
    }

    /// Return the structural field name when this column selects structural metadata.
    pub fn structural_field(&self) -> Option<&str> {
        match self {
            | Self::Structural { field } => Some(field),
            | Self::Id | Self::Name | Self::Path | Self::Desc => None,
        }
    }
}

/// One materialized query cell value.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
// sirno:witness:query:begin
pub enum QueryValue {
    /// Scalar entry field value.
    Text(String),
    /// Structural targets for one configured field.
    ///
    /// `None` means the field is absent.
    /// `Some([])` means the field is present and has no targets.
    Targets(Option<Vec<String>>),
}
// sirno:witness:query:end

impl QueryValue {
    /// Build a scalar query value.
    pub fn text(value: impl Into<String>) -> Self {
        Self::Text(value.into())
    }

    /// Build a structural target query value.
    pub fn targets(targets: Option<&[EntryAddress]>) -> Self {
        Self::Targets(
            targets.map(|targets| targets.iter().map(ToString::to_string).collect::<Vec<_>>()),
        )
    }

    /// Return the human table display string for this value.
    pub(crate) fn display(&self) -> String {
        match self {
            | Self::Text(value) => value.clone(),
            | Self::Targets(Some(targets)) => targets.join(", "),
            | Self::Targets(None) => String::new(),
        }
    }
}

impl From<String> for QueryValue {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

/// Error raised while parsing one `--columns` list.
#[derive(Debug, Error)]
pub enum QueryColumnsParseError {
    /// The list contains no columns.
    #[error("query columns must include at least one column")]
    Empty,
    /// The list contains a separator without a column.
    #[error("query columns contain an empty column")]
    EmptyColumn,
}

/// Structural query filter parsed from `FIELD=ENTRY_ADDRESS[,ENTRY_ADDRESS]`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StructuralFilter {
    /// Structural field name.
    pub field: String,
    /// Accepted target entry addresses for this field.
    pub targets: Vec<EntryAddress>,
}

impl FromStr for StructuralFilter {
    type Err = StructuralFilterParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        let Some((field, targets)) = raw.split_once('=') else {
            return Err(StructuralFilterParseError::MissingEquals);
        };
        let field = field.trim();
        if field.is_empty() {
            return Err(StructuralFilterParseError::EmptyField);
        }
        let targets = parse_structural_filter_targets(targets)?;
        Ok(Self { field: field.to_owned(), targets })
    }
}

fn parse_structural_filter_targets(
    raw: &str,
) -> Result<Vec<EntryAddress>, StructuralFilterParseError> {
    let mut targets = Vec::new();
    for raw_target in raw.split(',') {
        let target = raw_target.trim();
        if target.is_empty() {
            return Err(StructuralFilterParseError::EmptyTarget);
        }
        targets.push(EntryAddress::new(target)?);
    }
    Ok(targets)
}

/// Error raised while parsing one structural query filter.
#[derive(Debug, Error)]
pub enum StructuralFilterParseError {
    /// The argument does not contain the field-target separator.
    #[error("expected FIELD=ENTRY_ADDRESS[,ENTRY_ADDRESS]")]
    MissingEquals,
    /// The structural field name is empty.
    #[error("structural field name must not be empty")]
    EmptyField,
    /// The target entry address list contains a separator without a target.
    #[error("structural filter contains an empty target")]
    EmptyTarget,
    /// A target entry address is invalid.
    #[error(transparent)]
    EntryAddress(#[from] EntryAddressError),
}

/// Structural query state filter parsed from `FIELD=STATE`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StructuralStateFilter {
    /// Structural field name.
    pub field: String,
    /// Accepted state for this field.
    pub state: StructuralFieldState,
}

impl FromStr for StructuralStateFilter {
    type Err = StructuralStateFilterParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        let Some((field, state)) = raw.split_once('=') else {
            return Err(StructuralStateFilterParseError::MissingEquals);
        };
        let field = field.trim();
        if field.is_empty() {
            return Err(StructuralStateFilterParseError::EmptyField);
        }
        Ok(Self { field: field.to_owned(), state: state.trim().parse()? })
    }
}

/// Structural field state matched by `sirno query --is`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StructuralFieldState {
    /// The field is present with any target count.
    Present,
    /// The field is present with no targets.
    Empty,
    /// The field is absent.
    Missing,
}

impl FromStr for StructuralFieldState {
    type Err = StructuralStateFilterParseError;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        match raw {
            | "present" => Ok(Self::Present),
            | "empty" => Ok(Self::Empty),
            | "missing" => Ok(Self::Missing),
            | state => Err(StructuralStateFilterParseError::UnknownState(state.to_owned())),
        }
    }
}

impl From<StructuralFieldState> for EntryStructuralMatcher {
    fn from(value: StructuralFieldState) -> Self {
        match value {
            | StructuralFieldState::Present => Self::Present,
            | StructuralFieldState::Empty => Self::Empty,
            | StructuralFieldState::Missing => Self::Missing,
        }
    }
}

/// Error raised while parsing one structural query state filter.
#[derive(Debug, Error)]
pub enum StructuralStateFilterParseError {
    /// The argument does not contain the field-state separator.
    #[error("expected FIELD=present, FIELD=empty, or FIELD=missing")]
    MissingEquals,
    /// The structural field name is empty.
    #[error("structural field name must not be empty")]
    EmptyField,
    /// The structural field state is not recognized.
    #[error("unknown structural field state `{0}`; expected present, empty, or missing")]
    UnknownState(String),
}

/// Entry query request shared by CLI and tool callers.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct QueryRequest {
    /// Vague text terms matched against expanded entry text.
    pub terms: Vec<String>,
    /// Exact text terms matched against entry-local text.
    pub exact_terms: Vec<String>,
    /// Structural target filters.
    pub has: Vec<StructuralFilter>,
    /// Structural field state filters.
    pub is: Vec<StructuralStateFilter>,
    /// Output columns to materialize.
    pub columns: QueryColumnSelection,
}

/// Query execution result before presentation rendering.
#[derive(Debug)]
pub enum QueryRun {
    /// The caller requested selectable column names without selecting entries.
    ColumnOptions(QueryColumns),
    /// The lake did not pass the edit-mode checks needed for query.
    InvalidLake {
        /// Columns selected for the attempted query.
        columns: QueryColumns,
        /// Lake report that blocked query execution.
        report: EntryDirectoryReport,
    },
    /// The query completed and produced rows.
    Results(QueryResults),
}

/// Structured query rows plus the selected column order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryResults {
    pub(crate) columns: QueryColumns,
    pub(crate) rows: Vec<Vec<QueryValue>>,
}

impl QueryResults {
    /// Build query results from selected columns and materialized rows.
    pub fn new(columns: QueryColumns, rows: Vec<Vec<QueryValue>>) -> Self {
        Self { columns, rows }
    }

    /// Return selected columns in display order.
    pub fn columns(&self) -> &QueryColumns {
        &self.columns
    }

    /// Return raw row values in selected column order.
    pub fn rows(&self) -> &[Vec<QueryValue>] {
        &self.rows
    }

    /// Return JSON-ready records keyed by selected column labels.
    pub fn records(&self) -> Vec<IndexMap<String, QueryValue>> {
        query_result_records(&self.columns, &self.rows)
    }

    /// Render the result rows as pretty JSON.
    pub fn to_json(&self) -> Result<String, CommandError> {
        format_query_json(&self.columns, &self.rows)
    }
}

/// Entry address lookup request shared by CLI and tool callers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EntryPathsRequest {
    /// Entry address whose paths should be returned.
    pub id: EntryAddress,
    /// Selected path classes.
    pub selection: PathSelection,
    /// Whether returned paths should be absolute.
    pub absolute: bool,
}

impl EntryPathsRequest {
    /// Build a path lookup request from explicit typed fields.
    pub fn new(id: EntryAddress, selection: PathSelection, absolute: bool) -> Self {
        Self { id, selection, absolute }
    }
}

/// Lake initialization request shared by non-CLI front ends.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LakeInitRequest {
    /// Sirno Lake path written to `Sirno.toml`.
    pub lake: Option<PathBuf>,
}

/// Result of creating a Sirno Lake.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LakeInitResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Config file that was written.
    pub config_path: String,
    /// Sirno Lake directory that was initialized.
    pub lake_path: String,
    /// Number of seed entries written.
    pub entry_count: usize,
    /// Concise human-readable summary.
    pub message: String,
}

/// Structural metadata target for typed command callers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StructuralTarget {
    /// Structural field name.
    pub field: String,
    /// Target entry address.
    pub target: EntryAddress,
}

/// Entry creation request shared by the CLI and tool callers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntryNewRequest {
    /// Entry address.
    pub id: EntryAddress,
    /// Human-readable entry name.
    pub name: Option<String>,
    /// Short entry description.
    pub desc: String,
    /// Structural metadata targets.
    #[serde(default)]
    pub structural: Vec<StructuralTarget>,
    /// Initial Markdown body.
    pub body: Option<String>,
}

/// Result that points at one entry file.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntryFileResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Entry address affected by the command.
    pub id: String,
    /// Sirno Lake entry file path affected by the command.
    pub path: String,
    /// Concise human-readable summary.
    pub message: String,
}

/// Result of clearing or repairing local filesystem protection.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LocalProtectionResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Whether this run only reported selected paths.
    pub dry_run: bool,
    /// Sirno Lake directory inspected by the command.
    pub lake_path: String,
    /// Paths selected by the local protection operation.
    pub paths: Vec<String>,
    /// Concise human-readable summary.
    pub message: String,
}

/// Result of reading one Sirno Lake Markdown entry.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntryReadResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Entry address that was read.
    pub id: String,
    /// Sirno Lake entry file path.
    pub path: String,
    /// Human-readable entry name.
    pub name: String,
    /// Short entry description.
    pub desc: String,
    /// Markdown body outside the metadata block.
    pub body: String,
    /// Full Markdown source as stored on disk.
    pub source: String,
    /// Concise human-readable summary.
    pub message: String,
}

/// Result of renaming one entry address.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntryRenameResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Entry address before the rename.
    pub old_id: String,
    /// Entry address after the rename.
    pub new_id: String,
    /// Paths updated by the rename.
    pub updated_paths: Vec<String>,
    /// Concise human-readable summary.
    pub message: String,
}

/// Query result designed for JSON-first callers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueryResponse {
    /// Whether the request completed against a clean-enough lake.
    pub ok: bool,
    /// Available or selected output columns.
    pub columns: Vec<String>,
    /// Query records keyed by column label.
    pub records: Vec<IndexMap<String, QueryValue>>,
    /// Diagnostics when the lake prevents query execution.
    pub diagnostics: Vec<DiagnosticRecord>,
}

/// Ripgrep request shared by typed callers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RgRequest {
    /// Include Sirno-owned generated-footer regions in the search.
    #[serde(default)]
    pub with_generated_footer: bool,
    /// Arguments forwarded to ripgrep before the lake path.
    pub args: Vec<String>,
}

/// Captured ripgrep result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RgResult {
    /// Whether ripgrep exited successfully.
    pub ok: bool,
    /// Process exit code, or 1 when no ordinary code is available.
    pub exit_code: u8,
    /// Captured standard output.
    pub stdout: String,
    /// Captured standard error.
    pub stderr: String,
}

/// One JSON-ready source span.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WitnessSpanResult {
    /// One-based starting line.
    pub start_line: usize,
    /// One-based starting column.
    pub start_column: usize,
    /// One-based ending line.
    pub end_line: usize,
    /// One-based column after the span.
    pub end_column: usize,
}

// sirno:witness:mcp-interface:begin
/// One JSON-ready witness record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum WitnessRecordResult {
    /// Compact MCP witness record for ordinary agent use.
    Compact(CompactWitnessRecordResult),
    /// Verbose MCP witness record for callers that need structured coordinates.
    Verbose(VerboseWitnessRecordResult),
}

/// Compact JSON-ready witness record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CompactWitnessRecordResult {
    /// Entry address captured by the witness block.
    pub entry: String,
    /// Repository location of the matched witness block.
    pub location: String,
    /// Full matched witness block body.
    pub body: String,
}

/// Verbose JSON-ready witness record.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerboseWitnessRecordResult {
    /// Entry address captured by the witness block.
    pub entry: String,
    /// Repository file path containing the witness.
    pub path: String,
    /// Full matched block region.
    pub region: WitnessSpanResult,
    /// Full matched witness block body.
    pub body: String,
}

impl WitnessRecordResult {
    pub(crate) fn from_record(record: &WitnessRecord, verbose_json: bool) -> Self {
        if verbose_json {
            return Self::Verbose(VerboseWitnessRecordResult {
                entry: record.entry.to_string(),
                path: display_path(&record.path),
                region: WitnessSpanResult::from(record.region),
                body: record.body.clone(),
            });
        }

        Self::Compact(CompactWitnessRecordResult {
            entry: record.entry.to_string(),
            location: format_witness_location(record),
            body: record.body.clone(),
        })
    }
}

fn format_witness_location(record: &WitnessRecord) -> String {
    format!(
        "{}:{}:{}-{}:{}",
        display_path(&record.path),
        record.region.start_line,
        record.region.start_column,
        record.region.end_line,
        record.region.end_column
    )
}
// sirno:witness:mcp-interface:end

impl From<crate::witness::WitnessSpan> for WitnessSpanResult {
    fn from(value: crate::witness::WitnessSpan) -> Self {
        Self {
            start_line: value.start_line,
            start_column: value.start_column,
            end_line: value.end_line,
            end_column: value.end_column,
        }
    }
}

/// Repository witness lookup result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WitnessResult {
    /// Whether any witness block was found.
    pub ok: bool,
    /// Entry address used for lookup.
    pub id: String,
    /// Matching witness records.
    pub records: Vec<WitnessRecordResult>,
    /// Concise human-readable summary.
    pub message: String,
}

/// Artifact listing result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactListResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Entry address whose artifacts were listed.
    pub id: String,
    /// Owner-relative artifact paths.
    pub artifacts: Vec<String>,
}

/// Artifact add request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactAddRequest {
    /// Entry address that will own the artifact.
    pub id: EntryAddress,
    /// Source file to copy.
    pub source: PathBuf,
    /// Owner-relative artifact path.
    pub artifact_path: Option<PathBuf>,
}

/// Artifact rename request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactRenameRequest {
    /// Entry address that owns the artifact.
    pub id: EntryAddress,
    /// Existing owner-relative artifact path.
    pub old_path: PathBuf,
    /// New owner-relative artifact path.
    pub new_path: PathBuf,
}

/// Artifact removal request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactRemoveRequest {
    /// Entry address that owns the artifact.
    pub id: EntryAddress,
    /// Owner-relative artifact path to remove.
    pub artifact_path: PathBuf,
}

/// Result of changing one artifact file.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactChangeResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Entry address that owns the artifact.
    pub id: String,
    /// Owner-relative artifact path.
    pub artifact_path: String,
    /// Filesystem path affected by the command.
    pub path: String,
    /// Concise human-readable summary.
    pub message: String,
}

/// One discovered Sirno skill wrapper, package target, or adjacent skill link.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillWrapperRecord {
    /// Discipline entry that owns the wrapper artifact.
    pub entry_id: String,
    /// Installed skill package name.
    pub name: String,
    /// Lake-owned wrapper artifact path or link source path.
    pub wrapper_path: String,
    /// Lake-owned full resource artifact path.
    pub full_path: String,
    /// Repository-relative package or link target path.
    pub target_path: String,
    /// Stable command status label.
    pub status: String,
    /// Whether the package target differs or was rewritten.
    pub changed: bool,
}

/// Result of listing, checking, or installing Sirno skill wrappers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SkillWrapperResult {
    /// Whether every wrapper package matched the requested state.
    pub ok: bool,
    /// Discovered wrapper records.
    pub records: Vec<SkillWrapperRecord>,
    /// Concise human-readable summary.
    pub message: String,
}

/// Result of moving a configured repository path.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MovePathResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Whether the filesystem path actually moved.
    pub moved: bool,
    /// Previous configured path.
    pub old_path: String,
    /// New configured path.
    pub new_path: String,
    /// Concise human-readable summary.
    pub message: String,
}

/// One JSON-ready diagnostic.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiagnosticRecord {
    /// Diagnostic severity.
    pub severity: String,
    /// Optional path responsible for the diagnostic.
    pub path: Option<String>,
    /// Human-readable diagnostic message.
    pub message: String,
}

/// JSON-ready lake check result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LakeCheckResult {
    /// Whether the selected check mode produced no errors.
    pub ok: bool,
    /// Lake root that was checked.
    pub root: String,
    /// Whether at least one error was reported.
    pub has_errors: bool,
    /// Diagnostics reported by the check.
    pub diagnostics: Vec<DiagnosticRecord>,
}

impl LakeCheckResult {
    pub(crate) fn from_report(report: &EntryDirectoryReport) -> Self {
        let has_errors = report.has_errors();
        Self {
            ok: !has_errors,
            root: display_path(report.root()),
            has_errors,
            diagnostics: diagnostics_from_entry_report(report),
        }
    }
}

/// JSON-ready rendered-footer result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RenderResult {
    /// Whether rendering or dry-checking completed without blocking diagnostics.
    pub ok: bool,
    /// Whether the render operation only checked for changes.
    pub dry: bool,
    /// Lake root that was processed.
    pub root: String,
    /// Number of entries processed.
    pub entry_count: usize,
    /// Entry files whose generated-link region changed.
    pub changed_paths: Vec<String>,
    /// Diagnostics that blocked rendering.
    pub diagnostics: Vec<DiagnosticRecord>,
    /// Concise human-readable summary.
    pub message: String,
}

impl RenderResult {
    pub(crate) fn from_report(report: &GenLinkDirectoryReport, dry: bool) -> Self {
        let changed_paths = display_paths(report.changed_paths());
        Self {
            ok: true,
            dry,
            root: display_path(report.root()),
            entry_count: report.entry_count(),
            changed_paths,
            diagnostics: Vec::new(),
            message: format_gen_link_report(
                report.root(),
                report.entry_count(),
                report.changed_paths(),
            ),
        }
    }

    pub(crate) fn blocked(report: &EntryDirectoryReport) -> Self {
        Self {
            ok: false,
            dry: false,
            root: display_path(report.root()),
            entry_count: report.entries().len(),
            changed_paths: Vec::new(),
            diagnostics: diagnostics_from_entry_report(report),
            message: format!("render blocked by check errors in {}", report.root().display()),
        }
    }
}

/// Structured edge policy for one structural field direction.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StructuralEdgeStatus {
    /// Whether generated footers render this edge direction.
    pub render: bool,
    /// Whether lake-side neighbors create tide workitems.
    pub ripple_lake: bool,
    /// Whether frost-side neighbors create tide workitems.
    pub ripple_frost: bool,
}

impl StructuralEdgeStatus {
    pub(crate) fn from_settings(settings: &StructuralEdgeSettings) -> Self {
        Self {
            render: settings.render,
            ripple_lake: settings.ripple.lake,
            ripple_frost: settings.ripple.frost,
        }
    }
}

/// Structural field status in one Sirno config.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StructuralFieldStatus {
    /// Structural field name.
    pub field: String,
    /// Outgoing edge settings.
    pub to: StructuralEdgeStatus,
    /// Incoming edge settings.
    pub from: StructuralEdgeStatus,
    /// Shared-target edge settings.
    pub clique: StructuralEdgeStatus,
}

/// Current lock state of a configured Frost store.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StatusFrostState {
    /// No Sirno lock exists for the configured Frost path.
    Unlocked,
    /// The public lake is the current editable Frost version.
    Current,
    /// The public lake materializes a selected Frost version.
    CheckedOut,
}

/// Typed Frost status for the current project.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusFrost {
    /// Configured Frost path.
    pub path: String,
    /// Current public-lake state relative to Frost.
    pub state: StatusFrostState,
    /// Frost version when a lock names one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<u64>,
    /// Frost generation when a lock names one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generation: Option<u64>,
    /// Whether the public lake is writable as a Frost checkout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mutable: Option<bool>,
}

/// Check policy used by project status.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusCheckPolicy {
    /// Check boundary used for status.
    pub mode: CheckMode,
    /// Whether generated-footer freshness is checked.
    pub render: bool,
}

/// Compact Tide summary for project status.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusTide {
    /// Whether no open tide workitem remains.
    pub clear: bool,
    /// Number of open workitems.
    pub open_workitems: usize,
    /// Number of waves with at least one open workitem.
    pub open_waves: usize,
    /// Number of entries that still need review.
    pub review_entries: usize,
}

impl StatusTide {
    pub(crate) fn from_tide(tide: &Tide) -> Self {
        let open_statuses = tide.open_statuses().collect::<Vec<_>>();
        let open_waves = open_statuses
            .iter()
            .map(|status| &status.workitem.ripple)
            .collect::<std::collections::BTreeSet<_>>()
            .len();
        Self {
            clear: open_statuses.is_empty(),
            open_workitems: open_statuses.len(),
            open_waves,
            review_entries: tide.review_entries().len(),
        }
    }
}

/// Commit readiness for the configured project.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StatusCommitState {
    /// A Frost commit can proceed.
    Ready,
    /// A Frost commit is blocked by one or more project states.
    Blocked,
    /// Frost commits are unavailable because Frost is not configured.
    Unavailable,
}

/// Specific project state that blocks a Frost commit.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StatusCommitBlocker {
    /// Review-mode lake checks currently report errors.
    LakeCheck,
    /// The active Tide has open workitems.
    Tide,
    /// The public lake is an immutable Frost checkout.
    ImmutableCheckout,
}

/// Commit readiness summary for project status.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusCommit {
    /// Whether a Frost commit can proceed.
    pub ready: bool,
    /// Human-independent readiness state.
    pub state: StatusCommitState,
    /// States that block a commit.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub blockers: Vec<StatusCommitBlocker>,
}

/// JSON-ready project status.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusResult {
    /// Whether the configured project has no status blockers.
    pub ok: bool,
    /// Config file used for the status command.
    pub config_path: String,
    /// Lake path.
    pub lake_path: String,
    /// Number of parsed entries.
    pub entry_count: usize,
    /// Optional typed Frost status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frost: Option<StatusFrost>,
    /// Status check policy.
    pub check_policy: StatusCheckPolicy,
    /// Configured structural field summaries.
    pub structural_fields: Vec<StructuralFieldStatus>,
    /// Tide summary when Frost is configured and the lake can be compared.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tide: Option<StatusTide>,
    /// Frost commit readiness.
    pub commit: StatusCommit,
    /// Review-mode check result.
    pub check: LakeCheckResult,
}

/// Result of initializing frost.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrostInitResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Configured frost path.
    pub frost_path: String,
    /// Current frost version after initialization.
    pub version: u64,
    /// Concise human-readable summary.
    pub message: String,
}

/// Result of committing a frost snapshot.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrostCommitResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// New frost version.
    pub version: u64,
    /// Lake path committed to frost.
    pub lake_path: String,
    /// Concise human-readable summary.
    pub message: String,
}

/// Result of garbage-collecting frost storage.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrostGcResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Configured frost path.
    pub frost_path: String,
    /// GC generation before collection.
    pub before_generation: u64,
    /// Frost version before collection.
    pub before_version: u64,
    /// GC generation after collection.
    pub after_generation: u64,
    /// Frost version after collection.
    pub after_version: u64,
    /// Artifact byte files removed from frost storage.
    pub artifact_files_removed: usize,
    /// Empty artifact directories removed from frost storage.
    pub artifact_directories_removed: usize,
    /// Whether storage was physically collected.
    pub collected: bool,
    /// Concise human-readable summary.
    pub message: String,
}

/// Frost checkout request.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrostCheckoutRequest {
    /// Explicit frost version to check out.
    pub version: Option<u64>,
    /// Check out the latest frost version as mutable current lake.
    #[serde(default)]
    pub latest: bool,
    /// Leave an explicit version checkout writable.
    #[serde(default)]
    pub unsafe_mutable: bool,
}

/// Result of checking out a frost snapshot.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrostCheckoutResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Checked-out frost version.
    pub version: u64,
    /// Lake path written by checkout.
    pub lake_path: String,
    /// Number of entries written.
    pub entry_count: usize,
    /// Mutable or immutable lake state after checkout.
    pub state: String,
    /// Concise human-readable summary.
    pub message: String,
}

/// Tide workitem selection by exact workitems or neighbor ids.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TideSelectionRequest {
    /// Select all workitems whose neighbor matches one of these entry addresses.
    #[serde(default)]
    pub neighbors: Vec<EntryAddress>,
    /// Select exact workitem objects.
    #[serde(default)]
    pub workitems: Vec<TideWorkitem>,
}

/// Tide resolution request.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TideResolveRequest {
    /// Resolve workitems whose neighbor appears in the current ripple set.
    #[serde(default)]
    pub infer: bool,
    /// Select all workitems whose neighbor matches one of these entry addresses.
    #[serde(default)]
    pub neighbors: Vec<EntryAddress>,
    /// Select exact workitem objects.
    #[serde(default)]
    pub workitems: Vec<TideWorkitem>,
}

/// Result of changing tide resolutions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TideChangeResult {
    /// Whether the command completed successfully.
    pub ok: bool,
    /// Number of workitems changed.
    pub count: usize,
    /// Concise human-readable summary.
    pub message: String,
}

/// JSON-ready tide status result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct TideStatusResult {
    /// Whether no entry still needs review.
    pub ok: bool,
    /// Entry addresses that still need review.
    pub review_entries: Vec<EntryAddress>,
    /// Full workitem statuses when requested.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub statuses: Vec<TideStatus>,
}

/// Selected path classes for an entry address lookup.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PathSelection {
    pub(crate) entry: bool,
    pub(crate) artifact: bool,
    pub(crate) frost: bool,
}

impl PathSelection {
    /// Select entry, artifact, and frost paths.
    pub fn all() -> Self {
        Self { entry: true, artifact: true, frost: true }
    }

    /// Build an explicit path-class selection.
    pub fn new(entry: bool, artifact: bool, frost: bool) -> Self {
        Self { entry, artifact, frost }
    }
}

/// One filesystem path returned by an entry address lookup.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct PathRecord {
    /// Path class.
    pub kind: &'static str,
    /// Display-ready filesystem path.
    pub path: String,
}

impl PathRecord {
    pub(crate) fn new(kind: &'static str, path: PathBuf) -> Self {
        Self { kind, path: path.display().to_string() }
    }
}