kanbus 0.14.0

High-performance CLI and web console for the Kanbus issue tracker. Includes kanbus (CLI) and kanbus-console (web UI server).
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
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
//! File system helpers for initialization.

use std::path::{Path, PathBuf};
use std::process::Command;

use crate::config::default_project_configuration;
use crate::config_loader::load_project_configuration;
use crate::error::KanbusError;
use crate::models::ProjectConfiguration;
use crate::project_management_template::{
    DEFAULT_PROJECT_MANAGEMENT_TEMPLATE, DEFAULT_PROJECT_MANAGEMENT_TEMPLATE_FILENAME,
};
use serde_json;
use serde_yaml;

/// A resolved project directory with its label.
#[derive(Debug, Clone)]
pub struct ResolvedProject {
    pub label: String,
    pub project_dir: PathBuf,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepairPlan {
    pub project_dir: PathBuf,
    pub missing_project_dir: bool,
    pub missing_issues_dir: bool,
    pub missing_events_dir: bool,
}

fn should_force_canonicalize_failure() -> bool {
    std::env::var_os("KANBUS_TEST_CANONICALIZE_FAILURE").is_some()
}

pub(crate) fn canonicalize_path(path: &Path) -> Result<PathBuf, std::io::Error> {
    if should_force_canonicalize_failure() {
        return Err(std::io::Error::other("forced canonicalize failure"));
    }
    path.canonicalize()
}

/// Ensure the current directory is inside a git repository.
///
/// # Arguments
///
/// * `root` - Path to validate.
///
/// # Errors
///
/// Returns `KanbusError::Initialization` if the directory is not a git repository.
pub fn ensure_git_repository(root: &Path) -> Result<(), KanbusError> {
    let output = Command::new("git")
        .args(["rev-parse", "--is-inside-work-tree"])
        .current_dir(root)
        .output()
        .map_err(|error| KanbusError::Io(error.to_string()))?;

    if !output.status.success() {
        return Err(KanbusError::Initialization(
            "not a git repository".to_string(),
        ));
    }

    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if stdout != "true" {
        return Err(KanbusError::Initialization(
            "not a git repository".to_string(),
        ));
    }

    Ok(())
}

/// Initialize the Kanbus project structure.
///
/// # Arguments
///
/// * `root` - Repository root.
/// * `create_local` - Whether to create project-local.
///
/// # Errors
///
/// Returns `KanbusError::Initialization` if already initialized.
pub fn initialize_project(root: &Path, create_local: bool) -> Result<(), KanbusError> {
    let project_dir = root.join("project");
    if project_dir.exists() {
        return Err(KanbusError::Initialization(
            "already initialized".to_string(),
        ));
    }

    let issues_dir = project_dir.join("issues");
    let events_dir = project_dir.join("events");

    std::fs::create_dir(&project_dir).map_err(|error| KanbusError::Io(error.to_string()))?;
    std::fs::create_dir(&issues_dir).map_err(|error| KanbusError::Io(error.to_string()))?;
    std::fs::create_dir(&events_dir).map_err(|error| KanbusError::Io(error.to_string()))?;
    let config_path = root.join(".kanbus.yml");
    if !config_path.exists() {
        let default_configuration = default_project_configuration();
        let contents = serde_yaml::to_string(&default_configuration)
            .map_err(|error| KanbusError::Io(error.to_string()))?;
        std::fs::write(&config_path, contents)
            .map_err(|error| KanbusError::Io(error.to_string()))?;
    }
    let template_path = root.join(DEFAULT_PROJECT_MANAGEMENT_TEMPLATE_FILENAME);
    if !template_path.exists() {
        std::fs::write(&template_path, DEFAULT_PROJECT_MANAGEMENT_TEMPLATE)
            .map_err(|error| KanbusError::Io(error.to_string()))?;
    }
    write_project_guard_files(&project_dir)?;
    write_tool_block_files(root)?;
    if create_local {
        ensure_project_local_directory(&project_dir)?;
    }

    Ok(())
}

/// Resolve the repository root for initialization.
///
/// # Arguments
///
/// * `cwd` - Current working directory.
///
/// # Returns
///
/// The root path used for initialization. Walks up from cwd to find .kanbus.yml.
pub fn resolve_root(cwd: &Path) -> PathBuf {
    let mut current = cwd;
    loop {
        let config_path = current.join(".kanbus.yml");
        if config_path.exists() {
            return current.to_path_buf();
        }
        match current.parent() {
            Some(parent) => current = parent,
            None => return cwd.to_path_buf(), // Fallback to cwd if not found
        }
    }
}

fn write_project_guard_files(project_dir: &Path) -> Result<(), KanbusError> {
    let agents_path = project_dir.join("AGENTS.md");
    let agents_content = [
        "# DO NOT EDIT HERE",
        "",
        "Editing anything under project/ directly is hacking the data and is a sin against The Way.",
        "Do not read or write in this folder. Do not inspect issue JSON with tools like cat or jq. Use Kanbus commands instead.",
        "",
        "See ../AGENTS.md and ../CONTRIBUTING_AGENT.md for required process.",
    ]
    .join("\n")
        + "\n";
    std::fs::write(&agents_path, agents_content)
        .map_err(|error| KanbusError::Io(error.to_string()))?;

    let do_not_edit = project_dir.join("DO_NOT_EDIT");
    let do_not_edit_content = [
        "DO NOT EDIT ANYTHING IN project/",
        "This folder is guarded by The Way.",
        "Do not inspect issue JSON with tools like cat or jq.",
        "All changes must go through Kanbus (see ../AGENTS.md and ../CONTRIBUTING_AGENT.md).",
    ]
    .join("\n")
        + "\n";
    std::fs::write(&do_not_edit, do_not_edit_content)
        .map_err(|error| KanbusError::Io(error.to_string()))?;
    Ok(())
}

fn write_project_guard_files_if_missing(project_dir: &Path) -> Result<(), KanbusError> {
    let agents_path = project_dir.join("AGENTS.md");
    let do_not_edit = project_dir.join("DO_NOT_EDIT");
    if !agents_path.exists() || !do_not_edit.exists() {
        write_project_guard_files(project_dir)?;
    }
    Ok(())
}

fn write_tool_block_files(root: &Path) -> Result<(), KanbusError> {
    let cursorignore = root.join(".cursorignore");
    if !cursorignore.exists() {
        std::fs::write(&cursorignore, "project/\n")
            .map_err(|error| KanbusError::Io(error.to_string()))?;
    }

    let claude_dir = root.join(".claude");
    std::fs::create_dir_all(&claude_dir).map_err(|error| KanbusError::Io(error.to_string()))?;
    let claude_settings = claude_dir.join("settings.json");
    if !claude_settings.exists() {
        let payload = serde_json::json!({
            "permissions": {
                "deny": [
                    "Read(./project/**)",
                    "Edit(./project/**)"
                ]
            }
        });
        let content = serde_json::to_string_pretty(&payload)
            .map_err(|error| KanbusError::Io(error.to_string()))?;
        std::fs::write(&claude_settings, format!("{}\n", content))
            .map_err(|error| KanbusError::Io(error.to_string()))?;
    }

    let vscode_dir = root.join(".vscode");
    std::fs::create_dir_all(&vscode_dir).map_err(|error| KanbusError::Io(error.to_string()))?;
    let vscode_settings = vscode_dir.join("settings.json");
    if !vscode_settings.exists() {
        let payload = serde_json::json!({
            "files.exclude": {"**/project/**": true},
            "files.watcherExclude": {"**/project/**": true},
            "search.exclude": {"**/project/**": true},
        });
        let content = serde_json::to_string_pretty(&payload)
            .map_err(|error| KanbusError::Io(error.to_string()))?;
        std::fs::write(&vscode_settings, format!("{}\n", content))
            .map_err(|error| KanbusError::Io(error.to_string()))?;
    }
    Ok(())
}

/// Load a single Kanbus project directory by downward discovery.
///
/// # Arguments
///
/// * `root` - Repository root.
///
/// # Errors
///
/// Returns `KanbusError::IssueOperation` if no project or multiple projects are found.
pub fn load_project_directory(root: &Path) -> Result<PathBuf, KanbusError> {
    // When a config file is found, derive the primary project directory from it.
    // Virtual project directories are for reading and lookup only — including
    // them here causes "multiple projects found" errors for write operations.
    if let Ok(config_path) = get_configuration_path(root) {
        if let Ok(configuration) = load_project_configuration(&config_path) {
            let base = config_path.parent().unwrap_or_else(|| Path::new(""));
            let primary = base.join(&configuration.project_directory);
            if is_path_ignored(&primary, base, &configuration.ignore_paths) {
                return Err(KanbusError::IssueOperation(
                    "project not initialized".to_string(),
                ));
            }
            return Ok(match canonicalize_path(&primary) {
                Ok(p) => p,
                Err(_) => primary,
            });
        }
    }

    // No config file — fall back to filesystem scanning.
    let mut projects = Vec::new();
    discover_project_directories(root, &mut projects)?;

    let mut normalized = Vec::new();
    for path in projects {
        match canonicalize_path(&path) {
            Ok(canonical) => normalized.push(canonical),
            Err(_) => normalized.push(path),
        }
    }
    normalized.sort();
    normalized.dedup();
    filter_and_validate_projects(normalized)
}

pub fn detect_repairable_project_issues(
    root: &Path,
    allow_uninitialized: bool,
) -> Result<Option<RepairPlan>, KanbusError> {
    let config_path = match get_configuration_path(root) {
        Ok(path) => path,
        Err(KanbusError::IssueOperation(message)) if message == "project not initialized" => {
            if allow_uninitialized {
                return Ok(None);
            }
            return Err(KanbusError::IssueOperation(message));
        }
        Err(KanbusError::Io(message)) if message == "configuration path lookup failed" => {
            if allow_uninitialized {
                return Ok(None);
            }
            return Err(KanbusError::Io(message));
        }
        Err(error) => return Err(error),
    };
    let configuration = load_project_configuration(&config_path)?;
    let base = config_path.parent().unwrap_or_else(|| Path::new(""));
    let project_dir = base.join(&configuration.project_directory);
    let missing_project_dir = !project_dir.exists();
    let issues_dir = project_dir.join("issues");
    let events_dir = project_dir.join("events");
    let missing_issues_dir = !issues_dir.exists();
    let missing_events_dir = !events_dir.exists();

    if missing_project_dir || missing_issues_dir || missing_events_dir {
        return Ok(Some(RepairPlan {
            project_dir,
            missing_project_dir,
            missing_issues_dir,
            missing_events_dir,
        }));
    }

    Ok(None)
}

pub fn repair_project_structure(plan: &RepairPlan) -> Result<(), KanbusError> {
    if plan.missing_project_dir {
        std::fs::create_dir_all(&plan.project_dir)
            .map_err(|error| KanbusError::Io(error.to_string()))?;
    }
    if plan.missing_issues_dir {
        std::fs::create_dir_all(plan.project_dir.join("issues"))
            .map_err(|error| KanbusError::Io(error.to_string()))?;
    }
    if plan.missing_events_dir {
        std::fs::create_dir_all(plan.project_dir.join("events"))
            .map_err(|error| KanbusError::Io(error.to_string()))?;
    }
    if plan.project_dir.exists() {
        write_project_guard_files_if_missing(&plan.project_dir)?;
    }
    Ok(())
}

fn filter_and_validate_projects(normalized: Vec<PathBuf>) -> Result<PathBuf, KanbusError> {
    if normalized.is_empty() {
        return Err(KanbusError::IssueOperation(
            "project not initialized".to_string(),
        ));
    }
    if normalized.len() > 1 {
        let joined = normalized
            .iter()
            .map(|path| path.display().to_string())
            .collect::<Vec<String>>()
            .join(", ");
        return Err(KanbusError::IssueOperation(format!(
            "multiple projects found: {joined}. \
             Run this command from a directory with a single project/, \
             or remove extra entries from virtual_projects in .kanbus.yml."
        )));
    }
    Ok(normalized[0].clone())
}

/// Find a sibling project-local directory for a project.
///
/// # Arguments
///
/// * `project_dir` - Shared project directory.
pub fn find_project_local_directory(project_dir: &Path) -> Option<PathBuf> {
    let local_dir = project_dir
        .parent()
        .map(|parent| parent.join("project-local"))?;
    if local_dir.is_dir() {
        Some(local_dir)
    } else {
        None
    }
}

/// Ensure the project-local directory exists and is gitignored.
///
/// # Arguments
///
/// * `project_dir` - Shared project directory.
///
/// # Errors
///
/// Returns `KanbusError::Io` if filesystem operations fail.
pub fn ensure_project_local_directory(project_dir: &Path) -> Result<PathBuf, KanbusError> {
    let local_dir = project_dir
        .parent()
        .map(|parent| parent.join("project-local"))
        .ok_or_else(|| KanbusError::Io("project-local path unavailable".to_string()))?;
    let issues_dir = local_dir.join("issues");
    let events_dir = local_dir.join("events");
    std::fs::create_dir_all(&issues_dir).map_err(|error| KanbusError::Io(error.to_string()))?;
    std::fs::create_dir_all(&events_dir).map_err(|error| KanbusError::Io(error.to_string()))?;
    ensure_gitignore_entry(
        project_dir
            .parent()
            .ok_or_else(|| KanbusError::Io("project-local path unavailable".to_string()))?,
        "project-local/",
    )?;
    Ok(local_dir)
}

/// Locate the configuration file path.
///
/// # Arguments
///
/// * `root` - Path used for upward search.
///
/// # Errors
///
/// Returns `KanbusError::IssueOperation` if the configuration file is missing.
pub fn get_configuration_path(root: &Path) -> Result<PathBuf, KanbusError> {
    if std::env::var_os("KANBUS_TEST_CONFIGURATION_PATH_FAILURE").is_some() {
        return Err(KanbusError::Io(
            "configuration path lookup failed".to_string(),
        ));
    }
    let Some(path) = find_configuration_file(root)? else {
        return Err(KanbusError::IssueOperation(
            "project not initialized".to_string(),
        ));
    };
    Ok(path)
}

fn ensure_gitignore_entry(root: &Path, entry: &str) -> Result<(), KanbusError> {
    let gitignore_path = root.join(".gitignore");
    let existing = if gitignore_path.exists() {
        std::fs::read_to_string(&gitignore_path)
            .map_err(|error| KanbusError::Io(error.to_string()))?
    } else {
        String::new()
    };
    let lines: Vec<&str> = existing.lines().map(str::trim).collect();
    if lines.contains(&entry) {
        return Ok(());
    }
    let mut updated = existing;
    if !updated.is_empty() && !updated.ends_with('\n') {
        updated.push('\n');
    }
    updated.push_str(entry);
    updated.push('\n');
    std::fs::write(&gitignore_path, updated).map_err(|error| KanbusError::Io(error.to_string()))?;
    Ok(())
}

/// Discover configured project paths from .kanbus.yml.
///
/// # Arguments
/// * `root` - Repository root path.
///
/// # Errors
/// Returns `KanbusError` if configuration or dotfile paths are invalid.
pub fn discover_kanbus_projects(root: &Path) -> Result<Vec<PathBuf>, KanbusError> {
    let mut projects = Vec::new();
    if let Some(config_path) = find_configuration_file(root)? {
        let configuration = load_project_configuration(&config_path)?;
        let resolved = resolve_project_directories(
            config_path.parent().unwrap_or_else(|| Path::new("")),
            &configuration,
        )?;
        projects.extend(resolved.into_iter().map(|rp| rp.project_dir));
    }
    Ok(projects)
}

/// Resolve all labeled project directories from configuration.
///
/// # Arguments
///
/// * `root` - Repository root.
///
/// # Errors
///
/// Returns `KanbusError` if configuration or paths are invalid.
pub fn resolve_labeled_projects(root: &Path) -> Result<Vec<ResolvedProject>, KanbusError> {
    let config_path = get_configuration_path(root)?;
    let configuration = load_project_configuration(&config_path)?;
    resolve_project_directories(
        config_path.parent().unwrap_or_else(|| Path::new("")),
        &configuration,
    )
}

fn find_configuration_file(root: &Path) -> Result<Option<PathBuf>, KanbusError> {
    let git_root = find_git_root(root);
    let mut current = root
        .canonicalize()
        .map_err(|error| KanbusError::Io(error.to_string()))?;
    loop {
        let candidate = current.join(".kanbus.yml");
        if candidate.is_file() {
            return Ok(Some(candidate));
        }
        if let Some(root) = &git_root {
            if &current == root {
                break;
            }
        }
        let parent = match current.parent() {
            Some(parent) => parent.to_path_buf(),
            None => break,
        };
        #[cfg(windows)]
        if parent == current {
            break;
        }
        current = parent;
    }
    Ok(None)
}

fn resolve_project_directories(
    base: &Path,
    configuration: &ProjectConfiguration,
) -> Result<Vec<ResolvedProject>, KanbusError> {
    let mut projects = Vec::new();
    let primary = base.join(&configuration.project_directory);
    if !is_path_ignored(&primary, base, &configuration.ignore_paths) {
        projects.push(ResolvedProject {
            label: configuration.project_key.clone(),
            project_dir: primary,
        });
    }
    for (label, vp) in &configuration.virtual_projects {
        let candidate = Path::new(&vp.path);
        let resolved = if candidate.is_absolute() {
            candidate.to_path_buf()
        } else {
            base.join(candidate)
        };
        if !resolved.is_dir() {
            return Err(KanbusError::IssueOperation(format!(
                "virtual project path not found: {}",
                resolved.display()
            )));
        }
        if !is_path_ignored(&resolved, base, &configuration.ignore_paths) {
            projects.push(ResolvedProject {
                label: label.clone(),
                project_dir: resolved,
            });
        }
    }
    Ok(projects)
}

pub(crate) fn is_path_ignored(path: &Path, base: &Path, ignore_paths: &[String]) -> bool {
    for ignore_pattern in ignore_paths {
        let ignore_path = base.join(ignore_pattern);
        if let Ok(ignore_canonical) = ignore_path.canonicalize() {
            if let Ok(path_canonical) = path.canonicalize() {
                if path_canonical == ignore_canonical {
                    return true;
                }
            }
        }
    }
    false
}

fn find_git_root(root: &Path) -> Option<PathBuf> {
    let output = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(root)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    let path = PathBuf::from(stdout);
    path.is_dir().then_some(path)
}

pub(crate) fn discover_project_directories(
    root: &Path,
    projects: &mut Vec<PathBuf>,
) -> Result<(), KanbusError> {
    for entry in std::fs::read_dir(root).map_err(|error| KanbusError::Io(error.to_string()))? {
        let entry = entry.map_err(|error| KanbusError::Io(error.to_string()))?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let name = path
            .file_name()
            .and_then(|value| value.to_str())
            .unwrap_or("");
        if name == "project" {
            projects.push(path);
            continue;
        }
        if name == "project-local" {
            continue;
        }
        let nested_project = path.join("project");
        if nested_project.is_dir() {
            projects.push(nested_project);
        }
        // Avoid recursing into every subdirectory; doing so pulls in fixture
        // projects (e.g., apps/console/tests/fixtures/project) that are not real
        // Kanbus workspaces and can break commands with incomplete data.
        // Additional projects must be declared explicitly via configuration.
    }
    Ok(())
}