frostx 0.1.0

frostx monitors project directories for inactivity. Once a configured inactivity threshold elapses (e.g. "90 days since any file was modified"), frostx executes a pipeline of **actions** - e.g., checking git state, creating archives, uploading backups, deleting local copies. Automating the lifecycle of projects, frostx helps users manage disk space and maintain a clean workspace.
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
use crate::config::duration::Duration;
use crate::config::project::ProjectConfig;
use crate::config::state::ProjectState;
use crate::error::FrostxError;
use chrono::DateTime;
use chrono::Utc;
use serde::Serialize;
use std::path::{Path, PathBuf};

/// Status of a single action execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum ActionStatus {
    /// Check passed or action succeeded.
    Ok,
    /// Action or check failed - chain stops.
    Failed,
    /// Skipped because a preceding action failed.
    Skipped,
    /// Mutation was already completed in a previous run.
    Completed,
    /// Dry-run mode - action would have run.
    DryRun,
}

/// Outcome of a single action within a rule.
#[derive(Debug, Clone)]
pub struct ActionOutcome {
    pub name: String,
    pub status: ActionStatus,
    pub message: String,
}

/// Outcome of evaluating one rule.
#[derive(Debug, Clone)]
pub struct RuleOutcome {
    #[allow(dead_code)]
    pub index: usize,
    pub name: Option<String>,
    pub after: Duration,
    pub after_seconds: i64,
    pub triggered: bool,
    pub remaining_seconds: i64,
    pub action_outcomes: Vec<ActionOutcome>,
    /// `true` when this is a `once = true` rule that already completed in a
    /// previous run. The rule will not trigger again unless `--force` is used.
    pub completed_once: bool,
}

/// Options controlling pipeline execution.
pub struct RunOptions {
    pub dry_run: bool,
    pub force: bool,
    pub yes: bool,
    pub rule_filter: Option<usize>,
    pub action_filter: Option<String>,
}

/// Callback invoked after each action completes (used to stream output).
pub type ActionCallback<'a> = Box<dyn Fn(usize, Option<&str>, &ActionOutcome) + 'a>;

/// Evaluate which rules are triggered given a last-activity timestamp.
///
/// Returns `RuleOutcome` without executing any actions.
///
/// # Errors
///
/// Returns an error if config group expansion fails.
pub fn evaluate(
    config: &ProjectConfig,
    state: &ProjectState,
    last_modified: DateTime<Utc>,
) -> Result<Vec<RuleOutcome>, FrostxError> {
    let expanded = config.expand_groups()?;
    let mut outcomes = Vec::new();

    for (i, (rule, actions)) in config.rules.iter().zip(expanded.iter()).enumerate() {
        let index = i + 1;
        let triggered = rule.after.has_elapsed_since(last_modified);
        let remaining = rule.after.remaining_seconds_from(last_modified);
        let after_seconds = (Utc::now() - last_modified).num_seconds() - remaining;
        let after_seconds = after_seconds.max(0);

        let rule_hash = rule.rule_hash();
        let completed_once = rule.once && state.is_rule_done(&rule_hash);

        let action_outcomes = if completed_once {
            // Rule ran once and sealed — show every action as already completed.
            actions
                .iter()
                .map(|name| ActionOutcome {
                    name: name.clone(),
                    status: ActionStatus::Completed,
                    message: "rule completed (once)".into(),
                })
                .collect()
        } else if triggered {
            actions
                .iter()
                .map(|name| {
                    let completed = state.is_completed(&rule_hash, name);
                    ActionOutcome {
                        name: name.clone(),
                        status: if completed {
                            ActionStatus::Completed
                        } else {
                            ActionStatus::Ok
                        },
                        message: if completed {
                            "already completed".into()
                        } else {
                            "pending".into()
                        },
                    }
                })
                .collect()
        } else {
            vec![]
        };

        outcomes.push(RuleOutcome {
            index,
            name: rule.name.clone(),
            after: rule.after.clone(),
            after_seconds,
            // A completed-once rule is shown as not-triggered so the pipeline
            // knows it needs no further action.
            triggered: triggered && !completed_once,
            remaining_seconds: remaining,
            action_outcomes,
            completed_once,
        });
    }

    Ok(outcomes)
}

