ito-core 0.1.29

Core functionality and business logic for Ito
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
//! Backend-backed change repository adapter.
//!
//! Delegates change reads to a [`BackendChangeReader`] when backend mode is
//! enabled. The filesystem repository remains the fallback when backend mode
//! is disabled.

use std::collections::BTreeSet;

use ito_domain::backend::BackendChangeReader;
use ito_domain::changes::{
    Change, ChangeLifecycleFilter, ChangeRepository as DomainChangeRepository, ChangeSummary,
    ChangeTargetResolution, ResolveTargetOptions, parse_change_id, parse_module_id,
};
use ito_domain::errors::DomainResult;
use regex::Regex;

/// Backend-backed change repository.
///
/// Wraps a [`BackendChangeReader`] implementation and delegates all read
/// operations to the backend. Change target resolution is performed against
/// the backend-supplied change list.
pub struct BackendChangeRepository<R: BackendChangeReader> {
    reader: R,
}

impl<R: BackendChangeReader> BackendChangeRepository<R> {
    /// Create a backend-backed change repository.
    pub fn new(reader: R) -> Self {
        Self { reader }
    }
}

impl<R: BackendChangeReader> BackendChangeRepository<R> {
    fn split_canonical_change_id<'b>(&self, name: &'b str) -> Option<(String, String, &'b str)> {
        let (module_id, change_num) = parse_change_id(name)?;
        let slug = name.split_once('_').map(|(_id, s)| s).unwrap_or("");
        Some((module_id, change_num, slug))
    }

    fn tokenize_query(&self, input: &str) -> Vec<String> {
        let mut out = Vec::new();
        for part in input.split_whitespace() {
            let trimmed = part.trim();
            if trimmed.is_empty() {
                continue;
            }
            out.push(trimmed.to_lowercase());
        }
        out
    }

    fn normalized_slug_text(&self, slug: &str) -> String {
        let mut out = String::new();
        for ch in slug.chars() {
            if ch.is_ascii_alphanumeric() {
                out.push(ch.to_ascii_lowercase());
            } else {
                out.push(' ');
            }
        }
        out
    }

    fn slug_matches_tokens(&self, slug: &str, tokens: &[String]) -> bool {
        if tokens.is_empty() {
            return false;
        }
        let text = self.normalized_slug_text(slug);
        for token in tokens {
            if !text.contains(token) {
                return false;
            }
        }
        true
    }

    fn is_numeric_module_selector(&self, input: &str) -> bool {
        let trimmed = input.trim();
        !trimmed.is_empty() && trimmed.chars().all(|ch| ch.is_ascii_digit())
    }

    fn extract_two_numbers_as_change_id(&self, input: &str) -> Option<(String, String)> {
        let re = Regex::new(r"\d+").ok()?;
        let mut parts: Vec<&str> = Vec::new();
        for m in re.find_iter(input) {
            parts.push(m.as_str());
            if parts.len() > 2 {
                return None;
            }
        }
        if parts.len() != 2 {
            return None;
        }
        let parsed = format!("{}-{}", parts[0], parts[1]);
        parse_change_id(&parsed)
    }
}

