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
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
use std::collections::BTreeMap;

use crate::domain::model::body::Body;
use crate::domain::model::entry_locator::EntryLocator;
use crate::domain::model::entry_origin::EntryOrigin;
use crate::domain::model::event::State;
use crate::domain::model::event::{Event, EventAction};
use crate::domain::model::issue::{Issue, Tracker};
use crate::domain::model::record_ref::IssueRef;
use crate::domain::model::status::Status;
use crate::domain::model::tag_list::TagList;
use crate::domain::model::temporal::iso_date::IsoDate;
use crate::domain::model::temporal::timestamp::Timestamp;
use crate::domain::model::title::Title;
use crate::domain::usecases::source::IssueSource;

use super::http_client::HttpClient;

/// GitLab adapter that fetches issues via the GitLab REST API.
pub struct GitLabSource<'a> {
    client: &'a dyn HttpClient,
    base_url: String,
    project: String,
    token: String,
    status_map: BTreeMap<String, String>,
    id_prefix: String,
}

impl<'a> GitLabSource<'a> {
    pub fn new(client: &'a dyn HttpClient, base_url: &str, project: &str, token: &str) -> Self {
        GitLabSource {
            client,
            base_url: base_url.trim_end_matches('/').to_string(),
            project: project.to_string(),
            token: token.to_string(),
            status_map: BTreeMap::new(),
            id_prefix: "ISSUE".to_string(),
        }
    }

    /// Override the default GitLab → cartulary status mapping.
    ///
    /// Keys are GitLab state names (`"opened"`, `"closed"`); values are the
    /// cartulary status names to use.
    pub fn with_status_map(mut self, map: BTreeMap<String, String>) -> Self {
        self.status_map = map;
        self
    }

    /// Override the issue id prefix (defaults to `ISSUE`). Matches the
    /// `issues.id_prefix` from `cartulary.toml` so synthesised ids align
    /// with the rest of the workspace.
    pub fn with_id_prefix(mut self, prefix: &str) -> Self {
        self.id_prefix = prefix.to_string();
        self
    }

    /// Resolve a GitLab state name to a cartulary status name.
    fn map_state(&self, gitlab_state: &str) -> String {
        if let Some(mapped) = self.status_map.get(gitlab_state) {
            return mapped.clone();
        }
        match gitlab_state {
            "opened" => "open".to_string(),
            "closed" => "closed".to_string(),
            other => other.to_string(),
        }
    }

    fn api_url(&self, path: &str) -> String {
        let encoded_project = self.project.replace('/', "%2F");
        format!(
            "{}/api/v4/projects/{}/{}",
            self.base_url, encoded_project, path
        )
    }

    fn headers(&self) -> Vec<(&str, &str)> {
        vec![("PRIVATE-TOKEN", &self.token)]
    }

    /// Maximum number of pages to fetch — safety guard against infinite pagination.
    const MAX_PAGES: u32 = 1000;

    fn fetch_all_issues_json(&self) -> anyhow::Result<Vec<serde_json::Value>> {
        let mut all = Vec::new();
        let mut page = 1u32;

        loop {
            if page > Self::MAX_PAGES {
                anyhow::bail!(
                    "pagination limit reached ({} pages, {} issues fetched) — aborting",
                    Self::MAX_PAGES,
                    all.len()
                );
            }
            let url = format!("{}?per_page=100&page={page}", self.api_url("issues"));
            let headers = self.headers();
            let resp = self.client.get(&url, &headers)?;

            if resp.status != 200 {
                anyhow::bail!(
                    "GitLab API returned status {}: {}",
                    resp.status,
                    resp.body.chars().take(200).collect::<String>()
                );
            }

            let items: Vec<serde_json::Value> = serde_json::from_str(&resp.body)?;
            if items.is_empty() {
                break;
            }
            all.extend(items);
            page += 1;
        }

        Ok(all)
    }
}

