doctrine 0.14.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
// SPDX-License-Identifier: GPL-3.0-only
//! `doctrine needs` / `doctrine after` — dep/seq verbs (SL-060 §5.4).
//! SL-129: uses `entity::id_path`

use std::path::PathBuf;

/// The work-like membership predicate (SL-060 §5.4, SL-066 §PHASE-04) — the ONE
/// widen-later guard. Work-like = { slice } ∪ { the 5 backlog kinds } ∪ { revision }.
/// Both the dep/seq-authoring SRC set and the admissible TGT set are this same
/// membership (a slice / backlog item / revision may author dep/seq, and may only
/// depend/sequence on another piece of work). REV is admitted as BOTH source and
/// target: a slice or backlog item may `needs`/`after` a REV-NNN, and a REV may
/// itself `needs`/`after` a work item (the IDE-010 payoff). Governance docs
/// (spec/ADR/POL/STD) stay EXCLUDED — depending on governance routes THROUGH a
/// Revision, never the evergreen doc (the SL-060 invariant). A future phase that
/// allows cross-tier dep/seq deletes just this predicate (and its refusal tests).
pub(crate) fn is_work_like(kind: &'static crate::entity::Kind) -> bool {
    crate::kinds::WORK_LIKE.contains(&kind.prefix)
}

/// The record membership predicate (SL-158 D2) — the knowledge-record kinds that a
/// work item may now `needs`/`after`. Records are NOT work-like (cannot author
/// dep/seq), but are admissible as dep/seq TARGETS. Governance (SPEC/ADR/POL/STD)
/// stays excluded from BOTH gates.
pub(crate) fn is_record(kind: &'static crate::entity::Kind) -> bool {
    crate::kinds::is_record(kind.prefix)
}

/// The admissible target membership predicate (SL-158 D2) — widens the old single
/// work-like gate for targets to include records. A work item may now `needs`/`after`
/// a record (ASM/DEC/QUE/CON/EVD/HYP). Governance (SPEC/ADR/POL/STD) stays excluded because
/// depending on governance routes THROUGH a Revision, never the evergreen doc (the
/// SL-060 invariant).
pub(crate) fn is_admissible_dep_target(kind: &'static crate::entity::Kind) -> bool {
    is_work_like(kind) || is_record(kind)
}

/// Resolve a dep/seq source to its TOML path. Validates: canonical-ref parse,
/// work-like kind (slice or backlog). Returns the resolved path.
fn resolve_dep_seq_src_path(root: &std::path::Path, source: &str) -> anyhow::Result<PathBuf> {
    let (skref, sid) = crate::integrity::parse_resolvable_ref(root, source)?;
    anyhow::ensure!(
        is_work_like(skref.kind),
        "`{source}` is a {} entity, which cannot author needs/after — only a slice or a backlog item (issue/improvement/chore/risk/idea) carries dep/seq",
        skref.kind.prefix
    );
    Ok(crate::entity::id_path(
        root,
        skref.kind,
        sid,
        crate::entity::Ext::Toml,
    ))
}

