govctl 0.7.6

Project governance CLI for RFC, ADR, and Work Item management
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
//! Path-based nested field addressing per [[ADR-0029]].
//!
//! Parses field paths like `alt[0].pros[1]` into structured segments
//! for nested access into ADR alternatives, work item journal entries, etc.

use super::rules as edit_rules;
use crate::diagnostic::{Diagnostic, DiagnosticCode};
use winnow::Parser;
use winnow::ascii::digit1;
use winnow::combinator::{delimited, eof, opt, separated, terminated};
use winnow::error::{ContextError, ErrMode};
use winnow::token::{any, take_while};

type ParseErr = ErrMode<ContextError>;

#[derive(Debug, Clone, PartialEq, Eq)]
struct RawPathSegment {
    name: String,
    index: Option<String>,
}

/// A single segment in a field path (e.g., `alt[0]` → name="alternatives", index=Some(0)).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathSegment {
    pub name: String,
    pub index: Option<i32>,
}

/// A parsed field path with one or more segments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldPath {
    pub segments: Vec<PathSegment>,
}

impl FieldPath {
    /// True if this is a single segment with no index (flat field like "title").
    pub fn is_simple(&self) -> bool {
        self.segments.len() == 1 && self.segments[0].index.is_none()
    }

    /// Get the flat field name if this is a simple path.
    pub fn as_simple(&self) -> Option<&str> {
        if self.is_simple() {
            Some(&self.segments[0].name)
        } else {
            None
        }
    }

    /// True if the last segment has an explicit index.
    pub fn has_terminal_index(&self) -> bool {
        self.segments.last().is_some_and(|s| s.index.is_some())
    }

    /// Normalize aliases on each path segment (`alt` -> `alternatives`, etc.).
    pub fn normalize_aliases(mut self) -> Self {
        for seg in &mut self.segments {
            seg.name = normalize_segment_name(&seg.name);
        }
        self
    }

    /// Collapse legacy two-segment prefixes into their canonical single-segment form.
    ///
    /// `content.decision` → `decision`, `govctl.status` → `status`, etc.
    pub fn collapse_legacy_prefixes(mut self) -> Self {
        if self.segments.len() == 2 && self.segments[0].index.is_none() {
            let prefix = self.segments[0].name.as_str();
            let field = self.segments[1].name.as_str();
            if edit_rules::can_collapse_legacy_prefix(prefix, field) {
                self.segments.remove(0);
            }
        }
        self
    }
}

impl std::fmt::Display for FieldPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, seg) in self.segments.iter().enumerate() {
            if i > 0 {
                f.write_str(".")?;
            }
            f.write_str(&seg.name)?;
            if let Some(idx) = seg.index {
                write!(f, "[{idx}]")?;
            }
        }
        Ok(())
    }
}

/// Normalize a single field name, expanding aliases to canonical form.
fn normalize_segment_name(name: &str) -> String {
    edit_rules::normalize_alias(name).to_string()
}

/// Parse a field path string into a `FieldPath`.
///
/// Grammar: `segment ('.' segment | '[' index ']')*`
/// where `segment` is `[a-z_][a-z0-9_]*` and `index` is `-?[0-9]+`.
#[allow(dead_code)]
pub fn parse_field_path(input: &str) -> anyhow::Result<FieldPath> {
    parse_raw_field_path(input).map(FieldPath::normalize_aliases)
}

/// Parse a field path string into raw segments, without alias normalization.
pub fn parse_raw_field_path(input: &str) -> anyhow::Result<FieldPath> {
    if input.is_empty() {
        return Err(Diagnostic::new(
            DiagnosticCode::E0814InvalidPath,
            "Field path cannot be empty",
            "path",
        )
        .into());
    }

    let raw_segments = terminated(path_segments_parser, eof)
        .parse(input)
        .map_err(|_| {
            Diagnostic::new(
                DiagnosticCode::E0814InvalidPath,
                format!("Invalid field path: {input}"),
                "path",
            )
        })?;

    let mut segments = Vec::with_capacity(raw_segments.len());
    for raw in raw_segments {
        let index = match raw.index {
            Some(text) => Some(text.parse::<i32>().map_err(|_| {
                Diagnostic::new(
                    DiagnosticCode::E0814InvalidPath,
                    format!("Invalid field path: invalid index '{text}'"),
                    "path",
                )
            })?),
            None => None,
        };
        segments.push(PathSegment {
            name: raw.name,
            index,
        });
    }

    Ok(FieldPath { segments })
}