impl<R: BackendChangeReader> DomainChangeRepository for BackendChangeRepository<R> {
    fn resolve_target_with_options(
        &self,
        input: &str,
        options: ResolveTargetOptions,
    ) -> ChangeTargetResolution {
        let Ok(summaries) = self.reader.list_changes(options.lifecycle) else {
            return ChangeTargetResolution::NotFound;
        };

        let mut names: Vec<String> = summaries.iter().map(|s| s.id.clone()).collect();
        names.sort();
        names.dedup();

        if names.is_empty() {
            return ChangeTargetResolution::NotFound;
        }

        let input = input.trim();
        if input.is_empty() {
            return ChangeTargetResolution::NotFound;
        }

        if names.iter().any(|name| name == input) {
            return ChangeTargetResolution::Unique(input.to_string());
        }

        let mut numeric_matches: BTreeSet<String> = BTreeSet::new();
        let numeric_selector =
            parse_change_id(input).or_else(|| self.extract_two_numbers_as_change_id(input));
        if let Some((module_id, change_num)) = numeric_selector {
            let numeric_prefix = format!("{module_id}-{change_num}");
            let with_separator = format!("{numeric_prefix}_");
            for name in &names {
                if name == &numeric_prefix || name.starts_with(&with_separator) {
                    numeric_matches.insert(name.clone());
                }
            }
            if !numeric_matches.is_empty() {
                let numeric_matches: Vec<String> = numeric_matches.into_iter().collect();
                if numeric_matches.len() == 1 {
                    return ChangeTargetResolution::Unique(numeric_matches[0].clone());
                }
                return ChangeTargetResolution::Ambiguous(numeric_matches);
            }
        }

        if let Some((module, query)) = input.split_once(':') {
            let query = query.trim();
            if !query.is_empty() {
                let module_id = parse_module_id(module);
                let tokens = self.tokenize_query(query);
                let mut scoped_matches: BTreeSet<String> = BTreeSet::new();
                for name in &names {
                    let Some((name_module, _name_change, slug)) =
                        self.split_canonical_change_id(name)
                    else {
                        continue;
                    };
                    if name_module != module_id {
                        continue;
                    }
                    if self.slug_matches_tokens(slug, &tokens) {
                        scoped_matches.insert(name.clone());
                    }
                }
                if scoped_matches.is_empty() {
                    return ChangeTargetResolution::NotFound;
                }
                let scoped_matches: Vec<String> = scoped_matches.into_iter().collect();
                if scoped_matches.len() == 1 {
                    return ChangeTargetResolution::Unique(scoped_matches[0].clone());
                }
                return ChangeTargetResolution::Ambiguous(scoped_matches);
            }
        }

        if self.is_numeric_module_selector(input) {
            let module_id = parse_module_id(input);
            let mut module_matches: BTreeSet<String> = BTreeSet::new();
            for name in &names {
                let Some((name_module, _name_change, _slug)) = self.split_canonical_change_id(name)
                else {
                    continue;
                };
                if name_module == module_id {
                    module_matches.insert(name.clone());
                }
            }

            if !module_matches.is_empty() {
                let module_matches: Vec<String> = module_matches.into_iter().collect();
                if module_matches.len() == 1 {
                    return ChangeTargetResolution::Unique(module_matches[0].clone());
                }
                return ChangeTargetResolution::Ambiguous(module_matches);
            }
        }

        let mut matches: BTreeSet<String> = BTreeSet::new();
        for name in &names {
            if name.starts_with(input) {
                matches.insert(name.clone());
            }
        }

        if matches.is_empty() {
            let tokens = self.tokenize_query(input);
            for name in &names {
                let Some((_module, _change, slug)) = self.split_canonical_change_id(name) else {
                    continue;
                };
                if self.slug_matches_tokens(slug, &tokens) {
                    matches.insert(name.clone());
                }
            }
        }

        if matches.is_empty() {
            return ChangeTargetResolution::NotFound;
        }

        let matches: Vec<String> = matches.into_iter().collect();
        if matches.len() == 1 {
            return ChangeTargetResolution::Unique(matches[0].clone());
        }

        ChangeTargetResolution::Ambiguous(matches)
    }

    fn suggest_targets(&self, input: &str, max: usize) -> Vec<String> {
        let Ok(summaries) = self.reader.list_changes(ChangeLifecycleFilter::Active) else {
            return Vec::new();
        };

        let ids: Vec<String> = summaries.iter().map(|s| s.id.clone()).collect();
        ito_common::match_::nearest_matches(input, &ids, max)
    }

    fn exists(&self, id: &str) -> bool {
        self.exists_with_filter(id, ChangeLifecycleFilter::Active)
    }

    fn exists_with_filter(&self, id: &str, filter: ChangeLifecycleFilter) -> bool {
        self.reader.get_change(id, filter).is_ok()
    }

    fn get_with_filter(&self, id: &str, filter: ChangeLifecycleFilter) -> DomainResult<Change> {
        self.reader.get_change(id, filter)
    }

    fn list_with_filter(&self, filter: ChangeLifecycleFilter) -> DomainResult<Vec<ChangeSummary>> {
        self.reader.list_changes(filter)
    }

    fn list_by_module_with_filter(
        &self,
        module_id: &str,
        filter: ChangeLifecycleFilter,
    ) -> DomainResult<Vec<ChangeSummary>> {
        let normalized_id = parse_module_id(module_id);
        let all = self.reader.list_changes(filter)?;
        let mut filtered = Vec::new();
        for s in all {
            if s.module_id.as_deref() == Some(&normalized_id) {
                filtered.push(s);
            }
        }
        Ok(filtered)
    }

    fn list_incomplete_with_filter(
        &self,
        filter: ChangeLifecycleFilter,
    ) -> DomainResult<Vec<ChangeSummary>> {
        let all = self.reader.list_changes(filter)?;
        let filtered = all
            .into_iter()
            .filter(|s| s.completed_tasks < s.total_tasks || s.total_tasks == 0)
            .collect();
        Ok(filtered)
    }

    fn list_complete_with_filter(
        &self,
        filter: ChangeLifecycleFilter,
    ) -> DomainResult<Vec<ChangeSummary>> {
        let all = self.reader.list_changes(filter)?;
        let filtered = all
            .into_iter()
            .filter(|s| s.total_tasks > 0 && s.completed_tasks == s.total_tasks)
            .collect();
        Ok(filtered)
    }

