ito-domain 0.1.30

Domain models and repositories 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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Change domain models and repository.
//!
//! This module provides domain models for Ito changes and a repository
//! for loading and querying change data.

mod mutations;
mod repository;

pub use mutations::{
    ChangeArtifactKind, ChangeArtifactMutationError, ChangeArtifactMutationResult,
    ChangeArtifactMutationService, ChangeArtifactMutationServiceResult, ChangeArtifactRef,
};
pub use repository::{
    ChangeLifecycleFilter, ChangeRepository, ChangeTargetResolution, ResolveTargetOptions,
};

use chrono::{DateTime, Utc};
use std::path::PathBuf;

use crate::tasks::{ProgressInfo, TasksParseResult};

/// A specification within a change.
#[derive(Debug, Clone)]
pub struct Spec {
    /// Spec name (directory name under specs/)
    pub name: String,
    /// Spec content (raw markdown)
    pub content: String,
}

/// Status of a change based on task completion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeStatus {
    /// No tasks defined
    NoTasks,
    /// Some tasks incomplete
    InProgress,
    /// All tasks complete
    Complete,
}

/// Work status of a change.
///
/// This is a derived status intended for UX and filtering. It is NOT a persisted
/// lifecycle state.
///
/// Semantics:
/// - `Draft`: missing required planning artifacts (proposal + specs + tasks)
/// - `Ready`: planning artifacts exist and there is remaining work, with no in-progress tasks
/// - `InProgress`: at least one task is in-progress
/// - `Paused`: no remaining work, but at least one task is shelved (i.e. all tasks are done or shelved)
/// - `Complete`: all tasks are complete (shelved tasks do NOT count as complete)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChangeWorkStatus {
    /// Missing required planning artifacts (proposal + specs + tasks).
    Draft,
    /// Ready to start work (planning artifacts exist, remaining work, nothing in-progress).
    Ready,
    /// At least one task is in-progress.
    InProgress,
    /// No remaining work, but at least one task is shelved.
    ///
    /// This distinguishes "we're finished but chose to shelve something" from `Complete`.
    Paused,
    /// All tasks complete.
    ///
    /// Note: shelved tasks do NOT count as complete.
    Complete,
}

/// Per-change orchestration metadata.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ChangeOrchestrateMetadata {
    /// Canonical change IDs that must complete before this change is dispatched.
    pub depends_on: Vec<String>,
    /// Optional gate order override for this change.
    pub preferred_gates: Vec<String>,
}

impl std::fmt::Display for ChangeWorkStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChangeWorkStatus::Draft => write!(f, "draft"),
            ChangeWorkStatus::Ready => write!(f, "ready"),
            ChangeWorkStatus::InProgress => write!(f, "in-progress"),
            ChangeWorkStatus::Paused => write!(f, "paused"),
            ChangeWorkStatus::Complete => write!(f, "complete"),
        }
    }
}

impl std::fmt::Display for ChangeStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChangeStatus::NoTasks => write!(f, "no-tasks"),
            ChangeStatus::InProgress => write!(f, "in-progress"),
            ChangeStatus::Complete => write!(f, "complete"),
        }
    }
}

/// Full change with all artifacts loaded.
#[derive(Debug, Clone)]
pub struct Change {
    /// Change identifier (e.g., "005-01_my-change" or "005.01-03_my-change")
    pub id: String,
    /// Module ID extracted from the change ID (e.g., "005")
    pub module_id: Option<String>,
    /// Sub-module ID in canonical `NNN.SS` form when the change belongs to a sub-module.
    ///
    /// `None` for changes that use the legacy `NNN-NN_name` format without a sub-module.
    pub sub_module_id: Option<String>,
    /// Path to the change directory
    pub path: PathBuf,
    /// Proposal content (raw markdown)
    pub proposal: Option<String>,
    /// Design content (raw markdown)
    pub design: Option<String>,
    /// Specifications
    pub specs: Vec<Spec>,
    /// Parsed tasks
    pub tasks: TasksParseResult,
    /// Per-change orchestration metadata.
    pub orchestrate: ChangeOrchestrateMetadata,
    /// Last modification time of any artifact
    pub last_modified: DateTime<Utc>,
}

impl Change {
    /// Get the status of this change based on task completion.
    pub fn status(&self) -> ChangeStatus {
        let progress = &self.tasks.progress;
        if progress.total == 0 {
            ChangeStatus::NoTasks
        } else if progress.complete >= progress.total {
            ChangeStatus::Complete
        } else {
            ChangeStatus::InProgress
        }
    }

