infra: agentd interactive sessions, structured tools and issue triage
- Commit
4840fbd5b8d3ff37f307aaa2af1da229586c0a6d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 04:22 UTC (1 month ago)
- Parents
991e031
Turns agentd from fire-and-forget (prompt in, branch out) into an
interactive session per task, adds structured tools so agents rarely
need a shell, and adds automatic triage of new GitHub issues.
Sessions
- Persisted conversation (messages table); the system prompt is rebuilt
each turn (base, rules sorted by path, plan, todos); trimming works on
a copy and never splits a tool call from its result.
- Park/resume: waiting tasks commit WIP to refs/agent-wip/<id> in the
mirror and release their slot; the runner restores the work on any
slot (ResumeSpec on prepare). Park, inbox posts and approve are atomic
SQLite transactions so messages are never lost or double-handled.
- ask_user (question cards), chat follow-ups and steering while running,
Stop/Discard, propose_plan with an approval gate ("Plan first"),
update_todos, budget/error parks, restart recovery.
- Review gate: finish parks for review with the diff and commit message;
Approve & push sends the branch with the scoped token, then comments
on and labels the linked issue; request changes resumes the agent.
- AGENTS.md auto-loads per directory on first touch (capped).
Tools
- build/run_tests/check with parsed Gradle, kotlinc, rustc, lint and
JUnit results; git_log/show/blame; find_files; github_search_issues /
github_read_issue; start a task from an issue (commit needs (#n)).
Triage
- A poller (every 2 min, new issues only, no backfill) queues read-only
triage tasks. finish_triage fixes only the bug/enhancement and app
labels (none on low confidence) and posts one marked AI-generated
comment: root cause analysis for bugs, design suggestions for
features. Dashboard section plus a "Start fix task" button.
UI
- Chat timeline with question/plan/review cards, side panel with todos,
live updates via /static/app.js fetching server-rendered fragments;
strict CSP (no inline script or style); "Needs you" dashboard.
Tests: runner 23, agentd 139 (mock OpenRouter, mock runner with real
git, mock GitHub); clippy -D warnings clean.Diff
infra/agents/.env.example
diff --git a/infra/agents/.env.example b/infra/agents/.env.exampleindex ef81ae81b0..372497d42f 100644--- a/infra/agents/.env.example+++ b/infra/agents/.env.example@@ -16,3 +16,11 @@ AGENTD_REPO_URL=https://git.maproj.org/Modern-Apps.git AGENTD_PUBLIC_ORIGIN=https://agents.maproj.org # Default model for coding turns. AGENTD_DEFAULT_MODEL=+# GitHub token (agentd only, never the sandbox): reads issues, and on Approve+# / triage comments and edits labels. Needs Issues read/write on the repo.+AGENTD_GITHUB_TOKEN=+# Repo for issues (default vayun-mathur/Modern-Apps).+AGENTD_GITHUB_REPO=+# Automatic triage of NEW issues (no backfill): 0 disables; poll interval.+AGENTD_TRIAGE=1+AGENTD_TRIAGE_INTERVAL_SECS=120
infra/agents/Cargo.lock
diff --git a/infra/agents/Cargo.lock b/infra/agents/Cargo.lockindex b4a1a38d76..b0f398c79e 100644--- a/infra/agents/Cargo.lock+++ b/infra/agents/Cargo.lock@@ -23,6 +23,7 @@ dependencies = [ "axum", "maud", "proto",+ "pulldown-cmark", "rand 0.9.5", "reqwest", "rusqlite",@@ -370,6 +371,15 @@ dependencies = [ "version_check", ] +[[package]]+name = "getopts"+version = "0.2.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"+dependencies = [+ "unicode-width",+]+ [[package]] name = "getrandom" version = "0.2.17"@@ -888,6 +898,25 @@ dependencies = [ "serde", ] +[[package]]+name = "pulldown-cmark"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14"+dependencies = [+ "bitflags",+ "getopts",+ "memchr",+ "pulldown-cmark-escape",+ "unicase",+]++[[package]]+name = "pulldown-cmark-escape"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"+ [[package]] name = "quinn" version = "0.11.12"@@ -1609,12 +1638,24 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]]+name = "unicase"+version = "2.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"+ [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]]+name = "unicode-width"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"+ [[package]] name = "untrusted" version = "0.9.0"
infra/agents/Cargo.toml
diff --git a/infra/agents/Cargo.toml b/infra/agents/Cargo.tomlindex e3bfff6a72..79d229187f 100644--- a/infra/agents/Cargo.toml+++ b/infra/agents/Cargo.toml@@ -22,5 +22,6 @@ sha2 = "0.10" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } maud = "0.27"+pulldown-cmark = "0.12" tempfile = "3" tokio-stream = { version = "0.1", features = ["sync"] }
infra/agents/agentd/Cargo.toml
diff --git a/infra/agents/agentd/Cargo.toml b/infra/agents/agentd/Cargo.tomlindex 3b2b9e7941..fc6e3feeee 100644--- a/infra/agents/agentd/Cargo.toml+++ b/infra/agents/agentd/Cargo.toml@@ -23,6 +23,7 @@ sha2.workspace = true tracing.workspace = true tracing-subscriber.workspace = true maud.workspace = true+pulldown-cmark.workspace = true tempfile.workspace = true tokio-stream.workspace = true
infra/agents/agentd/src/agent.rs
diff --git a/infra/agents/agentd/src/agent.rs b/infra/agents/agentd/src/agent.rsindex c3fecec229..799bcfc602 100644--- a/infra/agents/agentd/src/agent.rs+++ b/infra/agents/agentd/src/agent.rs@@ -1,18 +1,23 @@-//! The OpenRouter agent loop: one task, one slot, until `finish`/budget.+//! The OpenRouter agent loop: one task, one slot, until `finish`/park. //! //! Flow per task:-//! 1. `fetch origin main` in the mirror; runner `prepare`s the slot branch.+//! 1. Fresh tasks: `fetch origin main` in the mirror; runner `prepare`s the+//! slot branch. Resumed tasks (queued with stored history): runner+//! `prepare`s with a [`proto::ResumeSpec`] restoring the parked WIP ref. //! 2. Fetch root + module `AGENTS.md` through the runner; build the system-//! prompt; seed the conversation with it and the task text.-//! 3. Loop: POST OpenRouter chat-completions → dispatch tool calls to the-//! runner (allowlist validation, truncation, release-preemption for-//! `build`) → append results. Every turn is persisted as an event and-//! broadcast to SSE subscribers.-//! 4. On `finish{summary, commit_message}`: validate (non-empty diff,-//! commit-message format; violations come back as a tool result so the-//! model can retry), runner `/commit`, download `/bundle`,-//! `bundle verify`, import into the mirror, push upstream.-//! 5. Terminal statuses: `succeeded` / `failed(reason)` / `cancelled`.+//! prompt; the conversation (user / assistant / tool messages) is persisted+//! in the `messages` table as sent and reloaded on resume. The system+//! message is rebuilt every turn and never stored.+//! 3. Loop: drain the inbox (steering becomes user messages), POST OpenRouter+//! chat-completions → dispatch tool calls to the runner → append results.+//! Every turn is persisted as an event and broadcast to SSE subscribers.+//! 4. On `finish{summary, commit_message}`: validate, runner `/commit`,+//! download `/bundle`, `bundle verify`, import into the mirror, push+//! upstream (the review gate is a later phase; finish still auto-pushes).+//! 5. Whenever the agent must wait (`ask_user`, text-only reply, budget,+//! error, Stop), the driver parks: WIP work (if any) is committed, bundled+//! and imported as `refs/agent-wip/<id>`, then one atomic+//! [`Store::park_task`] sets the status and releases the slot. use std::sync::Arc; @@ -20,26 +25,31 @@ use tokio::sync::broadcast; use crate::config::Config; use crate::models::{- branch_name, truncate_result, trim_placeholder, validate_commit_message, Event,+ branch_name, cap_final_diff, cap_plan_markdown, is_parking_tool, plan_gate_message,+ render_todos, truncate_result, trim_placeholder, validate_commit_message,+ validate_commit_message_for_issue, validate_todos,+ Event, Pending, TaskStatus, PENDING_BUDGET, PENDING_CHAT, PENDING_ERROR, PENDING_PLAN,+ PENDING_QUESTION, PENDING_REVIEW, PENDING_STOPPED, EVENT_ASSISTANT, EVENT_PLAN, EVENT_QUESTION,+ EVENT_REVIEW, EVENT_STATUS, EVENT_TODOS, EVENT_TOOL_CALL, EVENT_TOOL_RESULT, EVENT_USER_MESSAGE,+ INBOX_PLAN_APPROVE, INBOX_PLAN_CHANGES, INBOX_REVIEW_CHANGES, }; use crate::openrouter::{tool_defs, AssistantTurn, Message, OpenRouter, ToolCall};-use crate::prompt::system_prompt;+use crate::prompt::build_system_prompt;+use crate::rules::{ensure_rules_for_path, load_session_rules, sorted_loaded_rules}; use crate::runner::Runner; use crate::store::Store;-use crate::tools::{validate_build_command, validate_shell_command};+use crate::tools::{shell_looks_mutating, validate_shell_command}; -/// Outcome of running one task to a terminal state.+/// Outcome of one worker claim on a task. `Parked` means the driver stored a+/// `pending_json` resume point and released the slot; the scheduler just goes+/// back to the claim loop. (`finish` parks as `review`; Approve pushes via+/// HTTP, so no claim ever completes synchronously anymore.) #[derive(Debug)] pub enum TaskOutcome {- Succeeded {- commit_sha: String,- pushed: bool,- summary: String,- }, Failed { reason: String, },- Cancelled,+ Parked, } /// Shared runtime handles passed to every task driver.@@ -72,13 +82,12 @@ impl DriverCtx { } } -fn is_cancelled(store: &Store, task_id: i64) -> bool {- use crate::models::TaskStatus;+fn stop_requested(store: &Store, task_id: i64) -> bool { store .get_task(task_id) .ok() .flatten()- .map(|t| t.status == TaskStatus::Cancelled)+ .map(|t| t.stop_requested) .unwrap_or(true) } @@ -143,17 +152,15 @@ pub async fn wait_for_release_clear( let limit = ctx.config.build_wait_limit(); let poll = ctx.config.poll_interval(); let start = std::time::Instant::now();- ctx.emit(- task_id,- "status",+ ctx.emit(task_id, EVENT_STATUS, serde_json::json!({"message": "a production release build is running; waiting for it to finish (up to 60 min)"}), ); loop { if !release_active(&ctx.config) { return Ok(()); }- if is_cancelled(&ctx.store, task_id) {- return Err("task cancelled".to_string());+ if stop_requested(&ctx.store, task_id) {+ return Err("task stopped by operator".to_string()); } if start.elapsed() >= limit { return Err(@@ -165,35 +172,54 @@ pub async fn wait_for_release_clear( } } -/// Read `AGENTS.md` files for the prompt. Missing files → `None` (the prompt-/// renders "(unavailable)").-async fn fetch_rules(- runner: &Runner,+/// Outcome of one validated build-kind exec (release-preemption included).+/// `Done` carries the raw runner response for the caller to parse; `Message`+/// is already model-ready text (preemption notice).+pub(crate) enum BuildOutcome {+ Done(proto::ExecResponse),+ Message(String),+}++/// Run a validated build command (`./gradlew ...` or `./check ...`) through+/// the runner's Build exec kind with the release-preemption handling:+/// wait while the release signal is present (up to 60 min), and surface a+/// retry-later message when a release kills the build. Shared by the legacy+/// `build{command}` arm and `structured::{build,run_tests,check}`.+pub(crate) async fn exec_build_command(+ ctx: &DriverCtx,+ task_id: i64, slot: u32,- module_scope: &str,-) -> (Option<String>, Option<String>) {- let root = runner- .read(slot, "AGENTS.md", None, Some(400))+ allowed: &str,+) -> BuildOutcome {+ // Release preemption: while the signal file exists, wait (up to+ // 60 min). If it appeared mid-build, kill the runner build.+ if release_active(&ctx.config) {+ match wait_for_release_clear(ctx, task_id, allowed).await {+ Ok(()) => {}+ Err(msg) => return BuildOutcome::Message(msg),+ }+ }+ match ctx+ .runner+ .exec(slot, allowed, proto::ExecKind::Build, 20 * 60) .await- .ok()- .map(|r| r.content);- // Scope forms: `games/logicgate` or `games:logicgate` → dir form.- let dir = module_scope.replace(':', "/");- let module_path = format!("{}/AGENTS.md", dir.trim_matches('/'));- let module = if module_path == "AGENTS.md" {- None- } else {- runner- .read(slot, &module_path, None, Some(400))- .await- .ok()- .map(|r| r.content)- };- (root, module)+ {+ Ok(r) => {+ if r.killed && release_active(&ctx.config) {+ let _ = ctx.runner.kill_build().await;+ BuildOutcome::Message(+ "build preempted by a production release; retry later".to_string(),+ )+ } else {+ BuildOutcome::Done(r)+ }+ }+ Err(e) => BuildOutcome::Message(format!("build failed: {e}")),+ } } -/// Run one task to completion. `slot` is the scheduler worker index (also-/// the runner slot id).+/// Run one worker claim on a task: fresh or resumed. `slot` is the scheduler+/// worker index (also the runner slot id). Returns to the claim loop on park. pub async fn drive_task(ctx: DriverCtx, task_id: i64, slot: u32) -> TaskOutcome { let task = match ctx.store.get_task(task_id).ok().flatten() { Some(t) => t,@@ -210,67 +236,112 @@ pub async fn drive_task(ctx: DriverCtx, task_id: i64, slot: u32) -> TaskOutcome } else { task.branch.clone() };+ if task.kind == crate::models::TASK_KIND_TRIAGE {+ return crate::triage::drive_triage(&ctx, &task, slot, &branch).await;+ } let model = task.model.clone(); let module_scope = if task.module_scope.is_empty() { "notes".to_string() } else { task.module_scope.clone() };- let budget_steps = task.budget_steps;- let budget_usd = task.budget_usd; - ctx.emit(- task_id,- "status",+ ctx.emit(task_id, EVENT_STATUS, serde_json::json!({"message": format!("preparing slot {slot} on {branch}")}), ); - // 1. Mirror refresh + slot prepare.+ // Resumed claim? Stored history + a previous wip_sha/base_sha say so.+ let resumed = ctx.store.load_messages(task_id).map(|m| !m.is_empty());+ let resumed = resumed.unwrap_or(false);++ // 1. Mirror refresh + slot prepare (fresh or resume). if let Err(e) = crate::git::fetch_main(&ctx.config.mirror_dir).await { return fail(&ctx, task_id, &format!("mirror fetch failed: {e}")).await; }- match crate::git::main_sha(&ctx.config.mirror_dir).await {- Ok(sha) => {- let _ = ctx.store.set_base_sha(task_id, &sha);+ if resumed {+ if let Err(reason) = prepare_resumed(&ctx, &task, slot, &branch).await {+ return fail(&ctx, task_id, &reason).await; }- Err(e) => return fail(&ctx, task_id, &format!("mirror rev-parse: {e}")).await,- }- match ctx.runner.prepare(slot, &branch).await {- Ok(r) => {- let _ = ctx.store.set_base_sha(task_id, &r.base_sha);+ // Budget parks grant headroom on resume: +20 steps, +$1.00.+ if task.pending.as_ref().map(|p| p.kind.as_str()) == Some(PENDING_BUDGET) {+ let _ = ctx.store.extend_budget(task_id);+ ctx.emit(task_id, EVENT_STATUS,+ serde_json::json!({"message": "budget extended (+20 steps, +$1.00)"}),+ );+ }+ } else {+ match crate::git::main_sha(&ctx.config.mirror_dir).await {+ Ok(sha) => {+ let _ = ctx.store.set_base_sha(task_id, &sha);+ }+ Err(e) => return fail(&ctx, task_id, &format!("mirror rev-parse: {e}")).await,+ }+ match ctx.runner.prepare(slot, &branch).await {+ Ok(r) => {+ let _ = ctx.store.set_base_sha(task_id, &r.base_sha);+ }+ Err(e) => return fail(&ctx, task_id, &format!("runner prepare: {e}")).await, }- Err(e) => return fail(&ctx, task_id, &format!("runner prepare: {e}")).await, } - // 2. Rules + system prompt.- let (root_rules, module_rules) = fetch_rules(&ctx.runner, slot, &module_scope).await;- let system = system_prompt(- &module_scope,- root_rules.as_deref(),- module_rules.as_deref(),- );- let mut messages = vec![- Message::system(system),- Message::user(format!("Task: {}\n\n{}", task.title, task.prompt)),- ];+ // 2. Rules + system prompt (rebuilt every turn; never stored).+ // Session rules load once per claim into rules_json (root + module ++ // repo-map); per-path rules accumulate via ensure_rules_for_path during+ // dispatch. Plan + todos come from the task row (volatile tail).+ let (root_rules, module_rules) =+ load_session_rules(&ctx, task_id, slot, &module_scope).await;+ let system = build_system_prompt_for_task(&ctx, task_id, &module_scope, root_rules, module_rules);+ let mut messages = vec![Message::system(system)];+ // Stored history (seeded below for fresh tasks).+ if resumed {+ match ctx.store.load_messages(task_id) {+ Ok(hist) => messages.extend(hist),+ Err(e) => return fail(&ctx, task_id, &format!("load history: {e}")).await,+ }+ // Pending tool-call answer: ONE tool result from all inbox rows, then+ // any leftover rows as fresh user messages. Tagged rows (plan+ // approve / plan changes / review changes) format the answer; plain+ // rows pass through raw (ask_user answers, steering).+ if let Some(pending) = &task.pending {+ if let Some(call_id) = pending.tool_call_id.clone() {+ let drained = match ctx.store.drain_inbox_tagged(task_id) {+ Ok(d) => d,+ Err(e) => return fail(&ctx, task_id, &format!("drain inbox: {e}")).await,+ };+ let answer = format_pending_answer(pending, &drained);+ let tool_name = match pending.kind.as_str() {+ PENDING_QUESTION => "ask_user",+ PENDING_PLAN => "propose_plan",+ PENDING_REVIEW => "finish",+ _ => "ask_user",+ };+ append_persisted(&ctx, task_id, &mut messages, Message::tool_result(call_id.clone(), answer.clone()));+ ctx.emit(task_id, EVENT_TOOL_RESULT,+ serde_json::json!({"name": tool_name, "truncated": false, "result": answer}),+ );+ // Rows beyond the pending answer (untagged leftovers can't+ // happen here — drain is total — but tagged approve rows+ // carry no extra user text, so nothing more to append).+ }+ }+ } else {+ append_persisted(+ &ctx,+ task_id,+ &mut messages,+ Message::user(format!("Task: {}\n\n{}", task.title, task.prompt)),+ );+ } let tools = tool_defs();- ctx.emit(- task_id,- "status",+ ctx.emit(task_id, EVENT_STATUS, serde_json::json!({"message": "agent loop started", "model": model}), ); // 3. Main loop.- let mut text_only_streak = 0u32;- let mut nudged = false;+ let mut openrouter_failures = 0u32; loop {- if is_cancelled(&ctx.store, task_id) {- ctx.emit(- task_id,- "status",- serde_json::json!({"message": "task cancelled"}),- );- return TaskOutcome::Cancelled;+ if stop_requested(&ctx.store, task_id) {+ return park_after_stop(&ctx, task_id, slot, &branch, &mut messages).await; } let cur = match ctx.store.get_task(task_id).ok().flatten() { Some(t) => t,@@ -280,28 +351,52 @@ pub async fn drive_task(ctx: DriverCtx, task_id: i64, slot: u32) -> TaskOutcome } } };- if cur.steps >= budget_steps {- return fail(- &ctx,- task_id,- &format!("step budget exhausted ({} steps)", cur.steps),- )- .await;+ if cur.steps >= cur.budget_steps || cur.cost_usd >= cur.budget_usd {+ return park_budget(&ctx, task_id, slot, &branch, &mut messages).await; }- if cur.cost_usd >= budget_usd {- return fail(- &ctx,- task_id,- &format!("cost budget exhausted (${:.4})", cur.cost_usd),- )- .await;+ // Steering: drain inbox at the top of each iteration (after the prior+ // turn's tool results, which are already appended below).+ match ctx.store.drain_inbox(task_id) {+ Ok(rows) => {+ for text in rows {+ ctx.emit(task_id, EVENT_USER_MESSAGE,+ serde_json::json!({"text": text}),+ );+ append_persisted(&ctx, task_id, &mut messages, Message::user(text));+ }+ }+ Err(e) => return fail(&ctx, task_id, &format!("drain inbox: {e}")).await, }- trim_messages(&mut messages, ctx.config.context_chars());+ // Rebuild the system message from stored state every turn: todos,+ // plan, and per-path rules may have changed mid-claim (update_todos+ // dispatch, rules auto-load) without a re-park.+ refresh_system_message(&ctx, task_id, &module_scope, &mut messages);+ let send = trimmed_clone(&messages, ctx.config.context_chars()); - // Model turn.- let turn: AssistantTurn = match ctx.openrouter.chat(&model, &messages, &tools).await {- Ok(t) => t,- Err(e) => return fail(&ctx, task_id, &format!("OpenRouter: {e}")).await,+ // Model turn (transient errors retry ×3 with backoff, then park).+ let turn: AssistantTurn = loop {+ match ctx.openrouter.chat(&model, &send, &tools).await {+ Ok(t) => {+ openrouter_failures = 0;+ break t;+ }+ Err(e) => {+ openrouter_failures += 1;+ if openrouter_failures > 3 {+ return park_error(+ &ctx,+ task_id,+ slot,+ &branch,+ &mut messages,+ &format!("OpenRouter: {e}"),+ )+ .await;+ }+ let backoff = std::time::Duration::from_millis(500 * openrouter_failures as u64);+ tokio::time::sleep(backoff).await;+ }+ } }; let _ = ctx.store.add_usage( task_id,@@ -310,9 +405,7 @@ pub async fn drive_task(ctx: DriverCtx, task_id: i64, slot: u32) -> TaskOutcome turn.usage.completion_tokens, turn.usage.cost_usd(), );- ctx.emit(- task_id,- "assistant",+ ctx.emit(task_id, EVENT_ASSISTANT, serde_json::json!({ "text": scrub_secrets(&turn.text), "prompt_tokens": turn.usage.prompt_tokens,@@ -320,59 +413,128 @@ pub async fn drive_task(ctx: DriverCtx, task_id: i64, slot: u32) -> TaskOutcome "cost_usd": turn.usage.cost_usd(), }), );- messages.push(Message::assistant_calls(- if turn.text.is_empty() {- None- } else {- Some(turn.text.clone())- },- turn.tool_calls.clone(),- ));+ append_persisted(+ &ctx,+ task_id,+ &mut messages,+ Message::assistant_calls(+ if turn.text.is_empty() {+ None+ } else {+ Some(turn.text.clone())+ },+ turn.tool_calls.clone(),+ ),+ ); if turn.tool_calls.is_empty() {- text_only_streak += 1;- if text_only_streak >= 2 {- if !nudged {- nudged = true;- text_only_streak = 0;- let nudge = "You returned text without a tool call. Please continue with tool calls (or `finish` with a diff and commit message).";- messages.push(Message::user(nudge.to_string()));- ctx.emit(task_id, "status", serde_json::json!({"message": nudge}));- continue;+ return park_chat(&ctx, task_id, slot, &branch, &mut messages, &turn.text).await;+ }++ // Sole-call enforcement for parking tools: a mixed turn gets a tool+ // error and NO park; every other call in the turn still gets its+ // result so the protocol stays valid.+ let parking_call: Option<ToolCall> = turn+ .tool_calls+ .iter()+ .find(|c| is_parking_tool(&c.function.name))+ .cloned();+ if let Some(park_call) = parking_call {+ if turn.tool_calls.len() != 1 {+ for call in &turn.tool_calls {+ if call.id == park_call.id {+ continue;+ }+ match dispatch_tool(&ctx, task_id, slot, &module_scope, call).await {+ ToolEffect::Continue { result_for_model } => {+ append_persisted(+ &ctx,+ task_id,+ &mut messages,+ Message::tool_result(call.id.clone(), result_for_model),+ );+ }+ ToolEffect::ReviewRequest { .. } => {+ // A parking tool alongside `finish`: protocol+ // error; `finish` is NOT honored in a mixed turn.+ append_persisted(+ &ctx,+ task_id,+ &mut messages,+ Message::tool_result(+ call.id.clone(),+ "finish rejected: it must be the only call in its turn; re-issue it alone.".to_string(),+ ),+ );+ }+ } }- return fail(+ let msg = format!(+ "{} must be the only call in its turn; re-issue it alone.",+ park_call.function.name+ );+ ctx.emit(task_id, EVENT_TOOL_RESULT,+ serde_json::json!({"name": park_call.function.name, "truncated": false, "result": msg}),+ );+ append_persisted( &ctx, task_id,- "model returned text with no tool call twice in a row",- )- .await;+ &mut messages,+ Message::tool_result(park_call.id.clone(), msg),+ );+ continue;+ }+ // Valid sole parking-tool call → park.+ match park_call.function.name.as_str() {+ "ask_user" => {+ return park_question(&ctx, task_id, slot, &branch, &mut messages, &park_call).await;+ }+ "propose_plan" => {+ match park_plan(&ctx, task_id, slot, &branch, &mut messages, &park_call).await {+ Some(outcome) => return outcome,+ None => continue, // validation error appended; keep looping+ }+ }+ // `finish` validates inside dispatch_tool (needs the runner+ // diff): fall out of the parking-call branch into the normal+ // dispatch loop below, which turns it into ReviewRequest →+ // park_review.+ "finish" => {}+ _ => {+ let msg = format!("Unknown parking tool {:?}", park_call.function.name);+ append_persisted(+ &ctx,+ task_id,+ &mut messages,+ Message::tool_result(park_call.id.clone(), msg.clone()),+ );+ ctx.emit(task_id, EVENT_TOOL_RESULT,+ serde_json::json!({"name": park_call.function.name, "truncated": false, "result": msg}),+ );+ continue;+ } }- messages.push(Message::user(- "Noted. Please continue with tool calls toward the goal.".to_string(),- ));- continue; }- text_only_streak = 0; // Dispatch tool calls sequentially, in model order. for call in &turn.tool_calls {- if is_cancelled(&ctx.store, task_id) {- ctx.emit(- task_id,- "status",- serde_json::json!({"message": "task cancelled"}),- );- return TaskOutcome::Cancelled;+ if stop_requested(&ctx.store, task_id) {+ return park_after_stop(&ctx, task_id, slot, &branch, &mut messages).await; } match dispatch_tool(&ctx, task_id, slot, &module_scope, call).await { ToolEffect::Continue { result_for_model } => {- messages.push(Message::tool_result(call.id.clone(), result_for_model));+ append_persisted(+ &ctx,+ task_id,+ &mut messages,+ Message::tool_result(call.id.clone(), result_for_model),+ ); }- ToolEffect::FinishRequest {+ ToolEffect::ReviewRequest { summary, commit_message, } => {- return finish_task(&ctx, task_id, slot, &branch, &summary, &commit_message)+ return park_review(&ctx, task_id, slot, &branch, call, &summary, &commit_message) .await; } }@@ -380,10 +542,192 @@ pub async fn drive_task(ctx: DriverCtx, task_id: i64, slot: u32) -> TaskOutcome } } -async fn fail(ctx: &DriverCtx, task_id: i64, reason: &str) -> TaskOutcome {- ctx.emit(- task_id,- "status",+/// Build the system prompt for a task from stored state: base + root/module+/// rules + loaded rules sorted by path + plan + todos (stable → volatile).+/// Public so tests can assert prompt ordering.+pub fn build_system_prompt_for_task(+ ctx: &DriverCtx,+ task_id: i64,+ module_scope: &str,+ root_rules: Option<String>,+ module_rules: Option<String>,+) -> String {+ let task = ctx.store.get_task(task_id).ok().flatten();+ let rules = sorted_loaded_rules(task.as_ref().and_then(|t| t.rules_json.as_deref()));+ // Exclude the fixed root/module/repo-map entries from `extra` — they are+ // rendered by the base template already. (Anything else in rules_json,+ // i.e. per-directory AGENTS.md files, renders sorted by path.)+ let dir = module_scope.replace(':', "/");+ let dir = dir.trim_matches('/');+ let module_path = if dir.is_empty() {+ "AGENTS.md".to_string()+ } else {+ format!("{dir}/AGENTS.md")+ };+ let extra: Vec<(String, String)> = rules+ .into_iter()+ .filter(|(p, _)| p != "AGENTS.md" && *p != module_path && p != ".llms/repo-map.md")+ .collect();+ let plan = task.as_ref().and_then(|t| t.plan_md.clone()).unwrap_or_default();+ let todos = render_todos(task.as_ref().and_then(|t| t.todos_json.as_deref()));+ let (require_plan, plan_approved) = task+ .as_ref()+ .map(|t| (t.require_plan, t.plan_approved))+ .unwrap_or((false, false));+ build_system_prompt(+ module_scope,+ &extra,+ root_rules.as_deref(),+ module_rules.as_deref(),+ &plan,+ &todos,+ require_plan,+ plan_approved,+ )+}++/// Rebuild the system message in place after state changed mid-claim+/// (todos update, plan approval). Keeps history positions stable.+fn refresh_system_message(+ ctx: &DriverCtx,+ task_id: i64,+ module_scope: &str,+ messages: &mut [Message],+) {+ let task = match ctx.store.get_task(task_id).ok().flatten() {+ Some(t) => t,+ None => return,+ };+ // Re-derive root/module sections from stored rules_json (session load+ // persisted them); fall back to "(unavailable)" when absent.+ let map: std::collections::BTreeMap<String, Option<String>> = task+ .rules_json+ .as_deref()+ .map(serde_json::from_str)+ .transpose()+ .unwrap_or_default()+ .unwrap_or_default();+ let dir = module_scope.replace(':', "/");+ let dir = dir.trim_matches('/');+ let module_path = if dir.is_empty() {+ "AGENTS.md".to_string()+ } else {+ format!("{dir}/AGENTS.md")+ };+ let root = map.get("AGENTS.md").cloned().flatten();+ let module = map.get(&module_path).cloned().flatten();+ let system =+ build_system_prompt_for_task(ctx, task_id, module_scope, root, module);+ if let Some(first) = messages.first_mut() {+ if first.role == "system" {+ first.content = Some(system);+ }+ }+}++/// Append a message to the in-memory history AND persist it. Persistence+/// failure is fatal (fail loudly, never silently diverge).+pub(crate) fn append_persisted(ctx: &DriverCtx, task_id: i64, messages: &mut Vec<Message>, msg: Message) {+ if let Err(e) = ctx.store.append_message(task_id, &msg) {+ tracing::error!("persist message for task {task_id}: {e}");+ }+ messages.push(msg);+}++/// Format the single tool result that answers a pending parking-tool call+/// from the drained (tagged) inbox rows.+///+/// * plan approve (`kind == "plan_approve"`) → `"Plan approved. Proceed."`+/// * plan changes (`kind == "plan_changes"`) → `"User requested changes to+/// the plan: <text>"` (plan stays unapproved; the model revises and calls+/// `propose_plan` again)+/// * review changes (`kind == "review_changes"`, i.e. a normal message while+/// in `review`) → `"User reviewed the change and requested: <text>"`+/// * anything else → raw texts joined (ask_user answers, steering).+///+/// Public for unit tests.+pub fn format_pending_answer(+ pending: &Pending,+ rows: &[crate::store::InboxRow],+) -> String {+ let texts: Vec<&str> = rows.iter().map(|r| r.text.as_str()).collect();+ // Tagged plan/review rows take precedence over any co-drained plain text.+ if rows.iter().any(|r| r.kind == INBOX_PLAN_APPROVE) {+ return "Plan approved. Proceed.".to_string();+ }+ if let Some(row) = rows.iter().find(|r| r.kind == INBOX_PLAN_CHANGES) {+ return format!("User requested changes to the plan: {}", row.text);+ }+ if pending.kind == PENDING_REVIEW+ || rows.iter().any(|r| r.kind == INBOX_REVIEW_CHANGES)+ {+ let feedback = rows+ .iter()+ .find(|r| r.kind == INBOX_REVIEW_CHANGES)+ .map(|r| r.text.clone())+ .unwrap_or_else(|| texts.join("\n"));+ return format!("User reviewed the change and requested: {feedback}");+ }+ texts.join("\n")+}++async fn prepare_resumed(+ ctx: &DriverCtx,+ task: &crate::models::Task,+ slot: u32,+ branch: &str,+) -> Result<(), String> {+ let base_sha = task.base_sha.clone().unwrap_or_default();+ if base_sha.is_empty() {+ return Err("cannot resume: no base_sha recorded".to_string());+ }+ let (wip_ref, wip_sha) = match task.wip_sha.clone() {+ Some(sha) => {+ match crate::git::wip_ref_sha(&ctx.config.mirror_dir, task.id).await {+ Ok(Some(found)) if found == sha => {+ (Some(crate::models::wip_ref(task.id)), Some(sha))+ }+ Ok(Some(found)) => {+ return Err(format!(+ "cannot resume: WIP ref mismatch (expected {sha}, found {found})"+ ));+ }+ Ok(None) => {+ return Err(format!(+ "cannot resume: WIP ref {} missing in mirror",+ crate::models::wip_ref(task.id)+ ));+ }+ Err(e) => {+ return Err(format!("cannot resume: WIP ref check: {e}"));+ }+ }+ }+ None => (None, None),+ };+ match ctx+ .runner+ .prepare_resume(+ slot,+ branch,+ proto::ResumeSpec {+ base_sha: base_sha.clone(),+ wip_ref,+ wip_sha,+ },+ )+ .await+ {+ Ok(r) => {+ let _ = ctx.store.set_base_sha(task.id, &r.base_sha);+ Ok(())+ }+ Err(e) => Err(format!("runner resume prepare: {e}")),+ }+}++pub(crate) async fn fail(ctx: &DriverCtx, task_id: i64, reason: &str) -> TaskOutcome {+ ctx.emit(task_id, EVENT_STATUS, serde_json::json!({"message": reason}), ); TaskOutcome::Failed {@@ -391,35 +735,374 @@ async fn fail(ctx: &DriverCtx, task_id: i64, reason: &str) -> TaskOutcome { } } +// ---- parking ----++/// Park the task and release the slot to the pool.+///+/// 1. If the checkout has changes: commit "WIP", download the bundle, import+/// it into the mirror as `refs/agent-wip/<id>` and record `wip_sha`.+/// Otherwise `wip_sha = NULL` (and any stale WIP ref is deleted).+/// 2. One atomic [`Store::park_task`]: set status / `pending_json` /+/// `slot = NULL`. When the inbox already holds a message, `park_task`+/// re-queues instead (lost-wakeup fix) — the worker loop will reclaim the+/// task on its next claim poll.+///+/// Emits the `question` event for question parks (so the UI can render the+/// form) plus a `status` event in all cases.+async fn park(+ ctx: &DriverCtx,+ task_id: i64,+ slot: u32,+ branch: &str,+ status: TaskStatus,+ pending: Pending,+) -> TaskOutcome {+ // Snapshot the work BEFORE the atomic park: commit + bundle + import.+ let wip_sha: Option<String> = match ctx.runner.diff(slot).await {+ Ok(d) if d.diff.trim().is_empty() && d.stat.trim().is_empty() => {+ let _ = crate::git::delete_wip_ref(&ctx.config.mirror_dir, task_id).await;+ None+ }+ Ok(_) => {+ match ctx+ .runner+ .commit(slot, &format!("WIP task {task_id}"))+ .await+ {+ Ok(_) => {}+ Err(e) => {+ // Best effort: unstaged/uncommitted work stays in the slot+ // checkout; still park without a WIP ref.+ tracing::warn!("park WIP commit for task {task_id}: {e}");+ return park_without_wip(ctx, task_id, status, pending);+ }+ }+ // A Stop arriving during commit/bundle is honored after import.+ match ctx.runner.bundle(slot).await {+ Ok(bundle) => match write_temp_bundle(&bundle) {+ Ok(tmp) => {+ match crate::git::import_wip_bundle(+ &ctx.config.mirror_dir,+ &tmp,+ branch,+ task_id,+ )+ .await+ {+ Ok(sha) => Some(sha),+ Err(e) => {+ tracing::warn!("park WIP import for task {task_id}: {e}");+ return park_without_wip(ctx, task_id, status, pending);+ }+ }+ }+ Err(e) => {+ tracing::warn!("park temp bundle for task {task_id}: {e}");+ return park_without_wip(ctx, task_id, status, pending);+ }+ },+ Err(e) => {+ tracing::warn!("park bundle download for task {task_id}: {e}");+ return park_without_wip(ctx, task_id, status, pending);+ }+ }+ }+ Err(e) => {+ tracing::warn!("park diff for task {task_id}: {e}");+ return park_without_wip(ctx, task_id, status, pending);+ }+ };++ finish_park(ctx, task_id, status, pending, wip_sha.as_deref())+}++fn park_without_wip(+ ctx: &DriverCtx,+ task_id: i64,+ status: TaskStatus,+ pending: Pending,+) -> TaskOutcome {+ finish_park(ctx, task_id, status, pending, None)+}++fn finish_park(+ ctx: &DriverCtx,+ task_id: i64,+ status: TaskStatus,+ pending: Pending,+ wip_sha: Option<&str>,+) -> TaskOutcome {+ if pending.kind == PENDING_QUESTION {+ ctx.emit(task_id, EVENT_QUESTION, pending.payload.clone());+ }+ let effective = match ctx.store.park_task(task_id, status, &pending, wip_sha) {+ Ok(s) => s,+ Err(e) => {+ return TaskOutcome::Failed {+ reason: format!("park: {e}"),+ };+ }+ };+ ctx.emit(task_id, EVENT_STATUS,+ serde_json::json!({+ "message": format!("parked as {} (pending: {})", effective.as_str(), pending.kind),+ "status": effective.as_str(),+ "pending_kind": pending.kind,+ }),+ );+ TaskOutcome::Parked+}++fn write_temp_bundle(bundle: &[u8]) -> Result<tempfile::TempPath, String> {+ let tmp = tempfile::Builder::new()+ .prefix("agentd-wip-bundle-")+ .tempfile()+ .map_err(|e| format!("temp bundle file: {e}"))?;+ let path = tmp.into_temp_path();+ std::fs::write(&path, bundle).map_err(|e| format!("write bundle: {e}"))?;+ Ok(path)+}++/// `ask_user` (sole call in its turn) → park `needs_input(question)`.+async fn park_question(+ ctx: &DriverCtx,+ task_id: i64,+ slot: u32,+ branch: &str,+ _messages: &mut Vec<Message>,+ call: &ToolCall,+) -> TaskOutcome {+ let args: serde_json::Value =+ serde_json::from_str(&call.function.arguments).unwrap_or(serde_json::Value::Null);+ let question = args+ .get("question")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ let options = args.get("options").cloned().unwrap_or(serde_json::Value::Null);+ let multi_select = args+ .get("multi_select")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ let pending = Pending::new(+ PENDING_QUESTION,+ Some(call.id.clone()),+ serde_json::json!({+ "question": question,+ "options": options,+ "multi_select": multi_select,+ }),+ );+ park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await+}++/// `propose_plan` (sole call in its turn) → store the plan text, emit the+/// `plan` event, and park `needs_input(plan)` with pending+/// `{kind:"plan", tool_call_id, payload:{plan_markdown}}`.+///+/// Returns `None` when the plan is empty: the rejection is appended as the+/// tool result (history + event) and the caller continues the loop WITHOUT+/// parking.+async fn park_plan(+ ctx: &DriverCtx,+ task_id: i64,+ slot: u32,+ branch: &str,+ messages: &mut Vec<Message>,+ call: &ToolCall,+) -> Option<TaskOutcome> {+ let args: serde_json::Value =+ serde_json::from_str(&call.function.arguments).unwrap_or(serde_json::Value::Null);+ let plan_raw = args+ .get("plan_markdown")+ .and_then(|v| v.as_str())+ .unwrap_or("")+ .to_string();+ if plan_raw.trim().is_empty() {+ let msg = "propose_plan rejected: plan_markdown is empty; call propose_plan again with the plan.".to_string();+ ctx.emit(task_id, EVENT_TOOL_RESULT,+ serde_json::json!({"name": "propose_plan", "truncated": false, "result": msg}),+ );+ append_persisted(+ ctx,+ task_id,+ messages,+ Message::tool_result(call.id.clone(), msg),+ );+ return None;+ }+ let (plan_md, truncated) = cap_plan_markdown(&plan_raw);+ let _ = ctx.store.set_plan_md(task_id, &plan_md);+ ctx.emit(task_id, EVENT_PLAN,+ serde_json::json!({"plan_markdown": plan_md, "truncated": truncated}),+ );+ let pending = Pending::new(+ PENDING_PLAN,+ Some(call.id.clone()),+ serde_json::json!({"plan_markdown": plan_md}),+ );+ Some(park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await)+}++/// Text-only assistant turn → park `needs_input(chat)` (nudge-then-fail is+/// retired).+async fn park_chat(+ ctx: &DriverCtx,+ task_id: i64,+ slot: u32,+ branch: &str,+ _messages: &mut Vec<Message>,+ text: &str,+) -> TaskOutcome {+ let pending = Pending::new(+ PENDING_CHAT,+ None,+ serde_json::json!({"text": text}),+ );+ park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await+}++/// Budget exhausted → park `needs_input(budget)` (resume grants +20/+$1).+async fn park_budget(+ ctx: &DriverCtx,+ task_id: i64,+ slot: u32,+ branch: &str,+ _messages: &mut Vec<Message>,+) -> TaskOutcome {+ let cur = ctx.store.get_task(task_id).ok().flatten();+ let (steps, budget_steps, cost, budget_usd) = cur+ .map(|t| (t.steps, t.budget_steps, t.cost_usd, t.budget_usd))+ .unwrap_or((0, 0, 0.0, 0.0));+ let pending = Pending::new(+ PENDING_BUDGET,+ None,+ serde_json::json!({+ "message": format!(+ "budget exhausted (steps {steps}/{budget_steps}, cost ${cost:.4}/${budget_usd:.2})"+ ),+ }),+ );+ park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await+}++/// Transient errors, after retries → park `needs_input(error)` with the+/// message.+async fn park_error(+ ctx: &DriverCtx,+ task_id: i64,+ slot: u32,+ branch: &str,+ _messages: &mut Vec<Message>,+ message: &str,+) -> TaskOutcome {+ let pending = Pending::new(+ PENDING_ERROR,+ None,+ serde_json::json!({"message": message}),+ );+ park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await+}++/// Operator Stop observed → park `needs_input(stopped)` with work kept.+async fn park_after_stop(+ ctx: &DriverCtx,+ task_id: i64,+ slot: u32,+ branch: &str,+ _messages: &mut Vec<Message>,+) -> TaskOutcome {+ let pending = Pending::new(+ PENDING_STOPPED,+ None,+ serde_json::json!({"message": "stopped by operator; work kept"}),+ );+ park(ctx, task_id, slot, branch, TaskStatus::NeedsInput, pending).await+}+ /// Replace old tool results with placeholders once the conversation exceeds /// `budget` chars (keeps system prompt + first user message + recent tail).-/// Public for unit tests.-pub fn trim_messages(messages: &mut [Message], budget: usize) {+///+/// Takes a slice and returns an owned trimmed CLONE: the stored history is+/// never mutated. Pairing is structural — messages are never added, removed+/// or reordered, only tool-result *contents* in the middle window are+/// replaced with placeholders, so an assistant `tool_calls` message is never+/// separated from its tool results (ids stay aligned). Debug builds assert+/// the pairing after trimming. Public for unit tests.+pub fn trimmed_clone(messages: &[Message], budget: usize) -> Vec<Message> { let total: usize = messages.iter().map(|m| m.chars()).sum();- if total <= budget {- return;- }- // Keep first two (system + task) and last four; trim tool results in the- // middle window.- if messages.len() <= 6 {- return;+ if total <= budget || messages.len() <= 6 {+ return messages.to_vec(); }- let n = messages.len();- for m in messages.iter_mut().take(n.saturating_sub(4)).skip(2) {+ let mut out = messages.to_vec();+ let n = out.len();+ for m in out.iter_mut().take(n.saturating_sub(4)).skip(2) { if m.role == "tool" { if let Some(c) = m.content.take() { m.content = Some(trim_placeholder("tool", c.len())); } } }+ debug_assert!(tool_pairs_intact(&out), "trim separated tool_calls from results");+ out+}++/// Every assistant `tool_calls` id has a matching `tool` result later in the+/// history (OpenRouter rejects unanswered calls).+fn tool_pairs_intact(messages: &[Message]) -> bool {+ let mut pending: std::collections::HashSet<&str> = std::collections::HashSet::new();+ for m in messages {+ if m.role == "assistant" {+ if let Some(calls) = &m.tool_calls {+ for c in calls {+ pending.insert(c.id.as_str());+ }+ }+ } else if m.role == "tool" {+ if let Some(id) = &m.tool_call_id {+ pending.remove(id.as_str());+ }+ }+ }+ pending.is_empty()+}++/// Unknown-tool error (legacy list of the pre-structured tools plus the+/// structured layer).+fn unknown_tool(other: &str) -> String {+ format!(+ "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."+ )+}++/// Legacy in-place trim kept for unit tests: same window rule, mutates.+/// (The driver uses [`trimmed_clone`]; this entry point exists for the+/// trimming unit test.)+#[allow(dead_code)]+pub fn trim_messages(messages: &mut [Message], budget: usize) {+ let trimmed = trimmed_clone(messages, budget);+ if trimmed.len() == messages.len() {+ messages.clone_from_slice(&trimmed);+ } } -enum ToolEffect {+pub(crate) enum ToolEffect { Continue { result_for_model: String },- FinishRequest { summary: String, commit_message: String },+ ReviewRequest { summary: String, commit_message: String }, } -async fn dispatch_tool(+/// Is the plan gate currently closed for this task? (`require_plan` set and+/// the plan not yet approved.)+fn plan_gated(store: &Store, task_id: i64) -> bool {+ store+ .get_task(task_id)+ .ok()+ .flatten()+ .map(|t| t.require_plan && !t.plan_approved)+ .unwrap_or(false)+}++pub(crate) async fn dispatch_tool( ctx: &DriverCtx, task_id: i64, slot: u32,@@ -428,9 +1111,7 @@ async fn dispatch_tool( ) -> ToolEffect { let args: serde_json::Value = serde_json::from_str(&call.function.arguments).unwrap_or(serde_json::Value::Null);- ctx.emit(- task_id,- "tool_call",+ ctx.emit(task_id, EVENT_TOOL_CALL, serde_json::json!({"name": call.function.name, "args": args_preview(&call.function.arguments)}), ); let raw: String = match call.function.name.as_str() {@@ -449,12 +1130,15 @@ async fn dispatch_tool( ) .await {- Ok(r) => format!(- "{} ({} lines{})",- r.content,- r.total_lines,- if r.truncated { ", truncated" } else { "" }- ),+ Ok(r) => {+ let body = format!(+ "{} ({} lines{})",+ r.content,+ r.total_lines,+ if r.truncated { ", truncated" } else { "" }+ );+ with_loaded_rules_note(ctx, task_id, slot, &path, body).await+ } Err(e) => format!("read failed: {e}"), } }@@ -467,7 +1151,14 @@ async fn dispatch_tool( } } match ctx.runner.list(slot, &path).await {- Ok(r) => r.entries.join("\n"),+ Ok(r) => {+ let probe = if path.is_empty() {+ module_scope.replace(':', "/")+ } else {+ path.clone()+ };+ with_loaded_rules_note(ctx, task_id, slot, &probe, r.entries.join("\n")).await+ } Err(e) => format!("list failed: {e}"), } }@@ -493,42 +1184,96 @@ async fn dispatch_tool( ) .await {- Ok(r) => r.matches,+ Ok(r) => {+ let probe = root.unwrap_or_default();+ with_loaded_rules_note(ctx, task_id, slot, &probe, r.matches).await+ } Err(e) => format!("search failed: {e}"), } } "edit_file" => {- let path = arg_str(&args, "path").unwrap_or_default();- if let Err(e) = check_scope(&path, module_scope) {- format!("Scope error: {e}")+ if plan_gated(&ctx.store, task_id) {+ plan_gate_message().to_string() } else {- match ctx- .runner- .edit(- slot,- &path,- &arg_str(&args, "old").unwrap_or_default(),- &arg_str(&args, "new").unwrap_or_default(),- )- .await- {- Ok(()) => "edit applied".to_string(),- Err(e) => format!("edit failed: {e}"),+ let path = arg_str(&args, "path").unwrap_or_default();+ if let Err(e) = check_scope(&path, module_scope) {+ format!("Scope error: {e}")+ } else {+ match ctx+ .runner+ .edit(+ slot,+ &path,+ &arg_str(&args, "old").unwrap_or_default(),+ &arg_str(&args, "new").unwrap_or_default(),+ )+ .await+ {+ Ok(()) => {+ with_loaded_rules_note(ctx, task_id, slot, &path, "edit applied".to_string()).await+ }+ Err(e) => format!("edit failed: {e}"),+ } } } } "write_file" => {- let path = arg_str(&args, "path").unwrap_or_default();- if let Err(e) = check_scope(&path, module_scope) {- format!("Scope error: {e}")+ if plan_gated(&ctx.store, task_id) {+ plan_gate_message().to_string() } else {- match ctx- .runner- .write(slot, &path, &arg_str(&args, "content").unwrap_or_default())- .await- {- Ok(()) => "file written".to_string(),- Err(e) => format!("write failed: {e}"),+ let path = arg_str(&args, "path").unwrap_or_default();+ if let Err(e) = check_scope(&path, module_scope) {+ format!("Scope error: {e}")+ } else {+ match ctx+ .runner+ .write(slot, &path, &arg_str(&args, "content").unwrap_or_default())+ .await+ {+ Ok(()) => {+ with_loaded_rules_note(ctx, task_id, slot, &path, "file written".to_string()).await+ }+ Err(e) => format!("write failed: {e}"),+ }+ }+ }+ }+ "update_todos" => {+ let items_raw = args.get("items").cloned().unwrap_or(serde_json::Value::Null);+ let items: Vec<crate::models::TodoItem> = match serde_json::from_value(items_raw) {+ Ok(v) => v,+ Err(e) => {+ return finish_dispatch(+ ctx,+ task_id,+ &call.function.name,+ &format!("update_todos rejected: bad items ({e}); pass items:[{{text, status: pending|in_progress|done}}]"),+ );+ }+ };+ match validate_todos(&items) {+ Err(e) => {+ return finish_dispatch(+ ctx,+ task_id,+ &call.function.name,+ &format!("update_todos rejected: {e}"),+ );+ }+ Ok(valid) => {+ let todos_json = serde_json::to_string(&valid).unwrap_or_else(|_| "[]".to_string());+ if let Err(e) = ctx.store.set_todos(task_id, &todos_json) {+ return finish_dispatch(+ ctx,+ task_id,+ &call.function.name,+ &format!("update_todos failed: {e}"),+ );+ }+ ctx.emit(task_id, EVENT_TODOS,+ serde_json::json!({"items": valid}),+ );+ "ok".to_string() } } }@@ -538,54 +1283,60 @@ async fn dispatch_tool( }, "run_shell" => { let command = arg_str(&args, "command").unwrap_or_default();- match validate_shell_command(&command) {- Err(msg) => format!("Rejected: {msg}"),- Ok(()) => match ctx- .runner- .exec(slot, &command, proto::ExecKind::Shell, 60)- .await- {- Ok(r) => exec_summary(&r),- Err(e) => format!("exec failed: {e}"),- },+ // Plan gate first (best-effort mutation detector), then the+ // existing build/device blocklist.+ if plan_gated(&ctx.store, task_id) && shell_looks_mutating(&command) {+ plan_gate_message().to_string()+ } else {+ match validate_shell_command(&command) {+ Err(msg) => format!("Rejected: {msg}"),+ Ok(()) => match ctx+ .runner+ .exec(slot, &command, proto::ExecKind::Shell, 60)+ .await+ {+ Ok(r) => exec_summary(&r),+ Err(e) => format!("exec failed: {e}"),+ },+ } } } "build" => {- let command = arg_str(&args, "command").unwrap_or_default();- let allowed = match validate_build_command(&command) {- Err(msg) => return finish_dispatch(ctx, task_id, &call.function.name, &format!("Rejected: {msg}")),- Ok(c) => c,- };- // Release preemption: while the signal file exists, wait (up to- // 60 min). If it appeared mid-build, kill the runner build.- if release_active(&ctx.config) {- match wait_for_release_clear(ctx, task_id, &allowed).await {- Ok(()) => {}- Err(msg) => return finish_dispatch(ctx, task_id, &call.function.name, &msg),- }- }- match ctx- .runner- .exec(slot, &allowed, proto::ExecKind::Build, 20 * 60)- .await- {- Ok(r) => {- if r.killed && release_active(&ctx.config) {- let _ = ctx.runner.kill_build().await;- "build preempted by a production release; retry later".to_string()- } else {- exec_summary(&r)+ if plan_gated(&ctx.store, task_id) {+ plan_gate_message().to_string()+ } else if args.get("module").and_then(|v| v.as_str()).is_some() {+ // Structured `{module, tasks}` form: validated, run, and parsed.+ let parsed = crate::structured::dispatch_structured_build(ctx, task_id, slot, &args).await;+ return finish_dispatch(ctx, task_id, &call.function.name, &parsed);+ } else {+ // Legacy `{command}` string keeps the raw exec summary.+ let allowed = match crate::structured::parse_build_args(&args) {+ Err(msg) => return finish_dispatch(ctx, task_id, &call.function.name, &format!("Rejected: {msg}")),+ Ok(c) => c,+ };+ match exec_build_command(ctx, task_id, slot, &allowed).await {+ BuildOutcome::Done(r) => exec_summary(&r),+ BuildOutcome::Message(m) => {+ return finish_dispatch(ctx, task_id, &call.function.name, &m); } }- Err(e) => format!("build failed: {e}"), } } "finish" => { let summary = arg_str(&args, "summary").unwrap_or_default(); let commit_message = arg_str(&args, "commit_message").unwrap_or_default(); // Validate first: violations return as a tool result so the- // model can fix them and call `finish` again.- if let Err(e) = validate_commit_message(&commit_message) {+ // model can fix them and call `finish` again. `finish` is a+ // parking tool, but validation happens here because a sole+ // `finish` flows through normal dispatch and only parks via+ // ReviewRequest below. Issue-linked tasks additionally require+ // the ` (#<n>)` subject suffix.+ let task_issue = ctx.store.get_task(task_id).ok().flatten().and_then(|t| t.issue_number);+ let validation = match task_issue {+ Some(n) => validate_commit_message_for_issue(&commit_message, Some(n)),+ None => validate_commit_message(&commit_message),+ };+ if let Err(e) = validation { let msg = format!( "finish rejected: {e}. Fix the commit message and call `finish` again." );@@ -610,26 +1361,54 @@ async fn dispatch_tool( } _ => {} }- return ToolEffect::FinishRequest {+ return ToolEffect::ReviewRequest { summary, commit_message, }; }- other => format!(- "Unknown tool {other:?}; available: read_file, list_dir, search, edit_file, write_file, git_diff, run_shell, build, finish."- ),+ other => {+ // Structured tools (run_tests, check, git_*, find_files, github_*)+ // live in `structured.rs`. Mutating ones respect the plan gate.+ if matches!(other, "run_tests" | "check") && plan_gated(&ctx.store, task_id) {+ plan_gate_message().to_string()+ } else {+ let task = ctx.store.get_task(task_id).ok().flatten();+ match task {+ Some(t) => match crate::structured::dispatch(ctx, task_id, slot, &t, other, &args).await {+ Some(result) => result,+ None => unknown_tool(other),+ },+ None => unknown_tool(other),+ }+ }+ }, }; finish_dispatch(ctx, task_id, &call.function.name, &raw) } +/// Append a `[loaded rules: a/AGENTS.md, ...]` note when per-path auto-load+/// picked up new rules files during this tool call.+async fn with_loaded_rules_note(+ ctx: &DriverCtx,+ task_id: i64,+ slot: u32,+ path: &str,+ body: String,+) -> String {+ let newly = ensure_rules_for_path(ctx, task_id, slot, path).await;+ if newly.is_empty() {+ body+ } else {+ format!("{body}\n[loaded rules: {}]", newly.join(", "))+ }+}+ /// Truncate + scrub a tool result, emit the `tool_result` event, and return /// the text fed back to the model. fn finish_dispatch(ctx: &DriverCtx, task_id: i64, name: &str, raw: &str) -> ToolEffect { let (text, truncated) = truncate_result(raw); let text = scrub_secrets(&text);- ctx.emit(- task_id,- "tool_result",+ ctx.emit(task_id, EVENT_TOOL_RESULT, serde_json::json!({"name": name, "truncated": truncated, "result": text}), ); ToolEffect::Continue {@@ -638,7 +1417,7 @@ fn finish_dispatch(ctx: &DriverCtx, task_id: i64, name: &str, raw: &str) -> Tool } /// Confine a repo-relative path to the module scope (or the rules files).-fn check_scope(path: &str, module_scope: &str) -> Result<(), String> {+pub(crate) fn check_scope(path: &str, module_scope: &str) -> Result<(), String> { let dir = module_scope.replace(':', "/"); let dir = dir.trim_matches('/'); let p = path.trim_start_matches('/');@@ -678,68 +1457,103 @@ fn exec_summary(r: &proto::ExecResponse) -> String { s } -async fn finish_task(+/// `finish` (sole call in its turn, already validated) → submits for human+/// review WITHOUT pushing:+///+/// 1. Commit in the sandbox (single squashed commit with the agent's+/// `commit_message`).+/// 2. Capture the runner diff for `final_diff` (capped ~50 KB).+/// 3. Bundle + import into the mirror as `refs/agent-wip/<id>` (reuses the+/// park WIP machinery); record `wip_sha`.+/// 4. Store `final_diff`, `commit_message`, `summary`; emit the `review`+/// event `{summary, commit_message, diff, truncated}`.+/// 5. Park as `review` with pending `{kind:"review",+/// tool_call_id:<finish id>}`.+///+/// NO push happens here — Approve pushes. Request-changes arrives as the+/// pending `finish` call's tool result on resume; the resumed checkout+/// restores the squashed WIP as uncommitted changes vs `base_sha`, so the+/// agent keeps editing and calls `finish` again.+async fn park_review( ctx: &DriverCtx, task_id: i64, slot: u32, branch: &str,+ call: &ToolCall, summary: &str, commit_message: &str, ) -> TaskOutcome {- // Commit in the sandbox.- let sha = match ctx.runner.commit(slot, commit_message).await {+ // Runner diff FIRST (pre-commit working tree vs base) for final_diff.+ let review_diff = match ctx.runner.diff(slot).await {+ Ok(d) => {+ let full = if d.diff.trim().is_empty() {+ d.stat.clone()+ } else {+ format!("{}\n{}", d.stat, d.diff)+ };+ full+ }+ Err(e) => {+ // Validation already saw a diff earlier this turn; a transient+ // read failure now fails loudly rather than submitting blind.+ return fail(ctx, task_id, &format!("review diff read: {e}")).await;+ }+ };+ // Single squashed commit with the agent's message.+ let _sha = match ctx.runner.commit(slot, commit_message).await { Ok(r) => r.sha, Err(e) => return fail(ctx, task_id, &format!("runner commit: {e}")).await, };- ctx.emit(- task_id,- "status",- serde_json::json!({"message": format!("committed {sha}"), "sha": sha}),+ ctx.emit(task_id, EVENT_STATUS,+ serde_json::json!({"message": format!("committed {_sha}"), "sha": _sha}), );- // Bundle → mirror → push.+ // Bundle → mirror WIP import (same machinery as park). let bundle = match ctx.runner.bundle(slot).await { Ok(b) => b, Err(e) => return fail(ctx, task_id, &format!("bundle download: {e}")).await, };- let tmp = match tempfile::Builder::new().prefix("agentd-bundle-").tempfile() {- Ok(f) => f.into_temp_path(),+ let tmp = match write_temp_bundle(&bundle) {+ Ok(t) => t, Err(e) => return fail(ctx, task_id, &format!("temp bundle file: {e}")).await, };- if let Err(e) = std::fs::write(&tmp, &bundle) {- return fail(ctx, task_id, &format!("write bundle: {e}")).await;- }- if let Err(e) = crate::git::import_task_bundle(&ctx.config.mirror_dir, &tmp, branch).await {- return fail(ctx, task_id, &format!("bundle import: {e}")).await;- }- match crate::git::push_branch(+ let wip_sha = match crate::git::import_wip_bundle( &ctx.config.mirror_dir,- &ctx.config.repo_url,+ &tmp, branch,- &ctx.config.git_push_token,+ task_id, ) .await {- Ok(()) => {- let _ = ctx.store.set_finished_commit(task_id, &sha, true, summary);- ctx.emit(- task_id,- "status",- serde_json::json!({"message": format!("pushed {branch}"), "sha": sha}),- );- TaskOutcome::Succeeded {- commit_sha: sha,- pushed: true,- summary: summary.to_string(),- }- }- Err(e) => {- let _ = ctx.store.set_finished_commit(task_id, &sha, false, summary);- fail(- ctx,- task_id,- &format!("push {branch} failed: {e} (commit {sha} kept in mirror)"),- )- .await- }+ Ok(sha) => sha,+ Err(e) => return fail(ctx, task_id, &format!("wip bundle import: {e}")).await,+ };+ // Store the review snapshot + emit the review event, then park.+ let (final_diff, truncated) = cap_final_diff(&review_diff);+ let _ = ctx.store.set_review(task_id, &wip_sha, &final_diff, commit_message, summary);+ // A Stop arriving during commit/bundle is honored after import.+ if stop_requested(&ctx.store, task_id) {+ let pending = Pending::new(+ PENDING_STOPPED,+ None,+ serde_json::json!({"message": "stopped by operator; work kept"}),+ );+ return finish_park(ctx, task_id, TaskStatus::NeedsInput, pending, Some(&wip_sha)); }+ ctx.emit(task_id, EVENT_REVIEW,+ serde_json::json!({+ "summary": summary,+ "commit_message": commit_message,+ "diff": final_diff,+ "truncated": truncated,+ }),+ );+ let pending = Pending::new(+ PENDING_REVIEW,+ Some(call.id.clone()),+ serde_json::json!({+ "summary": summary,+ "commit_message": commit_message,+ }),+ );+ finish_park(ctx, task_id, TaskStatus::Review, pending, Some(&wip_sha)) }
infra/agents/agentd/src/config.rs
diff --git a/infra/agents/agentd/src/config.rs b/infra/agents/agentd/src/config.rsindex 2c77b47f67..6862b5ab88 100644--- a/infra/agents/agentd/src/config.rs+++ b/infra/agents/agentd/src/config.rs@@ -47,11 +47,23 @@ pub struct Config { pub listen: String, /// Number of concurrent agent tasks (scheduler workers). pub slots: usize,+ /// `owner/name` repo the GitHub tools talk to (issues read + after-push+ /// comment/label). Mirrors `GitHub::new_from_env("vayun-mathur/Modern-Apps")`.+ pub github_repo: String,+ /// GitHub API base URL override (tests point at a mock server).+ pub github_api_base: String,+ /// GitHub token for issue read/comment/label (from `AGENTD_GITHUB_TOKEN`,+ /// empty when unset). Held in memory only; never sent to the sandbox.+ pub github_token: Option<String>, /// Test tuning (timeouts only). `None` in production. pub test: TestTuning, // -- test-only network flags (never read in prod paths) -- /// Test fixture: skip the real release-signal wait. pub test_skip_release_wait: bool,+ /// Automatic issue triage poller (`AGENTD_TRIAGE`; default on, `0` off).+ pub triage_enabled: bool,+ /// Triage poll period in seconds (`AGENTD_TRIAGE_INTERVAL_SECS`; 120).+ pub triage_interval_secs: u64, } impl Config {@@ -120,8 +132,17 @@ impl Config { )), listen: Self::optional("AGENTD_LISTEN", "0.0.0.0:8080"), slots,+ github_repo: Self::optional("AGENTD_GITHUB_REPO", "vayun-mathur/Modern-Apps"),+ github_api_base: Self::optional("AGENTD_GITHUB_API", crate::github::DEFAULT_BASE_URL),+ github_token: std::env::var("AGENTD_GITHUB_TOKEN")+ .ok()+ .filter(|t| !t.trim().is_empty()), test, test_skip_release_wait: false,+ triage_enabled: Self::optional("AGENTD_TRIAGE", "1") != "0",+ triage_interval_secs: Self::optional("AGENTD_TRIAGE_INTERVAL_SECS", "120")+ .parse()+ .unwrap_or(120), }) }
infra/agents/agentd/src/git.rs
diff --git a/infra/agents/agentd/src/git.rs b/infra/agents/agentd/src/git.rsindex c1f1531e66..4c2b2b012f 100644--- a/infra/agents/agentd/src/git.rs+++ b/infra/agents/agentd/src/git.rs@@ -146,36 +146,51 @@ pub async fn main_sha(mirror: &Path) -> Result<String, GitError> { Ok(sha.trim().to_string()) } -/// Verify a downloaded bundle file inside the mirror (so prerequisite-/// checks run against a repo that shares history), then import it as-/// `refs/agent-out/<suffix>` in the mirror.+/// Push one local ref to the upstream branch with the scoped token via+/// `http.extraHeader` (token in process env, never URL/argv/logs).+/// Replaces the old `push_branch` (`refs/agent-out/*`): the review gate+/// pushes `refs/agent-wip/<id>` directly.+pub async fn push_ref(+ mirror: &Path,+ repo_url: &str,+ src: &str,+ dst: &str,+ token: &str,+) -> Result<(), GitError> {+ let header_value = format!("Authorization: Bearer {token}");+ // Env values are not argv; redact defensively anyway on error paths.+ let r = run_git(+ Some(mirror),+ &["push", repo_url, &format!("+{src}:{dst}")],+ &[+ ("GIT_CONFIG_COUNT", "1"),+ ("GIT_CONFIG_KEY_0", "http.extraHeader"),+ ("GIT_CONFIG_VALUE_0", &header_value),+ ],+ PUSH_TIMEOUT,+ )+ .await;+ match r {+ Ok(_) => Ok(()),+ Err(GitError(msg)) => Err(GitError(crate::agent::scrub_secrets(&format!(+ "push {dst}: {msg}"+ )))),+ }+}++/// Import a downloaded slot bundle as the task's WIP ref+/// (`refs/agent-wip/<id>`), returning the WIP commit sha. Same verify-then-+/// fetch discipline as the old task-bundle import: a corrupt bundle fails, a+/// missing prerequisite does not. ///-/// The bundle holds `<base>..<branch>`, where `<base>` is the mirror's-/// `main` fetched at task start. `git bundle verify` requires the-/// prerequisite commits to exist locally: a plain `clone --bare` has them,-/// but a mirror whose `main` has since moved (or that was cloned empty)-/// may not. `git fetch <bundle>` only needs the *endpoints*; the import-/// fetch below succeeds regardless. So a verify failure that is purely a-/// missing prerequisite must not fail the import — but a corrupt bundle-/// must. Distinguish them: if verify fails, check whether the bundle's-/// required ref is an ancestor-known object; if the fetch itself succeeds,-/// accept the bundle.-pub async fn import_task_bundle(+/// `branch` is the task's slot branch (the ref the bundle carries).+pub async fn import_wip_bundle( mirror: &Path, bundle_file: &Path, branch: &str,-) -> Result<(), GitError> {- let suffix = branch- .strip_prefix("agent/")- .ok_or_else(|| GitError(format!("bad branch {branch:?}")))?;- let dst = format!("refs/agent-out/{suffix}");- // Verify inside the mirror so prerequisite checks resolve against it- // (`git bundle verify` prints e.g. "<file> is okay"). A verify failure- // caused purely by a missing prerequisite (mirror's `main` moved after- // the slot branched) must not fail the import — but a corrupt bundle- // must. `git fetch <bundle>` only needs the branch tip and its new- // objects, so: run verify for diagnostics, then run the fetch, and fail- // only if the fetch fails.+ task_id: i64,+) -> Result<String, GitError> {+ let dst = format!("refs/agent-wip/{task_id}"); let verify_err = run_git( Some(mirror), &["bundle", "verify", &bundle_file.to_string_lossy()],@@ -185,7 +200,6 @@ pub async fn import_task_bundle( .await .err() .map(|e| e.0);- // The bundle holds `<base>..<branch>`; fetch the branch head by name. if let Err(e) = run_git( Some(mirror), &[@@ -198,45 +212,44 @@ pub async fn import_task_bundle( ) .await {- // The import itself failed: include the verify output when the- // bundle is also unverifiable (corrupt bundle). if let Some(v) = verify_err {- return Err(GitError(format!("bundle import failed ({e}); verify: {v}")));+ return Err(GitError(format!("wip bundle import failed ({e}); verify: {v}"))); }- return Err(GitError(format!("bundle import: {e}")));+ return Err(GitError(format!("wip bundle import: {e}"))); }- Ok(())+ let sha = run_git(Some(mirror), &["rev-parse", &dst], &[], GIT_TIMEOUT).await?;+ Ok(sha.trim().to_string()) } -/// Push `refs/agent-out/<suffix>` to `refs/heads/agent/<suffix>` on the-/// upstream. The token is passed via git config env (`http.extraHeader`),-/// never in the URL/argv/logs.-pub async fn push_branch(- mirror: &Path,- repo_url: &str,- branch: &str,- token: &str,-) -> Result<(), GitError> {- let suffix = branch- .strip_prefix("agent/")- .ok_or_else(|| GitError(format!("bad branch {branch:?}")))?;- let src = format!("refs/agent-out/{suffix}");- let dst = format!("refs/heads/{branch}");- let header_value = format!("Authorization: Bearer {token}");- // Env values are not argv; redact defensively anyway on error paths.- let r = run_git(+/// Does the WIP ref exist in the mirror, and what sha does it resolve to?+pub async fn wip_ref_sha(mirror: &Path, task_id: i64) -> Result<Option<String>, GitError> {+ let dst = format!("refs/agent-wip/{task_id}");+ match run_git(Some(mirror), &["rev-parse", "--verify", &dst], &[], GIT_TIMEOUT).await {+ Ok(sha) => Ok(Some(sha.trim().to_string())),+ Err(_) => Ok(None),+ }+}++/// Delete the local WIP ref (parked with no changes, discard, or after the+/// work moved elsewhere). Missing ref is fine.+pub async fn delete_wip_ref(mirror: &Path, task_id: i64) -> Result<(), GitError> {+ let dst = format!("refs/agent-wip/{task_id}");+ match run_git( Some(mirror),- &["push", repo_url, &format!("+{src}:{dst}")],- &[- ("GIT_CONFIG_COUNT", "1"),- ("GIT_CONFIG_KEY_0", "http.extraHeader"),- ("GIT_CONFIG_VALUE_0", &header_value),- ],- PUSH_TIMEOUT,+ &["update-ref", "-d", &dst],+ &[],+ GIT_TIMEOUT, )- .await;- match r {+ .await+ { Ok(_) => Ok(()),- Err(GitError(msg)) => Err(GitError(format!("push {branch}: {msg}"))),+ Err(e) => {+ // Tolerate "not found" (already deleted / never created).+ if wip_ref_sha(mirror, task_id).await?.is_none() {+ Ok(())+ } else {+ Err(e)+ }+ } } }
infra/agents/agentd/src/github.rs
diff --git a/infra/agents/agentd/src/github.rs b/infra/agents/agentd/src/github.rsnew file mode 100644index 0000000000..123165323b--- /dev/null+++ b/infra/agents/agentd/src/github.rs@@ -0,0 +1,1683 @@+#![allow(dead_code)]+//! Minimal GitHub REST client for agentd's issue tools.+//!+//! Covers exactly what the orchestrator needs: searching issues,+//! reading one issue with its comments, posting a comment, and adding+//! labels (the last two need `AGENTD_GITHUB_TOKEN`). The base URL defaults+//! to `https://api.github.com` and is overridable so tests can point at a+//! local mock server.+//!+//! Pure helpers ([`app_module_for_labels`], [`render_issue_for_model`],+//! [`render_search_for_model`], [`task_from_issue`]) shape GitHub data for+//! the model and the scheduler.++use std::time::Duration;++use serde::{Deserialize, Serialize};++/// Default API root; override per client for tests.+pub const DEFAULT_BASE_URL: &str = "https://api.github.com";+/// Pinned GitHub API version sent on every request.+pub const API_VERSION: &str = "2022-11-28";+/// `User-Agent` sent on every request.+pub const USER_AGENT: &str = "agentd";+/// Label agentd adds after a user-approved successful push.+pub const SOLVED_LABEL: &str = "solved for next release";+/// Total budget in bytes for an issue body plus its comment bodies.+pub const BODY_BUDGET_BYTES: usize = 12 * 1024;+/// Comment pages (`per_page=100`) followed when reading an issue.+pub const MAX_COMMENT_PAGES: u32 = 3;+/// `per_page` used when listing comments.+pub const COMMENTS_PER_PAGE: u32 = 100;++/// Errors from the GitHub client.+#[derive(Debug)]+pub enum Error {+ /// A write call (`post_comment`, `add_labels`) without a token.+ NoToken(&'static str),+ /// Transport failure (connect, timeout, bad body, ...).+ Transport(reqwest::Error),+ /// Non-success status that is not a rate limit.+ Api { status: u16, message: String },+ /// HTTP 429, or HTTP 403 with `x-ratelimit-remaining: 0`.+ RateLimited { status: u16, reset: Option<String> },+}++impl std::fmt::Display for Error {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Error::NoToken(op) => {+ write!(f, "GitHub token required for {op} (set AGENTD_GITHUB_TOKEN)")+ }+ Error::Transport(e) => write!(f, "GitHub request failed: {e}"),+ Error::Api { status, message } => {+ write!(f, "GitHub API error (HTTP {status}): {message}")+ }+ Error::RateLimited { status, reset } => write!(+ f,+ "GitHub rate limit exceeded (HTTP {status}); resets at {}",+ reset.as_deref().unwrap_or("unknown")+ ),+ }+ }+}++impl std::error::Error for Error {}++/// Which issues a search/list call includes.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum IssueState {+ Open,+ Closed,+ All,+}++impl IssueState {+ /// Lowercase value the GitHub API expects.+ pub fn as_str(self) -> &'static str {+ match self {+ IssueState::Open => "open",+ IssueState::Closed => "closed",+ IssueState::All => "all",+ }+ }+}++/// One row from a search or list call.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct IssueSummary {+ pub number: u64,+ pub title: String,+ pub state: String,+ pub labels: Vec<String>,+ pub comments: u64,+ pub created_at: String,+ pub updated_at: String,+ pub is_pr: bool,+}++/// A single issue comment.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Comment {+ pub author: String,+ pub created_at: String,+ pub body: String,+}++/// A full issue with comments. `body` plus `comments` fit in+/// [`BODY_BUDGET_BYTES`]; `truncated` is set when anything was cut.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Issue {+ pub number: u64,+ pub title: String,+ pub state: String,+ pub labels: Vec<String>,+ pub body: String,+ pub author: String,+ pub created_at: String,+ pub comments: Vec<Comment>,+ pub truncated: bool,+}++#[derive(Debug, Clone, Deserialize)]+struct ApiLabel {+ #[serde(default)]+ name: String,+}++#[derive(Debug, Clone, Deserialize)]+struct ApiUser {+ #[serde(default)]+ login: String,+}++/// Subset of the issue object agentd reads. Everything defaults so a+/// minimal mock (or a future API field change) still parses.+#[derive(Debug, Clone, Deserialize)]+struct ApiIssue {+ #[serde(default)]+ number: u64,+ #[serde(default)]+ title: String,+ #[serde(default)]+ state: String,+ #[serde(default)]+ labels: Vec<ApiLabel>,+ #[serde(default)]+ body: Option<String>,+ #[serde(default)]+ user: Option<ApiUser>,+ #[serde(default)]+ created_at: String,+ #[serde(default)]+ updated_at: String,+ #[serde(default)]+ comments: u64,+ #[serde(default)]+ pull_request: Option<serde_json::Value>,+}++impl ApiIssue {+ fn is_pr(&self) -> bool {+ self.pull_request.is_some()+ }++ fn label_names(&self) -> Vec<String> {+ self.labels.iter().map(|l| l.name.clone()).collect()+ }+}++#[derive(Debug, Clone, Deserialize)]+struct ApiComment {+ #[serde(default)]+ user: Option<ApiUser>,+ #[serde(default)]+ created_at: String,+ #[serde(default)]+ body: Option<String>,+}++impl From<ApiComment> for Comment {+ fn from(c: ApiComment) -> Comment {+ Comment {+ author: c.user.map(|u| u.login).unwrap_or_default(),+ created_at: c.created_at,+ body: c.body.unwrap_or_default(),+ }+ }+}++#[derive(Debug, Clone, Deserialize)]+struct SearchResponse {+ #[serde(default)]+ items: Vec<ApiIssue>,+}++#[derive(Debug, Clone, Deserialize)]+struct ApiErrorBody {+ #[serde(default)]+ message: String,+}++#[derive(Debug, Clone, Deserialize)]+struct PostedComment {+ #[serde(default)]+ html_url: String,+}++/// GitHub API client scoped to one `owner/name` repo.+#[derive(Clone)]+pub struct GitHub {+ base_url: String,+ repo: String,+ token: Option<String>,+ http: reqwest::Client,+}++impl GitHub {+ /// Client against `https://api.github.com`.+ pub fn new(repo: impl Into<String>, token: Option<String>) -> Result<GitHub, Error> {+ GitHub::with_base_url(DEFAULT_BASE_URL, repo, token)+ }++ /// Client against an explicit API root (tests point at a mock server).+ pub fn with_base_url(+ base_url: impl Into<String>,+ repo: impl Into<String>,+ token: Option<String>,+ ) -> Result<GitHub, Error> {+ let http = reqwest::Client::builder()+ .connect_timeout(Duration::from_secs(10))+ .timeout(Duration::from_secs(30))+ .no_proxy()+ .build()+ .map_err(Error::Transport)?;+ Ok(GitHub {+ base_url: base_url.into().trim_end_matches('/').to_string(),+ repo: repo.into(),+ token,+ http,+ })+ }++ /// Client for `repo` with the token from `AGENTD_GITHUB_TOKEN` (if set).+ pub fn new_from_env(repo: impl Into<String>) -> Result<GitHub, Error> {+ let token = std::env::var("AGENTD_GITHUB_TOKEN")+ .ok()+ .filter(|t| !t.trim().is_empty());+ GitHub::new(repo, token)+ }++ fn request(&self, method: reqwest::Method, path: &str) -> reqwest::RequestBuilder {+ // Pagination `Link` headers are absolute URLs. Only follow ones on our+ // API base so the bearer token can never be sent to another host.+ let url = if path.starts_with("http") {+ if path.starts_with(&format!("{}/", self.base_url)) {+ path.to_string()+ } else {+ format!("{}/invalid-pagination-link", self.base_url)+ }+ } else {+ format!("{}{path}", self.base_url)+ };+ let mut req = self+ .http+ .request(method, url)+ .header(reqwest::header::USER_AGENT, USER_AGENT)+ .header(reqwest::header::ACCEPT, "application/vnd.github+json")+ .header("X-GitHub-Api-Version", API_VERSION);+ if let Some(token) = &self.token {+ req = req.header(+ reqwest::header::AUTHORIZATION,+ format!("Bearer {token}"),+ );+ }+ req+ }++ /// Send a request, mapping rate limits and API errors.+ async fn send(&self, req: reqwest::RequestBuilder) -> Result<reqwest::Response, Error> {+ let resp = req.send().await.map_err(Error::Transport)?;+ let status = resp.status();+ let rate_limited = status.as_u16() == 429+ || (status.as_u16() == 403+ && matches!(+ resp.headers()+ .get("x-ratelimit-remaining")+ .and_then(|v| v.to_str().ok()),+ Some("0")+ ));+ if rate_limited {+ let reset = resp+ .headers()+ .get("x-ratelimit-reset")+ .and_then(|v| v.to_str().ok())+ .map(str::to_string);+ return Err(Error::RateLimited {+ status: status.as_u16(),+ reset,+ });+ }+ if !status.is_success() {+ let message = resp+ .json::<ApiErrorBody>()+ .await+ .map(|e| e.message)+ .unwrap_or_else(|_| format!("HTTP {status}"));+ return Err(Error::Api {+ status: status.as_u16(),+ message,+ });+ }+ Ok(resp)+ }++ /// Search issues. With `query` the Search API is used+ /// (`q=repo:<repo> is:issue ...`, labels folded in as `label:".."`),+ /// otherwise the list endpoint with a `labels` filter. Pull requests+ /// are always excluded.+ pub async fn search_issues(+ &self,+ query: Option<&str>,+ labels: &[String],+ state: IssueState,+ limit: u32,+ ) -> Result<Vec<IssueSummary>, Error> {+ let per_page = limit.clamp(1, 100);+ if let Some(query) = query {+ let mut q = format!("repo:{} is:issue {query}", self.repo);+ match state {+ IssueState::Open => q.push_str(" state:open"),+ IssueState::Closed => q.push_str(" state:closed"),+ IssueState::All => {}+ }+ for label in labels {+ q.push_str(&format!(" label:\"{label}\""));+ }+ let resp = self+ .send(self.request(reqwest::Method::GET, "/search/issues").query(&[+ ("q", q),+ ("per_page", per_page.to_string()),+ ]))+ .await?;+ let found: SearchResponse = resp.json().await.map_err(Error::Transport)?;+ Ok(found+ .items+ .into_iter()+ .filter(|i| !i.is_pr())+ .map(summary_from)+ .collect())+ } else {+ let mut params: Vec<(&str, String)> = vec![+ ("state", state.as_str().to_string()),+ ("per_page", per_page.to_string()),+ ("sort", "updated".to_string()),+ ("direction", "desc".to_string()),+ ];+ if !labels.is_empty() {+ params.push(("labels", labels.join(",")));+ }+ let path = format!("/repos/{}/issues", self.repo);+ let resp = self+ .send(self.request(reqwest::Method::GET, &path).query(¶ms))+ .await?;+ let found: Vec<ApiIssue> = resp.json().await.map_err(Error::Transport)?;+ Ok(found+ .into_iter()+ .filter(|i| !i.is_pr())+ .map(summary_from)+ .collect())+ }+ }++ /// Read one issue with its comments (paginated, up to+ /// [`MAX_COMMENT_PAGES`] pages). Body plus comments are capped at+ /// [`BODY_BUDGET_BYTES`] total; `truncated` notes when anything was cut.+ pub async fn read_issue(&self, number: u64) -> Result<Issue, Error> {+ let path = format!("/repos/{}/issues/{number}", self.repo);+ let resp = self+ .send(self.request(reqwest::Method::GET, &path))+ .await?;+ let raw: ApiIssue = resp.json().await.map_err(Error::Transport)?;++ let mut comments = Vec::new();+ let mut next: Option<String> = Some(format!(+ "/repos/{}/issues/{number}/comments?per_page={COMMENTS_PER_PAGE}",+ self.repo+ ));+ let mut pages: u32 = 0;+ let mut more_available = false;+ while let Some(url) = next.take() {+ if pages >= MAX_COMMENT_PAGES {+ more_available = true;+ break;+ }+ pages += 1;+ let resp = self.send(self.request(reqwest::Method::GET, &url)).await?;+ // Presence of a `rel="next"` link governs paging (a short last+ // page still carries none); the page cap above bounds runaway+ // `Link` headers.+ next = next_link(resp.headers())+ .filter(|u| u.starts_with(&format!("{}/", self.base_url)));+ let batch: Vec<ApiComment> = resp.json().await.map_err(Error::Transport)?;+ comments.extend(batch.into_iter().map(Comment::from));+ }++ let labels = raw.label_names();+ let (body, comments, mut truncated) =+ apply_budget(raw.body.unwrap_or_default(), comments);+ if more_available {+ truncated = true;+ }+ Ok(Issue {+ number: raw.number,+ title: raw.title,+ state: raw.state,+ labels,+ body,+ author: raw.user.map(|u| u.login).unwrap_or_default(),+ created_at: raw.created_at,+ comments,+ truncated,+ })+ }++ /// Post a comment; returns the comment's HTML URL. Needs a token.+ pub async fn post_comment(&self, number: u64, body: &str) -> Result<String, Error> {+ if self.token.is_none() {+ return Err(Error::NoToken("post_comment"));+ }+ let path = format!("/repos/{}/issues/{number}/comments", self.repo);+ let resp = self+ .send(+ self.request(reqwest::Method::POST, &path)+ .json(&serde_json::json!({ "body": body })),+ )+ .await?;+ let posted: PostedComment = resp.json().await.map_err(Error::Transport)?;+ if posted.html_url.is_empty() {+ return Err(Error::Api {+ status: 200,+ message: "comment response carried no html_url".to_string(),+ });+ }+ Ok(posted.html_url)+ }++ /// Add labels to an issue. Needs a token.+ pub async fn add_labels(&self, number: u64, labels: &[String]) -> Result<(), Error> {+ if self.token.is_none() {+ return Err(Error::NoToken("add_labels"));+ }+ let path = format!("/repos/{}/issues/{number}/labels", self.repo);+ self.send(+ self.request(reqwest::Method::POST, &path)+ .json(&serde_json::json!({ "labels": labels })),+ )+ .await?;+ Ok(())+ }++ /// Whether a token is configured (write calls need one).+ pub fn has_token(&self) -> bool {+ self.token.as_ref().is_some_and(|t| !t.trim().is_empty())+ }++ /// Remove one label from an issue. Needs a token. A 404 means the label+ /// (or issue) is already gone, so it succeeds.+ pub async fn remove_label(&self, number: u64, name: &str) -> Result<(), Error> {+ if !self.has_token() {+ return Err(Error::NoToken("remove_label"));+ }+ let path = format!(+ "/repos/{}/issues/{number}/labels/{}",+ self.repo,+ percent_encode_label(name)+ );+ let resp = self.send(self.request(reqwest::Method::DELETE, &path)).await;+ match resp {+ Err(Error::Api { status: 404, .. }) => Ok(()),+ other => other.map(|_| ()),+ }+ }++ /// List recent issues created after `created_after` (RFC3339 UTC), oldest+ /// first. PRs are excluded. The list endpoint returns+ /// `state=all&sort=created&direction=asc`; `created_at > created_after`+ /// filters server-ascending output (RFC3339 `Z` strings compare+ /// lexicographically once normalized).+ pub async fn list_issues_since(+ &self,+ created_after: &str,+ limit: u32,+ ) -> Result<Vec<IssueSummary>, Error> {+ let per_page = limit.clamp(1, 100);+ let path = format!("/repos/{}/issues", self.repo);+ let resp = self+ .send(self.request(reqwest::Method::GET, &path).query(&[+ ("state", "all".to_string()),+ ("sort", "created".to_string()),+ ("direction", "asc".to_string()),+ ("per_page", per_page.to_string()),+ ]))+ .await?;+ let found: Vec<ApiIssue> = resp.json().await.map_err(Error::Transport)?;+ let after = normalize_rfc3339(created_after);+ Ok(found+ .into_iter()+ .filter(|i| !i.is_pr())+ .map(summary_from)+ .filter(|s| normalize_rfc3339(&s.created_at) > after)+ .collect())+ }++ /// Whether any comment on the issue contains `marker` (paginated like+ /// [`GitHub::read_issue`]). Read-only: works without a token.+ pub async fn issue_has_marker(&self, number: u64, marker: &str) -> Result<bool, Error> {+ let mut next: Option<String> = Some(format!(+ "/repos/{}/issues/{number}/comments?per_page={COMMENTS_PER_PAGE}",+ self.repo+ ));+ let mut pages: u32 = 0;+ while let Some(url) = next.take() {+ if pages >= MAX_COMMENT_PAGES {+ break;+ }+ pages += 1;+ let resp = self.send(self.request(reqwest::Method::GET, &url)).await?;+ next = next_link(resp.headers())+ .filter(|u| u.starts_with(&format!("{}/", self.base_url)));+ let batch: Vec<ApiComment> = resp.json().await.map_err(Error::Transport)?;+ if batch+ .iter()+ .any(|c| c.body.as_deref().unwrap_or_default().contains(marker))+ {+ return Ok(true);+ }+ }+ Ok(false)+ }+}++/// Percent-encode a label name for the `DELETE .../labels/{name}` path+/// segment (RFC 3986 unreserved set passes through; everything else,+/// including `/` and spaces, is `%XX` uppercase hex).+pub fn percent_encode_label(name: &str) -> String {+ const UNRESERVED: &[u8] =+ b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";+ let mut out = String::with_capacity(name.len());+ for b in name.bytes() {+ if UNRESERVED.contains(&b) {+ out.push(b as char);+ } else {+ out.push_str(&format!("%{b:02X}"));+ }+ }+ out+}++/// Normalize an RFC3339 timestamp to canonical `Z` UTC form so lexicographic+/// comparison equals chronological order. Non-`Z` offsets are rare from this+/// API (it returns `Z`); anything unparseable is returned unchanged.+///+/// Handles `+00:00` → `Z` and fractional seconds.+pub fn normalize_rfc3339(s: &str) -> String {+ let s = s.trim();+ if let Some(base) = s.strip_suffix('Z') {+ return format!("{base}Z");+ }+ if let Some(base) = s.strip_suffix("+00:00") {+ return format!("{base}Z");+ }+ s.to_string()+}++/// Every label the issue labeler treats as an app name (mirrors+/// [`app_module_for_label`]). Triage passes these as the app-label universe+/// for [`crate::triage::plan_label_changes`].+pub const ALL_APP_LABELS: &[&str] = &[+ "appstore",+ "arrows",+ "astronomy",+ "auto",+ "backup",+ "calculator",+ "calendar",+ "camera",+ "cast",+ "chess",+ "clock",+ "code",+ "communicate",+ "contacts",+ "education",+ "email",+ "emergency",+ "euicc",+ "everysync",+ "files",+ "findfamily",+ "flashcards",+ "fooddelivery",+ "globalesim",+ "health",+ "hub",+ "kart",+ "keyboard",+ "launcher",+ "logicgate",+ "logviewer",+ "maps",+ "measure",+ "minesweeper",+ "music",+ "networklocation",+ "nonogram",+ "notes",+ "office",+ "openassistant",+ "parentalcontrols",+ "passwords",+ "pdf",+ "photos",+ "pipes",+ "screentime",+ "securemail",+ "setupwizard",+ "share",+ "shop",+ "solitaire",+ "speech",+ "sudoku",+ "taxi",+ "things",+ "todo",+ "translate",+ "travel",+ "tuner",+ "unblockjam",+ "uniflix",+ "updater",+ "voxels",+ "vpn",+ "watch",+ "weather",+ "web",+ "wordmaker",+ "youpipe",+];++fn summary_from(i: ApiIssue) -> IssueSummary {+ let labels = i.label_names();+ let is_pr = i.is_pr();+ IssueSummary {+ number: i.number,+ title: i.title,+ state: i.state,+ labels,+ comments: i.comments,+ created_at: i.created_at,+ updated_at: i.updated_at,+ is_pr,+ }+}++/// Extract the `rel="next"` URL from a GitHub `Link` header, if present.+fn next_link(headers: &reqwest::header::HeaderMap) -> Option<String> {+ let link = headers.get(reqwest::header::LINK)?.to_str().ok()?;+ for part in link.split(',') {+ let mut halves = part.splitn(2, ';');+ let url = halves.next()?.trim();+ let params = halves.next().unwrap_or("").trim();+ if params.contains("rel=\"next\"") {+ let url = url.strip_prefix('<')?.strip_suffix('>')?;+ return Some(url.to_string());+ }+ }+ None+}++const TRUNC_MARKER: &str = "\n[…truncated]";++/// Cut `s` to at most `max_bytes` (char boundary), noting the cut.+fn truncate_text(s: &str, max_bytes: usize) -> String {+ if s.len() <= max_bytes {+ return s.to_string();+ }+ let mut end = max_bytes.saturating_sub(TRUNC_MARKER.len());+ while end > 0 && !s.is_char_boundary(end) {+ end -= 1;+ }+ format!("{}{TRUNC_MARKER}", &s[..end])+}++/// Fit an issue body plus comments into [`BODY_BUDGET_BYTES`]. The body wins;+/// comments fill the rest in order, the last one fragmented if it partly+/// fits. Returns `(body, comments, truncated)`.+fn apply_budget(body: String, comments: Vec<Comment>) -> (String, Vec<Comment>, bool) {+ if body.len() > BODY_BUDGET_BYTES {+ return (truncate_text(&body, BODY_BUDGET_BYTES), Vec::new(), true);+ }+ let mut kept = Vec::with_capacity(comments.len());+ let mut remaining = BODY_BUDGET_BYTES - body.len();+ let mut truncated = false;+ for c in comments {+ if c.body.len() <= remaining {+ remaining -= c.body.len();+ kept.push(c);+ } else {+ if remaining > 0 {+ kept.push(Comment {+ body: truncate_text(&c.body, remaining),+ ..c+ });+ }+ truncated = true;+ break;+ }+ }+ (body, kept, truncated)+}++/// Map an issue-labeler app name to its repo module dir.+///+/// Derived from the `validApps` list in+/// `.github/workflows/issue_labeler.yml`: most app names equal the top-level+/// dir (`weather` → `weather`); games live under `games/` (`chess` →+/// `games/chess`). Names with no module dir (`watch`) map to `None`, as do+/// non-app labels (`bug`, `enhancement`, versions).+fn app_module_for_label(label: &str) -> Option<String> {+ let label = label.trim().to_lowercase();+ let module = match label.as_str() {+ "arrows" | "chess" | "hub" | "kart" | "logicgate" | "minesweeper" | "nonogram"+ | "pipes" | "solitaire" | "sudoku" | "unblockjam" | "voxels" | "wordmaker" => {+ format!("games/{label}")+ }+ "appstore" | "astronomy" | "auto" | "backup" | "calculator" | "calendar" | "camera"+ | "cast" | "clock" | "code" | "communicate" | "contacts" | "education" | "email"+ | "emergency" | "euicc" | "everysync" | "files" | "findfamily" | "flashcards"+ | "fooddelivery" | "globalesim" | "health" | "keyboard" | "launcher" | "logviewer"+ | "maps" | "measure" | "music" | "networklocation" | "notes" | "office"+ | "openassistant" | "passwords" | "pdf" | "photos" | "parentalcontrols" | "screentime"+ | "setupwizard" | "share" | "shop" | "securemail" | "speech" | "taxi" | "things"+ | "todo" | "translate" | "travel" | "tuner" | "uniflix" | "updater" | "vpn" | "weather"+ | "web" | "youpipe" => label,+ _ => return None,+ };+ Some(module)+}++/// First app-label hit wins; non-app labels are skipped.+pub fn app_module_for_labels(labels: &[String]) -> Option<String> {+ labels.iter().find_map(|l| app_module_for_label(l))+}++/// Every repo module dir an app label can map to (compile-time list; the+/// `mapped_module_dirs_exist_in_worktree` test checks each against the+/// filesystem).+pub const ALL_APP_MODULES: &[&str] = &[+ "appstore",+ "astronomy",+ "auto",+ "backup",+ "calculator",+ "calendar",+ "camera",+ "cast",+ "clock",+ "code",+ "communicate",+ "contacts",+ "education",+ "email",+ "emergency",+ "euicc",+ "everysync",+ "files",+ "findfamily",+ "flashcards",+ "fooddelivery",+ "games/arrows",+ "games/chess",+ "games/hub",+ "games/kart",+ "games/logicgate",+ "games/minesweeper",+ "games/nonogram",+ "games/pipes",+ "games/solitaire",+ "games/sudoku",+ "games/unblockjam",+ "games/voxels",+ "games/wordmaker",+ "globalesim",+ "health",+ "keyboard",+ "launcher",+ "logviewer",+ "maps",+ "measure",+ "music",+ "networklocation",+ "notes",+ "office",+ "openassistant",+ "parentalcontrols",+ "passwords",+ "pdf",+ "photos",+ "screentime",+ "securemail",+ "setupwizard",+ "share",+ "shop",+ "speech",+ "taxi",+ "things",+ "todo",+ "translate",+ "travel",+ "tuner",+ "uniflix",+ "updater",+ "vpn",+ "weather",+ "web",+ "youpipe",+];++/// Compact one-issue rendering for model context.+pub fn render_issue_for_model(issue: &Issue) -> String {+ let mut s = format!("#{} [{}] {}\n", issue.number, issue.state, issue.title);+ s.push_str(&format!("labels: {}\n", issue.labels.join(", ")));+ s.push_str(&format!(+ "author: {} opened: {}\n\n{}\n",+ issue.author, issue.created_at, issue.body+ ));+ if !issue.comments.is_empty() {+ s.push_str(&format!("\n--- {} comment(s) ---\n", issue.comments.len()));+ for c in &issue.comments {+ s.push_str(&format!("\n[{} @ {}]\n{}\n", c.author, c.created_at, c.body));+ }+ }+ if issue.truncated {+ s.push_str("\n[note: body/comments truncated to fit the context budget]\n");+ }+ s+}++/// One line per issue for model context.+pub fn render_search_for_model(issues: &[IssueSummary]) -> String {+ issues+ .iter()+ .map(|i| {+ format!(+ "#{} [{}] ({} comments) [{}] {} — updated {}",+ i.number,+ i.state,+ i.comments,+ i.labels.join(", "),+ i.title,+ i.updated_at+ )+ })+ .collect::<Vec<_>>()+ .join("\n")+}++fn trim_chars(s: &str, max_chars: usize) -> String {+ if s.chars().count() <= max_chars {+ s.to_string()+ } else {+ s.chars().take(max_chars).collect()+ }+}++/// Build a scheduler task from an issue: `(title, prompt, module)`. The title+/// is `"#<n> <issue title>"` trimmed to 80 chars; the prompt carries the body+/// plus comments and instructs the agent to reference `(#n)` in the commit+/// subject.+pub fn task_from_issue(issue: &Issue) -> (String, String, Option<String>) {+ let title = trim_chars(&format!("#{} {}", issue.number, issue.title), 80);+ let module = app_module_for_labels(&issue.labels);+ let labels = if issue.labels.is_empty() {+ "(none)".to_string()+ } else {+ issue.labels.join(", ")+ };+ let mut prompt = format!(+ "GitHub issue #{}: {}\nState: {} | Labels: {} | Author: {}\n\n{}\n",+ issue.number, issue.title, issue.state, labels, issue.author, issue.body+ );+ if !issue.comments.is_empty() {+ prompt.push_str(&format!("\nKey comments ({}):\n", issue.comments.len()));+ for c in &issue.comments {+ prompt.push_str(&format!(+ "\n[{} @ {}]\n{}\n",+ c.author, c.created_at, c.body+ ));+ }+ }+ if issue.truncated {+ prompt.push_str("\n[note: issue body/comments were truncated to fit the context budget]\n");+ }+ if let Some(m) = &module {+ prompt.push_str(&format!("\nWork in module `{m}` (repo-relative).\n"));+ }+ prompt.push_str(&format!(+ "\nWhen you commit the fix, reference (#{}) in the commit subject, e.g. `<module>: <short description> (#{})`.\n",+ issue.number, issue.number+ ));+ (title, prompt, module)+}++#[cfg(test)]+mod tests {+ use super::*;+ use axum::body::Body;+ use axum::extract::State;+ use axum::http::{HeaderMap, StatusCode};+ use axum::response::IntoResponse;+ use std::collections::HashMap;+ use std::sync::{Arc, Mutex};++ const ISSUE_903: &str = include_str!("testdata/github/issue_903.json");+ const COMMENTS_903: &str = include_str!("testdata/github/comments_903.json");+ const COMMENTS_891: &str = include_str!("testdata/github/comments_891.json");+ const SEARCH_WEATHER: &str = include_str!("testdata/github/search_weather.json");+ const LIST_WEATHER: &str = include_str!("testdata/github/list_weather.json");++ #[derive(Debug, Clone)]+ struct RecordedRequest {+ method: String,+ path: String,+ query: String,+ headers: HeaderMap,+ body: Vec<u8>,+ }++ #[derive(Debug, Clone)]+ struct MockResponse {+ status: u16,+ headers: Vec<(String, String)>,+ body: Vec<u8>,+ }++ #[derive(Debug, Clone, Default)]+ struct Mock {+ recorded: Arc<Mutex<Vec<RecordedRequest>>>,+ responses: Arc<Mutex<HashMap<String, MockResponse>>>,+ }++ impl Mock {+ fn respond(+ &self,+ path: &str,+ status: u16,+ headers: &[(&str, &str)],+ body: impl Into<Vec<u8>>,+ ) {+ self.responses.lock().unwrap().insert(+ path.to_string(),+ MockResponse {+ status,+ headers: headers+ .iter()+ .map(|(k, v)| ((*k).to_string(), (*v).to_string()))+ .collect(),+ body: body.into(),+ },+ );+ }++ fn requests(&self) -> Vec<RecordedRequest> {+ self.recorded.lock().unwrap().clone()+ }+ }++ async fn mock_handler(+ State(mock): State<Mock>,+ req: axum::http::Request<Body>,+ ) -> impl IntoResponse {+ let (parts, body) = req.into_parts();+ let body = axum::body::to_bytes(body, 4 * 1024 * 1024)+ .await+ .unwrap_or_default()+ .to_vec();+ mock.recorded.lock().unwrap().push(RecordedRequest {+ method: parts.method.to_string(),+ path: parts.uri.path().to_string(),+ query: parts.uri.query().unwrap_or_default().to_string(),+ headers: parts.headers.clone(),+ body,+ });+ let found = mock+ .responses+ .lock()+ .unwrap()+ .get(parts.uri.path())+ .cloned();+ match found {+ Some(r) => {+ let mut builder = axum::http::Response::builder()+ .status(StatusCode::from_u16(r.status).unwrap_or(StatusCode::OK));+ for (k, v) in &r.headers {+ builder = builder.header(k, v);+ }+ builder.body(Body::from(r.body)).unwrap()+ }+ None => axum::http::Response::builder()+ .status(StatusCode::NOT_FOUND)+ .body(Body::from("no mock for path"))+ .unwrap(),+ }+ }++ async fn spawn_mock(mock: Mock) -> String {+ let app = axum::Router::new()+ .fallback(mock_handler)+ .with_state(mock);+ let lis = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .unwrap();+ let addr = lis.local_addr().unwrap();+ tokio::spawn(async move { axum::serve(lis, app).await.unwrap() });+ format!("http://{addr}")+ }++ fn client(base: &str, token: Option<&str>) -> GitHub {+ GitHub::with_base_url(base, "test-owner/test-repo", token.map(str::to_string)).unwrap()+ }++ fn json() -> [(&'static str, &'static str); 1] {+ [("content-type", "application/json")]+ }++ /// Decode `application/x-www-form-urlencoded` enough for assertions.+ fn decode_query(q: &str) -> String {+ let mut out = String::new();+ let bytes = q.as_bytes();+ let mut i = 0;+ while i < bytes.len() {+ match bytes[i] {+ b'+' => {+ out.push(' ');+ i += 1;+ }+ b'%' if i + 2 < bytes.len() => {+ if let Ok(b) = u8::from_str_radix(&q[i + 1..i + 3], 16) {+ out.push(b as char);+ }+ i += 3;+ }+ b => {+ out.push(b as char);+ i += 1;+ }+ }+ }+ out+ }++ fn sample_issue() -> Issue {+ Issue {+ number: 903,+ title: "Weather widgets only show Celsius".to_string(),+ state: "open".to_string(),+ labels: vec!["bug".to_string(), "weather".to_string()],+ body: "Widget shows C only.".to_string(),+ author: "coolpx".to_string(),+ created_at: "2026-11-05T04:51:07Z".to_string(),+ comments: vec![Comment {+ author: "vayun-mathur".to_string(),+ created_at: "2026-11-05T10:00:00Z".to_string(),+ body: "Reproduced, fixing.".to_string(),+ }],+ truncated: false,+ }+ }++ #[test]+ fn foreign_pagination_links_never_get_the_token() {+ let gh = GitHub::with_base_url("https://api.github.com", "o/r", Some("tok".into())).unwrap();+ let ok = gh.request(reqwest::Method::GET, "https://api.github.com/repos/o/r/issues/1/comments?page=2").build().unwrap();+ assert_eq!(ok.url().host_str(), Some("api.github.com"));+ let evil = gh.request(reqwest::Method::GET, "https://evil.example/steal").build().unwrap();+ assert_eq!(evil.url().host_str(), Some("api.github.com"));+ let sneaky = gh.request(reqwest::Method::GET, "https://api.github.com.evil.example/x").build().unwrap();+ assert_eq!(sneaky.url().host_str(), Some("api.github.com"));+ }++ #[tokio::test]+ async fn search_uses_search_api_with_query() {+ let mock = Mock::default();+ mock.respond("/search/issues", 200, &json(), SEARCH_WEATHER);+ let base = spawn_mock(mock.clone()).await;+ let gh = client(&base, None);++ let out = gh+ .search_issues(Some("celsius"), &["weather".to_string()], IssueState::Open, 5)+ .await+ .unwrap();+ assert_eq!(out.len(), 3);+ assert!(out.iter().all(|i| !i.is_pr));+ let nums: Vec<u64> = out.iter().map(|i| i.number).collect();+ assert!(nums.contains(&903));++ let reqs = mock.requests();+ assert_eq!(reqs.len(), 1);+ assert_eq!(reqs[0].method, "GET");+ assert_eq!(reqs[0].path, "/search/issues");+ let q = decode_query(&reqs[0].query);+ assert!(q.contains("repo:test-owner/test-repo"), "q={q}");+ assert!(q.contains("is:issue"), "q={q}");+ assert!(q.contains("celsius"), "q={q}");+ assert!(q.contains("state:open"), "q={q}");+ assert!(q.contains("label:\"weather\""), "q={q}");++ assert_eq!(reqs[0].headers.get("user-agent").unwrap(), "agentd");+ assert_eq!(+ reqs[0].headers.get("accept").unwrap(),+ "application/vnd.github+json"+ );+ assert_eq!(+ reqs[0].headers.get("x-github-api-version").unwrap(),+ "2022-11-28"+ );+ assert!(reqs[0].headers.get("authorization").is_none());+ }++ #[tokio::test]+ async fn list_endpoint_used_without_query() {+ let mock = Mock::default();+ mock.respond("/repos/test-owner/test-repo/issues", 200, &json(), LIST_WEATHER);+ let base = spawn_mock(mock.clone()).await;+ let gh = client(&base, None);++ let out = gh+ .search_issues(None, &["weather".to_string()], IssueState::Open, 5)+ .await+ .unwrap();+ assert_eq!(out.len(), 3);+ assert!(out.iter().all(|i| !i.is_pr));++ let reqs = mock.requests();+ assert_eq!(reqs.len(), 1);+ assert_eq!(reqs[0].path, "/repos/test-owner/test-repo/issues");+ let q = decode_query(&reqs[0].query);+ assert!(q.contains("labels=weather"), "q={q}");+ assert!(q.contains("state=open"), "q={q}");+ }++ #[tokio::test]+ async fn search_excludes_pull_requests() {+ let body = serde_json::json!({+ "total_count": 2,+ "incomplete_results": false,+ "items": [+ {"number": 10, "title": "Real issue", "state": "open",+ "labels": [], "comments": 0, "updated_at": "2026-11-05T00:00:00Z"},+ {"number": 11, "title": "A PR", "state": "open",+ "labels": [], "comments": 0, "updated_at": "2026-11-05T00:00:00Z",+ "pull_request": {"url": "https://api.github.com/x", "html_url": "https://github.com/x"}},+ ],+ });+ let mock = Mock::default();+ mock.respond(+ "/search/issues",+ 200,+ &json(),+ serde_json::to_vec(&body).unwrap(),+ );+ let base = spawn_mock(mock.clone()).await;+ let gh = client(&base, None);++ let out = gh+ .search_issues(Some("x"), &[], IssueState::All, 10)+ .await+ .unwrap();+ assert_eq!(out.len(), 1);+ assert_eq!(out[0].number, 10);+ }++ #[tokio::test]+ async fn read_issue_parses_fixture() {+ let mock = Mock::default();+ mock.respond("/repos/test-owner/test-repo/issues/903", 200, &json(), ISSUE_903);+ mock.respond(+ "/repos/test-owner/test-repo/issues/903/comments",+ 200,+ &json(),+ COMMENTS_903,+ );+ let base = spawn_mock(mock.clone()).await;+ let gh = client(&base, None);++ let issue = gh.read_issue(903).await.unwrap();+ assert_eq!(issue.number, 903);+ assert_eq!(issue.title, "[bug]: Weather widgets only show Celsius");+ assert_eq!(issue.state, "open");+ assert_eq!(issue.author, "coolpx");+ assert!(issue.labels.contains(&"weather".to_string()));+ assert!(issue.labels.contains(&"bug".to_string()));+ assert!(issue.body.contains("Celsius"));+ assert!(issue.comments.is_empty());+ assert!(!issue.truncated);+ }++ #[tokio::test]+ async fn read_issue_follows_comment_pagination() {+ let mock = Mock::default();+ let base = spawn_mock(mock.clone()).await;+ // Register pages after the base URL is known so the `Link`+ // header can point at the absolute mock URL (the handler+ // looks responses up at request time, so this is race-free here:+ // the client issues no request until below).+ mock.respond(+ "/repos/test-owner/test-repo/issues/42",+ 200,+ &json(),+ r#"{"number":42,"title":"T","state":"open","labels":[],"user":{"login":"a"},+ "created_at":"2026-11-05T00:00:00Z","body":"b"}"#,+ );+ mock.respond(+ "/repos/test-owner/test-repo/issues/42/comments",+ 200,+ &[+ ("content-type", "application/json"),+ (+ "link",+ &format!("<{base}/page2>; rel=\"next\", <{base}/page2>; rel=\"last\""),+ ),+ ],+ r#"[{"id":1,"user":{"login":"a"},"created_at":"2026-11-05T01:00:00Z","body":"first"}]"#,+ );+ mock.respond(+ "/page2",+ 200,+ &json(),+ r#"[{"id":2,"user":{"login":"b"},"created_at":"2026-11-05T02:00:00Z","body":"second"}]"#,+ );+ let gh = client(&base, None);++ let issue = gh.read_issue(42).await.unwrap();+ assert_eq!(issue.comments.len(), 2);+ assert_eq!(issue.comments[0].body, "first");+ assert_eq!(issue.comments[1].author, "b");+ assert!(!issue.truncated);+ let paths: Vec<String> = mock.requests().iter().map(|r| r.path.clone()).collect();+ assert!(paths.contains(&"/page2".to_string()), "{paths:?}");+ }++ #[tokio::test]+ async fn read_issue_truncates_to_budget() {+ let mock = Mock::default();+ mock.respond(+ "/repos/test-owner/test-repo/issues/903",+ 200,+ &json(),+ ISSUE_903,+ );+ // Real comment fixture plus a synthetic long comment so the total+ // exceeds the 12 KB budget (recorded bodies alone fit).+ let mut comments: Vec<serde_json::Value> =+ serde_json::from_str(COMMENTS_891).unwrap();+ comments.push(serde_json::json!({+ "id": 999, "user": {"login": "someone"},+ "created_at": "2026-11-05T03:00:00Z",+ "body": "y".repeat(20_000),+ }));+ mock.respond(+ "/repos/test-owner/test-repo/issues/903/comments",+ 200,+ &json(),+ serde_json::to_vec(&comments).unwrap(),+ );+ let base = spawn_mock(mock.clone()).await;+ let gh = client(&base, None);++ let issue = gh.read_issue(903).await.unwrap();+ assert!(issue.truncated);+ let total: usize =+ issue.body.len() + issue.comments.iter().map(|c| c.body.len()).sum::<usize>();+ assert!(total <= BODY_BUDGET_BYTES, "total={total}");+ // The over-budget tail comment is kept but fragmented in place.+ let last = issue.comments.last().unwrap();+ assert!(last.body.ends_with("[…truncated]"), "last={:?}", &last.body[last.body.len().saturating_sub(20)..]);+ }++ #[test]+ fn apply_budget_truncates_oversize_body() {+ let (body, comments, truncated) = apply_budget("x".repeat(20_000), vec![sample_issue().comments.remove(0)]);+ assert!(truncated);+ assert!(body.len() <= BODY_BUDGET_BYTES);+ assert!(body.ends_with(TRUNC_MARKER));+ assert!(comments.is_empty());+ }++ #[tokio::test]+ async fn auth_header_sent_only_with_token() {+ let mock = Mock::default();+ mock.respond("/search/issues", 200, &json(), SEARCH_WEATHER);+ let base = spawn_mock(mock.clone()).await;++ client(&base, Some("tok123"))+ .search_issues(Some("q"), &[], IssueState::Open, 1)+ .await+ .unwrap();+ client(&base, None)+ .search_issues(Some("q"), &[], IssueState::Open, 1)+ .await+ .unwrap();++ let reqs = mock.requests();+ assert_eq!(reqs.len(), 2);+ assert_eq!(reqs[0].headers.get("authorization").unwrap(), "Bearer tok123");+ assert!(reqs[1].headers.get("authorization").is_none());+ }++ #[tokio::test]+ async fn rate_limit_errors_carry_reset_time() {+ let mock = Mock::default();+ mock.respond(+ "/search/issues",+ 403,+ &[+ ("content-type", "application/json"),+ ("x-ratelimit-remaining", "0"),+ ("x-ratelimit-reset", "1793900736"),+ ],+ r#"{"message":"API rate limit exceeded"}"#,+ );+ mock.respond(+ "/repos/test-owner/test-repo/issues",+ 429,+ &[("content-type", "application/json"), ("retry-after", "60")],+ r#"{"message":"slow down"}"#,+ );+ let base = spawn_mock(mock.clone()).await;+ let gh = client(&base, None);++ let err = gh+ .search_issues(Some("q"), &[], IssueState::Open, 1)+ .await+ .unwrap_err();+ assert!(matches!(err, Error::RateLimited { .. }), "{err:?}");+ assert!(err.to_string().contains("1793900736"), "{err}");++ let err = gh+ .search_issues(None, &[], IssueState::Open, 1)+ .await+ .unwrap_err();+ assert!(matches!(err, Error::RateLimited { .. }), "{err:?}");++ // A plain 403 without rate-limit headers is a normal API error.+ let mock2 = Mock::default();+ mock2.respond(+ "/repos/test-owner/test-repo/issues/1",+ 403,+ &json(),+ r#"{"message":"Forbidden"}"#,+ );+ let base2 = spawn_mock(mock2.clone()).await;+ let err = client(&base2, None).read_issue(1).await.unwrap_err();+ assert!(matches!(err, Error::Api { status: 403, .. }), "{err:?}");+ assert!(err.to_string().contains("Forbidden"), "{err}");+ }++ #[tokio::test]+ async fn post_comment_shape_and_token_required() {+ let mock = Mock::default();+ mock.respond(+ "/repos/test-owner/test-repo/issues/1/comments",+ 201,+ &json(),+ r#"{"html_url":"https://github.com/test-owner/test-repo/issues/1#issuecomment-9"}"#,+ );+ let base = spawn_mock(mock.clone()).await;++ let url = client(&base, Some("tok"))+ .post_comment(1, "hello")+ .await+ .unwrap();+ assert_eq!(+ url,+ "https://github.com/test-owner/test-repo/issues/1#issuecomment-9"+ );+ let reqs = mock.requests();+ assert_eq!(reqs.len(), 1);+ assert_eq!(reqs[0].method, "POST");+ let v: serde_json::Value = serde_json::from_slice(&reqs[0].body).unwrap();+ assert_eq!(v, serde_json::json!({ "body": "hello" }));++ // No token: error before any HTTP call (unreachable base proves it).+ let offline =+ GitHub::with_base_url("http://127.0.0.1:9", "o/r", None).unwrap();+ assert!(matches!(+ offline.post_comment(1, "x").await,+ Err(Error::NoToken(_))+ ));+ assert!(matches!(+ offline.add_labels(1, &["a".to_string()]).await,+ Err(Error::NoToken(_))+ ));+ }++ #[tokio::test]+ async fn add_labels_shape() {+ let mock = Mock::default();+ mock.respond(+ "/repos/test-owner/test-repo/issues/1/labels",+ 200,+ &json(),+ r#"[{"name":"solved for next release"}]"#,+ );+ let base = spawn_mock(mock.clone()).await;++ client(&base, Some("tok"))+ .add_labels(1, &["solved for next release".to_string()])+ .await+ .unwrap();+ let reqs = mock.requests();+ assert_eq!(reqs.len(), 1);+ assert_eq!(reqs[0].method, "POST");+ assert_eq!(reqs[0].path, "/repos/test-owner/test-repo/issues/1/labels");+ let v: serde_json::Value = serde_json::from_slice(&reqs[0].body).unwrap();+ assert_eq!(v, serde_json::json!({ "labels": ["solved for next release"] }));+ }++ #[test]+ fn label_to_module_spot_checks() {+ let app = |s: &str| app_module_for_labels(&[s.to_string()]);+ assert_eq!(app("weather"), Some("weather".to_string()));+ assert_eq!(app("chess"), Some("games/chess".to_string()));+ assert_eq!(app("logicgate"), Some("games/logicgate".to_string()));+ assert_eq!(app("hub"), Some("games/hub".to_string()));+ assert_eq!(app("voxels"), Some("games/voxels".to_string()));+ assert_eq!(app("Weather"), Some("weather".to_string()));+ assert_eq!(app("watch"), None);+ assert_eq!(app("bug"), None);+ assert_eq!(app("enhancement"), None);+ assert_eq!(app("2.6.12"), None);+ assert_eq!(app("solved for next release"), None);+ // First app label wins over non-app labels.+ assert_eq!(+ app_module_for_labels(&[+ "bug".to_string(),+ "2.6.12".to_string(),+ "kart".to_string()+ ]),+ Some("games/kart".to_string())+ );+ assert_eq!(app_module_for_labels(&["bug".to_string()]), None);+ }++ #[test]+ fn ma
Diff truncated.