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

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

agent.rs1559 lines · 58.8 KiBRaw
1//! The OpenRouter agent loop: one task, one slot, until `finish`/park.
2//!
3//! Flow per task:
4//! 1. Fresh tasks: `fetch origin main` in the mirror; runner `prepare`s the
5//! slot branch. Resumed tasks (queued with stored history): runner
6//! `prepare`s with a [`proto::ResumeSpec`] restoring the parked WIP ref.
7//! 2. Fetch root + module `AGENTS.md` through the runner; build the system
8//! prompt; the conversation (user / assistant / tool messages) is persisted
9//! in the `messages` table as sent and reloaded on resume. The system
10//! message is rebuilt every turn and never stored.
11//! 3. Loop: drain the inbox (steering becomes user messages), POST OpenRouter
12//! chat-completions → dispatch tool calls to the runner → append results.
13//! Every turn is persisted as an event and broadcast to SSE subscribers.
14//! 4. On `finish{summary, commit_message}`: validate, runner `/commit`,
15//! download `/bundle`, `bundle verify`, import into the mirror, push
16//! upstream (the review gate is a later phase; finish still auto-pushes).
17//! 5. Whenever the agent must wait (`ask_user`, text-only reply, budget,
18//! error, Stop), the driver parks: WIP work (if any) is committed, bundled
19//! and imported as `refs/agent-wip/<id>`, then one atomic
20//! [`Store::park_task`] sets the status and releases the slot.
21
22use std::sync::Arc;
23
24use tokio::sync::broadcast;
25
26use crate::config::Config;
27use crate::models::{
28 branch_name, cap_final_diff, cap_plan_markdown, is_parking_tool, plan_gate_message,
29 render_todos, truncate_result, trim_placeholder, validate_commit_message,
30 validate_commit_message_for_issue, validate_todos,
31 Event, Pending, TaskStatus, PENDING_BUDGET, PENDING_CHAT, PENDING_ERROR, PENDING_PLAN,
32 PENDING_QUESTION, PENDING_REVIEW, PENDING_STOPPED, EVENT_ASSISTANT, EVENT_PLAN, EVENT_QUESTION,
33 EVENT_REVIEW, EVENT_STATUS, EVENT_TODOS, EVENT_TOOL_CALL, EVENT_TOOL_RESULT, EVENT_USER_MESSAGE,
34 INBOX_PLAN_APPROVE, INBOX_PLAN_CHANGES, INBOX_REVIEW_CHANGES,
35};
36use crate::openrouter::{tool_defs, AssistantTurn, Message, OpenRouter, ToolCall};
37use crate::prompt::build_system_prompt;
38use crate::rules::{ensure_rules_for_path, load_session_rules, sorted_loaded_rules};
39use crate::runner::Runner;
40use crate::store::Store;
41use crate::tools::{shell_looks_mutating, validate_shell_command};
42
43/// Outcome of one worker claim on a task. `Parked` means the driver stored a
44/// `pending_json` resume point and released the slot; the scheduler just goes
45/// back to the claim loop. (`finish` parks as `review`; Approve pushes via
46/// HTTP, so no claim ever completes synchronously anymore.)
47#[derive(Debug)]
48pub enum TaskOutcome {
49 Failed {
50 reason: String,
51 },
52 Parked,
53}
54
55/// Shared runtime handles passed to every task driver.
56#[derive(Clone)]
57pub struct DriverCtx {
58 pub config: Arc<Config>,
59 pub store: Store,
60 pub runner: Runner,
61 pub openrouter: OpenRouter,
62 /// Broadcast of `(task_id, event)` for SSE.
63 pub events_tx: broadcast::Sender<(i64, Event)>,
64}
65
66impl DriverCtx {
67 /// Persist an event and broadcast it (broadcast failure = no listeners).
68 pub fn emit(&self, task_id: i64, kind: &str, body: serde_json::Value) -> Event {
69 let ev = self
70 .store
71 .push_event(task_id, kind, &body)
72 .unwrap_or(Event {
73 id: -1,
74 task_id,
75 seq: -1,
76 ts: crate::models::now_unix(),
77 kind: kind.to_string(),
78 body: body.clone(),
79 });
80 let _ = self.events_tx.send((task_id, ev.clone()));
81 ev
82 }
83}
84
85fn stop_requested(store: &Store, task_id: i64) -> bool {
86 store
87 .get_task(task_id)
88 .ok()
89 .flatten()
90 .map(|t| t.stop_requested)
91 .unwrap_or(true)
92}
93
94/// Scrub `Bearer <secret>` values before a string is stored in an event or
95/// log. The push token never flows through the loop, but a model could
96/// hallucinate something shaped like one; redact defensively.
97pub fn scrub_secrets(s: &str) -> String {
98 let mut out = String::with_capacity(s.len());
99 let mut rest = s;
100 loop {
101 if let Some(i) = rest.to_lowercase().find("bearer ") {
102 out.push_str(&rest[..i + 7]);
103 out.push_str("[redacted]");
104 let tail = &rest[i + 7..];
105 let end = tail
106 .find(|c: char| c.is_whitespace() || c == '"' || c == '\'')
107 .unwrap_or(tail.len());
108 rest = &tail[end..];
109 } else {
110 out.push_str(rest);
111 break;
112 }
113 }
114 out
115}
116
117/// Short (<=400 char) preview of tool arguments for the event log.
118fn args_preview(args: &str) -> String {
119 const MAX: usize = 400;
120 if args.len() <= MAX {
121 args.to_string()
122 } else {
123 format!("{}…[{} chars]", &args[..MAX], args.len())
124 }
125}
126
127/// Look up a string argument.
128fn arg_str(args: &serde_json::Value, key: &str) -> Option<String> {
129 args.get(key)
130 .and_then(|v| v.as_str())
131 .map(|s| s.to_string())
132}
133
134/// Release-signal check: `true` while a production release build runs.
135pub fn release_active(config: &Config) -> bool {
136 config.release_signal.exists()
137}
138
139/// Wait out the release signal (polling), up to the configured limit.
140/// Returns `Err(msg)` when the wait expires (message goes to the model).
141pub async fn wait_for_release_clear(
142 ctx: &DriverCtx,
143 task_id: i64,
144 _command: &str,
145) -> Result<(), String> {
146 if ctx.config.test_skip_release_wait {
147 // Test seam: behave as if preemption fired immediately. Match the
148 // production preemption message so tests assert one string.
149 let _ = ctx.runner.kill_build().await;
150 return Err("build preempted by a production release; retry later".to_string());
151 }
152 let limit = ctx.config.build_wait_limit();
153 let poll = ctx.config.poll_interval();
154 let start = std::time::Instant::now();
155 ctx.emit(task_id, EVENT_STATUS,
156 serde_json::json!({"message": "a production release build is running; waiting for it to finish (up to 60 min)"}),
157 );
158 loop {
159 if !release_active(&ctx.config) {
160 return Ok(());
161 }
162 if stop_requested(&ctx.store, task_id) {
163 return Err("task stopped by operator".to_string());
164 }
165 if start.elapsed() >= limit {
166 return Err(
167 "production release still running after 60 min; aborting build (retry later)"
168 .to_string(),
169 );
170 }
171 tokio::time::sleep(poll).await;
172 }
173}
174
175/// Outcome of one validated build-kind exec (release-preemption included).
176/// `Done` carries the raw runner response for the caller to parse; `Message`
177/// is already model-ready text (preemption notice).
178pub(crate) enum BuildOutcome {
179 Done(proto::ExecResponse),
180 Message(String),
181}
182
183/// Run a validated build command (`./gradlew ...` or `./check ...`) through
184/// the runner's Build exec kind with the release-preemption handling:
185/// wait while the release signal is present (up to 60 min), and surface a
186/// retry-later message when a release kills the build. Shared by the legacy
187/// `build{command}` arm and `structured::{build,run_tests,check}`.
188pub(crate) async fn exec_build_command(
189 ctx: &DriverCtx,
190 task_id: i64,
191 slot: u32,
192 allowed: &str,
193) -> BuildOutcome {
194 // Release preemption: while the signal file exists, wait (up to
195 // 60 min). If it appeared mid-build, kill the runner build.
196 if release_active(&ctx.config) {
197 match wait_for_release_clear(ctx, task_id, allowed).await {
198 Ok(()) => {}
199 Err(msg) => return BuildOutcome::Message(msg),
200 }
201 }
202 match ctx
203 .runner
204 .exec(slot, allowed, proto::ExecKind::Build, 20 * 60)
205 .await
206 {
207 Ok(r) => {
208 if r.killed && release_active(&ctx.config) {
209 let _ = ctx.runner.kill_build().await;
210 BuildOutcome::Message(
211 "build preempted by a production release; retry later".to_string(),
212 )
213 } else {
214 BuildOutcome::Done(r)
215 }
216 }
217 Err(e) => BuildOutcome::Message(format!("build failed: {e}")),
218 }
219}
220
221/// Run one worker claim on a task: fresh or resumed. `slot` is the scheduler
222/// worker index (also the runner slot id). Returns to the claim loop on park.
223pub async fn drive_task(ctx: DriverCtx, task_id: i64, slot: u32) -> TaskOutcome {
224 let task = match ctx.store.get_task(task_id).ok().flatten() {
225 Some(t) => t,
226 None => {
227 return TaskOutcome::Failed {
228 reason: "task row vanished".to_string(),
229 }
230 }
231 };
232 let branch = if task.branch.is_empty() {
233 let b = branch_name(task.id, &task.title);
234 let _ = ctx.store.set_branch(task.id, &b);
235 b
236 } else {
237 task.branch.clone()
238 };
239 if task.kind == crate::models::TASK_KIND_TRIAGE {
240 return crate::triage::drive_triage(&ctx, &task, slot, &branch).await;
241 }
242 let model = task.model.clone();
243 let module_scope = if task.module_scope.is_empty() {
244 "notes".to_string()
245 } else {
246 task.module_scope.clone()
247 };
248
249 ctx.emit(task_id, EVENT_STATUS,
250 serde_json::json!({"message": format!("preparing slot {slot} on {branch}")}),
251 );
252
253 // Resumed claim? Stored history + a previous wip_sha/base_sha say so.
254 let resumed = ctx.store.load_messages(task_id).map(|m| !m.is_empty());
255 let resumed = resumed.unwrap_or(false);
256
257 // 1. Mirror refresh + slot prepare (fresh or resume).
258 if let Err(e) = crate::git::fetch_main(&ctx.config.mirror_dir).await {
259 return fail(&ctx, task_id, &format!("mirror fetch failed: {e}")).await;
260 }
261 if resumed {
262 if let Err(reason) = prepare_resumed(&ctx, &task, slot, &branch).await {
263 return fail(&ctx, task_id, &reason).await;
264 }
265 // Budget parks grant headroom on resume: +20 steps, +$1.00.
266 if task.pending.as_ref().map(|p| p.kind.as_str()) == Some(PENDING_BUDGET) {
267 let _ = ctx.store.extend_budget(task_id);
268 ctx.emit(task_id, EVENT_STATUS,
269 serde_json::json!({"message": "budget extended (+20 steps, +$1.00)"}),
270 );
271 }
272 } else {
273 match crate::git::main_sha(&ctx.config.mirror_dir).await {
274 Ok(sha) => {
275 let _ = ctx.store.set_base_sha(task_id, &sha);
276 }
277 Err(e) => return fail(&ctx, task_id, &format!("mirror rev-parse: {e}")).await,
278 }
279 match ctx.runner.prepare(slot, &branch).await {
280 Ok(r) => {
281 let _ = ctx.store.set_base_sha(task_id, &r.base_sha);
282 }
283 Err(e) => return fail(&ctx, task_id, &format!("runner prepare: {e}")).await,
284 }
285 }
286
287 // 2. Rules + system prompt (rebuilt every turn; never stored).
288 // Session rules load once per claim into rules_json (root + module +
289 // repo-map); per-path rules accumulate via ensure_rules_for_path during
290 // dispatch. Plan + todos come from the task row (volatile tail).
291 let (root_rules, module_rules) =
292 load_session_rules(&ctx, task_id, slot, &module_scope).await;
293 let system = build_system_prompt_for_task(&ctx, task_id, &module_scope, root_rules, module_rules);
294 let mut messages = vec![Message::system(system)];
295 // Stored history (seeded below for fresh tasks).
296 if resumed {
297 match ctx.store.load_messages(task_id) {
298 Ok(hist) => messages.extend(hist),
299 Err(e) => return fail(&ctx, task_id, &format!("load history: {e}")).await,
300 }
301 // Pending tool-call answer: ONE tool result from all inbox rows, then
302 // any leftover rows as fresh user messages. Tagged rows (plan
303 // approve / plan changes / review changes) format the answer; plain
304 // rows pass through raw (ask_user answers, steering).
305 if let Some(pending) = &task.pending {
306 if let Some(call_id) = pending.tool_call_id.clone() {
307 let drained = match ctx.store.drain_inbox_tagged(task_id) {
308 Ok(d) => d,
309 Err(e) => return fail(&ctx, task_id, &format!("drain inbox: {e}")).await,
310 };
311 let answer = format_pending_answer(pending, &drained);
312 let tool_name = match pending.kind.as_str() {
313 PENDING_QUESTION => "ask_user",
314 PENDING_PLAN => "propose_plan",
315 PENDING_REVIEW => "finish",
316 _ => "ask_user",
317 };
318 append_persisted(&ctx, task_id, &mut messages, Message::tool_result(call_id.clone(), answer.clone()));
319 ctx.emit(task_id, EVENT_TOOL_RESULT,
320 serde_json::json!({"name": tool_name, "truncated": false, "result": answer}),
321 );
322 // Rows beyond the pending answer (untagged leftovers can't
323 // happen here — drain is total — but tagged approve rows
324 // carry no extra user text, so nothing more to append).
325 }
326 }
327 } else {
328 append_persisted(
329 &ctx,
330 task_id,
331 &mut messages,
332 Message::user(format!("Task: {}\n\n{}", task.title, task.prompt)),
333 );
334 }
335 let tools = tool_defs();
336 ctx.emit(task_id, EVENT_STATUS,
337 serde_json::json!({"message": "agent loop started", "model": model}),
338 );
339
340 // 3. Main loop.
341 let mut openrouter_failures = 0u32;
342 loop {
343 if stop_requested(&ctx.store, task_id) {
344 return park_after_stop(&ctx, task_id, slot, &branch, &mut messages).await;
345 }
346 let cur = match ctx.store.get_task(task_id).ok().flatten() {
347 Some(t) => t,
348 None => {
349 return TaskOutcome::Failed {
350 reason: "task row vanished".to_string(),
351 }
352 }
353 };
354 if cur.steps >= cur.budget_steps || cur.cost_usd >= cur.budget_usd {
355 return park_budget(&ctx, task_id, slot, &branch, &mut messages).await;
356 }
357 // Steering: drain inbox at the top of each iteration (after the prior
358 // turn's tool results, which are already appended below).
359 match ctx.store.drain_inbox(task_id) {
360 Ok(rows) => {
361 for text in rows {
362 ctx.emit(task_id, EVENT_USER_MESSAGE,
363 serde_json::json!({"text": text}),
364 );
365 append_persisted(&ctx, task_id, &mut messages, Message::user(text));
366 }
367 }
368 Err(e) => return fail(&ctx, task_id, &format!("drain inbox: {e}")).await,
369 }
370 // Rebuild the system message from stored state every turn: todos,
371 // plan, and per-path rules may have changed mid-claim (update_todos
372 // dispatch, rules auto-load) without a re-park.
373 refresh_system_message(&ctx, task_id, &module_scope, &mut messages);
374 let send = trimmed_clone(&messages, ctx.config.context_chars());
375
376 // Model turn (transient errors retry ×3 with backoff, then park).
377 let turn: AssistantTurn = loop {
378 match ctx.openrouter.chat(&model, &send, &tools).await {
379 Ok(t) => {
380 openrouter_failures = 0;
381 break t;
382 }
383 Err(e) => {
384 openrouter_failures += 1;
385 if openrouter_failures > 3 {
386 return park_error(
387 &ctx,
388 task_id,
389 slot,
390 &branch,
391 &mut messages,
392 &format!("OpenRouter: {e}"),
393 )
394 .await;
395 }
396 let backoff = std::time::Duration::from_millis(500 * openrouter_failures as u64);
397 tokio::time::sleep(backoff).await;
398 }
399 }
400 };
401 let _ = ctx.store.add_usage(
402 task_id,
403 1,
404 turn.usage.prompt_tokens,
405 turn.usage.completion_tokens,
406 turn.usage.cost_usd(),
407 );
408 ctx.emit(task_id, EVENT_ASSISTANT,
409 serde_json::json!({
410 "text": scrub_secrets(&turn.text),
411 "prompt_tokens": turn.usage.prompt_tokens,
412 "completion_tokens": turn.usage.completion_tokens,
413 "cost_usd": turn.usage.cost_usd(),
414 }),
415 );
416 append_persisted(
417 &ctx,
418 task_id,
419 &mut messages,
420 Message::assistant_calls(
421 if turn.text.is_empty() {
422 None
423 } else {
424 Some(turn.text.clone())
425 },
426 turn.tool_calls.clone(),
427 ),
428 );
429
430 if turn.tool_calls.is_empty() {
431 return park_chat(&ctx, task_id, slot, &branch, &mut messages, &turn.text).await;
432 }
433
434 // Sole-call enforcement for parking tools: a mixed turn gets a tool
435 // error and NO park; every other call in the turn still gets its
436 // result so the protocol stays valid.
437 let parking_call: Option<ToolCall> = turn
438 .tool_calls
439 .iter()
440 .find(|c| is_parking_tool(&c.function.name))
441 .cloned();
442 if let Some(park_call) = parking_call {
443 if turn.tool_calls.len() != 1 {
444 for call in &turn.tool_calls {
445 if call.id == park_call.id {
446 continue;
447 }
448 match dispatch_tool(&ctx, task_id, slot, &module_scope, call).await {
449 ToolEffect::Continue { result_for_model } => {
450 append_persisted(
451 &ctx,
452 task_id,
453 &mut messages,
454 Message::tool_result(call.id.clone(), result_for_model),
455 );
456 }
457 ToolEffect::ReviewRequest { .. } => {
458 // A parking tool alongside `finish`: protocol
459 // error; `finish` is NOT honored in a mixed turn.
460 append_persisted(
461 &ctx,
462 task_id,
463 &mut messages,
464 Message::tool_result(
465 call.id.clone(),
466 "finish rejected: it must be the only call in its turn; re-issue it alone.".to_string(),
467 ),
468 );
469 }
470 }
471 }
472 let msg = format!(
473 "{} must be the only call in its turn; re-issue it alone.",
474 park_call.function.name
475 );
476 ctx.emit(task_id, EVENT_TOOL_RESULT,
477 serde_json::json!({"name": park_call.function.name, "truncated": false, "result": msg}),
478 );
479 append_persisted(
480 &ctx,
481 task_id,
482 &mut messages,
483 Message::tool_result(park_call.id.clone(), msg),
484 );
485 continue;
486 }
487 // Valid sole parking-tool call → park.
488 match park_call.function.name.as_str() {
489 "ask_user" => {
490 return park_question(&ctx, task_id, slot, &branch, &mut messages, &park_call).await;
491 }
492 "propose_plan" => {
493 match park_plan(&ctx, task_id, slot, &branch, &mut messages, &park_call).await {
494 Some(outcome) => return outcome,
495 None => continue, // validation error appended; keep looping
496 }
497 }
498 // `finish` validates inside dispatch_tool (needs the runner
499 // diff): fall out of the parking-call branch into the normal
500 // dispatch loop below, which turns it into ReviewRequest →
501 // park_review.
502 "finish" => {}
503 _ => {
504 let msg = format!("Unknown parking tool {:?}", park_call.function.name);
505 append_persisted(
506 &ctx,
507 task_id,
508 &mut messages,
509 Message::tool_result(park_call.id.clone(), msg.clone()),
510 );
511 ctx.emit(task_id, EVENT_TOOL_RESULT,
512 serde_json::json!({"name": park_call.function.name, "truncated": false, "result": msg}),
513 );
514 continue;
515 }
516 }
517 }
518
519 // Dispatch tool calls sequentially, in model order.
520 for call in &turn.tool_calls {
521 if stop_requested(&ctx.store, task_id) {
522 return park_after_stop(&ctx, task_id, slot, &branch, &mut messages).await;
523 }
524 match dispatch_tool(&ctx, task_id, slot, &module_scope, call).await {
525 ToolEffect::Continue { result_for_model } => {
526 append_persisted(
527 &ctx,
528 task_id,
529 &mut messages,
530 Message::tool_result(call.id.clone(), result_for_model),
531 );
532 }
533 ToolEffect::ReviewRequest {
534 summary,
535 commit_message,
536 } => {
537 return park_review(&ctx, task_id, slot, &branch, call, &summary, &commit_message)
538 .await;
539 }
540 }
541 }
542 }
543}
544
545/// Build the system prompt for a task from stored state: base + root/module
546/// rules + loaded rules sorted by path + plan + todos (stable → volatile).
547/// Public so tests can assert prompt ordering.
548pub fn build_system_prompt_for_task(
549 ctx: &DriverCtx,
550 task_id: i64,
551 module_scope: &str,
552 root_rules: Option<String>,
553 module_rules: Option<String>,
554) -> String {
555 let task = ctx.store.get_task(task_id).ok().flatten();
556 let rules = sorted_loaded_rules(task.as_ref().and_then(|t| t.rules_json.as_deref()));
557 // Exclude the fixed root/module/repo-map entries from `extra` — they are
558 // rendered by the base template already. (Anything else in rules_json,
559 // i.e. per-directory AGENTS.md files, renders sorted by path.)
560 let dir = module_scope.replace(':', "/");
561 let dir = dir.trim_matches('/');
562 let module_path = if dir.is_empty() {
563 "AGENTS.md".to_string()
564 } else {
565 format!("{dir}/AGENTS.md")
566 };
567 let extra: Vec<(String, String)> = rules
568 .into_iter()
569 .filter(|(p, _)| p != "AGENTS.md" && *p != module_path && p != ".llms/repo-map.md")
570 .collect();
571 let plan = task.as_ref().and_then(|t| t.plan_md.clone()).unwrap_or_default();
572 let todos = render_todos(task.as_ref().and_then(|t| t.todos_json.as_deref()));
573 let (require_plan, plan_approved) = task
574 .as_ref()
575 .map(|t| (t.require_plan, t.plan_approved))
576 .unwrap_or((false, false));
577 build_system_prompt(
578 module_scope,
579 &extra,
580 root_rules.as_deref(),
581 module_rules.as_deref(),
582 &plan,
583 &todos,
584 require_plan,
585 plan_approved,
586 )
587}
588
589/// Rebuild the system message in place after state changed mid-claim
590/// (todos update, plan approval). Keeps history positions stable.
591fn refresh_system_message(
592 ctx: &DriverCtx,
593 task_id: i64,
594 module_scope: &str,
595 messages: &mut [Message],
596) {
597 let task = match ctx.store.get_task(task_id).ok().flatten() {
598 Some(t) => t,
599 None => return,
600 };
601 // Re-derive root/module sections from stored rules_json (session load
602 // persisted them); fall back to "(unavailable)" when absent.
603 let map: std::collections::BTreeMap<String, Option<String>> = task
604 .rules_json
605 .as_deref()
606 .map(serde_json::from_str)
607 .transpose()
608 .unwrap_or_default()
609 .unwrap_or_default();
610 let dir = module_scope.replace(':', "/");
611 let dir = dir.trim_matches('/');
612 let module_path = if dir.is_empty() {
613 "AGENTS.md".to_string()
614 } else {
615 format!("{dir}/AGENTS.md")
616 };
617 let root = map.get("AGENTS.md").cloned().flatten();
618 let module = map.get(&module_path).cloned().flatten();
619 let system =
620 build_system_prompt_for_task(ctx, task_id, module_scope, root, module);
621 if let Some(first) = messages.first_mut() {
622 if first.role == "system" {
623 first.content = Some(system);
624 }
625 }
626}
627
628/// Append a message to the in-memory history AND persist it. Persistence
629/// failure is fatal (fail loudly, never silently diverge).
630pub(crate) fn append_persisted(ctx: &DriverCtx, task_id: i64, messages: &mut Vec<Message>, msg: Message) {
631 if let Err(e) = ctx.store.append_message(task_id, &msg) {
632 tracing::error!("persist message for task {task_id}: {e}");
633 }
634 messages.push(msg);
635}
636
637/// Format the single tool result that answers a pending parking-tool call
638/// from the drained (tagged) inbox rows.
639///
640/// * plan approve (`kind == "plan_approve"`) → `"Plan approved. Proceed."`
641/// * plan changes (`kind == "plan_changes"`) → `"User requested changes to
642/// the plan: <text>"` (plan stays unapproved; the model revises and calls
643/// `propose_plan` again)
644/// * review changes (`kind == "review_changes"`, i.e. a normal message while
645/// in `review`) → `"User reviewed the change and requested: <text>"`
646/// * anything else → raw texts joined (ask_user answers, steering).
647///
648/// Public for unit tests.
649pub fn format_pending_answer(
650 pending: &Pending,
651 rows: &[crate::store::InboxRow],
652) -> String {
653 let texts: Vec<&str> = rows.iter().map(|r| r.text.as_str()).collect();
654 // Tagged plan/review rows take precedence over any co-drained plain text.
655 if rows.iter().any(|r| r.kind == INBOX_PLAN_APPROVE) {
656 return "Plan approved. Proceed.".to_string();
657 }
658 if let Some(row) = rows.iter().find(|r| r.kind == INBOX_PLAN_CHANGES) {
659 return format!("User requested changes to the plan: {}", row.text);
660 }
661 if pending.kind == PENDING_REVIEW
662 || rows.iter().any(|r| r.kind == INBOX_REVIEW_CHANGES)
663 {
664 let feedback = rows
665 .iter()
666 .find(|r| r.kind == INBOX_REVIEW_CHANGES)
667 .map(|r| r.text.clone())
668 .unwrap_or_else(|| texts.join("\n"));
669 return format!("User reviewed the change and requested: {feedback}");
670 }
671 texts.join("\n")
672}
673
674async fn prepare_resumed(
675 ctx: &DriverCtx,
676 task: &crate::models::Task,
677 slot: u32,
678 branch: &str,
679) -> Result<(), String> {
680 let base_sha = task.base_sha.clone().unwrap_or_default();
681 if base_sha.is_empty() {
682 return Err("cannot resume: no base_sha recorded".to_string());
683 }
684 let (wip_ref, wip_sha) = match task.wip_sha.clone() {
685 Some(sha) => {
686 match crate::git::wip_ref_sha(&ctx.config.mirror_dir, task.id).await {
687 Ok(Some(found)) if found == sha => {
688 (Some(crate::models::wip_ref(task.id)), Some(sha))
689 }
690 Ok(Some(found)) => {
691 return Err(format!(
692 "cannot resume: WIP ref mismatch (expected {sha}, found {found})"
693 ));
694 }
695 Ok(None) => {
696 return Err(format!(
697 "cannot resume: WIP ref {} missing in mirror",
698 crate::models::wip_ref(task.id)
699 ));
700 }
701 Err(e) => {
702 return Err(format!("cannot resume: WIP ref check: {e}"));
703 }
704 }
705 }
706 None => (None, None),
707 };
708 match ctx
709 .runner
710 .prepare_resume(
711 slot,
712 branch,
713 proto::ResumeSpec {
714 base_sha: base_sha.clone(),
715 wip_ref,
716 wip_sha,
717 },
718 )
719 .await
720 {
721 Ok(r) => {
722 let _ = ctx.store.set_base_sha(task.id, &r.base_sha);
723 Ok(())
724 }
725 Err(e) => Err(format!("runner resume prepare: {e}")),
726 }
727}
728
729pub(crate) async fn fail(ctx: &DriverCtx, task_id: i64, reason: &str) -> TaskOutcome {
730 ctx.emit(task_id, EVENT_STATUS,
731 serde_json::json!({"message": reason}),
732 );
733 TaskOutcome::Failed {
734 reason: reason.to_string(),
735 }
736}
737
738// ---- parking ----
739
740/// Park the task and release the slot to the pool.
741///
742/// 1. If the checkout has changes: commit "WIP", download the bundle, import
743/// it into the mirror as `refs/agent-wip/<id>` and record `wip_sha`.
744/// Otherwise `wip_sha = NULL` (and any stale WIP ref is deleted).
745/// 2. One atomic [`Store::park_task`]: set status / `pending_json` /
746/// `slot = NULL`. When the inbox already holds a message, `park_task`
747/// re-queues instead (lost-wakeup fix) — the worker loop will reclaim the
748/// task on its next claim poll.
749///
750/// Emits the `question` event for question parks (so the UI can render the
751/// form) plus a `status` event in all cases.
752async fn park(
753 ctx: &DriverCtx,
754 task_id: i64,
755 slot: u32,
756 branch: &str,
757 status: TaskStatus,
758 pending: Pending,
759) -> TaskOutcome {
760 // Snapshot the work BEFORE the atomic park: commit + bundle + import.
761 let wip_sha: Option<String> = match ctx.runner.diff(slot).await {
762 Ok(d) if d.diff.trim().is_empty() && d.stat.trim().is_empty() => {
763 let _ = crate::git::delete_wip_ref(&ctx.config.mirror_dir, task_id).await;
764 None
765 }
766 Ok(_) => {
767 match ctx
768 .runner
769 .commit(slot, &format!("WIP task {task_id}"))
770 .await
771 {
772 Ok(_) => {}
773 Err(e) => {
774 // Best effort: unstaged/uncommitted work stays in the slot
775 // checkout; still park without a WIP ref.
776 tracing::warn!("park WIP commit for task {task_id}: {e}");
777 return park_without_wip(ctx, task_id, status, pending);
778 }
779 }
780 // A Stop arriving during commit/bundle is honored after import.
781 match ctx.runner.bundle(slot).await {
782 Ok(bundle) => match write_temp_bundle(&bundle) {
783 Ok(tmp) => {
784 match crate::git::import_wip_bundle(
785 &ctx.config.mirror_dir,
786 &tmp,
787 branch,
788 task_id,
789 )
790 .await
791 {
792 Ok(sha) => Some(sha),
793 Err(e) => {
794 tracing::warn!("park WIP import for task {task_id}: {e}");
795 return park_without_wip(ctx, task_id, status, pending);
796 }
797 }
798 }
799 Err(e) => {
800 tracing::warn!("park temp bundle for task {task_id}: {e}");
801 return park_without_wip(ctx, task_id, status, pending);
802 }
803 },
804 Err(e) => {
805 tracing::warn!("park bundle download for task {task_id}: {e}");
806 return park_without_wip(ctx, task_id, status, pending);
807 }
808 }
809 }
810 Err(e) => {
811 tracing::warn!("park diff for task {task_id}: {e}");
812 return park_without_wip(ctx, task_id, status, pending);
813 }
814 };
815
816 finish_park(ctx, task_id, status, pending, wip_sha.as_deref())
817}
818
819fn park_without_wip(
820 ctx: &DriverCtx,
821 task_id: i64,
822 status: TaskStatus,
823 pending: Pending,
824) -> TaskOutcome {
825 finish_park(ctx, task_id, status, pending, None)
826}
827
828fn finish_park(
829 ctx: &DriverCtx,
830 task_id: i64,
831 status: TaskStatus,
832 pending: Pending,
833 wip_sha: Option<&str>,
834) -> TaskOutcome {
835 if pending.kind == PENDING_QUESTION {
836 ctx.emit(task_id, EVENT_QUESTION, pending.payload.clone());
837 }
838 let effective = match ctx.store.park_task(task_id, status, &pending, wip_sha) {
839 Ok(s) => s,
840 Err(e) => {
841 return TaskOutcome::Failed {
842 reason: format!("park: {e}"),
843 };
844 }
845 };
846 ctx.emit(task_id, EVENT_STATUS,
847 serde_json::json!({
848 "message": format!("parked as {} (pending: {})", effective.as_str(), pending.kind),
849 "status": effective.as_str(),
850 "pending_kind": pending.kind,
851 }),
852 );
853 TaskOutcome::Parked
854}
855
856fn write_temp_bundle(bundle: &[u8]) -> Result<tempfile::TempPath, String> {
857 let tmp = tempfile::Builder::new()
858 .prefix("agentd-wip-bundle-")
859 .tempfile()
860 .map_err(|e| format!("temp bundle file: {e}"))?;
861 let path = tmp.into_temp_path();
862 std::fs::write(&path, bundle).map_err(|e| format!("write bundle: {e}"))?;
863 Ok(path)
864}
865
866/// `ask_user` (sole call in its turn) → park `needs_input(question)`.
867async fn park_question(
868 ctx: &DriverCtx,
869 task_id: i64,
870 slot: u32,
871 branch: &str,
872 _messages: &mut Vec<Message>,
873 call: &ToolCall,
874) -> TaskOutcome {
875 let args: serde_json::Value =
876 serde_json::from_str(&call.function.arguments).unwrap_or(serde_json::Value::Null);
877 let question = args
878 .get("question")
879 .and_then(|v| v.as_str())
880 .unwrap_or("")
881 .to_string();
882 let options = args.get("options").cloned().unwrap_or(serde_json::Value::Null);
883 let multi_select = args
884 .get("multi_select")
885 .and_then(|v| v.as_bool())
886 .unwrap_or(false);
887 let pending = Pending::new(
888 PENDING_QUESTION,
889 Some(call.id.clone()),
890 serde_json::json!({
891 "question": question,
892 "options": options,
893 "multi_select": multi_select,
894 }),
895 );
896 park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await
897}
898
899/// `propose_plan` (sole call in its turn) → store the plan text, emit the
900/// `plan` event, and park `needs_input(plan)` with pending
901/// `{kind:"plan", tool_call_id, payload:{plan_markdown}}`.
902///
903/// Returns `None` when the plan is empty: the rejection is appended as the
904/// tool result (history + event) and the caller continues the loop WITHOUT
905/// parking.
906async fn park_plan(
907 ctx: &DriverCtx,
908 task_id: i64,
909 slot: u32,
910 branch: &str,
911 messages: &mut Vec<Message>,
912 call: &ToolCall,
913) -> Option<TaskOutcome> {
914 let args: serde_json::Value =
915 serde_json::from_str(&call.function.arguments).unwrap_or(serde_json::Value::Null);
916 let plan_raw = args
917 .get("plan_markdown")
918 .and_then(|v| v.as_str())
919 .unwrap_or("")
920 .to_string();
921 if plan_raw.trim().is_empty() {
922 let msg = "propose_plan rejected: plan_markdown is empty; call propose_plan again with the plan.".to_string();
923 ctx.emit(task_id, EVENT_TOOL_RESULT,
924 serde_json::json!({"name": "propose_plan", "truncated": false, "result": msg}),
925 );
926 append_persisted(
927 ctx,
928 task_id,
929 messages,
930 Message::tool_result(call.id.clone(), msg),
931 );
932 return None;
933 }
934 let (plan_md, truncated) = cap_plan_markdown(&plan_raw);
935 let _ = ctx.store.set_plan_md(task_id, &plan_md);
936 ctx.emit(task_id, EVENT_PLAN,
937 serde_json::json!({"plan_markdown": plan_md, "truncated": truncated}),
938 );
939 let pending = Pending::new(
940 PENDING_PLAN,
941 Some(call.id.clone()),
942 serde_json::json!({"plan_markdown": plan_md}),
943 );
944 Some(park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await)
945}
946
947/// Text-only assistant turn → park `needs_input(chat)` (nudge-then-fail is
948/// retired).
949async fn park_chat(
950 ctx: &DriverCtx,
951 task_id: i64,
952 slot: u32,
953 branch: &str,
954 _messages: &mut Vec<Message>,
955 text: &str,
956) -> TaskOutcome {
957 let pending = Pending::new(
958 PENDING_CHAT,
959 None,
960 serde_json::json!({"text": text}),
961 );
962 park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await
963}
964
965/// Budget exhausted → park `needs_input(budget)` (resume grants +20/+$1).
966async fn park_budget(
967 ctx: &DriverCtx,
968 task_id: i64,
969 slot: u32,
970 branch: &str,
971 _messages: &mut Vec<Message>,
972) -> TaskOutcome {
973 let cur = ctx.store.get_task(task_id).ok().flatten();
974 let (steps, budget_steps, cost, budget_usd) = cur
975 .map(|t| (t.steps, t.budget_steps, t.cost_usd, t.budget_usd))
976 .unwrap_or((0, 0, 0.0, 0.0));
977 let pending = Pending::new(
978 PENDING_BUDGET,
979 None,
980 serde_json::json!({
981 "message": format!(
982 "budget exhausted (steps {steps}/{budget_steps}, cost ${cost:.4}/${budget_usd:.2})"
983 ),
984 }),
985 );
986 park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await
987}
988
989/// Transient errors, after retries → park `needs_input(error)` with the
990/// message.
991async fn park_error(
992 ctx: &DriverCtx,
993 task_id: i64,
994 slot: u32,
995 branch: &str,
996 _messages: &mut Vec<Message>,
997 message: &str,
998) -> TaskOutcome {
999 let pending = Pending::new(
1000 PENDING_ERROR,
1001 None,
1002 serde_json::json!({"message": message}),
1003 );
1004 park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await
1005}
1006
1007/// Operator Stop observed → park `needs_input(stopped)` with work kept.
1008async fn park_after_stop(
1009 ctx: &DriverCtx,
1010 task_id: i64,
1011 slot: u32,
1012 branch: &str,
1013 _messages: &mut Vec<Message>,
1014) -> TaskOutcome {
1015 let pending = Pending::new(
1016 PENDING_STOPPED,
1017 None,
1018 serde_json::json!({"message": "stopped by operator; work kept"}),
1019 );
1020 park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await
1021}
1022
1023/// Replace old tool results with placeholders once the conversation exceeds
1024/// `budget` chars (keeps system prompt + first user message + recent tail).
1025///
1026/// Takes a slice and returns an owned trimmed CLONE: the stored history is
1027/// never mutated. Pairing is structural — messages are never added, removed
1028/// or reordered, only tool-result *contents* in the middle window are
1029/// replaced with placeholders, so an assistant `tool_calls` message is never
1030/// separated from its tool results (ids stay aligned). Debug builds assert
1031/// the pairing after trimming. Public for unit tests.
1032pub fn trimmed_clone(messages: &[Message], budget: usize) -> Vec<Message> {
1033 let total: usize = messages.iter().map(|m| m.chars()).sum();
1034 if total <= budget || messages.len() <= 6 {
1035 return messages.to_vec();
1036 }
1037 let mut out = messages.to_vec();
1038 let n = out.len();
1039 for m in out.iter_mut().take(n.saturating_sub(4)).skip(2) {
1040 if m.role == "tool" {
1041 if let Some(c) = m.content.take() {
1042 m.content = Some(trim_placeholder("tool", c.len()));
1043 }
1044 }
1045 }
1046 debug_assert!(tool_pairs_intact(&out), "trim separated tool_calls from results");
1047 out
1048}
1049
1050/// Every assistant `tool_calls` id has a matching `tool` result later in the
1051/// history (OpenRouter rejects unanswered calls).
1052fn tool_pairs_intact(messages: &[Message]) -> bool {
1053 let mut pending: std::collections::HashSet<&str> = std::collections::HashSet::new();
1054 for m in messages {
1055 if m.role == "assistant" {
1056 if let Some(calls) = &m.tool_calls {
1057 for c in calls {
1058 pending.insert(c.id.as_str());
1059 }
1060 }
1061 } else if m.role == "tool" {
1062 if let Some(id) = &m.tool_call_id {
1063 pending.remove(id.as_str());
1064 }
1065 }
1066 }
1067 pending.is_empty()
1068}
1069
1070/// Unknown-tool error (legacy list of the pre-structured tools plus the
1071/// structured layer).
1072fn unknown_tool(other: &str) -> String {
1073 format!(
1074 "Unknown tool {other:?}; available: read_file, list_dir, search, edit_file, write_file, update_todos, git_diff, run_shell, build, ask_user, propose_plan, finish, run_tests, check, git_log, git_show, git_blame, find_files, github_search_issues, github_read_issue."
1075 )
1076}
1077
1078/// Legacy in-place trim kept for unit tests: same window rule, mutates.
1079/// (The driver uses [`trimmed_clone`]; this entry point exists for the
1080/// trimming unit test.)
1081#[allow(dead_code)]
1082pub fn trim_messages(messages: &mut [Message], budget: usize) {
1083 let trimmed = trimmed_clone(messages, budget);
1084 if trimmed.len() == messages.len() {
1085 messages.clone_from_slice(&trimmed);
1086 }
1087}
1088
1089pub(crate) enum ToolEffect {
1090 Continue { result_for_model: String },
1091 ReviewRequest { summary: String, commit_message: String },
1092}
1093
1094/// Is the plan gate currently closed for this task? (`require_plan` set and
1095/// the plan not yet approved.)
1096fn plan_gated(store: &Store, task_id: i64) -> bool {
1097 store
1098 .get_task(task_id)
1099 .ok()
1100 .flatten()
1101 .map(|t| t.require_plan && !t.plan_approved)
1102 .unwrap_or(false)
1103}
1104
1105pub(crate) async fn dispatch_tool(
1106 ctx: &DriverCtx,
1107 task_id: i64,
1108 slot: u32,
1109 module_scope: &str,
1110 call: &ToolCall,
1111) -> ToolEffect {
1112 let args: serde_json::Value =
1113 serde_json::from_str(&call.function.arguments).unwrap_or(serde_json::Value::Null);
1114 ctx.emit(task_id, EVENT_TOOL_CALL,
1115 serde_json::json!({"name": call.function.name, "args": args_preview(&call.function.arguments)}),
1116 );
1117 let raw: String = match call.function.name.as_str() {
1118 "read_file" => {
1119 let path = arg_str(&args, "path").unwrap_or_default();
1120 if let Err(e) = check_scope(&path, module_scope) {
1121 format!("Scope error: {e}")
1122 } else {
1123 match ctx
1124 .runner
1125 .read(
1126 slot,
1127 &path,
1128 args.get("start_line").and_then(|v| v.as_u64()).map(|v| v as usize),
1129 args.get("max_lines").and_then(|v| v.as_u64()).map(|v| v as usize),
1130 )
1131 .await
1132 {
1133 Ok(r) => {
1134 let body = format!(
1135 "{} ({} lines{})",
1136 r.content,
1137 r.total_lines,
1138 if r.truncated { ", truncated" } else { "" }
1139 );
1140 with_loaded_rules_note(ctx, task_id, slot, &path, body).await
1141 }
1142 Err(e) => format!("read failed: {e}"),
1143 }
1144 }
1145 }
1146 "list_dir" => {
1147 let path = arg_str(&args, "path").unwrap_or_default();
1148 if !path.is_empty() {
1149 if let Err(e) = check_scope(&path, module_scope) {
1150 return finish_dispatch(ctx, task_id, &call.function.name, &format!("Scope error: {e}"));
1151 }
1152 }
1153 match ctx.runner.list(slot, &path).await {
1154 Ok(r) => {
1155 let probe = if path.is_empty() {
1156 module_scope.replace(':', "/")
1157 } else {
1158 path.clone()
1159 };
1160 with_loaded_rules_note(ctx, task_id, slot, &probe, r.entries.join("\n")).await
1161 }
1162 Err(e) => format!("list failed: {e}"),
1163 }
1164 }
1165 "search" => {
1166 let pattern = arg_str(&args, "pattern").unwrap_or_default();
1167 let sub = arg_str(&args, "path").filter(|s| !s.is_empty());
1168 if let Some(p) = &sub {
1169 if let Err(e) = check_scope(p, module_scope) {
1170 return finish_dispatch(ctx, task_id, &call.function.name, &format!("Scope error: {e}"));
1171 }
1172 }
1173 // Default the search root to the module scope when the model
1174 // passes none, so rg never scans the whole repo.
1175 let root = sub.or_else(|| Some(module_scope.replace(':', "/")));
1176 match ctx
1177 .runner
1178 .search(
1179 slot,
1180 &pattern,
1181 root.as_deref(),
1182 arg_str(&args, "glob").as_deref(),
1183 args.get("fixed_string").and_then(|v| v.as_bool()).unwrap_or(false),
1184 )
1185 .await
1186 {
1187 Ok(r) => {
1188 let probe = root.unwrap_or_default();
1189 with_loaded_rules_note(ctx, task_id, slot, &probe, r.matches).await
1190 }
1191 Err(e) => format!("search failed: {e}"),
1192 }
1193 }
1194 "edit_file" => {
1195 if plan_gated(&ctx.store, task_id) {
1196 plan_gate_message().to_string()
1197 } else {
1198 let path = arg_str(&args, "path").unwrap_or_default();
1199 if let Err(e) = check_scope(&path, module_scope) {
1200 format!("Scope error: {e}")
1201 } else {
1202 match ctx
1203 .runner
1204 .edit(
1205 slot,
1206 &path,
1207 &arg_str(&args, "old").unwrap_or_default(),
1208 &arg_str(&args, "new").unwrap_or_default(),
1209 )
1210 .await
1211 {
1212 Ok(()) => {
1213 with_loaded_rules_note(ctx, task_id, slot, &path, "edit applied".to_string()).await
1214 }
1215 Err(e) => format!("edit failed: {e}"),
1216 }
1217 }
1218 }
1219 }
1220 "write_file" => {
1221 if plan_gated(&ctx.store, task_id) {
1222 plan_gate_message().to_string()
1223 } else {
1224 let path = arg_str(&args, "path").unwrap_or_default();
1225 if let Err(e) = check_scope(&path, module_scope) {
1226 format!("Scope error: {e}")
1227 } else {
1228 match ctx
1229 .runner
1230 .write(slot, &path, &arg_str(&args, "content").unwrap_or_default())
1231 .await
1232 {
1233 Ok(()) => {
1234 with_loaded_rules_note(ctx, task_id, slot, &path, "file written".to_string()).await
1235 }
1236 Err(e) => format!("write failed: {e}"),
1237 }
1238 }
1239 }
1240 }
1241 "update_todos" => {
1242 let items_raw = args.get("items").cloned().unwrap_or(serde_json::Value::Null);
1243 let items: Vec<crate::models::TodoItem> = match serde_json::from_value(items_raw) {
1244 Ok(v) => v,
1245 Err(e) => {
1246 return finish_dispatch(
1247 ctx,
1248 task_id,
1249 &call.function.name,
1250 &format!("update_todos rejected: bad items ({e}); pass items:[{{text, status: pending|in_progress|done}}]"),
1251 );
1252 }
1253 };
1254 match validate_todos(&items) {
1255 Err(e) => {
1256 return finish_dispatch(
1257 ctx,
1258 task_id,
1259 &call.function.name,
1260 &format!("update_todos rejected: {e}"),
1261 );
1262 }
1263 Ok(valid) => {
1264 let todos_json = serde_json::to_string(&valid).unwrap_or_else(|_| "[]".to_string());
1265 if let Err(e) = ctx.store.set_todos(task_id, &todos_json) {
1266 return finish_dispatch(
1267 ctx,
1268 task_id,
1269 &call.function.name,
1270 &format!("update_todos failed: {e}"),
1271 );
1272 }
1273 ctx.emit(task_id, EVENT_TODOS,
1274 serde_json::json!({"items": valid}),
1275 );
1276 "ok".to_string()
1277 }
1278 }
1279 }
1280 "git_diff" => match ctx.runner.diff(slot).await {
1281 Ok(d) => format!("{}\n{}", d.stat, d.diff),
1282 Err(e) => format!("diff failed: {e}"),
1283 },
1284 "run_shell" => {
1285 let command = arg_str(&args, "command").unwrap_or_default();
1286 // Plan gate first (best-effort mutation detector), then the
1287 // existing build/device blocklist.
1288 if plan_gated(&ctx.store, task_id) && shell_looks_mutating(&command) {
1289 plan_gate_message().to_string()
1290 } else {
1291 match validate_shell_command(&command) {
1292 Err(msg) => format!("Rejected: {msg}"),
1293 Ok(()) => match ctx
1294 .runner
1295 .exec(slot, &command, proto::ExecKind::Shell, 60)
1296 .await
1297 {
1298 Ok(r) => exec_summary(&r),
1299 Err(e) => format!("exec failed: {e}"),
1300 },
1301 }
1302 }
1303 }
1304 "build" => {
1305 if plan_gated(&ctx.store, task_id) {
1306 plan_gate_message().to_string()
1307 } else if args.get("module").and_then(|v| v.as_str()).is_some() {
1308 // Structured `{module, tasks}` form: validated, run, and parsed.
1309 let parsed = crate::structured::dispatch_structured_build(ctx, task_id, slot, &args).await;
1310 return finish_dispatch(ctx, task_id, &call.function.name, &parsed);
1311 } else {
1312 // Legacy `{command}` string keeps the raw exec summary.
1313 let allowed = match crate::structured::parse_build_args(&args) {
1314 Err(msg) => return finish_dispatch(ctx, task_id, &call.function.name, &format!("Rejected: {msg}")),
1315 Ok(c) => c,
1316 };
1317 match exec_build_command(ctx, task_id, slot, &allowed).await {
1318 BuildOutcome::Done(r) => exec_summary(&r),
1319 BuildOutcome::Message(m) => {
1320 return finish_dispatch(ctx, task_id, &call.function.name, &m);
1321 }
1322 }
1323 }
1324 }
1325 "finish" => {
1326 let summary = arg_str(&args, "summary").unwrap_or_default();
1327 let commit_message = arg_str(&args, "commit_message").unwrap_or_default();
1328 // Validate first: violations return as a tool result so the
1329 // model can fix them and call `finish` again. `finish` is a
1330 // parking tool, but validation happens here because a sole
1331 // `finish` flows through normal dispatch and only parks via
1332 // ReviewRequest below. Issue-linked tasks additionally require
1333 // the ` (#<n>)` subject suffix.
1334 let task_issue = ctx.store.get_task(task_id).ok().flatten().and_then(|t| t.issue_number);
1335 let validation = match task_issue {
1336 Some(n) => validate_commit_message_for_issue(&commit_message, Some(n)),
1337 None => validate_commit_message(&commit_message),
1338 };
1339 if let Err(e) = validation {
1340 let msg = format!(
1341 "finish rejected: {e}. Fix the commit message and call `finish` again."
1342 );
1343 return finish_dispatch(ctx, task_id, &call.function.name, &msg);
1344 }
1345 match ctx.runner.diff(slot).await {
1346 Ok(d) if d.diff.trim().is_empty() => {
1347 return finish_dispatch(
1348 ctx,
1349 task_id,
1350 &call.function.name,
1351 "finish rejected: the diff is empty — make code changes first, then call `finish` again.",
1352 );
1353 }
1354 Err(e) => {
1355 return finish_dispatch(
1356 ctx,
1357 task_id,
1358 &call.function.name,
1359 &format!("finish rejected: could not read diff ({e}); retry `finish`"),
1360 );
1361 }
1362 _ => {}
1363 }
1364 return ToolEffect::ReviewRequest {
1365 summary,
1366 commit_message,
1367 };
1368 }
1369 other => {
1370 // Structured tools (run_tests, check, git_*, find_files, github_*)
1371 // live in `structured.rs`. Mutating ones respect the plan gate.
1372 if matches!(other, "run_tests" | "check") && plan_gated(&ctx.store, task_id) {
1373 plan_gate_message().to_string()
1374 } else {
1375 let task = ctx.store.get_task(task_id).ok().flatten();
1376 match task {
1377 Some(t) => match crate::structured::dispatch(ctx, task_id, slot, &t, other, &args).await {
1378 Some(result) => result,
1379 None => unknown_tool(other),
1380 },
1381 None => unknown_tool(other),
1382 }
1383 }
1384 },
1385 };
1386 finish_dispatch(ctx, task_id, &call.function.name, &raw)
1387}
1388
1389/// Append a `[loaded rules: a/AGENTS.md, ...]` note when per-path auto-load
1390/// picked up new rules files during this tool call.
1391async fn with_loaded_rules_note(
1392 ctx: &DriverCtx,
1393 task_id: i64,
1394 slot: u32,
1395 path: &str,
1396 body: String,
1397) -> String {
1398 let newly = ensure_rules_for_path(ctx, task_id, slot, path).await;
1399 if newly.is_empty() {
1400 body
1401 } else {
1402 format!("{body}\n[loaded rules: {}]", newly.join(", "))
1403 }
1404}
1405
1406/// Truncate + scrub a tool result, emit the `tool_result` event, and return
1407/// the text fed back to the model.
1408fn finish_dispatch(ctx: &DriverCtx, task_id: i64, name: &str, raw: &str) -> ToolEffect {
1409 let (text, truncated) = truncate_result(raw);
1410 let text = scrub_secrets(&text);
1411 ctx.emit(task_id, EVENT_TOOL_RESULT,
1412 serde_json::json!({"name": name, "truncated": truncated, "result": text}),
1413 );
1414 ToolEffect::Continue {
1415 result_for_model: text,
1416 }
1417}
1418
1419/// Confine a repo-relative path to the module scope (or the rules files).
1420pub(crate) fn check_scope(path: &str, module_scope: &str) -> Result<(), String> {
1421 let dir = module_scope.replace(':', "/");
1422 let dir = dir.trim_matches('/');
1423 let p = path.trim_start_matches('/');
1424 if p == "AGENTS.md" || *p == format!("{dir}/AGENTS.md") {
1425 return Ok(());
1426 }
1427 if dir.is_empty() || p == dir || p.starts_with(&format!("{dir}/")) {
1428 Ok(())
1429 } else {
1430 Err(format!(
1431 "path {path:?} is outside your scope `{dir}/`; stay inside the scope"
1432 ))
1433 }
1434}
1435
1436fn exec_summary(r: &proto::ExecResponse) -> String {
1437 let mut s = format!(
1438 "exit={} timed_out={} killed={} ({}ms)",
1439 r.exit_code
1440 .map(|c| c.to_string())
1441 .unwrap_or_else(|| "killed".to_string()),
1442 r.timed_out,
1443 r.killed,
1444 r.duration_ms,
1445 );
1446 if !r.stdout.is_empty() {
1447 s.push_str("\n--- stdout ---\n");
1448 s.push_str(&r.stdout);
1449 }
1450 if !r.stderr.is_empty() {
1451 s.push_str("\n--- stderr ---\n");
1452 s.push_str(&r.stderr);
1453 }
1454 if r.truncated {
1455 s.push_str("\n[output truncated by runner]");
1456 }
1457 s
1458}
1459
1460/// `finish` (sole call in its turn, already validated) → submits for human
1461/// review WITHOUT pushing:
1462///
1463/// 1. Commit in the sandbox (single squashed commit with the agent's
1464/// `commit_message`).
1465/// 2. Capture the runner diff for `final_diff` (capped ~50 KB).
1466/// 3. Bundle + import into the mirror as `refs/agent-wip/<id>` (reuses the
1467/// park WIP machinery); record `wip_sha`.
1468/// 4. Store `final_diff`, `commit_message`, `summary`; emit the `review`
1469/// event `{summary, commit_message, diff, truncated}`.
1470/// 5. Park as `review` with pending `{kind:"review",
1471/// tool_call_id:<finish id>}`.
1472///
1473/// NO push happens here — Approve pushes. Request-changes arrives as the
1474/// pending `finish` call's tool result on resume; the resumed checkout
1475/// restores the squashed WIP as uncommitted changes vs `base_sha`, so the
1476/// agent keeps editing and calls `finish` again.
1477async fn park_review(
1478 ctx: &DriverCtx,
1479 task_id: i64,
1480 slot: u32,
1481 branch: &str,
1482 call: &ToolCall,
1483 summary: &str,
1484 commit_message: &str,
1485) -> TaskOutcome {
1486 // Runner diff FIRST (pre-commit working tree vs base) for final_diff.
1487 let review_diff = match ctx.runner.diff(slot).await {
1488 Ok(d) => {
1489 let full = if d.diff.trim().is_empty() {
1490 d.stat.clone()
1491 } else {
1492 format!("{}\n{}", d.stat, d.diff)
1493 };
1494 full
1495 }
1496 Err(e) => {
1497 // Validation already saw a diff earlier this turn; a transient
1498 // read failure now fails loudly rather than submitting blind.
1499 return fail(ctx, task_id, &format!("review diff read: {e}")).await;
1500 }
1501 };
1502 // Single squashed commit with the agent's message.
1503 let _sha = match ctx.runner.commit(slot, commit_message).await {
1504 Ok(r) => r.sha,
1505 Err(e) => return fail(ctx, task_id, &format!("runner commit: {e}")).await,
1506 };
1507 ctx.emit(task_id, EVENT_STATUS,
1508 serde_json::json!({"message": format!("committed {_sha}"), "sha": _sha}),
1509 );
1510 // Bundle → mirror WIP import (same machinery as park).
1511 let bundle = match ctx.runner.bundle(slot).await {
1512 Ok(b) => b,
1513 Err(e) => return fail(ctx, task_id, &format!("bundle download: {e}")).await,
1514 };
1515 let tmp = match write_temp_bundle(&bundle) {
1516 Ok(t) => t,
1517 Err(e) => return fail(ctx, task_id, &format!("temp bundle file: {e}")).await,
1518 };
1519 let wip_sha = match crate::git::import_wip_bundle(
1520 &ctx.config.mirror_dir,
1521 &tmp,
1522 branch,
1523 task_id,
1524 )
1525 .await
1526 {
1527 Ok(sha) => sha,
1528 Err(e) => return fail(ctx, task_id, &format!("wip bundle import: {e}")).await,
1529 };
1530 // Store the review snapshot + emit the review event, then park.
1531 let (final_diff, truncated) = cap_final_diff(&review_diff);
1532 let _ = ctx.store.set_review(task_id, &wip_sha, &final_diff, commit_message, summary);
1533 // A Stop arriving during commit/bundle is honored after import.
1534 if stop_requested(&ctx.store, task_id) {
1535 let pending = Pending::new(
1536 PENDING_STOPPED,
1537 None,
1538 serde_json::json!({"message": "stopped by operator; work kept"}),
1539 );
1540 return finish_park(ctx, task_id, TaskStatus::NeedsInput, pending, Some(&wip_sha));
1541 }
1542 ctx.emit(task_id, EVENT_REVIEW,
1543 serde_json::json!({
1544 "summary": summary,
1545 "commit_message": commit_message,
1546 "diff": final_diff,
1547 "truncated": truncated,
1548 }),
1549 );
1550 let pending = Pending::new(
1551 PENDING_REVIEW,
1552 Some(call.id.clone()),
1553 serde_json::json!({
1554 "summary": summary,
1555 "commit_message": commit_message,
1556 }),
1557 );
1558 finish_park(ctx, task_id, TaskStatus::Review, pending, Some(&wip_sha))
1559}