Skip to content

Commit 7a15da8

Browse files
committed
feat(aft): add aft_check command for on-demand type checker validation
Adds a new aft_check tool that runs the configured type checker (ruff, tsc, pyright, etc.) on a single file and returns validation errors. Intended for use after completing a batch of edits, not after every intermediate edit. Changes: - commands/check.rs: new command handler calling validate_full - subc_translate.rs: translate_check maps filePath to file - subc_format.rs: format_check_response renders check results - config.rs + config_resolve.rs: CheckConfig with check.enabled (default false); tool is only registered when enabled and checker config is non-empty - opencode-plugin: tool definition, config schema, registration
1 parent ae446bc commit 7a15da8

11 files changed

Lines changed: 296 additions & 2 deletions

File tree

crates/aft/src/commands/check.rs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
//! Handler for the `check` command: on-demand type checker validation.
2+
3+
use std::path::Path;
4+
5+
use crate::context::AppContext;
6+
use crate::format;
7+
use crate::protocol::{RawRequest, Response};
8+
9+
/// Handle a `check` request.
10+
///
11+
/// Params:
12+
/// - `file` (string, required) - absolute path to the file to check
13+
///
14+
/// Returns: `{ file, error_count, errors?, skipped_reason? }`
15+
pub fn handle_check(req: &RawRequest, ctx: &AppContext) -> Response {
16+
let config = ctx.config();
17+
18+
if !config.check.enabled {
19+
return Response::error(
20+
&req.id,
21+
"invalid_request",
22+
"check: tool is disabled (set check.enabled=true in config)",
23+
);
24+
}
25+
26+
let file = match req.params.get("file").and_then(|v| v.as_str()) {
27+
Some(f) => f,
28+
None => {
29+
return Response::error(
30+
&req.id,
31+
"invalid_request",
32+
"check: missing required param 'file'",
33+
);
34+
}
35+
};
36+
37+
let path = match ctx.validate_path(&req.id, Path::new(file)) {
38+
Ok(p) => p,
39+
Err(resp) => return resp,
40+
};
41+
42+
if !path.is_file() {
43+
return Response::error(
44+
&req.id,
45+
"invalid_request",
46+
format!("check: path must be a file: {}", path.display()),
47+
);
48+
}
49+
50+
let (errors, skip_reason) = format::validate_full(&path, &config);
51+
52+
let mut result = serde_json::json!({
53+
"file": file,
54+
"error_count": errors.len(),
55+
});
56+
57+
if !errors.is_empty() {
58+
result["errors"] = serde_json::json!(errors);
59+
}
60+
if let Some(reason) = skip_reason {
61+
result["skipped_reason"] = serde_json::json!(reason);
62+
}
63+
64+
Response::success(&req.id, result)
65+
}

crates/aft/src/commands/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ pub mod batch;
1717
pub mod call_tree;
1818
pub mod callers;
1919
pub mod callgraph_store_adapter;
20+
pub mod check;
2021
pub mod checkpoint;
2122
pub mod configure;
2223
pub mod conflicts;

crates/aft/src/config.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,12 @@ pub struct InspectConfig {
9999
pub duplicates: InspectDuplicatesConfig,
100100
}
101101

