govctl 0.10.1

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
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
use super::ValidationResult;
use super::reference_hierarchy::{ReferenceSurface, check_ref_hierarchy};
use crate::artifact_index::artifact_ref_ids;
use crate::config::Config;
use crate::diagnostic::{Diagnostic, DiagnosticCode};
use crate::model::{AdrStatus, ProjectIndex, RfcStatus, WorkItemStatus};
use regex::Regex;
use std::collections::HashSet;

const BARE_ARTIFACT_ID_PATTERN: &str = r"\b(RFC-\d{4}(?::C-[A-Z][A-Z0-9-]*)?|ADR-\d{4}|WI-\d{4}-\d{2}-\d{2}-(?:[a-f0-9]{4}(?:-\d{3})?|\d{3}))\b";

struct ReferenceScanner {
    bracket_re: Regex,
    bare_re: Regex,
    known_ids: HashSet<String>,
}

#[derive(Clone, Copy)]
struct TextSource<'a> {
    path: &'a str,
    field: &'a str,
}

/// Validate inline references in governed prose per [[RFC-0000:C-REFERENCE-HIERARCHY]].
pub(super) fn validate_bracket_reference_hierarchy(
    index: &ProjectIndex,
    config: &Config,
    result: &mut ValidationResult,
) {
    let bracket_re = match Regex::new(&config.source_scan.pattern) {
        Ok(r) => r,
        Err(e) => {
            result.diagnostics.push(Diagnostic::new(
                DiagnosticCode::E0501ConfigInvalid,
                format!("Invalid source_scan.pattern for bracket reference scan: {e}"),
                "gov/config.toml".to_string(),
            ));
            return;
        }
    };
    let bare_re = match Regex::new(BARE_ARTIFACT_ID_PATTERN) {
        Ok(r) => r,
        Err(e) => {
            result.diagnostics.push(Diagnostic::new(
                DiagnosticCode::E0903UnexpectedError,
                format!("Invalid built-in bare artifact reference scan pattern: {e}"),
                "internal",
            ));
            return;
        }
    };
    let scanner = ReferenceScanner {
        bracket_re,
        bare_re,
        known_ids: artifact_ref_ids(index),
    };

    for rfc in &index.rfcs {
        let rfc_path = config.display_path(&rfc.path).display().to_string();
        let rid = rfc.rfc.rfc_id.as_str();
        let warn_on_bare_text = rfc.rfc.status == RfcStatus::Draft;
        for clause in &rfc.clauses {
            let clause_path = config.display_path(&clause.path).display().to_string();
            let field = format!("{} content.text", clause.spec.clause_id);
            scan_rfc_reference_hierarchy(
                &scanner,
                &clause.spec.text,
                rid,
                TextSource {
                    path: &clause_path,
                    field: &field,
                },
                true,
                warn_on_bare_text,
                result,
            );
        }
        for (entry_index, entry) in rfc.rfc.changelog.iter().enumerate() {
            if let Some(ref notes) = entry.notes {
                let field = format!("changelog[{entry_index}].notes");
                scan_rfc_reference_hierarchy(
                    &scanner,
                    notes,
                    rid,
                    TextSource {
                        path: &rfc_path,
                        field: &field,
                    },
                    false,
                    false,
                    result,
                );
            }
            let changelog_sections = [
                ("added", &entry.added),
                ("changed", &entry.changed),
                ("deprecated", &entry.deprecated),
                ("removed", &entry.removed),
                ("fixed", &entry.fixed),
                ("security", &entry.security),
            ];
            for (section, lines) in changelog_sections {
                for (line_index, line) in lines.iter().enumerate() {
                    let field = format!("changelog[{entry_index}].{section}[{line_index}]");
                    scan_rfc_reference_hierarchy(
                        &scanner,
                        line,
                        rid,
                        TextSource {
                            path: &rfc_path,
                            field: &field,
                        },
                        false,
                        false,
                        result,
                    );
                }
            }
        }
    }

    for adr in &index.adrs {
        let adr_path = config.display_path(&adr.path).display().to_string();
        let aid = adr.meta().id.as_str();
        let warn_on_bare_text = adr.meta().status == AdrStatus::Proposed;
        let c = &adr.spec.content;
        scan_adr_reference_hierarchy(
            &scanner,
            &c.context,
            aid,
            TextSource {
                path: &adr_path,
                field: "content.context",
            },
            warn_on_bare_text,
            result,
        );
        scan_adr_reference_hierarchy(
            &scanner,
            &c.decision,
            aid,
            TextSource {
                path: &adr_path,
                field: "content.decision",
            },
            warn_on_bare_text,
            result,
        );
        scan_adr_reference_hierarchy(
            &scanner,
            &c.consequences,
            aid,
            TextSource {
                path: &adr_path,
                field: "content.consequences",
            },
            warn_on_bare_text,
            result,
        );
        for (alt_index, alt) in c.alternatives.iter().enumerate() {
            let alt_text_field = format!("content.alternatives[{alt_index}].text");
            scan_adr_reference_hierarchy(
                &scanner,
                &alt.text,
                aid,
                TextSource {
                    path: &adr_path,
                    field: &alt_text_field,
                },
                warn_on_bare_text,
                result,
            );
            for (pro_index, p) in alt.pros.iter().enumerate() {
                let pro_field = format!("content.alternatives[{alt_index}].pros[{pro_index}]");
                scan_adr_reference_hierarchy(
                    &scanner,
                    p,
                    aid,
                    TextSource {
                        path: &adr_path,
                        field: &pro_field,
                    },
                    warn_on_bare_text,
                    result,
                );
            }
            for (con_index, cons) in alt.cons.iter().enumerate() {
                let con_field = format!("content.alternatives[{alt_index}].cons[{con_index}]");
                scan_adr_reference_hierarchy(
                    &scanner,
                    cons,
                    aid,
                    TextSource {
                        path: &adr_path,
                        field: &con_field,
                    },
                    warn_on_bare_text,
                    result,
                );
            }
            if let Some(ref rr) = alt.rejection_reason {
                let rejection_field = format!("content.alternatives[{alt_index}].rejection_reason");
                scan_adr_reference_hierarchy(
                    &scanner,
                    rr,
                    aid,
                    TextSource {
                        path: &adr_path,
                        field: &rejection_field,
                    },
                    warn_on_bare_text,
                    result,
                );
            }
        }
    }

    for work in &index.work_items {
        let work_path = config.display_path(&work.path).display().to_string();
        let wid = work.meta().id.as_str();
        let warn_on_bare_text = work.meta().status != WorkItemStatus::Done;
        let content = &work.spec.content;
        scan_work_reference_syntax(
            &scanner,
            &content.description,
            wid,
            TextSource {
                path: &work_path,
                field: "content.description",
            },
            warn_on_bare_text,
            result,
        );
        for (criterion_index, criterion) in content.acceptance_criteria.iter().enumerate() {
            let criterion_field = format!("content.acceptance_criteria[{criterion_index}].text");
            scan_work_reference_syntax(
                &scanner,
                &criterion.text,
                wid,
                TextSource {
                    path: &work_path,
                    field: &criterion_field,
                },
                warn_on_bare_text,
                result,
            );
        }
        for (note_index, note) in content.notes.iter().enumerate() {
            let note_field = format!("content.notes[{note_index}]");
            scan_work_reference_syntax(
                &scanner,
                note,
                wid,
                TextSource {
                    path: &work_path,
                    field: &note_field,
                },
                warn_on_bare_text,
                result,
            );
        }
    }
}

