Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / structured.rs

structured.rs1083 lines · 43.3 KiBRaw
1//! Structured tool layer: validated, purpose-built tools over the runner.
2//!
3//! These tools replace free-form shell for the common operations (builds,
4//! unit tests, `./check`, git history, file finding, GitHub). Every tool
5//! validates its arguments in pure Rust (accept/reject tables are unit-tested
6//! below), builds a command from the validated parts, runs it through the
7//! existing runner proto routes, and renders the result for the model with
8//! the shared [`crate::parsers`] / [`crate::github`] renderers.
9//!
10//! [`dispatch`] is called from the `other` fallback arm of the agent
11//! dispatch: `Some(text)` is a model-facing result, `None` means "not a
12//! structured tool" (the caller renders the unknown-tool error).
13//!
14//! Path-touching tools are scope-checked with
15//! [`crate::agent::check_scope`] exactly like `read_file`.
16//! [`dispatch`] also auto-loads per-directory `AGENTS.md` for the path a tool
17//! touches (via [`crate::rules::ensure_rules_for_path`]) and notes newly
18//! loaded files in the result.
19
20use crate::agent::{check_scope, exec_build_command, BuildOutcome, DriverCtx};
21use crate::github::{render_issue_for_model, render_search_for_model, IssueState};
22use crate::openrouter::{FunctionDef, ToolDef};
23use crate::parsers::{merge_test_summaries, parse_build_output, parse_junit_xml, render_build_for_model,
24 render_tests_for_model, TestSummary};
25
26// ---------------------------------------------------------------------------
27// tiny arg helpers
28// ---------------------------------------------------------------------------
29
30fn arg_str(args: &serde_json::Value, key: &str) -> Option<String> {
31 args.get(key).and_then(|v| v.as_str()).map(|s| s.to_string())
32}
33
34fn arg_u64(args: &serde_json::Value, key: &str) -> Option<u64> {
35 args.get(key).and_then(|v| v.as_u64())
36}
37
38// ---------------------------------------------------------------------------
39// shell quoting + path validation (pure, unit-tested)
40// ---------------------------------------------------------------------------
41
42/// POSIX single-quote a string for `bash -lc`. Safe for any input, including
43/// newlines and quotes: `'a'b` becomes `'a'"'"'b'`.
44pub fn shell_quote(s: &str) -> String {
45 let mut out = String::with_capacity(s.len() + 2);
46 out.push('\'');
47 for (i, part) in s.split('\'').enumerate() {
48 if i > 0 {
49 out.push_str("'\"'\"'");
50 }
51 out.push_str(part);
52 }
53 out.push('\'');
54 out
55}
56
57/// Reject absolute paths and `..` escapes (mirrors the runner client check).
58/// Scope confinement itself happens via [`check_scope`] at dispatch time.
59pub fn validate_rel_path(path: &str) -> Result<String, String> {
60 if path.is_empty() {
61 return Err("path must be non-empty".to_string());
62 }
63 if path.starts_with('/') {
64 return Err(format!("absolute paths are not allowed: {path:?}"));
65 }
66 for seg in path.split('/') {
67 if seg == ".." {
68 return Err(format!("`..` is not allowed in paths: {path:?}"));
69 }
70 if seg.is_empty() {
71 return Err(format!("empty path segment in {path:?}"));
72 }
73 }
74 Ok(path.to_string())
75}
76
77/// Validate a module dir (`games/logicgate`, also accepts `games:logicgate`)
78/// against the same allowlist as `tools.rs`. Returns the normalized `/` form.
79pub fn validate_module_dir(module: &str) -> Result<String, String> {
80 let m = module.trim().replace(':', "/");
81 if m.is_empty() {
82 return Err("module must be non-empty (e.g. `notes`, `games/logicgate`)".to_string());
83 }
84 if m.starts_with('/') {
85 return Err(format!("module must be repo-relative, not absolute: {module:?}"));
86 }
87 if !crate::tools::module_path_ok(&m.replace('/', ":")) {
88 return Err(format!(
89 "bad module {module:?}: segments must match [a-z0-9-]+ (e.g. `notes`, `games/logicgate`)"
90 ));
91 }
92 Ok(m)
93}
94
95/// Gradle path form of a validated module dir: `games/logicgate` →
96/// `:games:logicgate`.
97pub fn gradle_path(dir: &str) -> String {
98 format!(":{}", dir.replace('/', ":"))
99}
100
101// ---------------------------------------------------------------------------
102// build / run_tests / check command construction (pure, unit-tested)
103// ---------------------------------------------------------------------------
104
105/// Build the `./gradlew :<module>:<task> ... --console=plain` command from
106/// validated parts. Each task must pass the `tools.rs` allowlist (same as the
107/// legacy string form); the composed command is re-checked with
108/// [`crate::tools::validate_build_command`] as defense in depth.
109pub fn build_command(module: &str, tasks: &[String]) -> Result<String, String> {
110 let dir = validate_module_dir(module)?;
111 if tasks.is_empty() {
112 return Err("build needs at least one task (e.g. `lint`)".to_string());
113 }
114 if tasks.len() > 8 {
115 return Err(format!("at most 8 tasks per build call, got {}", tasks.len()));
116 }
117 for t in tasks {
118 if !crate::tools::build_task_ok(t) {
119 return Err(format!(
120 "task {t:?} is not allowed. {}",
121 crate::tools::build_help()
122 ));
123 }
124 }
125 let gp = gradle_path(&dir);
126 let targets: Vec<String> = tasks.iter().map(|t| format!("{gp}:{t}")).collect();
127 let cmd = format!("./gradlew {} --console=plain", targets.join(" "));
128 crate::tools::validate_build_command(&cmd)
129}
130
131/// Validate a `run_tests` variant (`Dev` in `testDevUnitTest`).
132/// `None`/empty selects the default `"Dev"`.
133pub fn validate_variant(variant: Option<&str>) -> Result<String, String> {
134 match variant.map(str::trim).filter(|v| !v.is_empty()) {
135 None => Ok("Dev".to_string()),
136 Some(v) => {
137 if v.len() <= 24 && v.chars().all(|c| c.is_ascii_alphabetic()) {
138 Ok(v.to_string())
139 } else {
140 Err(format!(
141 "bad variant {v:?}: expected 1-24 ASCII letters (e.g. `Dev`, `Debug`, `Release`)"
142 ))
143 }
144 }
145 }
146}
147
148/// Validate a `--tests` filter: Gradle test-filter chars only, no shell.
149pub fn validate_test_filter(filter: &str) -> Result<String, String> {
150 if filter.is_empty() {
151 return Err("filter must be non-empty when given".to_string());
152 }
153 if filter.len() > 200
154 || !filter
155 .chars()
156 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '*')
157 {
158 return Err(format!(
159 "bad filter {filter:?}: expected 1-200 chars of [A-Za-z0-9_.*] (e.g. `*.ExpressionTest`)"
160 ));
161 }
162 Ok(filter.to_string())
163}
164
165/// Build `./gradlew :<m>:test<Variant>UnitTest [--tests <filter>]
166/// --console=plain` from validated parts.
167///
168/// `--tests` is a structured-only flag on purpose: the legacy free-form
169/// `build` validator rejects it, so only this validated path can pass a
170/// filter to Gradle (the strict charset above plus [`shell_quote`] make
171/// injection impossible).
172pub fn run_tests_command(
173 module: &str,
174 variant: Option<&str>,
175 filter: Option<&str>,
176) -> Result<String, String> {
177 let dir = validate_module_dir(module)?;
178 let variant = validate_variant(variant)?;
179 let task = format!("test{variant}UnitTest");
180 if !crate::tools::test_unit_task_ok(&task) {
181 return Err(format!("internal: unexpected test task {task:?}"));
182 }
183 let mut cmd = format!("./gradlew {}:{task}", gradle_path(&dir));
184 if let Some(f) = filter {
185 let f = validate_test_filter(f.trim())?;
186 cmd.push_str(&format!(" --tests {}", shell_quote(&f)));
187 }
188 cmd.push_str(" --console=plain");
189 Ok(cmd)
190}
191
192/// Build `./check <module>` from a validated module dir.
193pub fn check_command(module: &str) -> Result<String, String> {
194 let dir = validate_module_dir(module)?;
195 let cmd = format!("./check {dir}");
196 crate::tools::validate_build_command(&cmd)
197}
198
199// ---------------------------------------------------------------------------
200// git command construction (pure, unit-tested)
201// ---------------------------------------------------------------------------
202
203/// `git_log{path?, n?}` → `git log --format=... --date=short -n N [-- path]`.
204/// `n` defaults to 20 and is capped at 50.
205pub fn git_log_command(path: Option<&str>, n: Option<u64>) -> Result<String, String> {
206 let n = n.unwrap_or(20);
207 if n == 0 || n > 50 {
208 return Err(format!("n must be 1-50, got {n}"));
209 }
210 let mut cmd = format!("git log --format='%h %ad %an %s' --date=short -n {n}");
211 if let Some(p) = path {
212 let p = validate_rel_path(p.trim())?;
213 cmd.push_str(&format!(" -- {}", shell_quote(&p)));
214 }
215 Ok(cmd)
216}
217
218/// Validate a `git_show` revision: 4-40 hex chars, `HEAD`, or `HEAD~<1-3 digits>`.
219pub fn validate_git_rev(rev: &str) -> Result<String, String> {
220 let r = rev.trim();
221 if r == "HEAD" {
222 return Ok(r.to_string());
223 }
224 if let Some(rest) = r.strip_prefix("HEAD~") {
225 if !rest.is_empty() && rest.len() <= 3 && rest.chars().all(|c| c.is_ascii_digit()) {
226 return Ok(r.to_string());
227 }
228 return Err(format!("bad revision {rev:?}: expected HEAD, HEAD~<n> (n <= 999), or 4-40 hex chars"));
229 }
230 if (4..=40).contains(&r.len()) && r.chars().all(|c| c.is_ascii_hexdigit()) {
231 return Ok(r.to_string());
232 }
233 Err(format!(
234 "bad revision {rev:?}: expected 4-40 hex chars, HEAD, or HEAD~<n>"
235 ))
236}
237
238/// `git_show{rev, path?}` → `git show <rev> [-- path]`.
239pub fn git_show_command(rev: &str, path: Option<&str>) -> Result<String, String> {
240 let rev = validate_git_rev(rev)?;
241 let mut cmd = format!("git show {}", shell_quote(&rev));
242 if let Some(p) = path {
243 let p = validate_rel_path(p.trim())?;
244 cmd.push_str(&format!(" -- {}", shell_quote(&p)));
245 }
246 Ok(cmd)
247}
248
249/// Validate a `git_blame` line range: 1-based, `start <= end`, at most 200 lines.
250pub fn validate_blame_range(start: u64, end: u64) -> Result<(u64, u64), String> {
251 if start == 0 || end == 0 {
252 return Err("blame lines are 1-based; start and end must be >= 1".to_string());
253 }
254 if start > end {
255 return Err(format!("blame start ({start}) is after end ({end})"));
256 }
257 if end - start + 1 > 200 {
258 return Err(format!(
259 "blame range is {} lines (max 200); narrow start/end",
260 end - start + 1
261 ));
262 }
263 Ok((start, end))
264}
265
266/// `git_blame{path, start, end}` → `git blame --porcelain -L s,e -- path`.
267/// The porcelain output is condensed by [`condense_blame_porcelain`].
268pub fn git_blame_command(path: &str, start: u64, end: u64) -> Result<String, String> {
269 let p = validate_rel_path(path.trim())?;
270 let (start, end) = validate_blame_range(start, end)?;
271 Ok(format!(
272 "git blame --porcelain -L {start},{end} -- {}",
273 shell_quote(&p)
274 ))
275}
276
277/// Convert a Unix timestamp to `YYYY-MM-DD` (civil-date algorithm; no date dep).
278pub fn unix_to_ymd(ts: i64) -> String {
279 let days = ts.div_euclid(86_400);
280 let z = days + 719_468;
281 let era = z.div_euclid(146_097);
282 let doe = z - era * 146_097;
283 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
284 let y = yoe + era * 400;
285 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
286 let mp = (5 * doy + 2) / 153;
287 let d = doy - (153 * mp + 2) / 5 + 1;
288 let m = if mp < 10 { mp + 3 } else { mp - 9 };
289 format!("{:04}-{:02}-{:02}", if m <= 2 { y + 1 } else { y }, m, d)
290}
291
292/// Condense `git blame --porcelain` to `shortsha author YYYY-MM-DD | line`
293/// lines. Malformed blocks degrade to `?` fields rather than failing.
294pub fn condense_blame_porcelain(out: &str) -> String {
295 let mut condensed = Vec::new();
296 let mut sha = "?".to_string();
297 let mut author = "?".to_string();
298 let mut date = "?".to_string();
299 for line in out.lines() {
300 if let Some(content) = line.strip_prefix('\t') {
301 let short: String = sha.chars().take(8).collect();
302 condensed.push(format!("{short} {author} {date} | {content}"));
303 } else if line.len() > 41
304 && line.as_bytes()[40] == b' '
305 && line[..40].chars().all(|c| c.is_ascii_hexdigit())
306 {
307 sha = line.split(' ').next().unwrap_or("?").to_string();
308 author = "?".to_string();
309 date = "?".to_string();
310 } else if let Some(a) = line.strip_prefix("author ") {
311 // (`author-time` / `author-mail` don't match: `author ` has the space.)
312 if !a.trim().is_empty() {
313 author = a.trim().to_string();
314 }
315 } else if let Some(t) = line.strip_prefix("author-time ") {
316 if let Ok(ts) = t.trim().parse::<i64>() {
317 date = unix_to_ymd(ts);
318 }
319 }
320 }
321 condensed.join("\n")
322}
323
324/// `find_files{glob, path?}` → `rg --files -g <glob> <root>`.
325pub fn find_files_command(glob: &str, root: &str) -> Result<String, String> {
326 let g = glob.trim();
327 if g.is_empty() {
328 return Err("glob must be non-empty (e.g. `*.kt`)".to_string());
329 }
330 if g.len() > 200 || g.chars().any(|c| c.is_control()) {
331 return Err(format!("bad glob {glob:?}: max 200 printable chars"));
332 }
333 let r = validate_rel_path(root.trim())?;
334 Ok(format!("rg --files -g {} {}", shell_quote(g), shell_quote(&r)))
335}
336
337/// Cap model-facing command output at `max` lines.
338fn cap_lines(s: &str, max: usize) -> String {
339 let mut count = 0;
340 let mut out = String::new();
341 for line in s.lines() {
342 count += 1;
343 if count > max {
344 out.push_str(&format!("…[output capped at {max} lines]"));
345 break;
346 }
347 out.push_str(line);
348 out.push('\n');
349 }
350 out
351}
352
353// ---------------------------------------------------------------------------
354// tool definitions (appended to `openrouter::tool_defs`)
355// ---------------------------------------------------------------------------
356
357fn params(props: serde_json::Value, required: &[&str]) -> serde_json::Value {
358 serde_json::json!({
359 "type": "object",
360 "properties": props,
361 "required": required,
362 "additionalProperties": false,
363 })
364}
365
366/// Structured tools. (`build` keeps its existing def in `openrouter.rs`,
367/// extended there with the `module` + `tasks` form.)
368pub fn tool_defs() -> Vec<ToolDef> {
369 vec![
370 ToolDef {
371 kind: "function",
372 function: FunctionDef {
373 name: "run_tests",
374 description: "Run module unit tests (`./gradlew :<module>:test<Variant>UnitTest [--tests <filter>]`) and return parsed JUnit counts plus failing test names. Prefer over run_shell.",
375 parameters: params(serde_json::json!({
376 "module": {"type": "string", "description": "Module dir, e.g. notes, games/logicgate"},
377 "filter": {"type": "string", "description": "Optional --tests filter, e.g. *.ExpressionTest"},
378 "variant": {"type": "string", "description": "Build variant, default Dev (testDevUnitTest)"},
379 }), &["module"]),
380 },
381 },
382 ToolDef {
383 kind: "function",
384 function: FunctionDef {
385 name: "check",
386 description: "Run `./check <module>` and return the parsed findings. Prefer over run_shell.",
387 parameters: params(serde_json::json!({
388 "module": {"type": "string", "description": "Module dir, e.g. notes, games/logicgate"},
389 }), &["module"]),
390 },
391 },
392 ToolDef {
393 kind: "function",
394 function: FunctionDef {
395 name: "git_log",
396 description: "Recent commit history (`git log --format='%h %ad %an %s' --date=short`). Read-only.",
397 parameters: params(serde_json::json!({
398 "path": {"type": "string", "description": "Optional repo-relative path to limit history to"},
399 "n": {"type": "integer", "description": "Max commits, 1-50 (default 20)"},
400 }), &[]),
401 },
402 },
403 ToolDef {
404 kind: "function",
405 function: FunctionDef {
406 name: "git_show",
407 description: "Show one commit, or a file at a revision. Read-only. rev is 4-40 hex chars, HEAD, or HEAD~N.",
408 parameters: params(serde_json::json!({
409 "rev": {"type": "string", "description": "Revision: 4-40 hex chars, HEAD, or HEAD~N"},
410 "path": {"type": "string", "description": "Optional repo-relative path"},
411 }), &["rev"]),
412 },
413 },
414 ToolDef {
415 kind: "function",
416 function: FunctionDef {
417 name: "git_blame",
418 description: "Blame lines start..end of a file (1-based, max 200 lines), condensed to `sha author date | line`. Read-only.",
419 parameters: params(serde_json::json!({
420 "path": {"type": "string", "description": "Repo-relative file path"},
421 "start": {"type": "integer", "description": "First line (1-based)"},
422 "end": {"type": "integer", "description": "Last line (inclusive, max start+199)"},
423 }), &["path", "start", "end"]),
424 },
425 },
426 ToolDef {
427 kind: "function",
428 function: FunctionDef {
429 name: "find_files",
430 description: "List files matching a glob (`rg --files -g <glob>`), capped at 200 lines, inside your scope. Prefer over broad list_dir/search.",
431 parameters: params(serde_json::json!({
432 "glob": {"type": "string", "description": "Glob, e.g. *.kt"},
433 "path": {"type": "string", "description": "Optional subdirectory (default: your module scope)"},
434 }), &["glob"]),
435 },
436 },
437 ToolDef {
438 kind: "function",
439 function: FunctionDef {
440 name: "github_search_issues",
441 description: "Search GitHub issues on the repo. Runs server-side; the sandbox never sees the token.",
442 parameters: params(serde_json::json!({
443 "query": {"type": "string", "description": "Free-text query (optional)"},
444 "labels": {"type": "array", "items": {"type": "string"}, "description": "Label filter (optional)"},
445 "state": {"type": "string", "description": "open, closed, or all (default open)"},
446 }), &[]),
447 },
448 },
449 ToolDef {
450 kind: "function",
451 function: FunctionDef {
452 name: "github_read_issue",
453 description: "Read one GitHub issue with its comments (capped). Runs server-side.",
454 parameters: params(serde_json::json!({
455 "number": {"type": "integer", "description": "Issue number"},
456 }), &["number"]),
457 },
458 },
459 ]
460}
461
462// ---------------------------------------------------------------------------
463// dispatch
464// ---------------------------------------------------------------------------
465
466/// Dispatch one structured tool call. `Some(text)` is the model-facing
467/// result; `None` means "not a structured tool".
468pub async fn dispatch(
469 ctx: &DriverCtx,
470 task_id: i64,
471 slot: u32,
472 task: &crate::models::Task,
473 name: &str,
474 args: &serde_json::Value,
475) -> Option<String> {
476 let scope = task.module_scope.clone();
477 let result = match name {
478 "build" => Some(dispatch_build(ctx, task_id, slot, args).await),
479 "run_tests" => Some(dispatch_run_tests(ctx, task_id, slot, args).await),
480 "check" => Some(dispatch_check(ctx, task_id, slot, args).await),
481 "git_log" => Some(dispatch_git_log(ctx, slot, &scope, args).await),
482 "git_show" => Some(dispatch_git_show(ctx, slot, &scope, args).await),
483 "git_blame" => Some(dispatch_git_blame(ctx, slot, &scope, args).await),
484 "find_files" => Some(dispatch_find_files(ctx, slot, &scope, args).await),
485 "github_search_issues" => Some(dispatch_github_search(ctx, args).await),
486 "github_read_issue" => Some(dispatch_github_read(ctx, args).await),
487 _ => None,
488 }?;
489 Some(match rules_path_for(name, args, &scope) {
490 Some(path) => with_rules_note(ctx, task_id, slot, &path, result).await,
491 None => result,
492 })
493}
494
495/// The repo path a structured tool touches, for AGENTS.md auto-load.
496fn rules_path_for(name: &str, args: &serde_json::Value, scope: &str) -> Option<String> {
497 let arg = |k: &str| arg_str(args, k).filter(|s| !s.trim().is_empty());
498 match name {
499 "build" | "run_tests" | "check" => arg("module"),
500 "git_log" | "git_show" | "git_blame" => arg("path"),
501 "find_files" => arg("path").or_else(|| Some(scope.replace(':', "/"))),
502 _ => None,
503 }
504}
505
506/// Load any not-yet-seen AGENTS.md on the way to `path` and note them in the
507/// tool result. Skipped for rejected calls (the path may be invalid).
508async fn with_rules_note(ctx: &DriverCtx, task_id: i64, slot: u32, path: &str, body: String) -> String {
509 if body.starts_with("Rejected:") {
510 return body;
511 }
512 let newly = crate::rules::ensure_rules_for_path(ctx, task_id, slot, path).await;
513 if newly.is_empty() {
514 body
515 } else {
516 format!("{body}\n[loaded rules: {}]", newly.join(", "))
517 }
518}
519
520/// Parse `build` args: structured `{module, tasks}` (preferred, also
521/// accepted by the `build` dispatch arm) or the legacy `{command}` string.
522pub(crate) fn parse_build_args(args: &serde_json::Value) -> Result<String, String> {
523 if let Some(module) = args.get("module").and_then(|v| v.as_str()) {
524 let tasks: Vec<String> = args
525 .get("tasks")
526 .and_then(|v| v.as_array())
527 .map(|a| {
528 a.iter()
529 .filter_map(|v| v.as_str().map(|s| s.to_string()))
530 .collect()
531 })
532 .unwrap_or_default();
533 return build_command(module, &tasks);
534 }
535 if let Some(cmd) = args.get("command").and_then(|v| v.as_str()) {
536 return crate::tools::validate_build_command(cmd);
537 }
538 Err("build needs `module` + `tasks` (e.g. {\"module\": \"notes\", \"tasks\": [\"lint\"]}) or the legacy `command` string".to_string())
539}
540
541async fn dispatch_build(ctx: &DriverCtx, task_id: i64, slot: u32, args: &serde_json::Value) -> String {
542 let allowed = match parse_build_args(args) {
543 Ok(c) => c,
544 Err(e) => return format!("Rejected: {e}"),
545 };
546 match exec_build_command(ctx, task_id, slot, &allowed).await {
547 BuildOutcome::Done(r) => {
548 let summary = parse_build_output(&r.stdout, &r.stderr, r.exit_code, "");
549 render_build_for_model(&summary)
550 }
551 BuildOutcome::Message(m) => m,
552 }
553}
554
555/// Structured-form `build{module, tasks}` entry point used by the `build`
556/// dispatch arm in `agent.rs` (same validation + parsed rendering as
557/// [`dispatch`] would produce for the structured shape).
558pub(crate) async fn dispatch_structured_build(
559 ctx: &DriverCtx,
560 task_id: i64,
561 slot: u32,
562 args: &serde_json::Value,
563) -> String {
564 let body = dispatch_build(ctx, task_id, slot, args).await;
565 match arg_str(args, "module").filter(|s| !s.trim().is_empty()) {
566 Some(module) => with_rules_note(ctx, task_id, slot, &module, body).await,
567 None => body,
568 }
569}
570
571async fn dispatch_run_tests(
572 ctx: &DriverCtx,
573 task_id: i64,
574 slot: u32,
575 args: &serde_json::Value,
576) -> String {
577 let module = arg_str(args, "module").unwrap_or_default();
578 let variant = arg_str(args, "variant").filter(|v| !v.trim().is_empty());
579 let filter = arg_str(args, "filter").filter(|f| !f.trim().is_empty());
580 let allowed = match run_tests_command(&module, variant.as_deref(), filter.as_deref()) {
581 Ok(c) => c,
582 Err(e) => return format!("Rejected: {e}"),
583 };
584 let variant = validate_variant(variant.as_deref()).unwrap_or_else(|_| "Dev".to_string());
585 let resp = match exec_build_command(ctx, task_id, slot, &allowed).await {
586 BuildOutcome::Done(r) => r,
587 BuildOutcome::Message(m) => return m,
588 };
589 // Prefer JUnit XML when the run produced any; otherwise (compile
590 // failure, no results dir) report the parsed build summary.
591 let dir = module.trim().replace(':', "/");
592 let dir = dir.trim_matches('/');
593 if let Some(summary) = read_test_xmls(ctx, slot, dir, &variant).await {
594 return render_tests_for_model(&summary);
595 }
596 let summary = parse_build_output(&resp.stdout, &resp.stderr, resp.exit_code, "");
597 render_build_for_model(&summary)
598}
599
600/// List `<module>/build/test-results/test<Variant>UnitTest/`, read each
601/// `TEST-*.xml` (first 20), parse and merge. `None` when no report parsed.
602async fn read_test_xmls(
603 ctx: &DriverCtx,
604 slot: u32,
605 module_dir: &str,
606 variant: &str,
607) -> Option<TestSummary> {
608 let results_dir = format!("{module_dir}/build/test-results/test{variant}UnitTest");
609 let listing = ctx.runner.list(slot, &results_dir).await.ok()?;
610 let mut parsed = Vec::new();
611 for entry in listing
612 .entries
613 .iter()
614 .filter(|e| e.starts_with("TEST-") && e.ends_with(".xml"))
615 .take(20)
616 {
617 let path = format!("{results_dir}/{entry}");
618 let content = match ctx.runner.read(slot, &path, None, None).await {
619 Ok(r) => r.content,
620 Err(_) => continue,
621 };
622 if let Ok(summary) = parse_junit_xml(&content) {
623 parsed.push(summary);
624 }
625 }
626 if parsed.is_empty() {
627 return None;
628 }
629 Some(merge_test_summaries(&parsed))
630}
631
632async fn dispatch_check(ctx: &DriverCtx, task_id: i64, slot: u32, args: &serde_json::Value) -> String {
633 let module = arg_str(args, "module").unwrap_or_default();
634 let allowed = match check_command(&module) {
635 Ok(c) => c,
636 Err(e) => return format!("Rejected: {e}"),
637 };
638 match exec_build_command(ctx, task_id, slot, &allowed).await {
639 BuildOutcome::Done(r) => {
640 let summary = parse_build_output(&r.stdout, &r.stderr, r.exit_code, "");
641 render_build_for_model(&summary)
642 }
643 BuildOutcome::Message(m) => m,
644 }
645}
646
647fn scoped_path(path: &str, module_scope: &str) -> Result<String, String> {
648 let p = validate_rel_path(path.trim())?;
649 check_scope(&p, module_scope)?;
650 Ok(p)
651}
652
653async fn dispatch_git_log(
654 ctx: &DriverCtx,
655 slot: u32,
656 module_scope: &str,
657 args: &serde_json::Value,
658) -> String {
659 let path = arg_str(args, "path").filter(|p| !p.trim().is_empty());
660 if let Some(p) = &path {
661 if let Err(e) = scoped_path(p, module_scope) {
662 return format!("Rejected: {e}");
663 }
664 }
665 let cmd = match git_log_command(path.as_deref(), arg_u64(args, "n")) {
666 Ok(c) => c,
667 Err(e) => return format!("Rejected: {e}"),
668 };
669 match ctx.runner.exec(slot, &cmd, proto::ExecKind::Shell, 60).await {
670 Ok(r) => {
671 if r.exit_code == Some(0) {
672 let out = if r.stdout.trim().is_empty() {
673 "(no commits)".to_string()
674 } else {
675 cap_lines(&r.stdout, 100)
676 };
677 out
678 } else {
679 format!("git log failed: {}", cap_lines(&r.stderr, 20).trim())
680 }
681 }
682 Err(e) => format!("git log failed: {e}"),
683 }
684}
685
686async fn dispatch_git_show(
687 ctx: &DriverCtx,
688 slot: u32,
689 module_scope: &str,
690 args: &serde_json::Value,
691) -> String {
692 let rev = arg_str(args, "rev").unwrap_or_default();
693 let path = arg_str(args, "path").filter(|p| !p.trim().is_empty());
694 if let Some(p) = &path {
695 if let Err(e) = scoped_path(p, module_scope) {
696 return format!("Rejected: {e}");
697 }
698 }
699 let cmd = match git_show_command(&rev, path.as_deref()) {
700 Ok(c) => c,
701 Err(e) => return format!("Rejected: {e}"),
702 };
703 match ctx.runner.exec(slot, &cmd, proto::ExecKind::Shell, 60).await {
704 Ok(r) => {
705 if r.exit_code == Some(0) {
706 cap_lines(&r.stdout, 300)
707 } else {
708 format!("git show failed: {}", cap_lines(&r.stderr, 20).trim())
709 }
710 }
711 Err(e) => format!("git show failed: {e}"),
712 }
713}
714
715async fn dispatch_git_blame(
716 ctx: &DriverCtx,
717 slot: u32,
718 module_scope: &str,
719 args: &serde_json::Value,
720) -> String {
721 let path = arg_str(args, "path").unwrap_or_default();
722 let path = match scoped_path(&path, module_scope) {
723 Ok(p) => p,
724 Err(e) => return format!("Rejected: {e}"),
725 };
726 let (start, end) = match (arg_u64(args, "start"), arg_u64(args, "end")) {
727 (Some(s), Some(e)) => (s, e),
728 _ => return "Rejected: git_blame needs integer `start` and `end` (1-based, at most 200 lines)".to_string(),
729 };
730 let cmd = match git_blame_command(&path, start, end) {
731 Ok(c) => c,
732 Err(e) => return format!("Rejected: {e}"),
733 };
734 match ctx.runner.exec(slot, &cmd, proto::ExecKind::Shell, 60).await {
735 Ok(r) => {
736 if r.exit_code == Some(0) {
737 condense_blame_porcelain(&r.stdout)
738 } else {
739 format!("git blame failed: {}", cap_lines(&r.stderr, 20).trim())
740 }
741 }
742 Err(e) => format!("git blame failed: {e}"),
743 }
744}
745
746async fn dispatch_find_files(
747 ctx: &DriverCtx,
748 slot: u32,
749 module_scope: &str,
750 args: &serde_json::Value,
751) -> String {
752 let glob = arg_str(args, "glob").unwrap_or_default();
753 // Default root is the module scope dir, so `rg` never scans the repo.
754 let default_root = module_scope.replace(':', "/");
755 let root = arg_str(args, "path").filter(|p| !p.trim().is_empty()).unwrap_or(default_root);
756 let root = match scoped_path(&root, module_scope) {
757 Ok(p) => p,
758 Err(e) => return format!("Rejected: {e}"),
759 };
760 let cmd = match find_files_command(&glob, &root) {
761 Ok(c) => c,
762 Err(e) => return format!("Rejected: {e}"),
763 };
764 match ctx.runner.exec(slot, &cmd, proto::ExecKind::Shell, 60).await {
765 Ok(r) => {
766 if r.exit_code == Some(0) {
767 let out = r.stdout.trim().to_string();
768 if out.is_empty() {
769 "(no files matched)".to_string()
770 } else {
771 cap_lines(&out, 200)
772 }
773 } else {
774 format!("find_files failed: {}", cap_lines(&r.stderr, 20).trim())
775 }
776 }
777 Err(e) => format!("find_files failed: {e}"),
778 }
779}
780
781/// Parse an issue `state` arg: `open` (default), `closed`, or `all`.
782pub fn parse_issue_state(args: &serde_json::Value) -> Result<IssueState, String> {
783 match args
784 .get("state")
785 .and_then(|v| v.as_str())
786 .map(|s| s.trim().to_lowercase())
787 .as_deref()
788 {
789 None | Some("") | Some("open") => Ok(IssueState::Open),
790 Some("closed") => Ok(IssueState::Closed),
791 Some("all") => Ok(IssueState::All),
792 Some(other) => Err(format!("bad state {other:?}: expected open, closed, or all")),
793 }
794}
795
796fn parse_labels(args: &serde_json::Value) -> Result<Vec<String>, String> {
797 match args.get("labels") {
798 None | Some(serde_json::Value::Null) => Ok(Vec::new()),
799 Some(serde_json::Value::Array(items)) => {
800 let mut labels = Vec::with_capacity(items.len());
801 for item in items {
802 match item.as_str() {
803 Some(l) if !l.trim().is_empty() && l.len() <= 100 => {
804 labels.push(l.trim().to_string())
805 }
806 _ => return Err("labels must be an array of non-empty strings (<=100 chars)".to_string()),
807 }
808 }
809 if labels.len() > 10 {
810 return Err("at most 10 labels per search".to_string());
811 }
812 Ok(labels)
813 }
814 Some(_) => Err("labels must be an array of strings".to_string()),
815 }
816}
817
818async fn dispatch_github_search(ctx: &DriverCtx, args: &serde_json::Value) -> String {
819 let state = match parse_issue_state(args) {
820 Ok(s) => s,
821 Err(e) => return format!("Rejected: {e}"),
822 };
823 let labels = match parse_labels(args) {
824 Ok(l) => l,
825 Err(e) => return format!("Rejected: {e}"),
826 };
827 let query = arg_str(args, "query").filter(|q| !q.trim().is_empty());
828 let gh = crate::issues::github_client(&ctx.config);
829 match gh {
830 Ok(gh) => match gh.search_issues(query.as_deref(), &labels, state, 20).await {
831 Ok(found) if found.is_empty() => "(no issues matched)".to_string(),
832 Ok(found) => render_search_for_model(&found),
833 Err(e) => format!("GitHub search failed: {e}"),
834 },
835 Err(e) => format!("GitHub unavailable: {e}"),
836 }
837}
838
839async fn dispatch_github_read(ctx: &DriverCtx, args: &serde_json::Value) -> String {
840 let number = match arg_u64(args, "number") {
841 Some(n) if n > 0 => n,
842 _ => return "Rejected: github_read_issue needs a positive integer `number`".to_string(),
843 };
844 match crate::issues::fetch_issue(&ctx.config, number).await {
845 Ok(issue) => render_issue_for_model(&issue),
846 Err(e) => format!("GitHub read failed: {e}"),
847 }
848}
849
850
851#[cfg(test)]
852mod tests {
853 use super::*;
854
855 fn strings(v: &[&str]) -> Vec<String> {
856 v.iter().map(|s| s.to_string()).collect()
857 }
858
859 #[test]
860 fn shell_quote_table() {
861 assert_eq!(shell_quote("abc"), "'abc'");
862 assert_eq!(shell_quote("a b"), "'a b'");
863 // Single quotes become '"'"' — the quoted value re-parses to the input.
864 assert_eq!(shell_quote("a'b"), "'a'\"'\"'b'");
865 // Injection metacharacters are inert inside single quotes (only the
866 // quote char itself needs the '"'"' dance).
867 for evil in ["$(whoami)", "a; rm -rf /", "x\ny", "a|b", "a>b", "$HOME"] {
868 let q = shell_quote(evil);
869 assert!(q.starts_with('\'') && q.ends_with('\'') && !q[1..q.len()-1].contains('\''), "{evil:?} -> {q:?}");
870 }
871 // (Backticks are likewise inert inside single quotes; they only need
872 // quoting when they appear, like any other char.)
873 assert_eq!(shell_quote("`id`"), "'`id`'");
874 }
875
876 #[test]
877 fn validate_rel_path_table() {
878 for ok in ["notes/file.txt", "games/logicgate/AGENTS.md", "a", "a-b/c_d/e"] {
879 assert!(validate_rel_path(ok).is_ok(), "{ok:?}");
880 }
881 for bad in ["", "/abs/path", "../escape", "a/../../b", "a//b", "a/./b", "notes/"] {
882 // Note: `a/./b` has no `..`/absolute but `.` segments are still
883 // rejected by the runner... here `.` is allowed through (only
884 // `..` + empty segments are rejected); assert the documented set.
885 let r = validate_rel_path(bad);
886 if bad == "a/./b" {
887 assert!(r.is_ok(), "{bad:?}");
888 } else {
889 assert!(r.is_err(), "{bad:?}");
890 }
891 }
892 }
893
894 #[test]
895 fn validate_module_dir_table() {
896 assert_eq!(validate_module_dir("notes").unwrap(), "notes");
897 assert_eq!(validate_module_dir("games/logicgate").unwrap(), "games/logicgate");
898 assert_eq!(validate_module_dir("games:logicgate").unwrap(), "games/logicgate");
899 assert_eq!(validate_module_dir(" notes ").unwrap(), "notes");
900 assert_eq!(validate_module_dir("my-app").unwrap(), "my-app");
901 for bad in ["", "Notes", "notes app", "notes;rm", "/notes", "../x", "a:b:c:", "a//b"] {
902 assert!(validate_module_dir(bad).is_err(), "{bad:?}");
903 }
904 assert_eq!(gradle_path("games/logicgate"), ":games:logicgate");
905 }
906
907 #[test]
908 fn build_command_accepts() {
909 assert_eq!(
910 build_command("notes", &strings(&["compileDevKotlin"])).unwrap(),
911 "./gradlew :notes:compileDevKotlin --console=plain"
912 );
913 assert_eq!(
914 build_command("games/logicgate", &strings(&["lint", "detekt"])).unwrap(),
915 "./gradlew :games:logicgate:lint :games:logicgate:detekt --console=plain"
916 );
917 assert_eq!(
918 build_command("games:logicgate", &strings(&["testDevUnitTest"])).unwrap(),
919 "./gradlew :games:logicgate:testDevUnitTest --console=plain"
920 );
921 }
922
923 #[test]
924 fn build_command_rejects() {
925 // Bad modules.
926 assert!(build_command("", &strings(&["lint"])).is_err());
927 assert!(build_command("../escape", &strings(&["lint"])).is_err());
928 assert!(build_command("/abs", &strings(&["lint"])).is_err());
929 // Task allowlist (same as tools.rs).
930 assert!(build_command("notes", &[]).is_err());
931 assert!(build_command("notes", &strings(&["assembleDebug"])).is_err());
932 assert!(build_command("notes", &strings(&["test"])).is_err());
933 assert!(build_command("notes", &strings(&["lint; rm -rf /"])).is_err());
934 assert!(build_command("notes", &strings(&["$(lint)"])).is_err());
935 assert!(build_command("notes", &strings(&["lint`"])).is_err());
936 assert!(build_command("notes", &strings(&["--console=plain"])).is_err());
937 // Too many tasks.
938 let many = vec!["lint".to_string(); 9];
939 assert!(build_command("notes", &many).is_err());
940 }
941
942 #[test]
943 fn run_tests_command_table() {
944 assert_eq!(
945 run_tests_command("notes", None, None).unwrap(),
946 "./gradlew :notes:testDevUnitTest --console=plain"
947 );
948 assert_eq!(
949 run_tests_command("notes", Some("Debug"), None).unwrap(),
950 "./gradlew :notes:testDebugUnitTest --console=plain"
951 );
952 assert_eq!(
953 run_tests_command("games/logicgate", Some("Release"), Some("*.EngineTest")).unwrap(),
954 "./gradlew :games:logicgate:testReleaseUnitTest --tests '*.EngineTest' --console=plain"
955 );
956 // Injection attempts in module / variant / filter.
957 assert!(run_tests_command("notes; evil", None, None).is_err());
958 assert!(run_tests_command("notes", Some("Dev; rm"), None).is_err());
959 assert!(run_tests_command("notes", Some("D3v"), None).is_err());
960 assert!(run_tests_command("notes", None, Some("a; rm -rf /")).is_err());
961 assert!(run_tests_command("notes", None, Some("$(whoami)")).is_err());
962 assert!(run_tests_command("notes", None, Some("a`b`")).is_err());
963 assert!(run_tests_command("notes", None, Some("a b")).is_err());
964 assert!(run_tests_command("notes", None, Some("a/b")).is_err());
965 assert!(run_tests_command("notes", None, Some("")).is_err());
966 // Filter quoting keeps values with dots/stars intact and inert.
967 let cmd = run_tests_command("notes", None, Some("com.example.*Test")).unwrap();
968 assert!(cmd.contains("--tests 'com.example.*Test'"), "{cmd}");
969 }
970
971 #[test]
972 fn check_command_table() {
973 assert_eq!(check_command("notes").unwrap(), "./check notes");
974 assert_eq!(check_command("games/logicgate").unwrap(), "./check games/logicgate");
975 assert_eq!(check_command("games:logicgate").unwrap(), "./check games/logicgate");
976 assert!(check_command("all").is_err());
977 assert!(check_command("").is_err());
978 assert!(check_command("notes backup").is_err());
979 assert!(check_command("../x").is_err());
980 assert!(check_command("notes; evil").is_err());
981 }
982
983 #[test]
984 fn git_log_command_table() {
985 assert_eq!(
986 git_log_command(None, None).unwrap(),
987 "git log --format='%h %ad %an %s' --date=short -n 20"
988 );
989 assert_eq!(
990 git_log_command(Some("notes/file.txt"), Some(5)).unwrap(),
991 "git log --format='%h %ad %an %s' --date=short -n 5 -- 'notes/file.txt'"
992 );
993 assert!(git_log_command(None, Some(0)).is_err());
994 assert!(git_log_command(None, Some(51)).is_err());
995 // Path traversal / absolute / injection rejected before quoting.
996 assert!(git_log_command(Some("../../etc/passwd"), None).is_err());
997 assert!(git_log_command(Some("/abs"), None).is_err());
998 assert!(git_log_command(Some("a'; rm -rf /; echo '"), None).is_ok()); // quoted inert
999 let cmd = git_log_command(Some("a'; rm -rf /; echo '"), None).unwrap();
1000 assert!(cmd.contains("-- 'a'"), "{cmd}");
1001 }
1002
1003 #[test]
1004 fn git_rev_and_show_table() {
1005 for ok in ["HEAD", "HEAD~1", "HEAD~999", "abc123", "ABCDEF0123456789abcdef", &"a".repeat(40)] {
1006 assert!(validate_git_rev(ok).is_ok(), "{ok:?}");
1007 }
1008 for bad in ["", "head", "main", "HEAD~", "HEAD~1000", "HEAD~-1", "abc", &"a".repeat(41), "xyz!", "HEAD~1; rm", "$(HEAD)", "`HEAD`", "HEAD~1 | cat"] {
1009 assert!(validate_git_rev(bad).is_err(), "{bad:?}");
1010 }
1011 assert_eq!(
1012 git_show_command("HEAD", None).unwrap(),
1013 "git show 'HEAD'"
1014 );
1015 assert_eq!(
1016 git_show_command("abc123", Some("notes/f.txt")).unwrap(),
1017 "git show 'abc123' -- 'notes/f.txt'"
1018 );
1019 assert!(git_show_command("nope!", None).is_err());
1020 assert!(git_show_command("HEAD", Some("../x")).is_err());
1021 }
1022
1023 #[test]
1024 fn git_blame_command_table() {
1025 assert_eq!(
1026 git_blame_command("notes/f.txt", 1, 50).unwrap(),
1027 "git blame --porcelain -L 1,50 -- 'notes/f.txt'"
1028 );
1029 assert!(git_blame_command("notes/f.txt", 0, 10).is_err());
1030 assert!(git_blame_command("notes/f.txt", 10, 5).is_err());
1031 assert!(git_blame_command("notes/f.txt", 1, 201).is_err());
1032 assert!(git_blame_command("notes/f.txt", 1, 200).is_ok());
1033 assert!(git_blame_command("../x", 1, 10).is_err());
1034 assert!(git_blame_command("/abs", 1, 10).is_err());
1035 }
1036
1037 #[test]
1038 fn blame_condense_and_dates() {
1039 assert_eq!(unix_to_ymd(0), "1970-01-01");
1040 assert_eq!(unix_to_ymd(1793904494), "2026-11-05");
1041 let sha = "a".repeat(40);
1042 let porcelain = format!(
1043 "{sha} 1 1 1\nauthor Jane Doe\nauthor-mail <j@x>\nauthor-time 1793904494\n\
1044 author-tz +0000\nsummary x\nfilename notes/f.txt\n\tgreeting line\n\
1045 {sha} 2 2 1\nauthor Jane Doe\nauthor-time 0\n\tsecond line\n"
1046 );
1047 let out = condense_blame_porcelain(&porcelain);
1048 let lines: Vec<&str> = out.lines().collect();
1049 assert_eq!(lines.len(), 2);
1050 assert!(lines[0].starts_with("aaaaaaaa Jane Doe 2026-11-05 | greeting line"), "{out}");
1051 assert!(lines[1].starts_with("aaaaaaaa Jane Doe 1970-01-01 | second line"), "{out}");
1052 }
1053
1054 #[test]
1055 fn find_files_command_table() {
1056 assert_eq!(
1057 find_files_command("*.kt", "notes").unwrap(),
1058 "rg --files -g '*.kt' 'notes'"
1059 );
1060 // Glob metacharacters that could escape to shell are quoted.
1061 let cmd = find_files_command("*.kt; rm -rf /", "notes").unwrap();
1062 assert!(cmd.contains("-g '*.kt; rm -rf /'"), "{cmd}");
1063 assert!(find_files_command("", "notes").is_err());
1064 assert!(find_files_command("*.kt", "../x").is_err());
1065 assert!(find_files_command("*.kt", "/abs").is_err());
1066 }
1067
1068 #[test]
1069 fn issue_state_and_labels_table() {
1070 let state = |v: serde_json::Value| parse_issue_state(&v).map(|s| s.as_str());
1071 assert_eq!(state(serde_json::json!({})).unwrap(), "open");
1072 assert_eq!(state(serde_json::json!({"state": "closed"})).unwrap(), "closed");
1073 assert_eq!(state(serde_json::json!({"state": "ALL"})).unwrap(), "all");
1074 assert!(state(serde_json::json!({"state": "bogus"})).is_err());
1075 assert_eq!(
1076 parse_labels(&serde_json::json!({"labels": ["bug", "weather"]})).unwrap(),
1077 vec!["bug".to_string(), "weather".to_string()]
1078 );
1079 assert!(parse_labels(&serde_json::json!({"labels": "bug"})).is_err());
1080 assert!(parse_labels(&serde_json::json!({"labels": [""]})).is_err());
1081 assert!(parse_labels(&serde_json::json!({"labels": ["$(x)"]})).unwrap().len() == 1);
1082 }
1083}