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
//! Rules under the `worktrees/*` namespace.
//!
//! These rules only run when `worktrees.enabled = true`; otherwise the
//! engine reports them as skipped via [`super::list_active_rules`].
//!
//! Two rules live here:
//!
//! - `worktrees/no-write-on-control` — fails when the current branch matches
//!   `worktrees.default_branch` and the staged-files snapshot is non-empty.
//!   This is the "default-branch worktree" check from the spec; combined
//!   with the bare-control-siblings layout used by Ito itself this is also
//!   sufficient to catch "writing to main".
//! - `worktrees/layout-consistent` — emits warnings about layout drift
//!   relative to the resolved configuration.

use std::path::Path;

use ito_config::types::{ItoConfig, WorktreeStrategy};

use crate::errors::CoreError;
use crate::process::{ProcessRequest, ProcessRunner};
use crate::validate::{ValidationIssue, error, warning, with_metadata, with_rule_id};

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

const NO_WRITE_ON_CONTROL_ID: RuleId = RuleId::new("worktrees/no-write-on-control");
const LAYOUT_CONSISTENT_ID: RuleId = RuleId::new("worktrees/layout-consistent");

/// `worktrees/no-write-on-control` — flag staged commits in the control checkout.
pub(crate) struct NoWriteOnControlRule;

impl Rule for NoWriteOnControlRule {
    fn id(&self) -> RuleId {
        NO_WRITE_ON_CONTROL_ID
    }

    fn severity(&self) -> RuleSeverity {
        RuleSeverity::Error
    }

    fn description(&self) -> &'static str {
        "Reject commits made directly in the control / default-branch worktree."
    }

    fn gate(&self) -> Option<&'static str> {
        Some("worktrees.enabled == true")
    }

    fn is_active(&self, config: &ItoConfig) -> bool {
        config.worktrees.enabled
    }

    fn check(&self, ctx: &RuleContext<'_>) -> Result<Vec<ValidationIssue>, CoreError> {
        // Skip cheaply when there is nothing staged. The engine treats the
        // empty result as "rule passed".
        if ctx.staged.is_empty() {
            return Ok(Vec::new());
        }

        let Some(branch) = current_branch(ctx.runner, ctx.project_root)? else {
            // Detached HEAD or git failure — nothing to do.
            return Ok(Vec::new());
        };

        let default_branch = ctx.config.worktrees.default_branch.trim();
        if default_branch.is_empty() || branch != default_branch {
            return Ok(Vec::new());
        }

        let issue = error(
            ".",
            format!(
                "Staged commits detected on the control / default-branch worktree (branch `{branch}`). \
                 Why: Ito's worktree workflow expects writes to live in change-specific worktrees so \
                 the control checkout stays clean and history stays separable per change. \
                 Fix: move the staged changes to a change worktree before committing.",
            ),
        );
        let issue = with_rule_id(issue, NO_WRITE_ON_CONTROL_ID.as_str());
        let issue = with_metadata(
            issue,
            serde_json::json!({
                "fix": "Run `ito worktree ensure --change <change-id>` and re-stage there.",
                "default_branch": branch,
                "staged_count": ctx.staged.len(),
            }),
        );

        Ok(vec![issue])
    }
}

/// Read the current branch name via `git rev-parse --abbrev-ref HEAD`.
///
/// Returns `Ok(None)` for detached HEAD (`HEAD`) or when the underlying
/// command fails non-fatally (rule passes silently in those cases).
/// Returns an error only when `git` cannot be spawned at all.
fn current_branch(
    runner: &dyn ProcessRunner,
    project_root: &Path,
) -> Result<Option<String>, CoreError> {
    let request = ProcessRequest::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(project_root);

    let output = runner.run(&request).map_err(|err| {
        CoreError::process(format!(
            "Cannot determine the current git branch.\n\
             Git command failed to run: {err}\n\
             Fix: ensure git is installed and `{root}` is a git repository.",
            root = project_root.display(),
        ))
    })?;

    if !output.success {
        return Ok(None);
    }

    let trimmed = output.stdout.trim();
    if trimmed.is_empty() || trimmed == "HEAD" {
        Ok(None)
    } else {
        Ok(Some(trimmed.to_string()))
    }
}