fn skipped_pipeline_outcomes(
    actions: &[String],
    index: usize,
    rule_name: Option<&str>,
    on_action: &ActionCallback<'_>,
) -> Vec<ActionOutcome> {
    actions
        .iter()
        .map(|action_name| {
            let outcome = ActionOutcome {
                name: action_name.clone(),
                status: ActionStatus::Skipped,
                message: "skipped - preceding rule failed".into(),
            };
            on_action(index, rule_name, &outcome);
            outcome
        })
        .collect()
}

#[allow(clippy::too_many_arguments)]
fn run_rule_actions(
    actions: &[String],
    index: usize,
    rule_name: Option<&str>,
    rule_hash: &str,
    config: &ProjectConfig,
    state: &mut ProjectState,
    current_path: &mut PathBuf,
    dry_run: bool,
    force: bool,
    yes: bool,
    action_filter: Option<&str>,
    on_action: &ActionCallback<'_>,
) -> Result<(Vec<ActionOutcome>, bool), FrostxError> {
    let mut outcomes = Vec::new();
    let mut chain_failed = false;
    for action_name in actions {
        if action_filter.is_some_and(|f| f != action_name) {
            continue;
        }
        if chain_failed {
            let outcome = ActionOutcome {
                name: action_name.clone(),
                status: ActionStatus::Skipped,
                message: "skipped - preceding action failed".into(),
            };
            on_action(index, rule_name, &outcome);
            outcomes.push(outcome);
            continue;
        }
        let action = crate::actions::create(action_name, config)?;
        if action.kind() == crate::actions::ActionKind::Mutation
            && !force
            && state.is_completed(rule_hash, action_name)
        {
            let outcome = ActionOutcome {
                name: action_name.clone(),
                status: ActionStatus::Completed,
                message: "already completed".into(),
            };
            on_action(index, rule_name, &outcome);
            outcomes.push(outcome);
            continue;
        }
        if current_path.is_file() && !action.supports_compressed_archive() {
            let (status, message, fails_chain) =
                if action.kind() == crate::actions::ActionKind::Check {
                    // Check actions are re-evaluated gates; if the project has
                    // already been compressed they are no longer applicable.
                    (
                        ActionStatus::Skipped,
                        format!("'{action_name}' skipped: project is a compressed archive"),
                        false,
                    )
                } else {
                    // A mutation that cannot operate on a compressed archive is a
                    // configuration error — stop the chain.
                    (
                        ActionStatus::Failed,
                        format!(
                            "'{action_name}' cannot run on a compressed archive; \
                             this action requires an uncompressed project directory"
                        ),
                        true,
                    )
                };
            let outcome = ActionOutcome {
                name: action_name.clone(),
                status,
                message,
            };
            on_action(index, rule_name, &outcome);
            outcomes.push(outcome);
            if fails_chain {
                chain_failed = true;
            }
            continue;
        }
        let ctx = crate::actions::ActionContext {
            project_path: current_path.as_path(),
            config,
            dry_run,
            yes,
        };
        let outcome = match action.run(&ctx) {
            Ok(ao) => {
                if !dry_run {
                    if let Some(new_path) = ao.new_project_path {
                        state.project_path.clone_from(&new_path);
                        *current_path = new_path;
                    }
                }
                ActionOutcome {
                    name: action_name.clone(),
                    status: ao.status.clone(),
                    message: ao.message.clone(),
                }
            }
            Err(e) => ActionOutcome {
                name: action_name.clone(),
                status: ActionStatus::Failed,
                message: e.to_string(),
            },
        };
        let failed = outcome.status == ActionStatus::Failed;
        if !dry_run
            && (outcome.status == ActionStatus::Ok || outcome.status == ActionStatus::Completed)
            && action.kind() == crate::actions::ActionKind::Mutation
        {
            state.mark_completed(rule_hash, action_name);
        }
        on_action(index, rule_name, &outcome);
        outcomes.push(outcome);
        if failed {
            chain_failed = true;
        }
    }
    Ok((outcomes, chain_failed))
}

