| 1 | //! /init command - Generate AGENTS.md for project |
| 2 | //! |
| 3 | //! Gathers rich project context (directory structure, build system, git info, CI/CD, |
| 4 | //! test frameworks) and delegates AGENTS.md generation to the LLM agent via |
| 5 | //! `AppAction::SendMessage`. This mirrors Claude Code's `/init` behavior — the agent |
| 6 | //! reads key source files, understands the architecture, and produces a customized, |
| 7 | //! comprehensive project guide. |
| 8 | |
| 9 | use std::io::Read; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 12 | |
| 13 | use codewhale_command_contract::facets::{BackgroundCancel, BackgroundRequest}; |
| 14 | use codewhale_command_contract::handler::CommandContexts; |
| 15 | use codewhale_command_contract::outcome::{BackgroundAction, BackgroundCommandResult}; |
| 16 | |
| 17 | use crate::tui::app::AppAction; |
| 18 | use codewhale_engine::project_context; |
| 19 | |
| 20 | use crate::commands::CommandResult; |
| 21 | |
| 22 | /// Generate an AGENTS.md file for the current project by gathering context and |
| 23 | /// delegating content generation to the LLM agent. |
| 24 | /// |
| 25 | /// FEAT-021 portable dispatch: consumes only the workspace path (supplied |
| 26 | /// through the `WORKSPACE` facet) and the UI language name (through the |
| 27 | /// `PRESENTATION` facet); the workspace scan and prompt composition stay |
| 28 | /// handler-owned (D2). `codewhale_util::utils`/`codewhale_engine::project_context` are leaf, |
| 29 | /// path-parameterized helpers (no App/service state), consistent with D8. |
| 30 | fn init(workspace: &Path, language: &str) -> CommandResult { |
| 31 | let (msg, prompt) = prepare_init(workspace, language); |
| 32 | CommandResult::with_message_and_action(msg, AppAction::SendMessage(prompt)) |
| 33 | } |
| 34 | |
| 35 | fn is_cancelled(cancel: Option<&AtomicBool>) -> bool { |
| 36 | cancel.is_some_and(|flag| flag.load(Ordering::SeqCst)) |
| 37 | } |
| 38 | |
| 39 | fn prepare_init(workspace: &Path, language: &str) -> (String, String) { |
| 40 | prepare_init_cancellable(workspace, language, None).expect("uncancellable init") |
| 41 | } |
| 42 | |
| 43 | fn prepare_init_cancellable( |
| 44 | workspace: &Path, |
| 45 | language: &str, |
| 46 | cancel: Option<&AtomicBool>, |
| 47 | ) -> Option<(String, String)> { |
| 48 | if is_cancelled(cancel) { |
| 49 | return None; |
| 50 | } |
| 51 | |
| 52 | ensure_deepseek_gitignored(workspace); |
| 53 | if is_cancelled(cancel) { |
| 54 | return None; |
| 55 | } |
| 56 | |
| 57 | let agents_path = workspace.join("AGENTS.md"); |
| 58 | let already_exists = agents_path.exists(); |
| 59 | |
| 60 | let context = gather_project_context_cancellable(workspace, cancel)?; |
| 61 | if is_cancelled(cancel) { |
| 62 | return None; |
| 63 | } |
| 64 | |
| 65 | let existing_content = if already_exists { |
| 66 | read_existing_agents_md(workspace) |
| 67 | } else { |
| 68 | None |
| 69 | }; |
| 70 | if is_cancelled(cancel) { |
| 71 | return None; |
| 72 | } |
| 73 | |
| 74 | let prompt = build_init_prompt( |
| 75 | &context, |
| 76 | existing_content.as_deref(), |
| 77 | already_exists, |
| 78 | language, |
| 79 | ); |
| 80 | |
| 81 | let verb = if already_exists { |
| 82 | "Updating" |
| 83 | } else { |
| 84 | "Creating" |
| 85 | }; |
| 86 | let msg = format!( |
| 87 | "{verb} AGENTS.md at {}\n\nThe agent will analyze the codebase and generate a customized project guide.", |
| 88 | agents_path.display() |
| 89 | ); |
| 90 | |
| 91 | Some((msg, prompt)) |
| 92 | } |
| 93 | |
| 94 | /// If `workspace` is inside a git repository, ensure workspace-local CodeWhale |
| 95 | /// state is listed in the nearest `.gitignore` so snapshots, auto-generated |
| 96 | /// instructions, and other runtime state are not accidentally committed — while |
| 97 | /// keeping the authored `.codewhale/constitution.json` repo authority policy |
| 98 | /// committable (a directory exclude cannot be overridden, so `.codewhale/*` plus |
| 99 | /// a negation is required). |
| 100 | fn ensure_deepseek_gitignored(workspace: &Path) { |
| 101 | let Some(git_root) = git_root(workspace) else { |
| 102 | return; |
| 103 | }; |
| 104 | |
| 105 | let gitignore = git_root.join(".gitignore"); |
| 106 | let entries = [ |
| 107 | "**/.codewhale/*", |
| 108 | "!**/.codewhale/constitution.json", |
| 109 | ".deepseek/", |
| 110 | ]; |
| 111 | |
| 112 | // Read existing contents once. |
| 113 | let existing = std::fs::read_to_string(&gitignore).unwrap_or_default(); |
| 114 | let mut missing: Vec<&str> = Vec::new(); |
| 115 | for entry in entries { |
| 116 | let entry_no_slash = entry.trim_end_matches('/'); |
| 117 | let already_ignored = existing.lines().any(|line| { |
| 118 | let trimmed = line.trim(); |
| 119 | trimmed == entry || trimmed == entry_no_slash |
| 120 | }); |
| 121 | if !already_ignored { |
| 122 | missing.push(entry); |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | if missing.is_empty() { |
| 127 | return; |
| 128 | } |
| 129 | |
| 130 | // Append missing entries. If .gitignore doesn't exist yet, create it. |
| 131 | use std::io::Write; |
| 132 | if let Ok(mut file) = std::fs::OpenOptions::new() |
| 133 | .create(true) |
| 134 | .append(true) |
| 135 | .open(&gitignore) |
| 136 | { |
| 137 | // If the file is non-empty and doesn't end with a newline, add one first. |
| 138 | if let Ok(meta) = file.metadata() |
| 139 | && meta.len() > 0 |
| 140 | && let Ok(mut f) = std::fs::File::open(&gitignore) |
| 141 | { |
| 142 | use std::io::Seek; |
| 143 | if f.seek(std::io::SeekFrom::End(-1)).is_ok() { |
| 144 | let mut buf = [0u8; 1]; |
| 145 | if f.read_exact(&mut buf).is_ok() && buf[0] != b'\n' { |
| 146 | let _ = writeln!(file); |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | for entry in &missing { |
| 151 | let _ = writeln!(file, "{entry}"); |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // --------------------------------------------------------------------------- |
| 157 | // Context gathering functions |
| 158 | // --------------------------------------------------------------------------- |
| 159 | |
| 160 | /// Orchestrate all context gathering and return structured Markdown for the agent prompt. |
| 161 | fn gather_project_context_cancellable( |
| 162 | workspace: &Path, |
| 163 | cancel: Option<&AtomicBool>, |
| 164 | ) -> Option<String> { |
| 165 | let mut ctx = String::new(); |
| 166 | |
| 167 | if is_cancelled(cancel) { |
| 168 | return None; |
| 169 | } |
| 170 | let summary = codewhale_util::utils::summarize_project(workspace); |
| 171 | ctx.push_str("## Project Summary\n\n"); |
| 172 | ctx.push_str(&summary); |
| 173 | ctx.push_str("\n\n"); |
| 174 | |
| 175 | if is_cancelled(cancel) { |
| 176 | return None; |
| 177 | } |
| 178 | if let Some(info) = parse_cargo_toml(workspace) { |
| 179 | ctx.push_str("## Rust / Cargo\n\n"); |
| 180 | ctx.push_str(&info); |
| 181 | ctx.push_str("\n\n"); |
| 182 | } |
| 183 | |
| 184 | if is_cancelled(cancel) { |
| 185 | return None; |
| 186 | } |
| 187 | if let Some(info) = parse_package_json(workspace) { |
| 188 | ctx.push_str("## Node.js / npm\n\n"); |
| 189 | ctx.push_str(&info); |
| 190 | ctx.push_str("\n\n"); |
| 191 | } |
| 192 | |
| 193 | if is_cancelled(cancel) { |
| 194 | return None; |
| 195 | } |
| 196 | if let Some(info) = gather_git_info_cancellable(workspace, cancel)? { |
| 197 | ctx.push_str("## Git Repository\n\n"); |
| 198 | ctx.push_str(&info); |
| 199 | ctx.push_str("\n\n"); |
| 200 | } |
| 201 | |
| 202 | if is_cancelled(cancel) { |
| 203 | return None; |
| 204 | } |
| 205 | let ci = detect_ci_systems(workspace); |
| 206 | if !ci.is_empty() { |
| 207 | ctx.push_str("## CI/CD\n\n"); |
| 208 | for system in &ci { |
| 209 | let _ = std::fmt::write(&mut ctx, format_args!("- {system}\n")); |
| 210 | } |
| 211 | ctx.push('\n'); |
| 212 | } |
| 213 | |
| 214 | if is_cancelled(cancel) { |
| 215 | return None; |
| 216 | } |
| 217 | let build = detect_build_systems(workspace); |
| 218 | if !build.is_empty() { |
| 219 | ctx.push_str("## Additional Build Systems\n\n"); |
| 220 | for system in &build { |
| 221 | let _ = std::fmt::write(&mut ctx, format_args!("- {system}\n")); |
| 222 | } |
| 223 | ctx.push('\n'); |
| 224 | } |
| 225 | |
| 226 | if is_cancelled(cancel) { |
| 227 | return None; |
| 228 | } |
| 229 | let tests = detect_test_frameworks(workspace); |
| 230 | if !tests.is_empty() { |
| 231 | ctx.push_str("## Test Frameworks\n\n"); |
| 232 | for framework in &tests { |
| 233 | let _ = std::fmt::write(&mut ctx, format_args!("- {framework}\n")); |
| 234 | } |
| 235 | ctx.push('\n'); |
| 236 | } |
| 237 | |
| 238 | if is_cancelled(cancel) { |
| 239 | return None; |
| 240 | } |
| 241 | let tree = codewhale_util::utils::project_tree(workspace, 3, false); |
| 242 | ctx.push_str("## Directory Structure (depth 3)\n\n```\n"); |
| 243 | ctx.push_str(&tree); |
| 244 | ctx.push_str("\n```\n\n"); |
| 245 | |
| 246 | if is_cancelled(cancel) { |
| 247 | return None; |
| 248 | } |
| 249 | if let Some(pack) = project_context::generate_project_context_pack(workspace) { |
| 250 | ctx.push_str("## Detailed Project Context\n\n```json\n"); |
| 251 | ctx.push_str(&pack); |
| 252 | ctx.push_str("\n```\n\n"); |
| 253 | } |
| 254 | |
| 255 | Some(ctx) |
| 256 | } |
| 257 | |
| 258 | /// Parse `Cargo.toml` and return a human-readable summary of the Rust project structure. |
| 259 | fn parse_cargo_toml(workspace: &Path) -> Option<String> { |
| 260 | let cargo_path = workspace.join("Cargo.toml"); |
| 261 | let raw = std::fs::read_to_string(&cargo_path).ok()?; |
| 262 | let doc: toml::Value = toml::from_str(&raw).ok()?; |
| 263 | |
| 264 | let mut lines: Vec<String> = Vec::new(); |
| 265 | |
| 266 | // Package info. |
| 267 | if let Some(package) = doc.get("package") { |
| 268 | if let Some(name) = package.get("name").and_then(|v| v.as_str()) { |
| 269 | lines.push(format!("- Package name: `{name}`")); |
| 270 | } |
| 271 | if let Some(version) = package.get("version").and_then(|v| v.as_str()) { |
| 272 | lines.push(format!("- Version: {version}")); |
| 273 | } |
| 274 | if let Some(edition) = package.get("edition").and_then(|v| v.as_str()) { |
| 275 | lines.push(format!("- Rust edition: {edition}")); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | // Workspace info. |
| 280 | if let Some(workspace_section) = doc.get("workspace") { |
| 281 | lines.push("- **This is a workspace root**".to_string()); |
| 282 | if let Some(members) = workspace_section.get("members").and_then(|v| v.as_array()) { |
| 283 | let mut member_names: Vec<&str> = members.iter().filter_map(|m| m.as_str()).collect(); |
| 284 | member_names.sort_unstable(); |
| 285 | if !member_names.is_empty() { |
| 286 | lines.push(format!("- Workspace members: {}", member_names.join(", "))); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // Dependencies. |
| 292 | if let Some(deps) = doc.get("dependencies").and_then(|v| v.as_table()) { |
| 293 | let mut dep_names: Vec<&str> = deps.keys().map(|k| k.as_str()).collect(); |
| 294 | dep_names.sort_unstable(); |
| 295 | if !dep_names.is_empty() { |
| 296 | lines.push(format!("- Key dependencies: {}", dep_names.join(", "))); |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | // Dev dependencies — test frameworks. |
| 301 | if let Some(dev_deps) = doc.get("dev-dependencies").and_then(|v| v.as_table()) { |
| 302 | let mut dev_names: Vec<&str> = dev_deps.keys().map(|k| k.as_str()).collect(); |
| 303 | dev_names.sort_unstable(); |
| 304 | if !dev_names.is_empty() { |
| 305 | lines.push(format!("- Dev dependencies: {}", dev_names.join(", "))); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | // Workspace-level dependencies (shared across workspace members). |
| 310 | if let Some(ws_deps) = doc |
| 311 | .get("workspace") |
| 312 | .and_then(|w| w.get("dependencies")) |
| 313 | .and_then(|v| v.as_table()) |
| 314 | { |
| 315 | let mut ws_dep_names: Vec<&str> = ws_deps.keys().map(|k| k.as_str()).collect(); |
| 316 | ws_dep_names.sort_unstable(); |
| 317 | if !ws_dep_names.is_empty() { |
| 318 | lines.push(format!( |
| 319 | "- Workspace dependencies: {}", |
| 320 | ws_dep_names.join(", ") |
| 321 | )); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | // Features. |
| 326 | if let Some(features) = doc.get("features").and_then(|v| v.as_table()) { |
| 327 | let mut feat_names: Vec<&str> = features.keys().map(|k| k.as_str()).collect(); |
| 328 | feat_names.sort_unstable(); |
| 329 | if !feat_names.is_empty() { |
| 330 | lines.push(format!("- Features: {}", feat_names.join(", "))); |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | if lines.is_empty() { |
| 335 | None |
| 336 | } else { |
| 337 | Some(lines.join("\n")) |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | /// Parse `package.json` and return a human-readable summary of the Node.js project. |
| 342 | fn parse_package_json(workspace: &Path) -> Option<String> { |
| 343 | let pkg_path = workspace.join("package.json"); |
| 344 | let raw = std::fs::read_to_string(&pkg_path).ok()?; |
| 345 | let doc: serde_json::Value = serde_json::from_str(&raw).ok()?; |
| 346 | |
| 347 | let mut lines: Vec<String> = Vec::new(); |
| 348 | |
| 349 | if let Some(name) = doc.get("name").and_then(|v| v.as_str()) { |
| 350 | lines.push(format!("- Package name: `{name}`")); |
| 351 | } |
| 352 | |
| 353 | // Scripts. |
| 354 | if let Some(scripts) = doc.get("scripts").and_then(|v| v.as_object()) { |
| 355 | let mut script_names: Vec<&str> = scripts.keys().map(|k| k.as_str()).collect(); |
| 356 | script_names.sort_unstable(); |
| 357 | if !script_names.is_empty() { |
| 358 | lines.push(format!("- Scripts: {}", script_names.join(", "))); |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | // Dependencies. |
| 363 | if let Some(deps) = doc.get("dependencies").and_then(|v| v.as_object()) { |
| 364 | let mut dep_keys: Vec<&str> = deps.keys().map(|k| k.as_str()).collect(); |
| 365 | dep_keys.sort_unstable(); |
| 366 | if !dep_keys.is_empty() { |
| 367 | // Detect frameworks from runtime deps. |
| 368 | let frameworks = detect_js_frameworks(&dep_keys); |
| 369 | if !frameworks.is_empty() { |
| 370 | lines.push(format!("- Frameworks detected: {}", frameworks.join(", "))); |
| 371 | } |
| 372 | lines.push(format!("- Dependencies: {}", dep_keys.join(", "))); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | // Dev dependencies. |
| 377 | if let Some(dev_deps) = doc.get("devDependencies").and_then(|v| v.as_object()) { |
| 378 | let mut dev_keys: Vec<&str> = dev_deps.keys().map(|k| k.as_str()).collect(); |
| 379 | dev_keys.sort_unstable(); |
| 380 | if !dev_keys.is_empty() { |
| 381 | // Also detect build-tool/framework entries from devDependencies |
| 382 | // (Vite, webpack, esbuild, Turbopack, etc.). |
| 383 | let dev_frameworks = detect_js_frameworks(&dev_keys); |
| 384 | if !dev_frameworks.is_empty() { |
| 385 | lines.push(format!( |
| 386 | "- Dev frameworks/tools: {}", |
| 387 | dev_frameworks.join(", ") |
| 388 | )); |
| 389 | } |
| 390 | lines.push(format!("- Dev dependencies: {}", dev_keys.join(", "))); |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | if lines.is_empty() { |
| 395 | None |
| 396 | } else { |
| 397 | Some(lines.join("\n")) |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | /// Detect JS frameworks from dependency names. |
| 402 | fn detect_js_frameworks(deps: &[&str]) -> Vec<String> { |
| 403 | let mut found: Vec<String> = Vec::new(); |
| 404 | let candidates: &[(&str, &str)] = &[ |
| 405 | ("react", "React"), |
| 406 | ("next", "Next.js"), |
| 407 | ("vue", "Vue"), |
| 408 | ("nuxt", "Nuxt"), |
| 409 | ("@sveltejs/kit", "SvelteKit"), |
| 410 | ("svelte", "Svelte"), |
| 411 | ("sveltekit", "SvelteKit"), |
| 412 | ("astro", "Astro"), |
| 413 | ("express", "Express"), |
| 414 | ("fastify", "Fastify"), |
| 415 | ("hono", "Hono"), |
| 416 | ("vite", "Vite"), |
| 417 | ("webpack", "Webpack"), |
| 418 | ("esbuild", "esbuild"), |
| 419 | ("turbo", "Turbopack"), |
| 420 | ("tailwindcss", "Tailwind CSS"), |
| 421 | ]; |
| 422 | for dep in deps { |
| 423 | let lower = dep.to_lowercase(); |
| 424 | for (key, label) in candidates { |
| 425 | if lower == *key && !found.contains(&label.to_string()) { |
| 426 | found.push((*label).to_string()); |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | found |
| 431 | } |
| 432 | |
| 433 | /// Strip embedded credentials, query strings, and fragments from a git remote |
| 434 | /// URL to avoid leaking secrets into the LLM prompt or session transcript. |
| 435 | fn strip_url_credentials(url: &str) -> String { |
| 436 | let without_query_or_fragment = url.split(['?', '#']).next().unwrap_or(url); |
| 437 | // Handle SCP-style SSH remotes: git@host:org/repo.git. |
| 438 | if without_query_or_fragment.contains('@') && !without_query_or_fragment.contains("://") { |
| 439 | if let Some((user_part, host_and_path)) = without_query_or_fragment.split_once('@') |
| 440 | && user_part.contains(':') |
| 441 | { |
| 442 | return host_and_path.to_string(); |
| 443 | } |
| 444 | return without_query_or_fragment.to_string(); |
| 445 | } |
| 446 | if let Some(scheme_end) = without_query_or_fragment.find("://") { |
| 447 | let scheme_name = without_query_or_fragment[..scheme_end].to_ascii_lowercase(); |
| 448 | let scheme = &without_query_or_fragment[..scheme_end + 3]; |
| 449 | let after_scheme = &without_query_or_fragment[scheme_end + 3..]; |
| 450 | let authority_end = after_scheme.find('/').unwrap_or(after_scheme.len()); |
| 451 | let (authority, path) = after_scheme.split_at(authority_end); |
| 452 | if let Some(at_pos) = authority.rfind('@') { |
| 453 | let userinfo = &authority[..at_pos]; |
| 454 | let host = &authority[at_pos + 1..]; |
| 455 | if scheme_name == "ssh" && !userinfo.contains(':') { |
| 456 | return format!("{scheme}{authority}{path}"); |
| 457 | } |
| 458 | return format!("{scheme}{host}{path}"); |
| 459 | } |
| 460 | return format!("{scheme}{authority}{path}"); |
| 461 | } |
| 462 | without_query_or_fragment.to_string() |
| 463 | } |
| 464 | |
| 465 | /// Find the enclosing git repository root. Works for nested workspaces and |
| 466 | /// worktrees where `.git` is a file instead of a directory. |
| 467 | fn git_root(workspace: &Path) -> Option<PathBuf> { |
| 468 | let direct_git_marker = workspace.join(".git"); |
| 469 | let discovered = codewhale_dependencies::Git::review_base(workspace) |
| 470 | .ok() |
| 471 | .and_then(|mut command| command.args(["rev-parse", "--show-toplevel"]).output().ok()) |
| 472 | .and_then(|out| { |
| 473 | if out.status.success() { |
| 474 | String::from_utf8(out.stdout) |
| 475 | .ok() |
| 476 | .map(|s| s.trim().to_string()) |
| 477 | .filter(|s| !s.is_empty()) |
| 478 | .map(PathBuf::from) |
| 479 | } else { |
| 480 | None |
| 481 | } |
| 482 | }); |
| 483 | discovered.or_else(|| direct_git_marker.exists().then(|| workspace.to_path_buf())) |
| 484 | } |
| 485 | |
| 486 | /// Gather git repository information via subprocess calls. |
| 487 | #[cfg(test)] |
| 488 | fn gather_git_info(workspace: &Path) -> Option<String> { |
| 489 | gather_git_info_cancellable(workspace, None).flatten() |
| 490 | } |
| 491 | |
| 492 | fn gather_git_info_cancellable( |
| 493 | workspace: &Path, |
| 494 | cancel: Option<&AtomicBool>, |
| 495 | ) -> Option<Option<String>> { |
| 496 | if is_cancelled(cancel) { |
| 497 | return None; |
| 498 | } |
| 499 | let Some(git_root) = git_root(workspace) else { |
| 500 | return Some(None); |
| 501 | }; |
| 502 | if is_cancelled(cancel) { |
| 503 | return None; |
| 504 | } |
| 505 | |
| 506 | let run = |args: &[&str]| -> Option<String> { |
| 507 | codewhale_dependencies::Git::review_base(&git_root) |
| 508 | .ok()? |
| 509 | .args(args) |
| 510 | .output() |
| 511 | .ok() |
| 512 | .and_then(|out| { |
| 513 | if out.status.success() { |
| 514 | String::from_utf8(out.stdout) |
| 515 | .ok() |
| 516 | .map(|s| s.trim().to_string()) |
| 517 | .filter(|s| !s.is_empty()) |
| 518 | } else { |
| 519 | None |
| 520 | } |
| 521 | }) |
| 522 | }; |
| 523 | |
| 524 | let mut lines: Vec<String> = Vec::new(); |
| 525 | |
| 526 | if let Some(url) = run(&["remote", "get-url", "origin"]) { |
| 527 | let sanitized = strip_url_credentials(&url); |
| 528 | lines.push(format!("- Remote: {sanitized}")); |
| 529 | } |
| 530 | if is_cancelled(cancel) { |
| 531 | return None; |
| 532 | } |
| 533 | |
| 534 | if let Some(branch) = run(&["rev-parse", "--abbrev-ref", "HEAD"]) { |
| 535 | lines.push(format!("- Branch: {branch}")); |
| 536 | } |
| 537 | if is_cancelled(cancel) { |
| 538 | return None; |
| 539 | } |
| 540 | |
| 541 | let status_output = codewhale_dependencies::Git::workspace_command(&git_root) |
| 542 | .ok() |
| 543 | .and_then(|mut command| { |
| 544 | command |
| 545 | .args([ |
| 546 | "status", |
| 547 | "--porcelain=v1", |
| 548 | "--untracked-files=no", |
| 549 | "--ignore-submodules=dirty", |
| 550 | ]) |
| 551 | .output() |
| 552 | .ok() |
| 553 | }); |
| 554 | if is_cancelled(cancel) { |
| 555 | return None; |
| 556 | } |
| 557 | if let Some(out) = status_output |
| 558 | && out.status.success() |
| 559 | { |
| 560 | let status_str = String::from_utf8_lossy(&out.stdout); |
| 561 | let staged = status_str |
| 562 | .lines() |
| 563 | .filter(|l| { |
| 564 | let b = l.as_bytes(); |
| 565 | b.len() >= 2 && b[0] != b' ' && b[0] != b'?' |
| 566 | }) |
| 567 | .count(); |
| 568 | let unstaged = status_str |
| 569 | .lines() |
| 570 | .filter(|l| { |
| 571 | let b = l.as_bytes(); |
| 572 | b.len() >= 2 && b[1] != b' ' && b[1] != b'?' |
| 573 | }) |
| 574 | .count(); |
| 575 | if staged > 0 || unstaged > 0 { |
| 576 | let mut parts = Vec::new(); |
| 577 | if staged > 0 { |
| 578 | parts.push(format!("{staged} staged")); |
| 579 | } |
| 580 | if unstaged > 0 { |
| 581 | parts.push(format!("{unstaged} modified")); |
| 582 | } |
| 583 | lines.push(format!("- Working tree: {}", parts.join(", "))); |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | if let Some(log) = run(&["log", "--oneline", "-5"]) { |
| 588 | let commits: Vec<&str> = log.lines().collect(); |
| 589 | if !commits.is_empty() { |
| 590 | lines.push("- Recent commits:".to_string()); |
| 591 | for c in commits { |
| 592 | lines.push(format!(" - {c}")); |
| 593 | } |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | if lines.is_empty() { |
| 598 | Some(None) |
| 599 | } else { |
| 600 | Some(Some(lines.join("\n"))) |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | /// Detect CI/CD systems configured in the project. |
| 605 | fn detect_ci_systems(workspace: &Path) -> Vec<String> { |
| 606 | let mut found: Vec<String> = Vec::new(); |
| 607 | |
| 608 | if workspace.join(".github").join("workflows").is_dir() |
| 609 | && let Ok(entries) = std::fs::read_dir(workspace.join(".github").join("workflows")) |
| 610 | { |
| 611 | let files: Vec<String> = entries |
| 612 | .filter_map(|e| e.ok()) |
| 613 | .filter_map(|e| { |
| 614 | let name = e.file_name().to_string_lossy().into_owned(); |
| 615 | if name.ends_with(".yml") || name.ends_with(".yaml") { |
| 616 | Some(name) |
| 617 | } else { |
| 618 | None |
| 619 | } |
| 620 | }) |
| 621 | .collect(); |
| 622 | let mut files = files; |
| 623 | files.sort_unstable(); |
| 624 | if files.is_empty() { |
| 625 | found.push("GitHub Actions".to_string()); |
| 626 | } else { |
| 627 | found.push(format!("GitHub Actions ({})", files.join(", "))); |
| 628 | } |
| 629 | } |
| 630 | if workspace.join(".gitlab-ci.yml").exists() { |
| 631 | found.push("GitLab CI".to_string()); |
| 632 | } |
| 633 | if workspace.join("Jenkinsfile").exists() { |
| 634 | found.push("Jenkins".to_string()); |
| 635 | } |
| 636 | if workspace.join(".circleci").join("config.yml").exists() { |
| 637 | found.push("CircleCI".to_string()); |
| 638 | } |
| 639 | if workspace.join(".travis.yml").exists() { |
| 640 | found.push("Travis CI".to_string()); |
| 641 | } |
| 642 | if workspace.join("azure-pipelines.yml").exists() { |
| 643 | found.push("Azure Pipelines".to_string()); |
| 644 | } |
| 645 | |
| 646 | found |
| 647 | } |
| 648 | |
| 649 | /// Detect additional build systems beyond Cargo/npm. |
| 650 | fn detect_build_systems(workspace: &Path) -> Vec<String> { |
| 651 | let mut found: Vec<String> = Vec::new(); |
| 652 | |
| 653 | if workspace.join("Makefile").exists() { |
| 654 | found.push("Makefile".to_string()); |
| 655 | } |
| 656 | if workspace.join("Justfile").exists() { |
| 657 | found.push("Justfile".to_string()); |
| 658 | } |
| 659 | if workspace.join("CMakeLists.txt").exists() { |
| 660 | found.push("CMake".to_string()); |
| 661 | } |
| 662 | if workspace.join("meson.build").exists() { |
| 663 | found.push("Meson".to_string()); |
| 664 | } |
| 665 | if workspace.join("BUILD.bazel").exists() || workspace.join("BUILD").exists() { |
| 666 | found.push("Bazel".to_string()); |
| 667 | } |
| 668 | if workspace.join("scripts").is_dir() |
| 669 | && let Ok(entries) = std::fs::read_dir(workspace.join("scripts")) |
| 670 | { |
| 671 | let scripts: Vec<String> = entries |
| 672 | .filter_map(|e| e.ok()) |
| 673 | .filter_map(|e| { |
| 674 | let name = e.file_name().to_string_lossy().into_owned(); |
| 675 | let path = e.path(); |
| 676 | if (name.ends_with(".sh") || name.ends_with(".py") || name.ends_with(".js")) |
| 677 | && path.is_file() |
| 678 | { |
| 679 | Some(name) |
| 680 | } else { |
| 681 | None |
| 682 | } |
| 683 | }) |
| 684 | .collect(); |
| 685 | let mut scripts = scripts; |
| 686 | scripts.sort_unstable(); |
| 687 | if !scripts.is_empty() { |
| 688 | found.push(format!("scripts/ ({})", scripts.join(", "))); |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | found |
| 693 | } |
| 694 | |
| 695 | /// Detect test frameworks from project configuration. |
| 696 | fn detect_test_frameworks(workspace: &Path) -> Vec<String> { |
| 697 | let mut found: Vec<String> = Vec::new(); |
| 698 | |
| 699 | // Rust: check Cargo.toml dev-dependencies (both crate and workspace level). |
| 700 | if let Ok(raw) = std::fs::read_to_string(workspace.join("Cargo.toml")) |
| 701 | && let Ok(doc) = toml::from_str::<toml::Value>(&raw) |
| 702 | { |
| 703 | let mut dep_keys: Vec<&str> = Vec::new(); |
| 704 | if let Some(dev_deps) = doc.get("dev-dependencies").and_then(|v| v.as_table()) { |
| 705 | dep_keys.extend(dev_deps.keys().map(|k| k.as_str())); |
| 706 | } |
| 707 | if let Some(ws_dev_deps) = doc |
| 708 | .get("workspace") |
| 709 | .and_then(|w| w.get("dev-dependencies")) |
| 710 | .and_then(|v| v.as_table()) |
| 711 | { |
| 712 | dep_keys.extend(ws_dev_deps.keys().map(|k| k.as_str())); |
| 713 | } |
| 714 | |
| 715 | let rust_test_frameworks: &[(&str, &str)] = &[ |
| 716 | ("tokio-test", "tokio-test"), |
| 717 | ("proptest", "proptest"), |
| 718 | ("quickcheck", "quickcheck"), |
| 719 | ("rstest", "rstest"), |
| 720 | ("criterion", "criterion (benchmark)"), |
| 721 | ("mockall", "mockall"), |
| 722 | ("pretty_assertions", "pretty_assertions"), |
| 723 | ]; |
| 724 | for (dep_key, label) in rust_test_frameworks { |
| 725 | if dep_keys.contains(dep_key) { |
| 726 | found.push((*label).to_string()); |
| 727 | } |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | // Node.js: check package.json devDependencies. |
| 732 | if let Ok(raw) = std::fs::read_to_string(workspace.join("package.json")) |
| 733 | && let Ok(doc) = serde_json::from_str::<serde_json::Value>(&raw) |
| 734 | && let Some(dev_deps) = doc.get("devDependencies").and_then(|v| v.as_object()) |
| 735 | { |
| 736 | let dev_keys: Vec<&str> = dev_deps.keys().map(|k| k.as_str()).collect(); |
| 737 | |
| 738 | let js_test_frameworks: &[(&str, &str)] = &[ |
| 739 | ("jest", "Jest"), |
| 740 | ("vitest", "Vitest"), |
| 741 | ("mocha", "Mocha"), |
| 742 | ("jasmine", "Jasmine"), |
| 743 | ("ava", "AVA"), |
| 744 | ("playwright", "Playwright"), |
| 745 | ("cypress", "Cypress"), |
| 746 | ("@testing-library/react", "Testing Library"), |
| 747 | ]; |
| 748 | for (dep_key, label) in js_test_frameworks { |
| 749 | if dev_keys.contains(dep_key) { |
| 750 | found.push((*label).to_string()); |
| 751 | } |
| 752 | } |
| 753 | } |
| 754 | |
| 755 | // Python: check common test config files. |
| 756 | if workspace.join("pytest.ini").exists() |
| 757 | || workspace.join("tox.ini").exists() |
| 758 | || workspace.join("conftest.py").exists() |
| 759 | || (workspace.join("pyproject.toml").exists() |
| 760 | && std::fs::read_to_string(workspace.join("pyproject.toml")) |
| 761 | .ok() |
| 762 | .is_some_and(|raw| raw.contains("[tool.pytest"))) |
| 763 | { |
| 764 | found.push("pytest".to_string()); |
| 765 | } |
| 766 | |
| 767 | found |
| 768 | } |
| 769 | |
| 770 | /// Read existing AGENTS.md content (up to 100KB) for in-place update. |
| 771 | fn read_existing_agents_md(workspace: &Path) -> Option<String> { |
| 772 | let path = workspace.join("AGENTS.md"); |
| 773 | let meta = std::fs::metadata(&path).ok()?; |
| 774 | let limit = 100 * 1024; |
| 775 | let len = meta.len() as usize; |
| 776 | let content = if len > limit { |
| 777 | let mut f = std::fs::File::open(&path).ok()?; |
| 778 | let mut buf = vec![0u8; limit]; |
| 779 | f.read_exact(&mut buf).ok()?; |
| 780 | String::from_utf8_lossy(&buf).into_owned() |
| 781 | } else { |
| 782 | std::fs::read_to_string(&path).ok()? |
| 783 | }; |
| 784 | if content.trim().is_empty() { |
| 785 | None |
| 786 | } else { |
| 787 | Some(content) |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | // --------------------------------------------------------------------------- |
| 792 | // Prompt builder |
| 793 | // --------------------------------------------------------------------------- |
| 794 | |
| 795 | /// Build the SendMessage prompt instructing the agent to analyze and generate AGENTS.md. |
| 796 | fn build_init_prompt( |
| 797 | context: &str, |
| 798 | existing_content: Option<&str>, |
| 799 | already_exists: bool, |
| 800 | language: &str, |
| 801 | ) -> String { |
| 802 | let mut prompt = String::new(); |
| 803 | |
| 804 | prompt.push_str( |
| 805 | "You are generating a comprehensive AGENTS.md file for this project. \ |
| 806 | Your task is to deeply analyze the codebase and produce a customized, \ |
| 807 | actionable project guide that will help future AI agents work effectively here.\n\n", |
| 808 | ); |
| 809 | |
| 810 | prompt.push_str("## Project Context (pre-gathered)\n\n"); |
| 811 | prompt.push_str(context); |
| 812 | prompt.push('\n'); |
| 813 | |
| 814 | if let Some(existing) = existing_content { |
| 815 | prompt.push_str("## Existing AGENTS.md\n\n"); |
| 816 | prompt.push_str("Below is the current AGENTS.md content. "); |
| 817 | if already_exists { |
| 818 | prompt.push_str( |
| 819 | "Update it in place: preserve any custom sections that still apply, \ |
| 820 | replace stale or incorrect information with your fresh analysis. ", |
| 821 | ); |
| 822 | } |
| 823 | prompt.push_str("\n\n```markdown\n"); |
| 824 | prompt.push_str(existing); |
| 825 | prompt.push_str("\n```\n\n"); |
| 826 | } |
| 827 | |
| 828 | prompt.push_str("## Instructions\n\n"); |
| 829 | |
| 830 | prompt.push_str(&format!( |
| 831 | "1. **Read key source files** to understand the architecture:\n\ |
| 832 | - Start with the main entry point(s) (e.g., main.rs, index.ts, app.py)\n\ |
| 833 | - Read the top-level module structure to understand component boundaries\n\ |
| 834 | - Read a few representative files from each major module or crate\n\ |
| 835 | - Read config files (config.example.toml, tsconfig.json, etc.) to understand settings\n\n\ |
| 836 | 2. **Generate AGENTS.md** at the workspace root. Use `AGENTS.md` as the filename. \ |
| 837 | Include these sections as applicable:\n\n\ |
| 838 | ### Build / Test / Lint\n\ |
| 839 | - Exact commands for: build, test (all + single), lint, format, run, install deps\n\ |
| 840 | - Be specific — if there's a Justfile, use `just <target>`; if nextest, use `cargo nextest run`\n\n\ |
| 841 | ### Architecture\n\ |
| 842 | - High-level description of the project's purpose\n\ |
| 843 | - Component or module tree with 1-2 sentence descriptions each\n\ |
| 844 | - Data flow through the system (if determinable)\n\n\ |
| 845 | ### Key Files & Directories\n\ |
| 846 | - What each top-level directory contains\n\ |
| 847 | - Important config files and what they control\n\n\ |
| 848 | ### Coding Conventions\n\ |
| 849 | - What you observe from reading source files: naming, error handling patterns, \ |
| 850 | module organization, test patterns\n\ |
| 851 | - Code generation (build.rs, protobuf, etc.) if present\n\n\ |
| 852 | ### Git Workflow\n\ |
| 853 | - Branch naming conventions (if observable from recent commits)\n\ |
| 854 | - Commit message style\n\n\ |
| 855 | ### CI/CD\n\ |
| 856 | - How tests run in CI, what's checked on PRs\n\n\ |
| 857 | ### Tips for AI Agents\n\ |
| 858 | - Common pitfalls in the codebase structure\n\ |
| 859 | - Where to look for specific kinds of things\n\ |
| 860 | - Any gotchas in the build setup\n\n\ |
| 861 | 3. **Style requirements**:\n\ |
| 862 | - Be concise and actionable. This is a reference document, not a tutorial.\n\ |
| 863 | - Use markdown headings, code blocks, and bullet lists.\n\ |
| 864 | - Keep the total under ~150 lines unless the project genuinely needs more.\n\ |
| 865 | - Write the whole file in {language}, headings included; keep commands, \ |
| 866 | file paths and code identifiers as they are.\n\ |
| 867 | - Do NOT include placeholder HTML comments like \"<!-- add stuff here -->\".\n\ |
| 868 | - If you cannot determine something with confidence, omit that section rather than guessing.\n\n\ |
| 869 | 4. **Write the file** using the file write tool. \ |
| 870 | The file should be named `AGENTS.md` at the workspace root.\n\n", |
| 871 | )); |
| 872 | |
| 873 | if already_exists { |
| 874 | prompt.push_str( |
| 875 | "The file already exists — update it in place, \ |
| 876 | preserving custom content that still applies but replacing stale information.\n\n", |
| 877 | ); |
| 878 | } |
| 879 | |
| 880 | prompt.push_str( |
| 881 | "5. After writing, briefly summarize what you learned and what you put into AGENTS.md.\n", |
| 882 | ); |
| 883 | |
| 884 | prompt |
| 885 | } |
| 886 | |
| 887 | pub(in crate::commands) const INIT_INFO: codewhale_command_contract::metadata::CommandInfo = |
| 888 | codewhale_command_contract::metadata::CommandInfo { |
| 889 | name: "init", |
| 890 | aliases: &[], |
| 891 | usage: "/init [cancel]", |
| 892 | description_key: "cmd_init_description", |
| 893 | }; |
| 894 | |
| 895 | pub(in crate::commands) struct InitCmd; |
| 896 | |
| 897 | impl codewhale_command_contract::metadata::RegisterCommand<crate::commands::CommandResult> |
| 898 | for InitCmd |
| 899 | { |
| 900 | fn info() -> &'static codewhale_command_contract::metadata::CommandInfo { |
| 901 | &INIT_INFO |
| 902 | } |
| 903 | |
| 904 | fn handler() |
| 905 | -> codewhale_command_contract::handler::CommandHandler<crate::commands::CommandResult> { |
| 906 | codewhale_command_contract::handler::CommandHandler::Contextual { |
| 907 | capabilities: codewhale_command_contract::handler::CommandCapabilities::WORKSPACE |
| 908 | .union(codewhale_command_contract::handler::CommandCapabilities::PRESENTATION) |
| 909 | .union(codewhale_command_contract::handler::CommandCapabilities::BACKGROUND), |
| 910 | handler: init_contextual, |
| 911 | } |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | /// Contextual `/init` dispatch (FEAT-021 Phase 4). |
| 916 | /// |
| 917 | /// Destructures the declared `WORKSPACE` and `PRESENTATION` facets with safe |
| 918 | /// missing-facet errors. The workspace path is consumed via the `WORKSPACE` |
| 919 | /// facet (D2) and the language the file is written in via `PRESENTATION`; |
| 920 | /// `/init` consumes no project-facet method, so it destructures exactly |
| 921 | /// those two (D4, least-capability — the initial PROJECT|WORKSPACE |
| 922 | /// declaration was amended after the critical audit; main's model expresses |
| 923 | /// the declaration as exact facet destructuring rather than a bitmask). |
| 924 | /// The scan runs through the `BACKGROUND` facet when the host offers one and |
| 925 | /// inline otherwise. |
| 926 | fn init_contextual(mut contexts: CommandContexts<'_>, arg: Option<&str>) -> CommandResult { |
| 927 | let background = contexts.take_background(); |
| 928 | let parts = contexts.into_parts(); |
| 929 | let Some(workspace) = parts.workspace.as_deref() else { |
| 930 | return crate::commands::CommandResult::error("Command capability unavailable: workspace"); |
| 931 | }; |
| 932 | let Some(presentation) = parts.presentation.as_deref() else { |
| 933 | return crate::commands::CommandResult::error( |
| 934 | "Command capability unavailable: presentation", |
| 935 | ); |
| 936 | }; |
| 937 | let workspace = workspace.workspace().to_path_buf(); |
| 938 | let language = presentation.language_name().to_string(); |
| 939 | let Some(background) = background else { |
| 940 | return crate::commands::contract::run_owner_blocking(move || { |
| 941 | Ok(init(&workspace, &language)) |
| 942 | }) |
| 943 | .unwrap_or_else(CommandResult::error); |
| 944 | }; |
| 945 | if arg.is_some_and(|arg| arg.trim().eq_ignore_ascii_case("cancel")) { |
| 946 | return background |
| 947 | .cancel(INIT_INFO.name) |
| 948 | .map_or_else(CommandResult::error, CommandResult::message); |
| 949 | } |
| 950 | background |
| 951 | .start( |
| 952 | INIT_INFO.name, |
| 953 | init_job, |
| 954 | BackgroundRequest { |
| 955 | workspace, |
| 956 | language, |
| 957 | ..BackgroundRequest::default() |
| 958 | }, |
| 959 | ) |
| 960 | .map_or_else(CommandResult::error, CommandResult::message) |
| 961 | } |
| 962 | |
| 963 | fn init_job(request: BackgroundRequest, cancel: BackgroundCancel) -> BackgroundCommandResult { |
| 964 | let Some((message, prompt)) = |
| 965 | prepare_init_cancellable(&request.workspace, &request.language, Some(&cancel)) |
| 966 | else { |
| 967 | return BackgroundCommandResult::error("/init was cancelled."); |
| 968 | }; |
| 969 | BackgroundCommandResult::with_message_and_action(message, BackgroundAction::SendMessage(prompt)) |
| 970 | } |
| 971 | |
| 972 | // --------------------------------------------------------------------------- |
| 973 | // Tests |
| 974 | // --------------------------------------------------------------------------- |
| 975 | |
| 976 | #[cfg(test)] |
| 977 | mod tests { |
| 978 | use super::*; |
| 979 | use std::process::Command; |
| 980 | use tempfile::TempDir; |
| 981 | |
| 982 | // --- init() integration tests --- |
| 983 | |
| 984 | #[test] |
| 985 | fn init_returns_send_message_action() { |
| 986 | let tmpdir = TempDir::new().unwrap(); |
| 987 | let result = init(tmpdir.path(), "English"); |
| 988 | assert!(result.message.is_some()); |
| 989 | let msg = result.message.unwrap(); |
| 990 | assert!(msg.contains("Creating AGENTS.md")); |
| 991 | assert!( |
| 992 | matches!(result.action, Some(AppAction::SendMessage(_))), |
| 993 | "expected SendMessage action" |
| 994 | ); |
| 995 | } |
| 996 | |
| 997 | #[test] |
| 998 | fn init_says_updating_when_agents_md_exists() { |
| 999 | let tmpdir = TempDir::new().unwrap(); |
| 1000 | std::fs::write(tmpdir.path().join("AGENTS.md"), "existing content").unwrap(); |
| 1001 | let result = init(tmpdir.path(), "English"); |
| 1002 | assert!(result.message.unwrap().contains("Updating AGENTS.md")); |
| 1003 | assert!(matches!(result.action, Some(AppAction::SendMessage(_)))); |
| 1004 | } |
| 1005 | |
| 1006 | #[test] |
| 1007 | fn init_includes_gitignore_handling() { |
| 1008 | let tmpdir = TempDir::new().unwrap(); |
| 1009 | std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap(); |
| 1010 | let result = init(tmpdir.path(), "English"); |
| 1011 | assert!(!result.is_error); |
| 1012 | // Should have added .deepseek/ to .gitignore. |
| 1013 | let gi = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap(); |
| 1014 | assert!(gi.contains(".deepseek/")); |
| 1015 | } |
| 1016 | |
| 1017 | #[test] |
| 1018 | fn init_prompt_includes_context_for_rust_project() { |
| 1019 | let tmpdir = TempDir::new().unwrap(); |
| 1020 | std::fs::write( |
| 1021 | tmpdir.path().join("Cargo.toml"), |
| 1022 | "[package]\nname = \"test-crate\"\nversion = \"0.1.0\"\n", |
| 1023 | ) |
| 1024 | .unwrap(); |
| 1025 | let result = init(tmpdir.path(), "English"); |
| 1026 | let Some(AppAction::SendMessage(prompt)) = result.action else { |
| 1027 | panic!("expected SendMessage action"); |
| 1028 | }; |
| 1029 | assert!( |
| 1030 | prompt.contains("test-crate"), |
| 1031 | "prompt should mention crate name" |
| 1032 | ); |
| 1033 | assert!( |
| 1034 | prompt.contains("Read key source files"), |
| 1035 | "should have instructions" |
| 1036 | ); |
| 1037 | assert!( |
| 1038 | prompt.contains("AGENTS.md"), |
| 1039 | "should mention AGENTS.md filename" |
| 1040 | ); |
| 1041 | } |
| 1042 | |
| 1043 | #[test] |
| 1044 | fn init_prompt_includes_existing_content() { |
| 1045 | let tmpdir = TempDir::new().unwrap(); |
| 1046 | std::fs::write( |
| 1047 | tmpdir.path().join("AGENTS.md"), |
| 1048 | "# My Project\n\nCustom instructions here.", |
| 1049 | ) |
| 1050 | .unwrap(); |
| 1051 | let result = init(tmpdir.path(), "English"); |
| 1052 | let Some(AppAction::SendMessage(prompt)) = result.action else { |
| 1053 | panic!("expected SendMessage action"); |
| 1054 | }; |
| 1055 | assert!(prompt.contains("Custom instructions here")); |
| 1056 | assert!(prompt.contains("update it in place")); |
| 1057 | } |
| 1058 | |
| 1059 | struct Background { |
| 1060 | started: Vec<( |
| 1061 | codewhale_command_contract::facets::BackgroundJob, |
| 1062 | BackgroundRequest, |
| 1063 | )>, |
| 1064 | cancelled: usize, |
| 1065 | } |
| 1066 | |
| 1067 | impl codewhale_command_contract::facets::CommandBackgroundContext for Background { |
| 1068 | fn start( |
| 1069 | &mut self, |
| 1070 | command: &'static str, |
| 1071 | job: codewhale_command_contract::facets::BackgroundJob, |
| 1072 | request: BackgroundRequest, |
| 1073 | ) -> Result<String, String> { |
| 1074 | if !self.started.is_empty() { |
| 1075 | return Err(format!("/{command} is already running")); |
| 1076 | } |
| 1077 | self.started.push((job, request)); |
| 1078 | Ok(format!("/{command} started")) |
| 1079 | } |
| 1080 | |
| 1081 | fn cancel(&mut self, command: &'static str) -> Result<String, String> { |
| 1082 | self.cancelled += 1; |
| 1083 | self.started.clear(); |
| 1084 | Ok(format!("/{command} cancelled")) |
| 1085 | } |
| 1086 | } |
| 1087 | |
| 1088 | struct Workspace(PathBuf); |
| 1089 | |
| 1090 | impl codewhale_command_contract::facets::CommandWorkspaceContext for Workspace { |
| 1091 | fn workspace(&self) -> PathBuf { |
| 1092 | self.0.clone() |
| 1093 | } |
| 1094 | fn effective_home_dir(&self) -> Option<PathBuf> { |
| 1095 | None |
| 1096 | } |
| 1097 | fn inspect_workspace_target( |
| 1098 | &self, |
| 1099 | _candidate: &Path, |
| 1100 | ) -> codewhale_command_contract::navigation::WorkspaceTarget { |
| 1101 | unreachable!("/init does not inspect workspace targets") |
| 1102 | } |
| 1103 | fn read_anchor_document(&self) -> Result<Option<String>, String> { |
| 1104 | Ok(None) |
| 1105 | } |
| 1106 | fn append_anchor_bytes( |
| 1107 | &mut self, |
| 1108 | _parts: &[&[u8]], |
| 1109 | ) -> Result<PathBuf, codewhale_command_contract::navigation::AnchorWriteError> { |
| 1110 | unreachable!("/init does not write anchors") |
| 1111 | } |
| 1112 | fn replace_anchor_document(&mut self, _bytes: &[u8]) -> Result<(), String> { |
| 1113 | Ok(()) |
| 1114 | } |
| 1115 | fn work_state_snapshot(&self) -> Result<Option<String>, String> { |
| 1116 | Ok(None) |
| 1117 | } |
| 1118 | fn operation_digest(&mut self) -> Result<String, String> { |
| 1119 | Ok(String::new()) |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | struct Presentation; |
| 1124 | |
| 1125 | impl codewhale_command_contract::facets::CommandPresentationContext for Presentation { |
| 1126 | fn translate(&self, _key: &str, _replacements: &[(&str, &str)]) -> Result<String, String> { |
| 1127 | Err("no catalog".to_string()) |
| 1128 | } |
| 1129 | } |
| 1130 | |
| 1131 | #[test] |
| 1132 | fn init_returns_at_once_and_delivers_the_prompt_as_the_background_result() { |
| 1133 | let tmpdir = TempDir::new().unwrap(); |
| 1134 | let mut workspace = Workspace(tmpdir.path().to_path_buf()); |
| 1135 | let mut presentation = Presentation; |
| 1136 | let mut background = Background { |
| 1137 | started: Vec::new(), |
| 1138 | cancelled: 0, |
| 1139 | }; |
| 1140 | |
| 1141 | let started = init_contextual( |
| 1142 | CommandContexts::empty() |
| 1143 | .with_workspace(&mut workspace) |
| 1144 | .with_presentation(&mut presentation) |
| 1145 | .with_background(&mut background), |
| 1146 | None, |
| 1147 | ); |
| 1148 | assert!(!started.is_error, "{started:?}"); |
| 1149 | assert_eq!(started.message.as_deref(), Some("/init started")); |
| 1150 | assert!( |
| 1151 | started.action.is_none(), |
| 1152 | "the prompt is not sent before the scan finishes" |
| 1153 | ); |
| 1154 | |
| 1155 | let refused = init_contextual( |
| 1156 | CommandContexts::empty() |
| 1157 | .with_workspace(&mut workspace) |
| 1158 | .with_presentation(&mut presentation) |
| 1159 | .with_background(&mut background), |
| 1160 | None, |
| 1161 | ); |
| 1162 | assert!(refused.is_error, "{refused:?}"); |
| 1163 | assert!(refused.message.unwrap().contains("already running")); |
| 1164 | |
| 1165 | let (job, request) = background.started.pop().expect("background job"); |
| 1166 | assert_eq!(request.workspace, tmpdir.path()); |
| 1167 | assert_eq!(request.language, "English"); |
| 1168 | let finished = job(request, BackgroundCancel::default()); |
| 1169 | assert!(!finished.is_error, "{finished:?}"); |
| 1170 | assert!(finished.message.unwrap().contains("Creating AGENTS.md")); |
| 1171 | assert!(matches!( |
| 1172 | finished.action, |
| 1173 | Some(BackgroundAction::SendMessage(prompt)) if prompt.contains("AGENTS.md") |
| 1174 | )); |
| 1175 | |
| 1176 | let cancelled = init_contextual( |
| 1177 | CommandContexts::empty() |
| 1178 | .with_workspace(&mut workspace) |
| 1179 | .with_presentation(&mut presentation) |
| 1180 | .with_background(&mut background), |
| 1181 | Some("cancel"), |
| 1182 | ); |
| 1183 | assert_eq!(cancelled.message.as_deref(), Some("/init cancelled")); |
| 1184 | assert_eq!(background.cancelled, 1); |
| 1185 | } |
| 1186 | |
| 1187 | #[test] |
| 1188 | fn init_job_stops_before_side_effects_when_cancelled() { |
| 1189 | let tmpdir = TempDir::new().unwrap(); |
| 1190 | std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap(); |
| 1191 | let cancel = BackgroundCancel::default(); |
| 1192 | cancel.store(true, Ordering::SeqCst); |
| 1193 | |
| 1194 | let result = init_job( |
| 1195 | BackgroundRequest { |
| 1196 | workspace: tmpdir.path().to_path_buf(), |
| 1197 | language: "English".to_string(), |
| 1198 | ..BackgroundRequest::default() |
| 1199 | }, |
| 1200 | cancel, |
| 1201 | ); |
| 1202 | |
| 1203 | assert!(result.is_error, "{result:?}"); |
| 1204 | assert!(result.action.is_none(), "{result:?}"); |
| 1205 | assert!( |
| 1206 | !tmpdir.path().join(".gitignore").exists(), |
| 1207 | "cancelled /init must not mutate .gitignore" |
| 1208 | ); |
| 1209 | } |
| 1210 | |
| 1211 | #[test] |
| 1212 | fn missing_workspace_facet_fails_safely() { |
| 1213 | // An empty envelope must fail safely — never panic and never perform a |
| 1214 | // partial workspace mutation. |
| 1215 | let result = init_contextual(CommandContexts::empty(), None); |
| 1216 | assert!(result.is_error); |
| 1217 | assert!( |
| 1218 | result |
| 1219 | .message |
| 1220 | .unwrap() |
| 1221 | .contains("Command capability unavailable: workspace"), |
| 1222 | "missing workspace facet must fail safely" |
| 1223 | ); |
| 1224 | } |
| 1225 | |
| 1226 | // --- parse_cargo_toml tests --- |
| 1227 | |
| 1228 | #[test] |
| 1229 | fn parse_cargo_toml_single_crate() { |
| 1230 | let tmpdir = TempDir::new().unwrap(); |
| 1231 | std::fs::write( |
| 1232 | tmpdir.path().join("Cargo.toml"), |
| 1233 | "[package]\nname = \"my-crate\"\nversion = \"1.0.0\"\nedition = \"2021\"\n\n\ |
| 1234 | [dependencies]\ntokio = \"1\"\nserde = \"1\"\n", |
| 1235 | ) |
| 1236 | .unwrap(); |
| 1237 | let info = parse_cargo_toml(tmpdir.path()).unwrap(); |
| 1238 | assert!(info.contains("my-crate")); |
| 1239 | assert!(info.contains("1.0.0")); |
| 1240 | assert!(info.contains("2021")); |
| 1241 | assert!(info.contains("tokio")); |
| 1242 | assert!(info.contains("serde")); |
| 1243 | } |
| 1244 | |
| 1245 | #[test] |
| 1246 | fn parse_cargo_toml_workspace() { |
| 1247 | let tmpdir = TempDir::new().unwrap(); |
| 1248 | std::fs::write( |
| 1249 | tmpdir.path().join("Cargo.toml"), |
| 1250 | "[workspace]\nmembers = [\"crates/cli\", \"crates/tui\"]\n\n\ |
| 1251 | [workspace.dependencies]\nserde = \"1\"\n", |
| 1252 | ) |
| 1253 | .unwrap(); |
| 1254 | let info = parse_cargo_toml(tmpdir.path()).unwrap(); |
| 1255 | assert!(info.contains("workspace root")); |
| 1256 | assert!(info.contains("crates/cli")); |
| 1257 | assert!(info.contains("crates/tui")); |
| 1258 | } |
| 1259 | |
| 1260 | #[test] |
| 1261 | fn parse_cargo_toml_missing() { |
| 1262 | let tmpdir = TempDir::new().unwrap(); |
| 1263 | assert!(parse_cargo_toml(tmpdir.path()).is_none()); |
| 1264 | } |
| 1265 | |
| 1266 | #[test] |
| 1267 | fn parse_cargo_toml_invalid() { |
| 1268 | let tmpdir = TempDir::new().unwrap(); |
| 1269 | std::fs::write(tmpdir.path().join("Cargo.toml"), "not valid toml {{{").unwrap(); |
| 1270 | assert!(parse_cargo_toml(tmpdir.path()).is_none()); |
| 1271 | } |
| 1272 | |
| 1273 | // --- parse_package_json tests --- |
| 1274 | |
| 1275 | #[test] |
| 1276 | fn parse_package_json_basic() { |
| 1277 | let tmpdir = TempDir::new().unwrap(); |
| 1278 | std::fs::write( |
| 1279 | tmpdir.path().join("package.json"), |
| 1280 | r#"{"name":"my-app","scripts":{"build":"tsc","test":"jest"},"dependencies":{"react":"^18"},"devDependencies":{"jest":"^29"}}"#, |
| 1281 | ) |
| 1282 | .unwrap(); |
| 1283 | let info = parse_package_json(tmpdir.path()).unwrap(); |
| 1284 | assert!(info.contains("my-app")); |
| 1285 | assert!(info.contains("build")); |
| 1286 | assert!(info.contains("test")); |
| 1287 | assert!(info.contains("React")); |
| 1288 | assert!(info.contains("jest")); |
| 1289 | } |
| 1290 | |
| 1291 | #[test] |
| 1292 | fn parse_package_json_sorts_context_keys() { |
| 1293 | let tmpdir = TempDir::new().unwrap(); |
| 1294 | std::fs::write( |
| 1295 | tmpdir.path().join("package.json"), |
| 1296 | r#"{ |
| 1297 | "scripts":{"zeta":"node z.js","alpha":"node a.js"}, |
| 1298 | "dependencies":{"react":"^18","axios":"^1"}, |
| 1299 | "devDependencies":{"vitest":"^1","@sveltejs/kit":"^2"} |
| 1300 | }"#, |
| 1301 | ) |
| 1302 | .unwrap(); |
| 1303 | |
| 1304 | let info = parse_package_json(tmpdir.path()).unwrap(); |
| 1305 | |
| 1306 | assert!(info.contains("- Scripts: alpha, zeta")); |
| 1307 | assert!(info.contains("- Dependencies: axios, react")); |
| 1308 | assert!(info.contains("- Dev dependencies: @sveltejs/kit, vitest")); |
| 1309 | } |
| 1310 | |
| 1311 | #[test] |
| 1312 | fn parse_package_json_detects_sveltekit_from_dev_dependencies() { |
| 1313 | let tmpdir = TempDir::new().unwrap(); |
| 1314 | std::fs::write( |
| 1315 | tmpdir.path().join("package.json"), |
| 1316 | r#"{"devDependencies":{"@sveltejs/kit":"^2","vite":"^5"}}"#, |
| 1317 | ) |
| 1318 | .unwrap(); |
| 1319 | |
| 1320 | let info = parse_package_json(tmpdir.path()).unwrap(); |
| 1321 | |
| 1322 | assert!(info.contains("SvelteKit")); |
| 1323 | assert!(info.contains("Vite")); |
| 1324 | } |
| 1325 | |
| 1326 | #[test] |
| 1327 | fn parse_package_json_missing() { |
| 1328 | let tmpdir = TempDir::new().unwrap(); |
| 1329 | assert!(parse_package_json(tmpdir.path()).is_none()); |
| 1330 | } |
| 1331 | |
| 1332 | // --- gather_git_info tests --- |
| 1333 | |
| 1334 | #[test] |
| 1335 | fn strip_url_credentials_removes_authority_userinfo() { |
| 1336 | assert_eq!( |
| 1337 | strip_url_credentials("https://user:token@github.com/org/repo.git"), |
| 1338 | "https://github.com/org/repo.git" |
| 1339 | ); |
| 1340 | assert_eq!( |
| 1341 | strip_url_credentials("https://token@github.com/org/repo.git"), |
| 1342 | "https://github.com/org/repo.git" |
| 1343 | ); |
| 1344 | } |
| 1345 | |
| 1346 | #[test] |
| 1347 | fn strip_url_credentials_preserves_non_authority_at_signs() { |
| 1348 | assert_eq!( |
| 1349 | strip_url_credentials("https://github.com/org/repo@feature.git"), |
| 1350 | "https://github.com/org/repo@feature.git" |
| 1351 | ); |
| 1352 | assert_eq!( |
| 1353 | strip_url_credentials("https://github.com/org/repo.git?ref=user@example.com"), |
| 1354 | "https://github.com/org/repo.git" |
| 1355 | ); |
| 1356 | assert_eq!( |
| 1357 | strip_url_credentials("git@github.com:org/repo.git"), |
| 1358 | "git@github.com:org/repo.git" |
| 1359 | ); |
| 1360 | assert_eq!( |
| 1361 | strip_url_credentials("ssh://git@github.com/org/repo.git"), |
| 1362 | "ssh://git@github.com/org/repo.git" |
| 1363 | ); |
| 1364 | } |
| 1365 | |
| 1366 | #[test] |
| 1367 | fn strip_url_credentials_strips_query_tokens_fragments_and_ssh_passwords() { |
| 1368 | assert_eq!( |
| 1369 | strip_url_credentials( |
| 1370 | "https://user:pass@github.com/org/repo.git?access_token=tok_12345#frag" |
| 1371 | ), |
| 1372 | "https://github.com/org/repo.git" |
| 1373 | ); |
| 1374 | assert_eq!( |
| 1375 | strip_url_credentials("https://github.com/org/repo.git?access_token=tok_12345"), |
| 1376 | "https://github.com/org/repo.git" |
| 1377 | ); |
| 1378 | assert_eq!( |
| 1379 | strip_url_credentials("ssh://user:pass@host/org/repo.git?token=x#section"), |
| 1380 | "ssh://host/org/repo.git" |
| 1381 | ); |
| 1382 | assert_eq!( |
| 1383 | strip_url_credentials("ssh://git@host/org/repo.git?token=x"), |
| 1384 | "ssh://git@host/org/repo.git" |
| 1385 | ); |
| 1386 | assert_eq!( |
| 1387 | strip_url_credentials("https://alice:pass%zz@github.com/org/repo.git?token=secret"), |
| 1388 | "https://github.com/org/repo.git" |
| 1389 | ); |
| 1390 | } |
| 1391 | |
| 1392 | #[test] |
| 1393 | fn gather_git_info_no_repo_returns_none() { |
| 1394 | let tmpdir = TempDir::new().unwrap(); |
| 1395 | assert!(gather_git_info(tmpdir.path()).is_none()); |
| 1396 | } |
| 1397 | |
| 1398 | #[cfg(unix)] |
| 1399 | fn repository_with_fsmonitor( |
| 1400 | seen: &std::path::Path, |
| 1401 | hooks: &std::path::Path, |
| 1402 | ) -> tempfile::TempDir { |
| 1403 | use std::os::unix::fs::PermissionsExt; |
| 1404 | let repo = tempfile::TempDir::new().unwrap(); |
| 1405 | let git = |args: &[&str]| { |
| 1406 | let out = std::process::Command::new("git") |
| 1407 | .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"]) |
| 1408 | .args(["-c", "commit.gpgsign=false"]) |
| 1409 | .args(args) |
| 1410 | .current_dir(repo.path()) |
| 1411 | .output() |
| 1412 | .expect("git runs"); |
| 1413 | assert!(out.status.success(), "git {args:?}: {out:?}"); |
| 1414 | }; |
| 1415 | git(&["init", "-q", "-b", "main"]); |
| 1416 | std::fs::write(repo.path().join("tracked.txt"), "one\n").unwrap(); |
| 1417 | git(&["add", "."]); |
| 1418 | git(&["commit", "-q", "-m", "first"]); |
| 1419 | let script = hooks.join("fsmonitor.sh"); |
| 1420 | std::fs::write( |
| 1421 | &script, |
| 1422 | format!("#!/bin/sh\necho ran >> '{}'\nexit 1\n", seen.display()), |
| 1423 | ) |
| 1424 | .unwrap(); |
| 1425 | std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); |
| 1426 | git(&["config", "core.fsmonitor", &script.to_string_lossy()]); |
| 1427 | std::fs::write(repo.path().join("tracked.txt"), "two\n").unwrap(); |
| 1428 | repo |
| 1429 | } |
| 1430 | |
| 1431 | #[cfg(unix)] |
| 1432 | #[test] |
| 1433 | fn gather_git_info_runs_no_repository_fsmonitor() { |
| 1434 | let hooks = tempfile::TempDir::new().unwrap(); |
| 1435 | let seen = hooks.path().join("seen"); |
| 1436 | let repo = repository_with_fsmonitor(&seen, hooks.path()); |
| 1437 | let info = gather_git_info(repo.path()).expect("repository info"); |
| 1438 | assert!(info.contains("Branch: main"), "{info}"); |
| 1439 | let observed = std::fs::read_to_string(&seen).unwrap_or_default(); |
| 1440 | assert!( |
| 1441 | observed.is_empty(), |
| 1442 | "a repository fsmonitor ran while gathering git info: {observed:?}" |
| 1443 | ); |
| 1444 | } |
| 1445 | |
| 1446 | #[test] |
| 1447 | fn gather_git_info_in_repo_returns_branch() { |
| 1448 | let tmpdir = TempDir::new().unwrap(); |
| 1449 | // Init a real git repo. |
| 1450 | Command::new("git") |
| 1451 | .args(["init"]) |
| 1452 | .current_dir(tmpdir.path()) |
| 1453 | .output() |
| 1454 | .unwrap(); |
| 1455 | Command::new("git") |
| 1456 | .args(["config", "user.email", "test@test.com"]) |
| 1457 | .current_dir(tmpdir.path()) |
| 1458 | .output() |
| 1459 | .unwrap(); |
| 1460 | Command::new("git") |
| 1461 | .args(["config", "user.name", "Test"]) |
| 1462 | .current_dir(tmpdir.path()) |
| 1463 | .output() |
| 1464 | .unwrap(); |
| 1465 | Command::new("git") |
| 1466 | .args(["config", "core.autocrlf", "false"]) |
| 1467 | .current_dir(tmpdir.path()) |
| 1468 | .output() |
| 1469 | .unwrap(); |
| 1470 | Command::new("git") |
| 1471 | .args(["checkout", "-b", "main"]) |
| 1472 | .current_dir(tmpdir.path()) |
| 1473 | .output() |
| 1474 | .unwrap(); |
| 1475 | // Create a commit so rev-parse works. |
| 1476 | std::fs::write(tmpdir.path().join("hello.txt"), "hi").unwrap(); |
| 1477 | Command::new("git") |
| 1478 | .args(["add", "."]) |
| 1479 | .current_dir(tmpdir.path()) |
| 1480 | .output() |
| 1481 | .unwrap(); |
| 1482 | Command::new("git") |
| 1483 | .args(["commit", "-m", "initial"]) |
| 1484 | .current_dir(tmpdir.path()) |
| 1485 | .output() |
| 1486 | .unwrap(); |
| 1487 | |
| 1488 | let info = gather_git_info(tmpdir.path()).unwrap(); |
| 1489 | assert!( |
| 1490 | info.contains("main") || info.contains("master"), |
| 1491 | "should show branch: {info}" |
| 1492 | ); |
| 1493 | } |
| 1494 | |
| 1495 | #[test] |
| 1496 | fn gather_git_info_works_from_nested_workspace() { |
| 1497 | let tmpdir = TempDir::new().unwrap(); |
| 1498 | Command::new("git") |
| 1499 | .args(["init"]) |
| 1500 | .current_dir(tmpdir.path()) |
| 1501 | .output() |
| 1502 | .unwrap(); |
| 1503 | Command::new("git") |
| 1504 | .args(["config", "user.email", "test@test.com"]) |
| 1505 | .current_dir(tmpdir.path()) |
| 1506 | .output() |
| 1507 | .unwrap(); |
| 1508 | Command::new("git") |
| 1509 | .args(["config", "user.name", "Test"]) |
| 1510 | .current_dir(tmpdir.path()) |
| 1511 | .output() |
| 1512 | .unwrap(); |
| 1513 | Command::new("git") |
| 1514 | .args(["config", "core.autocrlf", "false"]) |
| 1515 | .current_dir(tmpdir.path()) |
| 1516 | .output() |
| 1517 | .unwrap(); |
| 1518 | Command::new("git") |
| 1519 | .args(["checkout", "-b", "main"]) |
| 1520 | .current_dir(tmpdir.path()) |
| 1521 | .output() |
| 1522 | .unwrap(); |
| 1523 | std::fs::write(tmpdir.path().join("hello.txt"), "hi").unwrap(); |
| 1524 | Command::new("git") |
| 1525 | .args(["add", "."]) |
| 1526 | .current_dir(tmpdir.path()) |
| 1527 | .output() |
| 1528 | .unwrap(); |
| 1529 | Command::new("git") |
| 1530 | .args(["commit", "-m", "initial"]) |
| 1531 | .current_dir(tmpdir.path()) |
| 1532 | .output() |
| 1533 | .unwrap(); |
| 1534 | let nested = tmpdir.path().join("nested").join("app"); |
| 1535 | std::fs::create_dir_all(&nested).unwrap(); |
| 1536 | |
| 1537 | let info = gather_git_info(&nested).unwrap(); |
| 1538 | |
| 1539 | assert!(info.contains("Branch: main"), "git info was: {info}"); |
| 1540 | } |
| 1541 | |
| 1542 | // --- detect_ci_systems tests --- |
| 1543 | |
| 1544 | #[test] |
| 1545 | fn detect_ci_github_actions() { |
| 1546 | let tmpdir = TempDir::new().unwrap(); |
| 1547 | let wf_dir = tmpdir.path().join(".github").join("workflows"); |
| 1548 | std::fs::create_dir_all(&wf_dir).unwrap(); |
| 1549 | std::fs::write(wf_dir.join("ci.yml"), "").unwrap(); |
| 1550 | let ci = detect_ci_systems(tmpdir.path()); |
| 1551 | assert!(ci.iter().any(|s| s.contains("GitHub Actions"))); |
| 1552 | } |
| 1553 | |
| 1554 | #[test] |
| 1555 | fn detect_ci_github_actions_sorts_workflow_files() { |
| 1556 | let tmpdir = TempDir::new().unwrap(); |
| 1557 | let wf_dir = tmpdir.path().join(".github").join("workflows"); |
| 1558 | std::fs::create_dir_all(&wf_dir).unwrap(); |
| 1559 | std::fs::write(wf_dir.join("z.yml"), "").unwrap(); |
| 1560 | std::fs::write(wf_dir.join("a.yaml"), "").unwrap(); |
| 1561 | |
| 1562 | let ci = detect_ci_systems(tmpdir.path()); |
| 1563 | |
| 1564 | assert_eq!(ci[0], "GitHub Actions (a.yaml, z.yml)"); |
| 1565 | } |
| 1566 | |
| 1567 | #[test] |
| 1568 | fn detect_ci_none() { |
| 1569 | let tmpdir = TempDir::new().unwrap(); |
| 1570 | assert!(detect_ci_systems(tmpdir.path()).is_empty()); |
| 1571 | } |
| 1572 | |
| 1573 | // --- detect_build_systems tests --- |
| 1574 | |
| 1575 | #[test] |
| 1576 | fn detect_makefile() { |
| 1577 | let tmpdir = TempDir::new().unwrap(); |
| 1578 | std::fs::write(tmpdir.path().join("Makefile"), "").unwrap(); |
| 1579 | let build = detect_build_systems(tmpdir.path()); |
| 1580 | assert!(build.contains(&"Makefile".to_string())); |
| 1581 | } |
| 1582 | |
| 1583 | #[test] |
| 1584 | fn detect_justfile() { |
| 1585 | let tmpdir = TempDir::new().unwrap(); |
| 1586 | std::fs::write(tmpdir.path().join("Justfile"), "").unwrap(); |
| 1587 | let build = detect_build_systems(tmpdir.path()); |
| 1588 | assert!(build.contains(&"Justfile".to_string())); |
| 1589 | } |
| 1590 | |
| 1591 | #[test] |
| 1592 | fn detect_build_systems_sorts_scripts() { |
| 1593 | let tmpdir = TempDir::new().unwrap(); |
| 1594 | let scripts = tmpdir.path().join("scripts"); |
| 1595 | std::fs::create_dir_all(&scripts).unwrap(); |
| 1596 | std::fs::write(scripts.join("z.sh"), "").unwrap(); |
| 1597 | std::fs::write(scripts.join("a.py"), "").unwrap(); |
| 1598 | |
| 1599 | let build = detect_build_systems(tmpdir.path()); |
| 1600 | |
| 1601 | assert!(build.contains(&"scripts/ (a.py, z.sh)".to_string())); |
| 1602 | } |
| 1603 | |
| 1604 | // --- detect_test_frameworks tests --- |
| 1605 | |
| 1606 | #[test] |
| 1607 | fn detect_rust_test_frameworks_from_cargo() { |
| 1608 | let tmpdir = TempDir::new().unwrap(); |
| 1609 | std::fs::write( |
| 1610 | tmpdir.path().join("Cargo.toml"), |
| 1611 | "[dev-dependencies]\ntokio-test = \"1\"\nproptest = \"1\"\n", |
| 1612 | ) |
| 1613 | .unwrap(); |
| 1614 | let frameworks = detect_test_frameworks(tmpdir.path()); |
| 1615 | assert!(frameworks.contains(&"tokio-test".to_string())); |
| 1616 | assert!(frameworks.contains(&"proptest".to_string())); |
| 1617 | } |
| 1618 | |
| 1619 | #[test] |
| 1620 | fn detect_js_test_frameworks_from_package_json() { |
| 1621 | let tmpdir = TempDir::new().unwrap(); |
| 1622 | std::fs::write( |
| 1623 | tmpdir.path().join("package.json"), |
| 1624 | r#"{"devDependencies":{"jest":"^29","vitest":"^1"}}"#, |
| 1625 | ) |
| 1626 | .unwrap(); |
| 1627 | let frameworks = detect_test_frameworks(tmpdir.path()); |
| 1628 | assert!(frameworks.contains(&"Jest".to_string())); |
| 1629 | assert!(frameworks.contains(&"Vitest".to_string())); |
| 1630 | } |
| 1631 | |
| 1632 | // --- read_existing_agents_md tests --- |
| 1633 | |
| 1634 | #[test] |
| 1635 | fn read_existing_agents_md_present() { |
| 1636 | let tmpdir = TempDir::new().unwrap(); |
| 1637 | std::fs::write(tmpdir.path().join("AGENTS.md"), "hello world").unwrap(); |
| 1638 | let content = read_existing_agents_md(tmpdir.path()); |
| 1639 | assert_eq!(content, Some("hello world".to_string())); |
| 1640 | } |
| 1641 | |
| 1642 | #[test] |
| 1643 | fn read_existing_agents_md_missing() { |
| 1644 | let tmpdir = TempDir::new().unwrap(); |
| 1645 | assert!(read_existing_agents_md(tmpdir.path()).is_none()); |
| 1646 | } |
| 1647 | |
| 1648 | #[test] |
| 1649 | fn read_existing_agents_md_empty_file_returns_none() { |
| 1650 | let tmpdir = TempDir::new().unwrap(); |
| 1651 | std::fs::write(tmpdir.path().join("AGENTS.md"), "").unwrap(); |
| 1652 | assert!(read_existing_agents_md(tmpdir.path()).is_none()); |
| 1653 | } |
| 1654 | |
| 1655 | // --- build_init_prompt tests --- |
| 1656 | |
| 1657 | #[test] |
| 1658 | fn build_init_prompt_contains_all_sections() { |
| 1659 | let ctx = "## Project Summary\n\nA Rust project\n"; |
| 1660 | let prompt = build_init_prompt(ctx, None, false, "English"); |
| 1661 | assert!(prompt.contains("Project Context")); |
| 1662 | assert!(prompt.contains("A Rust project")); |
| 1663 | assert!(prompt.contains("Read key source files")); |
| 1664 | assert!(prompt.contains("Build / Test / Lint")); |
| 1665 | assert!(prompt.contains("Architecture")); |
| 1666 | assert!(prompt.contains("AGENTS.md")); |
| 1667 | } |
| 1668 | |
| 1669 | #[test] |
| 1670 | fn build_init_prompt_with_existing_content() { |
| 1671 | let ctx = "## Project Summary\n\nA Rust project\n"; |
| 1672 | let existing = "# Old AGENTS.md content"; |
| 1673 | let prompt = build_init_prompt(ctx, Some(existing), true, "English"); |
| 1674 | assert!(prompt.contains("Old AGENTS.md content")); |
| 1675 | assert!(prompt.contains("Update it in place")); |
| 1676 | } |
| 1677 | |
| 1678 | #[test] |
| 1679 | fn build_init_prompt_new_file_no_update_instruction() { |
| 1680 | let ctx = "## Project Summary\n\nA Rust project\n"; |
| 1681 | let prompt = build_init_prompt(ctx, None, false, "English"); |
| 1682 | assert!(!prompt.contains("The file already exists")); |
| 1683 | } |
| 1684 | |
| 1685 | // --- js framework detection --- |
| 1686 | |
| 1687 | #[test] |
| 1688 | fn detect_js_frameworks_react() { |
| 1689 | let deps = ["react", "react-dom", "vite"]; |
| 1690 | let frameworks = detect_js_frameworks(&deps); |
| 1691 | assert!(frameworks.contains(&"React".to_string())); |
| 1692 | assert!(frameworks.contains(&"Vite".to_string())); |
| 1693 | } |
| 1694 | |
| 1695 | #[test] |
| 1696 | fn detect_js_frameworks_none() { |
| 1697 | let deps = ["lodash", "axios"]; |
| 1698 | assert!(detect_js_frameworks(&deps).is_empty()); |
| 1699 | } |
| 1700 | |
| 1701 | // --- ensure_deepseek_gitignored (preserved tests) --- |
| 1702 | |
| 1703 | #[test] |
| 1704 | fn ensure_deepseek_gitignored_creates_gitignore() { |
| 1705 | let tmpdir = TempDir::new().unwrap(); |
| 1706 | std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap(); |
| 1707 | ensure_deepseek_gitignored(tmpdir.path()); |
| 1708 | let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap(); |
| 1709 | assert!(content.contains(".deepseek/")); |
| 1710 | // .codewhale/ is ignored at any depth, but the committed |
| 1711 | // constitution.json is kept. |
| 1712 | assert!(content.contains("**/.codewhale/*")); |
| 1713 | assert!(content.contains("!**/.codewhale/constitution.json")); |
| 1714 | } |
| 1715 | |
| 1716 | #[test] |
| 1717 | fn ensure_deepseek_gitignored_appends_to_existing() { |
| 1718 | let tmpdir = TempDir::new().unwrap(); |
| 1719 | std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap(); |
| 1720 | std::fs::write(tmpdir.path().join(".gitignore"), "target/\n").unwrap(); |
| 1721 | ensure_deepseek_gitignored(tmpdir.path()); |
| 1722 | let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap(); |
| 1723 | assert!(content.contains("target/")); |
| 1724 | assert!(content.contains(".deepseek/")); |
| 1725 | } |
| 1726 | |
| 1727 | #[test] |
| 1728 | fn ensure_deepseek_gitignored_idempotent() { |
| 1729 | let tmpdir = TempDir::new().unwrap(); |
| 1730 | std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap(); |
| 1731 | ensure_deepseek_gitignored(tmpdir.path()); |
| 1732 | ensure_deepseek_gitignored(tmpdir.path()); |
| 1733 | let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap(); |
| 1734 | assert_eq!(content.matches(".deepseek/").count(), 1); |
| 1735 | } |
| 1736 | |
| 1737 | #[test] |
| 1738 | fn ensure_deepseek_gitignored_skips_non_git_repo() { |
| 1739 | let tmpdir = TempDir::new().unwrap(); |
| 1740 | ensure_deepseek_gitignored(tmpdir.path()); |
| 1741 | assert!(!tmpdir.path().join(".gitignore").exists()); |
| 1742 | } |
| 1743 | |
| 1744 | #[test] |
| 1745 | fn ensure_deepseek_gitignored_handles_no_trailing_newline() { |
| 1746 | let tmpdir = TempDir::new().unwrap(); |
| 1747 | std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap(); |
| 1748 | std::fs::write(tmpdir.path().join(".gitignore"), "target/").unwrap(); |
| 1749 | ensure_deepseek_gitignored(tmpdir.path()); |
| 1750 | let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap(); |
| 1751 | assert!(content.contains("target/")); |
| 1752 | assert!(content.contains(".deepseek/")); |
| 1753 | let lines: Vec<&str> = content.lines().collect(); |
| 1754 | assert!(lines.len() >= 2); |
| 1755 | } |
| 1756 | |
| 1757 | #[test] |
| 1758 | fn ensure_deepseek_gitignored_detects_variant_without_slash() { |
| 1759 | let tmpdir = TempDir::new().unwrap(); |
| 1760 | std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap(); |
| 1761 | std::fs::write(tmpdir.path().join(".gitignore"), ".deepseek\n").unwrap(); |
| 1762 | ensure_deepseek_gitignored(tmpdir.path()); |
| 1763 | let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap(); |
| 1764 | assert_eq!(content.matches(".deepseek").count(), 1); |
| 1765 | } |
| 1766 | |
| 1767 | #[test] |
| 1768 | fn ensure_deepseek_gitignored_updates_repo_root_from_nested_workspace() { |
| 1769 | let tmpdir = TempDir::new().unwrap(); |
| 1770 | Command::new("git") |
| 1771 | .args(["init"]) |
| 1772 | .current_dir(tmpdir.path()) |
| 1773 | .output() |
| 1774 | .unwrap(); |
| 1775 | let nested = tmpdir.path().join("nested").join("app"); |
| 1776 | std::fs::create_dir_all(&nested).unwrap(); |
| 1777 | |
| 1778 | ensure_deepseek_gitignored(&nested); |
| 1779 | |
| 1780 | let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap(); |
| 1781 | assert!(content.contains(".deepseek/")); |
| 1782 | assert!(!nested.join(".gitignore").exists()); |
| 1783 | } |
| 1784 | } |
| 1785 |