cartulary 0.3.0-alpha.1

The knowledge layer of your project — decisions, issues, docs, all in one place.
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
use crate::domain::model::issue::{IssueEdit, IssueLink};
use crate::domain::model::record_ref::IssueRef;
use crate::domain::usecases::edit::issue::commit_issue_edits;
use crate::domain::usecases::issue::cycle_detection::{
    detect_cycle, would_introduce_second_parent,
};
use crate::domain::usecases::issue::IssueRepository;

/// Add a link to an existing issue.
///
/// The link is appended to the source's `links` and the matching inverse
/// pointer is cascaded onto the target so both files are self-contained
/// (DDR-018QWJVHRH35B § principles). Inverse writes are idempotent and
/// unconditional — they fire regardless of either issue's status.
///
/// Returns `Err` if the source is not found, or if the user requested a
/// system-only verb (`blocked-by`, `child-of`).
///
/// Hierarchical relationships (cf. [`IssueRelationship::is_hierarchical`])
/// trigger two extra invariants enforced at link time:
///   - the link must not create a cycle (rejected with a path-naming error);
///   - the target must not already be the child of a different issue
///     (rejected naming the existing parent).
///
/// [`IssueRelationship::is_hierarchical`]: crate::domain::model::issue::IssueRelationship::is_hierarchical
pub fn link_issue(
    repo: &dyn IssueRepository,
    id: &IssueRef,
    link: IssueLink,
) -> anyhow::Result<()> {
    let inverse = link.relationship.inverse();

    // Existence check + hierarchical validation are pre-emission concerns.
    if repo.find_by_id(id)?.is_none() {
        anyhow::bail!("issue {id} not found");
    }
    if link.relationship.is_hierarchical() {
        let all_issues = repo.list()?.into_vec();
        if let Some(cycle_path) = detect_cycle(id, &link.target, &all_issues) {
            anyhow::bail!("cycle detected: {cycle_path}");
        }
        if let Some(existing_parent) = would_introduce_second_parent(id, &link.target, &all_issues)
        {
            anyhow::bail!(
                "{} already has a parent ({existing_parent}); a child has at most one parent",
                link.target,
            );
        }
    }

    // Target first, source second — per DDR-018QWJVHRH35B atomicity: a
    // partial-save failure leaves a detectable asymmetry rather than an
    // orphaned forward link.
    let target = link.target.clone();
    commit_issue_edits(
        repo,
        vec![
            IssueEdit::AddLink {
                issue: target,
                link: IssueLink {
                    target: id.clone(),
                    relationship: inverse,
                },
            },
            IssueEdit::AddLink {
                issue: id.clone(),
                link,
            },
        ],
    )?;
    Ok(())
}