    /// Derived work status for UX and filtering.
    pub fn work_status(&self) -> ChangeWorkStatus {
        let ProgressInfo {
            total,
            complete,
            shelved,
            in_progress,
            pending,
            remaining: _,
        } = self.tasks.progress;

        // Planning artifacts required to start work.
        let has_planning_artifacts = self.proposal.is_some() && !self.specs.is_empty() && total > 0;
        if !has_planning_artifacts {
            return ChangeWorkStatus::Draft;
        }

        if complete == total {
            return ChangeWorkStatus::Complete;
        }
        if in_progress > 0 {
            return ChangeWorkStatus::InProgress;
        }

        let done_or_shelved = complete + shelved;
        if pending == 0 && shelved > 0 && done_or_shelved == total {
            return ChangeWorkStatus::Paused;
        }

        ChangeWorkStatus::Ready
    }

    /// Check if all required artifacts are present.
    pub fn artifacts_complete(&self) -> bool {
        self.proposal.is_some()
            && self.design.is_some()
            && !self.specs.is_empty()
            && self.tasks.progress.total > 0
    }

    /// Get task progress as (completed, total).
    pub fn task_progress(&self) -> (u32, u32) {
        (
            self.tasks.progress.complete as u32,
            self.tasks.progress.total as u32,
        )
    }

    /// Get the progress info for this change.
    pub fn progress(&self) -> &ProgressInfo {
        &self.tasks.progress
    }
}

/// Lightweight change summary for listings.
#[derive(Debug, Clone)]
pub struct ChangeSummary {
    /// Change identifier
    pub id: String,
    /// Module ID extracted from the change ID
    pub module_id: Option<String>,
    /// Sub-module ID in canonical `NNN.SS` form when the change belongs to a sub-module.
    ///
    /// `None` for changes that use the legacy `NNN-NN_name` format without a sub-module.
    pub sub_module_id: Option<String>,
    /// Number of completed tasks
    pub completed_tasks: u32,
    /// Number of shelved tasks (enhanced tasks only)
    pub shelved_tasks: u32,
    /// Number of in-progress tasks
    pub in_progress_tasks: u32,
    /// Number of pending tasks
    pub pending_tasks: u32,
    /// Total number of tasks
    pub total_tasks: u32,
    /// Last modification time
    pub last_modified: DateTime<Utc>,
    /// Whether proposal.md exists
    pub has_proposal: bool,
    /// Whether design.md exists
    pub has_design: bool,
    /// Whether specs/ directory has content
    pub has_specs: bool,
    /// Whether tasks.md exists and has tasks
    pub has_tasks: bool,
    /// Per-change orchestration metadata.
    pub orchestrate: ChangeOrchestrateMetadata,
}

impl ChangeSummary {
    /// Get the status of this change based on task counts.
    pub fn status(&self) -> ChangeStatus {
        if self.total_tasks == 0 {
            ChangeStatus::NoTasks
        } else if self.completed_tasks >= self.total_tasks {
            ChangeStatus::Complete
        } else {
            ChangeStatus::InProgress
        }
    }

    /// Derived work status for UX and filtering.
    pub fn work_status(&self) -> ChangeWorkStatus {
        let has_planning_artifacts = self.has_proposal && self.has_specs && self.has_tasks;
        if !has_planning_artifacts {
            return ChangeWorkStatus::Draft;
        }

        if self.total_tasks > 0 && self.completed_tasks == self.total_tasks {
            return ChangeWorkStatus::Complete;
        }
        if self.in_progress_tasks > 0 {
            return ChangeWorkStatus::InProgress;
        }

        let done_or_shelved = self.completed_tasks + self.shelved_tasks;
        if self.pending_tasks == 0 && self.shelved_tasks > 0 && done_or_shelved == self.total_tasks
        {
            return ChangeWorkStatus::Paused;
        }

        ChangeWorkStatus::Ready
    }

    /// Check if this change is ready for implementation.
    ///
    /// A change is "ready" when it has all required planning artifacts and has remaining work
    /// with no in-progress tasks.
    pub fn is_ready(&self) -> bool {
        self.work_status() == ChangeWorkStatus::Ready
    }
}

/// Extract module ID from a change ID.
///
/// Handles both the legacy `NNN-NN_name` format and the sub-module
/// `NNN.SS-NN_name` format. Always returns only the parent module number.
///
/// - `005-01_my-change` -> `005`
/// - `5-1_whatever` -> `005`
/// - `1-000002` -> `001`
/// - `024.01-03_foo` -> `024`
pub fn extract_module_id(change_id: &str) -> Option<String> {
    let parts: Vec<&str> = change_id.split('-').collect();
    if parts.len() >= 2 {
        // Strip any sub-module component (e.g., "024.01" -> "024").
        let module_part = parts[0].split('.').next().unwrap_or(parts[0]);
        Some(normalize_id(module_part, 3))
    } else {
        None
    }
}

