doctrine 0.34.0

Project tooling CLI
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
// SPDX-License-Identifier: GPL-3.0-only
//! `plan` — the authored implementation-plan read model.
//!
//! An engine-tier leaf: `Plan`/`PlanPhase` and the pure `Plan::parse`
//! validator, lifted out of `crate::slice` (SL-016) so the runtime `state`
//! layer can depend on a neutral home instead of reaching *up* into the
//! slice-CLI module. Pure — no clock, disk, or git here; disk IO
//! (`read_plan`) stays in the slice shell and calls `Plan::parse`.

use serde::Deserialize;

use anyhow::{Context, bail};

/// The authored implementation plan, read from `plan.toml`. Only the ordered
/// phase list is consumed in v1 (phase materialisation, slice-004 §5.2); the
/// specs/requirements link tables exist in the file but are empty (no registry
/// yet) and are not modelled. The first relational *read* model — no shared
/// `Meta` (slice-003 Non-Goal).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub(crate) struct Plan {
    #[serde(default)]
    pub phases: Vec<PlanPhase>,
}

/// One authored phase row. `id` is the canonical `PHASE-NN` join key; `name`
/// and `objective` seed the disposable phase sheet. The entrance/exit/verification
/// criteria are lifted into the model (SL-170 PHASE-01) so the VT existence/shape
/// gate (PHASE-03 `vtgate`) and downstream IDE-008 can read them; every added
/// field is `#[serde(default)]`, so legacy plans without them round-trip to
/// defaulted empties (the behaviour-preservation gate, design §3).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub(crate) struct PlanPhase {
    pub id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub objective: String,
    #[serde(default)]
    pub entrance_criteria: Vec<Criterion>,
    #[serde(default)]
    pub exit_criteria: Vec<Criterion>,
    #[serde(default)]
    pub verification: Vec<VerificationCriterion>,
}

/// An authored entrance (`EN-`) or exit (`EX-`) criterion. `id` is the immutable
/// doc-local handle; `text` is the prose body (defaulted empty if omitted).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub(crate) struct Criterion {
    pub id: String,
    #[serde(default)]
    pub text: String,
}

/// An authored verification criterion. Mode (VT test / VA agent / VH human) stays
/// encoded in the `id` prefix — there is no separate mode field. `expects` is the
/// free-text expectation (untouched, heterogeneous by design); the P2 structured
/// fields (`test_file` / `keywords` / `patterns`) are the machine-checkable mandate
/// the PHASE-03 gate reads, and `waived` / `waived_reason` are the recorded escape
/// valve. All but `id` default, so legacy `{ id, expects }` rows parse unchanged.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub(crate) struct VerificationCriterion {
    pub id: String,
    #[serde(default)]
    pub expects: String,
    #[serde(default)]
    pub test_file: Option<String>,
    #[serde(default)]
    pub keywords: Vec<String>,
    #[serde(default)]
    pub patterns: Vec<String>,
    #[serde(default)]
    pub waived: bool,
    #[serde(default)]
    pub waived_reason: Option<String>,
}

