thoughts-bin 0.1.12

CLI for flexible thought management using filesystem mounts
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use crate::config::RepoConfigManager;
use crate::git::utils::get_control_repo_root;
use crate::git::utils::get_current_repo;
use crate::git::utils::get_main_repo_for_worktree;
use crate::git::utils::is_worktree;
use crate::utils::git::ensure_gitignore_entry;
use crate::utils::paths::ensure_dir;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use colored::Colorize;
use std::fs;
use std::path::Path;
use std::path::PathBuf;

pub async fn execute(force: bool) -> Result<()> {
    // Ensure we're in a git repository
    let repo_root = get_current_repo().context("Not in a git repository. Run 'git init' first.")?;

    // Check if we're in a worktree
    if is_worktree(&repo_root)? {
        eprintln!("{}: Detected git worktree", "Info".cyan());

        // Get the main repository path
        let main_repo = get_main_repo_for_worktree(&repo_root)?;
        eprintln!("Main repository: {}", main_repo.display());

        let main_thoughts_data = main_repo.join(".thoughts-data");
        let worktree_thoughts_data = repo_root.join(".thoughts-data");

        // Ensure main repository is initialized first
        if !main_thoughts_data.exists() {
            eprintln!("{}: Main repository is not initialized", "Error".red());
            eprintln!("Please run 'thoughts init' in the main repository first:");
            eprintln!("  cd {}", main_repo.display());
            eprintln!("  thoughts init");
            return Err(anyhow!("Main repository must be initialized first"));
        }

        // Idempotent check-and-act for worktree .thoughts-data symlink
        let mut had_errors = false;
        match ensure_symlink_abs_target(&worktree_thoughts_data, &main_thoughts_data, force) {
            Ok(SymlinkOutcome::Created) => {
                eprintln!(
                    "{}: Created .thoughts-data symlink to main repository",
                    "Success".green()
                );
            }
            Ok(SymlinkOutcome::AlreadyCorrect) => {
                eprintln!("{}: .thoughts-data symlink already correct", "Info".cyan());
            }
            Ok(SymlinkOutcome::Fixed) => {
                eprintln!(
                    "{}: Fixed .thoughts-data symlink to main repository",
                    "Success".green()
                );
            }
            Ok(SymlinkOutcome::NeedsForce { current_target }) => {
                had_errors = true;
                eprintln!(
                    "{}: .thoughts-data symlink points to {} but should point to {}",
                    "Error".red(),
                    current_target.display(),
                    main_thoughts_data.display()
                );
                eprintln!(
                    "Re-run with {} to update the symlink safely.",
                    "--force".cyan()
                );
            }
            Ok(SymlinkOutcome::NonSymlinkExists) => {
                had_errors = true;
                eprintln!(
                    "{}: .thoughts-data exists but is not a symlink",
                    "Error".red()
                );
                eprintln!(
                    "Please remove/rename it manually (not removed automatically to avoid data loss)."
                );
            }
            Err(e) => {
                had_errors = true;
                eprintln!(
                    "{}: Failed to ensure .thoughts-data symlink: {}",
                    "Error".red(),
                    e
                );
            }
        }

        // Get mount dirs from config to create workspace symlinks
        let repo_config_manager = RepoConfigManager::new(get_control_repo_root(&repo_root)?);
        let mount_dirs = if let Some(desired) = repo_config_manager.load_desired_state()? {
            desired.mount_dirs
        } else {
            // Use v1 defaults that will map to v2
            crate::config::MountDirsV2 {
                thoughts: "thoughts".into(),
                context: "context".into(),
                references: "references".into(),
            }
        };

        // Create the three workspace symlinks in the worktree
        let thoughts_link = repo_root.join(&mount_dirs.thoughts);
        let context_link = repo_root.join(&mount_dirs.context);
        let references_link = repo_root.join(&mount_dirs.references);

        let thoughts_relative = format!(".thoughts-data/{}", mount_dirs.thoughts);
        let context_relative = format!(".thoughts-data/{}", mount_dirs.context);
        let references_relative = format!(".thoughts-data/{}", mount_dirs.references);

        // Idempotent workspace symlinks (relative links to .thoughts-data/*)
        for (name, link, rel, abs_target) in [
            (
                &mount_dirs.thoughts,
                &thoughts_link,
                &thoughts_relative,
                main_thoughts_data.join(&mount_dirs.thoughts),
            ),
            (
                &mount_dirs.context,
                &context_link,
                &context_relative,
                main_thoughts_data.join(&mount_dirs.context),
            ),
            (
                &mount_dirs.references,
                &references_link,
                &references_relative,
                main_thoughts_data.join(&mount_dirs.references),
            ),
        ] {
            match ensure_symlink_rel_target(link, rel, &abs_target, force) {
                Ok(SymlinkOutcome::Created) => {
                    eprintln!("{}: Created {} -> {}", "Success".green(), name, rel);
                }
                Ok(SymlinkOutcome::AlreadyCorrect) => {
                    eprintln!("{}: {} symlink already correct", "Info".cyan(), name);
                }
                Ok(SymlinkOutcome::Fixed) => {
                    eprintln!("{}: Fixed {} symlink", "Success".green(), name);
                }
                Ok(SymlinkOutcome::NeedsForce { current_target }) => {
                    had_errors = true;
                    eprintln!(
                        "{}: {} symlink points to {} but should be {}",
                        "Error".red(),
                        name,
                        current_target.display(),
                        rel
                    );
                    eprintln!(
                        "Re-run with {} to update the symlink safely.",
                        "--force".cyan()
                    );
                }
                Ok(SymlinkOutcome::NonSymlinkExists) => {
                    had_errors = true;
                    eprintln!("{}: {} exists but is not a symlink", "Error".red(), name);
                    eprintln!(
                        "Please remove/rename it manually (not removed automatically to avoid data loss)."
                    );
                }
                Err(e) => {
                    had_errors = true;
                    eprintln!(
                        "{}: Failed to ensure {} symlink: {}",
                        "Error".red(),
                        name,
                        e
                    );
                }
            }
        }

        // Inject Claude Code permissions (worktree)
        {
            match crate::utils::claude_settings::inject_additional_directories(&repo_root) {
                Ok(summary) => {
                    if !summary.warn_conflicting_denies.is_empty() {
                        eprintln!(
                            "{}: Some allow rules may be shadowed by deny rules: {:?}",
                            "Warning".yellow(),
                            summary.warn_conflicting_denies
                        );
                    }
                    let new_items =
                        summary.added_additional_dirs.len() + summary.added_allow_rules.len();
                    if new_items > 0 {
                        eprintln!(
                            "{}: Updated Claude Code permissions ({} new item{})",
                            "Success".green(),
                            new_items,
                            if new_items == 1 { "" } else { "s" }
                        );
                        eprintln!("  {}", summary.settings_path.display());
                    } else {
                        eprintln!(
                            "{}: Claude Code permissions already present; no changes needed",
                            "Info".cyan()
                        );
                    }
                }
                Err(e) => {
                    eprintln!(
                        "{}: Failed to update Claude Code settings: {}",
                        "Warning".yellow(),
                        e
                    );
                    eprintln!("Proceeding without updating .claude/settings.local.json");
                }
            }
        }

        // Ensure gitignore has backup patterns
        let _ = ensure_gitignore_entry(
            &repo_root,
            "/.claude/settings.local.json.bak",
            Some("Claude settings backup (managed by thoughts)"),
        );
        let _ = ensure_gitignore_entry(
            &repo_root,
            "/.claude/settings.local.json.malformed.*.bak",
            Some("Claude settings quarantine backups (auto-pruned)"),
        );

        if had_errors {
            // Return a genuine error after best-effort injection/gitignore updates
            return Err(anyhow!(
                "One or more symlinks require --force or manual cleanup"
            ));
        }
        eprintln!("{}: Worktree initialization complete!", "Success".green());
        eprintln!("The worktree now shares mounts with the main repository.");
        eprintln!("\nCreated workspace symlinks:");
        eprintln!("  {} -> {}", mount_dirs.thoughts, thoughts_relative);
        eprintln!("  {} -> {}", mount_dirs.context, context_relative);
        eprintln!("  {} -> {}", mount_dirs.references, references_relative);

        return Ok(());
    }

    // Continue with normal initialization for main repository...
    println!(
        "Initializing thoughts for repository at: {}",
        repo_root.display()
    );

    // Load or create repository configuration
    let repo_config_manager = RepoConfigManager::new(repo_root.clone());
    let was_v1 = matches!(repo_config_manager.peek_config_version()?, Some(v) if v == "1.0");
    let cfg_v2 = repo_config_manager
        .ensure_v2_default()
        .context("Failed to create repository configuration")?;
    let mount_dirs = cfg_v2.mount_dirs.clone();

    if was_v1 {
        println!(
            "Upgraded to v2 config. A v1 backup was created if non-empty. See MIGRATION_V1_TO_V2.md"
        );
    }

    // Create the actual thoughts directory structure
    let thoughts_dir = repo_root.join(".thoughts-data");
    ensure_dir(&thoughts_dir)?;

    let thoughts_target_dir = thoughts_dir.join(&mount_dirs.thoughts);
    let context_target_dir = thoughts_dir.join(&mount_dirs.context);
    let references_target_dir = thoughts_dir.join(&mount_dirs.references);

    ensure_dir(&thoughts_target_dir)?;
    ensure_dir(&context_target_dir)?;
    ensure_dir(&references_target_dir)?;

    // Resolve symlink targets and ensure idempotently
    let thoughts_link = repo_root.join(&mount_dirs.thoughts);
    let context_link = repo_root.join(&mount_dirs.context);
    let references_link = repo_root.join(&mount_dirs.references);

    let mut had_errors = false;

    // Create or validate symlinks with relative targets
    let thoughts_relative = format!(".thoughts-data/{}", mount_dirs.thoughts);
    let context_relative = format!(".thoughts-data/{}", mount_dirs.context);
    let references_relative = format!(".thoughts-data/{}", mount_dirs.references);

    for (name, link, rel, abs_target) in [
        (
            &mount_dirs.thoughts,
            &thoughts_link,
            &thoughts_relative,
            thoughts_target_dir.clone(),
        ),
        (
            &mount_dirs.context,
            &context_link,
            &context_relative,
            context_target_dir.clone(),
        ),
        (
            &mount_dirs.references,
            &references_link,
            &references_relative,
            references_target_dir.clone(),
        ),
    ] {
        match ensure_symlink_rel_target(link, rel, &abs_target, force) {
            Ok(SymlinkOutcome::Created) => {
                println!("{} Created {} -> {}", "✓".green(), name, rel);
            }
            Ok(SymlinkOutcome::AlreadyCorrect) => {
                println!("{} {} symlink already correct", "Info".cyan(), name);
            }
            Ok(SymlinkOutcome::Fixed) => {
                println!("{} Fixed {} symlink", "✓".green(), name);
            }
            Ok(SymlinkOutcome::NeedsForce { current_target }) => {
                had_errors = true;
                eprintln!(
                    "{}: {} symlink points to {} but should be {}",
                    "Error".red(),
                    name,
                    current_target.display(),
                    rel
                );
                eprintln!(
                    "Re-run with {} to update the symlink safely.",
                    "--force".cyan()
                );
            }
            Ok(SymlinkOutcome::NonSymlinkExists) => {
                had_errors = true;
                eprintln!("{}: {} exists but is not a symlink", "Error".red(), name);
                eprintln!(
                    "Please remove/rename it manually (not removed automatically to avoid data loss)."
                );
            }
            Err(e) => {
                had_errors = true;
                eprintln!(
                    "{}: Failed to ensure {} symlink: {}",
                    "Error".red(),
                    name,
                    e
                );
            }
        }
    }

    // Add to .gitignore - only the data directory needs to be ignored!
    // The symlinks themselves can be tracked by git
    ensure_gitignore_entry(
        &repo_root,
        "/.thoughts-data",
        Some("Thoughts data directory (created by thoughts init)"),
    )?;
    // Also ensure Claude backup patterns (best-effort; ignore errors)
    let _ = ensure_gitignore_entry(
        &repo_root,
        "/.claude/settings.local.json.bak",
        Some("Claude settings backup (managed by thoughts)"),
    );
    let _ = ensure_gitignore_entry(
        &repo_root,
        "/.claude/settings.local.json.malformed.*.bak",
        Some("Claude settings quarantine backups (auto-pruned)"),
    );

    // Create README files if directories are empty
    create_readme_if_empty(
        &thoughts_target_dir,
        "Thoughts Workspace",
        "This is your unified thoughts workspace.\n\n\
         When configured, your personal thoughts repository will be mounted here.\n\n\
         ## Usage\n\n\
         - Configure thoughts mount: Add `thoughts_mount` to your config\n\
         - This provides a single workspace for all your notes across projects\n\
         - Changes here sync to your personal thoughts repository\n",
    )?;

    create_readme_if_empty(
        &context_target_dir,
        "Context Mounts",
        "This directory contains project-specific context and documentation.\n\n\
         These mounts are shared with your team through the repository config.\n\n\
         ## Suggested Mounts\n\n\
         - `docs` - Project documentation\n\
         - `architecture` - System design documents\n\
         - `decisions` - Architectural decision records\n\
         - `planning` - Feature planning and specs\n",
    )?;

    create_readme_if_empty(
        &references_target_dir,
        "Reference Repositories",
        "This directory contains read-only reference repositories.\n\n\
         References are organized by organization/repository.\n\n\
         ## Usage\n\n\
         - Add references: `thoughts references add <url>`\n\
         - Browse code from other repositories\n\
         - All mounts here are read-only for safety\n",
    )?;

    // Note: The actual mounting happens in a separate sync step
    // This init command only sets up the directory structure and configuration

    // Auto-mount all configured mounts
    println!("\n{} mounts...", "Setting up".green());
    match crate::mount::auto_mount::update_active_mounts().await {
        Ok(()) => {}
        Err(e) => {
            eprintln!("{}: Failed to set up mounts: {}", "Warning".yellow(), e);
            eprintln!(
                "Run {} manually to set up mounts",
                "thoughts mount update".cyan()
            );
        }
    }

    // Inject Claude Code permissions (regular repo)
    {
        match crate::utils::claude_settings::inject_additional_directories(&repo_root) {
            Ok(summary) => {
                if !summary.warn_conflicting_denies.is_empty() {
                    println!(
                        "{}: Some allow rules may be shadowed by deny rules: {:?}",
                        "Warning".yellow(),
                        summary.warn_conflicting_denies
                    );
                }
                let new_items =
                    summary.added_additional_dirs.len() + summary.added_allow_rules.len();
                if new_items > 0 {
                    println!(
                        "{} Updated Claude Code permissions ({} new item{})",
                        "✓".green(),
                        new_items,
                        if new_items == 1 { "" } else { "s" }
                    );
                    println!("  {}", summary.settings_path.display());
                } else {
                    println!(
                        "{} Claude Code permissions already present; no changes needed",
                        "Info".cyan()
                    );
                }
            }
            Err(e) => {
                eprintln!(
                    "{}: Failed to update Claude Code settings: {}",
                    "Warning".yellow(),
                    e
                );
                eprintln!("Proceeding without updating .claude/settings.local.json");
            }
        }
    }

    if had_errors {
        return Err(anyhow!(
            "One or more symlinks require --force or manual cleanup"
        ));
    }
    // Success message
    println!("\n{} Successfully initialized thoughts!", "✓".green());
    println!("\nCreated directory structure:");
    println!(
        "  {} -> {} (personal workspace)",
        mount_dirs.thoughts.cyan(),
        thoughts_target_dir
            .strip_prefix(&repo_root)
            .unwrap_or(&thoughts_target_dir)
            .display()
    );
    println!(
        "  {} -> {} (team-shared context)",
        mount_dirs.context.cyan(),
        context_target_dir
            .strip_prefix(&repo_root)
            .unwrap_or(&context_target_dir)
            .display()
    );
    println!(
        "  {} -> {} (reference repos)",
        mount_dirs.references.cyan(),
        references_target_dir
            .strip_prefix(&repo_root)
            .unwrap_or(&references_target_dir)
            .display()
    );
    println!(
        "\nConfiguration saved to: {}",
        ".thoughts/config.json".cyan()
    );
    println!("\nNext steps:");
    println!(
        "  - {} to add a context mount",
        "thoughts mount add <path>".cyan()
    );
    println!(
        "  - {} to add a reference",
        "thoughts references add <url>".cyan()
    );

    Ok(())
}

