knotra 0.34.0

knotra: multi-project VCS dashboard and bulk-operation tool.
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
//! Sync Center UI state.

use knotra_vcs::{
    OperationId, ProjectId, WorkspaceId, WorkspaceStatus,
    model::operation::{
        ProjectOperationOutcome, SmartPullDisposition, SmartPullPlan, SmartPullPlanEntry,
        SmartPullProgress, SmartPullSkipReason,
    },
};

use super::{OperationLeaseId, RetryExclusion};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RetryPreparationId(pub u64);

#[derive(Debug, Clone)]
pub struct SmartPullRetryPreparation {
    pub id: RetryPreparationId,
    pub workspace_id: WorkspaceId,
    pub source_operation_id: OperationId,
    pub lease_id: OperationLeaseId,
    pub eligible_ids: Vec<ProjectId>,
    pub exclusions: Vec<RetryExclusion>,
}

// ---------------------------------------------------------------------------
// Sync Center phase
// ---------------------------------------------------------------------------

/// The current phase of the Sync Center workflow.
#[derive(Debug, Clone, Default)]
pub enum SyncPhase {
    /// Idle — waiting for the user to select an operation.
    #[default]
    Idle,
    /// A bulk fetch is running.
    FetchRunning {
        operation_id: OperationId,
        lease_id: OperationLeaseId,
        started_at: jiff::Timestamp,
        total: usize,
        done: usize,
        completed: Vec<ProjectOutcome>,
        operation_results: Vec<knotra_vcs::model::operation::ProjectOperationResult>,
    },
    /// Computing the Smart Pull plan (checking dirty states).
    Planning,
    /// Refreshing current status for a correlated Activity retry review.
    RetryPreparing,
    /// Retry status collection failed for every eligible project.
    RetryPreparationFailed,
    /// Plan ready — awaiting user confirmation.
    AwaitingConfirm(SmartPullPlan),
    /// Smart Pull in progress — collecting streaming results.
    PullRunning {
        plan: SmartPullPlan,
        lease_id: OperationLeaseId,
        started_at: jiff::Timestamp,
        completed: Vec<SmartPullProgress>,
    },
    /// Operation finished — show results.
    Done(SyncResult),
}

/// Aggregate result shown after an operation completes.
#[derive(Debug, Clone)]
pub struct SyncResult {
    pub per_project: Vec<ProjectOutcome>,
}

#[derive(Debug, Clone)]
pub struct ProjectOutcome {
    pub project_name: String,
    pub outcome: ProjectOperationOutcome,
    pub skip_reason: Option<String>,
    pub commands_executed: Vec<String>,
    pub stderr: String,
}

impl SyncResult {
    pub fn success_count(&self) -> usize {
        self.per_project
            .iter()
            .filter(|p| p.outcome == ProjectOperationOutcome::Succeeded)
            .count()
    }
    pub fn fail_count(&self) -> usize {
        self.per_project
            .iter()
            .filter(|p| p.outcome == ProjectOperationOutcome::Failed)
            .count()
    }
    pub fn skipped_count(&self) -> usize {
        self.per_project
            .iter()
            .filter(|p| p.outcome == ProjectOperationOutcome::Skipped)
            .count()
    }
}

// ---------------------------------------------------------------------------
// Sync Center state
// ---------------------------------------------------------------------------

#[derive(Debug, Default)]
pub struct SyncCenterState {
    /// Per-project inclusion toggle (true = included).
    pub project_selection: std::collections::HashMap<ProjectId, bool>,
    /// Disposition overrides set by the user in the plan view.
    pub disposition_overrides: std::collections::HashMap<ProjectId, SmartPullDisposition>,
    pub phase: SyncPhase,
    /// RFC-0009: project ids pre-populated from dashboard selection.
    pub selected_project_ids: std::collections::HashSet<knotra_vcs::ProjectId>,
    pub retry_preparation: Option<SmartPullRetryPreparation>,
    pub retry_exclusions: Vec<RetryExclusion>,
    next_retry_preparation_id: u64,
}

impl SyncCenterState {
    pub fn next_retry_preparation_id(&mut self) -> RetryPreparationId {
        self.next_retry_preparation_id = self.next_retry_preparation_id.wrapping_add(1).max(1);
        RetryPreparationId(self.next_retry_preparation_id)
    }

    pub fn set_selection(
        &mut self,
        projects: &[knotra_vcs::Project],
        selected: &std::collections::HashSet<ProjectId>,
    ) {
        self.project_selection.clear();
        for p in projects {
            self.project_selection
                .insert(p.id.clone(), selected.contains(&p.id));
        }
    }

