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

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

tests_integration.rs2430 lines · 106.6 KiBRaw
1//! In-process integration tests: mock OpenRouter + mock runner (real temp
2//! git repos, real bundles) + the real agentd HTTP server + scheduler.
3//!
4//! Covers: full success flow (read → edit → build → finish, branch pushed
5//! to the temp remote, token absent from logs/events), unauthenticated POST
6//! rejection, wrong-Origin rejection, and release-signal build preemption.
7
8#[cfg(test)]
9mod integration {
10 use std::collections::{HashMap, VecDeque};
11 use std::net::SocketAddr;
12 use std::path::{Path, PathBuf};
13 use std::process::Stdio;
14 use std::sync::{Arc, Mutex};
15
16 use axum::extract::{Path as AxPath, State};
17 use axum::http::{header, HeaderMap, StatusCode};
18 use axum::response::IntoResponse;
19 use axum::routing::{get, post};
20 use tokio::process::Command as TokioCommand;
21
22 use crate::state::AppState;
23 use crate::store::Store;
24
25 // ---------- tiny git helper (argv only, no shell) ----------
26
27 async fn git(dir: &Path, args: &[&str]) -> String {
28 let out = TokioCommand::new("git")
29 .arg("-C")
30 .arg(dir)
31 .args(args)
32 .env("GIT_PAGER", "cat")
33 .env("GIT_CONFIG_NOSYSTEM", "1")
34 .env("GIT_CONFIG_GLOBAL", "/dev/null")
35 .stdin(Stdio::null())
36 .output()
37 .await
38 .expect("spawn git");
39 assert!(
40 out.status.success(),
41 "git {} failed: {}",
42 args.join(" "),
43 String::from_utf8_lossy(&out.stderr)
44 );
45 String::from_utf8(out.stdout).unwrap()
46 }
47
48 async fn git_no_cwd(args: &[&str], workdir: &Path) -> String {
49 let out = TokioCommand::new("git")
50 .args(args)
51 .current_dir(workdir)
52 .env("GIT_PAGER", "cat")
53 .env("GIT_CONFIG_NOSYSTEM", "1")
54 .env("GIT_CONFIG_GLOBAL", "/dev/null")
55 .stdin(Stdio::null())
56 .output()
57 .await
58 .expect("spawn git");
59 assert!(
60 out.status.success(),
61 "git {} failed: {}",
62 args.join(" "),
63 String::from_utf8_lossy(&out.stderr)
64 );
65 String::from_utf8(out.stdout).unwrap()
66 }
67
68 /// Build a temp bare "remote" with one commit (`main` + AGENTS.md files).
69 async fn init_remote(tmp: &Path) -> PathBuf {
70 let remote = tmp.join("remote.git");
71 git_no_cwd(
72 &[
73 "init",
74 "--bare",
75 "-b",
76 "main",
77 remote.to_str().unwrap(),
78 ],
79 tmp,
80 )
81 .await;
82 let work = tmp.join("seed");
83 git_no_cwd(
84 &[
85 "clone",
86 remote.to_str().unwrap(),
87 work.to_str().unwrap(),
88 ],
89 tmp,
90 )
91 .await;
92 git_no_cwd(&["config", "user.email", "t@t"], &work).await;
93 git_no_cwd(&["config", "user.name", "t"], &work).await;
94 std::fs::create_dir_all(work.join("notes")).unwrap();
95 std::fs::write(work.join("AGENTS.md"), "ROOT RULES FOR TEST\n").unwrap();
96 std::fs::write(work.join("notes/AGENTS.md"), "NOTES MODULE RULES\n").unwrap();
97 std::fs::write(work.join("notes/file.txt"), "hello\n").unwrap();
98 // A committed JUnit report with one failure, so `run_tests` has XML
99 // to parse in every slot checkout. Committed → never pollutes diffs.
100 let xml_dir = work.join("notes/build/test-results/testDevUnitTest");
101 std::fs::create_dir_all(&xml_dir).unwrap();
102 std::fs::write(
103 xml_dir.join("TEST-com.example.GreetingTest.xml"),
104 r#"<?xml version="1.0" encoding="UTF-8"?>
105<testsuite name="com.example.GreetingTest" tests="3" skipped="0" failures="1" errors="0">
106 <testcase name="saysHello" classname="com.example.GreetingTest" time="0.01"/>
107 <testcase name="shoutsGreeting" classname="com.example.GreetingTest" time="0.02">
108 <failure message="expected:&lt;HELLO&gt; but was:&lt;hello&gt;">AssertionFailedError: expected:&lt;HELLO&gt; but was:&lt;hello&gt;
109 at com.example.GreetingTest.shoutsGreeting(GreetingTest.kt:42)
110</failure>
111 </testcase>
112 <testcase name="emptyIsEmpty" classname="com.example.GreetingTest" time="0.0"/>
113</testsuite>
114"#,
115 )
116 .unwrap();
117 git_no_cwd(&["add", "-A"], &work).await;
118 git_no_cwd(&["commit", "-m", "seed commit"], &work).await;
119 git_no_cwd(&["push", "origin", "main"], &work).await;
120 remote
121 }
122
123 // ---------- mock OpenRouter (scripted responses) ----------
124
125 #[derive(Clone)]
126 struct MockOr {
127 script: Arc<Mutex<VecDeque<serde_json::Value>>>,
128 seen: Arc<Mutex<Vec<serde_json::Value>>>,
129 }
130
131 async fn mock_or_chat(
132 State(st): State<MockOr>,
133 headers: HeaderMap,
134 body: axum::Json<serde_json::Value>,
135 ) -> impl IntoResponse {
136 // `usage: {include: true}` must be requested.
137 let usage_ok = body.get("usage").and_then(|u| u.get("include")).and_then(|v| v.as_bool()).unwrap_or(false);
138 assert!(usage_ok, "agentd must send usage:{{include:true}}");
139 assert!(
140 headers.contains_key(header::AUTHORIZATION),
141 "auth header present"
142 );
143 st.seen.lock().unwrap().push(body.0.clone());
144 let next = st.script.lock().unwrap().pop_front().unwrap_or_else(|| {
145 serde_json::json!({
146 "choices": [{"message": {"role": "assistant", "content": "stuck"}}],
147 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
148 })
149 });
150 axum::Json(next)
151 }
152
153 fn tool_resp(id: &str, name: &str, args: serde_json::Value, text: &str) -> serde_json::Value {
154 serde_json::json!({
155 "choices": [{"message": {
156 "role": "assistant", "content": text,
157 "tool_calls": [{
158 "id": id, "type": "function",
159 "function": {"name": name, "arguments": serde_json::to_string(&args).unwrap()}
160 }]
161 }}],
162 "usage": {"prompt_tokens": 10, "completion_tokens": 5, "cost": 0.0001}
163 })
164 }
165
166 fn success_script() -> Vec<serde_json::Value> {
167 vec![
168 tool_resp("c1", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading"),
169 tool_resp(
170 "c2",
171 "edit_file",
172 serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello world\n"}),
173 "editing",
174 ),
175 tool_resp(
176 "c3",
177 "build",
178 serde_json::json!({"command": "./gradlew :notes:compileDevKotlin"}),
179 "building",
180 ),
181 tool_resp(
182 "c4",
183 "finish",
184 serde_json::json!({
185 "summary": "Changed the greeting.",
186 "commit_message": "notes: change greeting\n\nSwitched the greeting text per the task."
187 }),
188 "finishing",
189 ),
190 ]
191 }
192
193 async fn serve_mock_or(script: Vec<serde_json::Value>) -> (String, MockOr) {
194 let st = MockOr {
195 script: Arc::new(Mutex::new(script.into())),
196 seen: Arc::new(Mutex::new(Vec::new())),
197 };
198 let app = axum::Router::new()
199 .route("/chat/completions", post(mock_or_chat))
200 .with_state(st.clone());
201 let lis = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
202 let addr = lis.local_addr().unwrap();
203 tokio::spawn(async move { axum::serve(lis, app).await.unwrap() });
204 (format!("http://{addr}"), st)
205 }
206
207 // ---------- mock runner (real git checkout per slot) ----------
208
209 /// One canned exec response: commands containing `pattern` get
210 /// (`exit_code`, `stdout`, `stderr`).
211 type CannedExec = (String, i32, String, String);
212
213 struct SlotState {
214 dir: PathBuf,
215 branch: String,
216 base_sha: String,
217 }
218
219 #[derive(Clone)]
220 struct MockRunner {
221 slots: Arc<Mutex<std::collections::HashMap<u32, SlotState>>>,
222 /// Repo slots clone from (agentd's mirror in the harness, so WIP refs
223 /// imported by agentd are fetchable) and record of every prepare as
224 /// `(slot, branch)` — resume may migrate a task to another slot.
225 clone_source: PathBuf,
226 prepares: Arc<Mutex<Vec<(u32, String)>>>,
227 build_seen: Arc<Mutex<Vec<String>>>,
228 build_should_preempt: bool,
229 /// Canned exec responses, first-match wins: `(substring, exit_code,
230 /// stdout, stderr)`. Checked before the default success response so
231 /// tests can simulate build/test failures per command pattern.
232 canned_exec: Arc<Mutex<Vec<CannedExec>>>,
233 /// Unique per-harness scratch dir. Slot checkouts live under it so
234 /// parallel tests (same process, distinct harnesses) never share a
235 /// slot directory. (An earlier revision used a fixed
236 /// `$TMPDIR/mockslot-{pid}-{slot}` path; two harnesses preparing the
237 /// same slot concurrently deleted each other's checkout mid-task.)
238 scratch: PathBuf,
239 }
240
241 impl MockRunner {
242 /// Add a canned exec response for commands containing `pattern`.
243 fn canned(&self, pattern: &str, exit_code: i32, stdout: &str, stderr: &str) {
244 self.canned_exec.lock().unwrap().push((
245 pattern.to_string(),
246 exit_code,
247 stdout.to_string(),
248 stderr.to_string(),
249 ));
250 }
251 }
252
253 #[allow(dead_code)]
254 fn parse_slot(path: &str, suffix: &str) -> Option<u32> {
255 // "/v1/slots/{slot}/{suffix}"
256 let rest = path.strip_prefix("/v1/slots/")?;
257 let (slot, tail) = rest.split_once('/')?;
258 if !tail.starts_with(suffix) {
259 return None;
260 }
261 slot.parse().ok()
262 }
263 async fn mock_prepare(
264 State(st): State<MockRunner>,
265 AxPath(slot): AxPath<u32>,
266 body: axum::Json<serde_json::Value>,
267 ) -> impl IntoResponse {
268 let branch = body.get("branch").and_then(|v| v.as_str()).unwrap_or("").to_string();
269 assert!(branch.starts_with("agent/"), "branch prefix");
270 // Record which slot each prepare lands on (resume may migrate slots).
271 st.prepares.lock().unwrap().push((slot, branch.clone()));
272 // Per-harness scratch dir: parallel tests (same process, distinct
273 // harnesses) must never share a slot checkout. A fixed
274 // `$TMPDIR/mockslot-{pid}-{slot}` path let two harnesses preparing
275 // the same slot concurrently delete each other's checkout mid-task.
276 let dir = st.scratch.join(format!("slot-{slot}"));
277 std::fs::create_dir_all(&st.scratch).unwrap();
278 let _ = std::fs::remove_dir_all(&dir);
279 git_no_cwd(
280 &["clone", st.clone_source.to_str().unwrap(), dir.to_str().unwrap()],
281 &st.scratch,
282 )
283 .await;
284 git(&dir, &["config", "user.email", "t@t"]).await;
285 git(&dir, &["config", "user.name", "t"]).await;
286 // Resume branch: fetch the WIP ref from the clone source (agentd's
287 // mirror) into the slot, check out the WIP sha, then reset --soft
288 // the base so the work reappears as uncommitted changes. Fresh
289 // prepare: new branch from main.
290 let base = if let Some(resume) = body.get("resume") {
291 let base_sha = resume.get("base_sha").and_then(|v| v.as_str()).unwrap_or("").to_string();
292 assert!(!base_sha.is_empty(), "resume needs base_sha");
293 if let (Some(wip_ref), Some(wip_sha)) = (
294 resume.get("wip_ref").and_then(|v| v.as_str()),
295 resume.get("wip_sha").and_then(|v| v.as_str()),
296 ) {
297 // Explicit fetch of the exact ref (plain `fetch origin` would
298 // not pick up `refs/agent-wip/*`).
299 git(&dir, &["fetch", "origin", &format!("+{wip_ref}:{wip_ref}")]).await;
300 let got = git(&dir, &["rev-parse", wip_ref]).await;
301 assert_eq!(got.trim(), wip_sha, "WIP ref sha must match");
302 git(&dir, &["checkout", "-B", &branch, wip_sha]).await;
303 git(&dir, &["reset", "--soft", &base_sha]).await;
304 } else {
305 git(&dir, &["checkout", "-B", &branch, &base_sha]).await;
306 }
307 // `.git/agent-base` records the original base, like the runner.
308 std::fs::write(dir.join(".git/agent-base"), &base_sha).unwrap();
309 base_sha
310 } else {
311 git(&dir, &["checkout", "-b", &branch]).await;
312 let base = git(&dir, &["rev-parse", "HEAD"]).await;
313 base.trim().to_string()
314 };
315 st.slots.lock().unwrap().insert(
316 slot,
317 SlotState { dir, branch, base_sha: base.clone() },
318 );
319 (
320 StatusCode::OK,
321 axum::Json(serde_json::json!({"base_sha": base})),
322 )
323 }
324
325 async fn mock_read(
326 State(st): State<MockRunner>,
327 AxPath(slot): AxPath<u32>,
328 body: axum::Json<serde_json::Value>,
329 ) -> impl IntoResponse {
330 let dir = st.slots.lock().unwrap().get(&slot).unwrap().dir.clone();
331 let rel = body.get("path").and_then(|v| v.as_str()).unwrap_or("");
332 let content = std::fs::read_to_string(dir.join(rel)).unwrap_or_else(|_| "MISSING".into());
333 let total = content.lines().count();
334 axum::Json(serde_json::json!({"content": content, "total_lines": total, "truncated": false}))
335 }
336
337 async fn mock_write(
338 State(st): State<MockRunner>,
339 AxPath(slot): AxPath<u32>,
340 body: axum::Json<serde_json::Value>,
341 ) -> impl IntoResponse {
342 let dir = st.slots.lock().unwrap().get(&slot).unwrap().dir.clone();
343 let rel = body.get("path").and_then(|v| v.as_str()).unwrap_or("");
344 let content = body.get("content").and_then(|v| v.as_str()).unwrap_or("");
345 let p = dir.join(rel);
346 std::fs::create_dir_all(p.parent().unwrap()).unwrap();
347 std::fs::write(p, content).unwrap();
348 (StatusCode::OK, axum::Json(serde_json::json!({})))
349 }
350
351 async fn mock_edit(
352 State(st): State<MockRunner>,
353 AxPath(slot): AxPath<u32>,
354 body: axum::Json<serde_json::Value>,
355 ) -> impl IntoResponse {
356 let dir = st.slots.lock().unwrap().get(&slot).unwrap().dir.clone();
357 let rel = body.get("path").and_then(|v| v.as_str()).unwrap_or("");
358 let old = body.get("old").and_then(|v| v.as_str()).unwrap_or("");
359 let new = body.get("new").and_then(|v| v.as_str()).unwrap_or("");
360 let p = dir.join(rel);
361 let content = std::fs::read_to_string(&p).unwrap();
362 if content.matches(old).count() != 1 {
363 return (
364 StatusCode::CONFLICT,
365 axum::Json(serde_json::json!({"error": "old must occur exactly once"})),
366 );
367 }
368 std::fs::write(p, content.replacen(old, new, 1)).unwrap();
369 (StatusCode::OK, axum::Json(serde_json::json!({})))
370 }
371
372 async fn mock_exec(
373 State(st): State<MockRunner>,
374 AxPath(slot): AxPath<u32>,
375 body: axum::Json<serde_json::Value>,
376 ) -> impl IntoResponse {
377 let cmd = body.get("command").and_then(|v| v.as_str()).unwrap_or("").to_string();
378 let kind = body.get("kind").and_then(|v| v.as_str()).unwrap_or("").to_string();
379 st.build_seen.lock().unwrap().push(cmd.clone());
380 if st.build_should_preempt && kind == "build" {
381 // Simulate a release kill: killed=true like the real runner.
382 return axum::Json(serde_json::json!({
383 "exit_code": null, "stdout": "", "stderr": "killed",
384 "truncated": false, "timed_out": false, "killed": true,
385 "queued_ms": 0, "duration_ms": 5
386 }));
387 }
388 {
389 let canned = st.canned_exec.lock().unwrap().clone();
390 for (pattern, exit_code, stdout, stderr) in &canned {
391 if cmd.contains(pattern.as_str()) {
392 return axum::Json(serde_json::json!({
393 "exit_code": exit_code, "stdout": stdout, "stderr": stderr,
394 "truncated": false, "timed_out": false, "killed": false,
395 "queued_ms": 0, "duration_ms": 5
396 }));
397 }
398 }
399 }
400 if kind == "shell" {
401 // Bind the dir in its own statement: holding the std MutexGuard
402 // across the `.await` below would make the future !Send and break
403 // axum's Handler bound.
404 let dir = st.slots.lock().unwrap().get(&slot).map(|s| s.dir.clone());
405 if let Some(dir) = dir {
406 // Only allow the read-only commands agentd's structured tools
407 // build (defense in depth: the harness never runs arbitrary
408 // shell from these tests).
409 let allowed = cmd.starts_with("git log ")
410 || cmd.starts_with("git show ")
411 || cmd.starts_with("git blame ")
412 || cmd.starts_with("rg --files ");
413 if allowed {
414 let out = TokioCommand::new("bash")
415 .arg("-lc")
416 .arg(&cmd)
417 .current_dir(&dir)
418 .env("GIT_PAGER", "cat")
419 .env("GIT_CONFIG_NOSYSTEM", "1")
420 .env("GIT_CONFIG_GLOBAL", "/dev/null")
421 .stdin(Stdio::null())
422 .output()
423 .await
424 .unwrap();
425 return axum::Json(serde_json::json!({
426 "exit_code": out.status.code().unwrap_or(1),
427 "stdout": String::from_utf8_lossy(&out.stdout),
428 "stderr": String::from_utf8_lossy(&out.stderr),
429 "truncated": false, "timed_out": false, "killed": false,
430 "queued_ms": 0, "duration_ms": 5
431 }));
432 }
433 }
434 }
435 // Fake build success; run `true`-equivalent by touching nothing.
436 axum::Json(serde_json::json!({
437 "exit_code": 0, "stdout": format!("ok: {cmd}"),
438 "stderr": "", "truncated": false, "timed_out": false,
439 "killed": false, "queued_ms": 0, "duration_ms": 5
440 }))
441 }
442
443 /// `list` backed by the real slot checkout (mirrors the runner: one
444 /// level, dirs end with `/`, sorted). Needed by `run_tests`, which lists
445 /// the JUnit XML dir.
446 async fn mock_list(
447 State(st): State<MockRunner>,
448 AxPath(slot): AxPath<u32>,
449 body: axum::Json<serde_json::Value>,
450 ) -> impl IntoResponse {
451 let dir = st.slots.lock().unwrap().get(&slot).unwrap().dir.clone();
452 let rel = body.get("path").and_then(|v| v.as_str()).unwrap_or("");
453 let target = dir.join(rel);
454 let mut entries: Vec<String> = Vec::new();
455 if let Ok(rd) = std::fs::read_dir(&target) {
456 for entry in rd.flatten() {
457 let name = entry.file_name().to_string_lossy().to_string();
458 if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
459 entries.push(format!("{name}/"));
460 } else {
461 entries.push(name);
462 }
463 }
464 }
465 entries.sort();
466 axum::Json(serde_json::json!({"entries": entries, "truncated": false}))
467 }
468
469 async fn mock_diff(
470 State(st): State<MockRunner>,
471 AxPath(slot): AxPath<u32>,
472 _body: axum::Json<serde_json::Value>,
473 ) -> impl IntoResponse {
474 let dir = st.slots.lock().unwrap().get(&slot).unwrap().dir.clone();
475 git(&dir, &["add", "-A"]).await;
476 let diff = git(&dir, &["diff", "--cached"]).await;
477 let stat = git(&dir, &["diff", "--cached", "--stat"]).await;
478 axum::Json(serde_json::json!({"stat": stat, "diff": diff, "truncated": false}))
479 }
480
481 async fn mock_commit(
482 State(st): State<MockRunner>,
483 AxPath(slot): AxPath<u32>,
484 body: axum::Json<serde_json::Value>,
485 ) -> impl IntoResponse {
486 let dir = st.slots.lock().unwrap().get(&slot).unwrap().dir.clone();
487 let msg = body.get("message").and_then(|v| v.as_str()).unwrap_or("").to_string();
488 git(&dir, &["add", "-A"]).await;
489 // Identity comes from the slot repo's local config (set at prepare),
490 // mirroring the real runner where the sandbox user has its own git
491 // identity — agentd never injects one.
492 let out = TokioCommand::new("git")
493 .arg("-C")
494 .arg(&dir)
495 .arg("commit")
496 .arg("-m")
497 .arg(&msg)
498 .env("GIT_PAGER", "cat")
499 .env("GIT_CONFIG_NOSYSTEM", "1")
500 .env("GIT_CONFIG_GLOBAL", "/dev/null")
501 .stdin(Stdio::null())
502 .output()
503 .await
504 .unwrap();
505 if !out.status.success() {
506 return (
507 StatusCode::INTERNAL_SERVER_ERROR,
508 axum::Json(serde_json::json!({"error": format!("commit failed: {}", String::from_utf8_lossy(&out.stderr))})),
509 );
510 }
511 let sha = git(&dir, &["rev-parse", "HEAD"]).await;
512 (StatusCode::OK, axum::Json(serde_json::json!({"sha": sha.trim()})))
513 }
514
515 async fn mock_bundle(
516 State(st): State<MockRunner>,
517 AxPath(slot): AxPath<u32>,
518 ) -> impl IntoResponse {
519 let (dir, branch, base) = {
520 let slots = st.slots.lock().unwrap();
521 let s = slots.get(&slot).unwrap();
522 (s.dir.clone(), s.branch.clone(), s.base_sha.clone())
523 };
524 let out = TokioCommand::new("git")
525 .arg("-C")
526 .arg(&dir)
527 .arg("bundle")
528 .arg("create")
529 .arg("-")
530 .arg(format!("{base}..{branch}"))
531 .env("GIT_PAGER", "cat")
532 .stdin(Stdio::null())
533 .output()
534 .await
535 .unwrap();
536 assert!(out.status.success());
537 (
538 StatusCode::OK,
539 [(header::CONTENT_TYPE, "application/octet-stream")],
540 out.stdout,
541 )
542 }
543
544 async fn serve_mock_runner(clone_source: PathBuf, preempt: bool, scratch: PathBuf) -> (String, MockRunner) {
545 std::fs::create_dir_all(&scratch).unwrap();
546 let st = MockRunner {
547 slots: Arc::new(Mutex::new(Default::default())),
548 clone_source,
549 prepares: Arc::new(Mutex::new(Vec::new())),
550 build_seen: Arc::new(Mutex::new(Vec::new())),
551 build_should_preempt: preempt,
552 canned_exec: Arc::new(Mutex::new(Vec::new())),
553 scratch,
554 };
555 let app: axum::Router = axum::Router::new()
556 .route("/v1/slots/:slot/prepare", post(mock_prepare))
557 .route("/v1/slots/:slot/read", post(mock_read))
558 .route("/v1/slots/:slot/write", post(mock_write))
559 .route("/v1/slots/:slot/edit", post(mock_edit))
560 .route("/v1/slots/:slot/exec", post(mock_exec))
561 .route("/v1/slots/:slot/list", post(mock_list))
562 .route("/v1/slots/:slot/diff", post(mock_diff))
563 .route("/v1/slots/:slot/commit", post(mock_commit))
564 .route("/v1/slots/:slot/bundle", get(mock_bundle))
565 .route(
566 "/v1/slots/:slot/cancel",
567 post(|_: AxPath<u32>| async {
568 axum::Json(serde_json::json!({"killed": false}))
569 }),
570 )
571 .route(
572 "/v1/builds/kill",
573 post(|| async { axum::Json(serde_json::json!({"killed": true})) }),
574 )
575 .with_state(st.clone());
576 let lis = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
577 let addr = lis.local_addr().unwrap();
578 tokio::spawn(async move { axum::serve(lis, app).await.unwrap() });
579 (format!("http://{addr}"), st)
580 }
581
582 // ---------- mock GitHub (recorded fixtures + recorded POSTs) ----------
583
584 #[derive(Debug, Clone)]
585 struct RecordedGhRequest {
586 method: String,
587 path: String,
588 }
589
590 #[derive(Clone, Default)]
591 struct MockGitHub {
592 recorded: Arc<Mutex<Vec<RecordedGhRequest>>>,
593 responses: Arc<Mutex<HashMap<String, GhFixture>>>,
594 }
595
596 /// A recorded fixture served at one mock-GitHub path: HTTP status + body.
597 type GhFixture = (u16, Vec<u8>);
598
599 impl MockGitHub {
600 /// Serve `body` at `path` with HTTP 200.
601 fn respond(&self, path: &str, body: impl Into<Vec<u8>>) {
602 self.responses
603 .lock()
604 .unwrap()
605 .insert(path.to_string(), (200, body.into()));
606 }
607
608 fn requests(&self) -> Vec<RecordedGhRequest> {
609 self.recorded.lock().unwrap().clone()
610 }
611 }
612
613 async fn mock_github_handler(
614 State(st): State<MockGitHub>,
615 req: axum::http::Request<axum::body::Body>,
616 ) -> impl IntoResponse {
617 let (parts, _body) = req.into_parts();
618 st.recorded.lock().unwrap().push(RecordedGhRequest {
619 method: parts.method.to_string(),
620 path: parts.uri.path().to_string(),
621 });
622 // Write endpoints take precedence over recorded GET fixtures sharing
623 // the same path (e.g. the comments list).
624 let path = parts.uri.path().to_string();
625 if parts.method == axum::http::Method::POST && path.ends_with("/comments") {
626 return (
627 StatusCode::CREATED,
628 [(header::CONTENT_TYPE, "application/json")],
629 br#"{"html_url":"https://github.com/vayun-mathur/Modern-Apps/issues/903#issuecomment-9"}"#.to_vec(),
630 )
631 .into_response();
632 }
633 if parts.method == axum::http::Method::POST && path.ends_with("/labels") {
634 return (
635 StatusCode::OK,
636 [(header::CONTENT_TYPE, "application/json")],
637 br#"[{"name":"solved for next release"}]"#.to_vec(),
638 )
639 .into_response();
640 }
641 let found = st
642 .responses
643 .lock()
644 .unwrap()
645 .get(parts.uri.path())
646 .cloned();
647 match found {
648 Some((status, body)) => (
649 StatusCode::from_u16(status).unwrap_or(StatusCode::OK),
650 [(header::CONTENT_TYPE, "application/json")],
651 body,
652 )
653 .into_response(),
654 None => (StatusCode::NOT_FOUND, "no mock for path").into_response(),
655 }
656 }
657
658 async fn serve_mock_github() -> (String, MockGitHub) {
659 let st = MockGitHub::default();
660 // Recorded fixtures for issue #903 (weather/Celsius) + search.
661 st.respond(
662 "/repos/vayun-mathur/Modern-Apps/issues/903",
663 include_str!("testdata/github/issue_903.json"),
664 );
665 st.respond(
666 "/repos/vayun-mathur/Modern-Apps/issues/903/comments",
667 include_str!("testdata/github/comments_903.json"),
668 );
669 st.respond("/search/issues", include_str!("testdata/github/search_weather.json"));
670 st.respond(
671 "/repos/vayun-mathur/Modern-Apps/issues",
672 include_str!("testdata/github/list_weather.json"),
673 );
674 let app = axum::Router::new()
675 .fallback(mock_github_handler)
676 .with_state(st.clone());
677 let lis = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
678 let addr = lis.local_addr().unwrap();
679 tokio::spawn(async move { axum::serve(lis, app).await.unwrap() });
680 (format!("http://{addr}"), st)
681 }
682
683 // ---------- harness: real agentd server pointed at the mocks ----------
684
685 struct Harness {
686 addr: SocketAddr,
687 client: reqwest::Client,
688 origin: String,
689 _tmp: tempfile::TempDir,
690 _remote: PathBuf,
691 runner_seen: MockRunner,
692 or_seen: MockOr,
693 github_seen: MockGitHub,
694 cookie: String,
695 store: Store,
696 }
697
698 async fn spawn_harness(script: Vec<serde_json::Value>) -> Harness {
699 spawn_harness_opts(script, false).await
700 }
701
702 async fn spawn_harness_opts(script: Vec<serde_json::Value>, preempt: bool) -> Harness {
703 spawn_harness_full(script, preempt, false).await
704 }
705
706 /// `skip_wait`: when true, the release-signal wait is skipped and the
707 /// build is preempted immediately (fast deterministic test).
708 async fn spawn_harness_full(
709 script: Vec<serde_json::Value>,
710 preempt: bool,
711 skip_wait: bool,
712 ) -> Harness {
713 let tmp = tempfile::tempdir().unwrap();
714 let remote = init_remote(tmp.path()).await;
715 // agentd's own mirror: a real bare clone of the temp remote. The
716 // mock runner clones/fetches from THIS mirror (not the seed remote),
717 // so WIP refs agentd imports at park time are fetchable at resume.
718 let mirror = tmp.path().join("mirror.git");
719 git_no_cwd(
720 &["clone", "--bare", remote.to_str().unwrap(), mirror.to_str().unwrap()],
721 tmp.path(),
722 )
723 .await;
724 let (or_url, or_seen) = serve_mock_or(script).await;
725 let (runner_url, runner_seen) = serve_mock_runner(mirror.clone(), preempt, tmp.path().join("slots")).await;
726 let (github_url, github_seen) = serve_mock_github().await;
727
728 let state_dir = tmp.path().join("state");
729 std::fs::create_dir_all(&state_dir).unwrap();
730 let store = Store::open(&state_dir).unwrap();
731
732 // Password hash for "s3cret".
733 let hash = {
734 use argon2::{Argon2, PasswordHasher, password_hash::SaltString};
735 let salt = SaltString::from_b64("AAAAAAAAAAAAAAAAAAAAAA").unwrap();
736 Argon2::default().hash_password(b"s3cret", &salt).unwrap().to_string()
737 };
738 let origin = "https://agents.example.test".to_string();
739 let cfg = crate::config::Config {
740 openrouter_api_key: "test-key".into(),
741 openrouter_base_url: or_url,
742 password_hash: hash,
743 git_push_token: "PUSH-TOKEN-SHOULD-NEVER-LEAK".into(),
744 repo_url: remote.to_str().unwrap().to_string(),
745 public_origin: origin.clone(),
746 default_model: "test/model".into(),
747 runner_url,
748 state_dir: state_dir.clone(),
749 mirror_dir: mirror.clone(),
750 release_signal: tmp.path().join("signal-release"),
751 listen: "127.0.0.1:0".into(),
752 slots: 2,
753 github_repo: "vayun-mathur/Modern-Apps".into(),
754 github_api_base: github_url.clone(),
755 github_token: Some("test-github-token".into()),
756 test: crate::config::TestTuning {
757 poll_ms: Some(20),
758 build_wait_secs: Some(2),
759 context_chars: None,
760 },
761 test_skip_release_wait: skip_wait,
762 triage_enabled: false,
763 triage_interval_secs: 120,
764 };
765 let state = AppState {
766 config: Arc::new(cfg.clone()),
767 store: store.clone(),
768 auth: crate::auth::Auth::new(store.clone(), cfg.password_hash.clone()),
769 runner: crate::runner::Runner::new(cfg.runner_url.clone()),
770 openrouter: crate::openrouter::OpenRouter::new(
771 cfg.openrouter_base_url.clone(),
772 cfg.openrouter_api_key.clone(),
773 ),
774 events_tx: {
775 let (tx, _) = tokio::sync::broadcast::channel(64);
776 tx
777 },
778 };
779 // Scheduler workers (2 slots).
780 let _ = crate::scheduler::spawn_workers(state.driver(), 2);
781 let app = crate::ui::router(state);
782 let lis = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
783 let addr = lis.local_addr().unwrap();
784 tokio::spawn(async move { axum::serve(lis, app).await.unwrap() });
785
786 let client = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).build().unwrap();
787 // Log in.
788 let resp = client
789 .post(format!("http://{addr}/login"))
790 .form(&[("password", "s3cret")])
791 .send()
792 .await
793 .unwrap();
794 assert_eq!(resp.status(), StatusCode::FOUND);
795 let cookie = resp
796 .headers()
797 .get(header::SET_COOKIE)
798 .unwrap()
799 .to_str()
800 .unwrap()
801 .split(';')
802 .next()
803 .unwrap()
804 .to_string();
805 assert!(cookie.starts_with("agentd_session="));
806 Harness {
807 addr,
808 client,
809 origin,
810 _tmp: tmp,
811 _remote: remote,
812 runner_seen,
813 or_seen,
814 github_seen,
815 cookie,
816 store,
817 }
818 }
819
820 fn url(h: &Harness, path: &str) -> String {
821 format!("http://{}{}", h.addr, path)
822 }
823
824 async fn create_task(h: &Harness, title: &str, prompt: &str) -> i64 {
825 create_task_opts(h, title, prompt, false).await
826 }
827
828 /// Create a task, optionally with the "Plan first" checkbox checked
829 /// (`require_plan=1` in the form body).
830 async fn create_task_opts(h: &Harness, title: &str, prompt: &str, require_plan: bool) -> i64 {
831 let mut form = vec![
832 ("title", title),
833 ("module_scope", "notes"),
834 ("model", "test/model"),
835 ("prompt", prompt),
836 ("budget_steps", "60"),
837 ("budget_usd", "2.0"),
838 ];
839 if require_plan {
840 form.push(("require_plan", "1"));
841 }
842 let resp = h
843 .client
844 .post(url(h, "/tasks"))
845 .header(header::COOKIE, &h.cookie)
846 .header(header::ORIGIN, &h.origin)
847 .form(&form)
848 .send()
849 .await
850 .unwrap();
851 assert_eq!(resp.status(), StatusCode::FOUND, "task created");
852 let loc = resp.headers().get(header::LOCATION).unwrap().to_str().unwrap().to_string();
853 loc.rsplit('/').next().unwrap().parse().unwrap()
854 }
855
856 /// Create a task from the start-from-issue form: blank title/prompt plus
857 /// an issue number (prefilled from the mock GitHub). Returns the raw
858 /// response so tests can assert non-FOUND statuses too.
859 async fn create_task_from_issue_raw(
860 h: &Harness,
861 title: &str,
862 prompt: &str,
863 module_scope: &str,
864 issue_number: &str,
865 ) -> reqwest::Response {
866 h.client
867 .post(url(h, "/tasks"))
868 .header(header::COOKIE, &h.cookie)
869 .header(header::ORIGIN, &h.origin)
870 .form(&[
871 ("title", title),
872 ("module_scope", module_scope),
873 ("model", "test/model"),
874 ("prompt", prompt),
875 ("budget_steps", "60"),
876 ("budget_usd", "2.0"),
877 ("issue_number", issue_number),
878 ])
879 .send()
880 .await
881 .unwrap()
882 }
883
884 async fn create_task_from_issue(h: &Harness, title: &str, prompt: &str, issue: u64) -> i64 {
885 let resp = create_task_from_issue_raw(h, title, prompt, "notes", &issue.to_string()).await;
886 assert_eq!(resp.status(), StatusCode::FOUND, "task created from issue");
887 let loc = resp.headers().get(header::LOCATION).unwrap().to_str().unwrap().to_string();
888 loc.rsplit('/').next().unwrap().parse().unwrap()
889 }
890
891 async fn post_message(h: &Harness, id: i64, text: &str) -> StatusCode {
892 h.client
893 .post(url(h, &format!("/tasks/{id}/messages")))
894 .header(header::COOKIE, &h.cookie)
895 .header(header::ORIGIN, &h.origin)
896 .form(&[("text", text)])
897 .send()
898 .await
899 .unwrap()
900 .status()
901 }
902
903 /// POST to an empty-body action route (plan approve, review approve,
904 /// stop, discard). Axum `Form` extractors on sibling routes need a body;
905 /// these routes take none, so send none.
906 async fn post_action(h: &Harness, id: i64, action: &str) -> StatusCode {
907 h.client
908 .post(url(h, &format!("/tasks/{id}/{action}")))
909 .header(header::COOKIE, &h.cookie)
910 .header(header::ORIGIN, &h.origin)
911 .send()
912 .await
913 .unwrap()
914 .status()
915 }
916
917 async fn post_plan_changes(h: &Harness, id: i64, text: &str) -> StatusCode {
918 h.client
919 .post(url(h, &format!("/tasks/{id}/plan/changes")))
920 .header(header::COOKIE, &h.cookie)
921 .header(header::ORIGIN, &h.origin)
922 .form(&[("text", text)])
923 .send()
924 .await
925 .unwrap()
926 .status()
927 }
928
929 /// Does `refs/heads/<branch>` exist on the temp remote?
930 async fn remote_has_branch(h: &Harness, branch: &str) -> bool {
931 TokioCommand::new("git")
932 .arg("--git-dir")
933 .arg(h._remote.clone())
934 .arg("rev-parse")
935 .arg("--verify")
936 .arg(format!("refs/heads/{branch}"))
937 .output()
938 .await
939 .map(|o| o.status.success())
940 .unwrap_or(false)
941 }
942
943 /// Show a file at a remote branch (`None` when missing).
944 async fn remote_show(h: &Harness, branch: &str, path: &str) -> Option<String> {
945 let out = TokioCommand::new("git")
946 .arg("--git-dir")
947 .arg(h._remote.clone())
948 .arg("show")
949 .arg(format!("refs/heads/{branch}:{path}"))
950 .output()
951 .await
952 .unwrap();
953 if out.status.success() {
954 Some(String::from_utf8(out.stdout).unwrap())
955 } else {
956 None
957 }
958 }
959
960 /// One-line log subjects on the remote branch after `main`.
961 async fn remote_log(h: &Harness, branch: &str) -> String {
962 let out = TokioCommand::new("git")
963 .arg("--git-dir")
964 .arg(h._remote.clone())
965 .arg("log")
966 .arg("--format=%s")
967 .arg(format!("main..refs/heads/{branch}"))
968 .output()
969 .await
970 .unwrap();
971 assert!(out.status.success(), "branch {branch} on remote");
972 String::from_utf8(out.stdout).unwrap()
973 }
974
975 async fn task_html(h: &Harness, id: i64) -> String {
976 h.client
977 .get(url(h, &format!("/tasks/{id}")))
978 .header(header::COOKIE, &h.cookie)
979 .send()
980 .await
981 .unwrap()
982 .text()
983 .await
984 .unwrap()
985 }
986
987 /// Ask-answer-resume: `ask_user` parks as needs_input, the POSTed answer
988 /// becomes the tool result in the next model request (right position),
989 /// edits survive, and `finish` parks as review (no push) → approve pushes
990 /// → succeeded.
991 #[tokio::test]
992 async fn ask_user_answer_resume_finish() {
993 let h = spawn_harness(vec![
994 tool_resp("c1", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello world\n"}), "editing"),
995 tool_resp(
996 "c2",
997 "ask_user",
998 serde_json::json!({"question": "Which greeting?", "options": ["hello world", "hi"]}),
999 "asking",
1000 ),
1001 // After resume: the tool result for c2 (the answer) must be in
1002 // this request, then the model finishes.
1003 tool_resp(
1004 "c3",
1005 "finish",
1006 serde_json::json!({
1007 "summary": "Changed the greeting per answer.",
1008 "commit_message": "notes: change greeting\n\nSwitched the greeting text per the task."
1009 }),
1010 "finishing",
1011 ),
1012 ])
1013 .await;
1014 let id = create_task(&h, "Ask flow", "Edit the file, ask which greeting, then finish.").await;
1015
1016 // Park as needs_input(question); the page shows the question + options.
1017 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1018 let html = task_html(&h, id).await;
1019 assert!(html.contains("pill needs_input\">needs_input<"), "parked; tail: {}", &html[html.len().saturating_sub(800)..]);
1020 assert!(html.contains("Which greeting?"), "question shown");
1021 assert!(html.contains("hello world"), "option shown");
1022
1023 // Answer via the option-button shape (form posts option text).
1024 assert_eq!(post_message(&h, id, "hello world").await, StatusCode::FOUND);
1025 // `finish` parks as review (no push yet).
1026 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
1027 let branch = format!("agent/{id}-ask-flow");
1028 assert!(!remote_has_branch(&h, &branch).await, "no push before approve");
1029 let html = task_html(&h, id).await;
1030 assert!(html.contains("pill review\">review<"), "in review");
1031 // Approve → push → succeeded.
1032 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
1033 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
1034 let html = task_html(&h, id).await;
1035 assert!(html.contains("pill succeeded\">succeeded<"), "approved to success");
1036
1037 // The request AFTER the park carries the tool result with the answer
1038 // in the right position: last message, role=tool, id=c2.
1039 let seen = h.or_seen.seen.lock().unwrap().clone();
1040 assert!(seen.len() >= 3, "model called again after resume: {}", seen.len());
1041 let resumed_req = &seen[2];
1042 let msgs = resumed_req.get("messages").and_then(|v| v.as_array()).unwrap();
1043 let last = msgs.last().unwrap();
1044 assert_eq!(last.get("role").and_then(|v| v.as_str()), Some("tool"));
1045 assert_eq!(last.get("tool_call_id").and_then(|v| v.as_str()), Some("c2"));
1046 assert!(
1047 last.get("content").and_then(|v| v.as_str()).unwrap_or("").contains("hello world"),
1048 "answer in tool result: {last}"
1049 );
1050
1051 // The branch was pushed with the edit intact.
1052 let branch = format!("agent/{id}-ask-flow");
1053 let out = TokioCommand::new("git")
1054 .arg("--git-dir")
1055 .arg(h._remote.clone())
1056 .arg("show")
1057 .arg(format!("refs/heads/{branch}:notes/file.txt"))
1058 .output()
1059 .await
1060 .unwrap();
1061 assert!(out.status.success(), "branch pushed");
1062 assert!(String::from_utf8(out.stdout).unwrap().contains("hello world"));
1063 }
1064
1065 /// Steering while running: a message posted mid-run appears as a user
1066 /// message in a subsequent model request.
1067 #[tokio::test]
1068 async fn steering_while_running() {
1069 let h = spawn_harness(vec![
1070 tool_resp("c1", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading"),
1071 tool_resp("c2", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello steered\n"}), "editing"),
1072 tool_resp(
1073 "c3",
1074 "finish",
1075 serde_json::json!({
1076 "summary": "Steered edit.",
1077 "commit_message": "notes: steered edit\n\nBody here."
1078 }),
1079 "finishing",
1080 ),
1081 ])
1082 .await;
1083 let id = create_task(&h, "Steer me", "Read, edit, finish.").await;
1084 // Post immediately: the driver's first inbox drain happens after its
1085 // first turn's tool results (claim poll + git clone + reads come
1086 // first), so this steering is guaranteed to be picked up for a later
1087 // request — deterministically, with no sleep.
1088 assert_eq!(post_message(&h, id, "steer: prefer exclamation").await, StatusCode::FOUND);
1089 // `finish` parks as review; approve to push.
1090 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
1091 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
1092 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
1093 let html = task_html(&h, id).await;
1094 assert!(html.contains("pill succeeded\">succeeded<"));
1095 let seen = h.or_seen.seen.lock().unwrap().clone();
1096 let mut found = false;
1097 for req in &seen {
1098 let msgs = req.get("messages").and_then(|v| v.as_array()).unwrap();
1099 for m in msgs {
1100 if m.get("role").and_then(|v| v.as_str()) == Some("user")
1101 && m.get("content").and_then(|v| v.as_str()).unwrap_or("").contains("steer: prefer exclamation")
1102 {
1103 found = true;
1104 }
1105 }
1106 }
1107 assert!(found, "steering message reached the model");
1108 }
1109
1110 /// Stop → needs_input(stopped) → message → resumes with edits kept.
1111 ///
1112 /// Deterministic by stopping immediately after create: the flag persists
1113 /// in the DB, so whenever the driver first observes it (queued or
1114 /// mid-run) it parks as stopped; the resume then replays the script to
1115 /// success. (Stopping after N turns is inherently racy — mock
1116 /// round-trips take milliseconds.)
1117 #[tokio::test]
1118 async fn stop_then_resume_keeps_edits() {
1119 let h = spawn_harness(vec![
1120 tool_resp("c1", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello stopped\n"}), "editing"),
1121 tool_resp("c2", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading"),
1122 tool_resp("c3", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading"),
1123 tool_resp(
1124 "c4",
1125 "finish",
1126 serde_json::json!({
1127 "summary": "Done after stop.",
1128 "commit_message": "notes: resume after stop\n\nBody here."
1129 }),
1130 "finishing",
1131 ),
1132 ])
1133 .await;
1134 let id = create_task(&h, "Stop flow", "Edit, then keep reading, then finish.").await;
1135 // Stop immediately (flag persists; the driver parks as stopped
1136 // whenever it first observes it — queued or mid-run).
1137 let resp = h
1138 .client
1139 .post(url(&h, &format!("/tasks/{id}/stop")))
1140 .header(header::COOKIE, &h.cookie)
1141 .header(header::ORIGIN, &h.origin)
1142 .send()
1143 .await
1144 .unwrap();
1145 assert_eq!(resp.status(), StatusCode::FOUND);
1146 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1147 let html = task_html(&h, id).await;
1148 assert!(html.contains("stopped"), "stopped park visible; tail: {}", &html[html.len().saturating_sub(1500)..]);
1149 // Resume with a message; the edit must survive the park/resume.
1150 assert_eq!(post_message(&h, id, "continue please").await, StatusCode::FOUND);
1151 // Script ends in `finish` → review; approve to push.
1152 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
1153 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
1154 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
1155 let branch = format!("agent/{id}-stop-flow");
1156 let out = TokioCommand::new("git")
1157 .arg("--git-dir")
1158 .arg(h._remote.clone())
1159 .arg("show")
1160 .arg(format!("refs/heads/{branch}:notes/file.txt"))
1161 .output()
1162 .await
1163 .unwrap();
1164 assert!(out.status.success(), "branch pushed");
1165 assert!(String::from_utf8(out.stdout).unwrap().contains("hello stopped"), "edit survived stop/resume");
1166 }
1167
1168 /// Multi-call turn with ask_user → error result, no park.
1169 #[tokio::test]
1170 async fn mixed_ask_user_turn_rejected_without_park() {
1171 let h = spawn_harness(vec![
1172 serde_json::json!({
1173 "choices": [{"message": {
1174 "role": "assistant", "content": "two calls",
1175 "tool_calls": [
1176 {"id": "m1", "type": "function", "function": {"name": "read_file", "arguments": "{\"path\": \"notes/file.txt\"}"}},
1177 {"id": "m2", "type": "function", "function": {"name": "ask_user", "arguments": "{\"question\": \"Q?\"}"}}
1178 ]
1179 }}],
1180 "usage": {"prompt_tokens": 10, "completion_tokens": 5}
1181 }),
1182 // After the rejection the model text-replies → parks as chat.
1183 serde_json::json!({
1184 "choices": [{"message": {"role": "assistant", "content": "understood, continuing alone"}}],
1185 "usage": {"prompt_tokens": 10, "completion_tokens": 5}
1186 }),
1187 ])
1188 .await;
1189 let id = create_task(&h, "Mixed turn", "Do things.").await;
1190 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1191 let html = task_html(&h, id).await;
1192 // Parked as chat (text-only), NOT as a question.
1193 assert!(html.contains("pill needs_input\">needs_input<"));
1194 assert!(!html.contains("Waiting for you (question)"), "no question park; tail: {}", &html[html.len().saturating_sub(1500)..]);
1195 assert!(html.contains("must be the only call in its turn"), "error surfaced");
1196 }
1197
1198 /// Text-only turn parks as chat (nudge-then-fail retired).
1199 #[tokio::test]
1200 async fn text_only_parks_as_chat() {
1201 let h = spawn_harness(vec![serde_json::json!({
1202 "choices": [{"message": {"role": "assistant", "content": "I need guidance"}}],
1203 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1204 })])
1205 .await;
1206 let id = create_task(&h, "Chat park", "Say hi.").await;
1207 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1208 let html = task_html(&h, id).await;
1209 assert!(html.contains("pill needs_input\">needs_input<"));
1210 assert!(html.contains("Waiting for you (chat)"), "chat park; tail: {}", &html[html.len().saturating_sub(1500)..]);
1211 }
1212
1213 /// Tiny budget → budget park; answering extends +20 steps / +$1.00.
1214 #[tokio::test]
1215 async fn budget_park_and_extension() {
1216 let h = spawn_harness(vec![
1217 tool_resp("c1", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading"),
1218 tool_resp("c2", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading"),
1219 tool_resp("c3", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading"),
1220 tool_resp("c4", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading"),
1221 serde_json::json!({
1222 "choices": [{"message": {"role": "assistant", "content": "still going"}}],
1223 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1224 }),
1225 ])
1226 .await;
1227 // Create with budget_steps=2 via the raw form.
1228 let resp = h
1229 .client
1230 .post(url(&h, "/tasks"))
1231 .header(header::COOKIE, &h.cookie)
1232 .header(header::ORIGIN, &h.origin)
1233 .form(&[
1234 ("title", "Budget flow"),
1235 ("module_scope", "notes"),
1236 ("model", "test/model"),
1237 ("prompt", "Read a lot."),
1238 ("budget_steps", "2"),
1239 ("budget_usd", "2.0"),
1240 ])
1241 .send()
1242 .await
1243 .unwrap();
1244 assert_eq!(resp.status(), StatusCode::FOUND);
1245 let loc = resp.headers().get(header::LOCATION).unwrap().to_str().unwrap().to_string();
1246 let id: i64 = loc.rsplit('/').next().unwrap().parse().unwrap();
1247 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1248 let html = task_html(&h, id).await;
1249 assert!(html.contains("Waiting for you (budget)"), "budget park; tail: {}", &html[html.len().saturating_sub(1500)..]);
1250 // Answer → resume grants +20 steps / +$1.00 (2 → 22 steps).
1251 assert_eq!(post_message(&h, id, "keep going").await, StatusCode::FOUND);
1252 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1253 let html = task_html(&h, id).await;
1254 assert!(html.contains("22"), "budget extended to 22 steps; tail: {}", &html[html.len().saturating_sub(1500)..]);
1255 }
1256
1257 /// Discard is terminal and removes the WIP ref.
1258 #[tokio::test]
1259 async fn discard_task_terminal() {
1260 let h = spawn_harness(vec![serde_json::json!({
1261 "choices": [{"message": {"role": "assistant", "content": "waiting"}}],
1262 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1263 })])
1264 .await;
1265 let id = create_task(&h, "Discard me", "Say hi.").await;
1266 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1267 let resp = h
1268 .client
1269 .post(url(&h, &format!("/tasks/{id}/discard")))
1270 .header(header::COOKIE, &h.cookie)
1271 .header(header::ORIGIN, &h.origin)
1272 .send()
1273 .await
1274 .unwrap();
1275 assert_eq!(resp.status(), StatusCode::FOUND);
1276 let html = task_html(&h, id).await;
1277 assert!(html.contains("pill discarded\">discarded<"), "discarded; tail: {}", &html[html.len().saturating_sub(800)..]);
1278 }
1279
1280 async fn wait_for(h: &Harness, id: i64, statuses: &[&str], timeout: std::time::Duration) {
1281 let start = std::time::Instant::now();
1282 loop {
1283 // Poll the task page for a status pill. NOTE: the page's CSS
1284 // block contains `.pill.failed` etc. selectors, so match the full
1285 // rendered span `pill {s}">{s}</span>` — never the bare class.
1286 let html = h
1287 .client
1288 .get(url(h, &format!("/tasks/{id}")))
1289 .header(header::COOKIE, &h.cookie)
1290 .send()
1291 .await
1292 .unwrap()
1293 .text()
1294 .await
1295 .unwrap();
1296 for s in statuses {
1297 let span = format!("pill {s}\">{s}</span>");
1298 if html.contains(&span) {
1299 return;
1300 }
1301 }
1302 if start.elapsed() > timeout {
1303 panic!("task {id} did not reach {statuses:?} in {timeout:?}; html tail: {}", &html[html.len().saturating_sub(500)..]);
1304 }
1305 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1306 }
1307 }
1308
1309 async fn wait_status(h: &Harness, id: i64, timeout: std::time::Duration) {
1310 wait_for(h, id, &["succeeded", "failed", "discarded", "cancelled"], timeout).await;
1311 }
1312
1313 async fn wait_parked(h: &Harness, id: i64, timeout: std::time::Duration) {
1314 wait_for(h, id, &["needs_input", "review"], timeout).await;
1315 }
1316
1317 async fn wait_review(h: &Harness, id: i64, timeout: std::time::Duration) {
1318 wait_for(h, id, &["review"], timeout).await;
1319 }
1320
1321 #[tokio::test]
1322 async fn full_success_flow_pushes_branch() {
1323 let h = spawn_harness(success_script()).await;
1324 let resp = h
1325 .client
1326 .post(url(&h, "/tasks"))
1327 .header(header::COOKIE, &h.cookie)
1328 .header(header::ORIGIN, &h.origin)
1329 .form(&[
1330 ("title", "Change greeting"),
1331 ("module_scope", "notes"),
1332 ("model", "test/model"),
1333 ("prompt", "Change the greeting text."),
1334 ("budget_steps", "60"),
1335 ("budget_usd", "2.0"),
1336 ])
1337 .send()
1338 .await
1339 .unwrap();
1340 assert_eq!(resp.status(), StatusCode::FOUND, "task created");
1341 let loc = resp.headers().get(header::LOCATION).unwrap().to_str().unwrap().to_string();
1342 let id: i64 = loc.rsplit('/').next().unwrap().parse().unwrap();
1343
1344 // `finish` parks as review WITHOUT pushing; the branch must not exist
1345 // on the remote yet.
1346 let branch = format!("agent/{id}-change-greeting");
1347 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
1348 assert!(!remote_has_branch(&h, &branch).await, "no push before approve");
1349 // Review card shows summary, commit message, and the diff.
1350 let html = task_html(&h, id).await;
1351 assert!(html.contains("pill review\">review<"), "in review");
1352 assert!(html.contains("Changed the greeting."), "summary shown");
1353 assert!(html.contains("notes: change greeting"), "commit message shown");
1354 assert!(html.contains("hello world"), "diff shown");
1355 assert!(html.contains("Approve &amp; push") || html.contains("Approve & push"), "approve button");
1356 // Approve → push → succeeded with the agent's message as the single commit.
1357 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
1358 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
1359 // Task page shows success.
1360 let html = h
1361 .client
1362 .get(url(&h, &format!("/tasks/{id}")))
1363 .header(header::COOKIE, &h.cookie)
1364 .send()
1365 .await
1366 .unwrap()
1367 .text()
1368 .await
1369 .unwrap();
1370 assert!(html.contains("pill succeeded\">succeeded<"), "task succeeded; html tail: {}", &html[html.len().saturating_sub(800)..]);
1371 assert!(html.contains("agent/"), "branch shown");
1372 // The branch exists in the temp remote with the expected commit.
1373 let log = remote_log(&h, &branch).await;
1374 assert!(log.contains("notes: change greeting"), "commit msg: {log}");
1375 assert_eq!(log.lines().count(), 1, "single squashed commit: {log}");
1376 // Token never appears in events (SSE backlog) or any page.
1377 // NOTE: `/tasks/{id}/events` is an infinite SSE stream (15s
1378 // keep-alives), so `.text()` on it would hang forever. Read it with
1379 // `?after=` bounded ... instead: assert on the DB-backed backlog via
1380 // the HTML page's rendered events (already covered) plus a direct
1381 // events query below with a timeout-guarded raw socket read.
1382 for path in [format!("/tasks/{id}"), "/".to_string()] {
1383 let body = h
1384 .client
1385 .get(url(&h, &path))
1386 .header(header::COOKIE, &h.cookie)
1387 .header(header::ACCEPT, "text/html")
1388 .send()
1389 .await
1390 .unwrap()
1391 .text()
1392 .await
1393 .unwrap();
1394 assert!(!body.contains("PUSH-TOKEN-SHOULD-NEVER-LEAK"), "token leaked in {path}");
1395 }
1396 {
1397 // Bounded SSE read: the backlog frames arrive immediately; the
1398 // stream then idles on keep-alives, so cap the read at 10s.
1399 use tokio::io::AsyncReadExt;
1400 let stream = tokio::net::TcpStream::connect(h.addr).await.unwrap();
1401 let (mut reader, mut writer) = stream.into_split();
1402 let req = format!(
1403 "GET /tasks/{id}/events HTTP/1.1\r\nHost: {}\r\nCookie: {}\r\nAccept: text/event-stream\r\nConnection: close\r\n\r\n",
1404 h.addr, h.cookie
1405 );
1406 use tokio::io::AsyncWriteExt;
1407 writer.write_all(req.as_bytes()).await.unwrap();
1408 let mut buf = vec![0u8; 1_000_000];
1409 let mut total = 0usize;
1410 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1411 loop {
1412 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
1413 if remaining.is_zero() {
1414 break;
1415 }
1416 match tokio::time::timeout(
1417 remaining,
1418 reader.read(&mut buf[total..]),
1419 )
1420 .await
1421 {
1422 Ok(Ok(0)) => break,
1423 Ok(Ok(n)) => {
1424 total += n;
1425 if total >= buf.len() {
1426 break;
1427 }
1428 }
1429 _ => break,
1430 }
1431 }
1432 let body = String::from_utf8_lossy(&buf[..total]);
1433 assert!(!body.contains("PUSH-TOKEN-SHOULD-NEVER-LEAK"), "token leaked in events stream");
1434 assert!(body.contains("data:"), "expected SSE data frames, got {body:?}");
1435 }
1436 // Runner saw the build command.
1437 let seen = h.runner_seen.build_seen.lock().unwrap();
1438 assert!(seen.iter().any(|c| c.contains(":notes:compileDevKotlin")), "build forwarded: {seen:?}");
1439 }
1440
1441 #[tokio::test]
1442 async fn unauthenticated_post_rejected() {
1443 let h = spawn_harness(vec![]).await;
1444 let resp = h
1445 .client
1446 .post(url(&h, "/tasks"))
1447 .header(header::ORIGIN, &h.origin)
1448 .form(&[
1449 ("title", "x"),
1450 ("module_scope", "notes"),
1451 ("model", "m"),
1452 ("prompt", "y"),
1453 ("budget_steps", "60"),
1454 ("budget_usd", "2.0"),
1455 ])
1456 .send()
1457 .await
1458 .unwrap();
1459 // Redirect to /login (not queued).
1460 assert_eq!(resp.status(), StatusCode::FOUND);
1461 assert_eq!(resp.headers().get(header::LOCATION).unwrap(), "/login");
1462 }
1463
1464 #[tokio::test]
1465 async fn wrong_origin_rejected() {
1466 let h = spawn_harness(vec![]).await;
1467 let resp = h
1468 .client
1469 .post(url(&h, "/tasks"))
1470 .header(header::COOKIE, &h.cookie)
1471 .header(header::ORIGIN, "https://evil.example.test")
1472 .form(&[
1473 ("title", "x"),
1474 ("module_scope", "notes"),
1475 ("model", "m"),
1476 ("prompt", "y"),
1477 ("budget_steps", "60"),
1478 ("budget_usd", "2.0"),
1479 ])
1480 .send()
1481 .await
1482 .unwrap();
1483 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1484 // Missing Origin also rejected.
1485 let resp = h
1486 .client
1487 .post(url(&h, "/tasks"))
1488 .header(header::COOKIE, &h.cookie)
1489 .form(&[
1490 ("title", "x"),
1491 ("module_scope", "notes"),
1492 ("model", "m"),
1493 ("prompt", "y"),
1494 ("budget_steps", "60"),
1495 ("budget_usd", "2.0"),
1496 ])
1497 .send()
1498 .await
1499 .unwrap();
1500 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1501 }
1502
1503 #[tokio::test]
1504 async fn release_signal_preempts_build() {
1505 // The harness holds the release-signal file present and skips the
1506 // 60-minute wait; agentd must surface "preempted by a production
1507 // release" to the model (and call the runner's builds/kill). The
1508 // trailing text-only turn now parks as needs_input(chat) instead of
1509 // failing (nudge-then-fail is retired).
1510 let h = spawn_harness_full(
1511 vec![
1512 tool_resp(
1513 "c1",
1514 "build",
1515 serde_json::json!({"command": "./gradlew :notes:lint"}),
1516 "try build",
1517 ),
1518 serde_json::json!({
1519 "choices": [{"message": {"role": "assistant", "content": "retrying"}}],
1520 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1521 }),
1522 ],
1523 false,
1524 true,
1525 )
1526 .await;
1527 // Hold the release signal for the whole task (harness points
1528 // AGENTD_RELEASE_SIGNAL at tmp/signal-release).
1529 std::fs::write(h._tmp.path().join("signal-release"), "1").unwrap();
1530
1531 let resp = h
1532 .client
1533 .post(url(&h, "/tasks"))
1534 .header(header::COOKIE, &h.cookie)
1535 .header(header::ORIGIN, &h.origin)
1536 .form(&[
1537 ("title", "Build during release"),
1538 ("module_scope", "notes"),
1539 ("model", "test/model"),
1540 ("prompt", "Run a build."),
1541 ("budget_steps", "60"),
1542 ("budget_usd", "2.0"),
1543 ])
1544 .send()
1545 .await
1546 .unwrap();
1547 assert_eq!(resp.status(), StatusCode::FOUND);
1548 let loc = resp.headers().get(header::LOCATION).unwrap().to_str().unwrap().to_string();
1549 let id: i64 = loc.rsplit('/').next().unwrap().parse().unwrap();
1550 let _ = wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1551 let html = h
1552 .client
1553 .get(url(&h, &format!("/tasks/{id}")))
1554 .header(header::COOKIE, &h.cookie)
1555 .send()
1556 .await
1557 .unwrap()
1558 .text()
1559 .await
1560 .unwrap();
1561 assert!(
1562 html.contains("preempted by a production release"),
1563 "preemption surfaced; tail: {}",
1564 &html[html.len().saturating_sub(2000)..]
1565 );
1566 assert!(
1567 html.contains("pill needs_input\">needs_input<"),
1568 "text-only turn parked as chat; tail: {}",
1569 &html[html.len().saturating_sub(2000)..]
1570 );
1571 }
1572
1573 /// Chat UI over HTTP: static assets carry JS/CSS content types, the four
1574 /// fragment routes 401 without auth, a parked (chat) task shows up under
1575 /// "Needs you" with a `(1)` title count, and the task page has no inline
1576 /// script/style plus a CSP without 'unsafe-inline'.
1577 #[tokio::test]
1578 async fn ui_fragments_dashboard_and_static() {
1579 let h = spawn_harness(vec![serde_json::json!({
1580 "choices": [{"message": {"role": "assistant", "content": "hello, need guidance"}}],
1581 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1582 })])
1583 .await;
1584 // Static assets: correct content types, real bodies.
1585 let resp = h.client.get(url(&h, "/static/app.js")).send().await.unwrap();
1586 assert_eq!(resp.status(), StatusCode::OK);
1587 let ct = resp.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap().to_string();
1588 assert!(ct.starts_with("application/javascript"), "js type: {ct}");
1589 let js = resp.text().await.unwrap();
1590 assert!(js.contains("EventSource"), "live-update script served");
1591 let resp = h.client.get(url(&h, "/static/app.css")).send().await.unwrap();
1592 assert_eq!(resp.status(), StatusCode::OK);
1593 let ct = resp.headers().get(header::CONTENT_TYPE).unwrap().to_str().unwrap().to_string();
1594 assert!(ct.starts_with("text/css"), "css type: {ct}");
1595 // Fragments require auth: no cookie → 401 (never a login redirect
1596 // the script would swap into the page).
1597 for path in [
1598 "/tasks/1/timeline",
1599 "/tasks/1/panel",
1600 "/tasks/1/cards",
1601 "/fragments/dashboard",
1602 ] {
1603 let r = h.client.get(url(&h, path)).send().await.unwrap();
1604 assert_eq!(r.status(), StatusCode::UNAUTHORIZED, "{path} needs auth");
1605 }
1606 // Park a task as chat (needs_input) → dashboard counts it.
1607 let id = create_task(&h, "Chat UI", "Say hi.").await;
1608 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1609 let dash = h
1610 .client
1611 .get(url(&h, "/"))
1612 .header(header::COOKIE, &h.cookie)
1613 .send()
1614 .await
1615 .unwrap()
1616 .text()
1617 .await
1618 .unwrap();
1619 assert!(dash.contains("<title>(1) agentd</title>"), "title count; head: {}", &dash[..dash.len().min(600)]);
1620 assert!(dash.contains("Needs you (1)"), "needs-you section");
1621 assert!(dash.contains("replied — waiting for you"), "chat reason");
1622 // Authed fragments render server markup.
1623 let body = h
1624 .client
1625 .get(url(&h, &format!("/tasks/{id}/timeline")))
1626 .header(header::COOKIE, &h.cookie)
1627 .send()
1628 .await
1629 .unwrap()
1630 .text()
1631 .await
1632 .unwrap();
1633 assert!(body.contains("bubble assistant"), "timeline fragment; body: {body}");
1634 let body = h
1635 .client
1636 .get(url(&h, &format!("/tasks/{id}/panel")))
1637 .header(header::COOKIE, &h.cookie)
1638 .send()
1639 .await
1640 .unwrap()
1641 .text()
1642 .await
1643 .unwrap();
1644 assert!(body.contains("Todos"), "panel fragment; body: {body}");
1645 let body = h
1646 .client
1647 .get(url(&h, &format!("/tasks/{id}/cards")))
1648 .header(header::COOKIE, &h.cookie)
1649 .send()
1650 .await
1651 .unwrap()
1652 .text()
1653 .await
1654 .unwrap();
1655 assert!(body.contains("Waiting for you (chat)"), "cards fragment; body: {body}");
1656 // Full task page: bundled script only, no inline script/style, and
1657 // the CSP no longer allows 'unsafe-inline'.
1658 let resp = h
1659 .client
1660 .get(url(&h, &format!("/tasks/{id}")))
1661 .header(header::COOKIE, &h.cookie)
1662 .send()
1663 .await
1664 .unwrap();
1665 let csp = resp.headers().get(header::CONTENT_SECURITY_POLICY).unwrap().to_str().unwrap().to_string();
1666 assert!(!csp.contains("unsafe-inline"), "no unsafe-inline: {csp}");
1667 assert!(csp.contains("script-src 'self'"), "script self: {csp}");
1668 let html = resp.text().await.unwrap();
1669 assert!(html.contains("<script src=\"/static/app.js\""), "bundled script tag");
1670 assert_eq!(html.matches("<script").count(), 1, "no inline script");
1671 assert!(!html.contains("<style"), "no style block");
1672 assert!(!html.contains("style="), "no inline style");
1673 }
1674
1675 /// Multi-select question: answering via the checkboxes form (repeated
1676 /// `options` values, no `text`) joins into one message that becomes the
1677 /// pending `ask_user` tool result.
1678 #[tokio::test]
1679 async fn ui_multiselect_question_posts_joined() {
1680 let h = spawn_harness(vec![
1681 tool_resp(
1682 "c1",
1683 "ask_user",
1684 serde_json::json!({"question": "Pick colors", "options": ["red", "blue"], "multi_select": true}),
1685 "asking",
1686 ),
1687 serde_json::json!({
1688 "choices": [{"message": {"role": "assistant", "content": "thanks"}}],
1689 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1690 }),
1691 ])
1692 .await;
1693 let id = create_task(&h, "Multi", "Ask me.").await;
1694 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1695 let html = task_html(&h, id).await;
1696 assert!(html.contains("name=\"options\""), "checkboxes form; tail: {}", &html[html.len().saturating_sub(1500)..]);
1697 // Answer with checkboxes only (no text field): repeated `options`.
1698 let resp = h
1699 .client
1700 .post(url(&h, &format!("/tasks/{id}/messages")))
1701 .header(header::COOKIE, &h.cookie)
1702 .header(header::ORIGIN, &h.origin)
1703 .form(&[("options", "red"), ("options", "blue")])
1704 .send()
1705 .await
1706 .unwrap();
1707 assert_eq!(resp.status(), StatusCode::FOUND);
1708 // Text-only turn parks as chat; the resumed request carries the
1709 // joined answer as the c1 tool result.
1710 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1711 let seen = h.or_seen.seen.lock().unwrap().clone();
1712 assert!(seen.len() >= 2, "model called again: {}", seen.len());
1713 let msgs = seen[1].get("messages").and_then(|v| v.as_array()).unwrap().clone();
1714 let last = msgs.last().unwrap();
1715 assert_eq!(last.get("role").and_then(|v| v.as_str()), Some("tool"));
1716 assert_eq!(last.get("tool_call_id").and_then(|v| v.as_str()), Some("c1"));
1717 assert!(
1718 last.get("content").and_then(|v| v.as_str()).unwrap_or("").contains("red, blue"),
1719 "joined answer in tool result: {last}"
1720 );
1721 }
1722
1723 #[tokio::test]
1724 async fn healthz_and_security_headers() {
1725 let h = spawn_harness(vec![]).await;
1726 let resp = h.client.get(url(&h, "/healthz")).send().await.unwrap();
1727 assert_eq!(resp.status(), StatusCode::OK);
1728 assert_eq!(resp.text().await.unwrap(), "ok");
1729 let resp = h
1730 .client
1731 .get(url(&h, "/login"))
1732 .send()
1733 .await
1734 .unwrap();
1735 let headers = resp.headers();
1736 assert!(headers.contains_key(header::CONTENT_SECURITY_POLICY));
1737 assert_eq!(headers.get("x-content-type-options").unwrap(), "nosniff");
1738 assert_eq!(headers.get("x-frame-options").unwrap(), "DENY");
1739 }
1740
1741 /// Structured `build{module, tasks}` failure: the parsed `file:line:
1742 /// error` diagnostic (not raw gradle output) reaches the model — checked
1743 /// on the next mock-OpenRouter request body.
1744 #[tokio::test]
1745 async fn structured_build_failure_returns_parsed_diagnostics() {
1746 let h = spawn_harness(vec![
1747 tool_resp(
1748 "c1",
1749 "build",
1750 serde_json::json!({"module": "notes", "tasks": ["compileDevKotlin"]}),
1751 "building",
1752 ),
1753 // Text-only turn parks as chat; the tool result is in request 2.
1754 serde_json::json!({
1755 "choices": [{"message": {"role": "assistant", "content": "build is broken"}}],
1756 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1757 }),
1758 ])
1759 .await;
1760 h.runner_seen.canned(
1761 ":notes:compileDevKotlin",
1762 1,
1763 "e: notes/src/main/java/notes/Main.kt:10:5 Type mismatch: inferred type is String but Int was expected\n> Task :notes:compileDevKotlin FAILED\n",
1764 "",
1765 );
1766 let id = create_task(&h, "Structured build", "Build notes.").await;
1767 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1768
1769 let seen = h.or_seen.seen.lock().unwrap().clone();
1770 assert!(seen.len() >= 2, "model called again: {}", seen.len());
1771 let body = serde_json::to_string(&seen[1]).unwrap();
1772 assert!(body.contains("notes/src/main/java/notes/Main.kt:10:5"), "parsed location: {body}");
1773 assert!(body.contains("Type mismatch"), "parsed message: {body}");
1774 assert!(!body.contains("> Task :notes:compileDevKotlin FAILED"), "no raw gradle noise: {body}");
1775 }
1776
1777 /// `run_tests{module}` failure: reads the seeded JUnit XML via list+read
1778 /// and surfaces the failing test name to the model.
1779 #[tokio::test]
1780 async fn structured_run_tests_failure_shows_failing_test() {
1781 let h = spawn_harness(vec![
1782 tool_resp("c1", "run_tests", serde_json::json!({"module": "notes"}), "testing"),
1783 serde_json::json!({
1784 "choices": [{"message": {"role": "assistant", "content": "tests are red"}}],
1785 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1786 }),
1787 ])
1788 .await;
1789 // The gradle run itself fails; XML on disk carries the details.
1790 h.runner_seen.canned(
1791 ":notes:testDevUnitTest",
1792 1,
1793 "FAILURE: Build failed with an exception.\n> Task :notes:testDevUnitTest FAILED\n* What went wrong:\nThere were failing tests.",
1794 "",
1795 );
1796 let id = create_task(&h, "Structured tests", "Run notes tests.").await;
1797 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1798
1799 let seen = h.or_seen.seen.lock().unwrap().clone();
1800 assert!(seen.len() >= 2, "model called again: {}", seen.len());
1801 let body = serde_json::to_string(&seen[1]).unwrap();
1802 assert!(body.contains("shoutsGreeting"), "failing test name: {body}");
1803 assert!(body.contains("tests: FAILED"), "test summary: {body}");
1804 }
1805
1806 /// `git_log{}` runs real `git log` in the mock slot checkout (seed
1807 /// commit visible).
1808 #[tokio::test]
1809 async fn structured_git_log_reads_slot_history() {
1810 let h = spawn_harness(vec![
1811 tool_resp("c1", "git_log", serde_json::json!({}), "logging"),
1812 serde_json::json!({
1813 "choices": [{"message": {"role": "assistant", "content": "history seen"}}],
1814 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1815 }),
1816 ])
1817 .await;
1818 let id = create_task(&h, "Git log", "Show history.").await;
1819 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1820
1821 let seen = h.or_seen.seen.lock().unwrap().clone();
1822 assert!(seen.len() >= 2, "model called again: {}", seen.len());
1823 let body = serde_json::to_string(&seen[1]).unwrap();
1824 assert!(body.contains("seed commit"), "slot history: {body}");
1825 }
1826
1827 /// `github_read_issue{number: 903}` returns the recorded fixture text.
1828 #[tokio::test]
1829 async fn structured_github_read_issue_returns_fixture_text() {
1830 let h = spawn_harness(vec![
1831 tool_resp("c1", "github_read_issue", serde_json::json!({"number": 903}), "reading"),
1832 serde_json::json!({
1833 "choices": [{"message": {"role": "assistant", "content": "issue seen"}}],
1834 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1835 }),
1836 ])
1837 .await;
1838 let id = create_task(&h, "Read issue", "Read issue 903.").await;
1839 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1840
1841 let seen = h.or_seen.seen.lock().unwrap().clone();
1842 assert!(seen.len() >= 2, "model called again: {}", seen.len());
1843 let body = serde_json::to_string(&seen[1]).unwrap();
1844 assert!(body.contains("Celsius"), "issue body: {body}");
1845 assert!(body.contains("903"), "issue number: {body}");
1846 // The mock GitHub saw the read (token sent server-side only).
1847 let reqs = h.github_seen.requests();
1848 assert!(
1849 reqs.iter().any(|r| r.method == "GET" && r.path.ends_with("/issues/903")),
1850 "issue fetched: {reqs:?}"
1851 );
1852 }
1853
1854 /// Start-from-issue form: blank title/prompt + issue #903 prefills from
1855 /// the mock GitHub, stores issue_number (shown on the task page), and
1856 /// the driver's first request carries the issue text.
1857 #[tokio::test]
1858 async fn start_from_issue_prefills_and_stores_number() {
1859 let h = spawn_harness(vec![serde_json::json!({
1860 "choices": [{"message": {"role": "assistant", "content": "working on it"}}],
1861 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
1862 })])
1863 .await;
1864 let id = create_task_from_issue(&h, "", "", 903).await;
1865 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1866 let html = task_html(&h, id).await;
1867 assert!(html.contains("#903"), "prefilled title + issue badge; tail: {}", &html[html.len().saturating_sub(1500)..]);
1868
1869 let seen = h.or_seen.seen.lock().unwrap().clone();
1870 assert!(!seen.is_empty(), "driver ran");
1871 let first = serde_json::to_string(&seen[0]).unwrap();
1872 assert!(first.contains("Celsius"), "prefilled prompt carries issue body: {first}");
1873 assert!(first.contains("(#903)"), "prompt notes the suffix convention: {first}");
1874 }
1875
1876 /// `finish` without the ` (#<n>)` suffix is rejected on an issue-linked
1877 /// task (tool error, task keeps running); with the suffix it succeeds.
1878 #[tokio::test]
1879 async fn finish_without_issue_suffix_rejected_then_accepted() {
1880 let h = spawn_harness(vec![
1881 tool_resp("c1", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello issue\n"}), "editing"),
1882 tool_resp(
1883 "c2",
1884 "finish",
1885 serde_json::json!({
1886 "summary": "Fixed the thing.",
1887 "commit_message": "notes: fix the thing\n\nBody without suffix."
1888 }),
1889 "finishing without suffix",
1890 ),
1891 tool_resp(
1892 "c3",
1893 "finish",
1894 serde_json::json!({
1895 "summary": "Fixed the thing.",
1896 "commit_message": "notes: fix the thing (#903)\n\nBody with suffix."
1897 }),
1898 "finishing with suffix",
1899 ),
1900 ])
1901 .await;
1902 let id = create_task_from_issue(&h, "", "", 903).await;
1903 // finish parks for review; approve pushes.
1904 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
1905 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
1906 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
1907 let html = task_html(&h, id).await;
1908 assert!(html.contains("pill succeeded\">succeeded<"), "finished after suffix fix; tail: {}", &html[html.len().saturating_sub(1500)..]);
1909 // Approve's post-push hook commented on the issue and labelled it.
1910 let reqs = h.github_seen.requests();
1911 let posts: Vec<String> = reqs
1912 .iter()
1913 .filter(|r| r.method == "POST")
1914 .map(|r| r.path.clone())
1915 .collect();
1916 assert!(posts.iter().any(|p| p.ends_with("/issues/903/comments")), "comment posted: {posts:?}");
1917 assert!(posts.iter().any(|p| p.ends_with("/issues/903/labels")), "label added: {posts:?}");
1918 assert!(html.contains("commented on issue"), "hook status surfaced on the task page");
1919 // The rejection surfaced the suffix rule to the model.
1920 let seen = h.or_seen.seen.lock().unwrap().clone();
1921 let all = serde_json::to_string(&seen).unwrap();
1922 assert!(all.contains("(#903)"), "suffix rule surfaced: {all}");
1923 // The pushed commit carries the suffix (discover the agent branch —
1924 // its slug derives from the prefilled issue title).
1925 let out = TokioCommand::new("git")
1926 .arg("--git-dir")
1927 .arg(h._remote.clone())
1928 .arg("branch")
1929 .arg("--list")
1930 .arg("agent/*")
1931 .arg("--format=%(refname:short)")
1932 .output()
1933 .await
1934 .unwrap();
1935 assert!(out.status.success());
1936 let branches = String::from_utf8(out.stdout).unwrap();
1937 let branch: String = branches.lines().next().unwrap_or("").trim().to_string();
1938 assert!(!branch.is_empty(), "an agent branch was pushed: {branches:?}");
1939 let out = TokioCommand::new("git")
1940 .arg("--git-dir")
1941 .arg(h._remote.clone())
1942 .arg("log")
1943 .arg("--format=%s")
1944 .arg(format!("main..refs/heads/{branch}"))
1945 .output()
1946 .await
1947 .unwrap();
1948 assert!(out.status.success(), "branch {branch} pushed");
1949 let log = String::from_utf8(out.stdout).unwrap();
1950 assert!(log.contains("notes: fix the thing (#903)"), "suffix in commit: {log}");
1951 }
1952
1953 /// Plan gate: a `require_plan` task rejects `edit_file` before approval;
1954 /// `propose_plan` parks `needs_input(plan)`; approve resumes with "Plan
1955 /// approved" and edits are allowed; the changes path keeps the gate shut.
1956 #[tokio::test]
1957 async fn plan_gate_approve_and_changes() {
1958 let h = spawn_harness(vec![
1959 // Turn 1: edit before approval → gate error (stays in-loop).
1960 tool_resp("p0", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hi\n"}), "trying edit first"),
1961 // Turn 2: propose the plan (sole call) → parks needs_input(plan).
1962 tool_resp("p1", "propose_plan", serde_json::json!({"plan_markdown": "## Plan\n1. edit greeting\n2. build"}), "planning"),
1963 // Turn 3 (after approve): edit now allowed, then finish.
1964 tool_resp("p2", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello planned\n"}), "editing"),
1965 tool_resp(
1966 "p3",
1967 "finish",
1968 serde_json::json!({
1969 "summary": "Planned edit.",
1970 "commit_message": "notes: planned edit\n\nBody here."
1971 }),
1972 "finishing",
1973 ),
1974 ])
1975 .await;
1976 let id = create_task_opts(&h, "Plan flow", "Edit the greeting, plan first.", true).await;
1977
1978 // Parks as needs_input(plan); the page shows the plan + buttons.
1979 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
1980 let html = task_html(&h, id).await;
1981 assert!(html.contains("Waiting for you (plan)"), "plan park; tail: {}", &html[html.len().saturating_sub(1500)..]);
1982 assert!(html.contains("edit greeting"), "plan shown");
1983
1984 // The gate error went to the model as the edit's tool result.
1985 let seen = h.or_seen.seen.lock().unwrap().clone();
1986 let mut found_gate = false;
1987 for req in &seen {
1988 for m in req.get("messages").and_then(|v| v.as_array()).unwrap() {
1989 if m.get("role").and_then(|v| v.as_str()) == Some("tool")
1990 && m.get("tool_call_id").and_then(|v| v.as_str()) == Some("p0")
1991 && m.get("content").and_then(|v| v.as_str()).unwrap_or("").contains("Propose a plan with propose_plan")
1992 {
1993 found_gate = true;
1994 }
1995 }
1996 }
1997 assert!(found_gate, "gate error delivered for pre-approval edit");
1998
1999 // Approve → resumes with "Plan approved. Proceed." → edit → finish.
2000 assert_eq!(post_action(&h, id, "plan/approve").await, StatusCode::FOUND);
2001 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
2002 let seen = h.or_seen.seen.lock().unwrap().clone();
2003 let mut found_approved = false;
2004 for req in &seen {
2005 for m in req.get("messages").and_then(|v| v.as_array()).unwrap() {
2006 if m.get("role").and_then(|v| v.as_str()) == Some("tool")
2007 && m.get("tool_call_id").and_then(|v| v.as_str()) == Some("p1")
2008 && m.get("content").and_then(|v| v.as_str()).unwrap_or("").contains("Plan approved. Proceed.")
2009 {
2010 found_approved = true;
2011 }
2012 }
2013 }
2014 assert!(found_approved, "approval result reached the model");
2015 // Review → approve → pushed with the edit.
2016 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
2017 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
2018 let branch = format!("agent/{id}-plan-flow");
2019 let content = remote_show(&h, &branch, "notes/file.txt").await.unwrap();
2020 assert!(content.contains("hello planned"), "edit landed after approval");
2021 }
2022
2023 /// Changes path in isolation: request changes → the pending propose_plan
2024 /// result contains the feedback and the plan stays unapproved (edits still
2025 /// gated), then a re-proposed plan can be approved.
2026 #[tokio::test]
2027 async fn plan_changes_keeps_gate_shut() {
2028 let h = spawn_harness(vec![
2029 tool_resp("q1", "propose_plan", serde_json::json!({"plan_markdown": "## v1\n1. step"}), "planning"),
2030 // After changes: try an edit (still gated), then re-propose.
2031 tool_resp("q2", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hi\n"}), "still gated?"),
2032 tool_resp("q3", "propose_plan", serde_json::json!({"plan_markdown": "## v2\n1. revised step"}), "revising"),
2033 tool_resp("q4", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello revised\n"}), "editing"),
2034 tool_resp(
2035 "q5",
2036 "finish",
2037 serde_json::json!({
2038 "summary": "Revised edit.",
2039 "commit_message": "notes: revised edit\n\nBody here."
2040 }),
2041 "finishing",
2042 ),
2043 ])
2044 .await;
2045 let id = create_task_opts(&h, "Plan changes", "Propose, revise, edit.", true).await;
2046 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
2047
2048 // Request changes → resumes; the pending result contains feedback.
2049 assert_eq!(post_plan_changes(&h, id, "revise: be more specific").await, StatusCode::FOUND);
2050 // Re-proposed plan parks again as needs_input(plan).
2051 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
2052 let html = task_html(&h, id).await;
2053 assert!(html.contains("Waiting for you (plan)"), "re-proposed plan parks");
2054 assert!(html.contains("revised step"), "v2 shown");
2055
2056 // The resumed request carried "User requested changes to the plan: …".
2057 let seen = h.or_seen.seen.lock().unwrap().clone();
2058 let mut found_changes = false;
2059 let mut found_gate = false;
2060 for req in &seen {
2061 let body = serde_json::to_string(req).unwrap();
2062 if body.contains("User requested changes to the plan: revise: be more specific") {
2063 found_changes = true;
2064 }
2065 if body.contains("Propose a plan with propose_plan") {
2066 found_gate = true;
2067 }
2068 }
2069 assert!(found_changes, "changes feedback reached the model");
2070 assert!(found_gate, "edit stayed gated after changes");
2071
2072 // Approve v2 → edit allowed → finish → review → approve.
2073 assert_eq!(post_action(&h, id, "plan/approve").await, StatusCode::FOUND);
2074 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
2075 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
2076 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
2077 let branch = format!("agent/{id}-plan-changes");
2078 let content = remote_show(&h, &branch, "notes/file.txt").await.unwrap();
2079 assert!(content.contains("hello revised"));
2080 }
2081
2082 /// `update_todos` stores the list, emits the event, and the next request's
2083 /// system message contains the todos (volatile tail) after the rules.
2084 #[tokio::test]
2085 async fn todos_stored_and_in_system_prompt() {
2086 let h = spawn_harness(vec![
2087 tool_resp(
2088 "t1",
2089 "update_todos",
2090 serde_json::json!({"items": [
2091 {"text": "edit greeting", "status": "in_progress"},
2092 {"text": "run build", "status": "pending"},
2093 ]}),
2094 "tracking",
2095 ),
2096 tool_resp("t2", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello todos\n"}), "editing"),
2097 tool_resp(
2098 "t3",
2099 "finish",
2100 serde_json::json!({
2101 "summary": "Todo edit.",
2102 "commit_message": "notes: todo edit\n\nBody here."
2103 }),
2104 "finishing",
2105 ),
2106 ])
2107 .await;
2108 let id = create_task(&h, "Todos flow", "Track todos, edit, finish.").await;
2109 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
2110
2111 // The request AFTER the todos update carries them in the system msg.
2112 let seen = h.or_seen.seen.lock().unwrap().clone();
2113 assert!(seen.len() >= 2, "at least two model calls");
2114 let second = &seen[1];
2115 let msgs = second.get("messages").and_then(|v| v.as_array()).unwrap();
2116 let system = msgs.first().unwrap();
2117 let content = system.get("content").and_then(|v| v.as_str()).unwrap_or("");
2118 assert!(content.contains("Todo list:"), "todos section present");
2119 assert!(content.contains("edit greeting"), "todo text present");
2120 assert!(content.contains("[>]"), "in_progress marker");
2121 // Ordering: rules (root AGENTS.md content) before plan/todos tail.
2122 let root_pos = content.find("ROOT RULES FOR TEST");
2123 let todos_pos = content.find("Todo list:");
2124 assert!(root_pos.is_some() && todos_pos.is_some(), "both present");
2125 assert!(root_pos.unwrap() < todos_pos.unwrap(), "rules before todos");
2126 // The update_todos tool result was "ok".
2127 let mut found_ok = false;
2128 for req in seen.iter().skip(1) {
2129 for m in req.get("messages").and_then(|v| v.as_array()).unwrap() {
2130 if m.get("role").and_then(|v| v.as_str()) == Some("tool")
2131 && m.get("tool_call_id").and_then(|v| v.as_str()) == Some("t1")
2132 {
2133 let c = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
2134 assert_eq!(c, "ok");
2135 found_ok = true;
2136 }
2137 }
2138 }
2139 assert!(found_ok, "update_todos result ok in history");
2140 }
2141
2142 /// Review round-trip: finish → review (final_diff stored, no push) →
2143 /// request changes → resume restores edits, finish again → approve →
2144 /// single-commit push with the agent's message.
2145 #[tokio::test]
2146 async fn review_request_changes_then_approve() {
2147 let h = spawn_harness(vec![
2148 tool_resp("r1", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello v1\n"}), "editing"),
2149 tool_resp(
2150 "r2",
2151 "finish",
2152 serde_json::json!({
2153 "summary": "First attempt.",
2154 "commit_message": "notes: first attempt\n\nBody one."
2155 }),
2156 "finishing",
2157 ),
2158 // After request-changes resume: edit again, finish again.
2159 tool_resp("r3", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello v1\n", "new": "hello v2\n"}), "editing"),
2160 tool_resp(
2161 "r4",
2162 "finish",
2163 serde_json::json!({
2164 "summary": "Second attempt.",
2165 "commit_message": "notes: second attempt\n\nBody two."
2166 }),
2167 "finishing",
2168 ),
2169 ])
2170 .await;
2171 let id = create_task(&h, "Review flow", "Edit, finish, revise, finish.").await;
2172 let branch = format!("agent/{id}-review-flow");
2173
2174 // First finish → review, no push, final_diff contains the change.
2175 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
2176 assert!(!remote_has_branch(&h, &branch).await, "no push before approve");
2177 let html = task_html(&h, id).await;
2178 assert!(html.contains("First attempt."), "summary in card");
2179 assert!(html.contains("hello v1"), "diff in card");
2180
2181 // Request changes = normal message in review → resume; the pending
2182 // finish result formats the feedback.
2183 assert_eq!(post_message(&h, id, "use v2 wording instead").await, StatusCode::FOUND);
2184 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
2185 let html = task_html(&h, id).await;
2186 assert!(html.contains("Second attempt."), "second review snapshot");
2187
2188 let seen = h.or_seen.seen.lock().unwrap().clone();
2189 let mut found_review_feedback = false;
2190 for req in &seen {
2191 let body = serde_json::to_string(req).unwrap();
2192 if body.contains("User reviewed the change and requested: use v2 wording instead") {
2193 found_review_feedback = true;
2194 }
2195 }
2196 assert!(found_review_feedback, "request-changes feedback reached the model");
2197
2198 // Approve → one commit with the agent's (second) message.
2199 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
2200 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
2201 let log = remote_log(&h, &branch).await;
2202 assert!(log.contains("notes: second attempt"), "second message pushed: {log}");
2203 assert_eq!(log.lines().count(), 1, "single squashed commit");
2204 let content = remote_show(&h, &branch, "notes/file.txt").await.unwrap();
2205 assert!(content.contains("hello v2"));
2206 }
2207
2208 /// Follow-up after `succeeded` resumes from `pushed_sha` with no WIP, and
2209 /// the next finish/approve fast-forwards the remote branch.
2210 #[tokio::test]
2211 async fn followup_after_succeeded_fast_forwards() {
2212 let h = spawn_harness(vec![
2213 tool_resp("f1", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello one\n"}), "editing"),
2214 tool_resp(
2215 "f2",
2216 "finish",
2217 serde_json::json!({
2218 "summary": "First.",
2219 "commit_message": "notes: first change\n\nBody one."
2220 }),
2221 "finishing",
2222 ),
2223 // Follow-up claim: edit again, finish again.
2224 tool_resp("f3", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello one\n", "new": "hello two\n"}), "editing"),
2225 tool_resp(
2226 "f4",
2227 "finish",
2228 serde_json::json!({
2229 "summary": "Second.",
2230 "commit_message": "notes: second change\n\nBody two."
2231 }),
2232 "finishing",
2233 ),
2234 ])
2235 .await;
2236 let id = create_task(&h, "Followup flow", "Edit, finish, then follow up.").await;
2237 let branch = format!("agent/{id}-followup-flow");
2238
2239 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
2240 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
2241 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
2242 assert_eq!(remote_log(&h, &branch).await.lines().count(), 1);
2243
2244 // Follow-up message re-queues the succeeded task; the agent edits and
2245 // finishes again; approve fast-forwards (2 commits total).
2246 assert_eq!(post_message(&h, id, "also change it to two").await, StatusCode::FOUND);
2247 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
2248 assert_eq!(post_action(&h, id, "approve").await, StatusCode::FOUND);
2249 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
2250 let log = remote_log(&h, &branch).await;
2251 assert_eq!(log.lines().count(), 2, "fast-forwarded: {log}");
2252 assert!(log.contains("notes: second change"));
2253 let content = remote_show(&h, &branch, "notes/file.txt").await.unwrap();
2254 assert!(content.contains("hello two"));
2255 }
2256
2257 /// Discard from review deletes the local WIP ref and is terminal; the
2258 /// remote branch (never pushed) does not exist.
2259 #[tokio::test]
2260 async fn discard_from_review_deletes_wip() {
2261 let h = spawn_harness(vec![
2262 tool_resp("d1", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "hello doomed\n"}), "editing"),
2263 tool_resp(
2264 "d2",
2265 "finish",
2266 serde_json::json!({
2267 "summary": "Doomed.",
2268 "commit_message": "notes: doomed change\n\nBody."
2269 }),
2270 "finishing",
2271 ),
2272 ])
2273 .await;
2274 let id = create_task(&h, "Discard flow", "Edit, finish, discard.").await;
2275 let branch = format!("agent/{id}-discard-flow");
2276 wait_review(&h, id, std::time::Duration::from_secs(60)).await;
2277 assert_eq!(post_action(&h, id, "discard").await, StatusCode::FOUND);
2278 let html = task_html(&h, id).await;
2279 assert!(html.contains("pill discarded\">discarded<"), "discarded");
2280 assert!(!remote_has_branch(&h, &branch).await, "never pushed");
2281 }
2282
2283 /// AGENTS.md auto-load: reading `notes/sub/file` loads
2284 /// `notes/sub/AGENTS.md`; the next request's system message contains it
2285 /// after root/module rules; a second read does not reload.
2286 #[tokio::test]
2287 async fn nested_rules_loaded_on_first_touch() {
2288 // The seed remote gains notes/sub/AGENTS.md + a file beneath it.
2289 // init_remote is fixed; add the nested files via a follow-up commit
2290 // through the harness remote before the agent starts. The harness
2291 // builds its own remote, so instead: create the files in the mock
2292 // slot? No — rules load through runner.read from the slot checkout,
2293 // which clones the harness mirror (seeded from the remote). Push the
2294 // nested files to the remote BEFORE spawning agentd's mirror... but
2295 // spawn_harness owns remote creation. Simplest: extend the mock
2296 // runner's prepare to write the nested files into every slot checkout
2297 // (they are part of the "repo" for this test). That needs mock
2298 // support — instead, drive it through git: the slot checkout is a
2299 // clone of the mirror; the mirror is a clone of the remote. We add
2300 // the files to the REMOTE via a temp clone after spawn? The mirror
2301 // fetches origin/main only at task start (`fetch_main` + prepare from
2302 // main), so committing to the remote BEFORE creating the task works:
2303 // mirror fetch picks it up, slot clones the mirror.
2304 let h = spawn_harness(vec![
2305 tool_resp("g1", "read_file", serde_json::json!({"path": "notes/sub/file.txt"}), "reading"),
2306 tool_resp("g2", "read_file", serde_json::json!({"path": "notes/sub/file.txt"}), "reading again"),
2307 tool_resp("g3", "read_file", serde_json::json!({"path": "notes/file.txt"}), "reading root file"),
2308 serde_json::json!({
2309 "choices": [{"message": {"role": "assistant", "content": "done looking"}}],
2310 "usage": {"prompt_tokens": 1, "completion_tokens": 1}
2311 }),
2312 ])
2313 .await;
2314 // Add nested rules to the remote (mirror fetches at task start).
2315 {
2316 let work = h._tmp.path().join("subseed");
2317 git_no_cwd(&["clone", h._remote.to_str().unwrap(), work.to_str().unwrap()], h._tmp.path()).await;
2318 git_no_cwd(&["config", "user.email", "t@t"], &work).await;
2319 git_no_cwd(&["config", "user.name", "t"], &work).await;
2320 std::fs::create_dir_all(work.join("notes/sub")).unwrap();
2321 std::fs::write(work.join("notes/sub/AGENTS.md"), "SUB RULES: frobnicate carefully\n").unwrap();
2322 std::fs::write(work.join("notes/sub/file.txt"), "sub content\n").unwrap();
2323 git_no_cwd(&["add", "-A"], &work).await;
2324 git_no_cwd(&["commit", "-m", "add sub rules"], &work).await;
2325 git_no_cwd(&["push", "origin", "main"], &work).await;
2326 }
2327 let id = create_task(&h, "Rules flow", "Read the nested files.").await;
2328 wait_parked(&h, id, std::time::Duration::from_secs(60)).await;
2329
2330 let seen = h.or_seen.seen.lock().unwrap().clone();
2331 assert!(seen.len() >= 3, "three reads + chat park = 4 requests, got {}", seen.len());
2332 // Request 2 (after first read): system msg contains SUB RULES after
2333 // root and module rules.
2334 let sys2 = seen[1].get("messages").and_then(|v| v.as_array()).unwrap()[0]
2335 .get("content").and_then(|v| v.as_str()).unwrap_or("");
2336 let root_pos = sys2.find("ROOT RULES FOR TEST").expect("root rules present");
2337 let module_pos = sys2.find("NOTES MODULE RULES").expect("module rules present");
2338 let sub_pos = sys2.find("SUB RULES").expect("nested rules loaded after first touch");
2339 assert!(root_pos < sub_pos && module_pos < sub_pos, "nested rules after root/module");
2340 // The first read's tool result noted the load.
2341 let mut noted = false;
2342 for m in seen[1].get("messages").and_then(|v| v.as_array()).unwrap() {
2343 if m.get("role").and_then(|v| v.as_str()) == Some("tool")
2344 && m.get("tool_call_id").and_then(|v| v.as_str()) == Some("g1")
2345 {
2346 let c = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
2347 if c.contains("[loaded rules: notes/sub/AGENTS.md]") {
2348 noted = true;
2349 }
2350 }
2351 }
2352 assert!(noted, "first read noted [loaded rules: notes/sub/AGENTS.md]");
2353 // Second read of the same dir: no reload note (already in rules_json).
2354 let mut reloaded = false;
2355 'outer: for req in seen.iter().skip(2) {
2356 for m in req.get("messages").and_then(|v| v.as_array()).unwrap() {
2357 if m.get("role").and_then(|v| v.as_str()) == Some("tool")
2358 && m.get("tool_call_id").and_then(|v| v.as_str()) == Some("g2")
2359 {
2360 let c = m.get("content").and_then(|v| v.as_str()).unwrap_or("");
2361 if c.contains("[loaded rules:") {
2362 reloaded = true;
2363 }
2364 break 'outer;
2365 }
2366 }
2367 }
2368 assert!(!reloaded, "second read does not reload");
2369 }
2370
2371 /// Triage: a triage task reads code, gets refused for edit_file, then
2372 /// `finish_triage` fixes only the type + app labels and posts one marked
2373 /// comment; version / release labels are never touched.
2374 #[tokio::test]
2375 async fn triage_task_fixes_labels_and_comments() {
2376 let h = spawn_harness(vec![
2377 tool_resp("t1", "read_file", serde_json::json!({"path": "notes/file.txt"}), "looking"),
2378 tool_resp("t2", "edit_file", serde_json::json!({"path": "notes/file.txt", "old": "hello\n", "new": "x\n"}), "try edit"),
2379 tool_resp("t3", "finish_triage", serde_json::json!({
2380 "type": "bug", "app": "weather", "confidence": "high",
2381 "analysis_markdown": "The widget ignores the unit preference in `weather/Widget.kt:42`."
2382 }), "done"),
2383 ])
2384 .await;
2385 // Issue currently mislabeled as an enhancement for notes.
2386 let mut issue: serde_json::Value =
2387 serde_json::from_str(include_str!("testdata/github/issue_903.json")).unwrap();
2388 issue["labels"] = serde_json::json!([
2389 {"name": "enhancement"}, {"name": "notes"}, {"name": "2.6.12"}, {"name": "solved for next release"}
2390 ]);
2391 h.github_seen.respond("/repos/vayun-mathur/Modern-Apps/issues/903", issue.to_string());
2392 let id = h.store.create_triage_task(903, "#903 widgets", "triage", "weather", "test/model").unwrap();
2393 assert!(h.store.triage_insert(903, id).unwrap());
2394 wait_status(&h, id, std::time::Duration::from_secs(60)).await;
2395 let task = h.store.get_task(id).unwrap().unwrap();
2396 assert_eq!(task.status, crate::models::TaskStatus::Succeeded, "summary/error: {:?} {:?}", task.summary, task.error);
2397
2398 let seen = serde_json::to_string(&h.or_seen.seen.lock().unwrap().clone()).unwrap();
2399 assert!(seen.contains("not available during triage"), "edit_file refused");
2400
2401 let reqs = h.github_seen.requests();
2402 let writes: Vec<String> = reqs
2403 .iter()
2404 .filter(|r| r.method != "GET")
2405 .map(|r| format!("{} {}", r.method, r.path))
2406 .collect();
2407 assert!(writes.iter().any(|w| w == "DELETE /repos/vayun-mathur/Modern-Apps/issues/903/labels/enhancement"), "{writes:?}");
2408 assert!(writes.iter().any(|w| w == "DELETE /repos/vayun-mathur/Modern-Apps/issues/903/labels/notes"), "{writes:?}");
2409 assert!(writes.iter().any(|w| w == "POST /repos/vayun-mathur/Modern-Apps/issues/903/labels"), "{writes:?}");
2410 assert_eq!(writes.iter().filter(|w| w.ends_with("/issues/903/comments")).count(), 1, "{writes:?}");
2411 assert!(!writes.iter().any(|w| w.contains("2.6.12") || w.contains("solved")), "other labels untouched: {writes:?}");
2412 let row = h.store.triage_get(903).unwrap().unwrap();
2413 assert_eq!(row.status, "done");
2414 let result: serde_json::Value = serde_json::from_str(row.result_json.as_deref().unwrap()).unwrap();
2415 assert_eq!(result["type"], "bug");
2416 assert_eq!(result["app"], "weather");
2417
2418 // Dashboard lists it with a fix button; the button creates a normal task.
2419 let dash = h.client.get(url(&h, "/")).header(header::COOKIE, &h.cookie).send().await.unwrap().text().await.unwrap();
2420 assert!(dash.contains("/triage/903/fix"), "triage row on dashboard");
2421 let resp = h.client.post(url(&h, "/triage/903/fix")).header(header::COOKIE, &h.cookie).header(header::ORIGIN, &h.origin).send().await.unwrap();
2422 assert!(resp.status().is_redirection(), "fix route redirects: {}", resp.status());
2423 let loc = resp.headers().get(header::LOCATION).unwrap().to_str().unwrap().to_string();
2424 let fix_id: i64 = loc.rsplit('/').next().unwrap().parse().unwrap();
2425 let fix = h.store.get_task(fix_id).unwrap().unwrap();
2426 assert_eq!(fix.kind, crate::models::TASK_KIND_TASK);
2427 assert_eq!(fix.issue_number, Some(903));
2428 assert!(fix.require_plan);
2429 }
2430}