102+
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
103+
#[serde(default)]
104+
pub struct CheckConfig {
105+
pub enabled: bool,
106+
}
107+
102108
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
103109
#[serde(default)]
104110
pub struct InspectDuplicatesConfig {
@@ -206,6 +212,7 @@ pub struct Config {
206212
pub search_index_max_file_size: u64,
207213
pub semantic: SemanticBackendConfig,
208214
pub inspect: InspectConfig,
215+
pub check: CheckConfig,
209216
pub backup: BackupConfig,
210217
/// Enable Astral ty as an experimental Python LSP server (default: false).
211218
pub experimental_lsp_ty: bool,
@@ -288,6 +295,7 @@ impl Default for Config {
288295
search_index_max_file_size: 1_048_576,
289296
semantic: SemanticBackendConfig::default(),
290297
inspect: InspectConfig::default(),
298+
check: CheckConfig::default(),
291299
backup: BackupConfig::default(),
292300
experimental_lsp_ty: false,
293301
lsp_servers: Vec::new(),

crates/aft/src/config_resolve.rs

Lines changed: 66 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ use serde::{Deserialize, Deserializer};
1212
use serde_json::{Map, Value};
1313

1414
use crate::config::{
15-
BackupConfig, Config, InspectConfig, SemanticBackend, SemanticBackendConfig, UserServerDef,
16-
MAX_SEMANTIC_QUERY_TIMEOUT_MS, MIN_SEMANTIC_QUERY_TIMEOUT_MS,
15+
BackupConfig, CheckConfig, Config, InspectConfig, SemanticBackend, SemanticBackendConfig,
16+
UserServerDef, MAX_SEMANTIC_QUERY_TIMEOUT_MS, MIN_SEMANTIC_QUERY_TIMEOUT_MS,
1717
};
1818
use crate::jsonc::strip_jsonc;
1919

@@ -91,6 +91,7 @@ pub struct RawAftConfig {
9191
#[serde(deserialize_with = "deserialize_opt_usize")]
9292
pub callgraph_chunk_size: Option<usize>,
9393
pub inspect: Option<RawInspect>,
94+
pub check: Option<RawCheck>,
9495
pub backup: Option<RawBackup>,
9596
pub bash: Option<RawBash>,
9697
pub experimental: Option<RawExperimental>,
@@ -368,6 +369,18 @@ impl RawInspect {
368369
}
369370
}
370371

372+
#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
373+
#[serde(default)]
374+
pub struct RawCheck {
375+
pub enabled: Option<bool>,
376+
}
377+
378+
impl RawCheck {
379+
fn is_empty(&self) -> bool {
380+
self.enabled.is_none()
381+
}
382+
}
383+
371384
/// Only `expected_mirrors` survives here: `lower_bound`, `discard_cost`, and
372385
/// `anonymize` were accepted-but-never-read knobs (the scanner hardcodes its
373386
/// cost bounds and anonymization rules), so they were removed from the schema
@@ -573,6 +586,9 @@ fn merge_trusted_config(base: &mut RawAftConfig, override_config: RawAftConfig)
573586
if override_config.inspect.is_some() {
574587
base.inspect = override_config.inspect;
575588
}
589+
if override_config.check.is_some() {
590+
base.check = override_config.check;
591+
}
576592
if override_config.backup.is_some() {
577593
base.backup = override_config.backup;
578594
}
@@ -640,6 +656,7 @@ fn merge_project_config(base: &mut RawAftConfig, project: RawAftConfig) {
640656
base.experimental = merge_experimental_config(base.experimental.clone(), project.experimental);
641657
base.bash = merge_bash_config(base.bash.clone(), project.bash);
642658
base.inspect = merge_inspect_config(base.inspect.clone(), project.inspect);
659+
base.check = merge_check_config(base.check.clone(), project.check);
643660
}
644661

645662
fn merge_formatter_map(
@@ -855,6 +872,18 @@ fn merge_inspect_config(
855872
(!inspect.is_empty()).then_some(inspect)
856873
}
857874

875+
fn merge_check_config(
876+
base: Option<RawCheck>,
877+
override_check: Option<RawCheck>,
878+
) -> Option<RawCheck> {
879+
let Some(override_check) = override_check else {
880+
return base;
881+
};
882+
let mut check = base.unwrap_or_default();
883+
check.enabled = override_check.enabled.or(check.enabled);
884+
(!check.is_empty()).then_some(check)
885+
}
886+
858887
fn merge_inspect_duplicates(
859888
base: Option<RawInspectDuplicates>,
860889
override_duplicates: Option<RawInspectDuplicates>,
@@ -998,6 +1027,7 @@ fn apply_resolved_config(raw: &RawAftConfig, config: &mut Config) {
9981027
}
9991028
config.semantic = resolve_semantic_config(raw.semantic.as_ref());
10001029
config.inspect = resolve_inspect_config(raw.inspect.as_ref());
1030+
config.check = resolve_check_config(raw.check.as_ref());
10011031
config.backup = resolve_backup_config(raw.backup.as_ref());
10021032
resolve_lsp_config(raw, config);
10031033
resolve_bash_fields(raw, config);
@@ -1056,6 +1086,16 @@ fn resolve_inspect_config(raw: Option<&RawInspect>) -> InspectConfig {
10561086
inspect
10571087
}
10581088

1089+
fn resolve_check_config(raw: Option<&RawCheck>) -> CheckConfig {
1090+
let mut check = CheckConfig::default();
1091+
if let Some(raw) = raw {
1092+
if let Some(enabled) = raw.enabled {
1093+
check.enabled = enabled;
1094+
}
1095+
}
1096+
check
1097+
}
1098+
10591099
fn resolve_backup_config(raw: Option<&RawBackup>) -> BackupConfig {
10601100
let mut backup = BackupConfig::default();
10611101
if let Some(raw) = raw {
@@ -2033,4 +2073,28 @@ mod tests {
20332073
Some("rustfmt")
20342074
);
20352075
}
2076+
2077+
#[test]
2078+
fn check_config_defaults_to_disabled() {
2079+
let result = resolve_config(&[tier("user", r#"{ "tool_surface": "all" }"#)]);
2080+
assert!(!result.config.check.enabled);
2081+
}
2082+
2083+
#[test]
2084+
fn check_config_enabled_via_user_tier() {
2085+
let result = resolve_config(&[tier(
2086+
"user",
2087+
r#"{ "check": { "enabled": true } }"#,
2088+
)]);
2089+
assert!(result.config.check.enabled);
2090+
}
2091+
2092+
#[test]
2093+
fn check_config_project_tier_overrides_user() {
2094+
let result = resolve_config(&[
2095+
tier("user", r#"{ "check": { "enabled": true } }"#),
2096+
tier("project", r#"{ "check": { "enabled": false } }"#),
2097+
]);
2098+
assert!(!result.config.check.enabled);
2099+
}
20362100
}

crates/aft/src/main.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,7 @@ fn dispatch(req: RawRequest, ctx: &AppContext) -> Response {
703703
"inline_symbol" => aft::commands::inline_symbol::handle_inline_symbol(&req, ctx),
704704
"inspect" => aft::commands::inspect::handle_inspect(&req, ctx),
705705
"inspect_tier2_run" => aft::commands::inspect::handle_inspect_tier2_run(&req, ctx),
706+
"check" => aft::commands::check::handle_check(&req, ctx),
706707
"git_conflicts" => aft::commands::conflicts::handle_git_conflicts(ctx, &req),
707708
"ast_search" => aft::commands::ast_search::handle_ast_search(&req, ctx),
708709
"ast_replace" => aft::commands::ast_replace::handle_ast_replace(&req, ctx),

crates/aft/src/subc_format.rs

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ fn is_core_agent_tool(bare_name: &str) -> bool {
257257
| "import"
258258
| "refactor"
259259
| "safety"
260+
| "check"
260261
)
261262
}
262263

@@ -314,6 +315,7 @@ pub fn format_response_with_context(
314315
"import" => format_import(data, ctx),
315316
"refactor" => format_refactor(data, ctx),
316317
"safety" => format_safety(data, ctx),
318+
"check" => format_check_response(data),
317319
_ => unreachable!("core agent tools are exhaustive"),
318320
}
319321
}
@@ -913,6 +915,47 @@ fn format_edit_response(data: &Value) -> String {
913915
result
914916
}
915917

918+
fn format_check_response(data: &Value) -> String {
919+
let file = data
920+
.get("file")
921+
.and_then(Value::as_str)
922+
.unwrap_or("(unknown)");
923+
let count = data
924+
.get("error_count")
925+
.and_then(Value::as_u64)
926+
.unwrap_or(0) as usize;
927+
928+
if let Some(reason) = data.get("skipped_reason").and_then(Value::as_str) {
929+
return format!("Checked {file} - validation skipped ({reason}).");
930+
}
931+
932+
if count == 0 {
933+
return format!("Checked {file} - no errors found.");
934+
}
935+
936+
let mut output = format!("Checked {file} - {count} error(s):\n");
937+
if let Some(errors) = data.get("errors").and_then(Value::as_array) {
938+
let lines = errors
939+
.iter()
940+
.map(|e| {
941+
let line = e
942+
.get("line")
943+
.and_then(Value::as_u64)
944+
.map(|n| n.to_string())
945+
.unwrap_or_else(|| "undefined".to_string());
946+
let message = e
947+
.get("message")
948+
.and_then(Value::as_str)
949+
.unwrap_or("undefined");
950+
format!(" Line {line}: {message}")
951+
})
952+
.collect::<Vec<_>>()
953+
.join("\n");
954+
output.push_str(&lines);
955+
}
956+
output
957+
}
958+
916959
fn format_glob_skip_reasons_note(reasons: Option<&Value>) -> Option<String> {
917960
let actionable = reasons?
918961
.as_array()?
@@ -2776,3 +2819,53 @@ mod status_memory_tests {
27762819
assert!(!rendered.contains("\"memory\""));
27772820
}
27782821
}
2822+
2823+
#[cfg(test)]
2824+
mod tests {
2825+
use super::*;
2826+
use serde_json::json;
2827+
2828+
fn temp_file(name: &str) -> String {
2829+
let dir = tempfile::tempdir().expect("tempdir");
2830+
dir.path().join(name).to_string_lossy().into_owned()
2831+
}
2832+
2833+
#[test]
2834+
fn format_check_response_with_errors() {
2835+
let file = temp_file("check_test.py");
2836+
let data = json!({
2837+
"file": file,
2838+
"error_count": 2,
2839+
"errors": [
2840+
{ "line": 1, "message": "F401: `os` imported but unused" },
2841+
{ "line": 2, "message": "F401: `sys` imported but unused" }
2842+
]
2843+
});
2844+
let text = format_check_response(&data);
2845+
assert!(text.contains("check_test.py"));
2846+
assert!(text.contains("2 error(s)"));
2847+
assert!(text.contains("Line 1: F401"));
2848+
assert!(text.contains("Line 2: F401"));
2849+
}
2850+
2851+
#[test]
2852+
fn format_check_response_no_errors() {
2853+
let file = temp_file("check_test.py");
2854+
let data = json!({ "file": file, "error_count": 0 });
2855+
let text = format_check_response(&data);
2856+
assert!(text.contains("no errors found"));
2857+
}
2858+
2859+
#[test]
2860+
fn format_check_response_skipped() {
2861+
let file = temp_file("check_test.py");
2862+
let data = json!({
2863+
"file": file,
2864+
"error_count": 0,
2865+
"skipped_reason": "no_checker_configured"
2866+
});
2867+
let text = format_check_response(&data);
2868+
assert!(text.contains("validation skipped"));
2869+
assert!(text.contains("no_checker_configured"));
2870+
}
2871+
}

crates/aft/src/subc_translate.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ pub fn subc_translate_with_context(
195195
"outline" => translate_outline(agent_args, project_root),
196196
"zoom" => translate_zoom(agent_args, project_root),
197197
"inspect" => translate_inspect(agent_args, project_root),
198+
"check" => translate_check(agent_args, project_root),
198199
"callgraph" => translate_callgraph(agent_args, project_root),
199200
"conflicts" => translate_conflicts(agent_args),
200201
"ast_search" => translate_ast_search(agent_args),
@@ -1585,3 +1586,20 @@ fn translate_inspect(args: &Value, project_root: &Path) -> Result<Translated, Tr
15851586
args: out,
15861587
})
15871588
}
1589+
1590+
fn translate_check(args: &Value, project_root: &Path) -> Result<Translated, TranslateError> {
1591+
let map_in = agent_args_map(args);
1592+
let file_path = map_in
1593+
.get("filePath")
1594+
.and_then(Value::as_str)
1595+
.filter(|s| !s.is_empty())
1596+
.ok_or_else(|| invalid_request("'filePath' is required"))?;
1597+
1598+
let mut out = Map::new();
1599+
insert_resolved_file(&mut out, project_root, file_path);
1600+
1601+
Ok(Translated {
1602+
command: "check".into(),
1603+
args: out,
1604+
})
1605+
}

0 commit comments

Comments
 (0)