fn scan_rfc_reference_hierarchy(
    scanner: &ReferenceScanner,
    text: &str,
    rfc_id: &str,
    source: TextSource<'_>,
    scan_bare_text: bool,
    warn_on_bare_text: bool,
    result: &mut ValidationResult,
) {
    scan_reference_hierarchy(
        scanner,
        text,
        rfc_id,
        source,
        scan_bare_text,
        warn_on_bare_text,
        result,
    );
}

fn scan_adr_reference_hierarchy(
    scanner: &ReferenceScanner,
    text: &str,
    adr_id: &str,
    source: TextSource<'_>,
    warn_on_bare_text: bool,
    result: &mut ValidationResult,
) {
    scan_reference_hierarchy(
        scanner,
        text,
        adr_id,
        source,
        true,
        warn_on_bare_text,
        result,
    );
}

fn scan_work_reference_syntax(
    scanner: &ReferenceScanner,
    text: &str,
    work_id: &str,
    source: TextSource<'_>,
    warn_on_bare_text: bool,
    result: &mut ValidationResult,
) {
    scan_reference_hierarchy(
        scanner,
        text,
        work_id,
        source,
        true,
        warn_on_bare_text,
        result,
    );
}

fn scan_reference_hierarchy(
    scanner: &ReferenceScanner,
    text: &str,
    owner_id: &str,
    source: TextSource<'_>,
    scan_bare_text: bool,
    warn_on_bare_text: bool,
    result: &mut ValidationResult,
) {
    let mut bracket_ranges = Vec::new();
    for caps in scanner.bracket_re.captures_iter(text) {
        if let Some(full) = caps.get(0) {
            bracket_ranges.push(full.range());
        }
        let Some(m) = caps.get(1) else {
            continue;
        };
        let target = m.as_str();
        if let Err(diagnostic) =
            check_ref_hierarchy(owner_id, target, source.path, ReferenceSurface::BracketLink)
        {
            result.diagnostics.push(diagnostic);
        }
    }

    if !scan_bare_text {
        return;
    }

    for caps in scanner.bare_re.captures_iter(text) {
        let Some(m) = caps.get(1) else {
            continue;
        };
        if bracket_ranges
            .iter()
            .any(|range| range.start <= m.start() && m.end() <= range.end)
        {
            continue;
        }
        let target = m.as_str();
        if !scanner.known_ids.contains(target) {
            continue;
        }
        match check_ref_hierarchy(owner_id, target, source.path, ReferenceSurface::BareText) {
            Ok(()) if warn_on_bare_text => result.diagnostics.push(
                bare_artifact_reference_warning(owner_id, target, source, text, m.start()),
            ),
            Ok(()) => {}
            Err(diagnostic) => result.diagnostics.push(diagnostic),
        }
    }
}