/// `worktrees/layout-consistent` — minimal layout drift checks.
pub(crate) struct LayoutConsistentRule;

impl Rule for LayoutConsistentRule {
    fn id(&self) -> RuleId {
        LAYOUT_CONSISTENT_ID
    }

    fn severity(&self) -> RuleSeverity {
        RuleSeverity::Warning
    }

    fn description(&self) -> &'static str {
        "Worktree layout configuration matches the resolved strategy and gitignore."
    }

    fn gate(&self) -> Option<&'static str> {
        Some("worktrees.enabled == true")
    }

    fn is_active(&self, config: &ItoConfig) -> bool {
        config.worktrees.enabled
    }

    fn check(&self, ctx: &RuleContext<'_>) -> Result<Vec<ValidationIssue>, CoreError> {
        let mut issues = Vec::new();

        let dir_name = ctx.config.worktrees.layout.dir_name.trim();

        if dir_name.is_empty() {
            let issue = warning(
                ".ito/config.json",
                "`worktrees.layout.dir_name` is empty; worktree directory placement is undefined.",
            );
            let issue = with_rule_id(issue, LAYOUT_CONSISTENT_ID.as_str());
            issues.push(with_metadata(
                issue,
                serde_json::json!({
                    "fix": "Set `worktrees.layout.dir_name` to a non-empty directory name (default: `ito-worktrees`).",
                }),
            ));
        }

        let strategy_requires_gitignore_entry = match ctx.config.worktrees.strategy {
            WorktreeStrategy::CheckoutSubdir => true,
            WorktreeStrategy::CheckoutSiblings | WorktreeStrategy::BareControlSiblings => false,
        };
        if strategy_requires_gitignore_entry
            && !dir_name.is_empty()
            && !gitignore_contains_dir(ctx.project_root, dir_name)?
        {
            let issue = warning(
                ".gitignore",
                format!(
                    "`worktrees.strategy = checkout_subdir` but `.gitignore` does not list `{dir_name}/`. \
                     Untracked worktree files will appear in `git status`.",
                ),
            );
            let issue = with_rule_id(issue, LAYOUT_CONSISTENT_ID.as_str());
            issues.push(with_metadata(
                issue,
                serde_json::json!({
                    "fix": format!("Append `{dir_name}/` to `.gitignore`."),
                }),
            ));
        }

        Ok(issues)
    }
}