fn path_segments_parser(input: &mut &str) -> Result<Vec<RawPathSegment>, ParseErr> {
    separated(1.., parse_segment_raw, '.').parse_next(input)
}

fn parse_segment_raw(input: &mut &str) -> Result<RawPathSegment, ParseErr> {
    let name = parse_name_raw(input)?;
    let index = opt(parse_index_text).parse_next(input)?;
    Ok(RawPathSegment { name, index })
}

fn parse_name_raw(rest: &mut &str) -> Result<String, ParseErr> {
    let first = any.verify(|c: &char| is_name_start(*c)).parse_next(rest)?;
    let suffix: &str = take_while(0.., is_name_char).parse_next(rest)?;
    Ok(format!("{first}{suffix}"))
}

fn parse_index_text(rest: &mut &str) -> Result<String, ParseErr> {
    let (sign, digits): (Option<char>, &str) =
        delimited('[', (opt('-'), digit1), ']').parse_next(rest)?;

    let mut idx = String::new();
    if sign.is_some() {
        idx.push('-');
    }
    idx.push_str(digits);
    Ok(idx)
}

fn is_name_start(c: char) -> bool {
    c.is_ascii_lowercase() || c == '_'
}

fn is_name_char(c: char) -> bool {
    c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'
}

/// Resolve an index (0-based, negative from end) against an array length.
pub fn resolve_index(idx: i32, len: usize) -> anyhow::Result<usize> {
    let len_i = len as i32;
    let actual = if idx < 0 { len_i + idx } else { idx };
    if actual < 0 || actual >= len_i {
        return Err(Diagnostic::new(
            DiagnosticCode::E0816PathIndexOutOfBounds,
            format!("Index {idx} out of range (array has {len} items)"),
            "path",
        )
        .into());
    }
    Ok(actual as usize)
}

/// Require that a segment has an index, resolve it against a length.
pub fn require_index(seg: &PathSegment, len: usize) -> anyhow::Result<usize> {
    let idx = seg.index.ok_or_else(|| {
        Diagnostic::new(
            DiagnosticCode::E0816PathIndexOutOfBounds,
            format!(
                "Field '{}' requires an index (e.g., {}[0])",
                seg.name, seg.name
            ),
            "path",
        )
    })?;
    resolve_index(idx, len)
}

#[cfg(test)]
mod tests {
    use super::*;

    // =========================================================================
    // parse_field_path — happy paths
    // =========================================================================

    #[test]
    fn test_simple_field() {
        let p = parse_field_path("title").unwrap();
        assert_eq!(p.segments.len(), 1);
        assert_eq!(p.segments[0].name, "title");
        assert_eq!(p.segments[0].index, None);
        assert!(p.is_simple());
        assert_eq!(p.as_simple(), Some("title"));
    }

    #[test]
    fn test_indexed_field() {
        let p = parse_field_path("alternatives[0]").unwrap();
        assert_eq!(p.segments.len(), 1);
        assert_eq!(p.segments[0].name, "alternatives");
        assert_eq!(p.segments[0].index, Some(0));
        assert!(!p.is_simple());
        assert!(p.has_terminal_index());
    }

    #[test]
    fn test_dotted_path() {
        let p = parse_field_path("alt[0].pros").unwrap();
        assert_eq!(p.segments.len(), 2);
        assert_eq!(p.segments[0].name, "alternatives");
        assert_eq!(p.segments[0].index, Some(0));
        assert_eq!(p.segments[1].name, "pros");
        assert_eq!(p.segments[1].index, None);
        assert!(!p.is_simple());
        assert!(!p.has_terminal_index());
    }

    #[test]
    fn test_dotted_path_with_terminal_index() {
        let p = parse_field_path("alt[0].pros[1]").unwrap();
        assert_eq!(p.segments.len(), 2);
        assert_eq!(p.segments[0].name, "alternatives");
        assert_eq!(p.segments[0].index, Some(0));
        assert_eq!(p.segments[1].name, "pros");
        assert_eq!(p.segments[1].index, Some(1));
        assert!(p.has_terminal_index());
    }

    #[test]
    fn test_negative_index() {
        let p = parse_field_path("alt[-1]").unwrap();
        assert_eq!(p.segments[0].index, Some(-1));
    }

    // =========================================================================
    // Alias expansion
    // =========================================================================

    #[test]
    fn test_alias_alt() {
        let p = parse_field_path("alt[0]").unwrap();
        assert_eq!(p.segments[0].name, "alternatives");
    }

    #[test]
    fn test_raw_parse_keeps_alias_token() {
        let p = parse_raw_field_path("alt[0]").unwrap();
        assert_eq!(p.segments[0].name, "alt");
    }