fn bare_artifact_reference_warning(
    owner_id: &str,
    target: &str,
    source: TextSource<'_>,
    text: &str,
    match_start: usize,
) -> Diagnostic {
    let (line, context) = source_line_context(text, match_start);
    Diagnostic::new(
        DiagnosticCode::W0112BareArtifactReference,
        format!(
            "Artifact '{owner_id}' {field} line {line} mentions known artifact ID {target} without [[...]] inline reference syntax (hint: use [[{target}]]; context: \"{context}\")",
            field = source.field,
        ),
        source.path,
    )
}

fn source_line_context(text: &str, byte_offset: usize) -> (usize, String) {
    let line = text[..byte_offset].bytes().filter(|b| *b == b'\n').count() + 1;
    let line_start = text[..byte_offset].rfind('\n').map_or(0, |idx| idx + 1);
    let line_end = text[byte_offset..]
        .find('\n')
        .map_or(text.len(), |idx| byte_offset + idx);
    let context = collapse_context_whitespace(&text[line_start..line_end]);
    (line, truncate_context(&context))
}

fn collapse_context_whitespace(line: &str) -> String {
    line.split_whitespace().collect::<Vec<_>>().join(" ")
}

fn truncate_context(context: &str) -> String {
    const MAX_CONTEXT_CHARS: usize = 120;
    let mut out = String::new();
    for (count, ch) in context.chars().enumerate() {
        if count == MAX_CONTEXT_CHARS {
            out.push_str("...");
            break;
        }
        out.push(ch);
    }
    out.replace('"', "\\\"")
}

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

    fn bracket_re() -> DiagnosticResult<Regex> {
        Regex::new(
            r"\[\[(RFC-\d{4}(?::C-[A-Z][A-Z0-9-]*)?|ADR-\d{4}|WI-\d{4}-\d{2}-\d{2}-(?:[a-f0-9]{4}(?:-\d{3})?|\d{3}))\]\]",
        )
        .map_err(|err| {
            Diagnostic::new(
                DiagnosticCode::E0903UnexpectedError,
                format!("test bracket regex must compile: {err}"),
                "test",
            )
        })
    }

    fn bare_re() -> DiagnosticResult<Regex> {
        Regex::new(BARE_ARTIFACT_ID_PATTERN).map_err(|err| {
            Diagnostic::new(
                DiagnosticCode::E0903UnexpectedError,
                format!("test bare regex must compile: {err}"),
                "test",
            )
        })
    }

    fn scanner(known_ids: HashSet<String>) -> DiagnosticResult<ReferenceScanner> {
        Ok(ReferenceScanner {
            bracket_re: bracket_re()?,
            bare_re: bare_re()?,
            known_ids,
        })
    }

    #[test]
    fn bare_known_adr_in_rfc_text_violates_hierarchy() -> DiagnosticResult<()> {
        let mut known_ids = HashSet::new();
        known_ids.insert("ADR-0001".to_string());
        let mut result = ValidationResult::default();

        scan_reference_hierarchy(
            &scanner(known_ids)?,
            "This mentions ADR-0001 without brackets.",
            "RFC-0001",
            TextSource {
                path: "f",
                field: "content.text",
            },
            true,
            true,
            &mut result,
        );

        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(
            result.diagnostics[0].code,
            DiagnosticCode::E0112RfcReferenceHierarchy
        );
        Ok(())
    }

    #[test]
    fn bare_unknown_artifact_shape_in_rfc_text_is_not_a_reference() -> DiagnosticResult<()> {
        let known_ids = HashSet::new();
        let mut result = ValidationResult::default();

        scan_reference_hierarchy(
            &scanner(known_ids)?,
            "This mentions ADR-0001 only as an example shape.",
            "RFC-0001",
            TextSource {
                path: "f",
                field: "content.text",
            },
            true,
            true,
            &mut result,
        );

        assert!(result.diagnostics.is_empty());
        Ok(())
    }

    #[test]
    fn bare_known_rfc_in_adr_text_warns() -> DiagnosticResult<()> {
        let mut known_ids = HashSet::new();
        known_ids.insert("RFC-0001".to_string());
        let mut result = ValidationResult::default();

        scan_reference_hierarchy(
            &scanner(known_ids)?,
            "Intro line.\nThis follows RFC-0001.",
            "ADR-0001",
            TextSource {
                path: "f",
                field: "content.decision",
            },
            true,
            true,
            &mut result,
        );

        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(
            result.diagnostics[0].code,
            DiagnosticCode::W0112BareArtifactReference
        );
        assert!(
            result.diagnostics[0]
                .message
                .contains("content.decision line 2"),
            "message: {}",
            result.diagnostics[0].message
        );
        assert!(
            result.diagnostics[0]
                .message
                .contains("context: \"This follows RFC-0001.\""),
            "message: {}",
            result.diagnostics[0].message
        );
        Ok(())
    }

    #[test]
    fn bracketed_known_rfc_in_adr_text_does_not_warn() -> DiagnosticResult<()> {
        let mut known_ids = HashSet::new();
        known_ids.insert("RFC-0001".to_string());
        let mut result = ValidationResult::default();

        scan_reference_hierarchy(
            &scanner(known_ids)?,
            "This follows [[RFC-0001]].",
            "ADR-0001",
            TextSource {
                path: "f",
                field: "content.decision",
            },
            true,
            true,
            &mut result,
        );

        assert!(result.diagnostics.is_empty());
        Ok(())
    }
}