/// Extract the sub-module ID from a change ID in `NNN.SS-NN_name` format.
///
/// Returns `Some("NNN.SS")` for sub-module changes, `None` for legacy
/// `NNN-NN_name` changes.
///
/// - `024.01-03_foo` -> `Some("024.01")`
/// - `005-01_my-change` -> `None`
pub fn extract_sub_module_id(change_id: &str) -> Option<String> {
    // A sub-module change has a dot before the first hyphen.
    let prefix = change_id.split('-').next()?;
    if !prefix.contains('.') {
        return None;
    }
    // Normalize: "24.1" -> "024.01" via the common parser.
    ito_common::id::parse_sub_module_id(prefix)
        .map(|p| p.sub_module_id.as_str().to_string())
        .ok()
}

/// Normalize an ID to a fixed width with zero-padding.
///
/// - `"5"` with width 3 -> `"005"`
/// - `"005"` with width 3 -> `"005"`
/// - `"0005"` with width 3 -> `"005"` (strips leading zeros beyond width)
pub fn normalize_id(id: &str, width: usize) -> String {
    // Parse as number to strip leading zeros, then reformat
    let num: u32 = id.parse().unwrap_or(0);
    format!("{:0>width$}", num, width = width)
}

/// Parse a change identifier and return the normalized module ID and change number.
///
/// Handles both legacy and sub-module formats:
/// - `005-01_my-change` → `("005", "01")`
/// - `5-1_whatever` → `("005", "01")`
/// - `1-2` → `("001", "02")`
/// - `001-000002_foo` → `("001", "02")`
/// - `024.01-03_foo` → `("024", "03")`
pub fn parse_change_id(input: &str) -> Option<(String, String)> {
    // Remove the name suffix if present (everything after underscore)
    let id_part = input.split('_').next().unwrap_or(input);

    let parts: Vec<&str> = id_part.split('-').collect();
    if parts.len() >= 2 {
        // Strip any sub-module component (e.g., "024.01" → "024").
        let module_part = parts[0].split('.').next().unwrap_or(parts[0]);
        let module_id = normalize_id(module_part, 3);
        let change_num = normalize_id(parts[1], 2);
        Some((module_id, change_num))
    } else {
        None
    }
}