impl Plan {
    /// Parse and validate a `plan.toml` body. Rejects a plan whose phase ids
    /// are not unique — a duplicate would alias two phases onto one tracking
    /// file (finding 6). Per-id well-formedness (`PHASE-<digits>`) is enforced
    /// at the filesystem boundary by `state::phase_stem` (slice-004 §9), where
    /// an id becomes a filename.
    pub(crate) fn parse(text: &str) -> anyhow::Result<Plan> {
        // serde renames the TOML `[[phase]]` array to the `phases` field.
        #[derive(Deserialize)]
        struct Raw {
            #[serde(default)]
            phase: Vec<PlanPhase>,
        }
        let raw: Raw = toml::from_str(text).context("Failed to parse plan.toml")?;
        let mut seen = std::collections::BTreeSet::new();
        for ph in &raw.phase {
            if !seen.insert(ph.id.as_str()) {
                bail!("Duplicate phase id {} in plan", ph.id);
            }
        }
        Ok(Plan { phases: raw.phase })
    }
}

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

    #[test]
    fn plan_parse_reads_ordered_phases() {
        let text = format!(
            r#"
            schema = "{SCHEMA_PLAN_OVERVIEW}"
            version = 1
            slice = "SL-004"
            [[phase]]
            id = "PHASE-01"
            name = "First"
            objective = "do a"
            [[phase]]
            id = "PHASE-02"
            name = "Second"
        "#
        );
        let plan = Plan::parse(&text).unwrap();
        let ids: Vec<&str> = plan.phases.iter().map(|p| p.id.as_str()).collect();
        assert_eq!(ids, vec!["PHASE-01", "PHASE-02"]);
        assert_eq!(plan.phases[0].objective, "do a");
        // an absent objective defaults to empty, not an error
        assert_eq!(plan.phases[1].objective, "");
    }

    #[test]
    fn plan_parse_lifts_criteria_and_p2_fields() {
        let text = format!(
            r#"
            schema = "{SCHEMA_PLAN_OVERVIEW}"
            version = 1
            slice = "SL-170"
            [[phase]]
            id = "PHASE-01"
            name = "Lift"
            objective = "do it"
            entrance_criteria = [
              {{ id = "EN-1", text = "design locked" }},
            ]
            exit_criteria = [
              {{ id = "EX-1", text = "fields parse" }},
            ]
            verification = [
              {{ id = "VT-1", expects = "round-trip", test_file = "src/plan.rs", keywords = ["entrance_criteria", "verification"], patterns = ["^\\s*pub"], waived = false }},
              {{ id = "VT-2", expects = "behaviour-preserved", waived = true, waived_reason = "covered by existing suite" }},
            ]
        "#
        );
        let plan = Plan::parse(&text).unwrap();
        let ph = &plan.phases[0];
        assert_eq!(ph.entrance_criteria.len(), 1);
        assert_eq!(ph.entrance_criteria[0].id, "EN-1");
        assert_eq!(ph.entrance_criteria[0].text, "design locked");
        assert_eq!(ph.exit_criteria[0].id, "EX-1");
        assert_eq!(ph.exit_criteria[0].text, "fields parse");
        assert_eq!(ph.verification.len(), 2);
        let vt1 = &ph.verification[0];
        assert_eq!(vt1.id, "VT-1");
        assert_eq!(vt1.expects, "round-trip");
        assert_eq!(vt1.test_file.as_deref(), Some("src/plan.rs"));
        assert_eq!(vt1.keywords, vec!["entrance_criteria", "verification"]);
        assert_eq!(vt1.patterns, vec!["^\\s*pub"]);
        assert!(!vt1.waived);
        assert_eq!(vt1.waived_reason, None);
        let vt2 = &ph.verification[1];
        assert!(vt2.waived);
        assert_eq!(
            vt2.waived_reason.as_deref(),
            Some("covered by existing suite")
        );
    }

    #[test]
    fn plan_parse_defaults_structured_fields_on_legacy_rows() {
        let text = format!(
            r#"
            schema = "{SCHEMA_PLAN_OVERVIEW}"
            version = 1
            slice = "SL-016"
            [[phase]]
            id = "PHASE-01"
            name = "Legacy"
            verification = [
              {{ id = "VT-1", expects = "full suite green" }},
            ]
        "#
        );
        let plan = Plan::parse(&text).unwrap();
        let ph = &plan.phases[0];
        assert!(ph.entrance_criteria.is_empty());
        assert!(ph.exit_criteria.is_empty());
        let vt = &ph.verification[0];
        assert_eq!(vt.expects, "full suite green");
        assert_eq!(vt.test_file, None);
        assert!(vt.keywords.is_empty());
        assert!(vt.patterns.is_empty());
        assert!(!vt.waived);
        assert_eq!(vt.waived_reason, None);
    }
}

// ---------------------------------------------------------------------------
// VT shape check — `doctrine check plan <id>` (IMP-209)
// ---------------------------------------------------------------------------

/// A finding from [`check_vt_shape`] — one per flagged verification criterion.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct VtShapeFinding {
    pub phase_id: String,
    pub vt_id: String,
    pub problem: VtShapeProblem,
}

/// The reason a VT row was flagged.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum VtShapeProblem {
    /// `test_file` is `None` — nothing to grep; the VT is UNCHECKABLE at runtime.
    BareTestFile,
    /// `test_file` is set but `keywords` is empty — vacuous pass at runtime.
    BareKeywords,
    /// `waived` is true but `waived_reason` is `None` — opaque waiver.
    MissingWaiverReason,
}