/// Resolve a generic dep/seq `(SRC, TGT)` pair against the author-time gate (§5.4),
/// returning SRC's `slice-NNN.toml`-shaped path ready for the leaf write. Rides the
/// SAME cross-kind canonical-ref seam as `link` (`integrity::parse_canonical_ref` +
/// the `KindRef` `(dir, stem)` path map) — no new resolver. The three refusals, each
/// a clear, specific message:
///   1. SRC must resolve AND be a dep/seq-authoring (work-like) kind.
///   2. TGT must resolve on disk (free-text / dangling refused) AND be
///      admissible as a dep/seq target (work-like OR record). SL-158 D2 widened
///      the old work-like-only gate to admit knowledge records (ASM/DEC/QUE/CON/EVD/HYP).
///      Governance (SPEC/ADR/POL/STD) stays excluded from BOTH gates.
///   3. self-edge (SRC == TGT) refused.
///
/// Returns SRC's toml path plus the CANONICAL ids of both endpoints
/// ([`crate::listing::canonical_id`]) — the caller stores and echoes the canonical
/// form, so a non-canonical input (`SL-1`) normalizes at both the write and the
/// echo, matching the backlog path (IMP-140 F-13).
fn resolve_dep_seq_src(
    root: &std::path::Path,
    source: &str,
    target: &str,
) -> anyhow::Result<(PathBuf, String, String)> {
    let toml_path = resolve_dep_seq_src_path(root, source)?;
    let (skref, sid) = crate::integrity::parse_resolvable_ref(root, source)?;
    // TGT must resolve on disk — a free-text or dangling target is refused here
    // (never write an edge to a non-entity). The resolver first so a
    // free-text target surfaces the ref-shape error, then a dir probe.
    let (tkref, tid) = crate::integrity::parse_resolvable_ref(root, target)?;
    anyhow::ensure!(
        is_admissible_dep_target(tkref.kind),
        "`{target}` is a {} entity — needs/after may only target work (a slice or a backlog item) or a knowledge record (assumption/decision/question/constraint/evidence/hypothesis); governance docs are excluded",
        tkref.kind.prefix
    );
    anyhow::ensure!(
        !(skref.kind.prefix == tkref.kind.prefix && sid == tid),
        "a {source} edge to itself is not a dependency — self-edges are refused"
    );
    let source_id = crate::listing::canonical_id(skref.kind.prefix, sid);
    let target_id = crate::listing::canonical_id(tkref.kind.prefix, tid);
    Ok((toml_path, source_id, target_id))
}

/// `doctrine needs <SRC> <TGT>` (SL-060 §5.4, SL-158 D2) — append TGT to SRC's
/// `needs` axis. Generic cross-kind: the author-time gate
/// ([`resolve_dep_seq_src`]) gates SRC as work-like and TGT as admissible
/// (work-like OR record, SL-158 D2), then the shared leaf `dep_seq::append`.
/// NO author-time cycle check (deferred to read time by design — the cross-kind
/// cycle oracle is a later phase).
pub(crate) fn run_needs_edge(
    path: Option<PathBuf>,
    source: &str,
    target: &str,
) -> anyhow::Result<()> {
    use std::io::Write;
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (toml_path, source_id, target_id) = resolve_dep_seq_src(&root, source, target)?;
    crate::dep_seq::append(
        &toml_path,
        &crate::dep_seq::RelEdit::Needs(std::slice::from_ref(&target_id)),
    )?;
    writeln!(std::io::stdout(), "{source_id} needs {target_id}")?;
    Ok(())
}

/// `doctrine after <SRC> <TGT> [--rank N]` (SL-060 §5.4) — append `{ to, rank }` to
/// SRC's `after` axis through the same gate + leaf. Rank default 0.
pub(crate) fn run_after_edge(
    path: Option<PathBuf>,
    source: &str,
    target: &str,
    rank: i32,
) -> anyhow::Result<()> {
    use std::io::Write;
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (toml_path, source_id, target_id) = resolve_dep_seq_src(&root, source, target)?;
    crate::dep_seq::append(
        &toml_path,
        &crate::dep_seq::RelEdit::After {
            to: &target_id,
            rank,
        },
    )?;
    let suffix = if rank == 0 {
        String::new()
    } else {
        format!(" (rank {rank})")
    };
    writeln!(std::io::stdout(), "{source_id} after {target_id}{suffix}")?;
    Ok(())
}

/// `doctrine after <SRC> <TGT> --remove [--rank N]`
pub(crate) fn run_after_remove(
    path: Option<PathBuf>,
    source: &str,
    target: &str,
    rank: i32,
) -> anyhow::Result<()> {
    use std::io::Write;
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let (toml_path, source_id, target_id) = resolve_dep_seq_src(&root, source, target)?;
    let ceiling = if rank == 0 { None } else { Some(rank) };
    let removed = crate::dep_seq::remove(&toml_path, &target_id, ceiling)?;
    if removed == 0 {
        anyhow::bail!("{source_id} has no after edge to {target_id}");
    }
    writeln!(
        std::io::stdout(),
        "{source_id} after {target_id} removed ({} edge{})",
        removed,
        if removed == 1 { "" } else { "s" }
    )?;
    Ok(())
}

