hematite-cli 0.5.4

Local AI coding harness for LM Studio with TUI, voice, retrieval, and grounded workstation tooling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
use crate::agent::config;
use crate::agent::inference::InferenceEvent;
use serde_json::Value;
use tokio::sync::mpsc;

const BUILD_TIMEOUT_SECS: u64 = 120;

/// Streaming variant — emits live shell lines to the SPECULAR panel while buffering
/// the final combined output for the tool result returned to the model.
pub async fn execute_streaming(
    args: &Value,
    tx: mpsc::Sender<InferenceEvent>,
) -> Result<String, String> {
    let cwd =
        std::env::current_dir().map_err(|e| format!("Cannot determine working directory: {e}"))?;
    let action = args
        .get("action")
        .and_then(|v| v.as_str())
        .unwrap_or("build");
    let explicit_profile = args.get("profile").and_then(|v| v.as_str());
    let timeout_override = args.get("timeout_secs").and_then(|v| v.as_u64());

    let config = config::load_config();
    if let Some(profile_name) = explicit_profile {
        let profile = config.verify.profiles.get(profile_name).ok_or_else(|| {
            format!(
                "Unknown verify profile `{}`. Define it in `.hematite/settings.json` or omit the profile argument.",
                profile_name
            )
        })?;
        if let Some(command) = profile_command(profile, action) {
            let timeout_secs = timeout_override
                .or(profile.timeout_secs)
                .unwrap_or(BUILD_TIMEOUT_SECS);
            return run_profile_command_streaming(profile_name, action, command, timeout_secs, tx)
                .await;
        }

        return Err(format!(
            "VERIFY PROFILE MISSING [{profile_name}] action `{action}`.\n\
             Configure `.hematite/settings.json` with a `{action}` command for this profile, \
             or call `verify_build` with a different action/profile."
        ));
    }

    if let Some(default_profile) = config.verify.default_profile.as_deref() {
        let profile = config.verify.profiles.get(default_profile).ok_or_else(|| {
            format!(
                "Configured default verify profile `{}` was not found in `.hematite/settings.json`.",
                default_profile
            )
        })?;
        if let Some(command) = profile_command(profile, action) {
            let timeout_secs = timeout_override
                .or(profile.timeout_secs)
                .unwrap_or(BUILD_TIMEOUT_SECS);
            return run_profile_command_streaming(
                default_profile,
                action,
                command,
                timeout_secs,
                tx,
            )
            .await;
        }

        return Err(format!(
            "VERIFY PROFILE MISSING [{default_profile}] action `{action}`.\n\
             Configure `.hematite/settings.json` with a `{action}` command for the default profile, \
             or call `verify_build` with an explicit profile."
        ));
    }

    let (label, command, timeout_secs) = autodetect_command(&cwd, action, timeout_override)?;
    run_profile_command_streaming(label, action, &command, timeout_secs, tx).await
}

pub async fn execute(args: &Value) -> Result<String, String> {
    let cwd =
        std::env::current_dir().map_err(|e| format!("Cannot determine working directory: {e}"))?;
    let action = args
        .get("action")
        .and_then(|v| v.as_str())
        .unwrap_or("build");
    let explicit_profile = args.get("profile").and_then(|v| v.as_str());
    let timeout_override = args.get("timeout_secs").and_then(|v| v.as_u64());

    let config = config::load_config();
    if let Some(profile_name) = explicit_profile {
        let profile = config.verify.profiles.get(profile_name).ok_or_else(|| {
            format!(
                "Unknown verify profile `{}`. Define it in `.hematite/settings.json` or omit the profile argument.",
                profile_name
            )
        })?;
        if let Some(command) = profile_command(profile, action) {
            let timeout_secs = timeout_override
                .or(profile.timeout_secs)
                .unwrap_or(BUILD_TIMEOUT_SECS);
            return run_profile_command(profile_name, action, command, timeout_secs).await;
        }

        return Err(format!(
            "VERIFY PROFILE MISSING [{profile_name}] action `{action}`.\n\
             Configure `.hematite/settings.json` with a `{action}` command for this profile, \
             or call `verify_build` with a different action/profile."
        ));
    }

    if let Some(default_profile) = config.verify.default_profile.as_deref() {
        let profile = config.verify.profiles.get(default_profile).ok_or_else(|| {
            format!(
                "Configured default verify profile `{}` was not found in `.hematite/settings.json`.",
                default_profile
            )
        })?;
        if let Some(command) = profile_command(profile, action) {
            let timeout_secs = timeout_override
                .or(profile.timeout_secs)
                .unwrap_or(BUILD_TIMEOUT_SECS);
            return run_profile_command(default_profile, action, command, timeout_secs).await;
        }

        return Err(format!(
            "VERIFY PROFILE MISSING [{default_profile}] action `{action}`.\n\
             Configure `.hematite/settings.json` with a `{action}` command for the default profile, \
             or call `verify_build` with an explicit profile."
        ));
    }

    let (label, command, timeout_secs) = autodetect_command(&cwd, action, timeout_override)?;
    run_profile_command(label, action, &command, timeout_secs).await
}

