codewhale-tui 0.8.53

Terminal UI for open-source and open-weight coding models
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
//! /init command - Generate AGENTS.md for project

use std::fmt::Write;
use std::io::Read;
use std::path::Path;

use crate::tui::app::App;

use super::CommandResult;

/// Generate an AGENTS.md file for the current project
pub fn init(app: &mut App) -> CommandResult {
    let workspace = &app.workspace;

    // Ensure .deepseek/ is gitignored if we're inside a git repo.
    ensure_deepseek_gitignored(workspace);

    // Check if AGENTS.md already exists — update it in place rather than refusing.
    let agents_path = workspace.join("AGENTS.md");
    let already_exists = agents_path.exists();

    // Detect project type and generate appropriate content
    let content = generate_project_doc(workspace);

    // Write the file
    match std::fs::write(&agents_path, &content) {
        Ok(()) => {
            let verb = if already_exists { "Updated" } else { "Created" };
            CommandResult::message(format!(
                "{verb} AGENTS.md at {}\n\nEdit this file to customize agent behavior for your project.",
                agents_path.display()
            ))
        }
        Err(e) => CommandResult::error(format!("Failed to write AGENTS.md: {e}")),
    }
}

/// If `workspace` is inside a git repository, ensure workspace-local CodeWhale
/// state is listed in the nearest `.gitignore` so snapshots, auto-generated
/// instructions, and other runtime state are not accidentally committed — while
/// keeping the authored `.codewhale/constitution.json` repo authority policy
/// committable (a directory exclude cannot be overridden, so `.codewhale/*` plus
/// a negation is required).
fn ensure_deepseek_gitignored(workspace: &Path) {
    // Only act if this workspace is a git repo.
    if !workspace.join(".git").exists() {
        return;
    }

    let gitignore = workspace.join(".gitignore");
    let entries = [
        "**/.codewhale/*",
        "!**/.codewhale/constitution.json",
        ".deepseek/",
    ];

    // Read existing contents once.
    let existing = std::fs::read_to_string(&gitignore).unwrap_or_default();
    let mut missing: Vec<&str> = Vec::new();
    for entry in entries {
        let entry_no_slash = entry.trim_end_matches('/');
        let already_ignored = existing.lines().any(|line| {
            let trimmed = line.trim();
            trimmed == entry || trimmed == entry_no_slash
        });
        if !already_ignored {
            missing.push(entry);
        }
    }

    if missing.is_empty() {
        return;
    }

    // Append missing entries. If .gitignore doesn't exist yet, create it.
    use std::io::Write;
    if let Ok(mut file) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&gitignore)
    {
        // If the file is non-empty and doesn't end with a newline, add one first.
        if let Ok(meta) = file.metadata()
            && meta.len() > 0
            && let Ok(mut f) = std::fs::File::open(&gitignore)
        {
            use std::io::Seek;
            if f.seek(std::io::SeekFrom::End(-1)).is_ok() {
                let mut buf = [0u8; 1];
                if f.read_exact(&mut buf).is_ok() && buf[0] != b'\n' {
                    let _ = writeln!(file);
                }
            }
        }
        for entry in &missing {
            let _ = writeln!(file, "{entry}");
        }
    }
}