/// True when `.gitignore` at `project_root` contains a line matching
/// `{dir_name}/` or `{dir_name}` (trimmed).
///
/// This is a deliberate substring match — it does not parse `.gitignore`
/// syntax (comments starting with `#`, negation patterns starting with
/// `!`, or glob patterns). For the WARNING-level
/// `worktrees/layout-consistent` rule that consumes it, false positives
/// (i.e. claiming an entry exists when a comment-only line matches) are
/// preferable to false negatives (silently letting drift through), and
/// the canonical entry is always a literal directory name.
fn gitignore_contains_dir(project_root: &Path, dir_name: &str) -> Result<bool, CoreError> {
    let gitignore = project_root.join(".gitignore");
    if !gitignore.exists() {
        return Ok(false);
    }
    let content = std::fs::read_to_string(&gitignore).map_err(|e| {
        CoreError::io(
            format!(
                "Cannot read `{path}` to check `worktrees/layout-consistent`.\n\
                 Why: filesystem error.\n\
                 Fix: confirm read permissions on `{path}`.",
                path = gitignore.display(),
            ),
            e,
        )
    })?;

    let with_slash = format!("{dir_name}/");
    Ok(content
        .lines()
        .map(str::trim)
        .any(|line| line == dir_name || line == with_slash))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::process::{ProcessExecutionError, ProcessOutput};
    use crate::validate_repo::staged::StagedFiles;
    use ito_config::types::{ItoConfig, WorktreesConfig};
    use std::path::PathBuf;
    use std::time::Duration;
    use tempfile::TempDir;

    /// Test runner that returns canned output for git commands.
    struct CannedRunner {
        stdout: String,
        success: bool,
    }

    impl CannedRunner {
        fn branch(branch: &str) -> Self {
            Self {
                stdout: format!("{branch}\n"),
                success: true,
            }
        }

        fn detached() -> Self {
            Self {
                stdout: "HEAD\n".to_string(),
                success: true,
            }
        }

        fn failed() -> Self {
            Self {
                stdout: String::new(),
                success: false,
            }
        }
    }

    impl ProcessRunner for CannedRunner {
        fn run(&self, _request: &ProcessRequest) -> Result<ProcessOutput, ProcessExecutionError> {
            Ok(ProcessOutput {
                exit_code: if self.success { 0 } else { 1 },
                success: self.success,
                stdout: self.stdout.clone(),
                stderr: String::new(),
                timed_out: false,
            })
        }
        fn run_with_timeout(
            &self,
            request: &ProcessRequest,
            _timeout: Duration,
        ) -> Result<ProcessOutput, ProcessExecutionError> {
            self.run(request)
        }
    }

    fn config_with_worktrees(enabled: bool, strategy: WorktreeStrategy) -> ItoConfig {
        ItoConfig {
            worktrees: WorktreesConfig {
                enabled,
                strategy,
                ..WorktreesConfig::default()
            },
            ..ItoConfig::default()
        }
    }

    #[test]
    fn no_write_on_control_inactive_when_worktrees_disabled() {
        let cfg = config_with_worktrees(false, WorktreeStrategy::CheckoutSubdir);
        assert!(!NoWriteOnControlRule.is_active(&cfg));
    }

    #[test]
    fn no_write_on_control_active_when_worktrees_enabled() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        assert!(NoWriteOnControlRule.is_active(&cfg));
    }

    #[test]
    fn no_write_on_control_passes_when_no_staged_files() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        let tmp = TempDir::new().unwrap();
        let runner = CannedRunner::branch("main");
        let staged = StagedFiles::empty();
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = NoWriteOnControlRule.check(&ctx).unwrap();
        assert!(issues.is_empty(), "no staged files => rule passes");
    }

    #[test]
    fn no_write_on_control_fails_when_on_default_branch_with_staged_files() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        // default_branch defaults to "main".
        assert_eq!(cfg.worktrees.default_branch, "main");

        let tmp = TempDir::new().unwrap();
        let runner = CannedRunner::branch("main");
        let staged = StagedFiles::from_paths(vec![PathBuf::from("README.md")]);
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = NoWriteOnControlRule.check(&ctx).unwrap();
        assert_eq!(issues.len(), 1, "expected one error, got {issues:?}");
        assert_eq!(issues[0].level, "ERROR");
        assert_eq!(
            issues[0].rule_id.as_deref(),
            Some(NO_WRITE_ON_CONTROL_ID.as_str()),
        );
    }

    #[test]
    fn no_write_on_control_passes_in_change_branch() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        let tmp = TempDir::new().unwrap();
        let runner = CannedRunner::branch("011-05_demo");
        let staged = StagedFiles::from_paths(vec![PathBuf::from("README.md")]);
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = NoWriteOnControlRule.check(&ctx).unwrap();
        assert!(
            issues.is_empty(),
            "change branch with staged files should pass; got {issues:?}",
        );
    }

    #[test]
    fn no_write_on_control_passes_on_detached_head() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        let tmp = TempDir::new().unwrap();
        let runner = CannedRunner::detached();
        let staged = StagedFiles::from_paths(vec![PathBuf::from("README.md")]);
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = NoWriteOnControlRule.check(&ctx).unwrap();
        assert!(issues.is_empty(), "detached HEAD => rule passes silently");
    }

    #[test]
    fn no_write_on_control_passes_when_git_command_fails() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        let tmp = TempDir::new().unwrap();
        let runner = CannedRunner::failed();
        let staged = StagedFiles::from_paths(vec![PathBuf::from("README.md")]);
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = NoWriteOnControlRule.check(&ctx).unwrap();
        assert!(issues.is_empty(), "git failure => rule passes silently");
    }

    #[test]
    fn layout_consistent_inactive_when_worktrees_disabled() {
        let cfg = config_with_worktrees(false, WorktreeStrategy::CheckoutSubdir);
        assert!(!LayoutConsistentRule.is_active(&cfg));
    }

    #[test]
    fn layout_consistent_warns_on_empty_dir_name() {
        let mut cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        cfg.worktrees.layout.dir_name = String::new();

        let tmp = TempDir::new().unwrap();
        let runner = CannedRunner::branch("main");
        let staged = StagedFiles::empty();
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = LayoutConsistentRule.check(&ctx).unwrap();
        assert_eq!(issues.len(), 1);
        assert_eq!(
            issues[0].rule_id.as_deref(),
            Some(LAYOUT_CONSISTENT_ID.as_str()),
        );
        assert!(issues[0].message.contains("dir_name"));
    }

    #[test]
    fn layout_consistent_warns_when_checkout_subdir_missing_gitignore_entry() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        let tmp = TempDir::new().unwrap();
        // .gitignore exists but does not contain ito-worktrees/.
        std::fs::write(tmp.path().join(".gitignore"), "target/\n").unwrap();

        let runner = CannedRunner::branch("main");
        let staged = StagedFiles::empty();
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = LayoutConsistentRule.check(&ctx).unwrap();
        assert_eq!(issues.len(), 1, "expected one warning, got {issues:?}");
        assert!(
            issues[0].message.contains("ito-worktrees"),
            "warning should name the missing dir; got: {}",
            issues[0].message,
        );
    }

    #[test]
    fn layout_consistent_quiet_when_gitignore_has_entry() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSubdir);
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join(".gitignore"), "ito-worktrees/\n").unwrap();

        let runner = CannedRunner::branch("main");
        let staged = StagedFiles::empty();
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = LayoutConsistentRule.check(&ctx).unwrap();
        assert!(issues.is_empty(), "gitignore has entry => no warning");
    }

    #[test]
    fn layout_consistent_quiet_for_bare_control_siblings_strategy() {
        let cfg = config_with_worktrees(true, WorktreeStrategy::BareControlSiblings);
        let tmp = TempDir::new().unwrap();
        // No .gitignore at all — bare_control_siblings does not require one.
        let runner = CannedRunner::branch("main");
        let staged = StagedFiles::empty();
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = LayoutConsistentRule.check(&ctx).unwrap();
        assert!(
            issues.is_empty(),
            "bare_control_siblings should not require a gitignore entry; got {issues:?}",
        );
    }

    #[test]
    fn layout_consistent_quiet_for_checkout_siblings_strategy() {
        // CheckoutSiblings places worktrees alongside the project (e.g.
        // `<parent>/<project>-ito-worktrees/`); the project's own
        // `.gitignore` therefore does not need a `<dir_name>/` entry.
        let cfg = config_with_worktrees(true, WorktreeStrategy::CheckoutSiblings);
        let tmp = TempDir::new().unwrap();
        // No .gitignore at all.
        let runner = CannedRunner::branch("main");
        let staged = StagedFiles::empty();
        let ctx = RuleContext::new(&cfg, tmp.path(), &staged, &runner);

        let issues = LayoutConsistentRule.check(&ctx).unwrap();
        assert!(
            issues.is_empty(),
            "checkout_siblings should not require a gitignore entry; got {issues:?}",
        );
    }
}