    pub fn is_selected(&self, id: &ProjectId) -> bool {
        *self.project_selection.get(id).unwrap_or(&true)
    }

    pub fn selected_ids(&self) -> Vec<ProjectId> {
        self.project_selection
            .iter()
            .filter(|(_, v)| **v)
            .map(|(id, _)| id.clone())
            .collect()
    }

    /// Build a Smart Pull plan from the current workspace status + user selections.
    pub fn build_plan(
        &self,
        projects: &[knotra_vcs::Project],
        workspace_status: Option<&WorkspaceStatus>,
    ) -> SmartPullPlan {
        use knotra_vcs::OperationId;

        let statuses = workspace_status
            .map(|ws| ws.projects.as_slice())
            .unwrap_or(&[]);

        let entries: Vec<SmartPullPlanEntry> = projects
            .iter()
            .map(|p| {
                let selected = self.is_selected(&p.id);
                let status = statuses.iter().find(|s| s.project_id == p.id);
                let is_dirty = status.map(|s| s.working_tree.is_dirty()).unwrap_or(false);
                let has_conflict = status.map(|s| s.conflict.has_conflict).unwrap_or(false);
                let has_upstream = status.and_then(|s| s.remote.upstream.as_ref()).is_some();

                // Default disposition.
                let (disposition, skip_reason) = if !selected {
                    (
                        SmartPullDisposition::Excluded,
                        Some(SmartPullSkipReason::Deselected),
                    )
                } else if status.is_none() {
                    (
                        SmartPullDisposition::Excluded,
                        Some(SmartPullSkipReason::MissingStatus),
                    )
                } else if let Some(d) = self.disposition_overrides.get(&p.id) {
                    (d.clone(), None)
                } else if has_conflict {
                    (
                        SmartPullDisposition::Excluded,
                        Some(SmartPullSkipReason::Conflict),
                    )
                } else if !has_upstream {
                    (
                        SmartPullDisposition::Excluded,
                        Some(SmartPullSkipReason::NoUpstream),
                    )
                } else if is_dirty {
                    (SmartPullDisposition::FetchOnly, None)
                } else {
                    (SmartPullDisposition::Pull, None)
                };

                SmartPullPlanEntry {
                    project_id: p.id.clone(),
                    project_name: p.name.clone(),
                    is_dirty,
                    has_conflict,
                    skip_reason,
                    disposition,
                }
            })
            .collect();

        SmartPullPlan {
            id: OperationId::new(),
            entries,
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use jiff::Timestamp;
    use knotra_vcs::{
        ProjectId, WorkspaceStatus,
        model::status::{
            ConflictStatus, RemoteStatus, RepositoryIdentity, VcsKind, WorkingTreeStatus,
        },
    };

    fn make_project(name: &str) -> knotra_vcs::Project {
        knotra_vcs::Project::new(name, "/tmp")
    }

    fn make_status(
        project_id: ProjectId,
        uncommitted: u32,
        conflict: bool,
    ) -> knotra_vcs::ProjectStatus {
        make_status_with_upstream(project_id, uncommitted, conflict, Some("origin/main"))
    }

    fn make_status_with_upstream(
        project_id: ProjectId,
        uncommitted: u32,
        conflict: bool,
        upstream: Option<&str>,
    ) -> knotra_vcs::ProjectStatus {
        knotra_vcs::ProjectStatus {
            project_id,
            identity: RepositoryIdentity {
                path: "/tmp".into(),
                vcs_kind: VcsKind::Git,
            },
            context: None,
            remote: RemoteStatus {
                upstream: upstream.map(str::to_owned),
                ..RemoteStatus::default()
            },
            working_tree: WorkingTreeStatus {
                uncommitted_count: uncommitted,
                untracked_count: 0,
            },
            conflict: ConflictStatus {
                has_conflict: conflict,
                conflict_count: None,
                detection_unavailable: false,
            },
            refreshed_at: Timestamp::now(),
            read_error: None,
        }
    }

    #[test]
    fn clean_project_gets_pull_disposition() {
        let p = make_project("svc");
        let status = make_status(p.id.clone(), 0, false);
        let ws = WorkspaceStatus {
            projects: vec![status],
            last_refresh: None,
        };

        let mut sc = SyncCenterState::default();
        sc.project_selection.insert(p.id.clone(), true);
        let plan = sc.build_plan(std::slice::from_ref(&p), Some(&ws));

        assert_eq!(plan.entries[0].disposition, SmartPullDisposition::Pull);
    }

    #[test]
    fn dirty_project_defaults_to_fetch_only() {
        let p = make_project("svc");
        let status = make_status(p.id.clone(), 3, false);
        let ws = WorkspaceStatus {
            projects: vec![status],
            last_refresh: None,
        };

        let mut sc = SyncCenterState::default();
        sc.project_selection.insert(p.id.clone(), true);
        let plan = sc.build_plan(std::slice::from_ref(&p), Some(&ws));

        assert_eq!(plan.entries[0].disposition, SmartPullDisposition::FetchOnly);
    }

    #[test]
    fn conflicted_project_is_excluded() {
        let p = make_project("svc");
        let status = make_status(p.id.clone(), 0, true);
        let ws = WorkspaceStatus {
            projects: vec![status],
            last_refresh: None,
        };

        let mut sc = SyncCenterState::default();
        sc.project_selection.insert(p.id.clone(), true);
        let plan = sc.build_plan(std::slice::from_ref(&p), Some(&ws));

        assert_eq!(plan.entries[0].disposition, SmartPullDisposition::Excluded);
        assert_eq!(
            plan.entries[0].skip_reason,
            Some(SmartPullSkipReason::Conflict)
        );
    }

    #[test]
    fn deselected_project_is_excluded() {
        let p = make_project("svc");
        let mut sc = SyncCenterState::default();
        sc.project_selection.insert(p.id.clone(), true);
        sc.project_selection.insert(p.id.clone(), false);

        let plan = sc.build_plan(std::slice::from_ref(&p), None);
        assert_eq!(plan.entries[0].disposition, SmartPullDisposition::Excluded);
        assert_eq!(
            plan.entries[0].skip_reason,
            Some(SmartPullSkipReason::Deselected)
        );
    }

    #[test]
    fn selected_project_without_upstream_is_excluded() {
        let p = make_project("svc");
        let status = make_status_with_upstream(p.id.clone(), 0, false, None);
        let ws = WorkspaceStatus {
            projects: vec![status],
            last_refresh: None,
        };

        let mut sc = SyncCenterState::default();
        sc.project_selection.insert(p.id.clone(), true);
        let plan = sc.build_plan(std::slice::from_ref(&p), Some(&ws));

        assert_eq!(plan.entries[0].disposition, SmartPullDisposition::Excluded);
        assert_eq!(
            plan.entries[0].skip_reason,
            Some(SmartPullSkipReason::NoUpstream)
        );
    }

    #[test]
    fn mixed_upstream_plan_has_pull_and_skipped_no_upstream() {
        let p1 = make_project("has-upstream");
        let p2 = make_project("no-upstream");

        let s1 = make_status(p1.id.clone(), 0, false);
        let s2 = make_status_with_upstream(p2.id.clone(), 0, false, None);
        let ws = WorkspaceStatus {
            projects: vec![s1, s2],
            last_refresh: None,
        };

        let mut sc = SyncCenterState::default();
        sc.project_selection.insert(p1.id.clone(), true);
        sc.project_selection.insert(p2.id.clone(), true);
        let plan = sc.build_plan(&[p1, p2], Some(&ws));

        assert_eq!(plan.pull_count(), 1);
        assert_eq!(plan.excluded_count(), 1);
        assert_eq!(
            plan.entries[1].skip_reason,
            Some(SmartPullSkipReason::NoUpstream)
        );
    }

    #[test]
    fn user_override_stash_and_pull() {
        let p = make_project("svc");
        let status = make_status(p.id.clone(), 2, false);
        let ws = WorkspaceStatus {
            projects: vec![status],
            last_refresh: None,
        };

        let mut sc = SyncCenterState::default();
        sc.project_selection.insert(p.id.clone(), true);
        sc.disposition_overrides
            .insert(p.id.clone(), SmartPullDisposition::StashAndPull);

        let plan = sc.build_plan(std::slice::from_ref(&p), Some(&ws));
        assert_eq!(
            plan.entries[0].disposition,
            SmartPullDisposition::StashAndPull
        );
    }

    #[test]
    fn plan_pull_count() {
        let p1 = make_project("a");
        let p2 = make_project("b");
        let p3 = make_project("c");

        let s1 = make_status(p1.id.clone(), 0, false);
        let s2 = make_status(p2.id.clone(), 1, false); // dirty → FetchOnly
        let s3 = make_status(p3.id.clone(), 0, true); // conflict → Excluded
        let ws = WorkspaceStatus {
            projects: vec![s1, s2, s3],
            last_refresh: None,
        };

        let mut sc = SyncCenterState::default();
        sc.project_selection.insert(p1.id.clone(), true);
        sc.project_selection.insert(p2.id.clone(), true);
        sc.project_selection.insert(p3.id.clone(), true);
        let plan = sc.build_plan(&[p1, p2, p3], Some(&ws));

        assert_eq!(plan.pull_count(), 1);
        assert_eq!(plan.excluded_count(), 1);
    }
}