/// Generate project documentation based on detected project type
fn generate_project_doc(workspace: &Path) -> String {
    let mut doc = String::new();

    // Header
    doc.push_str("# Project Instructions\n\n");
    doc.push_str("This file provides context for AI assistants working on this project.\n\n");

    // Detect project type
    let project_info = detect_project_type(workspace);
    doc.push_str(&project_info);

    // Agent behavior — conventions, gotchas, testing
    doc.push_str("## Agent Guidance\n\n");
    doc.push_str("<!-- How should an AI agent approach this project? Fill in tool gotchas, -->\n");
    doc.push_str("<!-- file patterns to avoid, and anything that helps a model navigate -->\n");
    doc.push_str("<!-- the codebase without reading every file. -->\n");
    doc.push('\n');
    doc.push_str("- **CodeWhale reads this file as:** AGENTS.md (canonical cross-agent project instructions). <!-- WHALE.md is deprecated; put CodeWhale-specific authority policy in .codewhale/constitution.json -->\n");
    doc.push_str(
        "- **Read-only surface:** <!-- Which directories can the agent read but not write? -->\n",
    );
    doc.push_str(
        "- **Never edit:** <!-- Files that are generated, vendored, or owned by another tool -->\n",
    );
    doc.push_str("- **Always test with:** <!-- The single command that validates a change (e.g. `cargo test -p foo`) -->\n");
    doc.push('\n');

    // Architecture — the "big picture" that requires reading multiple files
    doc.push_str("## Architecture\n\n");
    doc.push_str("<!-- Describe the high-level structure. What are the key modules and how -->\n");
    doc.push_str("<!-- do they connect? Focus on the context a new contributor would need. -->\n");
    doc.push('\n');
    doc.push_str("### Entry Points\n");
    doc.push_str(
        "<!-- Where does execution start? Binary entry, request handler, main loop? -->\n",
    );
    doc.push('\n');
    doc.push_str("### Key Modules\n");
    doc.push_str("<!-- List the 3-6 most important directories/files and their role -->\n");
    doc.push('\n');
    doc.push_str("### Data Flow\n");
    doc.push_str("<!-- How does a request / event / input travel through the system? -->\n");
    doc.push('\n');

    // Cache-aware editing — helps maintain prefix-cache hit rates
    doc.push_str("## Cache Stability\n\n");
    doc.push_str("<!-- DeepSeek V4 uses a byte-stable prefix cache (128-token granularity). -->\n");
    doc.push_str(
        "<!-- Keeping these things stable turn-over-turn saves ~90% on input tokens. -->\n",
    );
    doc.push('\n');
    doc.push_str("- **Frequently-rebuilt files:** <!-- Generated code, lockfiles, build artifacts → mark as cache-churn -->\n");
    doc.push_str("- **Stable scaffolding:** <!-- Config files, project instructions, model cards → keep byte-stable -->\n");
    doc.push_str("- **Append, don't reorder:** <!-- New context goes at the end of the request; reordering invalidates cache -->\n");
    doc.push('\n');

    // Guidelines
    doc.push_str("## Guidelines\n\n");
    doc.push_str("- Follow existing code style and patterns\n");
    doc.push_str("- Write tests for new functionality\n");
    doc.push_str("- Keep changes focused and atomic\n");
    doc.push_str("- Document public APIs\n");
    doc.push_str("- Update this file when project conventions change\n");

    doc
}

/// Detect project type and return relevant information
fn detect_project_type(workspace: &Path) -> String {
    let mut info = String::new();

    // Check for Rust project
    if workspace.join("Cargo.toml").exists() {
        info.push_str("## Project Type: Rust\n\n");
        info.push_str("### Commands\n");
        info.push_str("- Build: `cargo build`\n");
        info.push_str("- Test: `cargo test`\n");
        info.push_str("- Run: `cargo run`\n");
        info.push_str("- Check: `cargo check`\n");
        info.push_str("- Format: `cargo fmt`\n");
        info.push_str("- Lint: `cargo clippy`\n\n");

        // Try to extract project name from Cargo.toml
        if let Some(name) = std::fs::read_to_string(workspace.join("Cargo.toml"))
            .ok()
            .and_then(|content| extract_cargo_name(&content))
        {
            let _ = write!(info, "### Project: {name}\n\n");
        }
    }
    // Check for Node.js project
    else if workspace.join("package.json").exists() {
        info.push_str("## Project Type: Node.js\n\n");
        info.push_str("### Commands\n");
        info.push_str("- Install: `npm install`\n");
        info.push_str("- Test: `npm test`\n");
        info.push_str("- Build: `npm run build`\n");
        info.push_str("- Start: `npm start`\n\n");

        // Check for common frameworks
        if workspace.join("next.config.js").exists() || workspace.join("next.config.ts").exists() {
            info.push_str("### Framework: Next.js\n\n");
        } else if workspace.join("vite.config.js").exists()
            || workspace.join("vite.config.ts").exists()
        {
            info.push_str("### Framework: Vite\n\n");
        }
    }
    // Check for Python project
    else if workspace.join("pyproject.toml").exists() || workspace.join("setup.py").exists() {
        info.push_str("## Project Type: Python\n\n");
        info.push_str("### Commands\n");
        if workspace.join("pyproject.toml").exists() {
            info.push_str("- Install: `pip install -e .`\n");
        }
        info.push_str("- Test: `pytest`\n");
        info.push_str("- Format: `black .`\n");
        info.push_str("- Lint: `ruff check .`\n\n");
    }
    // Check for Go project
    else if workspace.join("go.mod").exists() {
        info.push_str("## Project Type: Go\n\n");
        info.push_str("### Commands\n");
        info.push_str("- Build: `go build`\n");
        info.push_str("- Test: `go test ./...`\n");
        info.push_str("- Run: `go run .`\n");
        info.push_str("- Format: `go fmt ./...`\n\n");
    }
    // Unknown project type
    else {
        info.push_str("## Project Type: Unknown\n\n");
        info.push_str("<!-- Add build/test commands here -->\n\n");
    }

    // Check for README
    if workspace.join("README.md").exists() {
        info.push_str("### Documentation\n");
        info.push_str("See README.md for project overview.\n\n");
    }

    // Check for .gitignore
    if workspace.join(".gitignore").exists() {
        info.push_str("### Version Control\n");
        info.push_str("This project uses Git. See .gitignore for excluded files.\n\n");
    }

    info
}

