ai-dispatch 8.99.9

Multi-AI CLI team orchestrator
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
// Project command handlers for the `aid project` CLI group.
// Exports: ProjectAction, run_project_command.
// Deps: crate::config, crate::project, serde_json, std::{fs, io, path, process}.
mod state_command;

use crate::{config as aid_config, project};
use anyhow::{anyhow, bail, Context, Result};
use serde_json::Value;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
pub enum ProjectAction {
    Init,
    Show,
    State,
    Sync,
}
pub fn run_project_command(action: ProjectAction) -> Result<()> {
    match action {
        ProjectAction::Init => init(),
        ProjectAction::Show => show(),
        ProjectAction::State => state(),
        ProjectAction::Sync => sync(),
    }
}
fn init() -> Result<()> {
    let git_root = current_git_root()?;
    let project_id = prompt_project_id(&git_root)?;
    let profile = prompt_profile("Profile (hobby/standard/production)", "standard")?;
    let language = prompt_language(detect_language(&git_root).as_deref())?;
    let (budget_shorthand, budget_cost, budget_window) =
        prompt_daily_budget(default_budget_for_profile(&profile))?;
    let team_input = prompt_line("Team (optional)", Some(""), true)?;
    let team = if team_input.is_empty() {
        None
    } else {
        Some(team_input)
    };
    let verify_default = default_verify_for_language(language.as_deref());
    let verify_command = prompt_line("Verify command", Some(verify_default), false)?;
    let gitbutler = detect_gitbutler_mode()?;
    let (project_path, knowledge_index) = write_project_config(
        &git_root,
        &project_id,
        &profile,
        language.as_deref(),
        Some(&budget_shorthand),
        team.as_deref(),
        Some(verify_command.as_str()),
        gitbutler,
    )?;
    aid_config::upsert_budget(&project_id, budget_cost, budget_window.as_deref())?;
    println!("  Budget synced to ~/.aid/config.toml");
    let config = project::load_project(&project_path)?;
    crate::claudemd::sync_claude_md(&git_root, &config)?;
    println!("  CLAUDE.md updated with aid section");
    println!("Project: {}", config.id);
    println!("  Profile: {}", config.profile.as_deref().unwrap_or("-"));
    println!("  Language: {}", config.language.as_deref().unwrap_or("-"));
    println!("  File: {}", project_path.display());
    println!("  Knowledge: {}", knowledge_index.display());
    Ok(())
}
fn sync() -> Result<()> {
    let git_root = current_git_root()?;
    let config = project::detect_project()
        .ok_or_else(|| anyhow!("No project configuration found. Run `aid project init` first."))?;

    if let Some(cost) = config.budget.cost_limit_usd {
        let window = config.budget.window.as_deref();
        aid_config::upsert_budget(&config.id, cost, window)?;
        println!("Budget synced to ~/.aid/config.toml");
    }

    crate::claudemd::sync_claude_md(&git_root, &config)?;
    println!("CLAUDE.md updated with aid section");

    Ok(())
}
fn show() -> Result<()> {
    let config = project::detect_project().ok_or_else(|| {
        anyhow!("No project configuration found. Run `aid project init` in a git repository.")
    })?;
    let git_root = current_git_root()?;
    println!("Project: {}", config.id);
    println!("  Profile:    {}", config.profile.as_deref().unwrap_or("-"));
    println!("  Team:       {}", config.team.as_deref().unwrap_or("-"));
    println!("  Language:   {}", config.language.as_deref().unwrap_or("-"));
    println!("  Verify:     {}", config.verify.as_deref().unwrap_or("-"));
    println!("  Container:  {}", config.container.as_deref().unwrap_or("-"));
    let gitbutler_display = config
        .gitbutler
        .as_deref()
        .map(|_| config.gitbutler_mode().as_str())
        .unwrap_or("-");
    println!("  GitButler:  {}", gitbutler_display);
    let budget_display = if let Some(shorthand) = config.budget.budget_shorthand() {
        format!("{shorthand} (shorthand)")
    } else if let Some(cost) = config.budget.cost_limit_usd {
        let window = config.budget.window.as_deref().unwrap_or("unlimited");
        format!("${cost:.2}/{window}")
    } else {
        "-".to_string()
    };
    println!("  Budget:     {}", budget_display);
    match aid_config::effective_budget(&config.id) {
        Ok(Some((cost, window))) => {
            let window_str = window.as_deref().unwrap_or("unlimited");
            println!(
                "  Effective:  ${cost:.2}/{window_str} (synced to ~/.aid/config.toml)"
            );
        }
        Ok(None) => {
            println!("  Effective:  (not configured in ~/.aid/config.toml)");
        }
        Err(_) => {}
    }
    if config.rules.is_empty() {
        println!("  Rules:      (none)");
    } else {
        println!("  Rules:      {} rule(s)", config.rules.len());
        for rule in &config.rules {
            println!("    - {rule}");
        }
    }
    let knowledge_entries = project::read_project_knowledge(&git_root);
    let knowledge_index = project::project_knowledge_dir(&git_root).join("KNOWLEDGE.md");
    println!("  Knowledge:  {} entries", knowledge_entries.len());
    println!("    Index: {}", knowledge_index.display());
    Ok(())
}
fn state() -> Result<()> {
    state_command::run()
}
fn write_project_config(
    git_root: &Path,
    project_id: &str,
    profile: &str,
    language: Option<&str>,
    budget: Option<&str>,
    team: Option<&str>,
    verify: Option<&str>,
    gitbutler: Option<&str>,
) -> Result<(PathBuf, PathBuf)> {
    let aid_dir = git_root.join(".aid");
    let project_path = aid_dir.join("project.toml");
    fs::create_dir_all(&aid_dir)
        .with_context(|| format!("Failed to create {}", aid_dir.display()))?;
    let batches_dir = aid_dir.join("batches");
    if !batches_dir.exists() {
        std::fs::create_dir_all(&batches_dir)?;
        aid_info!("[aid] Created .aid/batches/ for batch TOML files");
    }
    if project_path.exists() {
        bail!("Project config already exists at {}", project_path.display());
    }
    let mut lines = vec![
        "[project]".to_string(),
        format!("id = \"{}\"", project_id),
        format!("profile = \"{}\"", profile),
    ];
    if let Some(lang) = language && !lang.trim().is_empty() {
        lines.push(format!("language = \"{}\"", lang.trim()));
    }
    if let Some(value) = budget && !value.trim().is_empty() {
        lines.push(format!("budget = \"{}\"", value.trim()));
    }
    if let Some(value) = team && !value.trim().is_empty() {
        lines.push(format!("team = \"{}\"", value.trim()));
    }
    if let Some(value) = verify && !value.trim().is_empty() {
        lines.push(format!("verify = \"{}\"", value.trim()));
    }
    if let Some(value) = gitbutler && !value.trim().is_empty() {
        lines.push(format!("gitbutler = \"{}\"", value.trim()));
    }
    lines.push(String::new());
    fs::write(&project_path, lines.join("\n"))?;
    let knowledge_dir = project::project_knowledge_dir(git_root);
    fs::create_dir_all(&knowledge_dir)
        .with_context(|| format!("Failed to create {}", knowledge_dir.display()))?;
    let knowledge_index = knowledge_dir.join("KNOWLEDGE.md");
    if !knowledge_index.exists() {
        fs::write(
            &knowledge_index,
            format!(
                "# {project_id} — Project Knowledge\n\n<!-- Add knowledge entries as: - [topic](knowledge/file.md) — description -->\n",
            ),
        )?;
    }
    Ok((project_path, knowledge_index))
}
fn prompt_project_id(git_root: &Path) -> Result<String> {
    let default = git_root
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("project");
    prompt_line("Project ID", Some(default), false)
}
fn prompt_profile(label: &str, default: &str) -> Result<String> {
    loop {
        let value = prompt_line(label, Some(default), false)?;
        let normalized = value.to_lowercase();
        match normalized.as_str() {
            "hobby" | "standard" | "production" => return Ok(normalized),
            _ => aid_error!("Allowed profiles: hobby, standard, production."),
        }
    }
}
fn prompt_language(default: Option<&str>) -> Result<Option<String>> {
    let entry = prompt_line("Language", default, true)?;
    if entry.trim().is_empty() {
        Ok(None)
    } else {
        Ok(Some(entry.trim().to_string()))
    }
}

