reposix-core 0.12.0

Shared types for reposix: BackendConnector trait, Record/Project/RemoteSpec, Tainted<T>.
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
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
//! Record (the unit a partial-clone working-tree file represents) types.
//!
//! A `Record` may be an issue (sim, GitHub), a JIRA issue, a Confluence page,
//! or any other backend-specific unit that maps onto a single `.md` file.

use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::error::{Error, Result};

/// A non-negative integer record identifier within a project. We deliberately avoid u32 so the
/// type signals that the simulator may use a much larger ID space without API breakage.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RecordId(pub u64);

impl std::fmt::Display for RecordId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Workflow state. Modeled after a Jira-flavored superset of GitHub Issues.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RecordStatus {
    /// Newly filed, not yet triaged.
    Open,
    /// Actively being worked on.
    InProgress,
    /// Awaiting review.
    InReview,
    /// Closed successfully.
    Done,
    /// Closed without resolution.
    WontFix,
}

impl RecordStatus {
    /// Render to canonical YAML scalar form.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Open => "open",
            Self::InProgress => "in_progress",
            Self::InReview => "in_review",
            Self::Done => "done",
            Self::WontFix => "wont_fix",
        }
    }
}

/// A single issue. Serialized to disk as a Markdown file with YAML frontmatter; the body of the
/// markdown is `body`, everything else lives in the frontmatter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Record {
    /// Project-scoped unique id.
    pub id: RecordId,
    /// Single-line summary.
    pub title: String,
    /// Workflow state.
    pub status: RecordStatus,
    /// Optional assignee (free-form string; e.g. `"agent-alpha"`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
    /// Free-form labels.
    #[serde(default)]
    pub labels: Vec<String>,
    /// Server-managed creation timestamp.
    pub created_at: DateTime<Utc>,
    /// Server-managed last-update timestamp.
    pub updated_at: DateTime<Utc>,
    /// Optimistic-concurrency version. Bumped on every server-side update.
    #[serde(default)]
    pub version: u64,
    /// Free-form Markdown body.
    #[serde(default)]
    pub body: String,
    /// Parent in a hierarchy-supporting backend (currently Confluence only).
    ///
    /// Always `None` for sim and GitHub. When `Some`, is the parent page/issue
    /// id as reported by the backend. Historically used to synthesize a
    /// `tree/` overlay (pre-v0.9.0); preserved as a metadata field on
    /// the partial-clone working tree.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<RecordId>,
    /// Backend-specific metadata that does not fit the canonical 5-field schema.
    ///
    /// Keys are backend-defined strings (e.g. `"jira_key"`, `"issue_type"`).
    /// Values are arbitrary YAML-compatible scalars or nested structures.
    /// Empty map is omitted from serialized frontmatter (does not appear in `.md` files).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extensions: BTreeMap<String, serde_yaml::Value>,
}

/// Frontmatter helpers — round-trip an [`Record`] through `---\n<yaml>\n---\n<body>` form.
pub mod frontmatter {
    use std::collections::BTreeMap;

    use super::{DateTime, Error, Record, Result, Utc};
    use serde::{Deserialize, Serialize};

    /// Subset of [`Record`] that lives inside the frontmatter (everything except `body`).
    #[derive(Debug, Serialize, Deserialize)]
    struct Frontmatter {
        id: super::RecordId,
        title: String,
        status: super::RecordStatus,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        assignee: Option<String>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        labels: Vec<String>,
        created_at: DateTime<Utc>,
        updated_at: DateTime<Utc>,
        #[serde(default)]
        version: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        parent_id: Option<super::RecordId>,
        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
        extensions: BTreeMap<String, serde_yaml::Value>,
    }