fn create_symlink(target: &str, link: &Path) -> Result<()> {
    std::os::unix::fs::symlink(target, link)
        .with_context(|| format!("Failed to create symlink {} -> {target}", link.display()))?;
    Ok(())
}

fn create_readme_if_empty(dir: &Path, title: &str, content: &str) -> Result<()> {
    let readme_path = dir.join("README.md");

    if !readme_path.exists() {
        let full_content = format!("# {title}\n\n{content}");
        fs::write(&readme_path, full_content)
            .with_context(|| format!("Failed to create README at {}", readme_path.display()))?;
    }

    Ok(())
}

#[derive(Debug)]
enum SymlinkOutcome {
    Created,
    AlreadyCorrect,
    Fixed,
    NeedsForce { current_target: PathBuf },
    NonSymlinkExists,
}

/// Ensure that `link` is a symlink pointing to the absolute `abs_target`.
/// If incorrect and `force` is true, fix it. If force is false, return `NeedsForce`.
/// Never delete non-symlinks.
fn ensure_symlink_abs_target(
    link: &Path,
    abs_target: &Path,
    force: bool,
) -> Result<SymlinkOutcome> {
    if !link.exists() {
        create_symlink(&abs_target.to_string_lossy(), link)?;
        return Ok(SymlinkOutcome::Created);
    }
    let meta = fs::symlink_metadata(link)?;
    if !meta.file_type().is_symlink() {
        return Ok(SymlinkOutcome::NonSymlinkExists);
    }
    // Compare resolved targets; fall back to literal compare on failure
    let current = fs::read_link(link).unwrap_or_default();
    let resolved_link = fs::canonicalize(link);
    let resolved_expected = fs::canonicalize(abs_target);
    let is_correct = match (resolved_link, resolved_expected) {
        (Ok(a), Ok(b)) => a == b,
        _ => current == abs_target, // fallback
    };
    if is_correct {
        return Ok(SymlinkOutcome::AlreadyCorrect);
    }
    if force {
        fs::remove_file(link)?;
        create_symlink(&abs_target.to_string_lossy(), link)?;
        Ok(SymlinkOutcome::Fixed)
    } else {
        Ok(SymlinkOutcome::NeedsForce {
            current_target: current,
        })
    }
}