fn prompt_daily_budget(default_cost: f64) -> Result<(String, f64, Option<String>)> {
    let default_label = format_budget_default_label(default_cost);
    loop {
        let entry = prompt_line("Daily budget", Some(&default_label), false)?;
        match normalize_budget_input(&entry, "day") {
            Ok(parsed) => return Ok(parsed),
            Err(err) => aid_error!("Invalid budget: {err}"),
        }
    }
}

fn default_budget_for_profile(profile: &str) -> f64 {
    match profile {
        "hobby" => 5.0,
        "standard" => 20.0,
        "production" => 50.0,
        _ => 20.0,
    }
}

fn format_budget_default_label(cost: f64) -> String {
    let amount = if (cost - cost.trunc()).abs() < f64::EPSILON {
        format!("{:.0}", cost)
    } else {
        format!("{cost}")
    };
    format!("${amount}")
}

fn normalize_budget_input(value: &str, default_window: &str) -> Result<(String, f64, Option<String>)> {
    let mut sanitized = value.trim().to_string();
    if sanitized.is_empty() {
        bail!("Budget cannot be empty");
    }
    if !sanitized.starts_with('$') {
        sanitized.insert(0, '$');
    }
    if !sanitized.contains('/') {
        sanitized.push('/');
        sanitized.push_str(default_window);
    }
    let (cost, window) = parse_budget_value(&sanitized)?;
    Ok((sanitized, cost, window))
}