    #[test]
    fn test_alias_ac() {
        let p = parse_field_path("ac[0]").unwrap();
        assert_eq!(p.segments[0].name, "acceptance_criteria");
    }

    #[test]
    fn test_alias_pro_con() {
        let p = parse_field_path("alt[0].pro[0]").unwrap();
        assert_eq!(p.segments[1].name, "pros");
        let p = parse_field_path("alt[0].con[0]").unwrap();
        assert_eq!(p.segments[1].name, "cons");
    }

    #[test]
    fn test_alias_reason() {
        let p = parse_field_path("alt[0].reason").unwrap();
        assert_eq!(p.segments[1].name, "rejection_reason");
    }

    #[test]
    fn test_alias_desc() {
        let p = parse_field_path("desc").unwrap();
        assert_eq!(p.segments[0].name, "description");
    }

    // =========================================================================
    // Legacy prefix collapse
    // =========================================================================

    #[test]
    fn test_collapse_content_decision() {
        let p = parse_field_path("content.decision")
            .unwrap()
            .collapse_legacy_prefixes();
        assert!(p.is_simple());
        assert_eq!(p.as_simple(), Some("decision"));
    }

    #[test]
    fn test_collapse_govctl_status() {
        let p = parse_field_path("govctl.status")
            .unwrap()
            .collapse_legacy_prefixes();
        assert!(p.is_simple());
        assert_eq!(p.as_simple(), Some("status"));
    }

    #[test]
    fn test_no_collapse_when_indexed() {
        // content[0].decision should NOT collapse — content has index
        let p = parse_field_path("content[0].decision")
            .unwrap()
            .collapse_legacy_prefixes();
        assert_eq!(p.segments.len(), 2);
    }

    #[test]
    fn test_no_collapse_non_legacy_prefix() {
        let p = parse_field_path("alt[0].pros")
            .unwrap()
            .collapse_legacy_prefixes();
        assert_eq!(p.segments.len(), 2);
    }

    #[test]
    fn test_no_collapse_unknown_legacy_field() {
        let p = parse_field_path("content.unknown")
            .unwrap()
            .collapse_legacy_prefixes();
        assert_eq!(p.segments.len(), 2);
        assert_eq!(p.segments[0].name, "content");
    }

    // =========================================================================
    // Error cases
    // =========================================================================

    #[test]
    fn test_empty_path() {
        assert!(parse_field_path("").is_err());
    }

    #[test]
    fn test_invalid_start_char() {
        assert!(parse_field_path("0invalid").is_err());
        assert!(parse_field_path("[0]").is_err());
        assert!(parse_field_path("Alt").is_err());
    }

    #[test]
    fn test_double_index() {
        assert!(parse_field_path("alt[0][1]").is_err());
    }

    #[test]
    fn test_full_consumption_rejects_trailing_garbage() {
        assert!(parse_field_path("alt[0]oops").is_err());
    }

    #[test]
    fn test_empty_index() {
        assert!(parse_field_path("alt[]").is_err());
    }

    #[test]
    fn test_unclosed_bracket() {
        assert!(parse_field_path("alt[0").is_err());
    }

    #[test]
    fn test_trailing_dot() {
        assert!(parse_field_path("alt.").is_err());
    }

    // =========================================================================
    // resolve_index
    // =========================================================================

    #[test]
    fn test_resolve_index_zero() {
        assert_eq!(resolve_index(0, 3).unwrap(), 0);
    }

    #[test]
    fn test_resolve_index_positive() {
        assert_eq!(resolve_index(2, 5).unwrap(), 2);
    }

    #[test]
    fn test_resolve_index_negative() {
        assert_eq!(resolve_index(-1, 3).unwrap(), 2);
        assert_eq!(resolve_index(-3, 3).unwrap(), 0);
    }

    #[test]
    fn test_resolve_index_out_of_bounds() {
        assert!(resolve_index(3, 3).is_err());
        assert!(resolve_index(-4, 3).is_err());
    }

    #[test]
    fn test_resolve_index_empty_array() {
        assert!(resolve_index(0, 0).is_err());
    }

    // =========================================================================
    // require_index
    // =========================================================================

    #[test]
    fn test_require_index_present() {
        let seg = PathSegment {
            name: "alt".to_string(),
            index: Some(1),
        };
        assert_eq!(require_index(&seg, 3).unwrap(), 1);
    }

    #[test]
    fn test_require_index_missing() {
        let seg = PathSegment {
            name: "alt".to_string(),
            index: None,
        };
        assert!(require_index(&seg, 3).is_err());
    }
}