    /// Render an [`Record`] to its on-disk form.
    ///
    /// # Errors
    /// Returns [`Error::Yaml`] if the frontmatter cannot be serialized (e.g. a label contains
    /// a character no YAML representation can encode).
    pub fn render(issue: &Record) -> Result<String> {
        let fm = Frontmatter {
            id: issue.id,
            title: issue.title.clone(),
            status: issue.status,
            assignee: issue.assignee.clone(),
            labels: issue.labels.clone(),
            created_at: issue.created_at,
            updated_at: issue.updated_at,
            version: issue.version,
            parent_id: issue.parent_id,
            extensions: issue.extensions.clone(),
        };
        let yaml = serde_yaml::to_string(&fm)?;
        let mut out = String::with_capacity(yaml.len() + issue.body.len() + 16);
        out.push_str("---\n");
        out.push_str(&yaml);
        out.push_str("---\n");
        out.push_str(&issue.body);
        if !issue.body.ends_with('\n') {
            out.push('\n');
        }
        Ok(out)
    }

    /// Parse on-disk Markdown+frontmatter into an [`Record`].
    ///
    /// # Errors
    /// Returns [`Error::InvalidRecord`] if the file does not start with a `---` fence or the
    /// fence is malformed; [`Error::Yaml`] if the frontmatter YAML is invalid.
    pub fn parse(text: &str) -> Result<Record> {
        let body_start;
        let yaml = if let Some(rest) = text.strip_prefix("---\n") {
            // Find closing fence — accept either `---\n` or `---` at EOF.
            if let Some(end) = rest.find("\n---\n") {
                body_start = end + 5; // length of "\n---\n"
                &rest[..end]
            } else if let Some(end) = rest.find("\n---") {
                if rest[end + 4..].is_empty() {
                    body_start = end + 4;
                    &rest[..end]
                } else {
                    return Err(Error::InvalidRecord(
                        "frontmatter close fence not followed by newline".into(),
                    ));
                }
            } else {
                return Err(Error::InvalidRecord(
                    "frontmatter open without close fence".into(),
                ));
            }
        } else {
            return Err(Error::InvalidRecord(
                "missing frontmatter open fence".into(),
            ));
        };
        let fm: Frontmatter = serde_yaml::from_str(yaml)?;
        let body = rest_after(text, body_start).to_owned();
        Ok(Record {
            id: fm.id,
            title: fm.title,
            status: fm.status,
            assignee: fm.assignee,
            labels: fm.labels,
            created_at: fm.created_at,
            updated_at: fm.updated_at,
            version: fm.version,
            body,
            parent_id: fm.parent_id,
            extensions: fm.extensions,
        })
    }

    /// Re-extract just the YAML map and re-emit as canonical JSON. Useful for the remote helper
    /// when diffing frontmatter across versions.
    ///
    /// # Errors
    /// Propagates any error from [`parse`] or from JSON serialization.
    pub fn yaml_to_json_value(text: &str) -> Result<serde_json::Value> {
        let issue = parse(text)?;
        Ok(serde_json::to_value(issue)?)
    }