/// Execute the pipeline for a project.
///
/// # Errors
///
/// Returns an error if config group expansion fails or action creation fails.
pub fn run(
    config: &ProjectConfig,
    state: &mut ProjectState,
    project_path: &Path,
    last_modified: DateTime<Utc>,
    opts: &RunOptions,
    on_action: &ActionCallback<'_>,
) -> Result<Vec<RuleOutcome>, FrostxError> {
    let expanded = config.expand_groups()?;
    let mut outcomes = Vec::new();
    let mut pipeline_failed = false;
    // Tracks the live project path; updated in-place when an action relocates
    // the project (e.g. archive.compress replaces the directory with an archive).
    let mut current_path = project_path.to_path_buf();

    for (i, (rule, actions)) in config.rules.iter().zip(expanded.iter()).enumerate() {
        let index = i + 1;
        if let Some(filter) = opts.rule_filter {
            if filter != index {
                continue;
            }
        }
        let triggered = opts.action_filter.is_some() || rule.after.has_elapsed_since(last_modified);
        let remaining = rule.after.remaining_seconds_from(last_modified);
        if !triggered {
            outcomes.push(RuleOutcome {
                index,
                name: rule.name.clone(),
                after: rule.after.clone(),
                after_seconds: 0,
                triggered: false,
                remaining_seconds: remaining,
                action_outcomes: vec![],
                completed_once: false,
            });
            continue;
        }
        if pipeline_failed {
            let action_outcomes =
                skipped_pipeline_outcomes(actions, index, rule.name.as_deref(), on_action);
            outcomes.push(RuleOutcome {
                index,
                name: rule.name.clone(),
                after: rule.after.clone(),
                after_seconds: 0,
                triggered: true,
                remaining_seconds: 0,
                action_outcomes,
                completed_once: false,
            });
            continue;
        }
        let rule_hash = rule.rule_hash();

        // Skip a once-rule that already completed (unless --force overrides).
        if rule.once && !opts.force && state.is_rule_done(&rule_hash) {
            outcomes.push(RuleOutcome {
                index,
                name: rule.name.clone(),
                after: rule.after.clone(),
                after_seconds: 0,
                triggered: false,
                remaining_seconds: 0,
                action_outcomes: vec![],
                completed_once: true,
            });
            continue;
        }

        let (action_outcomes, chain_failed) = run_rule_actions(
            actions,
            index,
            rule.name.as_deref(),
            &rule_hash,
            config,
            state,
            &mut current_path,
            opts.dry_run,
            opts.force,
            opts.yes,
            opts.action_filter.as_deref(),
            on_action,
        )?;

        // Seal a once-rule after a fully successful run.
        if rule.once && !chain_failed && !opts.dry_run {
            state.mark_rule_done(&rule_hash);
        }

        if chain_failed {
            pipeline_failed = true;
        }
        outcomes.push(RuleOutcome {
            index,
            name: rule.name.clone(),
            after: rule.after.clone(),
            after_seconds: 0,
            triggered: true,
            remaining_seconds: 0,
            action_outcomes,
            completed_once: false,
        });
    }

    Ok(outcomes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::duration::Duration;
    use crate::config::project::{ActionConfig, Rule};
    use std::collections::HashMap;
    use uuid::Uuid;

    fn make_config(rules: Vec<Rule>) -> ProjectConfig {
        ProjectConfig {
            id: Uuid::new_v4(),
            name: None,
            description: None,
            include: vec![],
            template: HashMap::new(),
            groups: HashMap::new(),
            config: ActionConfig::default(),
            rules,
        }
    }

    #[test]
    fn untriggered_rule_is_not_triggered() {
        let cfg = make_config(vec![Rule {
            name: None,
            after: Duration::parse("90d").unwrap(),
            actions: vec!["git.check_clean".into()],
            once: false,
        }]);
        let state = ProjectState::default();
        let recent = Utc::now() - chrono::Duration::days(10);
        let outcomes = evaluate(&cfg, &state, recent).unwrap();
        assert!(!outcomes[0].triggered);
    }

    #[test]
    fn triggered_rule_lists_actions() {
        let cfg = make_config(vec![Rule {
            name: None,
            after: Duration::parse("90d").unwrap(),
            actions: vec!["git.check_clean".into()],
            once: false,
        }]);
        let state = ProjectState::default();
        let old = Utc::now() - chrono::Duration::days(100);
        let outcomes = evaluate(&cfg, &state, old).unwrap();
        assert!(outcomes[0].triggered);
        assert_eq!(outcomes[0].action_outcomes.len(), 1);
    }

    #[test]
    fn failed_rule_blocks_subsequent_triggered_rules() {
        use crate::config::project::{HookConfig, HookKind, ProjectConfig};

        let tmp = std::env::temp_dir();
        let mut hooks = HashMap::new();
        hooks.insert(
            "fail_check".into(),
            HookConfig {
                command: "exit 1".into(),
                kind: HookKind::Check,
                run_on_archive: false,
            },
        );
        hooks.insert(
            "should_not_run".into(),
            HookConfig {
                command: "true".into(),
                kind: HookKind::Check,
                run_on_archive: false,
            },
        );
        let cfg = ProjectConfig {
            id: Uuid::new_v4(),
            name: None,
            description: None,
            include: vec![],
            template: HashMap::new(),
            groups: HashMap::new(),
            config: ActionConfig {
                hooks,
                ..ActionConfig::default()
            },
            rules: vec![
                Rule {
                    name: None,
                    after: Duration::parse("1h").unwrap(),
                    actions: vec!["hook.fail_check".into()],
                    once: false,
                },
                Rule {
                    name: None,
                    after: Duration::parse("1h").unwrap(),
                    actions: vec!["hook.should_not_run".into()],
                    once: false,
                },
            ],
        };
        let mut state = ProjectState::default();
        let old = Utc::now() - chrono::Duration::hours(2);
        let opts = RunOptions {
            dry_run: false,
            force: false,
            yes: true,
            rule_filter: None,
            action_filter: None,
        };
        let noop: ActionCallback<'_> = Box::new(|_, _, _| {});
        let outcomes = run(&cfg, &mut state, &tmp, old, &opts, &noop).unwrap();

        assert!(outcomes[0].triggered);
        assert_eq!(outcomes[0].action_outcomes[0].status, ActionStatus::Failed);
        assert!(outcomes[1].triggered);
        assert_eq!(outcomes[1].action_outcomes[0].status, ActionStatus::Skipped);
    }

    #[test]
    fn completed_action_shows_as_completed() {
        let id = Uuid::new_v4();
        let rule = Rule {
            name: None,
            after: Duration::parse("90d").unwrap(),
            actions: vec!["archive.compress".into()],
            once: false,
        };
        let rule_hash = rule.rule_hash();
        let cfg = make_config(vec![rule]);
        let mut state = ProjectState::default();
        state.mark_completed(&rule_hash, "archive.compress");
        let old = Utc::now() - chrono::Duration::days(100);
        let outcomes = evaluate(&cfg, &state, old).unwrap();
        assert_eq!(
            outcomes[0].action_outcomes[0].status,
            ActionStatus::Completed
        );
        let _ = id;
    }
}