diff --git a/doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md b/doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md index b7b7ce6403..591a72c579 100644 --- a/doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md +++ b/doc/2026-11-21T11-30-00Z_design_fleet-agent-front-door/2026-11-21T11-30-00Z_design_fleet-agent-front-door.md @@ -271,3 +271,31 @@ Each is made, with how to undo it. 4. The PM stack does not yet show which rung fed each agent's task. It does now separate hands items from choices an agent parked on the owner. 5. A `feature_slice` queue kind, so slices can also be scheduled centrally. + +--- + +## 2026-11-21T12-45-00Z Update: nine review findings fixed + +An automated review of #12227 arrived after the merge with nine findings. +Each was checked against the code, each was real, and each is fixed with a +test that fails without the fix. + +| Finding | Fix | +| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| `fleet shell --build` gave the lock wrapper only the first word of a compound command | The whole command runs in one shell beneath the lock: `fleet-build-lock sh -c ''`. Checked against a real shell and a recording wrapper | +| `--build` was ignored when the target was this host | A local build takes the lock where the host has one, and says so on stderr where it does not | +| A shortlist entry was handed out without checking it again | The issue is read again first. A hold, a claim, a close, a tracker or a hands item drops the entry; the next one is tried | +| An option given with no value fell back to its default (`--target=`, `--profile=`) | A blank value, a missing value, or another option where the value should be is a usage error, before anything runs | +| Two runs at the same moment could take the same priority issue | The pick and its reservation happen in one locked update. Twelve concurrent reservations over eight issues hand each out once | +| Only the first 30 issues of a rank were read | Each rank is read page by page until enough free issues are found, a short page ends it, or five pages are read | +| With one to three eligible issues the list stayed low, so every run was told to refill it | A fill records its time. For 30 minutes after a fill a low list is worked, not refilled again | +| Follow-up commands dropped a chosen `--shortlist` | `--shortlist`, `--repo` and `--profile` are carried into every follow-up command, quoted | +| `doctor` and a dry-run enrolment trusted the bridge's public health page | The mailbox is read as the agent, taking nothing. With no agent name the push rung is reported as not working, with the reason | + +When GitHub cannot be asked, a listed issue is still handed out, marked +`rechecked: false` with a note to read the issue for a hold first: the +shortlist is the rung that works without the network, and withholding its +work then would defeat it. + +This closes gap 3 in the list above. `fleet-agent` now has 65 tests; 16 more +hand-made faults, one per fix or more, were each caught. diff --git a/doc/agents/onboarding-an-agent.md b/doc/agents/onboarding-an-agent.md index f184abf92b..882642a1f9 100644 --- a/doc/agents/onboarding-an-agent.md +++ b/doc/agents/onboarding-an-agent.md @@ -67,6 +67,9 @@ fleet shell --build -- # a long build: takes a build slot fleet shell # an interactive shell ``` +A whole command line works as one quoted argument, and all of it runs under +the build slot: `fleet shell --build -- 'cd pkgs/id && cargo test'`. + ## What you need HTTPS is enough for messages and for three of the four rungs. The queue rung diff --git a/pkgs/fleet/crates/fleet-agent/src/enroll.rs b/pkgs/fleet/crates/fleet-agent/src/enroll.rs index 5855effd13..b0d4300a1b 100644 --- a/pkgs/fleet/crates/fleet-agent/src/enroll.rs +++ b/pkgs/fleet/crates/fleet-agent/src/enroll.rs @@ -85,6 +85,9 @@ fn write_profile(path: &PathBuf, profile: &Profile) -> R<()> { fs::write(path, format!("{text}\n")).map_err(down) } +const BRIDGE_NEEDS: &str = + "HTTPS to the message bridge, and the fleet token by name through fleet secrets"; + /// One leg's answer from this seat. #[derive(Debug, Clone, PartialEq)] pub struct Leg { @@ -108,11 +111,23 @@ impl Leg { } } -/// Probe the four legs. With `register`, the bridge probe is the -/// `hello` that registers the agent; without it, a health check. -pub fn probe(world: &dyn World, register: Option<(&str, &[String])>) -> Vec { - let bridge_call = match register { - Some((agent, groups)) => { +/// How the bridge leg is checked. The service's health answers +/// anyone, so it says nothing about whether this seat holds the fleet +/// token; only a call made as an agent does. +#[derive(Debug, Clone, Copy)] +pub enum BridgeProbe<'a> { + /// Register the agent with its groups (`bridge hello`). + Register(&'a str, &'a [String]), + /// Read the agent's mailbox without taking anything. + Read(&'a str), + /// No agent name is known: only the service can be asked. + Service, +} + +/// Probe the four legs, the bridge leg as `how` says. +pub fn probe(world: &dyn World, how: BridgeProbe) -> Vec { + let bridge_call = match how { + BridgeProbe::Register(agent, groups) => { let mut hello = argv(&["bridge", "hello", "--agent", agent]); if !groups.is_empty() { hello.push("--groups".to_string()); @@ -120,7 +135,10 @@ pub fn probe(world: &dyn World, register: Option<(&str, &[String])>) -> Vec } hello } - None => argv(&["bridge", "health"]), + // A read that takes nothing: it needs the fleet token, so it + // shows this seat can really read its mailbox. + BridgeProbe::Read(agent) => argv(&["bridge", "inbox", "--agent", agent, "--limit", "1"]), + BridgeProbe::Service => argv(&["bridge", "health"]), }; // The four legs are independent, so they are asked together. let mut outs = world @@ -157,16 +175,28 @@ pub fn probe(world: &dyn World, register: Option<(&str, &[String])>) -> Vec (plain, route) }; vec![ - leg( - "bridge", - &bridge_out, - if register.is_some() { - "registered" - } else { - "answers" + match how { + // The service answering is not this seat reading a + // mailbox: without an agent name the push rung is not + // shown as working. + BridgeProbe::Service => Leg { + name: "bridge", + ok: false, + detail: if bridge_out.ok() { + "the service answers, but no agent name is known to read a mailbox with: \ + enrol, or pass --agent" + .to_string() + } else { + bridge_out.why() + }, + needs: BRIDGE_NEEDS, + route: None, }, - "HTTPS to the message bridge, and the fleet token by name through fleet secrets", - ), + BridgeProbe::Register(..) => leg("bridge", &bridge_out, "registered", BRIDGE_NEEDS), + BridgeProbe::Read(..) => { + leg("bridge", &bridge_out, "the mailbox answers", BRIDGE_NEEDS) + } + }, leg( "queue", &queue_out, @@ -287,9 +317,9 @@ pub fn enroll(world: &dyn World, args: &[String]) -> R<(Value, i32)> { } let legs = if dry_run { - probe(world, None) + probe(world, BridgeProbe::Read(&name)) } else { - probe(world, Some((&name, &groups))) + probe(world, BridgeProbe::Register(&name, &groups)) }; let registered = !dry_run && leg_ok(&legs, "bridge"); @@ -375,7 +405,13 @@ pub fn doctor(world: &dyn World, args: &[String]) -> R<(Value, i32)> { Some(n) => Some(check_name("--agent", &n)?), None => None, }; - let legs = probe(world, None); + let legs = probe( + world, + match &agent { + Some(name) => BridgeProbe::Read(name), + None => BridgeProbe::Service, + }, + ); let code = if any_intake(&legs) { EXIT_OK } else { diff --git a/pkgs/fleet/crates/fleet-agent/src/lib.rs b/pkgs/fleet/crates/fleet-agent/src/lib.rs index e16224cdeb..30e93426e9 100644 --- a/pkgs/fleet/crates/fleet-agent/src/lib.rs +++ b/pkgs/fleet/crates/fleet-agent/src/lib.rs @@ -383,13 +383,24 @@ pub fn parse(args: &[String], switches: &[&str], values: &[&str]) -> R { None => (a.clone(), None), }; if values.contains(&name.as_str()) { + // A present option with no value is a usage error, never + // the default (the operator argument contract): a blank + // value, the end of the line, `--`, or another declared + // option where the value should be. + let declared = |token: &str| { + let head = token.split_once('=').map_or(token, |(n, _)| n); + token == "--" || values.contains(&head) || switches.contains(&head) + }; let v = match inline { Some(v) => v, - None => it - .next() - .cloned() - .ok_or_else(|| usage(format!("{name} needs a value")))?, + None => match it.next() { + Some(v) if !declared(v) => v.clone(), + _ => return Err(usage(format!("{name} needs a value"))), + }, }; + if v.trim().is_empty() { + return Err(usage(format!("{name} needs a value"))); + } out.flags.push((name, Some(v))); } else if switches.contains(&name.as_str()) { if inline.is_some() { @@ -414,7 +425,6 @@ impl Args { .find(|(n, _)| n == name) .and_then(|(_, v)| v.clone()) .map(|v| v.trim().to_string()) - .filter(|v| !v.is_empty()) } pub fn uint(&self, name: &str) -> R> { match self.last(name) { diff --git a/pkgs/fleet/crates/fleet-agent/src/next.rs b/pkgs/fleet/crates/fleet-agent/src/next.rs index 4c945d8fb8..3981e52608 100644 --- a/pkgs/fleet/crates/fleet-agent/src/next.rs +++ b/pkgs/fleet/crates/fleet-agent/src/next.rs @@ -157,6 +157,41 @@ fn label_names(issue: &Value) -> Vec { .unwrap_or_default() } +/// Issues read per request, and how many pages of one rank are read +/// before moving on. Held, busy and pull-request rows are dropped after +/// a page is read, so one page is not enough to know a rank is empty. +const PER_PAGE: usize = 30; +const MAX_PAGES_PER_RANK: usize = 5; + +/// Why an issue, as GitHub returns it, may not be handed to an agent; +/// None when it may. One rule for the ranking and for the recheck +/// before a hand-out. +fn kept_out(issue: &Value) -> Option<&'static str> { + if issue.get("pull_request").is_some() { + return Some("it is a pull request"); + } + let labels = label_names(issue); + if labels.iter().any(|l| HOLD_LABELS.contains(&l.as_str())) { + return Some("it carries a hold label"); + } + if labels.iter().any(|l| BUSY_LABELS.contains(&l.as_str())) { + return Some("someone is on it"); + } + if labels.iter().any(|l| NOT_WORK_LABELS.contains(&l.as_str())) { + return Some("it is a tracker"); + } + // A hands item waits on a person's hands (FDR-0013): no agent can + // do it, so no agent is handed it. + let hands_item = issue + .get("body") + .and_then(Value::as_str) + .is_some_and(|body| body.contains(HANDS_MARKER)); + if hands_item { + return Some("it is a hands item"); + } + None +} + /// Open issues worth doing next in `repo`, soonest first: by label /// rank, then oldest. Pull requests, held issues and issues someone is /// already on are left out. Owner parks are kept. @@ -166,64 +201,56 @@ pub fn candidates(world: &dyn World, repo: &str, want: usize) -> Result= want { - break; - } - let path = format!( - "repos/{repo}/issues?state=open&labels={}&per_page=30&sort=created&direction=asc", - encode_label(label) - ); - let page = match gh_api(world, &path, route) { - Ok((Value::Array(items), used)) => { - answered = true; - route = used; - items - } - Ok(_) => { - last_error = format!("GitHub's answer for label {label} was not a list"); - continue; - } - Err(e) => { - last_error = e; - continue; - } - }; - for issue in &page { - if issue.get("pull_request").is_some() { - continue; + for page_number in 1..=MAX_PAGES_PER_RANK { + if found.len() >= want { + break; } - let Some(number) = issue.get("number").and_then(Value::as_u64) else { - continue; + let path = format!( + "repos/{repo}/issues?state=open&labels={}&per_page={PER_PAGE}&sort=created&direction=asc&page={page_number}", + encode_label(label) + ); + let page = match gh_api(world, &path, route) { + Ok((Value::Array(items), used)) => { + answered = true; + route = used; + items + } + Ok(_) => { + last_error = format!("GitHub's answer for label {label} was not a list"); + break; + } + Err(e) => { + last_error = e; + break; + } }; - let labels = label_names(issue); - let kept_out = labels.iter().any(|l| { - HOLD_LABELS.contains(&l.as_str()) - || BUSY_LABELS.contains(&l.as_str()) - || NOT_WORK_LABELS.contains(&l.as_str()) - }); - // A hands item waits on a person's hands (FDR-0013): no - // agent can do it, so no agent is handed it. - let hands_item = issue - .get("body") - .and_then(Value::as_str) - .is_some_and(|body| body.contains(HANDS_MARKER)); - if kept_out || hands_item || found.iter().any(|e| e.issue == number) { - continue; + for issue in &page { + let Some(number) = issue.get("number").and_then(Value::as_u64) else { + continue; + }; + if kept_out(issue).is_some() || found.iter().any(|e| e.issue == number) { + continue; + } + let labels = label_names(issue); + found.push(Entry { + repo: repo.to_string(), + issue: number, + title: issue + .get("title") + .and_then(Value::as_str) + .unwrap_or("") + .to_string(), + rank: rank_of(&labels), + why: format!("label {label}"), + labels, + added_by: String::new(), + added_at: 0, + }); + } + // A short page is the last page of this rank. + if page.len() < PER_PAGE { + break; } - found.push(Entry { - repo: repo.to_string(), - issue: number, - title: issue - .get("title") - .and_then(Value::as_str) - .unwrap_or("") - .to_string(), - rank: rank_of(&labels), - why: format!("label {label}"), - labels, - added_by: String::new(), - added_at: 0, - }); } } if !answered { @@ -234,13 +261,54 @@ pub fn candidates(world: &dyn World, repo: &str, want: usize) -> Result Recheck { + let path = format!("repos/{}/issues/{}", entry.repo, entry.issue); + let issue = match gh_api(world, &path, first_route(world)) { + Ok((issue, _)) => issue, + Err(e) => return Recheck::Unknown(e), + }; + if issue.get("number").and_then(Value::as_u64) != Some(entry.issue) { + return Recheck::Unknown("GitHub's answer was not this issue".to_string()); + } + if issue.get("state").and_then(Value::as_str) != Some("open") { + return Recheck::Gone("it is closed"); + } + if let Some(why) = kept_out(&issue) { + return Recheck::Gone(why); + } + let labels = label_names(&issue); + Recheck::Free(Entry { + title: issue + .get("title") + .and_then(Value::as_str) + .unwrap_or(&entry.title) + .to_string(), + rank: rank_of(&labels), + labels, + ..entry.clone() + }) +} + +/// The task an issue becomes, the same shape from rung 3 and rung 4. fn owner_parked(labels: &[String]) -> bool { labels .iter() .any(|l| OWNER_PARK_LABELS.contains(&l.as_str())) } -/// The task an issue becomes, the same shape from rung 3 and rung 4. fn issue_task(entry: &Entry) -> Value { let parked = owner_parked(&entry.labels); let mut instructions = format!( @@ -272,6 +340,10 @@ fn tried(list: &mut Vec, rung: &str, result: &str, why: impl Into list.push(json!({"rung": rung, "result": result, "why": why.into()})); } +/// How many listed entries in a row may turn out stale in one run +/// before the shortlist rung gives way to the priority rung. +const MAX_STALE_ENTRIES: usize = 5; + enum FromShortlist { Take(Entry), Refill, @@ -319,6 +391,15 @@ pub fn next(world: &dyn World, args: &[String]) -> R<(Value, i32)> { .uint("--low-water")? .unwrap_or(shortlist::DEFAULT_LOW_WATER); let now = world.now(); + // What the caller chose is carried into every follow-up command, + // so the next step reads the same list, repo and profile. + let mut carried = String::new(); + for flag in ["--repo", "--shortlist", "--profile"] { + if let Some(value) = a.last(flag) { + carried.push_str(&format!(" {flag} {}", crate::shell::sh_quote(&value))); + } + } + let again = format!("fleet agent next --agent {agent}{carried}"); let mut log: Vec = Vec::new(); let answer = |rung: &str, task: Value, then: Vec, log: Vec| { ( @@ -416,28 +497,56 @@ pub fn next(world: &dyn World, args: &[String]) -> R<(Value, i32)> { if a.has("--no-shortlist") { tried(&mut log, "shortlist", "skipped", "--no-shortlist"); } else { - let step = list_path.clone().and_then(|file| { - shortlist::update(&file, now, |list| { - if list.is_low(low_water) && list.refill.is_none() { - list.refill = Some((agent.clone(), now)); - FromShortlist::Refill - } else { - match list.take(&agent, now) { - Some(entry) => FromShortlist::Take(entry), - None => FromShortlist::Empty, + // An entry was free when it was listed. It is read again before + // it is handed out, so a hold or a claim made since then wins; + // a few stale entries in a row are dropped, not handed out. + let mut dropped: Vec = Vec::new(); + let step = loop { + let step = list_path.clone().and_then(|file| { + shortlist::update(&file, now, |list| { + if list.needs_refill(low_water, now) { + list.refill = Some((agent.clone(), now)); + FromShortlist::Refill + } else { + match list.take(&agent, now) { + Some(entry) => FromShortlist::Take(entry), + None => FromShortlist::Empty, + } + } + }) + }); + let Ok(FromShortlist::Take(entry)) = step else { + break step.map(|s| (s, None)); + }; + match recheck(world, &entry) { + Recheck::Free(fresh) => break Ok((FromShortlist::Take(fresh), None)), + Recheck::Unknown(why) => break Ok((FromShortlist::Take(entry), Some(why))), + Recheck::Gone(why) => { + dropped.push(format!("#{} dropped: {why}", entry.issue)); + if dropped.len() >= MAX_STALE_ENTRIES { + break Ok((FromShortlist::Empty, None)); } } - }) - }); + } + }; + let stale = dropped.join("; "); match step { - Ok(FromShortlist::Take(entry)) => { + Ok((FromShortlist::Take(entry), unchecked)) => { + let mut task = issue_task(&entry); + task["rechecked"] = json!(unchecked.is_none()); + if let Some(why) = unchecked { + task["recheck_note"] = json!(format!( + "GitHub did not answer, so this entry's labels are as listed. Read the \ + issue for a hold before you start. ({why})" + )); + } let then = vec![ "post one progress note on the issue when a PR is open".to_string(), - format!("fleet agent next --agent {agent}"), + again.clone(), ]; - return Ok(answer("shortlist", issue_task(&entry), then, log)); + return Ok(answer("shortlist", task, then, log)); } - Ok(FromShortlist::Refill) => { + Ok((FromShortlist::Refill, _)) => { // Best effort: hand the filler what GitHub ranks highest. let (found, note) = match candidates(world, &repo, 16) { Ok(found) => (found, String::new()), @@ -454,21 +563,31 @@ pub fn next(world: &dyn World, args: &[String]) -> R<(Value, i32)> { `fleet agent shortlist add` where you can do better than the ranking.", "candidates": found.iter().map(issue_task).collect::>(), "candidates_note": note, + "dropped": stale, }); + let list_flag = a + .last("--shortlist") + .map(|p| format!(" --shortlist {}", crate::shell::sh_quote(&p))) + .unwrap_or_default(); let then = vec![ - format!("fleet agent shortlist fill --agent {agent} --repo {repo}"), + format!("fleet agent shortlist fill --agent {agent} --repo {repo}{list_flag}"), format!( - "fleet agent shortlist add --agent {agent} --issue --title --why " + "fleet agent shortlist add --agent {agent} --repo {repo}{list_flag} --issue --title --why " ), - format!("fleet agent next --agent {agent}"), + again.clone(), ]; return Ok(answer("refill", task, then, log)); } - Ok(FromShortlist::Empty) => tried( + Ok((FromShortlist::Empty, _)) => tried( &mut log, "shortlist", "empty", - "another run is refilling it", + if stale.is_empty() { + "nothing is listed, and it was filled or claimed for filling recently" + .to_string() + } else { + stale + }, ), Err(e) => tried(&mut log, "shortlist", "down", e.to_string()), } @@ -480,36 +599,20 @@ pub fn next(world: &dyn World, args: &[String]) -> R<(Value, i32)> { } else { match candidates(world, &repo, 12) { Ok(found) => { - // Do not hand out what this host handed out in the last two hours. - let handed = list_path - .as_ref() - .ok() - .and_then(|file| shortlist::load(file).ok()) - .map(|mut list| { - list.prune(now); - list - }) - .unwrap_or_default(); - let pick = found - .into_iter() - .find(|e| !handed.recently_handed(&e.repo, e.issue)); + // Choose and reserve in one locked update, so two runs + // on this host at the same moment cannot both take the + // same issue. A host that cannot write the file still + // gets a task: the first candidate. + let pick = match &list_path { + Ok(file) => shortlist::reserve(file, now, &agent, &found) + .unwrap_or_else(|_| found.first().cloned()), + Err(_) => found.first().cloned(), + }; match pick { Some(entry) => { - if let Ok(file) = &list_path { - // Remembering the hand-out is best effort: a host - // that cannot write the file still gets its task. - let _ = shortlist::update(file, now, |list| { - list.handed.push(shortlist::Handed { - repo: entry.repo.clone(), - issue: entry.issue, - to: agent.clone(), - at: now, - }); - }); - } let then = vec![ "post one progress note on the issue when a PR is open".to_string(), - format!("fleet agent next --agent {agent}"), + again.clone(), ]; return Ok(answer("priority", issue_task(&entry), then, log)); } diff --git a/pkgs/fleet/crates/fleet-agent/src/shell.rs b/pkgs/fleet/crates/fleet-agent/src/shell.rs index 87d2ed8041..36b3098b11 100644 --- a/pkgs/fleet/crates/fleet-agent/src/shell.rs +++ b/pkgs/fleet/crates/fleet-agent/src/shell.rs @@ -101,6 +101,11 @@ pub fn sh_quote(word: &str) -> String { } } +/// One word in single quotes, whatever it holds. +pub fn sh_quote_always(word: &str) -> String { + format!("'{}'", word.replace('\'', "'\\''")) +} + /// The command as one shell string. A single word is taken as a shell /// string already; several words are quoted one by one. pub fn shell_string(words: &[String]) -> String { @@ -205,6 +210,25 @@ pub struct Options { pub detach: bool, } +/// The whole command, run by a shell beneath the build lock. The lock +/// wrapper execs one program with its arguments, so a command with +/// `cd`, `&&` or a pipe has to be one shell's argument: otherwise only +/// its first word would hold the slot. +fn under_build_lock(command: &str) -> String { + format!("{BUILD_LOCK} sh -c {}", sh_quote_always(command)) +} + +/// A build on this host: under the build lock where this host has one +/// (the laptop does), and plainly, with a note, where it does not. +fn local_build_line(command: &str) -> String { + let quoted = sh_quote_always(command); + format!( + "if [ -x {BUILD_LOCK} ]; then exec {BUILD_LOCK} sh -c {quoted}; fi; \ + echo 'fleet shell: this host has no build lock; running without one' >&2; \ + exec sh -c {quoted}" + ) +} + /// Build the argv for a target. Pure: no probing, no running. pub fn plan(target: Target, because: String, words: &[String], opts: &Options) -> R { let interactive = words.is_empty(); @@ -228,6 +252,11 @@ pub fn plan(target: Target, because: String, words: &[String], opts: &Options) - Some(dir) => format!("cd {} && {command}", sh_quote(dir)), None => command, }; + let line = if opts.build { + local_build_line(&line) + } else { + line + }; ("sh".to_string(), vec!["-lc".to_string(), line]) } } @@ -253,7 +282,7 @@ pub fn plan(target: Target, because: String, words: &[String], opts: &Options) - args.push("--shell".to_string()); args.push("--".to_string()); args.push(if opts.build { - format!("{BUILD_LOCK} {command}") + under_build_lock(&command) } else { command }); diff --git a/pkgs/fleet/crates/fleet-agent/src/shortlist.rs b/pkgs/fleet/crates/fleet-agent/src/shortlist.rs index 4daa081602..7660ac1176 100644 --- a/pkgs/fleet/crates/fleet-agent/src/shortlist.rs +++ b/pkgs/fleet/crates/fleet-agent/src/shortlist.rs @@ -65,6 +65,10 @@ pub struct Shortlist { pub entries: Vec, /// Who is refilling, and since when. pub refill: Option<(String, u64)>, + /// When a fill last finished. A list that is still low just after + /// a fill is low because little work is eligible, not because + /// nobody filled it. + pub filled_at: Option, pub handed: Vec, } @@ -137,6 +141,7 @@ impl Shortlist { "version": 1, "entries": self.entries.iter().map(Entry::to_json).collect::>(), "refill": self.refill.as_ref().map(|(by, at)| json!({"by": by, "at": at})), + "filled_at": self.filled_at, "handed": self .handed .iter() @@ -176,6 +181,7 @@ impl Shortlist { Some(Shortlist { entries, refill, + filled_at: v.get("filled_at").and_then(Value::as_u64), handed, }) } @@ -235,6 +241,20 @@ impl Shortlist { pub fn is_low(&self, low_water: u64) -> bool { (self.entries.len() as u64) <= low_water } + + /// Whether a fill finished within the refill window. + pub fn filled_recently(&self, now: u64) -> bool { + self.filled_at + .is_some_and(|at| now.saturating_sub(at) < REFILL_FRESH_SECS) + } + + /// Whether this run should switch purpose and refill: the list is + /// low, nobody has claimed the refill, and no fill just finished. + /// The last part is what lets a host with only one or two eligible + /// issues work them, in place of refilling for ever. + pub fn needs_refill(&self, low_water: u64, now: u64) -> bool { + self.is_low(low_water) && self.refill.is_none() && !self.filled_recently(now) + } } // ---- the file ---- @@ -365,6 +385,28 @@ pub fn update(path: &Path, now: u64, change: impl FnOnce(&mut Shortlist) -> T Ok(answer) } +/// Pick the first of `found` that this host has not handed out +/// lately, and record the hand-out, in one locked update. Choosing +/// outside the lock would let two runs at the same moment both pick +/// the same issue. +pub fn reserve(path: &Path, now: u64, to: &str, found: &[Entry]) -> R> { + update(path, now, |list| { + let pick = found + .iter() + .find(|e| !list.recently_handed(&e.repo, e.issue)) + .cloned(); + if let Some(entry) = &pick { + list.handed.push(Handed { + repo: entry.repo.clone(), + issue: entry.issue, + to: to.to_string(), + at: now, + }); + } + pick + }) +} + // ---- the verbs ---- fn status_json(path: &Path, list: &Shortlist, low_water: u64) -> Value { @@ -487,8 +529,11 @@ pub fn run(world: &dyn World, args: &[String]) -> R<(Value, i32)> { added += 1; } } - // The fill is done: whoever held the purpose is released. + // The fill is done: whoever held the purpose is released, + // and the time is kept so a list that stays low is + // worked, not refilled again at once. list.refill = None; + list.filled_at = Some(now); (added, list.entries.len()) })?; Ok(( diff --git a/pkgs/fleet/crates/fleet-agent/src/tests.rs b/pkgs/fleet/crates/fleet-agent/src/tests.rs index 4767f1df31..82e4ff56e2 100644 --- a/pkgs/fleet/crates/fleet-agent/src/tests.rs +++ b/pkgs/fleet/crates/fleet-agent/src/tests.rs @@ -325,6 +325,10 @@ fn a_low_shortlist_makes_this_run_the_filler_and_only_this_run() { "labels=now", vec![ok(json!([issue(557, &["now"]), issue(1067, &["now"])]))], ) + .on( + "issues/900", + vec![ok(open_issue(900, &["priority/normal"]))], + ) .on("gh api", vec![ok(json!([]))]); fake.seed(vec![entry(900, 5, 10), entry(901, 5, 11)]); // two entries: at or under three let (out, code) = run(&fake, &["next", "--agent", "muse-3"]); @@ -1004,11 +1008,131 @@ fn a_build_takes_a_lock_slot_and_an_hour() { "3600", "--shell", "--", - "~/tools/fleet-build-lock cargo test -p id-core", + "~/tools/fleet-build-lock sh -c 'cargo test -p id-core'", ]) ); } +#[test] +fn a_compound_build_command_runs_whole_under_the_lock() { + // The lock wrapper execs one program with its arguments + // (pkgs/fleet/fleet-build-lock ends in `exec "$@"`), so `cd` and + // `&&` must reach it inside one shell's argument. + let plan = shell::plan( + Target::Laptop, + "test".into(), + &words(&["cd pkgs/id && cargo test -p 'id core'"]), + &Options { + build: true, + ..opts() + }, + ) + .unwrap(); + assert_eq!( + plan.args.last().unwrap(), + r#"~/tools/fleet-build-lock sh -c 'cd pkgs/id && cargo test -p '\''id core'\'''"# + ); +} + +/// A HOME whose `tools/fleet-build-lock` logs its arguments, one per +/// line, and then runs them, like the real wrapper's last line. +fn home_with_a_recording_lock() -> PathBuf { + let home = std::env::temp_dir().join(format!( + "fleet-agent-lock-{}-{}", + std::process::id(), + NEXT_DIR.fetch_add(1, Ordering::SeqCst) + )); + let tools = home.join("tools"); + std::fs::create_dir_all(&tools).expect("tools dir"); + let lock = tools.join("fleet-build-lock"); + std::fs::write( + &lock, + "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$HOME/lock.log\"\nexec \"$@\"\n", + ) + .expect("write the lock"); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o755)).expect("chmod"); + home +} + +fn run_local_plan(home: &std::path::Path, plan: &shell::Plan) -> std::process::Output { + assert_eq!(plan.program, "sh"); + assert_eq!(plan.args[0], "-lc"); + std::process::Command::new("/bin/sh") + .arg("-c") + .arg(&plan.args[1]) + .env("HOME", home) + .current_dir(home) + .output() + .expect("sh runs") +} + +#[test] +fn a_local_build_runs_every_part_of_the_command_under_the_lock() { + // Oracle: a real shell and a recording stand-in for the wrapper. + // Both halves of `a && b` must run, and the lock must have been + // given the whole command, once. + let home = home_with_a_recording_lock(); + std::fs::create_dir_all(home.join("work dir")).unwrap(); + let plan = shell::plan( + Target::Local, + "test".into(), + &words(&["echo first && echo second"]), + &Options { + cwd: Some("work dir".into()), + build: true, + ..opts() + }, + ) + .unwrap(); + let out = run_local_plan(&home, &plan); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(String::from_utf8_lossy(&out.stdout), "first\nsecond\n"); + let log = std::fs::read_to_string(home.join("lock.log")).unwrap(); + assert_eq!(log, "sh\n-c\ncd 'work dir' && echo first && echo second\n"); + let _ = std::fs::remove_dir_all(&home); +} + +#[test] +fn a_local_build_on_a_host_without_the_lock_still_runs_and_says_so() { + let home = std::env::temp_dir().join(format!( + "fleet-agent-nolock-{}-{}", + std::process::id(), + NEXT_DIR.fetch_add(1, Ordering::SeqCst) + )); + std::fs::create_dir_all(&home).unwrap(); + let plan = shell::plan( + Target::Local, + "test".into(), + &words(&["echo built"]), + &Options { + build: true, + ..opts() + }, + ) + .unwrap(); + let out = run_local_plan(&home, &plan); + assert!(out.status.success()); + assert_eq!(String::from_utf8_lossy(&out.stdout), "built\n"); + assert!( + String::from_utf8_lossy(&out.stderr).contains("no build lock"), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let _ = std::fs::remove_dir_all(&home); +} + +#[test] +fn a_local_command_without_build_is_left_alone() { + // Positive control: no --build, no wrapper. + let plan = shell::plan(Target::Local, "test".into(), &words(&["echo hi"]), &opts()).unwrap(); + assert_eq!(plan.args, argv(&["-lc", "echo hi"])); +} + #[test] fn detach_starts_a_job_and_only_on_the_laptop() { let detached = Options { @@ -1189,7 +1313,10 @@ fn shell_runs_the_plan_or_prints_it() { match printed { shell::Done::Printed(plan) => { assert_eq!(plan["target"], "laptop"); - assert_eq!(plan["args"][6], "~/tools/fleet-build-lock cargo check"); + assert_eq!( + plan["args"][6], + "~/tools/fleet-build-lock sh -c 'cargo check'" + ); } shell::Done::Ran(_) => panic!("--print must not run"), } @@ -1218,6 +1345,491 @@ proptest! { } } +// ---- review fixes: recheck, reservation, pagination, refill, carried flags ---- + +fn open_issue(number: u64, labels: &[&str]) -> Value { + let mut v = issue(number, labels); + v["state"] = json!("open"); + v +} + +#[test] +fn a_listed_issue_that_was_held_since_is_dropped_and_the_next_free_one_is_handed_out() { + // Oracle: AGENTS.md's hold rule — a human hold wins whenever it is + // set. #900 was free when listed and carries `held` now. + let fake = Fake::new(); + fake.on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]) + .on("issues/900", vec![ok(open_issue(900, &["now", "held"]))]) + .on("issues/901", vec![ok(open_issue(901, &["now"]))]); + fake.seed(vec![ + entry(900, 2, 10), + entry(901, 2, 11), + entry(902, 2, 12), + entry(903, 2, 13), + entry(904, 2, 14), + ]); + let (out, code) = run(&fake, &["next", "--agent", "muse-3"]); + assert_eq!(code, EXIT_OK); + assert_eq!(out["rung"], "shortlist"); + assert_eq!(out["task"]["issue"], 901); + assert_eq!(out["task"]["rechecked"], true); + // The held entry is gone from the list and was never the task. + let list = shortlist::load(&fake.shortlist_path()).unwrap(); + assert!(!list.has("developing-today/code", 900)); + assert_eq!(list.entries.len(), 3); +} + +#[test] +fn a_listed_issue_that_closed_or_was_claimed_is_not_handed_out() { + let fake = Fake::new(); + fake.on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]) + .on( + "issues/900", + vec![ok({ + let mut v = issue(900, &["now"]); + v["state"] = json!("closed"); + v + })], + ) + .on( + "issues/901", + vec![ok(open_issue(901, &["now", "status/in-progress"]))], + ) + .on("issues/902", vec![ok(open_issue(902, &["priority/high"]))]); + // Seven entries: dropping two leaves the list above its low-water + // mark, so the run keeps taking and is not made the filler. + fake.seed((900..907u64).map(|n| entry(n, 2, n)).collect()); + let (out, _) = run(&fake, &["next", "--agent", "muse-3"]); + assert_eq!(out["rung"], "shortlist"); + assert_eq!(out["task"]["issue"], 902); + // The entry carries today's labels, so its rank is today's too. + assert_eq!(out["task"]["rank"], 3); + assert_eq!(out["task"]["labels"], json!(["priority/high"])); +} + +#[test] +fn when_github_cannot_be_asked_the_listed_issue_is_handed_out_and_says_it_was_not_rechecked() { + let fake = Fake::new(); + fake.on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]) + .on("gh api", vec![fail(1, "gh: no network")]); + fake.seed(vec![ + entry(900, 2, 10), + entry(901, 2, 11), + entry(902, 2, 12), + entry(903, 2, 13), + ]); + let (out, code) = run(&fake, &["next", "--agent", "muse-3"]); + assert_eq!(code, EXIT_OK); + assert_eq!(out["task"]["issue"], 900); + assert_eq!(out["task"]["rechecked"], false); + assert!( + out["task"]["recheck_note"] + .as_str() + .unwrap() + .contains("Read the issue for a hold"), + "{}", + out["task"] + ); +} + +#[test] +fn a_run_of_stale_entries_gives_way_to_the_priority_rung() { + // The first five listed issues have closed. After five in a row + // the rung stops and says what it dropped; priority still finds + // work. Twelve entries keep the list above its low-water mark. + let fake = Fake::new(); + let closed = |n: u64| { + let mut v = issue(n, &["now"]); + v["state"] = json!("closed"); + ok(v) + }; + fake.on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]); + for n in 900..905u64 { + fake.on(&format!("issues/{n}"), vec![closed(n)]); + } + fake.on("labels=now", vec![ok(json!([issue(557, &["now"])]))]) + .on("gh api", vec![ok(json!([]))]); + fake.seed((900..912u64).map(|n| entry(n, 2, n)).collect()); + let (out, code) = run(&fake, &["next", "--agent", "muse-3"]); + assert_eq!(code, EXIT_OK); + assert_eq!(out["rung"], "priority"); + assert_eq!(out["task"]["issue"], 557); + let shortlist_try = out["tried"] + .as_array() + .unwrap() + .iter() + .find(|t| t["rung"] == "shortlist") + .unwrap(); + assert_eq!(shortlist_try["result"], "empty"); + let why = shortlist_try["why"].as_str().unwrap(); + assert!(why.contains("#900 dropped: it is closed"), "{why}"); + assert_eq!(why.matches("dropped").count(), 5, "{why}"); +} + +#[test] +fn when_dropping_stale_entries_leaves_the_list_low_this_run_refills_it() { + let fake = Fake::new(); + fake.on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]) + .on( + "issues/900", + vec![ok({ + let mut v = issue(900, &["now"]); + v["state"] = json!("closed"); + v + })], + ) + .on("gh api", vec![ok(json!([]))]); + // Four entries: one drop leaves three, the low-water mark. + fake.seed((900..904u64).map(|n| entry(n, 2, n)).collect()); + let (out, _) = run(&fake, &["next", "--agent", "muse-3"]); + assert_eq!(out["rung"], "refill"); + assert_eq!(out["task"]["dropped"], "#900 dropped: it is closed"); + // The three entries that were not read stay listed. + assert_eq!( + shortlist::load(&fake.shortlist_path()) + .unwrap() + .entries + .len(), + 3 + ); +} + +#[test] +fn a_host_with_only_a_little_eligible_work_does_it_and_does_not_refill_for_ever() { + // The review's case: one eligible issue exists. The fill leaves the + // list under the low-water mark; the next run must take the issue. + let fake = Fake::new(); + fake.on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]) + .on("issues/557", vec![ok(open_issue(557, &["now"]))]) + .on("labels=now", vec![ok(json!([issue(557, &["now"])]))]) + .on("gh api", vec![ok(json!([]))]); + let (first, _) = run(&fake, &["next", "--agent", "muse-3"]); + assert_eq!(first["rung"], "refill"); + let (filled, _) = run(&fake, &["shortlist", "fill", "--agent", "muse-3"]); + assert_eq!(filled["added"], 1); + assert_eq!(filled["count"], 1); + // One entry is under the low-water mark of three, and still: + let (second, _) = run(&fake, &["next", "--agent", "muse-3"]); + assert_eq!(second["rung"], "shortlist"); + assert_eq!(second["task"]["issue"], 557); + // With the list empty just after a fill, the run looks further + // down the ladder; it is not made the filler again. + let (third, code) = run(&fake, &["next", "--agent", "muse-3"]); + assert_ne!(third["rung"], "refill"); + assert_eq!(code, EXIT_NO_WORK); + // Positive control: once the window has passed, a low list is + // refilled again. + fake.now.set(fake.now.get() + shortlist::REFILL_FRESH_SECS); + let (later, _) = run(&fake, &["next", "--agent", "muse-3"]); + assert_eq!(later["rung"], "refill"); +} + +#[test] +fn a_rank_is_read_past_its_first_page_when_that_page_holds_nothing_free() { + // Thirty held issues fill page one of `now`; the free one is on + // page two. A short page ends the rank: no page three is asked. + let fake = Fake::new(); + let held: Vec = (100..130u64).map(|n| issue(n, &["now", "held"])).collect(); + fake.on( + "labels=now&per_page=30&sort=created&direction=asc&page=2", + vec![ok(json!([issue(557, &["now"])]))], + ) + .on("labels=now", vec![ok(Value::Array(held))]) + .on("gh api", vec![ok(json!([]))]); + let found = crate::next::candidates(&fake, "developing-today/code", 10).unwrap(); + assert_eq!(found.iter().map(|e| e.issue).collect::>(), vec![557]); + let now_pages = fake + .calls() + .iter() + .filter(|c| c.contains("labels=now&")) + .count(); + assert_eq!(now_pages, 2); + // A rank whose first page is short is asked once. + assert_eq!( + fake.calls() + .iter() + .filter(|c| c.contains("labels=expedite&")) + .count(), + 1 + ); +} + +#[test] +fn a_rank_that_never_ends_is_read_a_bounded_number_of_pages() { + let fake = Fake::new(); + let held: Vec = (100..130u64).map(|n| issue(n, &["now", "held"])).collect(); + fake.on("gh api", vec![ok(Value::Array(held))]); + let found = crate::next::candidates(&fake, "developing-today/code", 10).unwrap(); + assert!(found.is_empty()); + // Five ranked labels, five pages each at most. + assert_eq!(count_calls(&fake, "fleet gh api repos/"), 25); +} + +#[test] +fn follow_up_commands_carry_the_list_repo_and_profile_the_caller_chose() { + let fake = Fake::new(); + let list = fake.dir.join("my list.json"); + let list_text = list.to_str().unwrap().to_string(); + fake.on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]) + .on("gh api", vec![ok(json!([]))]); + let (out, _) = run( + &fake, + &[ + "next", + "--agent", + "muse-3", + "--repo", + "developing-today/opencode", + "--shortlist", + &list_text, + ], + ); + assert_eq!(out["rung"], "refill"); + let quoted = shell::sh_quote(&list_text); + assert!(quoted.starts_with('\''), "a path with a space is quoted"); + let then: Vec = out["then"] + .as_array() + .unwrap() + .iter() + .map(|l| l.as_str().unwrap().to_string()) + .collect(); + assert_eq!( + then[0], + format!( + "fleet agent shortlist fill --agent muse-3 --repo developing-today/opencode --shortlist {quoted}" + ) + ); + assert!( + then[1].contains(&format!("--shortlist {quoted}")), + "{}", + then[1] + ); + assert_eq!( + then[2], + format!( + "fleet agent next --agent muse-3 --repo developing-today/opencode --shortlist {quoted}" + ) + ); + // The marker went into the chosen file, not the default one. + assert!(shortlist::load(&list).unwrap().refill.is_some()); + assert!(!fake.shortlist_path().exists()); + // Positive control: with nothing chosen, nothing is carried. + let plain = Fake::new(); + plain + .on(INBOX, vec![empty_inbox()]) + .on(CLAIM, vec![no_claim()]) + .on("gh api", vec![ok(json!([]))]); + let (out, _) = run(&plain, &["next", "--agent", "muse-3"]); + assert_eq!(out["then"][2], "fleet agent next --agent muse-3"); +} + +#[test] +fn runs_at_the_same_moment_never_reserve_the_same_issue() { + // Oracle: eight candidates, twelve concurrent reservations on one + // file. Each issue is handed to at most one run, all eight are + // handed out, and the four runs left over get nothing. + let dir = std::env::temp_dir().join(format!( + "fleet-agent-reserve-{}-{}", + std::process::id(), + NEXT_DIR.fetch_add(1, Ordering::SeqCst) + )); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("shortlist.json"); + let found: Vec = (1..=8u64).map(|n| entry(n, 2, n)).collect(); + let picks: Vec> = std::thread::scope(|scope| { + let handles: Vec<_> = (0..12) + .map(|i| { + let file = &file; + let found = &found; + scope.spawn(move || { + shortlist::reserve(file, 1_800_000_000, &format!("run-{i}"), found) + .expect("reserve") + .map(|e| e.issue) + }) + }) + .collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect() + }); + let mut taken: Vec = picks.iter().flatten().copied().collect(); + taken.sort_unstable(); + assert_eq!(taken, (1..=8u64).collect::>()); + assert_eq!(picks.iter().filter(|p| p.is_none()).count(), 4); + let _ = std::fs::remove_dir_all(&dir); +} + +// ---- the bridge leg is checked as an agent, not by the public health page ---- +// +// Oracle: the review's case. `fleet bridge health` answers anyone; a +// seat that cannot resolve the fleet token must not be told its push +// rung works. + +const NO_TOKEN: &str = "secret 'message-bridge.fleet-token' could not be resolved"; + +#[test] +fn doctor_reads_the_mailbox_as_the_agent_and_a_seat_without_the_token_is_not_ok() { + let fake = Fake::new(); + // The service is up, and would answer a health check. + fake.on("fleet bridge health", vec![ok(json!({"ok": true}))]) + .on("fleet bridge inbox", vec![fail(3, NO_TOKEN)]) + .on( + "fleet queue health", + vec![fail(3, "queue broker unreachable")], + ) + .on("fleet gh api", vec![fail(3, "no token")]) + .on("gh api", vec![fail(1, "gh: not signed in")]) + .on( + "fleet laptop-agent health", + vec![fail(3, "no leg answered")], + ); + let (out, code) = run(&fake, &["doctor", "--agent", "muse-7"]); + // No intake leg answers: that is exit 3, not a healthy seat. + assert_eq!(code, EXIT_DOWN); + assert_eq!(out["rungs"]["push"], false); + assert_eq!(out["legs"][0]["leg"], "bridge"); + assert_eq!(out["legs"][0]["ok"], false); + assert!( + out["legs"][0]["detail"] + .as_str() + .unwrap() + .contains("fleet-token"), + "{}", + out["legs"][0] + ); + // The probe read the mailbox without taking anything, and never + // used the public health page. + assert!(fake.called("fleet bridge inbox --agent muse-7 --limit 1")); + assert!(!fake.called("--take")); + assert!(!fake.called("fleet bridge health")); +} + +#[test] +fn doctor_with_a_readable_mailbox_reports_the_push_rung() { + let fake = Fake::new(); + fake.on("fleet bridge inbox", vec![empty_inbox()]) + .on( + "fleet queue health", + vec![fail(3, "queue broker unreachable")], + ) + .on("fleet gh api", vec![fail(3, "no token")]) + .on("gh api", vec![fail(1, "gh: not signed in")]) + .on( + "fleet laptop-agent health", + vec![fail(3, "no leg answered")], + ); + let (out, code) = run(&fake, &["doctor", "--agent", "muse-7"]); + assert_eq!(code, EXIT_OK); + assert_eq!(out["rungs"]["push"], true); + assert_eq!(out["legs"][0]["detail"], "the mailbox answers"); +} + +#[test] +fn doctor_without_an_agent_name_does_not_claim_the_push_rung() { + let fake = Fake::new(); + fake.on("fleet bridge health", vec![ok(json!({"ok": true}))]) + .on( + "fleet queue health", + vec![fail(3, "queue broker unreachable")], + ) + .on( + "fleet gh api", + vec![ok(json!({"rate": {"remaining": 4000}}))], + ) + .on( + "fleet laptop-agent health", + vec![fail(3, "no leg answered")], + ); + let (out, code) = run(&fake, &["doctor"]); + // GitHub answers, so the seat has an intake leg. + assert_eq!(code, EXIT_OK); + assert_eq!(out["agent"], Value::Null); + assert_eq!(out["rungs"]["push"], false); + assert_eq!(out["rungs"]["priority"], true); + assert!( + out["legs"][0]["detail"] + .as_str() + .unwrap() + .contains("no agent name is known"), + "{}", + out["legs"][0] + ); +} + +#[test] +fn a_dry_run_enrolment_checks_the_mailbox_without_registering() { + let fake = Fake::new(); + fake.on("fleet bridge health", vec![ok(json!({"ok": true}))]) + .on("fleet bridge inbox", vec![fail(3, NO_TOKEN)]) + .on("fleet ", vec![fail(3, "unreachable")]) + .on("gh ", vec![fail(1, "x")]); + let (out, _) = run( + &fake, + &["enroll", "--kind", "muse", "--name", "muse-7", "--dry-run"], + ); + assert_eq!(out["rungs"]["push"], false); + assert!(fake.called("fleet bridge inbox --agent muse-7 --limit 1")); + assert!(!fake.called("bridge hello")); + assert!(!fake.called("--take")); +} + +// ---- strict arguments ---- +// +// Oracle: doc/agents/operator-script-argument-contract.md — "a +// present-but-valueless option is a usage error, never the default". + +#[test] +fn an_option_given_without_a_value_is_a_usage_error_not_the_default() { + let values = ["--target", "--profile", "--name", "--kind"]; + let switches = ["--dry-run"]; + for line in [ + vec!["--target="], + vec!["--target", ""], + vec!["--target", " "], + vec!["--target"], + vec!["--name", "--kind", "muse"], + vec!["--name", "--kind=muse"], + vec!["--name", "--dry-run"], + vec!["--profile", "--", "true"], + ] { + let err = crate::parse(&argv(&line), &switches, &values).unwrap_err(); + match err { + AgentError::Usage(text) => { + assert!(text.ends_with("needs a value"), "{line:?}: {text}") + } + other => panic!("{line:?}: expected a usage error, got {other:?}"), + } + } + // Positive controls: both spellings of a real value parse alike. + let spaced = crate::parse(&argv(&["--target", "laptop"]), &switches, &values).unwrap(); + let inline = crate::parse(&argv(&["--target=laptop"]), &switches, &values).unwrap(); + assert_eq!(spaced.last("--target").as_deref(), Some("laptop")); + assert_eq!(inline.last("--target").as_deref(), Some("laptop")); + // A value that only looks like an option, but is not one, is a value. + let odd = crate::parse(&argv(&["--name", "--x"]), &switches, &values).unwrap(); + assert_eq!(odd.last("--name").as_deref(), Some("--x")); +} + +#[test] +fn a_blank_profile_path_never_falls_back_to_the_default_profile() { + // The review's case: `--profile=` must not overwrite the default + // profile. Nothing is probed and nothing is written. + let fake = Fake::new(); + let err = execute( + &fake, + &argv(&["enroll", "--kind", "muse", "--name", "muse-7", "--profile="]), + ) + .unwrap_err(); + assert!(matches!(err, AgentError::Usage(_)), "{err:?}"); + assert!(fake.calls().is_empty(), "{:?}", fake.calls()); + assert!(!fake.profile_path().exists()); +} + // ---- bounded steps ---- // // Oracle: the contract in `capture`'s doc comment, checked against