thoughts_tool/workspace/
mod.rs1use 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
20fn is_main_like(branch: &str) -> bool {
22 matches!(branch, "main" | "master")
23}
24
25fn 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
35fn is_weekly_dir_name(name: &str) -> bool {
37 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 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
60fn 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
81fn 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
111fn migrate_active_layer(thoughts_root: &Path) -> Result<()> {
116 let active = thoughts_root.join("active");
117
118 if active.exists() && active.is_dir() && !active.is_symlink() {
120 debug!("Migrating active/ layer at {}", thoughts_root.display());
121
122 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 #[cfg(unix)]
140 {
141 use std::os::unix::fs as unixfs;
142 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#[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
165fn 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
192pub fn check_branch_allowed() -> Result<()> {
195 let thoughts_root = resolve_thoughts_root()?;
196 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
207pub fn ensure_active_work() -> Result<ActiveWork> {
210 let thoughts_root = resolve_thoughts_root()?;
211
212 migrate_active_layer(&thoughts_root)?;
214 auto_archive_weekly_dirs(&thoughts_root)?;
215
216 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 let dir_name = branch.clone();
225 let base = thoughts_root.join(&dir_name);
226
227 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 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 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 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 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 assert!(is_weekly_dir_name("2024_week_52"));
307 assert!(is_weekly_dir_name("2025_week_01"));
308
309 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 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 assert!(!is_weekly_dir_name("2025-W1")); assert!(!is_weekly_dir_name("202-W01")); assert!(!is_weekly_dir_name("2025_week_1")); }
326
327 #[test]
328 fn auto_archive_moves_weekly_dirs() {
329 let temp = TempDir::new().unwrap();
330 let root = temp.path();
331
332 fs::create_dir_all(root.join("2025-W01")).unwrap();
334 fs::create_dir_all(root.join("2024_week_52")).unwrap();
335 fs::create_dir_all(root.join("feature-branch")).unwrap();
337
338 auto_archive_weekly_dirs(root).unwrap();
339
340 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 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 fs::create_dir_all(root.join("completed/2025-W01")).unwrap();
357 fs::create_dir_all(root.join("2025-W01")).unwrap();
359
360 auto_archive_weekly_dirs(root).unwrap();
361
362 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 fs::create_dir_all(root.join("completed/2025-W01")).unwrap();
375 fs::create_dir_all(root.join("completed/2025-W01-migrated")).unwrap();
376
377 fs::create_dir_all(root.join("2025-W01")).unwrap();
379
380 auto_archive_weekly_dirs(root).unwrap();
381
382 assert!(!root.join("2025-W01").exists());
384 assert!(root.join("completed/2025-W01").exists());
386 assert!(root.join("completed/2025-W01-migrated").exists());
387 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 fs::create_dir_all(root.join("feature-branch")).unwrap();
398 fs::create_dir_all(root.join("completed")).unwrap();
399
400 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 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}