/// Ensure that `link` points to the relative target string `rel_target`.
/// For correctness check, we prefer resolved path equality against `abs_target`,
/// falling back to literal link text equality with `rel_target`.
fn ensure_symlink_rel_target(
    link: &Path,
    rel_target: &str,
    abs_target: &Path,
    force: bool,
) -> Result<SymlinkOutcome> {
    if !link.exists() {
        create_symlink(rel_target, link)?;
        return Ok(SymlinkOutcome::Created);
    }
    let meta = fs::symlink_metadata(link)?;
    if !meta.file_type().is_symlink() {
        return Ok(SymlinkOutcome::NonSymlinkExists);
    }
    let current = fs::read_link(link).unwrap_or_default();

    let resolved_link = fs::canonicalize(link);
    let resolved_expected = fs::canonicalize(abs_target);
    let is_correct = match (resolved_link, resolved_expected) {
        (Ok(a), Ok(b)) => a == b,
        _ => current == Path::new(rel_target),
    };

    if is_correct {
        return Ok(SymlinkOutcome::AlreadyCorrect);
    }
    if force {
        fs::remove_file(link)?;
        create_symlink(rel_target, link)?;
        Ok(SymlinkOutcome::Fixed)
    } else {
        Ok(SymlinkOutcome::NeedsForce {
            current_target: current,
        })
    }
}