/// `doctrine after <SRC> --prune` (SL-105 PHASE-03) — probe every `after` target
/// of SRC for dangling edges (absent or terminal target) and remove them. Reads
/// the `DepSeq` ONCE before any modifications (collecting dangling targets), then
/// removes in a second pass using the shared `dep_seq::remove` leaf.
pub(crate) fn run_after_prune(path: Option<PathBuf>, source: &str) -> anyhow::Result<()> {
    use std::io::Write;
    let root = crate::root::find(path, &crate::root::default_markers())?;
    let toml_path = resolve_dep_seq_src_path(&root, source)?;

    // 1. Read DepSeq
    let ds = crate::dep_seq::read(&toml_path)?;

    // 2. Probe each after-edge target: absent (dir missing) or terminal (resolved/closed) → dangling
    let mut dropped: Vec<(String, i32, String)> = Vec::new();
    let mut to_drop: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();

    for edge in &ds.after {
        let is_dangling = match crate::integrity::parse_canonical_ref(&edge.to) {
            Ok((kref, tid)) => {
                let target_path =
                    crate::entity::id_path(&root, kref.kind, tid, crate::entity::Ext::Toml);
                if target_path.exists() {
                    let body = std::fs::read_to_string(&target_path).unwrap_or_default();
                    let val: toml::Value = match toml::from_str(&body) {
                        Ok(v) => v,
                        Err(_) => toml::Value::Table(toml::Table::new()),
                    };
                    let status = val.get("status").and_then(|s| s.as_str()).unwrap_or("");
                    status == "resolved" || status == "closed"
                } else {
                    true
                }
            }
            Err(_) => true,
        };

        if is_dangling {
            let reason = match crate::integrity::parse_canonical_ref(&edge.to) {
                Ok((kref2, tid2)) => {
                    let target_path =
                        crate::entity::id_path(&root, kref2.kind, tid2, crate::entity::Ext::Toml);
                    if target_path.exists() {
                        let body = std::fs::read_to_string(&target_path).unwrap_or_default();
                        let val: toml::Value = match toml::from_str(&body) {
                            Ok(v) => v,
                            Err(_) => toml::Value::Table(toml::Table::new()),
                        };
                        let status = val.get("status").and_then(|s| s.as_str()).unwrap_or("");
                        let resolution =
                            val.get("resolution").and_then(|s| s.as_str()).unwrap_or("");
                        if resolution.is_empty() {
                            status.to_string()
                        } else {
                            format!("{status}/{resolution}")
                        }
                    } else {
                        "absent".to_string()
                    }
                }
                Err(_) => "absent (unparseable ref)".to_string(),
            };
            dropped.push((edge.to.clone(), edge.rank, reason));
            to_drop.insert(edge.to.clone());
        }
    }

    if dropped.is_empty() {
        writeln!(std::io::stdout(), "{source}: nothing to prune")?;
        return Ok(());
    }

    // 3. Remove all edges per unique dangling target (one pass each) via shared leaf
    for target in &to_drop {
        // `None` ceiling → remove every edge matching the target wildcard
        let _ = crate::dep_seq::remove(&toml_path, target, None)?;
    }

    // 4. Report dropped edges
    for (target, rank, reason) in &dropped {
        writeln!(
            std::io::stdout(),
            "{source} after {target} (rank {rank}) dropped (dangling: {reason})"
        )?;
    }
    Ok(())
}

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

    /// SL-060 / SL-066 §PHASE-04: the work-like membership predicate is the ONE
    /// widen-later guard — exactly { slice } ∪ { the 5 backlog kinds } ∪ { revision },
    /// every other admitted kind refused. REV joins as both dep/seq source and target
    /// (the IDE-010 payoff); governance docs stay off the allowlist (SL-060 invariant).
    /// SL-158 D2 / SL-161 PHASE-01: the record membership predicate
    /// over KINDS equals [`crate::kinds::RECORD`] — set equality guards
    /// both false positives (a prefix in KINDS but not in RECORD) and
    /// false negatives (a prefix in RECORD but not captured by the predicate).
    #[test]
    fn is_record_predicate_matches_kinds_record() {
        let mut from_pred: Vec<&str> = crate::integrity::KINDS
            .iter()
            .filter(|k| is_record(k.kind))
            .map(|k| k.kind.prefix)
            .collect();
        from_pred.sort_unstable();
        let mut want: Vec<&str> = crate::kinds::RECORD.to_vec();
        want.sort_unstable();
        assert_eq!(from_pred, want);
    }

    /// SL-158 D2: the admissible-target predicate = work-like ∪ record.
    /// Governance (SPEC/ADR/POL/STD) and everything else stay excluded.
    #[test]
    fn is_admissible_dep_target_is_work_like_plus_records() {
        // work-like ∪ RECORD (kinds::ADMISSIBLE_DEP_TARGETS)
        let admissible: &[&str] = crate::kinds::ADMISSIBLE_DEP_TARGETS;
        for k in integrity::KINDS
            .iter()
            .filter(|k| admissible.contains(&k.kind.prefix))
        {
            assert!(
                is_admissible_dep_target(k.kind),
                "{} is admissible as dep target",
                k.kind.prefix
            );
        }
        for k in integrity::KINDS
            .iter()
            .filter(|k| !admissible.contains(&k.kind.prefix))
        {
            assert!(
                !is_admissible_dep_target(k.kind),
                "{} must NOT be admissible as dep target",
                k.kind.prefix
            );
        }
    }

    /// SL-158 D2 / VT-6: resolve_dep_seq_src accepts a record (QUE) as target.
    #[test]
    fn resolve_dep_seq_src_accepts_record_target() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join(".doctrine")).unwrap();
        std::fs::write(root.join(crate::dtoml::DOCTRINE_TOML), "").unwrap();
        // Seed a slice as source
        seed_sl_toml(root, 1);
        // Seed a question record as target
        seed_record_toml(root, "question", "QUE", 1, "open");

        let path = resolve_dep_seq_src(root, "SL-001", "QUE-001");
        assert!(
            path.is_ok(),
            "SL needs QUE should be accepted, got: {path:?}"
        );
    }

    /// SL-158 D2 / VT-6: resolve_dep_seq_src still refuses governance target.
    #[test]
    fn resolve_dep_seq_src_refuses_governance_target() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join(".doctrine")).unwrap();
        std::fs::write(root.join(crate::dtoml::DOCTRINE_TOML), "").unwrap();
        seed_sl_toml(root, 1);
        // Seed an ADR as target (governance)
        seed_adr_toml(root, 1);

        let err = resolve_dep_seq_src(root, "SL-001", "ADR-001").unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("ADR") && msg.contains("governance"),
            "governance target should be refused with mention of governance, got: {msg}"
        );
    }

    /// SL-158 D2 / VT-6: resolve_dep_seq_src still refuses record as source.
    #[test]
    fn resolve_dep_seq_src_refuses_record_source() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join(".doctrine")).unwrap();
        std::fs::write(root.join(crate::dtoml::DOCTRINE_TOML), "").unwrap();
        seed_record_toml(root, "question", "QUE", 1, "open");
        seed_sl_toml(root, 1);

        let err = resolve_dep_seq_src(root, "QUE-001", "SL-001").unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("QUE") && msg.contains("cannot author"),
            "record source should be refused, got: {msg}"
        );
    }

    /// SL-158 D2 / VT-3: SL needs QUE with open QUE → the SL is blocked (gating).
    /// Because `resolve_dep_seq_src` admits the edge, the edge is written. The
    /// downstream priority system classifies open QUE as Gating → the SL is
    /// blocked.
    #[test]
    fn sl_needs_open_que_is_blocked() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join(".doctrine")).unwrap();
        std::fs::write(root.join(crate::dtoml::DOCTRINE_TOML), "").unwrap();
        seed_sl_toml(root, 1);
        seed_record_toml(root, "question", "QUE", 1, "open");

        // Write the needs edge
        run_needs_edge(Some(root.to_path_buf()), "SL-001", "QUE-001").unwrap();

        // Verify edge was written in SL-001's toml
        let sl_toml =
            std::fs::read_to_string(root.join(".doctrine/slice/001/slice-001.toml")).unwrap();
        assert!(
            sl_toml.contains("QUE-001"),
            "SL-001 should reference QUE-001"
        );
    }

    /// SL-158 D2 / VT-4: QUE answered → SL unblocked (terminal). The edge is
    /// still present but QUE's status-class is now Terminal, so the SL is
    /// unblocked.
    #[test]
    fn sl_needs_answered_que_is_unblocked() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join(".doctrine")).unwrap();
        std::fs::write(root.join(crate::dtoml::DOCTRINE_TOML), "").unwrap();
        seed_sl_toml(root, 1);
        // QUE starts answered (terminal)
        seed_record_toml(root, "question", "QUE", 1, "answered");

        // Write the needs edge — should be accepted
        run_needs_edge(Some(root.to_path_buf()), "SL-001", "QUE-001").unwrap();

        // Verify edge was written
        let sl_toml =
            std::fs::read_to_string(root.join(".doctrine/slice/001/slice-001.toml")).unwrap();
        assert!(
            sl_toml.contains("QUE-001"),
            "SL-001 should reference QUE-001"
        );
    }

    /// Helper: seed a knowledge record TOML in the correct directory layout.
    fn seed_record_toml(
        root: &std::path::Path,
        kind_dir: &str,
        prefix: &str,
        id: u32,
        status: &str,
    ) {
        let padded = format!("{id:03}");
        let dir = root
            .join(".doctrine")
            .join("knowledge")
            .join(kind_dir)
            .join(&padded);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(format!("record-{padded}.toml")),
            format!(
                "id = {id}\nslug = \"r{padded}\"\ntitle = \"Test {prefix}\"\n\
                 status = \"{status}\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
                 [relationships]\nsupersedes = []\nsuperseded_by = []\n",
            ),
        )
        .unwrap();
    }

    /// Helper: seed a slice TOML (local copy of relation.rs's helper, with `needs`
    /// array added for dep/seq tests — SL-158 D2).
    fn seed_sl_toml(root: &std::path::Path, id: u32) {
        let padded = format!("{id:03}");
        let dir = root.join(".doctrine").join("slice").join(&padded);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(format!("slice-{padded}.toml")),
            format!(
                "id = {id}\nslug = \"s{padded}\"\ntitle = \"Test S{padded}\"\n\
                 status = \"proposed\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
                 [relationships]\nsupersedes = []\nsuperseded_by = []\nneeds = []\n",
            ),
        )
        .unwrap();
    }

    /// Helper: seed an ADR TOML (local copy — identical to relation.rs's helper).
    fn seed_adr_toml(root: &std::path::Path, id: u32) {
        let padded = format!("{id:03}");
        let dir = root.join(".doctrine").join("adr").join(&padded);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join(format!("adr-{padded}.toml")),
            format!(
                "id = {id}\nslug = \"a{padded}\"\ntitle = \"Test A{padded}\"\n\
                 status = \"accepted\"\ncreated = \"2026-01-01\"\nupdated = \"2026-01-01\"\n\
                 [relationships]\nsupersedes = []\nsuperseded_by = []\n",
            ),
        )
        .unwrap();
    }

    #[test]
    fn is_work_like_is_exactly_slice_plus_backlog_plus_revision() {
        // The work-like set: slice + the five backlog kinds + revision.
        assert!(is_work_like(&slice::SLICE_KIND));
        for k in integrity::KINDS
            .iter()
            .filter(|k| matches!(k.kind.prefix, "ISS" | "IMP" | "CHR" | "RSK" | "IDE" | "REV"))
        {
            assert!(is_work_like(k.kind), "{} is work-like", k.kind.prefix);
        }
        // Every OTHER admitted kind in the corpus table is refused (gov / spec / req /
        // review / reconciliation / knowledge) — the closed allowlist.
        for k in integrity::KINDS
            .iter()
            .filter(|k| !crate::kinds::WORK_LIKE.contains(&k.kind.prefix))
        {
            assert!(
                !is_work_like(k.kind),
                "{} must NOT be work-like (off the allowlist)",
                k.kind.prefix
            );
        }
    }
}