/// Extract project name from Cargo.toml
fn extract_cargo_name(content: &str) -> Option<String> {
    for line in content.lines() {
        let line = line.trim();
        if line.starts_with("name") && line.contains('=') {
            let parts: Vec<&str> = line.splitn(2, '=').collect();
            if parts.len() == 2 {
                let name = parts[1].trim().trim_matches('"').trim_matches('\'');
                return Some(name.to_string());
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::tui::app::{App, TuiOptions};
    use tempfile::TempDir;

    fn create_test_app_with_tmpdir(tmpdir: &TempDir) -> App {
        let options = TuiOptions {
            model: "deepseek-v4-pro".to_string(),
            workspace: tmpdir.path().to_path_buf(),
            config_path: None,
            config_profile: None,
            allow_shell: false,
            use_alt_screen: true,
            use_mouse_capture: false,
            use_bracketed_paste: true,
            max_subagents: 1,
            skills_dir: tmpdir.path().join("skills"),
            memory_path: tmpdir.path().join("memory.md"),
            notes_path: tmpdir.path().join("notes.txt"),
            mcp_config_path: tmpdir.path().join("mcp.json"),
            use_memory: false,
            start_in_agent_mode: false,
            skip_onboarding: true,
            yolo: false,
            resume_session_id: None,
            initial_input: None,
        };
        App::new(options, &Config::default())
    }

    #[test]
    fn test_init_creates_agents_md() {
        let tmpdir = TempDir::new().unwrap();
        let mut app = create_test_app_with_tmpdir(&tmpdir);
        let result = init(&mut app);
        assert!(result.message.is_some());
        let msg = result.message.unwrap();
        assert!(msg.contains("Created AGENTS.md"));
        let agents_path = tmpdir.path().join("AGENTS.md");
        assert!(agents_path.exists());
    }

    #[test]
    fn test_init_updates_if_exists() {
        let tmpdir = TempDir::new().unwrap();
        let mut app = create_test_app_with_tmpdir(&tmpdir);
        // Create file first with stale content
        let agents_path = tmpdir.path().join("AGENTS.md");
        std::fs::write(&agents_path, "existing stale content").unwrap();
        let result = init(&mut app);
        assert!(!result.is_error);
        assert!(result.message.is_some());
        assert!(result.message.unwrap().contains("Updated AGENTS.md"));
        let new_content = std::fs::read_to_string(&agents_path).unwrap();
        assert!(new_content.contains("# Project Instructions"));
        assert!(!new_content.contains("existing stale content"));
    }

    #[test]
    fn test_detect_project_type_rust() {
        let tmpdir = TempDir::new().unwrap();
        std::fs::write(
            tmpdir.path().join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .unwrap();
        let info = detect_project_type(tmpdir.path());
        assert!(info.contains("Project Type: Rust"));
        assert!(info.contains("cargo build"));
        assert!(info.contains("cargo test"));
    }

    #[test]
    fn test_detect_project_type_node() {
        let tmpdir = TempDir::new().unwrap();
        std::fs::write(tmpdir.path().join("package.json"), "{}").unwrap();
        let info = detect_project_type(tmpdir.path());
        assert!(info.contains("Project Type: Node.js"));
        assert!(info.contains("npm install"));
    }

    #[test]
    fn test_detect_project_type_python() {
        let tmpdir = TempDir::new().unwrap();
        std::fs::write(tmpdir.path().join("pyproject.toml"), "[project]").unwrap();
        let info = detect_project_type(tmpdir.path());
        assert!(info.contains("Project Type: Python"));
    }

    #[test]
    fn test_detect_project_type_go() {
        let tmpdir = TempDir::new().unwrap();
        std::fs::write(tmpdir.path().join("go.mod"), "module test").unwrap();
        let info = detect_project_type(tmpdir.path());
        assert!(info.contains("Project Type: Go"));
    }

    #[test]
    fn test_detect_project_type_unknown() {
        let tmpdir = TempDir::new().unwrap();
        let info = detect_project_type(tmpdir.path());
        assert!(info.contains("Project Type: Unknown"));
    }

    #[test]
    fn test_extract_cargo_name() {
        let cargo = r#"
[package]
name = "my-project"
version = "1.0.0"
"#;
        assert_eq!(extract_cargo_name(cargo), Some("my-project".to_string()));
    }

    #[test]
    fn test_extract_cargo_name_single_quotes() {
        let cargo = r#"name = 'single-quoted'"#;
        assert_eq!(extract_cargo_name(cargo), Some("single-quoted".to_string()));
    }

    #[test]
    fn test_extract_cargo_name_not_found() {
        let cargo = "[package]\nversion = \"1.0.0\"";
        assert_eq!(extract_cargo_name(cargo), None);
    }

    #[test]
    fn ensure_deepseek_gitignored_creates_gitignore() {
        let tmpdir = TempDir::new().unwrap();
        // Simulate a git repo.
        std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap();

        ensure_deepseek_gitignored(tmpdir.path());

        let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap();
        assert!(content.contains(".deepseek/"));
        // .codewhale/ is ignored at any depth, but the committed
        // constitution.json is kept.
        assert!(content.contains("**/.codewhale/*"));
        assert!(content.contains("!**/.codewhale/constitution.json"));
    }

    #[test]
    fn ensure_deepseek_gitignored_appends_to_existing() {
        let tmpdir = TempDir::new().unwrap();
        std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap();
        std::fs::write(tmpdir.path().join(".gitignore"), "target/\n").unwrap();

        ensure_deepseek_gitignored(tmpdir.path());

        let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap();
        assert!(content.contains("target/"));
        assert!(content.contains(".deepseek/"));
    }

    #[test]
    fn ensure_deepseek_gitignored_idempotent() {
        let tmpdir = TempDir::new().unwrap();
        std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap();

        ensure_deepseek_gitignored(tmpdir.path());
        ensure_deepseek_gitignored(tmpdir.path());

        let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap();
        assert_eq!(content.matches(".deepseek/").count(), 1);
    }

    #[test]
    fn ensure_deepseek_gitignored_skips_non_git_repo() {
        let tmpdir = TempDir::new().unwrap();
        // No .git directory — not a git repo.

        ensure_deepseek_gitignored(tmpdir.path());

        assert!(!tmpdir.path().join(".gitignore").exists());
    }

    #[test]
    fn ensure_deepseek_gitignored_handles_no_trailing_newline() {
        let tmpdir = TempDir::new().unwrap();
        std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap();
        // Write a file that does NOT end with a newline.
        std::fs::write(tmpdir.path().join(".gitignore"), "target/").unwrap();

        ensure_deepseek_gitignored(tmpdir.path());

        let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap();
        // Must have both entries on separate lines.
        assert!(content.contains("target/"));
        assert!(content.contains(".deepseek/"));
        // The entries should be on different lines.
        let lines: Vec<&str> = content.lines().collect();
        assert!(lines.len() >= 2);
    }

    #[test]
    fn ensure_deepseek_gitignored_detects_variant_without_slash() {
        let tmpdir = TempDir::new().unwrap();
        std::fs::create_dir_all(tmpdir.path().join(".git")).unwrap();
        // Write .deepseek without trailing slash.
        std::fs::write(tmpdir.path().join(".gitignore"), ".deepseek\n").unwrap();

        ensure_deepseek_gitignored(tmpdir.path());

        let content = std::fs::read_to_string(tmpdir.path().join(".gitignore")).unwrap();
        // Should NOT add a duplicate entry.
        assert_eq!(content.matches(".deepseek").count(), 1);
    }
}