/// Check every VT-mode row in the plan for structured mandate completeness.
///
/// Returns findings for:
/// - non-waived VTs without `test_file` (`BareTestFile`)
/// - non-waived VTs with `test_file` but empty `keywords` (`BareKeywords` —
///   vacuous pass)
/// - waived VTs without `waived_reason` (`MissingWaiverReason` — opaque)
///
/// VA/VH rows are skipped entirely.
pub(crate) fn check_vt_shape(plan: &Plan) -> Vec<VtShapeFinding> {
    let mut findings = Vec::new();
    for ph in &plan.phases {
        for vt in &ph.verification {
            // Skip non-VT rows.
            if !vt.id.starts_with("VT-") {
                continue;
            }
            if vt.waived {
                if vt.waived_reason.is_none() {
                    findings.push(VtShapeFinding {
                        phase_id: ph.id.clone(),
                        vt_id: vt.id.clone(),
                        problem: VtShapeProblem::MissingWaiverReason,
                    });
                }
                continue;
            }
            // Non-waived VT — must have a structured mandate.
            if vt.test_file.is_none() {
                findings.push(VtShapeFinding {
                    phase_id: ph.id.clone(),
                    vt_id: vt.id.clone(),
                    problem: VtShapeProblem::BareTestFile,
                });
            } else if vt.keywords.is_empty() {
                findings.push(VtShapeFinding {
                    phase_id: ph.id.clone(),
                    vt_id: vt.id.clone(),
                    problem: VtShapeProblem::BareKeywords,
                });
            }
        }
    }
    findings
}

// ---------------------------------------------------------------------------
// Selector-completeness check — plan-time under-declaration lint (SL-224)
// ---------------------------------------------------------------------------

/// A finding from [`undeclared_test_files`] — one non-waived VT whose
/// `test_file` is covered by NO design-target selector. The "scope-relevant
/// doesn't clear the belt; must be design-target" trap, caught at plan time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct VtSelectorFinding {
    pub phase_id: String,
    pub vt_id: String,
    pub path: String,
}