fn profile_command<'a>(profile: &'a config::VerifyProfile, action: &str) -> Option<&'a str> {
    match action {
        "build" => profile.build.as_deref(),
        "test" => profile.test.as_deref(),
        "lint" => profile.lint.as_deref(),
        "fix" => profile.fix.as_deref(),
        _ => None,
    }
}

fn autodetect_command(
    cwd: &std::path::Path,
    action: &str,
    timeout_override: Option<u64>,
) -> Result<(&'static str, String, u64), String> {
    let timeout_secs = timeout_override.unwrap_or(BUILD_TIMEOUT_SECS);
    let command = if cwd.join("Cargo.toml").exists() {
        match action {
            "build" => ("Rust/Cargo", "cargo build --color never".to_string()),
            "test" => ("Rust/Cargo", "cargo test --color never".to_string()),
            "lint" => (
                "Rust/Cargo",
                "cargo clippy --all-targets --all-features -- -D warnings".to_string(),
            ),
            "fix" => ("Rust/Cargo", "cargo fmt".to_string()),
            _ => return Err(unknown_action(action)),
        }
    } else if cwd.join("package.json").exists() {
        match action {
            "build" => ("Node/npm", "npm run build --if-present".to_string()),
            "test" => ("Node/npm", "npm test --if-present".to_string()),
            "lint" => ("Node/npm", "npm run lint --if-present".to_string()),
            "fix" => return Err(missing_profile_msg("Node/npm", action)),
            _ => return Err(unknown_action(action)),
        }
    } else if cwd.join("pyproject.toml").exists() || cwd.join("setup.py").exists() {
        match action {
            "build" => ("Python", "python -m compileall .".to_string()),
            "test" => return Err(missing_profile_msg("Python", action)),
            "lint" => return Err(missing_profile_msg("Python", action)),
            "fix" => return Err(missing_profile_msg("Python", action)),
            _ => return Err(unknown_action(action)),
        }
    } else if cwd.join("go.mod").exists() {
        match action {
            "build" => ("Go", "go build ./...".to_string()),
            "test" => ("Go", "go test ./...".to_string()),
            "lint" => return Err(missing_profile_msg("Go", action)),
            "fix" => return Err(missing_profile_msg("Go", action)),
            _ => return Err(unknown_action(action)),
        }
    } else {
        return Err(
            "No recognized project root found.\n\
             Expected one of: Cargo.toml, package.json, pyproject.toml, go.mod\n\
             Ensure you are in the project root directory or configure `.hematite/settings.json` verify profiles."
                .into(),
        );
    };

    Ok((command.0, command.1, timeout_secs))
}

fn missing_profile_msg(stack: &str, action: &str) -> String {
    format!(
        "No auto-detected `{action}` command for [{stack}].\n\
         Add a verify profile in `.hematite/settings.json` if you want Hematite to run `{action}` for this project."
    )
}

fn unknown_action(action: &str) -> String {
    format!(
        "Unknown verify_build action `{}`. Use one of: build, test, lint, fix.",
        action
    )
}

async fn run_profile_command(
    profile_name: &str,
    action: &str,
    command: &str,
    timeout_secs: u64,
) -> Result<String, String> {
    let output = crate::tools::shell::execute(&serde_json::json!({
        "command": command,
        "timeout_secs": timeout_secs,
        "reason": format!("verify_build:{}:{}", profile_name, action),
    }))
    .await?;

    if output.contains("[exit code: 0]") || !output.contains("[exit code:") {
        Ok(format!(
            "BUILD OK [{}:{}]\ncommand: {}\n{}",
            profile_name,
            action,
            command,
            output.trim()
        ))
    } else if should_fallback_to_cargo_check(action, command, &output) {
        run_windows_self_hosted_check_fallback(profile_name, action, command, timeout_secs, &output)
            .await
    } else {
        Err(format!(
            "BUILD FAILED [{}:{}]\ncommand: {}\n{}",
            profile_name,
            action,
            command,
            output.trim()
        ))
    }
}

async fn run_profile_command_streaming(
    profile_name: &str,
    action: &str,
    command: &str,
    timeout_secs: u64,
    tx: mpsc::Sender<InferenceEvent>,
) -> Result<String, String> {
    let output = crate::tools::shell::execute_streaming(
        &serde_json::json!({
            "command": command,
            "timeout_secs": timeout_secs,
            "reason": format!("verify_build:{}:{}", profile_name, action),
        }),
        tx.clone(),
    )
    .await?;

    if output.contains("[exit code: 0]") || !output.contains("[exit code:") {
        Ok(format!(
            "BUILD OK [{}:{}]\ncommand: {}\n{}",
            profile_name,
            action,
            command,
            output.trim()
        ))
    } else if should_fallback_to_cargo_check(action, command, &output) {
        run_windows_self_hosted_check_fallback_streaming(
            profile_name,
            action,
            command,
            timeout_secs,
            &output,
            tx,
        )
        .await
    } else {
        Err(format!(
            "BUILD FAILED [{}:{}]\ncommand: {}\n{}",
            profile_name,
            action,
            command,
            output.trim()
        ))
    }
}