impl GitLabSource<'_> {
    /// Fetch state events for a single issue and return them as domain events.
    ///
    /// GitLab endpoint: `GET /projects/:id/issues/:iid/resource_state_events`
    /// Returns events like `{"state": "closed", "created_at": "..."}`.
    fn fetch_state_events(&self, iid: u32) -> anyhow::Result<Vec<Event>> {
        let url = format!(
            "{}?per_page=100",
            self.api_url(&format!("issues/{iid}/resource_state_events"))
        );
        let headers = self.headers();
        let resp = self.client.get(&url, &headers)?;

        if resp.status != 200 {
            return Ok(vec![]); // silently skip on error
        }

        let items: Vec<serde_json::Value> = serde_json::from_str(&resp.body)?;
        let mut events = Vec::new();

        for item in &items {
            let state = match item.get("state").and_then(|v| v.as_str()) {
                Some(s) => s,
                None => continue,
            };
            let ts_raw = match item.get("created_at").and_then(|v| v.as_str()) {
                Some(s) => s,
                None => continue,
            };
            let ts = match Timestamp::new(&normalize_gitlab_timestamp(ts_raw)) {
                Ok(t) => t,
                Err(_) => continue,
            };

            let (from, to) = match state {
                "closed" => (self.map_state("opened"), self.map_state("closed")),
                "reopened" => (self.map_state("closed"), self.map_state("opened")),
                _ => continue,
            };

            events.push(Event {
                timestamp: ts,
                action: EventAction::StatusChanged {
                    from: State::new(&from)
                        .map_err(|e| anyhow::anyhow!("invalid state '{from}': {e}"))?,
                    to: State::new(&to)
                        .map_err(|e| anyhow::anyhow!("invalid state '{to}': {e}"))?,
                },
            });
        }

        Ok(events)
    }
}

impl IssueSource for GitLabSource<'_> {
    fn list_issues(&self) -> anyhow::Result<Vec<Issue>> {
        let items = self.fetch_all_issues_json()?;
        let mut issues = Vec::new();

        for item in &items {
            match self.parse_issue(item) {
                Ok(mut issue) => {
                    let iid = item.get("iid").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
                    match self.fetch_state_events(iid) {
                        Ok(state_events) => {
                            for event in state_events {
                                issue.events.push(event);
                            }
                            // Update status from last event
                            if let Some(latest) = issue.events.latest_state() {
                                issue.status = Status::unresolved(latest.as_str());
                            }
                        }
                        Err(e) => {
                            eprintln!("warning: could not fetch events for #{iid}: {e}");
                        }
                    }
                    issues.push(issue);
                }
                Err(e) => {
                    let iid = item.get("iid").and_then(|v| v.as_u64()).unwrap_or(0);
                    eprintln!("warning: skipping GitLab issue #{iid}: {e}");
                }
            }
        }

        Ok(issues)
    }
}

impl GitLabSource<'_> {
    fn parse_issue(&self, item: &serde_json::Value) -> anyhow::Result<Issue> {
        let iid = item
            .get("iid")
            .and_then(|v| v.as_u64())
            .ok_or_else(|| anyhow::anyhow!("missing iid"))? as u32;

        let title_str = item
            .get("title")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("missing title"))?;

        let state = item
            .get("state")
            .and_then(|v| v.as_str())
            .unwrap_or("opened");

        let status_name = self.map_state(state);

        let created_at = item
            .get("created_at")
            .and_then(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("missing created_at"))?;

        let description = item
            .get("description")
            .and_then(|v| v.as_str())
            .unwrap_or("");

        let tags: TagList = item
            .get("labels")
            .and_then(|v| v.as_array())
            .map(|labels| {
                labels
                    .iter()
                    .filter_map(|label| label.as_str())
                    .filter_map(|l| crate::domain::model::tag::Tag::new(l).ok())
                    .collect()
            })
            .unwrap_or_default();

        let assignee = item
            .get("assignee")
            .and_then(|v| v.get("username"))
            .and_then(|v| v.as_str())
            .and_then(|u| crate::domain::model::issue::Assignee::new(u).ok());

        let due_date = item
            .get("due_date")
            .and_then(|v| v.as_str())
            .and_then(|d| IsoDate::new(d).ok());

        let id = IssueRef::new(format!("{}-{iid:04}", self.id_prefix))
            .map_err(|e| anyhow::anyhow!("invalid issue ref: {e}"))?;
        let tracker = Tracker::new(&format!("gitlab:{}#{iid}", self.project))?;
        let normalized_ts = normalize_gitlab_timestamp(created_at);
        let timestamp = Timestamp::new(&normalized_ts)
            .map_err(|e| anyhow::anyhow!("invalid timestamp: {e}"))?;
        let status = Status::unresolved(&status_name);
        let initial_state = State::new(&status_name)
            .map_err(|e| anyhow::anyhow!("invalid state '{status_name}': {e}"))?;

        let created_event = Event {
            timestamp,
            action: EventAction::Created {
                state: initial_state,
            },
        };

        Ok(Issue {
            id,
            title: Title::new(title_str).map_err(|e| anyhow::anyhow!("invalid title: {e}"))?,
            description: None,
            status,
            date: IsoDate::new(&created_at[..10])?,
            tags,
            aliases: Vec::new(),
            content: Body::new(description),
            events: [created_event].into_iter().collect(),
            links: crate::domain::model::issue::IssueLinks::new(),
            relates: crate::domain::model::relates::Relates::default(),
            assignee,
            due_date,
            tracker,
            origin: EntryOrigin::Local,
            location: EntryLocator::default(),
        })
    }
}

