ito-core 0.1.31

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
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
//! Rule registry holding the built-in rule set.
//!
//! The registry is stateless and cheap to construct; callers typically build
//! one per `ito validate repo` invocation via [`RuleRegistry::built_in`].
//!
//! Wave 1 ships an empty built-in registry plus the introspection helper
//! [`list_active_rules`]. Subsequent waves register concrete rules:
//!
//! - Wave 2: `coordination/*`, `worktrees/*`, plus pre-commit detection.
//! - Change `011-06`: `audit/*`, `repository/*`, `backend/*`.

use ito_config::types::ItoConfig;

use super::rule::{Rule, RuleId, RuleSeverity};

/// Snapshot of a rule's activation state for introspection.
///
/// Returned by [`list_active_rules`] and by the
/// `ito validate repo --list-rules` CLI handler.
///
/// Marked `#[non_exhaustive]` so additional metadata fields can be added in
/// later waves without breaking external consumers.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActiveRule {
    /// Stable rule identifier.
    pub rule_id: RuleId,
    /// Nominal severity declared by the rule.
    pub severity: RuleSeverity,
    /// Short human-readable description of what the rule checks.
    pub description: &'static str,
    /// Whether the rule is active for the resolved [`ItoConfig`].
    pub active: bool,
    /// Optional description of the activation gate
    /// (e.g. `"changes.coordination_branch.storage == worktree"`). `None`
    /// when the rule is unconditionally active.
    pub gate: Option<&'static str>,
}

/// Container for the set of built-in [`Rule`]s.
///
/// The registry owns trait objects so concrete rule structs are kept
/// crate-private; consumers interact only with [`Rule`] and
/// [`ActiveRule`].
#[derive(Default)]
pub struct RuleRegistry {
    rules: Vec<Box<dyn Rule>>,
}

impl RuleRegistry {
    /// Construct an empty registry.
    ///
    /// Useful for tests; production code should call [`Self::built_in`].
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Construct a registry pre-populated with every built-in rule.
    ///
    /// Order of registration does not matter — [`list_active_rules`] sorts
    /// by `RuleId` for deterministic output.
    ///
    /// Built-in rules:
    ///
    /// - `coordination/*` and `worktrees/*` — change 011-05.
    /// - `audit/*`, `repository/*`, `backend/*` — change 011-06.
    #[must_use]
    pub fn built_in() -> Self {
        use super::audit_rules::{MirrorBranchDistinctRule, MirrorBranchSetRule};
        use super::backend_rules::{
            ProjectOrgRepoSetRule, TokenNotCommittedRule, UrlSchemeValidRule,
        };
        use super::coordination_rules::{
            BranchNameSetRule, GitignoreEntriesRule, StagedSymlinkedPathsRule, SymlinksWiredRule,
        };
        use super::repository_rules::{SqliteDbNotCommittedRule, SqliteDbPathSetRule};
        use super::worktrees_rules::{LayoutConsistentRule, NoWriteOnControlRule};

        Self::empty()
            // 011-05: coordination/*, worktrees/*
            .with_rule(Box::new(SymlinksWiredRule))
            .with_rule(Box::new(GitignoreEntriesRule))
            .with_rule(Box::new(StagedSymlinkedPathsRule))
            .with_rule(Box::new(BranchNameSetRule))
            .with_rule(Box::new(NoWriteOnControlRule))
            .with_rule(Box::new(LayoutConsistentRule))
            // 011-06: audit/*, repository/*, backend/*
            .with_rule(Box::new(MirrorBranchSetRule))
            .with_rule(Box::new(MirrorBranchDistinctRule))
            .with_rule(Box::new(SqliteDbPathSetRule))
            .with_rule(Box::new(SqliteDbNotCommittedRule))
            .with_rule(Box::new(TokenNotCommittedRule))
            .with_rule(Box::new(UrlSchemeValidRule))
            .with_rule(Box::new(ProjectOrgRepoSetRule))
    }

    /// Register a rule with this registry.
    ///
    /// Builder-style API used internally by [`Self::built_in`] and by tests.
    #[must_use]
    pub fn with_rule(mut self, rule: Box<dyn Rule>) -> Self {
        self.rules.push(rule);
        self
    }

    /// Iterate over registered rules in registration order.
    pub fn iter(&self) -> impl Iterator<Item = &dyn Rule> {
        self.rules.iter().map(Box::as_ref)
    }

    /// Number of registered rules.
    #[must_use]
    pub fn len(&self) -> usize {
        self.rules.len()
    }

    /// True if no rules are registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }
}