async fn run_windows_self_hosted_check_fallback_streaming(
    profile_name: &str,
    action: &str,
    original_command: &str,
    timeout_secs: u64,
    original_output: &str,
    tx: mpsc::Sender<InferenceEvent>,
) -> Result<String, String> {
    let fallback_command = "cargo check --color never";
    let fallback_output = crate::tools::shell::execute_streaming(
        &serde_json::json!({
            "command": fallback_command,
            "timeout_secs": timeout_secs,
            "reason": format!("verify_build:{}:{}:self_hosted_windows_fallback", profile_name, action),
        }),
        tx,
    )
    .await?;

    if fallback_output.contains("[exit code: 0]") || !fallback_output.contains("[exit code:") {
        Ok(format!(
            "BUILD OK [{}:{}]\ncommand: {}\n\
             Windows self-hosted note: `cargo build` could not replace the running `target\\\\debug\\\\hematite.exe`, so Hematite fell back to `cargo check` to verify code health without deleting the live binary.\n\
             original build output:\n{}\n\
             fallback command: {}\n{}",
            profile_name,
            action,
            original_command,
            original_output.trim(),
            fallback_command,
            fallback_output.trim()
        ))
    } else {
        Err(format!(
            "BUILD FAILED [{}:{}]\ncommand: {}\n\
             Windows self-hosted note: `cargo build` could not replace the running `target\\\\debug\\\\hematite.exe`, and the fallback `cargo check` also failed.\n\
             original build output:\n{}\n\
             fallback command: {}\n{}",
            profile_name,
            action,
            original_command,
            original_output.trim(),
            fallback_command,
            fallback_output.trim()
        ))
    }
}

fn should_fallback_to_cargo_check(action: &str, command: &str, output: &str) -> bool {
    if action != "build" || command.trim() != "cargo build --color never" {
        return false;
    }

    if cfg!(windows) {
        looks_like_windows_self_hosted_build_lock(output)
    } else {
        false
    }
}

fn looks_like_windows_self_hosted_build_lock(output: &str) -> bool {
    let lower = output.to_ascii_lowercase();
    lower.contains("failed to remove file")
        && lower.contains("target\\debug\\hematite.exe")
        && (lower.contains("access is denied")
            || lower.contains("being used by another process")
            || lower.contains("permission denied"))
}

async fn run_windows_self_hosted_check_fallback(
    profile_name: &str,
    action: &str,
    original_command: &str,
    timeout_secs: u64,
    original_output: &str,
) -> Result<String, String> {
    let fallback_command = "cargo check --color never";
    let fallback_output = crate::tools::shell::execute(&serde_json::json!({
        "command": fallback_command,
        "timeout_secs": timeout_secs,
        "reason": format!("verify_build:{}:{}:self_hosted_windows_fallback", profile_name, action),
    }))
    .await?;

    if fallback_output.contains("[exit code: 0]") || !fallback_output.contains("[exit code:") {
        Ok(format!(
            "BUILD OK [{}:{}]\ncommand: {}\n\
             Windows self-hosted note: `cargo build` could not replace the running `target\\\\debug\\\\hematite.exe`, so Hematite fell back to `cargo check` to verify code health without deleting the live binary.\n\
             original build output:\n{}\n\
             fallback command: {}\n{}",
            profile_name,
            action,
            original_command,
            original_output.trim(),
            fallback_command,
            fallback_output.trim()
        ))
    } else {
        Err(format!(
            "BUILD FAILED [{}:{}]\ncommand: {}\n\
             Windows self-hosted note: `cargo build` could not replace the running `target\\\\debug\\\\hematite.exe`, and the fallback `cargo check` also failed.\n\
             original build output:\n{}\n\
             fallback command: {}\n{}",
            profile_name,
            action,
            original_command,
            original_output.trim(),
            fallback_command,
            fallback_output.trim()
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_windows_self_hosted_build_lock_pattern() {
        let sample = "[stderr] error: failed to remove file `C:\\Users\\ocean\\AntigravityProjects\\Hematite-CLI\\target\\debug\\hematite.exe`\r\nAccess is denied. (os error 5)";
        assert!(looks_like_windows_self_hosted_build_lock(sample));
    }

    #[test]
    fn ignores_unrelated_build_failures() {
        let sample = "[stderr] error[E0425]: cannot find value `foo` in this scope";
        assert!(!looks_like_windows_self_hosted_build_lock(sample));
        assert!(!should_fallback_to_cargo_check(
            "build",
            "cargo build --color never",
            sample
        ));
    }
}