/// Parse a module identifier and return the normalized module ID.
///
/// Handles various formats:
/// - `005` -> `"005"`
/// - `5` -> `"005"`
/// - `005_dev-tooling` -> `"005"`
/// - `5_dev-tooling` -> `"005"`
pub fn parse_module_id(input: &str) -> String {
    // Remove the name suffix if present (everything after underscore)
    let id_part = input.split('_').next().unwrap_or(input);
    normalize_id(id_part, 3)
}

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

    #[test]
    fn test_normalize_id() {
        assert_eq!(normalize_id("5", 3), "005");
        assert_eq!(normalize_id("05", 3), "005");
        assert_eq!(normalize_id("005", 3), "005");
        assert_eq!(normalize_id("0005", 3), "005");
        assert_eq!(normalize_id("1", 2), "01");
        assert_eq!(normalize_id("01", 2), "01");
        assert_eq!(normalize_id("001", 2), "01");
    }

    #[test]
    fn test_parse_change_id() {
        assert_eq!(
            parse_change_id("005-01_my-change"),
            Some(("005".to_string(), "01".to_string()))
        );
        assert_eq!(
            parse_change_id("5-1_whatever"),
            Some(("005".to_string(), "01".to_string()))
        );
        assert_eq!(
            parse_change_id("1-2"),
            Some(("001".to_string(), "02".to_string()))
        );
        assert_eq!(
            parse_change_id("001-000002_foo"),
            Some(("001".to_string(), "02".to_string()))
        );
        assert_eq!(parse_change_id("invalid"), None);
    }

    #[test]
    fn test_parse_module_id() {
        assert_eq!(parse_module_id("005"), "005");
        assert_eq!(parse_module_id("5"), "005");
        assert_eq!(parse_module_id("005_dev-tooling"), "005");
        assert_eq!(parse_module_id("5_dev-tooling"), "005");
    }

    #[test]
    fn test_extract_module_id() {
        assert_eq!(
            extract_module_id("005-01_my-change"),
            Some("005".to_string())
        );
        assert_eq!(extract_module_id("013-18_cleanup"), Some("013".to_string()));
        assert_eq!(extract_module_id("5-1_foo"), Some("005".to_string()));
        assert_eq!(extract_module_id("invalid"), None);
        // Sub-module format: strip sub-module component
        assert_eq!(extract_module_id("024.01-03_foo"), Some("024".to_string()));
        assert_eq!(extract_module_id("5.1-2_bar"), Some("005".to_string()));
    }

    #[test]
    fn test_extract_sub_module_id() {
        assert_eq!(
            extract_sub_module_id("024.01-03_foo"),
            Some("024.01".to_string())
        );
        assert_eq!(
            extract_sub_module_id("5.1-2_bar"),
            Some("005.01".to_string())
        );
        assert_eq!(extract_sub_module_id("005-01_my-change"), None);
        assert_eq!(extract_sub_module_id("invalid"), None);
    }

    #[test]
    fn test_parse_change_id_sub_module_format() {
        assert_eq!(
            parse_change_id("024.01-03_foo"),
            Some(("024".to_string(), "03".to_string()))
        );
        assert_eq!(
            parse_change_id("5.1-2_bar"),
            Some(("005".to_string(), "02".to_string()))
        );
    }

    #[test]
    fn test_change_sub_module_id_field() {
        let summary = ChangeSummary {
            id: "005.01-03_my-change".to_string(),
            module_id: Some("005".to_string()),
            sub_module_id: Some("005.01".to_string()),
            completed_tasks: 0,
            shelved_tasks: 0,
            in_progress_tasks: 0,
            pending_tasks: 0,
            total_tasks: 0,
            last_modified: Utc::now(),
            has_proposal: false,
            has_design: false,
            has_specs: false,
            has_tasks: false,
            orchestrate: ChangeOrchestrateMetadata::default(),
        };

        assert_eq!(summary.sub_module_id.as_deref(), Some("005.01"));
    }

    #[test]
    fn test_change_status_display() {
        assert_eq!(ChangeStatus::NoTasks.to_string(), "no-tasks");
        assert_eq!(ChangeStatus::InProgress.to_string(), "in-progress");
        assert_eq!(ChangeStatus::Complete.to_string(), "complete");
    }

    #[test]
    fn test_change_summary_status() {
        let mut summary = ChangeSummary {
            id: "test".to_string(),
            module_id: None,
            sub_module_id: None,
            completed_tasks: 0,
            shelved_tasks: 0,
            in_progress_tasks: 0,
            pending_tasks: 0,
            total_tasks: 0,
            last_modified: Utc::now(),
            has_proposal: false,
            has_design: false,
            has_specs: false,
            has_tasks: false,
            orchestrate: ChangeOrchestrateMetadata::default(),
        };

        assert_eq!(summary.status(), ChangeStatus::NoTasks);

        summary.total_tasks = 5;
        summary.completed_tasks = 3;
        assert_eq!(summary.status(), ChangeStatus::InProgress);

        summary.completed_tasks = 5;
        assert_eq!(summary.status(), ChangeStatus::Complete);
    }

    #[test]
    fn test_change_work_status() {
        let mut summary = ChangeSummary {
            id: "test".to_string(),
            module_id: None,
            sub_module_id: None,
            completed_tasks: 0,
            shelved_tasks: 0,
            in_progress_tasks: 0,
            pending_tasks: 0,
            total_tasks: 0,
            last_modified: Utc::now(),
            has_proposal: false,
            has_design: false,
            has_specs: false,
            has_tasks: false,
            orchestrate: ChangeOrchestrateMetadata::default(),
        };

        assert_eq!(summary.work_status(), ChangeWorkStatus::Draft);

        summary.has_proposal = true;
        summary.has_specs = true;
        summary.has_tasks = true;
        summary.total_tasks = 3;
        summary.pending_tasks = 3;

        assert_eq!(summary.work_status(), ChangeWorkStatus::Ready);

        summary.in_progress_tasks = 1;
        summary.pending_tasks = 2;
        assert_eq!(summary.work_status(), ChangeWorkStatus::InProgress);

        summary.in_progress_tasks = 0;
        summary.pending_tasks = 0;
        summary.shelved_tasks = 1;
        summary.completed_tasks = 2;
        assert_eq!(summary.work_status(), ChangeWorkStatus::Paused);

        summary.shelved_tasks = 0;
        summary.completed_tasks = 3;
        assert_eq!(summary.work_status(), ChangeWorkStatus::Complete);
    }
}