impl std::fmt::Debug for RuleRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RuleRegistry")
            .field(
                "rules",
                &self
                    .rules
                    .iter()
                    .map(|r| r.id().as_str())
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

/// Return the set of registered rules with their activation state for the
/// given config, sorted lexicographically by [`RuleId`].
///
/// Equivalent to `list_active_rules_for(&RuleRegistry::built_in(), config)`.
#[must_use]
pub fn list_active_rules(config: &ItoConfig) -> Vec<ActiveRule> {
    list_active_rules_for(&RuleRegistry::built_in(), config)
}

/// Return the set of rules in `registry` with their activation state for
/// `config`, sorted lexicographically by [`RuleId`].
///
/// Exposed primarily for unit tests that construct ad-hoc registries; most
/// callers should use [`list_active_rules`].
#[must_use]
pub fn list_active_rules_for(registry: &RuleRegistry, config: &ItoConfig) -> Vec<ActiveRule> {
    let mut active: Vec<ActiveRule> = registry
        .iter()
        .map(|rule| ActiveRule {
            rule_id: rule.id(),
            severity: rule.severity(),
            description: rule.description(),
            active: rule.is_active(config),
            gate: rule.gate(),
        })
        .collect();
    active.sort_by_key(|item| item.rule_id);
    active
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors::CoreError;
    use crate::validate::ValidationIssue;
    use crate::validate_repo::rule::RuleContext;

    /// Minimal stub rule used to exercise the registry without depending on
    /// any of the real rule modules (which land in Wave 2).
    struct StubRule {
        id: RuleId,
        severity: RuleSeverity,
        active: bool,
        description: &'static str,
        gate: Option<&'static str>,
    }

    impl Rule for StubRule {
        fn id(&self) -> RuleId {
            self.id
        }
        fn severity(&self) -> RuleSeverity {
            self.severity
        }
        fn description(&self) -> &'static str {
            self.description
        }
        fn gate(&self) -> Option<&'static str> {
            self.gate
        }
        fn is_active(&self, _config: &ItoConfig) -> bool {
            self.active
        }
        fn check(&self, _ctx: &RuleContext<'_>) -> Result<Vec<ValidationIssue>, CoreError> {
            Ok(Vec::new())
        }
    }

    fn stub(id: &'static str, active: bool) -> Box<dyn Rule> {
        Box::new(StubRule {
            id: RuleId::new(id),
            severity: RuleSeverity::Warning,
            active,
            description: "always available",
            gate: None,
        })
    }

    fn gated_stub(id: &'static str, active: bool, gate: &'static str) -> Box<dyn Rule> {
        Box::new(StubRule {
            id: RuleId::new(id),
            severity: RuleSeverity::Error,
            active,
            description: "gated",
            gate: Some(gate),
        })
    }

    #[test]
    fn empty_registry_has_no_rules() {
        let registry = RuleRegistry::empty();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
        assert!(registry.iter().next().is_none());
    }

    #[test]
    fn built_in_registry_contains_every_built_in_rule() {
        let registry = RuleRegistry::built_in();
        // Thirteen rules ship after changes 011-05 + 011-06:
        // - 011-05: coordination/{symlinks-wired,gitignore-entries,
        //   staged-symlinked-paths,branch-name-set} + worktrees/{
        //   no-write-on-control,layout-consistent} = 6.
        // - 011-06: audit/{mirror-branch-set,
        //   mirror-branch-distinct-from-coordination} +
        //   repository/{sqlite-db-path-set,sqlite-db-not-committed} +
        //   backend/{token-not-committed,url-scheme-valid,
        //   project-org-repo-set} = 7.
        let ids: Vec<_> = registry.iter().map(|r| r.id().as_str()).collect();
        assert_eq!(ids.len(), 13, "expected 13 built-in rules, got {ids:?}");
        for expected in [
            "audit/mirror-branch-distinct-from-coordination",
            "audit/mirror-branch-set",
            "backend/project-org-repo-set",
            "backend/token-not-committed",
            "backend/url-scheme-valid",
            "coordination/branch-name-set",
            "coordination/gitignore-entries",
            "coordination/staged-symlinked-paths",
            "coordination/symlinks-wired",
            "repository/sqlite-db-not-committed",
            "repository/sqlite-db-path-set",
            "worktrees/layout-consistent",
            "worktrees/no-write-on-control",
        ] {
            assert!(
                ids.contains(&expected),
                "built-in registry missing `{expected}`; have: {ids:?}",
            );
        }
    }

    #[test]
    fn list_active_rules_for_empty_registry_returns_empty() {
        let config = ItoConfig::default();
        assert!(list_active_rules_for(&RuleRegistry::empty(), &config).is_empty());
    }

    #[test]
    fn list_active_rules_for_single_active_rule_reports_active_true() {
        let config = ItoConfig::default();
        let registry = RuleRegistry::empty().with_rule(stub("test/always", true));

        let rules = list_active_rules_for(&registry, &config);
        assert_eq!(rules.len(), 1);
        let only = &rules[0];
        assert_eq!(only.rule_id.as_str(), "test/always");
        assert_eq!(only.severity, RuleSeverity::Warning);
        assert!(only.active);
        assert_eq!(only.description, "always available");
        assert_eq!(only.gate, None);
    }

    #[test]
    fn list_active_rules_for_inactive_rule_reports_active_false() {
        let config = ItoConfig::default();
        let registry = RuleRegistry::empty().with_rule(stub("test/never", false));

        let rules = list_active_rules_for(&registry, &config);
        assert_eq!(rules.len(), 1);
        assert!(!rules[0].active);
    }

    #[test]
    fn list_active_rules_for_returns_rules_sorted_by_id() {
        let config = ItoConfig::default();
        let registry = RuleRegistry::empty()
            .with_rule(stub("zeta/last", true))
            .with_rule(stub("alpha/first", false))
            .with_rule(stub("mu/middle", true));

        let ids: Vec<_> = list_active_rules_for(&registry, &config)
            .into_iter()
            .map(|r| r.rule_id.as_str())
            .collect();

        assert_eq!(ids, vec!["alpha/first", "mu/middle", "zeta/last"]);
    }

    #[test]
    fn list_active_rules_for_surfaces_gate_metadata() {
        let config = ItoConfig::default();
        let registry = RuleRegistry::empty().with_rule(gated_stub(
            "coordination/example",
            true,
            "changes.coordination_branch.storage == worktree",
        ));

        let rules = list_active_rules_for(&registry, &config);
        assert_eq!(
            rules[0].gate,
            Some("changes.coordination_branch.storage == worktree"),
            "gate metadata should be surfaced verbatim",
        );
    }

    /// Activation matrix for the full built-in rule set.
    ///
    /// Each row is a config permutation and the rule ids that should be
    /// `active = true` for it. Rules not listed are expected to be
    /// inactive. This test catches accidental gate changes by enforcing
    /// the entire matrix at once rather than one rule at a time.
    #[test]
    fn list_active_rules_matrix_matches_specification() {
        use ito_config::types::{
            AuditConfig, AuditMirrorConfig, BackendApiConfig, BackendProjectConfig, ChangesConfig,
            CoordinationBranchConfig, CoordinationStorage, RepositoryPersistenceMode,
            RepositoryRuntimeConfig, RepositorySqliteConfig, WorktreesConfig,
        };

        struct Case {
            label: &'static str,
            mutate: fn(&mut ItoConfig),
            expected_active: &'static [&'static str],
        }

        // Always-active rule applies to every row.
        const ALWAYS: &[&str] = &["coordination/branch-name-set"];

        let cases = [
            Case {
                label: "minimal: embedded coord, worktrees off, fs repo, backend/audit off",
                mutate: |c| {
                    c.changes.coordination_branch.storage = CoordinationStorage::Embedded;
                    c.worktrees.enabled = false;
                    c.repository.mode = RepositoryPersistenceMode::Filesystem;
                    c.audit.mirror.enabled = false;
                    c.backend.enabled = false;
                },
                expected_active: ALWAYS,
            },
            Case {
                label: "coordination_worktree only",
                mutate: |c| {
                    c.changes.coordination_branch.storage = CoordinationStorage::Worktree;
                    c.worktrees.enabled = false;
                    c.repository.mode = RepositoryPersistenceMode::Filesystem;
                    c.audit.mirror.enabled = false;
                    c.backend.enabled = false;
                },
                expected_active: &[
                    "coordination/branch-name-set",
                    "coordination/gitignore-entries",
                    "coordination/staged-symlinked-paths",
                    "coordination/symlinks-wired",
                ],
            },
            Case {
                label: "worktrees enabled only",
                mutate: |c| {
                    c.changes.coordination_branch.storage = CoordinationStorage::Embedded;
                    c.worktrees.enabled = true;
                    c.repository.mode = RepositoryPersistenceMode::Filesystem;
                    c.audit.mirror.enabled = false;
                    c.backend.enabled = false;
                },
                expected_active: &[
                    "coordination/branch-name-set",
                    "worktrees/layout-consistent",
                    "worktrees/no-write-on-control",
                ],
            },
            Case {
                label: "audit mirror enabled, embedded coord (distinct rule still skipped)",
                mutate: |c| {
                    c.changes.coordination_branch.storage = CoordinationStorage::Embedded;
                    c.worktrees.enabled = false;
                    c.repository.mode = RepositoryPersistenceMode::Filesystem;
                    c.audit.mirror.enabled = true;
                    c.backend.enabled = false;
                },
                expected_active: &["audit/mirror-branch-set", "coordination/branch-name-set"],
            },
            Case {
                label: "audit mirror + worktree coord (both audit rules active)",
                mutate: |c| {
                    c.changes.coordination_branch.storage = CoordinationStorage::Worktree;
                    c.worktrees.enabled = false;
                    c.repository.mode = RepositoryPersistenceMode::Filesystem;
                    c.audit.mirror.enabled = true;
                    c.backend.enabled = false;
                },
                expected_active: &[
                    "audit/mirror-branch-distinct-from-coordination",
                    "audit/mirror-branch-set",
                    "coordination/branch-name-set",
                    "coordination/gitignore-entries",
                    "coordination/staged-symlinked-paths",
                    "coordination/symlinks-wired",
                ],
            },
            Case {
                label: "sqlite repo only",
                mutate: |c| {
                    c.changes.coordination_branch.storage = CoordinationStorage::Embedded;
                    c.worktrees.enabled = false;
                    c.repository.mode = RepositoryPersistenceMode::Sqlite;
                    c.audit.mirror.enabled = false;
                    c.backend.enabled = false;
                },
                expected_active: &[
                    "coordination/branch-name-set",
                    "repository/sqlite-db-not-committed",
                    "repository/sqlite-db-path-set",
                ],
            },
            Case {
                label: "backend enabled only",
                mutate: |c| {
                    c.changes.coordination_branch.storage = CoordinationStorage::Embedded;
                    c.worktrees.enabled = false;
                    c.repository.mode = RepositoryPersistenceMode::Filesystem;
                    c.audit.mirror.enabled = false;
                    c.backend.enabled = true;
                },
                expected_active: &[
                    "backend/project-org-repo-set",
                    "backend/token-not-committed",
                    "backend/url-scheme-valid",
                    "coordination/branch-name-set",
                ],
            },
            Case {
                label: "everything on (all 13 rules active)",
                mutate: |c| {
                    c.changes.coordination_branch.storage = CoordinationStorage::Worktree;
                    c.worktrees.enabled = true;
                    c.repository.mode = RepositoryPersistenceMode::Sqlite;
                    c.audit.mirror.enabled = true;
                    c.backend.enabled = true;
                },
                expected_active: &[
                    "audit/mirror-branch-distinct-from-coordination",
                    "audit/mirror-branch-set",
                    "backend/project-org-repo-set",
                    "backend/token-not-committed",
                    "backend/url-scheme-valid",
                    "coordination/branch-name-set",
                    "coordination/gitignore-entries",
                    "coordination/staged-symlinked-paths",
                    "coordination/symlinks-wired",
                    "repository/sqlite-db-not-committed",
                    "repository/sqlite-db-path-set",
                    "worktrees/layout-consistent",
                    "worktrees/no-write-on-control",
                ],
            },
        ];

        // Suppress unused warnings when the matrix references types that
        // some compilation units may not exercise.
        let _ = (
            AuditConfig::default(),
            AuditMirrorConfig::default(),
            BackendApiConfig::default(),
            BackendProjectConfig::default(),
            ChangesConfig::default(),
            CoordinationBranchConfig::default(),
            RepositoryRuntimeConfig::default(),
            RepositorySqliteConfig::default(),
            WorktreesConfig::default(),
        );

        for case in &cases {
            let mut cfg = ItoConfig::default();
            (case.mutate)(&mut cfg);

            let active_ids: Vec<_> = list_active_rules(&cfg)
                .into_iter()
                .filter(|r| r.active)
                .map(|r| r.rule_id.as_str())
                .collect();

            let expected: Vec<&str> = case.expected_active.to_vec();
            assert_eq!(
                active_ids,
                expected,
                "case `{label}`: active set mismatch",
                label = case.label,
            );
        }
    }

    #[test]
    fn public_list_active_rules_delegates_to_built_in_registry() {
        let config = ItoConfig::default();
        // After Wave 2 the built-in registry is non-empty and rules are
        // sorted by id.
        let rules = list_active_rules(&config);
        assert!(!rules.is_empty(), "built-in registry should be non-empty");

        // Rules are sorted lexicographically by RuleId.
        let mut sorted_ids: Vec<_> = rules.iter().map(|r| r.rule_id.as_str()).collect();
        let original = sorted_ids.clone();
        sorted_ids.sort();
        assert_eq!(
            original, sorted_ids,
            "list_active_rules must return sorted output"
        );
    }
}