/// Normalize a GitLab timestamp to `YYYY-MM-DDTHH:MM:SSZ`.
///
/// GitLab returns timestamps like `"2025-01-08T21:40:15.325Z"` with
/// fractional seconds. This function strips the fractional part.
fn normalize_gitlab_timestamp(ts: &str) -> String {
    // Find the dot before fractional seconds, if any.
    if let Some(dot_pos) = ts.find('.') {
        format!("{}Z", &ts[..dot_pos])
    } else {
        ts.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::infra::driven::gitlab::http_client::HttpResponse;

    struct StubClient {
        issues_body: String,
        state_events_body: String,
    }

    impl StubClient {
        fn with_issues(json: String) -> Self {
            StubClient {
                issues_body: json,
                state_events_body: "[]".to_string(),
            }
        }

        fn with_state_events(mut self, json: String) -> Self {
            self.state_events_body = json;
            self
        }
    }

    impl HttpClient for StubClient {
        fn get(&self, url: &str, _headers: &[(&str, &str)]) -> anyhow::Result<HttpResponse> {
            let body = if url.contains("resource_state_events") {
                self.state_events_body.clone()
            } else {
                // Return issues only for the first page.
                let is_first_page = url.contains("page=1&") || url.ends_with("page=1");
                if is_first_page || !url.contains("page=") {
                    self.issues_body.clone()
                } else {
                    "[]".to_string()
                }
            };
            Ok(HttpResponse { status: 200, body })
        }
    }

    fn gitlab_issue_json(iid: u32, title: &str, state: &str) -> String {
        format!(
            r#"{{
                "iid": {iid},
                "title": "{title}",
                "state": "{state}",
                "created_at": "2026-03-10T08:00:00Z",
                "description": "Issue body.",
                "labels": ["bug", "urgent"],
                "assignee": {{ "username": "alice" }},
                "due_date": "2026-04-01"
            }}"#
        )
    }

    #[test]
    fn parses_a_single_gitlab_issue() {
        let json = format!("[{}]", gitlab_issue_json(42, "Fix login", "opened"));
        let client = StubClient::with_issues(json);
        let source = GitLabSource::new(&client, "https://gitlab.com", "group/project", "token");
        let issues = source.list_issues().unwrap();

        assert_eq!(issues.len(), 1);
        let issue = &issues[0];
        assert_eq!(issue.title.as_str(), "Fix login");
        assert_eq!(issue.status.as_str(), "open");
        assert_eq!(issue.tracker.system(), "gitlab");
        assert_eq!(issue.tracker.locator(), "group/project#42");
        assert_eq!(issue.assignee.as_ref().unwrap().as_str(), "alice");
        assert_eq!(issue.due_date.as_ref().unwrap().as_str(), "2026-04-01");
        // Only the Created event, no state events
        assert_eq!(issue.events.len(), 1);
        assert!(issue.events[0].action.is_created());
    }

    #[test]
    fn maps_closed_state() {
        let json = format!("[{}]", gitlab_issue_json(1, "Done", "closed"));
        let client = StubClient::with_issues(json);
        let source = GitLabSource::new(&client, "https://gitlab.com", "g/p", "t");
        let issues = source.list_issues().unwrap();
        assert_eq!(issues[0].status.as_str(), "closed");
    }

    #[test]
    fn handles_empty_response() {
        let client = StubClient::with_issues("[]".to_string());
        let source = GitLabSource::new(&client, "https://gitlab.com", "g/p", "t");
        let issues = source.list_issues().unwrap();
        assert!(issues.is_empty());
    }

    #[test]
    fn api_error_is_reported() {
        struct ErrorClient;
        impl HttpClient for ErrorClient {
            fn get(&self, _url: &str, _headers: &[(&str, &str)]) -> anyhow::Result<HttpResponse> {
                Ok(HttpResponse {
                    status: 401,
                    body: "Unauthorized".to_string(),
                })
            }
        }
        let source = GitLabSource::new(&ErrorClient, "https://gitlab.com", "g/p", "bad");
        let result = source.list_issues();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("401"));
    }

    #[test]
    fn labels_become_tags() {
        let json = format!("[{}]", gitlab_issue_json(1, "T", "opened"));
        let client = StubClient::with_issues(json);
        let source = GitLabSource::new(&client, "https://gitlab.com", "g/p", "t");
        let issues = source.list_issues().unwrap();
        assert!(issues[0].tags.iter().any(|t| t.as_str() == "bug"));
    }

    #[test]
    fn state_events_produce_status_changed_events() {
        let issues_json = format!("[{}]", gitlab_issue_json(1, "Feature", "closed"));
        let events_json = r#"[
            {"state": "closed", "created_at": "2026-03-12T10:00:00Z"},
            {"state": "reopened", "created_at": "2026-03-14T08:00:00Z"},
            {"state": "closed", "created_at": "2026-03-15T16:00:00Z"}
        ]"#;
        let client =
            StubClient::with_issues(issues_json).with_state_events(events_json.to_string());
        let source = GitLabSource::new(&client, "https://gitlab.com", "g/p", "t");
        let issues = source.list_issues().unwrap();

        let issue = &issues[0];
        // 1 Created + 3 StatusChanged
        assert_eq!(issue.events.len(), 4);
        assert!(issue.events[0].action.is_created());
        assert!(issue.events[1].action.is_status_changed());
        assert!(issue.events[2].action.is_status_changed());
        assert!(issue.events[3].action.is_status_changed());
        // Final status should be closed (from last event)
        assert_eq!(issue.status.as_str(), "closed");
    }

    #[test]
    fn status_map_overrides_default_state_translation() {
        let json = format!("[{}]", gitlab_issue_json(1, "T", "opened"));
        let client = StubClient::with_issues(json);
        let mut map = BTreeMap::new();
        map.insert("opened".to_string(), "in-progress".to_string());
        map.insert("closed".to_string(), "done".to_string());
        let source =
            GitLabSource::new(&client, "https://gitlab.com", "g/p", "t").with_status_map(map);
        let issues = source.list_issues().unwrap();
        assert_eq!(issues[0].status.as_str(), "in-progress");
    }

    #[test]
    fn status_map_applies_to_state_events() {
        let issues_json = format!("[{}]", gitlab_issue_json(1, "T", "closed"));
        let events_json = r#"[
            {"state": "closed", "created_at": "2026-03-12T10:00:00Z"},
            {"state": "reopened", "created_at": "2026-03-13T10:00:00Z"}
        ]"#;
        let client =
            StubClient::with_issues(issues_json).with_state_events(events_json.to_string());
        let mut map = BTreeMap::new();
        map.insert("opened".to_string(), "in-progress".to_string());
        map.insert("closed".to_string(), "done".to_string());
        let source =
            GitLabSource::new(&client, "https://gitlab.com", "g/p", "t").with_status_map(map);
        let issues = source.list_issues().unwrap();
        // Created + closed (in-progress → done) + reopened (done → in-progress)
        assert_eq!(issues[0].events.len(), 3);
        if let EventAction::StatusChanged { from, to } = &issues[0].events[1].action {
            assert_eq!(from.as_str(), "in-progress");
            assert_eq!(to.as_str(), "done");
        } else {
            panic!("expected StatusChanged");
        }
        if let EventAction::StatusChanged { from, to } = &issues[0].events[2].action {
            assert_eq!(from.as_str(), "done");
            assert_eq!(to.as_str(), "in-progress");
        } else {
            panic!("expected StatusChanged");
        }
    }

    #[test]
    fn state_events_with_milliseconds_are_normalized() {
        let issues_json = format!("[{}]", gitlab_issue_json(1, "T", "closed"));
        let events_json = r#"[{"state": "closed", "created_at": "2026-03-12T10:00:00.123Z"}]"#;
        let client =
            StubClient::with_issues(issues_json).with_state_events(events_json.to_string());
        let source = GitLabSource::new(&client, "https://gitlab.com", "g/p", "t");
        let issues = source.list_issues().unwrap();
        // Should have Created + 1 StatusChanged despite milliseconds
        assert_eq!(issues[0].events.len(), 2);
    }
}