diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index 48a7b4e9d5..529488da4d 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -321,7 +321,20 @@ pub const DOMAINS: &[Domain] = &[ capabilities: &[Capability::Gh], primary: Capability::Gh, aliases: &[], - subcommands: &["tiers", "cache-serve", "cache-status", "closures"], + subcommands: &[ + "tiers", + "cache-serve", + "cache-status", + "closures", + "sync-labels", + "sync-view", + "sync-comment", + "sync-issue-create", + "sync-issue-get", + "sync-labels-add", + "sync-label-ensure", + "sync-issue-close", + ], }, Domain { name: "bridge", diff --git a/pkgs/fleet/crates/fleet/src/gh.rs b/pkgs/fleet/crates/fleet/src/gh.rs index 70ab07e607..2ca2b33302 100644 --- a/pkgs/fleet/crates/fleet/src/gh.rs +++ b/pkgs/fleet/crates/fleet/src/gh.rs @@ -132,6 +132,7 @@ use crate::gh_cache; use crate::gh_closure; use crate::gh_guard; use crate::gh_metadata; +use crate::gh_sync; use fleet_config::{Config, DEFAULT_GH_CACHE_PORT}; use fleet_secrets::Resolver; use std::io::{IsTerminal, Write}; @@ -189,7 +190,20 @@ FLEET_GH_CACHE as a comma list; an address without a port gets port `fleet gh cache-status` probes the configured daemons. `--cache-addr` overrides every daemon address for one call; `--no-cache` resolves in-process. When no daemon answers, the call resolves in-process and -says so on stderr — never silently."; +says so on stderr — never silently. + +Sync verbs (code#10973, step 2.2 of #9016): the `sync-*` shadow +verbs are the typed Queue/GitHub sync surface for scripted flows +(pm-stack dispatch's fallback, the opencode claimant, job bodies). +Each declares its whole command line, validates it strictly, and +rewrites to the canonical gh call before the guard, closure and +metadata layers run, inheriting the rotation and the retry-safety +rule. `fleet gh sync-labels --repo OWNER/REPO ` prints +an item's label names as JSON; `sync-view` prints labels,state,title +JSON; `sync-comment` posts a comment (`--body` or `--body-file`); +`sync-issue-create`, `sync-issue-get`, `sync-labels-add`, +`sync-label-ensure` and `sync-issue-close` (fleet closure reasons) +cover the issue writes dispatch composes. See gh_sync.rs."; /// The fleet's GitHub Apps, in rotation order. Each carries its /// private key (and, except the fleet App whose ID is a public @@ -1500,6 +1514,24 @@ pub fn run(config: &Config, args: &[String]) -> i32 { if args.first().is_some_and(|a| a == "closures") { return run_closures(&args[1..]); } + // Sync verbs (#10973, step 2.2 of #9016): strictly-parsed typed + // verbs that rewrite to the canonical gh call. The rewrite is + // applied here, before the close guard, the closure layer and + // the metadata create path parse the arguments, so a sync call + // inherits every passthrough control — and the rotation below — + // exactly as the hand-written call it replaces would have. + let sync_rewrite; + let args: &[String] = match gh_sync::parse(args) { + Ok(Some(canonical)) => { + sync_rewrite = canonical; + &sync_rewrite + } + Ok(None) => args, + Err(e) => { + eprintln!("{e}"); + return EXIT_USAGE; + } + }; let guard_intent = match gh_guard::parse(args) { Ok(intent) => intent, Err(e) => { diff --git a/pkgs/fleet/crates/fleet/src/gh_sync.rs b/pkgs/fleet/crates/fleet/src/gh_sync.rs new file mode 100644 index 0000000000..d15c0b95e0 --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/gh_sync.rs @@ -0,0 +1,767 @@ +//! Queue/GitHub sync verbs for `fleet gh` (developing-today/code#10973, +//! step 2.2 of #9016). +//! +//! The recurring scripted flows — pm-stack dispatch's gh fallback, +//! the opencode claimant's label reads and agent notes, launch_one's +//! hard-stop check and launch notes, and the job-body flows named by +//! #9016 (program tending, stewardship verdict posting, pool +//! reviews) — used to compose raw `gh issue` / `gh pr` argument +//! lists at every call site. The `sync-*` shadow verbs give those +//! callers one typed surface instead: each verb declares its whole +//! command line (the #3352 operator-script contract), validates it +//! strictly, and rewrites to the canonical gh call. The rewrite is +//! applied in `gh::run` before the close guard, the closure layer +//! and the metadata create path see the arguments, so a sync call +//! inherits the token rotation, the retry-safety rule, value-free +//! errors and the audit trail exactly as a hand-written passthrough +//! call does — and a caller's stdout contract is gh's own output, +//! byte-exact, because the final attempt's output is never wrapped. +//! +//! Every verb takes `--repo OWNER/REPO`. Item targets are an +//! `issue`/`pr` kind plus a number where the underlying call is +//! kinded. The verbs are: +//! +//! sync-labels label names, JSON list +//! sync-view labels,state,title JSON +//! sync-comment --body T | --body-file P +//! sync-issue-create --title T (--body T | --body-file P) [--label L]... +//! sync-issue-get one issue, API JSON +//! sync-labels-add --label L [--label L]... +//! sync-label-ensure --label L --color C --description D +//! sync-issue-close --reason +//! +//! `sync-issue-close` deliberately speaks the fleet closure taxonomy +//! (#9221, gh_closure::REASONS), not gh's `--reason` state-reason +//! spellings: the canonical call it rewrites to is the closure +//! layer's own input shape, so the close carries its reason comment +//! and closure record like every other fleet close. +//! +//! `--body-file` is read by this layer and substituted as `--body`, +//! so the canonical call is identical whichever form the caller +//! used; an unreadable file refuses the verb before any GitHub +//! write. Errors name the verb, the flag and the stage only — never +//! a body, a token, or any other value the caller passed. + +/// The sync verb names, in help order. Real `gh` has none of these, +/// so intercepting them cannot shadow a passthrough call. +pub const VERBS: [&str; 8] = [ + "sync-labels", + "sync-view", + "sync-comment", + "sync-issue-create", + "sync-issue-get", + "sync-labels-add", + "sync-label-ensure", + "sync-issue-close", +]; + +fn usage(verb: &str) -> &'static str { + match verb { + "sync-labels" => "fleet gh sync-labels --repo OWNER/REPO ", + "sync-view" => "fleet gh sync-view --repo OWNER/REPO ", + "sync-comment" => { + "fleet gh sync-comment --repo OWNER/REPO --body TEXT | --body-file PATH" + } + "sync-issue-create" => { + "fleet gh sync-issue-create --repo OWNER/REPO --title TITLE (--body TEXT | --body-file PATH) [--label LABEL]..." + } + "sync-issue-get" => "fleet gh sync-issue-get --repo OWNER/REPO ", + "sync-labels-add" => { + "fleet gh sync-labels-add --repo OWNER/REPO --label LABEL [--label LABEL]..." + } + "sync-label-ensure" => { + "fleet gh sync-label-ensure --repo OWNER/REPO --label LABEL --color COLOR --description TEXT" + } + "sync-issue-close" => { + "fleet gh sync-issue-close --repo OWNER/REPO --reason REASON" + } + _ => "fleet gh sync-*", + } +} + +fn err(verb: &str, message: &str) -> String { + format!("fleet gh {verb}: {message}\nusage: {}", usage(verb)) +} + +/// One verb's strictly-parsed command line: declared value flags +/// (repeatable flags collect), plus the positional arguments. Any +/// token the verb did not declare is a usage error (#3352). +struct Parsed { + flags: Vec<(String, String)>, + positionals: Vec, +} + +impl Parsed { + fn get(&self, name: &str) -> Option<&str> { + self.flags + .iter() + .rev() + .find(|(n, _)| n == name) + .map(|(_, v)| v.as_str()) + } + + fn get_all(&self, name: &str) -> Vec<&str> { + self.flags + .iter() + .filter(|(n, _)| n == name) + .map(|(_, v)| v.as_str()) + .collect() + } + + fn require(&self, verb: &str, name: &str) -> Result { + self.get(name) + .map(str::to_string) + .ok_or_else(|| err(verb, &format!("missing required flag '{name}'"))) + } +} + +fn parse_declared( + verb: &str, + tail: &[String], + value_flags: &[&str], +) -> Result { + let mut parsed = Parsed { + flags: Vec::new(), + positionals: Vec::new(), + }; + let mut i = 0; + while i < tail.len() { + let a = tail[i].as_str(); + if let Some(long) = a.strip_prefix("--") { + let (name, inline) = match long.split_once('=') { + Some((n, v)) => (n, Some(v.to_string())), + None => (long, None), + }; + let full = format!("--{name}"); + if !value_flags.contains(&full.as_str()) { + return Err(err(verb, &format!("unexpected argument '{a}'"))); + } + let value = match inline { + Some(v) => v, + None => { + i += 1; + match tail.get(i) { + Some(v) => v.clone(), + None => { + return Err(err(verb, &format!("flag '{full}' needs a value"))); + } + } + } + }; + parsed.flags.push((full, value)); + } else if a.starts_with('-') && a.len() > 1 { + return Err(err(verb, &format!("unexpected argument '{a}'"))); + } else { + parsed.positionals.push(a.to_string()); + } + i += 1; + } + Ok(parsed) +} + +/// `--repo` is always OWNER/REPO: two non-empty segments of the +/// characters GitHub allows in owner and repository names. +fn repo(parsed: &Parsed, verb: &str) -> Result { + let raw = parsed.require(verb, "--repo")?; + let mut parts = raw.split('/'); + let ok = match (parts.next(), parts.next(), parts.next()) { + (Some(owner), Some(name), None) => { + !owner.is_empty() + && !name.is_empty() + && owner + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-') + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + } + _ => false, + }; + if ok { + Ok(raw) + } else { + Err(err( + verb, + &format!("--repo '{raw}' is not an OWNER/REPO slug"), + )) + } +} + +/// An item number: digits, with one optional leading `#`. +fn item_number(verb: &str, raw: &str) -> Result { + let digits = raw.strip_prefix('#').unwrap_or(raw); + if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) { + Ok(digits.to_string()) + } else { + Err(err(verb, &format!("'{raw}' is not an item number"))) + } +} + +fn kind(verb: &str, raw: &str) -> Result { + match raw { + "issue" | "pr" => Ok(raw.to_string()), + _ => Err(err( + verb, + &format!("'{raw}' is not an item kind: use 'issue' or 'pr'"), + )), + } +} + +/// The ` ` positional pair most verbs take. +fn kinded_item(verb: &str, parsed: &Parsed) -> Result<(String, String), String> { + if parsed.positionals.len() != 2 { + return Err(err( + verb, + "expected exactly two arguments: ", + )); + } + Ok(( + kind(verb, &parsed.positionals[0])?, + item_number(verb, &parsed.positionals[1])?, + )) +} + +/// The bare `` positional the issue-only verbs take. +fn lone_item(verb: &str, parsed: &Parsed) -> Result { + if parsed.positionals.len() != 1 { + return Err(err(verb, "expected exactly one argument: ")); + } + item_number(verb, &parsed.positionals[0]) +} + +fn no_positionals(verb: &str, parsed: &Parsed) -> Result<(), String> { + match parsed.positionals.first() { + Some(extra) => Err(err(verb, &format!("unexpected argument '{extra}'"))), + None => Ok(()), + } +} + +/// Exactly one of `--body` / `--body-file`; a file is read here so +/// the canonical call carries `--body` either way, and an unreadable +/// file refuses the verb before any GitHub write. +fn body(verb: &str, parsed: &Parsed) -> Result { + match (parsed.get("--body"), parsed.get("--body-file")) { + (Some(_), Some(_)) => Err(err( + verb, + "give exactly one of '--body' and '--body-file'", + )), + (Some(text), None) => Ok(text.to_string()), + (None, Some(path)) => std::fs::read_to_string(path).map_err(|e| { + err( + verb, + &format!("cannot read --body-file '{path}': {e}"), + ) + }), + (None, None) => Err(err( + verb, + "missing required flag '--body' (or '--body-file')", + )), + } +} + +/// Recognise a sync verb and rewrite it to the canonical gh call. +/// Returns Ok(None) for every other invocation, which then passes +/// through untouched. The rewrite is a pure argument transform — +/// the caller in `gh::run` feeds the result through the close +/// guard, the closure layer, the metadata create path and the +/// token rotation unchanged. +pub fn parse(args: &[String]) -> Result>, String> { + let verb = match args.first().map(|s| s.as_str()) { + Some(v) if VERBS.contains(&v) => v, + _ => return Ok(None), + }; + let tail = &args[1..]; + let canonical = match verb { + "sync-labels" => { + let p = parse_declared(verb, tail, &["--repo"])?; + let repo = repo(&p, verb)?; + let (kind, item) = kinded_item(verb, &p)?; + vec![ + kind, + "view".into(), + item, + "--repo".into(), + repo, + "--json".into(), + "labels".into(), + "--jq".into(), + "[.labels[].name]".into(), + ] + } + "sync-view" => { + let p = parse_declared(verb, tail, &["--repo"])?; + let repo = repo(&p, verb)?; + let (kind, item) = kinded_item(verb, &p)?; + vec![ + kind, + "view".into(), + item, + "--repo".into(), + repo, + "--json".into(), + "labels,state,title".into(), + ] + } + "sync-comment" => { + let p = parse_declared(verb, tail, &["--repo", "--body", "--body-file"])?; + let repo = repo(&p, verb)?; + let (kind, item) = kinded_item(verb, &p)?; + let body = body(verb, &p)?; + vec![ + kind, + "comment".into(), + item, + "--repo".into(), + repo, + "--body".into(), + body, + ] + } + "sync-issue-create" => { + let p = parse_declared( + verb, + tail, + &["--repo", "--title", "--body", "--body-file", "--label"], + )?; + no_positionals(verb, &p)?; + let repo = repo(&p, verb)?; + let title = p.require(verb, "--title")?; + let body = body(verb, &p)?; + let mut out = vec![ + "issue".into(), + "create".into(), + "--repo".into(), + repo, + "--title".into(), + title, + "--body".into(), + body, + ]; + for label in p.get_all("--label") { + out.push("--label".into()); + out.push(label.to_string()); + } + out + } + "sync-issue-get" => { + let p = parse_declared(verb, tail, &["--repo"])?; + let repo = repo(&p, verb)?; + let item = lone_item(verb, &p)?; + vec!["api".into(), format!("repos/{repo}/issues/{item}")] + } + "sync-labels-add" => { + let p = parse_declared(verb, tail, &["--repo", "--label"])?; + let repo = repo(&p, verb)?; + let item = lone_item(verb, &p)?; + let labels = p.get_all("--label"); + if labels.is_empty() { + return Err(err(verb, "missing required flag '--label'")); + } + let mut out = vec![ + "issue".into(), + "edit".into(), + item, + "--repo".into(), + repo, + ]; + for label in labels { + out.push("--add-label".into()); + out.push(label.to_string()); + } + out + } + "sync-label-ensure" => { + let p = parse_declared( + verb, + tail, + &["--repo", "--label", "--color", "--description"], + )?; + no_positionals(verb, &p)?; + let repo = repo(&p, verb)?; + let label = p.require(verb, "--label")?; + let color = p.require(verb, "--color")?; + let description = p.require(verb, "--description")?; + vec![ + "label".into(), + "create".into(), + label, + "--repo".into(), + repo, + "--color".into(), + color, + "--description".into(), + description, + "--force".into(), + ] + } + "sync-issue-close" => { + let p = parse_declared(verb, tail, &["--repo", "--reason"])?; + let repo = repo(&p, verb)?; + let item = lone_item(verb, &p)?; + let reason = p.require(verb, "--reason")?; + if !crate::gh_closure::REASONS.contains(&reason.as_str()) { + return Err(err( + verb, + &format!( + "unknown reason '{reason}': use one of {}", + crate::gh_closure::REASONS.join(", ") + ), + )); + } + vec![ + "issue".into(), + "close".into(), + item, + "--repo".into(), + repo, + "--reason".into(), + reason, + ] + } + _ => unreachable!("verb is drawn from VERBS"), + }; + Ok(Some(canonical)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn args(parts: &[&str]) -> Vec { + parts.iter().map(|s| s.to_string()).collect() + } + + fn rewrite(parts: &[&str]) -> Vec { + parse(&args(parts)) + .expect("parse should succeed") + .expect("a sync verb should rewrite") + } + + fn refused(parts: &[&str]) -> String { + parse(&args(parts)).expect_err("parse should refuse") + } + + #[test] + fn non_sync_calls_pass_through_untouched() { + assert_eq!(parse(&args(&["issue", "view", "1"])).unwrap(), None); + assert_eq!(parse(&args(&["sync"])).unwrap(), None); + assert_eq!(parse(&args(&[])).unwrap(), None); + assert_eq!(parse(&args(&["sync-label"])).unwrap(), None); + } + + #[test] + fn sync_labels_rewrites_to_the_jq_label_read() { + assert_eq!( + rewrite(&[ + "sync-labels", + "--repo", + "developing-today/code", + "issue", + "10973" + ]), + args(&[ + "issue", + "view", + "10973", + "--repo", + "developing-today/code", + "--json", + "labels", + "--jq", + "[.labels[].name]" + ]) + ); + } + + #[test] + fn sync_view_rewrites_to_the_state_read() { + assert_eq!( + rewrite(&["sync-view", "--repo=developing-today/code", "pr", "#45"]), + args(&[ + "pr", + "view", + "45", + "--repo", + "developing-today/code", + "--json", + "labels,state,title" + ]) + ); + } + + #[test] + fn sync_comment_rewrites_for_issues_and_prs() { + assert_eq!( + rewrite(&[ + "sync-comment", + "--repo", + "developing-today/code", + "issue", + "7", + "--body", + "note text" + ]), + args(&[ + "issue", + "comment", + "7", + "--repo", + "developing-today/code", + "--body", + "note text" + ]) + ); + assert_eq!( + rewrite(&[ + "sync-comment", + "--repo", + "developing-today/code", + "pr", + "9", + "--body", + "verdict" + ]), + args(&[ + "pr", + "comment", + "9", + "--repo", + "developing-today/code", + "--body", + "verdict" + ]) + ); + } + + #[test] + fn sync_comment_reads_a_body_file() { + let path = std::env::temp_dir().join(format!( + "fleet-gh-sync-test-{}-body.md", + std::process::id() + )); + std::fs::write(&path, "from a file\n").unwrap(); + let out = rewrite(&[ + "sync-comment", + "--repo", + "developing-today/code", + "issue", + "7", + "--body-file", + path.to_str().unwrap(), + ]); + assert_eq!(out.last().map(|s| s.as_str()), Some("from a file\n")); + std::fs::remove_file(&path).ok(); + } + + #[test] + fn sync_comment_refuses_two_body_sources_and_a_missing_file() { + let both = refused(&[ + "sync-comment", + "--repo", + "developing-today/code", + "issue", + "7", + "--body", + "x", + "--body-file", + "y", + ]); + assert!(both.contains("exactly one of '--body' and '--body-file'"), "{both}"); + let missing = refused(&[ + "sync-comment", + "--repo", + "developing-today/code", + "issue", + "7", + "--body-file", + "/nonexistent/fleet-gh-sync-body.md", + ]); + assert!(missing.contains("cannot read --body-file"), "{missing}"); + let neither = refused(&[ + "sync-comment", + "--repo", + "developing-today/code", + "issue", + "7", + ]); + assert!(neither.contains("missing required flag '--body'"), "{neither}"); + } + + #[test] + fn sync_issue_create_rewrites_with_labels_in_order() { + assert_eq!( + rewrite(&[ + "sync-issue-create", + "--repo", + "developing-today/code", + "--title", + "tracking", + "--body", + "body", + "--label", + "queue/queued", + "--label", + "source/dispatch" + ]), + args(&[ + "issue", + "create", + "--repo", + "developing-today/code", + "--title", + "tracking", + "--body", + "body", + "--label", + "queue/queued", + "--label", + "source/dispatch" + ]) + ); + } + + #[test] + fn sync_issue_get_rewrites_to_the_api_read() { + assert_eq!( + rewrite(&["sync-issue-get", "--repo", "developing-today/code", "3007"]), + args(&["api", "repos/developing-today/code/issues/3007"]) + ); + } + + #[test] + fn sync_labels_add_rewrites_and_requires_a_label() { + assert_eq!( + rewrite(&[ + "sync-labels-add", + "--repo", + "developing-today/code", + "12", + "--label", + "queue/claimed", + "--label", + "work/assigned" + ]), + args(&[ + "issue", + "edit", + "12", + "--repo", + "developing-today/code", + "--add-label", + "queue/claimed", + "--add-label", + "work/assigned" + ]) + ); + let none = refused(&["sync-labels-add", "--repo", "developing-today/code", "12"]); + assert!(none.contains("missing required flag '--label'"), "{none}"); + } + + #[test] + fn sync_label_ensure_rewrites_to_a_forced_create() { + assert_eq!( + rewrite(&[ + "sync-label-ensure", + "--repo", + "developing-today/code", + "--label", + "queue/queued", + "--color", + "7057ff", + "--description", + "Has a queued queue task" + ]), + args(&[ + "label", + "create", + "queue/queued", + "--repo", + "developing-today/code", + "--color", + "7057ff", + "--description", + "Has a queued queue task", + "--force" + ]) + ); + } + + #[test] + fn sync_issue_close_speaks_the_closure_taxonomy() { + assert_eq!( + rewrite(&[ + "sync-issue-close", + "--repo", + "developing-today/code", + "12", + "--reason", + "cancelled" + ]), + args(&[ + "issue", + "close", + "12", + "--repo", + "developing-today/code", + "--reason", + "cancelled" + ]) + ); + // gh's own state-reason spelling is not the fleet taxonomy: + // the closure layer would refuse it, so the verb refuses it + // first, naming the accepted reasons. + let gh_shape = refused(&[ + "sync-issue-close", + "--repo", + "developing-today/code", + "12", + "--reason", + "not planned", + ]); + assert!(gh_shape.contains("unknown reason 'not planned'"), "{gh_shape}"); + } + + #[test] + fn strict_parsing_refuses_undeclared_shapes() { + // Unknown flag. + assert!(refused(&[ + "sync-labels", + "--repo", + "developing-today/code", + "issue", + "1", + "--json", + "labels" + ]) + .contains("unexpected argument '--json'")); + // Missing --repo. + assert!(refused(&["sync-labels", "issue", "1"]).contains("missing required flag '--repo'")); + // Repo that is not an OWNER/REPO slug. + assert!(refused(&["sync-labels", "--repo", "code", "issue", "1"]) + .contains("is not an OWNER/REPO slug")); + assert!(refused(&["sync-labels", "--repo", "a/b/c", "issue", "1"]) + .contains("is not an OWNER/REPO slug")); + // Kind that is neither issue nor pr. + assert!(refused(&["sync-labels", "--repo", "a/b", "issuee", "1"]) + .contains("not an item kind")); + // Item that is not a number. + assert!(refused(&["sync-labels", "--repo", "a/b", "issue", "12a"]) + .contains("is not an item number")); + // A value flag with no value. + assert!(refused(&["sync-labels", "--repo"]).contains("flag '--repo' needs a value")); + // A stray positional on a flag-only verb. + assert!(refused(&[ + "sync-label-ensure", + "--repo", + "a/b", + "--label", + "l", + "--color", + "c", + "--description", + "d", + "extra" + ]) + .contains("unexpected argument 'extra'")); + } +} diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index ef9a9073a1..839d6eb3a8 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -56,6 +56,8 @@ mod gh_closure; mod gh_guard; #[cfg(feature = "gh")] mod gh_metadata; +#[cfg(feature = "gh")] +mod gh_sync; mod invocation_ledger; mod session_state; diff --git a/pkgs/fleet/docs/verbs.md b/pkgs/fleet/docs/verbs.md index 3eb6bd83bd..a0d62cd3d4 100644 --- a/pkgs/fleet/docs/verbs.md +++ b/pkgs/fleet/docs/verbs.md @@ -171,6 +171,19 @@ The resolver uses the configured Fleet secrets broker and supported fallback sto Leading `--cache-addr ADDR` options and `--no-cache` control the token cache for a call. Normal `gh` flags and subcommands pass through unchanged. +The `sync-*` verbs are the typed Queue/GitHub sync surface for scripted flows (#10973, step 2.2 of #9016): each declares its whole command line, validates it strictly, and rewrites to the canonical `gh` call before the close guard, closure and metadata layers run, inheriting the rotation and the retry-safety rule. All take `--repo OWNER/REPO`. + +| Verb | Purpose | +| ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `sync-labels ` | Print the item's label names as a JSON list. | +| `sync-view ` | Print the item's labels, state and title as JSON. | +| `sync-comment --body TEXT \| --body-file PATH` | Post a comment on the item. | +| `sync-issue-create --title TITLE (--body TEXT \| --body-file PATH) [--label LABEL]` | Create an issue; the metadata create path stamps the body as usual. | +| `sync-issue-get ` | Print one issue's API JSON. | +| `sync-labels-add --label LABEL [--label LABEL]` | Add labels to an issue. | +| `sync-label-ensure --label LABEL --color COLOR --description TEXT` | Create a label, or update it when it already exists. | +| `sync-issue-close --reason REASON` | Close an issue with a fleet closure reason (implemented, superseded, cancelled, started-incorrectly). | + ## `bridge` — Fleet messaging | Verb | Purpose | diff --git a/pm-stack/dispatch/src/github.ts b/pm-stack/dispatch/src/github.ts index df59afeec1..da0936eea1 100644 --- a/pm-stack/dispatch/src/github.ts +++ b/pm-stack/dispatch/src/github.ts @@ -10,12 +10,21 @@ // developing-today/zettel, dezren39/dezren39) before reaching here. // // Fallback: if the app route is unusable (no app credentials in env, or -// the installation/token call fails), use the laptop's authenticated -// `gh` CLI. Either way failures surface as GitHubError with both routes' -// errors summarized — issue creation is never silently skipped. +// the installation/token call fails), use the fleet gh sync verbs +// (code#10973, step 2.2 of #9016) on the laptop's packaged fleet +// binary, over the fleet token rotation. Either way failures surface +// as GitHubError with both routes' errors summarized — issue creation +// is never silently skipped. import { createSign } from "node:crypto"; +import { homedir } from "node:os"; +import { join } from "node:path"; import { isTimeoutAbort, outboundTimeout } from "./fetchTimeout.ts"; +/** The packaged fleet binary the fallback's sync verbs run through: + * PM_DISPATCH_FLEET_BIN overrides; the default is the packaged + * location the opencode claimant also uses (~/.local/bin/fleet). */ +const FLEET_BIN = process.env.PM_DISPATCH_FLEET_BIN ?? join(homedir(), ".local", "bin", "fleet"); + const GH_API = "https://api.github.com"; export class GitHubError extends Error { @@ -197,20 +206,33 @@ export class GitHubClient { return token; } - // --- gh CLI fallback ------------------------------------------------------- + // --- fleet gh sync-verb fallback ------------------------------------------- + // + // Every fallback call runs one typed sync verb (code#10973) instead + // of composing raw gh arguments here: the verb validates its whole + // command line and rewrites to the canonical gh call over the fleet + // token rotation, and its stdout is the underlying call's stdout, + // byte-exact, so the parsers below keep their shapes. - private async gh(args: string[], input?: string): Promise { - const proc = Bun.spawn(["gh", ...args], { - stdin: input !== undefined ? new Blob([input]) : "ignore", - stdout: "pipe", - stderr: "pipe", - }); + private async fleetGh(args: string[]): Promise { + let proc; + try { + proc = Bun.spawn([FLEET_BIN, "gh", ...args], { + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + }); + } catch (e) { + throw new GitHubError( + `fleet gh ${args[0]} failed to start: ${e instanceof Error ? e.message : String(e)}`, + ); + } const [out, err, code] = await Promise.all([ new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited, ]); - if (code !== 0) throw new GitHubError(`gh ${args[0]} ${args[1] ?? ""} failed: ${err.trim().slice(0, 200)}`); + if (code !== 0) throw new GitHubError(`fleet gh ${args[0]} failed: ${err.trim().slice(0, 200)}`); return out; } @@ -230,20 +252,19 @@ export class GitHubClient { }); } } catch { - // gh fallback for label creation is best-effort: `gh issue create - // --label` fails on a missing label, so create it there too. + // The verb fallback for label creation is best-effort: issue + // create with a missing label fails, so ensure it there too. try { - await this.gh([ - "label", - "create", - label, + await this.fleetGh([ + "sync-label-ensure", "--repo", repo, + "--label", + label, "--color", def.color, "--description", def.description, - "--force", ]); } catch { /* label may already exist — the create call below will say so */ @@ -296,13 +317,13 @@ export class GitHubClient { // POST may already have created the issue server-side, so a gh // create would file a duplicate tracking issue (#7101). if (e instanceof MalformedCreateBodyError || e instanceof AmbiguousCreateError) throw e; - // Fall through to gh with the app error preserved in the message - // if gh fails too. + // Fall through to the fleet gh verb with the app error + // preserved in the message if the verb fails too. try { return await this.createIssueViaGh(repo, title, body, labels); } catch (ghErr) { throw new GitHubError( - `issue create failed via app (${e instanceof Error ? e.message : String(e)}) and via gh (${ghErr instanceof Error ? ghErr.message : String(ghErr)})`, + `issue create failed via app (${e instanceof Error ? e.message : String(e)}) and via fleet gh (${ghErr instanceof Error ? ghErr.message : String(ghErr)})`, ); } } @@ -316,12 +337,12 @@ export class GitHubClient { body: string, labels: string[], ): Promise<{ number: number; url: string }> { - const args = ["issue", "create", "--repo", repo, "--title", title, "--body", body]; + const args = ["sync-issue-create", "--repo", repo, "--title", title, "--body", body]; for (const l of labels) args.push("--label", l); - const out = await this.gh(args); + const out = await this.fleetGh(args); const url = out.trim().split("\n").pop()!.trim(); const m = /\/issues\/(\d+)$/.exec(url); - if (!m) throw new GitHubError(`gh issue create returned an unparseable URL: ${url.slice(0, 120)}`); + if (!m) throw new GitHubError(`fleet gh sync-issue-create returned an unparseable URL: ${url.slice(0, 120)}`); return { number: Number(m[1]), url }; } @@ -350,12 +371,12 @@ export class GitHubClient { }; } catch (e) { appError = e; - /* fall through to gh, mirroring createIssue */ + /* fall through to the fleet gh verb, mirroring createIssue */ } } try { - const out = await this.gh(["api", `repos/${repo}/issues/${issueNumber}`]); - const endpoint = `gh api repos/${repo}/issues/${issueNumber}`; + const out = await this.fleetGh(["sync-issue-get", "--repo", repo, String(issueNumber)]); + const endpoint = `fleet gh sync-issue-get repos/${repo}/issues/${issueNumber}`; let parsed: unknown; try { parsed = JSON.parse(out); @@ -374,7 +395,7 @@ export class GitHubClient { if (isNotFoundError(msg)) return null; if (appError) { throw new GitHubError( - `issue lookup failed via app (${appError instanceof Error ? appError.message : String(appError)}) and via gh (${msg})`, + `issue lookup failed via app (${appError instanceof Error ? appError.message : String(appError)}) and via fleet gh (${msg})`, ); } throw e; @@ -390,10 +411,16 @@ export class GitHubClient { if (!res.ok) throw new GitHubError(`add labels failed (HTTP ${res.status})`); return; } catch { - /* fall through to gh */ + /* fall through to the fleet gh verb */ } } - await this.gh(["issue", "edit", String(issueNumber), "--repo", repo, ...labels.flatMap((l) => ["--add-label", l])]); + await this.fleetGh([ + "sync-labels-add", + "--repo", + repo, + String(issueNumber), + ...labels.flatMap((l) => ["--label", l]), + ]); } /** @@ -418,17 +445,23 @@ export class GitHubClient { if (!res.ok) throw new GitHubError(`issue close failed (HTTP ${res.status})`); return; } catch { - /* fall through to gh */ + /* fall through to the fleet gh verb */ } } - await this.gh([ - "issue", - "close", - String(issueNumber), + // Through the verb the close speaks the fleet closure taxonomy + // (#9221): not_planned closes as `cancelled`, completed as + // `implemented`, and the close carries the closure reason + // comment + record. GitHub's own state_reason granularity is + // not preserved; every live caller closes with not_planned, to + // compensate a dispatch-created tracking issue whose launch + // failed (launch_failure.ts). + await this.fleetGh([ + "sync-issue-close", "--repo", repo, + String(issueNumber), "--reason", - stateReason === "not_planned" ? "not planned" : "completed", + stateReason === "not_planned" ? "cancelled" : "implemented", ]); } @@ -440,9 +473,9 @@ export class GitHubClient { if (!res.ok) throw new GitHubError(`issue comment failed (HTTP ${res.status})`); return; } catch { - /* fall through to gh */ + /* fall through to the fleet gh verb */ } } - await this.gh(["issue", "comment", String(issueNumber), "--repo", repo, "--body", body]); + await this.fleetGh(["sync-comment", "--repo", repo, "issue", String(issueNumber), "--body", body]); } } diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index 458fe3bb25..e3afaf81dd 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -71,6 +71,11 @@ def _required_home() -> Path: # ~/fleet-brokers/bin tree was retired by the code#5362 cutover # (task 12731). REPO_QUEUE_CMD = HOME_DIR / ".local" / "bin" / "repo-queue" +# The same packaged fleet binary under its own name: this module's +# GitHub reads and agent notes run through its `gh` sync verbs +# (code#10973, step 2.2 of #9016) over the fleet token rotation, +# instead of composing raw `gh` argument lists at each call site. +FLEET_CMD = HOME_DIR / ".local" / "bin" / "fleet" PRIMARY_CLONE = HOME_DIR / "git" / "code" # OpenCode server coordinates: the standing server requires HTTP @@ -1186,33 +1191,61 @@ def _collect_handed_offs(queue: str, want: int) -> Dict[int, Dict]: def _github_issue_labels(repo: str, issue_number: int) -> set: - """Live label names on an issue, read through the gh CLI. + """Live label names on an issue, read through the fleet gh + sync-labels verb (code#10973) over the token rotation. Raises on any failure so the caller can fail closed (#7670).""" result = subprocess.run( [ + str(FLEET_CMD), "gh", - "issue", - "view", - str(issue_number), + "sync-labels", "--repo", repo, - "--json", - "labels", - "--jq", - "[.labels[].name]", + "issue", + str(issue_number), ], capture_output=True, text=True, timeout=15, ) if result.returncode != 0: - raise RuntimeError(f"gh issue view failed: {result.stderr.strip()[:200]}") + raise RuntimeError( + f"fleet gh sync-labels failed: {result.stderr.strip()[:200]}" + ) names = json.loads(result.stdout) if not isinstance(names, list): - raise RuntimeError("gh issue view returned a non-list label set") + raise RuntimeError("fleet gh sync-labels returned a non-list label set") return {str(n) for n in names} +def _post_issue_agent_note(repo, issue_number, note) -> bool: + """Post one agent note on an issue through the fleet gh + sync-comment verb (code#10973). True iff the verb's exit code + confirms the post; any failure (including the verb failing to + run at all) is False - a failed note never undoes the queue + action it records, per the note posters' shared contract.""" + try: + result = subprocess.run( + [ + str(FLEET_CMD), + "gh", + "sync-comment", + "--repo", + str(repo), + "issue", + str(int(str(issue_number).lstrip("#"))), + "--body", + note, + ], + capture_output=True, + text=True, + timeout=15, + ) + except Exception: + return False + return result.returncode == 0 + + def _prompt_safe_packet(packet): """Deep-copy a packet for the execution prompt with any credential-shaped values redacted (#7670): a credential must @@ -1239,7 +1272,7 @@ def _post_launch_agent_note(task_id, session_id, candidate, packet) -> bool: ids - no packet content enters it. A failed note never unbinds or fails the launch (the binding stands; supervision owns the session) - the caller flags the launch entry instead. Returns - True iff the post is confirmed by the gh CLI's exit code.""" + True iff the post is confirmed by the sync verb's exit code.""" _packet = packet if isinstance(packet, dict) else {} repo = _packet.get("repo") or "" issue_no = candidate.get("issue_number") @@ -1259,25 +1292,7 @@ def _post_launch_agent_note(task_id, session_id, candidate, packet) -> bool: f"(step 4e). The session works the task under its bound " f"claim; terminal state is recorded by the worker session." ) - try: - result = subprocess.run( - [ - "gh", - "issue", - "comment", - str(int(str(issue_no).lstrip("#"))), - "--repo", - str(repo), - "--body", - note, - ], - capture_output=True, - text=True, - timeout=15, - ) - except Exception: - return False - return result.returncode == 0 + return _post_issue_agent_note(repo, issue_no, note) HANDBACK_REASON_CLASS = "executor-saturated" @@ -1350,7 +1365,7 @@ def _post_handback_agent_note(task_id, candidate) -> bool: local fire log). Mirrors _post_launch_agent_note's repo/issue resolution and failure contract: a failed note never undoes the park - the caller records it in the hand-back record. - Returns True iff the post is confirmed by the gh CLI's exit + Returns True iff the post is confirmed by the sync verb's exit code.""" packet = ( candidate.get("packet") if isinstance(candidate.get("packet"), dict) else {} @@ -1378,25 +1393,7 @@ def _post_handback_agent_note(task_id, candidate) -> bool: "not a failure: a Claude lane can still claim the task if " "urgent." ) - try: - result = subprocess.run( - [ - "gh", - "issue", - "comment", - str(int(str(issue_no).lstrip("#"))), - "--repo", - str(repo), - "--body", - note, - ], - capture_output=True, - text=True, - timeout=15, - ) - except Exception: - return False - return result.returncode == 0 + return _post_issue_agent_note(repo, issue_no, note) def _post_stuck_holder_agent_note( @@ -1409,7 +1406,7 @@ def _post_stuck_holder_agent_note( _post_handback_agent_note's failure contract: a failed note does not mark the episode escalated, so nudges.py retries the escalation next round. Returns True iff the post is confirmed - by the gh CLI's exit code.""" + by the sync verb's exit code.""" if not repo or not issue_number: return False note = ( @@ -1425,25 +1422,7 @@ def _post_stuck_holder_agent_note( "release it. The babysitter sends no further nudges for " "this stall episode." ) - try: - result = subprocess.run( - [ - "gh", - "issue", - "comment", - str(int(str(issue_number).lstrip("#"))), - "--repo", - str(repo), - "--body", - note, - ], - capture_output=True, - text=True, - timeout=15, - ) - except Exception: - return False - return result.returncode == 0 + return _post_issue_agent_note(repo, issue_number, note) def hand_back_step(mode, candidates, exclude_task_ids=None): diff --git a/pm-stack/opencode-claimant/launch_one.py b/pm-stack/opencode-claimant/launch_one.py index 212cdc46d3..463fd6e0c3 100644 --- a/pm-stack/opencode-claimant/launch_one.py +++ b/pm-stack/opencode-claimant/launch_one.py @@ -272,13 +272,20 @@ def hard_stop_reason(repo, ref): if not ref: return None kind, num = ref - cmd = ( - ["pr", "view", str(num), "--repo", repo, "--json", "labels,state,title"] - if kind == "pr" - else ["issue", "view", str(num), "--repo", repo, "--json", "labels,state,title"] - ) + # The labels/state/title read runs through the fleet gh + # sync-view verb (code#10973) over the token rotation, not a + # raw gh composition. + cmd = [ + str(claimant.FLEET_CMD), + "gh", + "sync-view", + "--repo", + repo, + kind, + str(num), + ] try: - p = subprocess.run(["gh", *cmd], capture_output=True, text=True, timeout=60) + p = subprocess.run(cmd, capture_output=True, text=True, timeout=60) if p.returncode != 0: return f"label-check-failed:{p.stderr.strip()[:160]}" d = json.loads(p.stdout) @@ -390,13 +397,21 @@ def post_agent_note(row, ref, repo, sid): claimant.ensure_state_dir() with open(path, "w") as f: f.write(note_body(row, ref, sid, url)) - ncmd = ( - ["pr", "comment", str(ref[1]), "--repo", repo, "--body-file", str(path)] - if ref[0] == "pr" - else ["issue", "comment", str(ref[1]), "--repo", repo, "--body-file", str(path)] - ) + # The note post runs through the fleet gh sync-comment verb + # (code#10973) over the token rotation, not a raw gh composition. + ncmd = [ + str(claimant.FLEET_CMD), + "gh", + "sync-comment", + "--repo", + repo, + ref[0], + str(ref[1]), + "--body-file", + str(path), + ] try: - p = subprocess.run(["gh", *ncmd], capture_output=True, text=True, timeout=60) + p = subprocess.run(ncmd, capture_output=True, text=True, timeout=60) return p.returncode == 0, ( None if p.returncode == 0 else p.stderr.strip()[:300] ) diff --git a/pm-stack/opencode-claimant/test_claimant.py b/pm-stack/opencode-claimant/test_claimant.py index 6bd6f334d6..e951b77bfc 100644 --- a/pm-stack/opencode-claimant/test_claimant.py +++ b/pm-stack/opencode-claimant/test_claimant.py @@ -1334,10 +1334,10 @@ def test_launch_posts_agent_note_and_inlines_runbook(self): def fake_run(cmd, **kwargs): argv = [str(part) for part in cmd] - if argv[0] == "gh" and "view" in argv: + if argv[1:3] == ["gh", "sync-labels"]: # The step-4a2 held-label read: no labels at all. return Result(0, "[]") - if argv[0] == "gh": + if argv[1:3] == ["gh", "sync-comment"]: notes.append(cmd) return Result(0, "") return base_fake(cmd, **kwargs) @@ -1407,7 +1407,7 @@ def fake_run(cmd, **kwargs): if "repo-queue" in argv[0] and "park" in argv: calls["park"].append(argv) return Result(park_rc, "{}") - if argv[0] == "gh": + if argv[1:3] == ["gh", "sync-comment"]: calls["gh"].append(argv) return Result(0, "") calls["other"].append(argv) @@ -1492,7 +1492,18 @@ def test_live_saturated_fire_hands_back_next_candidate(self): # One hand-back note on the candidate's issue. self.assertEqual(len(calls["gh"]), 1) gh_argv = calls["gh"][0] - self.assertEqual(gh_argv[:4], ["gh", "issue", "comment", "1187"]) + self.assertEqual( + gh_argv[:7], + [ + str(claimant.FLEET_CMD), + "gh", + "sync-comment", + "--repo", + "developing-today/code", + "issue", + "1187", + ], + ) self.assertEqual(gh_argv[gh_argv.index("--repo") + 1], "developing-today/code") body = gh_argv[gh_argv.index("--body") + 1] self.assertIn("agent-note:v1", body)