    fn rest_after(text: &str, body_start_in_rest: usize) -> &str {
        // `text` begins with "---\n", which is 4 bytes; the parse function recorded
        // body_start as offset within `rest = text[4..]`, so add 4 to index into `text`.
        let abs = 4 + body_start_in_rest;
        &text[abs.min(text.len())..]
    }
}

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

    fn sample() -> Record {
        let t = Utc.with_ymd_and_hms(2026, 4, 13, 0, 0, 0).unwrap();
        Record {
            id: RecordId(123),
            title: "thing is broken".into(),
            status: RecordStatus::InProgress,
            assignee: Some("agent-alpha".into()),
            labels: vec!["bug".into(), "p1".into()],
            created_at: t,
            updated_at: t,
            version: 3,
            body: "Steps to reproduce:\n1. do the thing\n2. observe brokenness\n".into(),
            parent_id: None,
            extensions: std::collections::BTreeMap::new(),
        }
    }

    #[test]
    fn frontmatter_roundtrips() {
        let original = sample();
        let rendered = frontmatter::render(&original).expect("render");
        assert!(rendered.starts_with("---\n"));
        let parsed = frontmatter::parse(&rendered).expect("parse");
        assert_eq!(parsed.id, original.id);
        assert_eq!(parsed.title, original.title);
        assert_eq!(parsed.status as u8, original.status as u8);
        assert_eq!(parsed.body, original.body);
        assert_eq!(parsed.version, original.version);
    }

    #[test]
    fn missing_open_fence_is_rejected() {
        let bad = "no frontmatter here\n";
        assert!(matches!(
            frontmatter::parse(bad),
            Err(Error::InvalidRecord(_))
        ));
    }

    #[test]
    fn parent_id_roundtrips_through_json_when_some() {
        let mut iss = sample();
        iss.parent_id = Some(RecordId(42));
        let json = serde_json::to_string(&iss).unwrap();
        assert!(
            json.contains("\"parent_id\":42"),
            "expected `\"parent_id\":42` in JSON, got: {json}"
        );
        let back: Record = serde_json::from_str(&json).unwrap();
        assert_eq!(back.parent_id, Some(RecordId(42)));
    }

    #[test]
    fn parent_id_omitted_when_none() {
        let iss = sample(); // parent_id: None
        let json = serde_json::to_string(&iss).unwrap();
        assert!(
            !json.contains("parent_id"),
            "parent_id should be omitted when None, got: {json}"
        );
    }

    #[test]
    fn parent_id_default_on_missing_field() {
        // Old JSON payload, no parent_id field at all — must deserialize with None.
        let json = r#"{"id":1,"title":"t","status":"open","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}"#;
        let iss: Record = serde_json::from_str(json).unwrap();
        assert_eq!(iss.parent_id, None);
    }

    #[test]
    fn parent_id_roundtrips_through_frontmatter_when_some() {
        let mut iss = sample();
        iss.parent_id = Some(RecordId(777));
        let rendered = frontmatter::render(&iss).expect("render");
        assert!(
            rendered.contains("parent_id: 777"),
            "expected `parent_id: 777` in YAML, got: {rendered}"
        );
        let parsed = frontmatter::parse(&rendered).expect("parse");
        assert_eq!(parsed.parent_id, Some(RecordId(777)));
    }

    #[test]
    fn parent_id_omitted_from_frontmatter_when_none() {
        let iss = sample(); // parent_id: None
        let rendered = frontmatter::render(&iss).expect("render");
        assert!(
            !rendered.contains("parent_id"),
            "parent_id should be omitted from YAML when None, got: {rendered}"
        );
    }

    #[test]
    fn frontmatter_renders_parent_id_when_some() {
        // Plan 13-B3 SC-required test: the rendered YAML contains the exact line
        // `parent_id: 42` (serde_yaml emits numeric scalars unquoted).
        let mut iss = sample();
        iss.parent_id = Some(RecordId(42));
        let rendered = frontmatter::render(&iss).expect("render");
        assert!(
            rendered.contains("parent_id: 42\n"),
            "expected exact line `parent_id: 42` in YAML, got: {rendered}"
        );
    }

    #[test]
    fn frontmatter_parses_parent_id_when_present() {
        // A frontmatter block authored by a hierarchy-aware backend (e.g. Confluence)
        // round-trips through parse with the numeric id preserved.
        let text = "---\n\
id: 1\n\
title: child page\n\
status: open\n\
created_at: 2026-04-14T00:00:00Z\n\
updated_at: 2026-04-14T00:00:00Z\n\
version: 1\n\
parent_id: 42\n\
---\n\
body here.\n";
        let iss = frontmatter::parse(text).expect("parse");
        assert_eq!(iss.parent_id, Some(RecordId(42)));
        assert_eq!(iss.id, RecordId(1));
        assert_eq!(iss.title, "child page");
    }

    #[test]
    fn frontmatter_parses_legacy_without_parent_id() {
        // Fixture shape matches a pre-Phase-13 on-disk file: no `parent_id:` key at
        // all. The `#[serde(default)]` attribute must fill it in with `None` rather
        // than erroring. This is the load-bearing backward-compat test.
        let text = "---\n\
id: 1\n\
title: Legacy issue\n\
status: open\n\
created_at: 2025-01-01T00:00:00Z\n\
updated_at: 2025-01-01T00:00:00Z\n\
version: 1\n\
---\n\
Body goes here.\n";
        let iss = frontmatter::parse(text).expect("legacy frontmatter must parse");
        assert_eq!(iss.parent_id, None);
        assert_eq!(iss.title, "Legacy issue");
    }

    #[test]
    fn frontmatter_roundtrip_with_parent() {
        // Deep-equality roundtrip: parse(render(issue)) yields the same Issue.
        // Catches any drift between the public `Record` struct and the private
        // `Frontmatter` DTO.
        let mut original = sample();
        original.parent_id = Some(RecordId(131_192));
        let rendered = frontmatter::render(&original).expect("render");
        let parsed = frontmatter::parse(&rendered).expect("parse");
        assert_eq!(parsed.id, original.id);
        assert_eq!(parsed.title, original.title);
        assert_eq!(parsed.status as u8, original.status as u8);
        assert_eq!(parsed.assignee, original.assignee);
        assert_eq!(parsed.labels, original.labels);
        assert_eq!(parsed.created_at, original.created_at);
        assert_eq!(parsed.updated_at, original.updated_at);
        assert_eq!(parsed.version, original.version);
        assert_eq!(parsed.body, original.body);
        assert_eq!(parsed.parent_id, Some(RecordId(131_192)));
    }

    #[test]
    fn frontmatter_roundtrip_without_parent() {
        // Deep-equality roundtrip for the None branch — verifies `skip_serializing_if`
        // doesn't accidentally drop other fields and that the deserialize default
        // kicks in on the return trip.
        let original = sample(); // parent_id: None
        let rendered = frontmatter::render(&original).expect("render");
        let parsed = frontmatter::parse(&rendered).expect("parse");
        assert_eq!(parsed.id, original.id);
        assert_eq!(parsed.title, original.title);
        assert_eq!(parsed.status as u8, original.status as u8);
        assert_eq!(parsed.assignee, original.assignee);
        assert_eq!(parsed.labels, original.labels);
        assert_eq!(parsed.created_at, original.created_at);
        assert_eq!(parsed.updated_at, original.updated_at);
        assert_eq!(parsed.version, original.version);
        assert_eq!(parsed.body, original.body);
        assert_eq!(parsed.parent_id, None);
    }

    #[test]
    fn extensions_empty_omitted_from_yaml() {
        // An Issue with no extensions must not emit the word "extensions" in YAML.
        let iss = sample(); // extensions: BTreeMap::new()
        let rendered = frontmatter::render(&iss).expect("render");
        assert!(
            !rendered.contains("extensions"),
            "empty extensions must be omitted from YAML, got: {rendered}"
        );
    }

    #[test]
    fn extensions_roundtrip() {
        // Non-empty extensions survive a render→parse cycle with value equality.
        let mut iss = sample();
        iss.extensions
            .insert("foo".into(), serde_yaml::Value::from(42_i64));
        iss.extensions
            .insert("bar".into(), serde_yaml::Value::from("x"));
        let rendered = frontmatter::render(&iss).expect("render");
        assert!(
            rendered.contains("extensions"),
            "non-empty extensions must appear in YAML, got: {rendered}"
        );
        let parsed = frontmatter::parse(&rendered).expect("parse");
        assert_eq!(
            parsed.extensions, iss.extensions,
            "extensions must round-trip through render/parse"
        );
    }

    #[test]
    fn extensions_defaults_to_empty_on_parse() {
        // A legacy frontmatter without an `extensions:` key must parse to an empty map.
        let text = "---\n\
id: 1\n\
title: Legacy issue\n\
status: open\n\
created_at: 2025-01-01T00:00:00Z\n\
updated_at: 2025-01-01T00:00:00Z\n\
version: 1\n\
---\n\
Body goes here.\n";
        let iss = frontmatter::parse(text).expect("legacy frontmatter must parse");
        assert!(
            iss.extensions.is_empty(),
            "extensions must default to empty on legacy parse, got: {:?}",
            iss.extensions
        );
    }
}