Skip to main content

thoughts_tool/workspace/
mod.rs

1use anyhow::Context;
2use anyhow::Result;
3use atomicwrites::AtomicFile;
4use atomicwrites::OverwriteBehavior;
5use serde_json::json;
6use std::fs;
7use std::io::Write;
8use std::path::Path;
9use std::path::PathBuf;
10use tracing::debug;
11
12use crate::config::Mount;
13use crate::config::RepoConfigManager;
14use crate::git::utils::find_repo_root;
15use crate::git::utils::get_control_repo_root;
16use crate::git::utils::get_current_branch;
17use crate::git::utils::get_remote_url;
18use crate::mount::MountResolver;
19
20// Centralized main/master detection
21fn is_main_like(branch: &str) -> bool {
22    matches!(branch, "main" | "master")
23}
24
25// Standardized lockout error text for CLI + MCP
26fn main_branch_lockout_error(branch: &str) -> anyhow::Error {
27    anyhow::anyhow!(
28        "Branch protection: operations that create or access branch-specific work are blocked on '{}'.\n\
29         Create a feature branch first, then re-run:\n  git checkout -b my/feature\n\n\
30         Note: branch-agnostic commands like 'thoughts work list' and 'thoughts references list' are allowed on main.",
31        branch
32    )
33}
34
35// Detect weekly dir formats "YYYY-WWW" and legacy "YYYY_week_WW"
36fn is_weekly_dir_name(name: &str) -> bool {
37    // Pattern 1: YYYY-WWW (e.g., "2025-W01")
38    if let Some((year, rest)) = name.split_once("-W")
39        && year.len() == 4
40        && year.chars().all(|c| c.is_ascii_digit())
41        && rest.len() == 2
42        && rest.chars().all(|c| c.is_ascii_digit())
43        && let Ok(w) = rest.parse::<u32>()
44    {
45        return (1..=53).contains(&w);
46    }
47    // Pattern 2 (legacy): YYYY_week_WW (e.g., "2025_week_01")
48    if let Some((year, rest)) = name.split_once("_week_")
49        && year.len() == 4
50        && year.chars().all(|c| c.is_ascii_digit())
51        && rest.len() == 2
52        && rest.chars().all(|c| c.is_ascii_digit())
53        && let Ok(w) = rest.parse::<u32>()
54    {
55        return (1..=53).contains(&w);
56    }
57    false
58}
59
60// Choose collision-free archive name (name, name-migrated, name-migrated-2, ...)
61fn next_archive_name(completed_dir: &Path, base_name: &str) -> PathBuf {
62    let candidate = completed_dir.join(base_name);
63    if !candidate.exists() {
64        return candidate;
65    }
66    let mut i = 1usize;
67    loop {
68        let with_suffix = if i == 1 {
69            format!("{}-migrated", base_name)
70        } else {
71            format!("{}-migrated-{}", base_name, i)
72        };
73        let p = completed_dir.join(with_suffix);
74        if !p.exists() {
75            return p;
76        }
77        i += 1;
78    }
79}
80
81// Auto-archive weekly dirs from thoughts_root/* -> thoughts_root/completed/*
82fn auto_archive_weekly_dirs(thoughts_root: &Path) -> Result<()> {
83    let completed = thoughts_root.join("completed");
84    std::fs::create_dir_all(&completed).ok();
85    for entry in std::fs::read_dir(thoughts_root)? {
86        let entry = entry?;
87        let p = entry.path();
88        if !p.is_dir() {
89            continue;
90        }
91        let name = entry.file_name();
92        let name = name.to_string_lossy();
93        if name == "completed" || name == "active" {
94            continue;
95        }
96        if is_weekly_dir_name(&name) {
97            let dest = next_archive_name(&completed, &name);
98            debug!("Archiving weekly dir {} -> {}", p.display(), dest.display());
99            std::fs::rename(&p, &dest).with_context(|| {
100                format!(
101                    "Failed to archive weekly dir {} -> {}",
102                    p.display(),
103                    dest.display()
104                )
105            })?;
106        }
107    }
108    Ok(())
109}
110
111/// Migrate from `thoughts/active/*` structure to `thoughts/*`.
112///
113/// Moves directories from active/ to the root and creates a compatibility
114/// symlink `active -> .` for backward compatibility.
115fn migrate_active_layer(thoughts_root: &Path) -> Result<()> {
116    let active = thoughts_root.join("active");
117
118    // Check if active is a real directory (not already a symlink)
119    if active.exists() && active.is_dir() && !active.is_symlink() {
120        debug!("Migrating active/ layer at {}", thoughts_root.display());
121
122        // Move all directories from active/ to thoughts_root
123        for entry in std::fs::read_dir(&active)? {
124            let entry = entry?;
125            let p = entry.path();
126            if p.is_dir() {
127                let name = entry.file_name();
128                let newp = thoughts_root.join(&name);
129                if !newp.exists() {
130                    std::fs::rename(&p, &newp).with_context(|| {
131                        format!("Failed to move {} to {}", p.display(), newp.display())
132                    })?;
133                    debug!("Migrated {} -> {}", p.display(), newp.display());
134                }
135            }
136        }
137
138        // Create compatibility symlink active -> .
139        #[cfg(unix)]
140        {
141            use std::os::unix::fs as unixfs;
142            // Only remove if it's now empty
143            if std::fs::read_dir(&active)?.next().is_none() {
144                let _ = std::fs::remove_dir(&active);
145                if unixfs::symlink(".", &active).is_ok() {
146                    debug!("Created compatibility symlink: active -> .");
147                }
148            }
149        }
150    }
151    Ok(())
152}
153
154/// Paths for the current active work directory
155#[derive(Debug, Clone)]
156pub struct ActiveWork {
157    pub dir_name: String,
158    pub base: PathBuf,
159    pub research: PathBuf,
160    pub plans: PathBuf,
161    pub artifacts: PathBuf,
162    pub logs: PathBuf,
163}
164
165/// Resolve thoughts root via configured thoughts_mount
166fn resolve_thoughts_root() -> Result<PathBuf> {
167    let control_root = get_control_repo_root(&std::env::current_dir()?)?;
168    let mgr = RepoConfigManager::new(control_root);
169    let ds = mgr.load_desired_state()?.ok_or_else(|| {
170        anyhow::anyhow!("No repository configuration found. Run 'thoughts init'.")
171    })?;
172
173    let tm = ds.thoughts_mount.as_ref().ok_or_else(|| {
174        anyhow::anyhow!(
175            "No thoughts_mount configured in repository configuration.\n\
176             Add thoughts_mount to .thoughts/config.json and run 'thoughts mount update'."
177        )
178    })?;
179
180    let resolver = MountResolver::new()?;
181    let mount = Mount::Git {
182        url: tm.remote.clone(),
183        subpath: tm.subpath.clone(),
184        sync: tm.sync,
185    };
186
187    resolver
188        .resolve_mount(&mount)
189        .context("Thoughts mount not cloned. Run 'thoughts sync' or 'thoughts mount update' first.")
190}
191
192/// Public helper for commands that must not create dirs (e.g., work complete).
193/// Runs migration and auto-archive, then enforces branch lockout.
194pub fn check_branch_allowed() -> Result<()> {
195    let thoughts_root = resolve_thoughts_root()?;
196    // Preserve legacy migration then auto-archive
197    migrate_active_layer(&thoughts_root)?;
198    auto_archive_weekly_dirs(&thoughts_root)?;
199    let code_root = find_repo_root(&std::env::current_dir()?)?;
200    let branch = get_current_branch(&code_root)?;
201    if is_main_like(&branch) {
202        return Err(main_branch_lockout_error(&branch));
203    }
204    Ok(())
205}
206
207/// Ensure active work directory exists with subdirs and manifest.
208/// Fails on main/master; never creates weekly directories.
209pub fn ensure_active_work() -> Result<ActiveWork> {
210    let thoughts_root = resolve_thoughts_root()?;
211
212    // Run migrations before any branch checks
213    migrate_active_layer(&thoughts_root)?;
214    auto_archive_weekly_dirs(&thoughts_root)?;
215
216    // Get branch and enforce lockout
217    let code_root = find_repo_root(&std::env::current_dir()?)?;
218    let branch = get_current_branch(&code_root)?;
219    if is_main_like(&branch) {
220        return Err(main_branch_lockout_error(&branch));
221    }
222
223    // Use branch name directly - no weekly directories
224    let dir_name = branch.clone();
225    let base = thoughts_root.join(&dir_name);
226
227    // Create structure if missing
228    if !base.exists() {
229        fs::create_dir_all(base.join("research")).context("Failed to create research directory")?;
230        fs::create_dir_all(base.join("plans")).context("Failed to create plans directory")?;
231        fs::create_dir_all(base.join("artifacts"))
232            .context("Failed to create artifacts directory")?;
233        fs::create_dir_all(base.join("logs")).context("Failed to create logs directory")?;
234
235        // Create manifest.json atomically
236        let source_repo = get_remote_url(&code_root).unwrap_or_else(|_| "unknown".to_string());
237        let manifest = json!({
238            "source_repo": source_repo,
239            "branch_or_week": dir_name,
240            "started_at": chrono::Utc::now().to_rfc3339(),
241        });
242
243        let manifest_path = base.join("manifest.json");
244        AtomicFile::new(&manifest_path, OverwriteBehavior::AllowOverwrite)
245            .write(|f| f.write_all(serde_json::to_string_pretty(&manifest)?.as_bytes()))
246            .with_context(|| format!("Failed to write manifest at {}", manifest_path.display()))?;
247    } else {
248        // Ensure subdirs exist even if base exists
249        for sub in ["research", "plans", "artifacts", "logs"] {
250            let subdir = base.join(sub);
251            if !subdir.exists() {
252                fs::create_dir_all(&subdir)
253                    .with_context(|| format!("Failed to ensure {} directory", sub))?;
254            }
255        }
256        // Ensure manifest exists
257        let manifest_path = base.join("manifest.json");
258        if !manifest_path.exists() {
259            let source_repo = get_remote_url(&code_root).unwrap_or_else(|_| "unknown".to_string());
260            let manifest = json!({
261                "source_repo": source_repo,
262                "branch_or_week": dir_name,
263                "started_at": chrono::Utc::now().to_rfc3339(),
264            });
265            AtomicFile::new(&manifest_path, OverwriteBehavior::AllowOverwrite)
266                .write(|f| f.write_all(serde_json::to_string_pretty(&manifest)?.as_bytes()))
267                .with_context(|| {
268                    format!("Failed to write manifest at {}", manifest_path.display())
269                })?;
270        }
271    }
272
273    Ok(ActiveWork {
274        dir_name: dir_name.clone(),
275        base: base.clone(),
276        research: base.join("research"),
277        plans: base.join("plans"),
278        artifacts: base.join("artifacts"),
279        logs: base.join("logs"),
280    })
281}
282
283#[cfg(test)]
284mod branch_lock_tests {
285    use super::*;
286    use std::fs;
287    use tempfile::TempDir;
288
289    #[test]
290    fn is_main_like_detection() {
291        assert!(is_main_like("main"));
292        assert!(is_main_like("master"));
293        assert!(!is_main_like("feature/login"));
294        assert!(!is_main_like("main-feature"));
295        assert!(!is_main_like("my-master"));
296    }
297
298    #[test]
299    fn weekly_name_detection() {
300        // Valid new format: YYYY-WWW
301        assert!(is_weekly_dir_name("2025-W01"));
302        assert!(is_weekly_dir_name("2024-W53"));
303        assert!(is_weekly_dir_name("2020-W10"));
304
305        // Valid legacy format: YYYY_week_WW
306        assert!(is_weekly_dir_name("2024_week_52"));
307        assert!(is_weekly_dir_name("2025_week_01"));
308
309        // Invalid: branch names
310        assert!(!is_weekly_dir_name("feat/login-page"));
311        assert!(!is_weekly_dir_name("main"));
312        assert!(!is_weekly_dir_name("master"));
313        assert!(!is_weekly_dir_name("feature-2025-W01"));
314
315        // Invalid: out of range weeks
316        assert!(!is_weekly_dir_name("2025-W00"));
317        assert!(!is_weekly_dir_name("2025-W54"));
318        assert!(!is_weekly_dir_name("2025_week_00"));
319        assert!(!is_weekly_dir_name("2025_week_54"));
320
321        // Invalid: malformed
322        assert!(!is_weekly_dir_name("2025-W1")); // single digit week
323        assert!(!is_weekly_dir_name("202-W01")); // 3 digit year
324        assert!(!is_weekly_dir_name("2025_week_1")); // single digit week
325    }
326
327    #[test]
328    fn auto_archive_moves_weekly_dirs() {
329        let temp = TempDir::new().unwrap();
330        let root = temp.path();
331
332        // Create weekly dirs to archive
333        fs::create_dir_all(root.join("2025-W01")).unwrap();
334        fs::create_dir_all(root.join("2024_week_52")).unwrap();
335        // Create non-weekly dir that should NOT be archived
336        fs::create_dir_all(root.join("feature-branch")).unwrap();
337
338        auto_archive_weekly_dirs(root).unwrap();
339
340        // Weekly dirs should be moved to completed/
341        assert!(!root.join("2025-W01").exists());
342        assert!(!root.join("2024_week_52").exists());
343        assert!(root.join("completed/2025-W01").exists());
344        assert!(root.join("completed/2024_week_52").exists());
345
346        // Non-weekly dir should remain
347        assert!(root.join("feature-branch").exists());
348    }
349
350    #[test]
351    fn auto_archive_handles_collision() {
352        let temp = TempDir::new().unwrap();
353        let root = temp.path();
354
355        // Create completed dir with existing entry
356        fs::create_dir_all(root.join("completed/2025-W01")).unwrap();
357        // Create weekly dir to archive (will collide)
358        fs::create_dir_all(root.join("2025-W01")).unwrap();
359
360        auto_archive_weekly_dirs(root).unwrap();
361
362        // Should be archived with -migrated suffix
363        assert!(!root.join("2025-W01").exists());
364        assert!(root.join("completed/2025-W01").exists());
365        assert!(root.join("completed/2025-W01-migrated").exists());
366    }
367
368    #[test]
369    fn auto_archive_multiple_collision() {
370        let temp = TempDir::new().unwrap();
371        let root = temp.path();
372
373        // Pre-existing archived entries that will cause multiple collisions
374        fs::create_dir_all(root.join("completed/2025-W01")).unwrap();
375        fs::create_dir_all(root.join("completed/2025-W01-migrated")).unwrap();
376
377        // Create the weekly dir that should be archived and collide twice
378        fs::create_dir_all(root.join("2025-W01")).unwrap();
379
380        auto_archive_weekly_dirs(root).unwrap();
381
382        // Source should be moved
383        assert!(!root.join("2025-W01").exists());
384        // Original and first migrated remain
385        assert!(root.join("completed/2025-W01").exists());
386        assert!(root.join("completed/2025-W01-migrated").exists());
387        // New archive should be suffixed with -migrated-2
388        assert!(root.join("completed/2025-W01-migrated-2").exists());
389    }
390
391    #[test]
392    fn auto_archive_idempotent() {
393        let temp = TempDir::new().unwrap();
394        let root = temp.path();
395
396        // No weekly dirs to archive
397        fs::create_dir_all(root.join("feature-branch")).unwrap();
398        fs::create_dir_all(root.join("completed")).unwrap();
399
400        // Should not fail and should not move anything
401        auto_archive_weekly_dirs(root).unwrap();
402        auto_archive_weekly_dirs(root).unwrap();
403
404        assert!(root.join("feature-branch").exists());
405    }
406
407    #[test]
408    fn lockout_error_message_format() {
409        let err = main_branch_lockout_error("main");
410        let msg = err.to_string();
411        // Verify standardized message components
412        assert!(msg.contains("Branch protection"));
413        assert!(msg.contains("'main'"));
414        assert!(msg.contains("git checkout -b"));
415        assert!(msg.contains("work list"));
416    }
417}