    fn get_summary_with_filter(
        &self,
        id: &str,
        filter: ChangeLifecycleFilter,
    ) -> DomainResult<ChangeSummary> {
        let all = self.reader.list_changes(filter)?;
        for summary in all {
            if summary.id == id {
                return Ok(summary);
            }
        }
        Err(ito_domain::errors::DomainError::not_found("change", id))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Utc;
    use ito_domain::tasks::TasksParseResult;

    /// In-memory backend reader for testing.
    struct FakeReader {
        changes: Vec<ChangeSummary>,
        full: Vec<Change>,
    }

    impl FakeReader {
        fn new(changes: Vec<ChangeSummary>, full: Vec<Change>) -> Self {
            Self { changes, full }
        }
    }

    impl BackendChangeReader for FakeReader {
        fn list_changes(
            &self,
            _filter: ito_domain::changes::ChangeLifecycleFilter,
        ) -> DomainResult<Vec<ChangeSummary>> {
            Ok(self.changes.clone())
        }

        fn get_change(
            &self,
            change_id: &str,
            _filter: ito_domain::changes::ChangeLifecycleFilter,
        ) -> DomainResult<Change> {
            for c in &self.full {
                if c.id == change_id {
                    return Ok(c.clone());
                }
            }
            Err(ito_domain::errors::DomainError::not_found(
                "change", change_id,
            ))
        }
    }

    fn make_summary(id: &str, completed: u32, total: u32) -> ChangeSummary {
        ChangeSummary {
            id: id.to_string(),
            module_id: None,
            sub_module_id: None,
            completed_tasks: completed,
            shelved_tasks: 0,
            in_progress_tasks: 0,
            pending_tasks: total - completed,
            total_tasks: total,
            last_modified: Utc::now(),
            has_proposal: true,
            has_design: false,
            has_specs: true,
            has_tasks: true,
            orchestrate: ito_domain::changes::ChangeOrchestrateMetadata::default(),
        }
    }

    fn make_change(id: &str) -> Change {
        Change {
            id: id.to_string(),
            module_id: None,
            sub_module_id: None,
            path: std::path::PathBuf::from("/fake"),
            proposal: Some("# Proposal".to_string()),
            design: None,
            specs: vec![],
            tasks: TasksParseResult::empty(),
            orchestrate: ito_domain::changes::ChangeOrchestrateMetadata::default(),
            last_modified: Utc::now(),
        }
    }

    #[test]
    fn list_returns_all_changes() {
        let summaries = vec![
            make_summary("001-01_a", 0, 2),
            make_summary("001-02_b", 1, 2),
        ];
        let reader = FakeReader::new(summaries.clone(), vec![]);
        let repo = BackendChangeRepository::new(reader);

        let result = repo.list().unwrap();
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn resolve_target_exact_match() {
        let summaries = vec![make_summary("001-01_a", 0, 2)];
        let reader = FakeReader::new(summaries, vec![]);
        let repo = BackendChangeRepository::new(reader);

        let resolution = DomainChangeRepository::resolve_target(&repo, "001-01_a");
        assert!(matches!(resolution, ChangeTargetResolution::Unique(id) if id == "001-01_a"));
    }

    #[test]
    fn resolve_target_prefix_match() {
        let summaries = vec![make_summary("001-01_something", 0, 2)];
        let reader = FakeReader::new(summaries, vec![]);
        let repo = BackendChangeRepository::new(reader);

        let resolution = DomainChangeRepository::resolve_target(&repo, "001-01");
        assert!(
            matches!(resolution, ChangeTargetResolution::Unique(id) if id == "001-01_something")
        );
    }

    #[test]
    fn resolve_target_ambiguous() {
        let summaries = vec![
            make_summary("001-01_a", 0, 2),
            make_summary("001-01_b", 0, 2),
        ];
        let reader = FakeReader::new(summaries, vec![]);
        let repo = BackendChangeRepository::new(reader);

        let resolution = DomainChangeRepository::resolve_target(&repo, "001-01");
        assert!(matches!(resolution, ChangeTargetResolution::Ambiguous(_)));
    }

    #[test]
    fn resolve_target_not_found() {
        let summaries = vec![make_summary("001-01_a", 0, 2)];
        let reader = FakeReader::new(summaries, vec![]);
        let repo = BackendChangeRepository::new(reader);

        let resolution = DomainChangeRepository::resolve_target(&repo, "999");
        assert!(matches!(resolution, ChangeTargetResolution::NotFound));
    }

    #[test]
    fn get_delegates_to_reader() {
        let change = make_change("001-01_a");
        let reader = FakeReader::new(vec![], vec![change]);
        let repo = BackendChangeRepository::new(reader);

        let result = DomainChangeRepository::get(&repo, "001-01_a").unwrap();
        assert_eq!(result.id, "001-01_a");
    }

    #[test]
    fn list_incomplete_filters_correctly() {
        let summaries = vec![
            make_summary("001-01_a", 2, 2),
            make_summary("001-02_b", 1, 2),
        ];
        let reader = FakeReader::new(summaries, vec![]);
        let repo = BackendChangeRepository::new(reader);

        let incomplete = DomainChangeRepository::list_incomplete(&repo).unwrap();
        assert_eq!(incomplete.len(), 1);
        assert_eq!(incomplete[0].id, "001-02_b");
    }

    #[test]
    fn list_complete_filters_correctly() {
        let summaries = vec![
            make_summary("001-01_a", 2, 2),
            make_summary("001-02_b", 1, 2),
        ];
        let reader = FakeReader::new(summaries, vec![]);
        let repo = BackendChangeRepository::new(reader);

        let complete = DomainChangeRepository::list_complete(&repo).unwrap();
        assert_eq!(complete.len(), 1);
        assert_eq!(complete[0].id, "001-01_a");
    }
}