/// Flag every non-waived VT whose `test_file` is declared by no design-target
/// selector — the same under-declaration the import belt refuses at integrate
/// time, surfaced at plan time instead.
///
/// EMPTY `selectors` ⇒ EMPTY result: mirrors the import belt's no-op-when-no-scope
/// (an unscoped plan cannot under-declare). Guarded FIRST, before delegating to
/// [`crate::conformance::undeclared_paths`] (which flags every path on empty input).
///
/// Coverage is decided by the SHARED `undeclared_paths` predicate — the exact
/// glob-aware match the import belt uses — so a flag here is precisely what the
/// belt would refuse. Waived VTs and VTs without a `test_file` are skipped,
/// mirroring [`check_vt_shape`]'s iteration.
pub(crate) fn undeclared_test_files(plan: &Plan, selectors: &[String]) -> Vec<VtSelectorFinding> {
    // No scope ⇒ nothing to under-declare (import belt parity, A3).
    if selectors.is_empty() {
        return Vec::new();
    }
    let mut findings = Vec::new();
    for ph in &plan.phases {
        for vt in &ph.verification {
            if !vt.id.starts_with("VT-") {
                continue;
            }
            if vt.waived {
                continue;
            }
            let Some(test_file) = &vt.test_file else {
                continue;
            };
            // Shared predicate: non-empty ⇒ the path is declared by no selector.
            if !crate::conformance::undeclared_paths(selectors, &[test_file.as_str()]).is_empty() {
                findings.push(VtSelectorFinding {
                    phase_id: ph.id.clone(),
                    vt_id: vt.id.clone(),
                    path: test_file.clone(),
                });
            }
        }
    }
    findings
}

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

    #[test]
    fn bare_test_file_flag() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VT-1", expects = "just prose" },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].vt_id, "VT-1");
        assert_eq!(findings[0].phase_id, "PHASE-01");
        assert_eq!(findings[0].problem, VtShapeProblem::BareTestFile);
    }

    #[test]
    fn bare_keywords_flag() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VT-1", test_file = "src/foo.rs", keywords = [] },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].problem, VtShapeProblem::BareKeywords);
    }

    #[test]
    fn structured_vt_passes() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VT-1", test_file = "src/foo.rs", keywords = ["fn"] },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert!(findings.is_empty());
    }

    #[test]
    fn waived_with_reason_passes() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VT-1", waived = true, waived_reason = "manual only" },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert!(findings.is_empty());
    }

    #[test]
    fn waived_without_reason_warns() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VT-1", waived = true },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].problem, VtShapeProblem::MissingWaiverReason);
    }

    #[test]
    fn va_rows_skipped() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VA-1", expects = "agent reviews" },
              { id = "VH-1", expects = "human signs off" },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert!(findings.is_empty());
    }

    #[test]
    fn multi_phase_multi_finding() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VT-1", test_file = "src/foo.rs", keywords = ["fn"] },
              { id = "VT-2", expects = "bare prose" },
            ]
            [[phase]]
            id = "PHASE-02"
            verification = [
              { id = "VT-3", test_file = "src/bar.rs", keywords = [] },
              { id = "VT-4", waived = true },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert_eq!(findings.len(), 3);
        assert_eq!(findings[0].vt_id, "VT-2");
        assert_eq!(findings[0].problem, VtShapeProblem::BareTestFile);
        assert_eq!(findings[1].vt_id, "VT-3");
        assert_eq!(findings[1].problem, VtShapeProblem::BareKeywords);
        assert_eq!(findings[2].vt_id, "VT-4");
        assert_eq!(findings[2].problem, VtShapeProblem::MissingWaiverReason);
    }

    #[test]
    fn empty_phases_no_findings() {
        let text = "";
        let plan = Plan::parse(text).unwrap();
        assert!(plan.phases.is_empty());
        let findings = check_vt_shape(&plan);
        assert!(findings.is_empty());
    }

    #[test]
    fn waived_overrides_bare_shape() {
        // A waived VT without test_file should NOT report BareTestFile — the
        // waiver short-circuits; only MissingWaiverReason if reason is absent.
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VT-1", waived = true, waived_reason = "N/A" },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert!(findings.is_empty());
    }

    #[test]
    fn waived_overrides_bare_shape_no_reason() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              { id = "VT-1", waived = true },
            ]
        "#;
        let plan = Plan::parse(text).unwrap();
        let findings = check_vt_shape(&plan);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].problem, VtShapeProblem::MissingWaiverReason);
        // NOT BareTestFile — waiver short-circuits.
    }
}

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

    fn plan_with(vt_rows: &str) -> Plan {
        let text = format!(
            r#"
            [[phase]]
            id = "PHASE-01"
            verification = [
              {vt_rows}
            ]
        "#
        );
        Plan::parse(&text).unwrap()
    }

    #[test]
    fn undeclared_test_file_flags_one_finding() {
        let plan = plan_with(r#"{ id = "VT-1", test_file = "src/plan.rs", keywords = ["fn"] },"#);
        let selectors = vec!["src/commands/check.rs".to_string()];
        let findings = undeclared_test_files(&plan, &selectors);
        assert_eq!(findings.len(), 1);
        assert_eq!(
            findings[0],
            VtSelectorFinding {
                phase_id: "PHASE-01".to_string(),
                vt_id: "VT-1".to_string(),
                path: "src/plan.rs".to_string(),
            }
        );
    }

    #[test]
    fn covered_test_file_yields_no_finding() {
        let plan = plan_with(r#"{ id = "VT-1", test_file = "src/plan.rs", keywords = ["fn"] },"#);
        let selectors = vec!["src/plan.rs".to_string()];
        assert!(undeclared_test_files(&plan, &selectors).is_empty());
    }

    #[test]
    fn empty_selectors_yields_no_finding() {
        // A3: no scope ⇒ nothing under-declared, even though the path is unmatched.
        let plan = plan_with(r#"{ id = "VT-1", test_file = "src/plan.rs", keywords = ["fn"] },"#);
        assert!(undeclared_test_files(&plan, &[]).is_empty());
    }

    #[test]
    fn glob_covered_test_file_yields_no_finding() {
        // Exercises undeclared_paths's glob path — a directory glob covers the file.
        let plan = plan_with(r#"{ id = "VT-1", test_file = "src/plan.rs", keywords = ["fn"] },"#);
        let selectors = vec!["src/**".to_string()];
        assert!(undeclared_test_files(&plan, &selectors).is_empty());
    }

    #[test]
    fn waived_and_bare_vts_skipped() {
        let plan = plan_with(
            r#"{ id = "VT-1", test_file = "src/plan.rs", keywords = ["fn"], waived = true, waived_reason = "manual" },
              { id = "VT-2", expects = "no test_file" },"#,
        );
        let selectors = vec!["src/other.rs".to_string()];
        // VT-1 waived, VT-2 has no test_file — neither is flagged.
        assert!(undeclared_test_files(&plan, &selectors).is_empty());
    }
}

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

    #[test]
    fn plan_parse_rejects_duplicate_phase_ids() {
        let text = r#"
            [[phase]]
            id = "PHASE-01"
            [[phase]]
            id = "PHASE-01"
        "#;
        let err = Plan::parse(text).unwrap_err();
        assert!(err.to_string().contains("Duplicate phase id PHASE-01"));
    }
}