/// Remove the matching `(target, relationship)` link from an existing
/// issue. Errors if the issue is not found or no such link exists.
///
/// The matching inverse pointer on the target is removed too (cascade)
/// so both endpoints lose the relation atomically per DDR-018QWJVHRH35B.
/// A missing inverse on the target is tolerated — `cartu check` is the
/// canonical reporter for asymmetric state.
pub fn unlink_issue(
    repo: &dyn IssueRepository,
    id: &IssueRef,
    link: IssueLink,
) -> anyhow::Result<()> {
    let inverse = link.relationship.inverse();

    // Forward-link existence is a precondition error, not silent.
    let issue = repo
        .find_by_id(id)?
        .ok_or_else(|| anyhow::anyhow!("issue {id} not found"))?;
    if issue.links.with_removed(&link).is_none() {
        anyhow::bail!(
            "no {} link from {} to {}",
            link.relationship,
            id,
            link.target
        );
    }

    let target = link.target.clone();
    commit_issue_edits(
        repo,
        vec![
            IssueEdit::RemoveLink {
                issue: target,
                link: IssueLink {
                    target: id.clone(),
                    relationship: inverse,
                },
            },
            IssueEdit::RemoveLink {
                issue: id.clone(),
                link,
            },
        ],
    )?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::usecases::issue::tests::{
        feature, issue_link, FakeIssueRepository, IssueFixture,
    };

    fn scenario() -> Scenario {
        Scenario {
            repo: FakeIssueRepository::new(),
        }
    }

    struct Scenario {
        repo: FakeIssueRepository,
    }

    impl Scenario {
        fn given(mut self, fixture: IssueFixture) -> Self {
            let raw = fixture
                .id
                .as_deref()
                .expect("given() requires an explicit id — use .with_id()")
                .to_string();
            let numeric =
                IssueRef::new(&raw).unwrap_or_else(|_| panic!("given(): invalid id {raw:?}"));
            self.repo.push_issue(fixture.build(numeric));
            self
        }

        fn when_link(self, id: &str, target: &str, relationship: &str) -> Outcome {
            let id_ref = IssueRef::new(id).unwrap_or_else(|_| panic!("invalid issue ref {id:?}"));
            let result = link_issue(&self.repo, &id_ref, issue_link(target, relationship));
            Outcome {
                repo: self.repo,
                result,
            }
        }

        fn when_unlink(self, id: &str, target: &str, relationship: &str) -> Outcome {
            let id_ref = IssueRef::new(id).unwrap_or_else(|_| panic!("invalid issue ref {id:?}"));
            let result = unlink_issue(&self.repo, &id_ref, issue_link(target, relationship));
            Outcome {
                repo: self.repo,
                result,
            }
        }
    }

    struct Outcome {
        repo: FakeIssueRepository,
        result: anyhow::Result<()>,
    }

    impl Outcome {
        fn then_saved_link_count(self, expected: usize) -> Self {
            self.result.as_ref().expect("expected Ok, got Err");
            let saved = self.repo.last_saved().expect("expected a save, got none");
            assert_eq!(
                saved.links.len(),
                expected,
                "expected {expected} links, got {}",
                saved.links.len()
            );
            self
        }

        fn then_saved_link_target(self, index: usize, expected: &str) -> Self {
            let saved = self.repo.last_saved().expect("expected a save, got none");
            assert_eq!(
                saved.links[index].target.as_str(),
                expected,
                "expected link[{index}].target = {expected:?}"
            );
            self
        }

        fn then_err_contains(self, substring: &str) {
            let msg = self.result.expect_err("expected Err, got Ok").to_string();
            assert!(
                msg.contains(substring),
                "expected error containing {substring:?}, got {msg:?}"
            );
        }
    }

    #[test]
    fn adding_a_link_appends_it_to_the_issue() {
        scenario()
            .given(feature("Add login").with_id("ISSUE-0001"))
            .when_link("ISSUE-0001", "ISSUE-0002", "blocked-by")
            .then_saved_link_count(1)
            .then_saved_link_target(0, "ISSUE-0002");
    }

    #[test]
    fn linking_an_unknown_issue_returns_an_error() {
        scenario()
            .when_link("ISSUE-0099", "ISSUE-0001", "blocked-by")
            .then_err_contains("not found");
    }

    #[test]
    fn adding_a_link_preserves_existing_links() {
        scenario()
            .given(
                feature("Add login")
                    .with_id("ISSUE-0001")
                    .with_link("ISSUE-0001", "parent-of"),
            )
            .when_link("ISSUE-0001", "ISSUE-0002", "blocked-by")
            .then_saved_link_count(2);
    }

    #[test]
    fn adding_a_parent_of_link_succeeds_when_target_is_orphan() {
        scenario()
            .given(feature("Epic").with_id("ISSUE-0001"))
            .given(feature("Story").with_id("ISSUE-0002"))
            .when_link("ISSUE-0001", "ISSUE-0002", "parent-of")
            .then_saved_link_count(1)
            .then_saved_link_target(0, "ISSUE-0002");
    }

    #[test]
    fn adding_a_second_parent_to_a_child_is_rejected() {
        scenario()
            .given(
                feature("Epic A")
                    .with_id("ISSUE-0001")
                    .with_link("ISSUE-0003", "parent-of"),
            )
            .given(feature("Epic B").with_id("ISSUE-0002"))
            .given(
                feature("Story")
                    .with_id("ISSUE-0003")
                    .with_link("ISSUE-0001", "child-of"),
            )
            .when_link("ISSUE-0002", "ISSUE-0003", "parent-of")
            .then_err_contains("already has a parent");
    }

    #[test]
    fn a_parent_of_link_that_would_create_a_cycle_is_rejected() {
        scenario()
            .given(
                feature("A")
                    .with_id("ISSUE-0001")
                    .with_link("ISSUE-0002", "parent-of"),
            )
            .given(feature("B").with_id("ISSUE-0002"))
            .when_link("ISSUE-0002", "ISSUE-0001", "parent-of")
            .then_err_contains("cycle detected");
    }

    #[test]
    fn unlink_removes_the_matching_edge() {
        scenario()
            .given(
                feature("Add login")
                    .with_id("ISSUE-0001")
                    .with_link("ISSUE-0002", "blocked-by"),
            )
            .when_unlink("ISSUE-0001", "ISSUE-0002", "blocked-by")
            .then_saved_link_count(0);
    }

    #[test]
    fn unlink_keeps_other_edges() {
        scenario()
            .given(
                feature("Add login")
                    .with_id("ISSUE-0001")
                    .with_link("ISSUE-0002", "blocked-by")
                    .with_link("ISSUE-0003", "parent-of"),
            )
            .when_unlink("ISSUE-0001", "ISSUE-0002", "blocked-by")
            .then_saved_link_count(1)
            .then_saved_link_target(0, "ISSUE-0003");
    }

    #[test]
    fn unlink_a_missing_edge_errors() {
        scenario()
            .given(feature("Add login").with_id("ISSUE-0001"))
            .when_unlink("ISSUE-0001", "ISSUE-0002", "blocked-by")
            .then_err_contains("no blocked-by link");
    }

    #[test]
    fn unlink_an_unknown_issue_errors() {
        scenario()
            .when_unlink("ISSUE-0099", "ISSUE-0001", "blocked-by")
            .then_err_contains("not found");
    }

    #[test]
    fn a_self_parent_of_link_is_rejected() {
        scenario()
            .given(feature("Solo").with_id("ISSUE-0001"))
            .when_link("ISSUE-0001", "ISSUE-0001", "parent-of")
            .then_err_contains("cycle detected");
    }

    // ── Cascade (DDR-018QWJVHRH35B § files self-contained) ────────────────

    impl Outcome {
        fn then_target_has_inverse(self, target_id: &str, verb: &str) -> Self {
            let target_ref =
                IssueRef::new(target_id).unwrap_or_else(|_| panic!("invalid id {target_id:?}"));
            let saved = self
                .repo
                .saved_for(&target_ref)
                .unwrap_or_else(|| panic!("expected a save for {target_id}, got none"));
            assert!(
                saved.links.iter().any(|l| l.relationship.as_str() == verb),
                "target {target_id} missing inverse {verb}; saved links = {:?}",
                saved
                    .links
                    .iter()
                    .map(|l| l.relationship.as_str())
                    .collect::<Vec<_>>()
            );
            self
        }

        fn then_no_save_for(self, target_id: &str) -> Self {
            let target_ref =
                IssueRef::new(target_id).unwrap_or_else(|_| panic!("invalid id {target_id:?}"));
            assert!(
                self.repo.saved_for(&target_ref).is_none(),
                "expected no save for {target_id}, but one was recorded"
            );
            self
        }
    }

    #[test]
    fn depends_on_writes_blocked_by_on_target() {
        scenario()
            .given(feature("A").with_id("ISSUE-0001"))
            .given(feature("B").with_id("ISSUE-0002"))
            .when_link("ISSUE-0001", "ISSUE-0002", "blocked-by")
            .then_target_has_inverse("ISSUE-0002", "blocks");
    }

    #[test]
    fn parent_of_writes_child_of_on_target() {
        scenario()
            .given(feature("Epic").with_id("ISSUE-0001"))
            .given(feature("Story").with_id("ISSUE-0002"))
            .when_link("ISSUE-0001", "ISSUE-0002", "parent-of")
            .then_target_has_inverse("ISSUE-0002", "child-of");
    }

    #[test]
    fn cascade_fires_even_when_target_is_terminal_status() {
        scenario()
            .given(feature("A").with_id("ISSUE-0001"))
            .given(feature("B").with_id("ISSUE-0002").status("closed"))
            .when_link("ISSUE-0001", "ISSUE-0002", "blocked-by")
            .then_target_has_inverse("ISSUE-0002", "blocks");
    }

    #[test]
    fn cascade_is_idempotent_when_inverse_already_present() {
        scenario()
            .given(feature("A").with_id("ISSUE-0001"))
            .given(
                feature("B")
                    .with_id("ISSUE-0002")
                    .with_link("ISSUE-0001", "blocks"),
            )
            .when_link("ISSUE-0001", "ISSUE-0002", "blocked-by")
            .then_no_save_for("ISSUE-0002");
    }

    #[test]
    fn unlink_removes_inverse_on_target() {
        let outcome = scenario()
            .given(
                feature("A")
                    .with_id("ISSUE-0001")
                    .with_link("ISSUE-0002", "blocked-by"),
            )
            .given(
                feature("B")
                    .with_id("ISSUE-0002")
                    .with_link("ISSUE-0001", "blocks"),
            )
            .when_unlink("ISSUE-0001", "ISSUE-0002", "blocked-by");
        outcome.result.as_ref().expect("expected Ok, got Err");
        let target_ref = IssueRef::new("ISSUE-0002").unwrap();
        let target_saved = outcome
            .repo
            .saved_for(&target_ref)
            .expect("cascade should have saved the target");
        assert!(
            target_saved.links.is_empty(),
            "expected target's blocked-by removed; got: {:?}",
            target_saved.links
        );
    }
}