fn parse_budget_value(value: &str) -> Result<(f64, Option<String>)> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        bail!("budget shorthand is empty");
    }
    let amount_window = trimmed.strip_prefix('$').unwrap_or(trimmed).trim();
    if amount_window.is_empty() {
        bail!("budget amount is missing");
    }
    let (amount_part, window_part) = match amount_window.split_once('/') {
        Some((left, right)) => (left.trim(), Some(right.trim())),
        None => (amount_window, None),
    };
    if amount_part.is_empty() {
        bail!("budget amount is missing");
    }
    let cost_limit = amount_part
        .parse::<f64>()
        .map_err(|_| anyhow!("invalid budget amount '{amount_part}'"))?;
    let window = match window_part {
        Some(part) if !part.is_empty() => {
            match part.to_lowercase().as_str() {
                "day" | "daily" => Some("daily".to_string()),
                "month" | "monthly" => Some("monthly".to_string()),
                other => bail!("unsupported budget window '{other}'"),
            }
        }
        Some(_) => bail!("budget window is empty"),
        None => None,
    };
    Ok((cost_limit, window))
}

fn default_verify_for_language(language: Option<&str>) -> &'static str {
    match language {
        Some(lang) => {
            let lower = lang.to_ascii_lowercase();
            match lower.as_str() {
                "typescript" | "javascript" | "node" => "npm test",
                _ => "cargo test",
            }
        }
        None => "cargo test",
    }
}

fn detect_gitbutler_mode() -> Result<Option<&'static str>> {
    if crate::gitbutler::but_available() {
        if prompt_confirm("Enable GitButler auto-commit/oplog? [Y/n]", true)? {
            return Ok(Some("auto"));
        }
        return Ok(None);
    }

    println!(
        "  GitButler not found. Install: https://gitbutler.com (CLI provides auto-commit + per-task lanes). Re-run aid project init after install."
    );
    Ok(None)
}

fn prompt_confirm(label: &str, default_yes: bool) -> Result<bool> {
    loop {
        print!("{label}: ");
        io::stdout().flush()?;
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        match input.trim().to_ascii_lowercase().as_str() {
            "" => return Ok(default_yes),
            "y" | "yes" => return Ok(true),
            "n" | "no" => return Ok(false),
            _ => aid_error!("Please answer yes or no."),
        }
    }
}
fn prompt_line(label: &str, default: Option<&str>, allow_empty: bool) -> Result<String> {
    loop {
        match default {
            Some(value) => print!("{label} [{value}]: "),
            None => print!("{label}: "),
        }
        io::stdout().flush()?;
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        let trimmed = input.trim().to_string();
        if !trimmed.is_empty() {
            return Ok(trimmed);
        }
        if let Some(value) = default {
            return Ok(value.to_string());
        }
        if allow_empty {
            return Ok(String::new());
        }
        aid_error!("{} cannot be empty.", label);
    }
}
fn detect_language(git_root: &Path) -> Option<String> {
    let cargo = git_root.join("Cargo.toml");
    if cargo.is_file() {
        return Some("rust".to_string());
    }
    let package = git_root.join("package.json");
    if package.is_file() {
        if package_json_has_typescript(&package) {
            return Some("typescript".to_string());
        }
        return Some("javascript".to_string());
    }
    None
}

fn package_json_has_typescript(path: &Path) -> bool {
    let raw = match fs::read_to_string(path) {
        Ok(text) => text,
        Err(_) => return false,
    };
    let parsed: Value = match serde_json::from_str(&raw) {
        Ok(value) => value,
        Err(_) => return false,
    };
    ["dependencies", "devDependencies", "peerDependencies"].iter().any(|key| {
        parsed
            .get(*key)
            .and_then(|deps| deps.as_object())
            .is_some_and(|deps| deps.contains_key("typescript"))
    })
}
fn current_git_root() -> Result<PathBuf> {
    let output = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .context("Failed to run `git rev-parse --show-toplevel`")?;
    if !output.status.success() {
        bail!("Not inside a git repository");
    }
    let root = String::from_utf8(output.stdout)
        .context("Failed to read git root from git output")?
        .trim()
        .to_string();
    if root.is_empty() {
        bail!("Git root path is empty");
    }
    Ok(PathBuf::from(root))
}