From 9a5e70ed3272ced86a778772470c7416b42fd10d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 4 Dec 2026 14:55:27 -0500 Subject: [PATCH 1/5] Own red CI never handed off; every agent reads the whole installation A check red on the pull request and green on the base first gets the mode diagnosis: files the pull request changes are compared with the merge base, and a mode CoderHelm's commits dropped is put back in one commit with no model round; what can't be put back yet is CoderHelm's own problem, alerted and retried. restore_file restores the mode with the bytes, set_mode sets a file's executable bit (refusing links and submodules), and a sandbox chmod says it never reaches the commit. The repair sweep compares with the base, reads failed runs first and resumes a run that ended on red CI. Every worker loop with tools gets list_repos, read_repo_file and search_repo over the team's installation, with the prompt; Chat's prompt says the same. Text claiming CoderHelm can't see or confirm something is rejected unless a tool returned a refusal it names. --- docs/incidents/xo_own_modes_never_red_ci.md | 9 + .../xp_answers_read_the_other_repo.md | 14 + services/common/src/coder_shell.rs | 10 + services/common/src/lib.rs | 1 + services/common/src/rendered.rs | 21 +- services/common/src/reply_compose.rs | 4 + services/common/src/repo_reach.rs | 468 ++++++++++++++++++ services/common/src/repo_read.rs | 36 ++ services/common/src/tool_registry.rs | 6 + services/gateway/src/routes/brain.rs | 19 +- services/gateway/src/routes/chat_agent.rs | 28 ++ services/worker/src/agent/mod.rs | 1 + services/worker/src/agent/provider.rs | 89 +++- services/worker/src/agent/reach.rs | 248 ++++++++++ services/worker/src/clients/git_mode.rs | 99 ++++ services/worker/src/clients/github.rs | 106 ++++ services/worker/src/passes/feedback.rs | 45 +- services/worker/src/passes/implement.rs | 47 +- .../incidents/xo_own_modes_never_red_ci.rs | 357 +++++++++++++ .../xp_answers_read_the_other_repo.rs | 336 +++++++++++++ services/worker/src/passes/mode_repair.rs | 408 +++++++++++++-- services/worker/src/passes/resume.rs | 143 ++++++ 22 files changed, 2453 insertions(+), 42 deletions(-) create mode 100644 docs/incidents/xo_own_modes_never_red_ci.md create mode 100644 docs/incidents/xp_answers_read_the_other_repo.md create mode 100644 services/common/src/repo_reach.rs create mode 100644 services/worker/src/agent/reach.rs create mode 100644 services/worker/src/passes/incidents/xo_own_modes_never_red_ci.rs create mode 100644 services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs diff --git a/docs/incidents/xo_own_modes_never_red_ci.md b/docs/incidents/xo_own_modes_never_red_ci.md new file mode 100644 index 000000000..890034177 --- /dev/null +++ b/docs/incidents/xo_own_modes_never_red_ci.md @@ -0,0 +1,9 @@ +# xo. `xo_own_modes_never_red_ci` + +**What happened:** A front-end fix's pull request also listed three shell scripts of the repository's CI as files it changed: a cleanup script, a stub command its tests put on the path, and the test that runs it. Merging the base into the branch had dropped their executable bit (before `xl`). The pull request's script tests failed while the base stayed green on them. The fix rounds ran `chmod +x` in the sandbox, called `restore_file` on the scripts several times, and deleted and wrote them again in a batch write. None of it reached the mode. After five rounds the run ended failed on red CI and was handed to a person, for a cause CoderHelm made itself. + +**Why:** `restore_file` took the bytes from the ref and the mode from the branch, which had already lost it. No tool set a mode. Nothing compared the pull request's modes with the base when its checks were red and the base's green. The repair sweep of `xl` compared each CoderHelm commit with its parent only, where a delete followed by a write shows no drop. It took its runs from the description catch-up's picks, which skip runs in flight and every run whose description was already rebuilt, and it never set a failed run going again. + +**The guarantee:** A check red on the pull request and green on the base first gets the mode diagnosis. Every file the pull request changes is compared with the merge base, and an executable, symbolic link or submodule that CoderHelm's commits turned into a plain file is put back in one commit, with no model round, and CI decides again. A mode CoderHelm dropped that it can't put back yet is its own problem: an internal alert, the run page's line, and a retry. It is never `failed` on red CI and never a person's to-do. A path a person's commit changed is theirs and is left. `restore_file` restores the mode from the same ref as the bytes. `set_mode` sets a file's executable bit as a commit, or puts back the base's mode, and refuses symbolic links and submodules. A `chmod` in the sandbox says it never reaches the commit and names `set_mode`. The repair sweep compares each pull request with its base too, reads runs of every status a pull request can still be open under (failed runs first, runs in flight included), and resumes a run that ended on red CI once its modes are back. + +**Where it's enforced:** `clients::git_mode::{mode_move, against_base}`, `GitHubClient::{set_mode, merge_base_and_files}`, `mode_repair::{base_plan, against_base, on_red, write_restore, picks, reads, set_mode_tool, set_mode_call, restore_mode, sweep, repair_one}`, `resume::{mode_cause, hand_off_red_ci, resume_after_mode_repair}`, the `restore_file` and `set_mode` arms of the coder's and the feedback round's executors, and `common::coder_shell::CHMOD`. diff --git a/docs/incidents/xp_answers_read_the_other_repo.md b/docs/incidents/xp_answers_read_the_other_repo.md new file mode 100644 index 000000000..19b2aae43 --- /dev/null +++ b/docs/incidents/xp_answers_read_the_other_repo.md @@ -0,0 +1,14 @@ +# xp. `xp_answers_read_the_other_repo` + +**What happened:** A person asked on an API repository's pull request why a card read "Ages 1 - 4 years" when the data said 3 months to 4 years. CoderHelm's reply named the website's age formatter as the cause and said it couldn't open that formatter from this repository, so it hadn't confirmed the rounding. The website was another repository of the same team, and CoderHelm's GitHub app could read it. + +**Why:** The round that answered had only the tools of the repository it worked in. Nothing told the model the installation's other repositories were readable, and nothing checked an answer that said it couldn't see something it never tried to read. + +**The guarantee (invariants, enforced in code):** + +- Every worker model loop that is offered tools (the coder, every fix round, the reviewer, ticket replies, triage, skills) is also offered `list_repos`, `read_repo_file` and `search_repo`, read only, over every repository of the team's GitHub installation. They are added in the one place every worker loop starts, and a source scan fails on a worker loop that goes around it. Chat and team agents read the same repositories through their code tools. +- Every such system prompt says the team's whole installation is readable, and to look before answering. +- Text a person reads that claims CoderHelm can't see, open, access, read or confirm something is rejected before it is posted, unless a tool call in that same turn returned a refusal; then the line must name the repository or path and the refusal. A loop's answer that fails is sent back once to look with the tools, and what still fails is taken out. The person-text check and the reply composer hold the same rule. +- A source scan fails on any prompt that tells the model it is limited to one repository. + +**Where it's enforced:** `common::repo_reach::{defs, call, prompt_for, claim, allowed, strip, look_first, refusal_in}`, `common::repo_read::GitHubHost::installation_repos`, `common::rendered::{person_text, person_text_after}`, `common::reply_compose::finish`, the worker's `agent::reach::{offer, prompt, Exec, access}` in `agent::provider::converse_as`, Chat's `brain::system_prompt` and `chat_agent::run`, and `tool_registry::BUILTIN`. diff --git a/services/common/src/coder_shell.rs b/services/common/src/coder_shell.rs index 0a6af1009..041054918 100644 --- a/services/common/src/coder_shell.rs +++ b/services/common/src/coder_shell.rs @@ -273,6 +273,13 @@ pub const WRITES: &str = "Commands don't change files here: the sandbox works on a file, write_file to create or replace one, batch_write to write several or delete one \ (`action: delete`), restore_file to put one back as it was."; +/// The message for `chmod`: a mode set in the sandbox's copy never reaches +/// the branch. +pub const CHMOD: &str = "chmod doesn't reach the commit: the sandbox works on a copy and \ + nothing it changes is kept, modes included. Set a file's mode on the branch with set_mode \ + (`executable: true`), or put back the mode it has on the base branch with set_mode and no \ + `executable`; restore_file brings a file's mode back with its content."; + /// The message for git commands that change the branch or reach the remote. pub const GIT: &str = "git doesn't run here: every write_file, edit_file and batch_write is \ committed to the branch, and CoderHelm pushes and opens the pull request itself. See the \ @@ -401,6 +408,9 @@ fn refusal(prog: &str, args: &[String], redirects: bool) -> Option<&'static str> if SECRET_READERS.contains(&prog) { return Some(SECRETS); } + if prog == "chmod" { + return Some(CHMOD); + } if FILE_WRITERS.contains(&prog) { return Some(WRITES); } diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index 09d6d4b3b..90a938e7d 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -215,6 +215,7 @@ pub mod embed; /// brain chat and the team's agents search. pub mod knowledge; // Reading the team's repositories for Chat (overview, files, search). +pub mod repo_reach; pub mod repo_read; // The test that every model call site is a metered helper pub mod ci_cover; diff --git a/services/common/src/rendered.rs b/services/common/src/rendered.rs index 6b00fa7a3..608d57a87 100644 --- a/services/common/src/rendered.rs +++ b/services/common/src/rendered.rs @@ -175,11 +175,26 @@ static RUN_ON: LazyLock = LazyLock::new(|| Regex::new(r"[^:\n]{1,80}: [^:\n]{1,200}: [^:\n]{1,200}: ").expect("regex")); /// What in `text` a person shouldn't be shown, or `None`: an empty slot -/// ([`empty_slot`]), a hand-off of work CoderHelm does itself, a template -/// plural ("file(s)"), a bracketed internal key, or clauses run together -/// with colons. Code spans are taken out first, so a command or a name in +/// ([`empty_slot`]), a claim that CoderHelm can't see, open, access or +/// confirm something (`repo_reach::claim`: every repository of the team's +/// installation is readable, so with no refusal from a tool the claim is a +/// guess), a hand-off of work CoderHelm does itself, a template plural +/// ("file(s)"), a bracketed internal key, or clauses run together with +/// colons. Code spans are taken out first, so a command or a name in /// backticks never trips it. pub fn person_text(text: &str) -> Option { + person_text_after(text, &[]) +} + +/// [`person_text`] for text written in a turn whose tool calls returned +/// `refusals`: a line saying a read was refused stands when it names that +/// repository or path and the refusal (`repo_reach::allowed`). +pub fn person_text_after(text: &str, refusals: &[crate::repo_reach::Refusal]) -> Option { + if let Err(line) = crate::repo_reach::allowed(text, refusals) { + return Some(format!( + "a claim CoderHelm can't see or confirm something, with no refusal to show for it: {line}" + )); + } if let Some(gap) = empty_slot(text) { return Some(gap); } diff --git a/services/common/src/reply_compose.rs b/services/common/src/reply_compose.rs index 32e297b67..30a18daa8 100644 --- a/services/common/src/reply_compose.rs +++ b/services/common/src/reply_compose.rs @@ -920,6 +920,10 @@ pub fn finish( markdown: bool, ) -> Option<(String, Vec<(String, String)>)> { let text = cv::no_arrows(&without_greeting(raw, to)); + // A sentence saying CoderHelm can't see or confirm something is never + // posted: the composer has no refusal from a tool to show for it + // (`repo_reach`). + let text = crate::repo_reach::strip(&text, &[]); let (kept, dropped) = check(&text, g); let kept = with_commit_link(&kept, g.facts, markdown); let kept = cv::cut_words(&kept, MAX_REPLY_CHARS); diff --git a/services/common/src/repo_reach.rs b/services/common/src/repo_reach.rs new file mode 100644 index 000000000..34d22fc76 --- /dev/null +++ b/services/common/src/repo_reach.rs @@ -0,0 +1,468 @@ +//! Every agent reads every repository of the team's installation, and no +//! text CoderHelm posts says it can't. +//! +//! A person asked on a pull request why a card read "Ages 1 - 4 years" for +//! data of 3 months to 4 years. The answer named the website's age +//! formatter as the cause and said it couldn't open that formatter from +//! this repository, so the rounding wasn't confirmed. The website was +//! another repository the same team had connected, and CoderHelm's GitHub +//! app could read it. The round that answered had only the tools of the +//! repository it worked in. +//! +//! Two invariants, enforced in code: +//! +//! - **Every agent has the installation.** [`defs`] are the read-only +//! cross-repository tools ([`LIST_REPOS`], [`READ_REPO_FILE`], +//! [`SEARCH_REPO`]) over every repository the team's GitHub installation +//! can read, and [`prompt`] tells the model so. The worker offers them in +//! its one model loop (`agent::provider`), so the coder, every fix round, +//! the reviewer, ticket replies and triage all have them; Chat and team +//! agents read the same repositories through their own code tools. +//! - **No claim of blindness without a refusal.** Person-facing text that +//! says CoderHelm can't see, open, access, read or confirm something +//! ([`claim`]) is rejected ([`allowed`]) unless a tool call in the same +//! turn returned a refusal ([`Refusal`]), and then the sentence must name +//! that repository or path and the refusal. A loop's answer that fails is +//! sent back once to look first, and what still fails is taken out +//! ([`strip`]) before anyone reads it. + +use std::sync::LazyLock; + +use regex::Regex; +use serde_json::{json, Value}; + +use crate::repo_read::{CodeReader, ReadError}; + +/// Lists the installation's repositories. +pub const LIST_REPOS: &str = "list_repos"; +/// Reads a file of any of them, by lines. +pub const READ_REPO_FILE: &str = "read_repo_file"; +/// Searches code in one or all of them. +pub const SEARCH_REPO: &str = "search_repo"; +/// The cross-repository tools, in the order they are offered. +pub const TOOLS: [&str; 3] = [LIST_REPOS, READ_REPO_FILE, SEARCH_REPO]; + +/// Most repositories listed for one loop. +pub const MAX_REPOS: usize = 500; +/// Most search hits returned for one call. +const MAX_HITS: usize = 20; + +/// The words every agent's system prompt carries, naming its own tools to +/// list repositories, read a file and search code. +pub fn prompt_for(list: &str, read: &str, search: &str) -> String { + format!( + "Every repository in the team's GitHub installation is readable to you, not only the \ + one this work is in: list them with {list}, read any file with {read}, and search \ + code with {search}. When an answer or a cause lies in another repository (a website, \ + an app, a shared library), read it there and cite the exact file and line. Look \ + before answering: never write that you can't open, see, access or confirm something \ + you haven't tried to read. Only when a read was refused, name the repository or path \ + and the refusal it returned." + ) +} + +/// [`prompt_for`] with this module's tools. +pub fn prompt() -> String { + prompt_for(LIST_REPOS, READ_REPO_FILE, SEARCH_REPO) +} + +/// True for one of the cross-repository tools. +pub fn is_reach_tool(name: &str) -> bool { + TOOLS.contains(&name) +} + +/// The tools' definitions (`name`, `description`, `input_schema`). +pub fn defs() -> Vec { + let repo = json!({ + "type": "string", + "description": "The repository, as owner/name or its name alone (list_repos names them)" + }); + vec![ + json!({ + "name": LIST_REPOS, + "description": "List every repository the team's GitHub installation can read, with its default branch and description. Use it to find where code lives when it isn't in the repository this work is in.", + "input_schema": {"type": "object", "properties": {}} + }), + json!({ + "name": READ_REPO_FILE, + "description": "Read a file of any repository in the team's installation (read only), by line range, at its default branch. The reply numbers the lines and gives the link to cite them.", + "input_schema": {"type": "object", "properties": { + "repo": repo, + "path": {"type": "string", "description": "The file's path in that repository"}, + "start_line": {"type": "integer", "description": "First line (1-based); leave out for the top"}, + "end_line": {"type": "integer", "description": "Last line; leave out for a page"} + }, "required": ["repo", "path"]} + }), + json!({ + "name": SEARCH_REPO, + "description": "Search code in one repository of the team's installation, or in all of them when `repo` is left out (read only). Returns files with matching lines.", + "input_schema": {"type": "object", "properties": { + "query": {"type": "string", "description": "Words, a name or a string to find"}, + "repo": repo + }, "required": ["query"]} + }), + ] +} + +/// A read a tool call was refused: the repository, the path (empty for a +/// listing or a search), the status and the host's words. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refusal { + pub repo: String, + pub path: String, + pub status: u16, + pub said: String, +} + +/// What one cross-repository call came to: the model's reply, and the +/// refusal when the read was refused. +#[derive(Debug, Clone, PartialEq)] +pub struct Outcome { + pub text: String, + pub refusal: Option, +} + +/// The status a read error stands for: 404 for what isn't there, the +/// host's own status when it named one, 503 otherwise. +pub fn status_of(e: &ReadError) -> u16 { + static STATUS: LazyLock = + LazyLock::new(|| Regex::new(r"status (\d{3})").expect("regex")); + match e { + ReadError::NotFound(_) => 404, + ReadError::Unavailable(m) => STATUS + .captures(m) + .and_then(|c| c[1].parse().ok()) + .unwrap_or(503), + } +} + +fn refused(repo: &str, path: &str, e: &ReadError) -> Outcome { + let status = status_of(e); + Outcome { + text: format!("Refused ({status}): {e}"), + refusal: Some(Refusal { + repo: repo.to_string(), + path: path.to_string(), + status, + said: e.to_string(), + }), + } +} + +/// The outcome of a call when the team has no installation to read: a +/// refusal, said as it is. +pub fn without_access(name: &str, why: &str) -> Outcome { + Outcome { + text: format!("Refused (403): {why}"), + refusal: Some(Refusal { + repo: String::new(), + path: String::new(), + status: 403, + said: format!("{name}: {why}"), + }), + } +} + +fn line_of(input: &Value, key: &str) -> Option { + input[key] + .as_u64() + .or_else(|| input[key].as_str().and_then(|s| s.trim().parse().ok())) + .map(|n| n as usize) + .filter(|n| *n > 0) +} + +/// Runs one cross-repository call over `reader`. +pub async fn call(reader: &CodeReader<'_>, name: &str, input: &Value) -> Outcome { + let repo = input["repo"].as_str().unwrap_or("").trim(); + match name { + LIST_REPOS => { + let mut text = format!( + "{} repositories in the team's installation:\n", + reader.repos().len() + ); + for r in reader.repos() { + text.push_str(&format!("- {} (default branch {})", r.name, r.branch)); + if let Some(role) = &r.role { + text.push_str(&format!(", {role}")); + } + if let Some(d) = &r.description { + text.push_str(&format!(": {d}")); + } + text.push('\n'); + } + Outcome { + text, + refusal: None, + } + } + READ_REPO_FILE => { + let path = input["path"].as_str().unwrap_or("").trim(); + match reader + .read( + repo, + path, + line_of(input, "start_line"), + line_of(input, "end_line"), + ) + .await + { + Ok(slice) => Outcome { + text: format!( + "{}\nCite as {}/{}:{}-{} ({})", + slice.numbered(), + slice.repo, + slice.path, + slice.start, + slice.end, + slice.url() + ), + refusal: None, + }, + Err(e) => refused(repo, path, &e), + } + } + SEARCH_REPO => { + let query = input["query"].as_str().unwrap_or(""); + let repos: Vec = if repo.is_empty() { + Vec::new() + } else { + vec![repo.to_string()] + }; + match reader.search(&repos, query).await { + Ok(hits) if hits.is_empty() => Outcome { + text: format!("Nothing matched `{query}`."), + refusal: None, + }, + Ok(hits) => { + let mut text = String::new(); + for h in hits.iter().take(MAX_HITS) { + text.push_str(&format!("{} {}\n", h.repo, h.path)); + for f in h.fragments.iter().take(3) { + text.push_str(&format!(" {}\n", f.trim())); + } + } + Outcome { + text, + refusal: None, + } + } + Err(e) => refused(repo, "", &e), + } + } + _ => Outcome { + text: format!("{name} isn't a cross-repository tool."), + refusal: None, + }, + } +} + +/// A refusal another read tool's error stands for: a 401, 403, 404 or 410 +/// it names, with the repository and path of its call. +pub fn refusal_in(name: &str, input: &Value, error: &str) -> Option { + static CODE: LazyLock = + LazyLock::new(|| Regex::new(r"\b(401|403|404|410)\b").expect("regex")); + static GONE: LazyLock = LazyLock::new(|| { + Regex::new(r"(?i)\b(?:wasn't found|was not found|not found|there is no)\b").expect("regex") + }); + let status = match CODE.captures(error) { + Some(c) => c[1].parse().ok()?, + None if GONE.is_match(error) => 404, + None => return None, + }; + Some(Refusal { + repo: input["repo"].as_str().unwrap_or_default().to_string(), + path: input["path"].as_str().unwrap_or_default().to_string(), + status, + said: format!("{name}: {}", crate::truncate_str(error, 300)), + }) +} + +// ── The guard on what people read ────────────────────────────────────────── + +/// A sentence saying CoderHelm can't see, open, access or read something, +/// or couldn't confirm it because of where it lives. +static CLAIM: LazyLock = LazyLock::new(|| { + let not = r"(?:can['’]?t|cannot|can not|couldn['’]?t|could not|am unable to|was unable to|unable to|am not able to|wasn['’]?t able to|not able to|have no way to)"; + let lack = r"(?:don['’]?t|do not|doesn['’]?t|does not|didn['’]?t|did not)\s+have"; + let who = r"(?:I|we|CoderHelm|the agent)"; + let alternatives = [ + format!(r"\b{who}\s+{not}\s+(?:\w+\s+){{0,2}}?(?:open|see|access|read|view|reach|inspect|look at|look into|check|confirm|verify)\b"), + format!(r"\b{who}\s+{lack}\s+(?:\w+\s+){{0,2}}?(?:access|visibility|permission)\b"), + r"\bno access to\b".to_string(), + r"\b(?:lives?|sits?)\s+outside\s+(?:of\s+)?(?:this|the current)\s+(?:repo|repository)\b".to_string(), + format!(r"\boutside\s+(?:of\s+)?(?:this|the current)\s+(?:repo|repository),?\s+so\s+{who}\b"), + r"\b(?:couldn['’]?t|could not|can['’]?t|cannot|haven['’]?t|have not)\s+(?:\w+\s+){0,2}?(?:confirm|verify)(?:ed)?\b[^.\n]*\bbecause\b".to_string(), + format!(r"\bso\s+{who}\s+(?:haven['’]?t|have not|couldn['’]?t|could not)\s+(?:confirmed|verified|confirm|verify)\b"), + ]; + Regex::new(&format!("(?i){}", alternatives.join("|"))).expect("regex") +}); + +/// Words that name a refusal in a sentence. +const REFUSAL_WORDS: &[&str] = &[ + "not found", + "forbidden", + "refused", + "denied", + "wasn't found", + "was not found", +]; + +/// The first sentence of `text` that claims CoderHelm can't see something, +/// or `None`. +pub fn claim(text: &str) -> Option { + sentences(text) + .into_iter() + .find(|s| CLAIM.is_match(s)) + .map(|s| s.trim().to_string()) +} + +/// Whether `sentence` names one of `refusals` the way an honest line does: +/// the repository (its full or short name) or the path, and the refusal +/// (its status, or a word for it). +fn names_refusal(sentence: &str, refusals: &[Refusal]) -> bool { + let low = sentence.to_lowercase(); + refusals.iter().any(|r| { + let short = r.repo.rsplit('/').next().unwrap_or(&r.repo); + let place = (!r.path.is_empty() && low.contains(&r.path.to_lowercase())) + || (!r.repo.is_empty() && low.contains(&r.repo.to_lowercase())) + || (short.len() > 2 && low.contains(&short.to_lowercase())); + let how = + low.contains(&r.status.to_string()) || REFUSAL_WORDS.iter().any(|w| low.contains(w)); + place && how + }) +} + +/// `Ok` when every claim in `text` of not seeing something is backed by a +/// refusal a tool returned in the same turn (`refusals`) and names it; +/// `Err` with the first sentence that isn't. +pub fn allowed(text: &str, refusals: &[Refusal]) -> Result<(), String> { + for s in sentences(text) { + if CLAIM.is_match(&s) && !names_refusal(&s, refusals) { + return Err(s.trim().to_string()); + } + } + Ok(()) +} + +/// `text` with every sentence [`allowed`] refuses taken out. +pub fn strip(text: &str, refusals: &[Refusal]) -> String { + let mut out = Vec::new(); + for line in text.lines() { + if !CLAIM.is_match(line) { + out.push(line.to_string()); + continue; + } + let kept: Vec = sentences(line) + .into_iter() + .filter(|s| !CLAIM.is_match(s) || names_refusal(s, refusals)) + .map(|s| s.trim().to_string()) + .collect(); + let kept = kept.join(" "); + if !kept.trim().is_empty() { + out.push(kept); + } + } + out.join("\n") +} + +/// What a loop whose answer claimed blindness is told, once, before its +/// answer is taken. +pub fn look_first(sentence: &str) -> String { + format!( + "Your answer says: \"{sentence}\". Nothing was refused to you. Every repository in the \ + team's installation is readable: find the code with list_repos or search_repo, read it \ + with read_repo_file, and answer with the exact file and line. If a read is refused, say \ + which repository or path and the refusal it returned. Then give your whole answer again." + ) +} + +/// The sentences of `text`, each with its closing mark: cut after `.`, +/// `!` or `?` followed by a space, and at each line break. +fn sentences(text: &str) -> Vec { + let mut out = Vec::new(); + for line in text.lines() { + let mut cur = String::new(); + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + cur.push(c); + if matches!(c, '.' | '!' | '?') && chars.peek().is_some_and(|n| n.is_whitespace()) { + out.push(std::mem::take(&mut cur)); + } + } + if !cur.trim().is_empty() { + out.push(cur); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn refusal(repo: &str, path: &str, status: u16) -> Refusal { + Refusal { + repo: repo.into(), + path: path.into(), + status, + said: "x".into(), + } + } + + #[test] + fn claims_of_not_seeing_are_found() { + for t in [ + "The 2 comes from the storefront's label helper. I can't open that helper from this repo, so I haven't confirmed the rounding.", + "CoderHelm doesn't have access to the billing service.", + "I don't have access to that repository.", + "The helper lives outside this repo.", + "I couldn't confirm it because the code is in another repository.", + "We cannot see the mobile app's code.", + ] { + assert!(claim(t).is_some(), "{t}"); + assert!(allowed(t, &[]).is_err(), "{t}"); + } + } + + #[test] + fn plain_text_is_not_a_claim() { + for t in [ + "The test can't reach the database without the fixture.", + "Users cannot open the page before signing in.", + "Read `src/labels.ts` line 12: the helper rounds months down to years.", + "This change is outside the scope of the ticket.", + "The cause is outside this repository: the queue's timeout is set in the account.", + "`deploy` waits on a change outside this repository.", + ] { + assert_eq!(claim(t), None, "{t}"); + } + } + + #[test] + fn a_real_refusal_named_lets_the_line_through() { + let r = [refusal("acme/storefront", "src/labels.ts", 404)]; + let honest = + "I couldn't read `src/labels.ts` in acme/storefront: GitHub answered 404 not found."; + assert_eq!(allowed(honest, &r), Ok(())); + // The same refusal, not named: still a guess. + let vague = "I can't open that helper from this repo."; + assert!(allowed(vague, &r).is_err()); + assert_eq!( + strip(&format!("The age is rounded. {vague}"), &r), + "The age is rounded." + ); + assert_eq!(strip(honest, &r), honest); + } + + #[test] + fn refusal_statuses_are_read() { + assert_eq!(status_of(&ReadError::NotFound("x".into())), 404); + assert_eq!( + status_of(&ReadError::Unavailable( + "GitHub didn't let CoderHelm read acme/web (status 403).".into() + )), + 403 + ); + assert_eq!(status_of(&ReadError::Unavailable("down".into())), 503); + } +} diff --git a/services/common/src/repo_read.rs b/services/common/src/repo_read.rs index 137782f95..84793a758 100644 --- a/services/common/src/repo_read.rs +++ b/services/common/src/repo_read.rs @@ -168,6 +168,42 @@ impl GitHubHost<'_> { r } + /// Every repository the installation can read (its default branch with + /// each), at most `max`: what an agent's cross-repository tools read + /// (`repo_reach`). + pub async fn installation_repos(&self, max: usize) -> Result, ReadError> { + let mut out = Vec::new(); + for page in 1..=max.div_ceil(100).max(1) { + let url = format!("{GITHUB_API}/installation/repositories?per_page=100&page={page}"); + let (status, body) = self + .send(self.get(&url, "application/vnd.github+json", Limit::Mcp)) + .await?; + if !(200..300).contains(&status) { + return Err(github_status(status, "the installation's repositories")); + } + let v: Value = serde_json::from_slice(&body).map_err(|e| { + ReadError::Unavailable(format!("GitHub's list of repositories didn't read: {e}")) + })?; + let rows = v["repositories"].as_array().cloned().unwrap_or_default(); + for r in &rows { + if let Some(full) = r["full_name"].as_str() { + let mut info = + RepoInfo::new(full, r["default_branch"].as_str().unwrap_or("main")); + info.description = r["description"] + .as_str() + .filter(|d| !d.trim().is_empty()) + .map(str::to_string); + out.push(info); + } + } + if rows.len() < 100 || out.len() >= max { + break; + } + } + out.truncate(max); + Ok(out) + } + async fn send(&self, req: HttpRequest) -> Result<(u16, Vec), ReadError> { let r = self .http diff --git a/services/common/src/tool_registry.rs b/services/common/src/tool_registry.rs index f5672fdfa..b3f856777 100644 --- a/services/common/src/tool_registry.rs +++ b/services/common/src/tool_registry.rs @@ -63,6 +63,11 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("github__read_file", Risk::Read), ("github__search_code", Risk::Read), ("github__list_directory", Risk::Read), + // Every repository of the team's installation, read only, offered to + // every agent (`common::repo_reach`). + ("list_repos", Risk::Read), + ("read_repo_file", Risk::Read), + ("search_repo", Risk::Read), ("graph_definition", Risk::Read), ("graph_callers", Risk::Read), ("graph_impact", Risk::Read), @@ -130,6 +135,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("edit_file", Risk::Write), ("batch_write", Risk::Write), ("restore_file", Risk::Write), + ("set_mode", Risk::Write), ("run_codegen", Risk::Write), ("run_checks", Risk::Write), ("reproduce_on_base", Risk::Write), diff --git a/services/gateway/src/routes/brain.rs b/services/gateway/src/routes/brain.rs index 21a8d3029..a18312a4b 100644 --- a/services/gateway/src/routes/brain.rs +++ b/services/gateway/src/routes/brain.rs @@ -1701,6 +1701,13 @@ How to write: - Name real files and functions in backticks, like `src/app/page.tsx`. Quote code only when it helps: a short fenced block with its language and the file's path as its title, like ```ts title="src/app/page.tsx" - Write for the person asking, in plain words; explain a technical term in a few words the first time."#; +/// What Chat's prompt says when GitHub gave CoderHelm no token for the +/// team: the one case its answer may say it can't read the code, since the +/// refusal is GitHub's (`chat_agent::run` holds every other answer to +/// `common::repo_reach::allowed`). +pub const NO_CODE: &str = + "CoderHelm can't read these repositories right now (GitHub didn't give it access)."; + /// The system prompt: how to work, and the repositories this question may /// read (with what each is for). pub fn system_prompt(repos: &[RepoInfo], can_read_code: bool) -> String { @@ -1720,9 +1727,19 @@ pub fn system_prompt(repos: &[RepoInfo], can_read_code: bool) -> String { s.push_str(&format!(": {}", common::truncate_str(d, 200))); } } + if can_read_code { + s.push_str("\n\n"); + s.push_str(&common::repo_reach::prompt_for( + super::chat_code::LIST_REPOS, + super::chat_code::READ_FILE, + super::chat_code::SEARCH_CODE, + )); + } if !can_read_code { + s.push_str("\n\n"); + s.push_str(NO_CODE); s.push_str( - "\n\nCoderHelm can't read these repositories right now (GitHub didn't give it access). \ + " \ If the question needs the code, say that plainly and that an admin can check the GitHub \ connection in Settings; don't ask the person to open or paste files.", ); diff --git a/services/gateway/src/routes/chat_agent.rs b/services/gateway/src/routes/chat_agent.rs index 752d40451..a27002a5c 100644 --- a/services/gateway/src/routes/chat_agent.rs +++ b/services/gateway/src/routes/chat_agent.rs @@ -396,6 +396,18 @@ pub async fn run( let mut last_text = String::new(); let mut retries = 0; let has_tools = !tools.defs().is_empty(); + // Reads a lookup was refused, for the guard on the answer: a claim the + // code can't be read stands only beside one of them (`repo_reach`). + // With no GitHub access at all the prompt says so, and so may Chat. + let mut refusals: Vec = Vec::new(); + let blind = system.contains(super::brain::NO_CODE); + let guarded = |text: &str, refusals: &[common::repo_reach::Refusal]| { + if blind { + text.to_string() + } else { + common::repo_reach::strip(text, refusals) + } + }; for turn in 0..limits.turns { let elapsed = started.elapsed(); @@ -449,6 +461,7 @@ pub async fn run( } else { last_text.clone() }; + let text = guarded(&text, &refusals); sink.send("text_reset", json!({})).await; sink.send("text_delta", json!({ "text": text })).await; return Ok(Answered { @@ -501,6 +514,17 @@ pub async fn run( sink.send("text_reset", json!({})).await; continue; } + // An answer that says it can't see something it never tried to + // read looks first. + if has_tools && !blind && retries < limits.retries && !must_answer { + if let Err(sentence) = common::repo_reach::allowed(&text, &refusals) { + retries += 1; + info!("Chat: the answer claimed it couldn't see something; it looks first"); + messages.push(json!({ "role": "user", "content": [{"type": "text", "text": common::repo_reach::look_first(&sentence)}] })); + sink.send("text_reset", json!({})).await; + continue; + } + } // An answer. Check it doesn't hand back work the tools can do. if has_tools && retries < limits.retries && !must_answer && !text.trim().is_empty() { // In code first; the model's check only when that passes; @@ -607,6 +631,9 @@ pub async fn run( if !is_error && was_cut(&text) { cut.push((name.to_string(), label.clone())); } + if is_error { + refusals.extend(common::repo_reach::refusal_in(name, input, &text)); + } // What this call registered, so the answer's citations show as // it streams. let found: Vec<_> = (before + 1..=reg.len()) @@ -641,6 +668,7 @@ pub async fn run( // The next turn's text replaces what was said before the tools. sink.send("text_reset", json!({})).await; } + let last_text = guarded(&last_text, &refusals); Ok(Answered { fin: finalize_reply(&last_text, reg, uncited_ok), used, diff --git a/services/worker/src/agent/mod.rs b/services/worker/src/agent/mod.rs index e109f51c5..29fddc4c9 100644 --- a/services/worker/src/agent/mod.rs +++ b/services/worker/src/agent/mod.rs @@ -3,5 +3,6 @@ pub mod llm; pub mod mcp; pub mod policy; pub mod provider; +pub mod reach; pub mod run_log; pub mod tool_outcome; diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 4399f1ce7..6af1b09eb 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -339,6 +339,21 @@ pub async fn converse_document( .await } +/// The turns a loop gets to look before it answers again, when its answer +/// claimed it couldn't see something. +const LOOK_FIRST_TURNS: usize = 12; + +fn copy(tools: &[ToolDefinition]) -> Vec { + tools + .iter() + .map(|t| ToolDefinition { + name: t.name.clone(), + description: t.description.clone(), + input_schema: t.input_schema.clone(), + }) + .collect() +} + #[allow(clippy::too_many_arguments)] async fn converse_as( state: &crate::WorkerState, @@ -361,24 +376,52 @@ async fn converse_as( // Every call this loop makes is asked of the policy gate first, and a // tool the policy would refuse whatever the call is never offered. let mut gate = super::policy::gate(state, provider.scope.ctx(agent), opts.deadline); - let tools = super::policy::offerable(&mut gate, tools).await; + // Every loop offered tools reads every repository of the team's + // installation too, and is told so (`reach`): no agent answers from + // one repository what another one holds. + let reaches = !tools.is_empty() && !provider.scope.team.is_empty(); + let tools = if reaches { + super::reach::offer(tools) + } else { + copy(tools) + }; + let tools = super::policy::offerable(&mut gate, &tools).await; + let access = if reaches { + super::reach::access(state, &provider.scope.team).await + } else { + Err(String::new()) + }; + let host = access.as_ref().ok().map(super::reach::Access::host); + let reader = host.as_ref().map(|h| { + common::repo_read::CodeReader::new( + h, + access.as_ref().map(|a| a.repos.clone()).unwrap_or_default(), + ) + }); + let missing = access.as_ref().err().cloned().unwrap_or_default(); + let exec = super::reach::Exec::new(tool_executor, reader.as_ref(), &missing); + let system = if reaches { + super::reach::prompt(system_prompt) + } else { + system_prompt.to_string() + }; // A loop on a run whose caller keeps no log of its own is logged here, // under the pass the run is in, one file per call (`run_log`). let scope = &provider.scope; let mut own: Vec = Vec::new(); let own_log = conversation_log.is_none() && !scope.run_id.is_empty() && !scope.team.is_empty(); - let log = match conversation_log { + let mut log = match conversation_log { Some(l) => Some(l), None if own_log => Some(&mut own), None => None, }; - let out = anthropic::converse_tool_loop( + let mut out = anthropic::converse_tool_loop( &client, model_id, - system_prompt, + &system, messages, &tools, - tool_executor, + &exec, &gate, usage, opts.max_turns, @@ -386,10 +429,44 @@ async fn converse_as( opts.deadline, opts.effort, observer, - log, + log.as_deref_mut(), form, ) .await; + // An answer saying CoderHelm can't see or confirm something, with no + // refusal from this loop's tools to show for it, is sent back once to + // look first; what still says so is taken out before anyone reads it + // (`common::repo_reach`). + if let Ok(text) = &out { + if let Err(sentence) = common::repo_reach::allowed(text, &exec.refusals()) { + tracing::warn!(sentence = %sentence, "An answer claimed it couldn't see something it never tried to read; asking it to look first"); + if reaches && form == super::llm::AnswerForm::Auto { + messages.push(( + "user".to_string(), + vec![serde_json::json!({"type": "text", "text": common::repo_reach::look_first(&sentence)})], + )); + out = anthropic::converse_tool_loop( + &client, + model_id, + &system, + messages, + &tools, + &exec, + &gate, + usage, + LOOK_FIRST_TURNS, + opts.max_tokens, + opts.deadline, + opts.effort, + observer, + log.as_deref_mut(), + form, + ) + .await; + } + out = out.map(|t| common::repo_reach::strip(&t, &exec.refusals())); + } + } if own_log { let step = scope.agent(agent).key(); let pass = super::run_log::current_pass(&scope.run_id).unwrap_or_else(|| step.to_string()); diff --git a/services/worker/src/agent/reach.rs b/services/worker/src/agent/reach.rs new file mode 100644 index 000000000..670fa6635 --- /dev/null +++ b/services/worker/src/agent/reach.rs @@ -0,0 +1,248 @@ +//! The cross-repository tools in every worker model loop. +//! +//! `provider::converse_as` is the one place a worker agent's loop starts +//! (the coder, every fix round, the reviewer, ticket replies, triage, +//! skills). There, a loop that is offered tools is also offered +//! `common::repo_reach`'s read-only tools over every repository of the +//! team's GitHub installation ([`offer`]), its system prompt says so +//! ([`prompt`]), and its calls to them run here ([`Exec`]), each refusal +//! kept. The loop's answer is then held to `repo_reach::allowed` with the +//! refusals of that same loop. + +use std::collections::HashMap; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use common::mcp_remote::http::GuardedHttps; +use common::repo_reach::{self, Refusal}; +use common::repo_read::{CodeReader, GitHubHost, RepoInfo}; +use serde_json::{json, Value}; + +use super::llm::{ToolDefinition, ToolExecutor}; + +/// The transport every installation read goes through. +static HTTP: GuardedHttps = GuardedHttps; + +/// How long a team's token and repository list are kept between loops. +const KEEP: Duration = Duration::from_secs(600); + +/// What a team's loops read with: the installation token and every +/// repository it can read. +#[derive(Clone)] +pub struct Access { + token: String, + pub repos: Vec, +} + +impl Access { + /// The host the reads go to. + pub fn host(&self) -> GitHubHost<'static> { + GitHubHost { + http: &HTTP, + auth: format!("Bearer {}", self.token), + } + } +} + +type Kept = (Instant, Result); + +static CACHE: LazyLock>> = LazyLock::new(Default::default); + +/// The team's access, read at most every [`KEEP`]: `Err` says why there is +/// none (no installation, a refused token), as the tools then say. +pub async fn access(state: &crate::WorkerState, team: &str) -> Result { + if let Some((at, a)) = CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(team) + .cloned() + { + if at.elapsed() < KEEP { + return a; + } + } + let got = read_access(state, team).await; + CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(team.to_string(), (Instant::now(), got.clone())); + got +} + +async fn read_access(state: &crate::WorkerState, team: &str) -> Result { + let id = crate::passes::review_reminder::team_installation_id(state, team) + .await + .filter(|id| *id > 0) + .ok_or("the team has no GitHub installation stored")?; + let gh = crate::clients::github::GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + id, + &state.http, + ) + .map_err(|e| format!("the GitHub app couldn't be used: {e}"))?; + let token = gh + .installation_token() + .await + .map_err(|e| format!("GitHub refused the installation's token: {e}"))?; + let mut a = Access { + token, + repos: Vec::new(), + }; + a.repos = a + .host() + .installation_repos(repo_reach::MAX_REPOS) + .await + .map_err(|e| e.to_string())?; + Ok(a) +} + +/// `tools` with the cross-repository tools after them, each once. A loop +/// offered no tools is left as it is: it answers from its prompt. +pub fn offer(tools: &[ToolDefinition]) -> Vec { + let mut out: Vec = tools + .iter() + .map(|t| ToolDefinition { + name: t.name.clone(), + description: t.description.clone(), + input_schema: t.input_schema.clone(), + }) + .collect(); + if out.is_empty() { + return out; + } + for d in repo_reach::defs() { + let name = d["name"].as_str().unwrap_or_default().to_string(); + if out.iter().any(|t| t.name == name) { + continue; + } + out.push(ToolDefinition { + name, + description: d["description"].as_str().unwrap_or_default().to_string(), + input_schema: d["input_schema"].clone(), + }); + } + out +} + +/// `system` with `repo_reach::prompt` after it (once), for a loop +/// offered the tools. +pub fn prompt(system: &str) -> String { + let words = repo_reach::prompt(); + if system.contains(&words) { + return system.to_string(); + } + format!("{}\n\n{words}", system.trim_end()) +} + +/// A loop's executor with the cross-repository tools in front of it. +pub struct Exec<'a> { + inner: &'a dyn ToolExecutor, + reader: Option<&'a CodeReader<'a>>, + missing: String, + refusals: Mutex>, +} + +impl<'a> Exec<'a> { + /// `reader` over the team's installation, or `missing`: why there is + /// none. + pub fn new( + inner: &'a dyn ToolExecutor, + reader: Option<&'a CodeReader<'a>>, + missing: &str, + ) -> Self { + Exec { + inner, + reader, + missing: missing.to_string(), + refusals: Mutex::new(Vec::new()), + } + } + + /// Every refusal a call of this loop returned so far. + pub fn refusals(&self) -> Vec { + self.refusals + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + } + + fn keep(&self, r: Refusal) { + self.refusals + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(r); + } +} + +#[async_trait::async_trait] +impl ToolExecutor for Exec<'_> { + async fn execute( + &self, + name: &str, + input: &Value, + ) -> Result> { + if repo_reach::is_reach_tool(name) { + let out = match self.reader { + Some(r) => repo_reach::call(r, name, input).await, + None => repo_reach::without_access(name, &self.missing), + }; + if let Some(r) = out.refusal { + self.keep(r); + } + return Ok(json!(out.text)); + } + let out = self.inner.execute(name, input).await; + if let Err(e) = &out { + if let Some(r) = repo_reach::refusal_in(name, input, &e.to_string()) { + self.keep(r); + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tool(name: &str) -> ToolDefinition { + ToolDefinition { + name: name.into(), + description: String::new(), + input_schema: json!({}), + } + } + + #[test] + fn every_loop_with_tools_gets_the_installation() { + let names = |t: Vec| t.into_iter().map(|t| t.name).collect::>(); + let coder = names(offer(&[tool("read_file"), tool("edit_file")])); + for t in repo_reach::TOOLS { + assert_eq!(coder.iter().filter(|n| *n == t).count(), 1, "{t}"); + } + // Offered once, even when a loop names one itself. + let again = names(offer(&[tool(repo_reach::LIST_REPOS)])); + assert_eq!(again.len(), 3); + // A loop with no tools answers from its prompt. + assert!(offer(&[]).is_empty()); + let p = prompt("You review code."); + assert!(p.ends_with(&repo_reach::prompt())); + assert_eq!(prompt(&p), p); + } + + #[test] + fn a_tools_404_is_a_refusal() { + let r = repo_reach::refusal_in( + "read_file", + &json!({"path": "src/x.ts"}), + "GitHub answered 404 Not Found", + ) + .unwrap(); + assert_eq!((r.status, r.path.as_str()), (404, "src/x.ts")); + assert_eq!( + repo_reach::refusal_in("read_file", &json!({}), "timed out"), + None + ); + } +} diff --git a/services/worker/src/clients/git_mode.rs b/services/worker/src/clients/git_mode.rs index f1d4ebf46..c9b99fbc1 100644 --- a/services/worker/src/clients/git_mode.rs +++ b/services/worker/src/clients/git_mode.rs @@ -345,3 +345,102 @@ pub fn restore_message(restored: &[(String, GitEntry)]) -> String { fn short(sha: &str) -> &str { &sha[..7.min(sha.len())] } + +/// The mode a `set_mode` call or a restore asks for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Want<'a> { + /// An executable file (true) or a plain file (false). + Executable(bool), + /// The mode the path has at another ref (a restore), with that entry. + Like(Option<&'a GitEntry>), +} + +/// The entry `path` gets when its mode moves to `want` from `current`, or +/// `None` when it already has that mode. Only a file's executable bit is +/// ever set this way: a symbolic link or a submodule is never made from or +/// into a file by a mode alone, except by a restore (`links`) whose source +/// is a link with exactly this text. +pub fn mode_move( + path: &str, + current: Option<&GitEntry>, + want: Want<'_>, + links: bool, +) -> Result, String> { + let Some(cur) = current else { + return Err(format!( + "`{path}` isn't on the branch, so it has no mode to set" + )); + }; + if cur.kind != "blob" || !is_file(&cur.mode) { + return Err(format!( + "`{path}` is {} on the branch; only a file's executable bit is set here, \ + so nothing was changed", + named(&cur.mode) + )); + } + let target = match want { + Want::Executable(true) => EXECUTABLE.to_string(), + Want::Executable(false) => FILE.to_string(), + Want::Like(None) => { + return Err(format!( + "`{path}` isn't at that ref, so there is no mode to take from it" + )) + } + Want::Like(Some(src)) if src.kind == "blob" && is_file(&src.mode) => src.mode.clone(), + Want::Like(Some(src)) if links && src.mode == SYMLINK && src.sha == cur.sha => { + return Ok(Some(src.clone())); + } + Want::Like(Some(src)) => { + return Err(format!( + "`{path}` is {} at that ref; a file is never turned into one by its mode, \ + so nothing was changed", + named(&src.mode) + )) + } + }; + if target == cur.mode { + return Ok(None); + } + Ok(Some(GitEntry { + mode: target, + kind: "blob".to_string(), + sha: cur.sha.clone(), + })) +} + +/// What a pull request's head did to the mode `path` has at the merge base +/// with its base branch. A path that was an executable, a symbolic link or +/// a submodule at the base and is a plain file at the head lost its mode; +/// when no person's commit on the branch touched it, CoderHelm's commits +/// did, and the base's mode is put back (a link or a submodule as the base +/// has it, an executable with the head's content). A path a person touched +/// is theirs: it is left, with why. +pub fn against_base( + path: &str, + base: Option<&GitEntry>, + head: Option<&GitEntry>, + person_touched: bool, +) -> Repair { + let (Some(b), Some(h)) = (base, head) else { + return Repair::Fine; + }; + let lost = b.mode == EXECUTABLE || b.mode == SYMLINK || b.mode == SUBMODULE; + if !lost || h.mode != FILE || h.kind != "blob" { + return Repair::Fine; + } + if person_touched { + return Repair::Leave(format!( + "`{path}` is {} on the base and a plain file on the branch; a person's commit \ + changed it, so it is left for them", + named(&b.mode) + )); + } + match b.mode.as_str() { + EXECUTABLE => Repair::Restore(GitEntry { + mode: EXECUTABLE.to_string(), + kind: "blob".to_string(), + sha: h.sha.clone(), + }), + _ => Repair::Restore(b.clone()), + } +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index f005e65cd..50da81dcb 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3746,6 +3746,103 @@ impl GitHubClient { Ok(true) } + /// Sets `path`'s mode on `branch` in one commit that changes nothing + /// else (`git_mode::mode_move` decides the entry): `Ok(None)` when the + /// path already has that mode, `Err` with why when the move is refused + /// or the branch moved meanwhile. `links`: a restore may put a symbolic + /// link back whose text is already exactly the source's. + #[allow(clippy::too_many_arguments)] + pub async fn set_mode( + &self, + owner: &str, + repo: &str, + branch: &str, + path: &str, + want: SetModeTo<'_>, + message: &str, + links: bool, + ) -> Result, String> { + let head = self + .get_ref(owner, repo, branch) + .await + .map_err(|e| format!("couldn't read `{branch}`: {e}"))?; + let current = self + .entries_at(owner, repo, &head, &[path]) + .await + .map_err(|e| format!("couldn't read `{path}` on `{branch}`: {e}"))? + .remove(path); + let source = match want { + SetModeTo::Executable(_) => None, + SetModeTo::Like(rev) => self + .entries_at(owner, repo, rev, &[path]) + .await + .map_err(|e| format!("couldn't read `{path}` at `{rev}`: {e}"))? + .remove(path), + }; + let wanted = match want { + SetModeTo::Executable(x) => git_mode::Want::Executable(x), + SetModeTo::Like(_) => git_mode::Want::Like(source.as_ref()), + }; + let Some(entry) = git_mode::mode_move(path, current.as_ref(), wanted, links)? else { + return Ok(None); + }; + let change = git_mode::ModeChange { + path: path.to_string(), + from: current.map(|c| c.mode).unwrap_or_default(), + to: entry.mode.clone(), + }; + let fail = |e: Box| e.to_string(); + let (tree, _) = self + .commit_tree_parents(owner, repo, &head) + .await + .map_err(fail)?; + let tree = self + .put_tree(owner, repo, &tree, &[(path.to_string(), Some(entry))]) + .await + .map_err(fail)?; + let message = git_mode::with_trailer(message, std::slice::from_ref(&change)); + let commit = self + .put_commit(owner, repo, &message, &tree, &[head.clone()]) + .await + .map_err(fail)?; + if !self + .fast_forward(owner, repo, branch, &head, &commit) + .await + .map_err(fail)? + { + return Err(format!( + "`{branch}` moved while `{path}`'s mode was being set; nothing was pushed" + )); + } + Ok(Some((commit, change))) + } + + /// The merge base of `base` and `head` and the paths the comparison + /// changes (first page, up to 300), in one request. + pub async fn merge_base_and_files( + &self, + owner: &str, + repo: &str, + base: &str, + head: &str, + ) -> Result<(String, Vec), Box> { + let url = format!("{API_BASE}/repos/{owner}/{repo}/compare/{base}...{head}"); + let data = self.get(&url).await?; + let mb = data["merge_base_commit"]["sha"] + .as_str() + .ok_or("the comparison named no merge base")? + .to_string(); + let files = data["files"] + .as_array() + .map(|arr| { + arr.iter() + .filter_map(|f| f["filename"].as_str().map(String::from)) + .collect() + }) + .unwrap_or_default(); + Ok((mb, files)) + } + /// Moves `branch` to `to` only if it still points at `lease`: `false` /// (nothing moved) when someone pushed since. pub async fn move_with_lease( @@ -6770,6 +6867,15 @@ pub struct DirEntry { pub path: String, } +/// What [`GitHubClient::set_mode`] sets a path to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SetModeTo<'a> { + /// An executable file (true) or a plain file (false). + Executable(bool), + /// The mode the path has at this ref. + Like(&'a str), +} + /// A path's entry in a git tree: its mode, type (`blob`, `commit` for a /// submodule) and object sha. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index 3a7312112..e9ed4f587 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -2592,6 +2592,7 @@ fn feedback_tools() -> Vec { "required": ["path"] }), }, + super::mode_repair::set_mode_tool(), ] } @@ -3328,11 +3329,53 @@ impl<'a> ToolExecutor for FeedbackToolExecutor<'a> { ) .await?; *self.files_modified.lock().unwrap() = true; + // The mode comes from the same ref as the bytes. + let mode = super::mode_repair::restore_mode( + self.github, + (self.owner, self.repo, self.branch), + path, + from_ref, + &self.commit_message(&format!("Restore the mode of {path} from {from_ref}")), + ) + .await + .unwrap_or_default(); Ok(json!(format!( - "Restored {path} from '{from_ref}' ({} bytes) — exact copy, content not loaded into context", + "Restored {path} from '{from_ref}' ({} bytes) — exact copy, content not loaded into context.{mode}", content.len() ))) } + super::mode_repair::SET_MODE => { + let path = input.get("path").and_then(|v| v.as_str()).unwrap_or(""); + if super::implement::is_protected_path(path) { + return Ok(json!(format!( + "Cannot modify {path}: CI/CD workflow files are protected." + ))); + } + let message = self.commit_message(&format!("Set the mode of {path}")); + match super::mode_repair::set_mode_call( + self.github, + (self.owner, self.repo, self.branch, self.base_branch), + input, + &message, + ) + .await + { + Ok(said) => { + if said.starts_with("Committed") { + *self.files_modified.lock().unwrap() = true; + } + Ok(json!(said)) + } + Err(why) => { + crate::agent::tool_outcome::note( + crate::agent::tool_outcome::ToolOutcome::soft_fail(format!( + "mode not set: {path}" + )), + ); + Ok(json!(why)) + } + } + } _ => Err(format!("Unknown tool: {name}").into()), } } diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 48ec0c32e..8b2d5521b 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -2031,6 +2031,7 @@ fn all_tools() -> Vec { "required": ["path"] }), }, + super::mode_repair::set_mode_tool(), ] } @@ -2356,7 +2357,7 @@ fn checks_outcome(passed: bool, codes: &[Option]) -> LogOutcome { fn is_write_tool(name: &str) -> bool { matches!( name, - "write_file" | "edit_file" | "batch_write" | "restore_file" + "write_file" | "edit_file" | "batch_write" | "restore_file" | "set_mode" ) } @@ -3092,12 +3093,54 @@ impl<'a> WriteToolExecutor<'a> { .insert(format!("{}:{}", self.branch, path), content.clone()) .await; self.task_tracker.mark_files_done(&[path]).await; + // The mode comes from the same ref as the bytes. + let mode = super::mode_repair::restore_mode( + &self.github, + (&self.owner, &self.repo, &self.branch), + path, + from_ref, + &self.commit_message(&format!("Restore the mode of {path} from {from_ref}")), + ) + .await + .unwrap_or_default(); note(LogOutcome::ok(format!("restored from {from_ref}"))); Ok(json!(format!( - "Restored {path} from '{from_ref}' ({} bytes) — exact copy, content not loaded into context", + "Restored {path} from '{from_ref}' ({} bytes) — exact copy, content not loaded into context.{mode}", content.len() ))) } + super::mode_repair::SET_MODE => { + let path = input.get("path").and_then(|v| v.as_str()).unwrap_or(""); + if is_protected_path(path) { + note(LogOutcome::soft_fail( + "mode not set: a protected CI/CD file", + )); + return Ok(json!(format!( + "Cannot modify {path}: CI/CD workflow files are protected." + ))); + } + let message = self.commit_message(&format!("Set the mode of {path}")); + match super::mode_repair::set_mode_call( + &self.github, + (&self.owner, &self.repo, &self.branch, &self.base_branch), + input, + &message, + ) + .await + { + Ok(said) => { + if said.starts_with("Committed") { + self.mark_written(path.to_string()); + } + note(LogOutcome::ok("mode set")); + Ok(json!(said)) + } + Err(why) => { + note(LogOutcome::soft_fail(format!("mode not set: {path}"))); + Ok(json!(why)) + } + } + } "run_checks" => self.run_checks_impl().await, "run_codegen" => self.run_codegen_impl().await, _ => Err(format!("Unknown tool: {name}").into()), diff --git a/services/worker/src/passes/incidents/xo_own_modes_never_red_ci.rs b/services/worker/src/passes/incidents/xo_own_modes_never_red_ci.rs new file mode 100644 index 000000000..a96d47d54 --- /dev/null +++ b/services/worker/src/passes/incidents/xo_own_modes_never_red_ci.rs @@ -0,0 +1,357 @@ +//! xo. A front-end fix's pull request also listed three shell scripts of +//! the repository's CI as files it changed (a cleanup script, a stub +//! command its tests put on the path, and the test that runs it). Merging +//! the base into the branch had dropped their executable bit, before file +//! modes were kept (`xl`). The pull request's script tests failed while +//! the base stayed green on them. The fix rounds ran `chmod +x` in the +//! sandbox, called `restore_file` on the scripts again and again, and +//! deleted and wrote them again in a batch write: none of it reached the +//! mode, since the sandbox works on a copy and the restore wrote every file +//! plain. After five rounds the run ended failed on red CI and was handed +//! to a person, for a cause CoderHelm made itself. +//! +//! Why: `restore_file` took the bytes from the ref and the mode from the +//! branch, which had already lost it; no tool set a mode at all; nothing +//! compared the pull request's modes with the base when its checks were red +//! and the base's green; and the repair sweep of `xl` compared each +//! CoderHelm commit with its parent only, where a delete and a write again +//! show no drop, read runs through the description catch-up's picks (which +//! skip runs in flight and every run whose description was rebuilt), and +//! never set a failed run going again. +//! +//! Guarantee: a red check that is green on the base first gets the mode +//! diagnosis: every file the pull request changes is compared with the +//! merge base, and an executable, link or submodule CoderHelm's commits +//! turned into a plain file is put back in one commit with no model round. +//! What can't be put back yet is CoderHelm's own problem, alerted and +//! tried again, never a hand-off. `restore_file` restores the mode with +//! the bytes; `set_mode` sets a file's executable bit as a commit and +//! refuses links and submodules; a sandbox `chmod` says it never reaches +//! the commit. The repair sweep compares with the base too, reads runs of +//! every status a pull request can still be open under (failed first), and +//! resumes a run that ended on red CI once its modes are back. + +use std::collections::{HashMap, HashSet}; + +use super::fixture::fn_src; +use crate::clients::git_mode::{self, Want, EXECUTABLE, FILE, SUBMODULE, SYMLINK}; +use crate::clients::github::GitEntry; +use crate::passes::mode_repair::{self, ModeFix}; + +const CLEANUP: &str = "ops/ci/cleanup-env.sh"; +const STUB: &str = "ops/ci/test/bin/cloudctl"; +const SPEC: &str = "ops/ci/test/cleanup-env.test.sh"; +const PAGE: &str = "web/src/pages/plans.tsx"; + +fn entry(mode: &str, sha: &str) -> GitEntry { + GitEntry { + mode: mode.to_string(), + kind: "blob".to_string(), + sha: sha.to_string(), + } +} + +fn tree(entries: &[(&str, GitEntry)]) -> HashMap { + entries + .iter() + .map(|(p, e)| (p.to_string(), e.clone())) + .collect() +} + +const RESUME: &str = include_str!("../resume.rs"); +const REPAIR: &str = include_str!("../mode_repair.rs"); + +/// The replay: the merge base had the three scripts executable; a merge +/// commit dropped the bit, a fix round deleted the scripts and the next +/// wrote them again as plain files. Commit by commit, the delete and the +/// write show no drop; against the base, all three are plain files that +/// were executables, and the diagnosis puts each back in one commit. +#[test] +fn a_red_check_from_dropped_modes_is_fixed_by_a_mode_commit_not_handed_off() { + // Commit by commit: a delete (the path gone after it) and a write again + // (the path new before it) are no drop. + let deleted = ( + "d1".to_string(), + true, + tree(&[(CLEANUP, entry(EXECUTABLE, "a1"))]), + HashMap::new(), + ); + let rewritten = ( + "d2".to_string(), + true, + HashMap::new(), + tree(&[(CLEANUP, entry(FILE, "a1"))]), + ); + assert!(mode_repair::drops_of(&[deleted, rewritten]).is_empty()); + + // Against the merge base: the whole cause. + let base = tree(&[ + (CLEANUP, entry(EXECUTABLE, "a1")), + (STUB, entry(EXECUTABLE, "b1")), + (SPEC, entry(EXECUTABLE, "c1")), + (PAGE, entry(FILE, "p1")), + ]); + let head = tree(&[ + (CLEANUP, entry(FILE, "a1")), + (STUB, entry(FILE, "b1")), + (SPEC, entry(FILE, "c1")), + (PAGE, entry(FILE, "p2")), + ]); + let changed: Vec = [CLEANUP, STUB, SPEC, PAGE].map(String::from).to_vec(); + let r = mode_repair::base_plan(&changed, &base, &head, &HashSet::new()); + assert!(r.left.is_empty(), "{:?}", r.left); + let restored: Vec<(&str, &str, &str)> = r + .restored + .iter() + .map(|(p, e)| (p.as_str(), e.mode.as_str(), e.sha.as_str())) + .collect(); + assert_eq!( + restored, + vec![ + (CLEANUP, EXECUTABLE, "a1"), + (SPEC, EXECUTABLE, "c1"), + (STUB, EXECUTABLE, "b1"), + ] + ); + // One commit, named, with nothing but modes in it. + let message = git_mode::restore_message(&r.restored); + assert!(message.starts_with(git_mode::RESTORE_MESSAGE), "{message}"); + let line = mode_repair::page_line(&mode_repair::Repaired { + commit: Some("0123456789".into()), + ..r.clone() + }) + .unwrap(); + assert!( + line.contains(CLEANUP) && line.contains("an executable file"), + "{line}" + ); + + // A second look at the repaired head finds nothing. + let fixed: HashMap = r.restored.iter().cloned().collect(); + let mut after = head.clone(); + after.extend(fixed); + assert_eq!( + mode_repair::base_plan(&changed, &base, &after, &HashSet::new()), + mode_repair::Repaired::default() + ); + + // In the CI loop: a red check green on the base gets the diagnosis + // before the stall check spends a round or hands anything off, and the + // hand-off itself asks it first. + let run = fn_src(RESUME, "pub async fn run("); + let diag = run + .find("mode_cause(") + .expect("the CI loop runs the diagnosis"); + assert!( + run.find("failing_wf.iter().any(|c| !on_base.contains(c))") + .unwrap() + < diag + ); + assert!(diag < run.find("check_and_record_stall(").unwrap()); + let hand_off = fn_src(RESUME, "async fn hand_off_red_ci("); + assert!( + hand_off.find("mode_cause(").unwrap() < hand_off.find("record_ci_outcome(").unwrap(), + "the hand-off asks the diagnosis before it records anything" + ); + // What the diagnosis does: a commit and a wait on CI, or CoderHelm's + // own problem tried again; never a failed run. + let cause = fn_src(RESUME, "async fn mode_cause("); + for part in [ + "mode_repair::on_red(", + "own_problems::record(", + "set_run_awaiting_ci(", + "send_delayed_resume(", + ] { + assert!(cause.contains(part), "{part}"); + } + for never in ["Stop::RedCi", "finish_", "FAILED", "wait_on_person"] { + assert!(!cause.contains(never), "{never}"); + } + let on_red = fn_src(REPAIR, "pub async fn on_red("); + assert!(on_red.contains("write_restore(")); + assert!(matches!(ModeFix::Nothing, ModeFix::Nothing)); +} + +/// A path a person changed on the branch is theirs: left, with why. A path +/// the head made executable, or one the base never had, is no drop. +#[test] +fn a_persons_change_is_left_and_new_modes_are_not_drops() { + let base = tree(&[(CLEANUP, entry(EXECUTABLE, "a1"))]); + let head = tree(&[(CLEANUP, entry(FILE, "a2"))]); + let people: HashSet = [CLEANUP.to_string()].into(); + let r = mode_repair::base_plan(&[CLEANUP.to_string()], &base, &head, &people); + assert!(r.restored.is_empty()); + assert!( + r.left[0].contains("a person's commit changed it"), + "{:?}", + r.left + ); + + assert_eq!( + git_mode::against_base( + PAGE, + Some(&entry(FILE, "p1")), + Some(&entry(EXECUTABLE, "p1")), + false + ), + git_mode::Repair::Fine + ); + assert_eq!( + git_mode::against_base(PAGE, None, Some(&entry(FILE, "p1")), false), + git_mode::Repair::Fine + ); + // A link the head turned into a file comes back as the base has it. + let link = entry(SYMLINK, "l1"); + assert_eq!( + git_mode::against_base("ops/current", Some(&link), Some(&entry(FILE, "l9")), false), + git_mode::Repair::Restore(link) + ); +} + +/// `restore_file` restores the mode with the bytes: an executable comes +/// back executable, and a link whose text came back exactly is a link +/// again. Both executors' restores call it. +#[test] +fn restore_file_keeps_the_mode_of_the_ref_it_restores_from() { + let plain = entry(FILE, "a1"); + let at_base = entry(EXECUTABLE, "a1"); + assert_eq!( + git_mode::mode_move(CLEANUP, Some(&plain), Want::Like(Some(&at_base)), true), + Ok(Some(entry(EXECUTABLE, "a1"))) + ); + // Already right: nothing to commit. + assert_eq!( + git_mode::mode_move(CLEANUP, Some(&at_base), Want::Like(Some(&at_base)), true), + Ok(None) + ); + let link = entry(SYMLINK, "l1"); + assert_eq!( + git_mode::mode_move( + "ops/current", + Some(&entry(FILE, "l1")), + Want::Like(Some(&link)), + true + ), + Ok(Some(link.clone())) + ); + assert!(git_mode::mode_move( + "ops/current", + Some(&entry(FILE, "l2")), + Want::Like(Some(&link)), + true + ) + .is_err()); + + for (name, src) in [ + ("implement.rs", include_str!("../implement.rs")), + ("feedback.rs", include_str!("../feedback.rs")), + ] { + let at = src.find("\"restore_file\" => {").expect(name); + let arm = &src[at..at + + src[at..] + .find("super::mode_repair::SET_MODE =>") + .expect(name)]; + assert!(arm.contains("mode_repair::restore_mode("), "{name}"); + assert!( + src.contains("super::mode_repair::set_mode_tool()"), + "{name}" + ); + } +} + +/// `set_mode` sets a file's executable bit and nothing else: a symbolic +/// link or a submodule is refused, on the branch or at the ref. A sandbox +/// `chmod` says it never reaches the commit and names `set_mode`. +#[test] +fn set_mode_refuses_links_and_chmod_points_to_it() { + let link = entry(SYMLINK, "l1"); + let why = + git_mode::mode_move("ops/current", Some(&link), Want::Executable(true), false).unwrap_err(); + assert!(why.contains("a symbolic link"), "{why}"); + let sub = GitEntry { + mode: SUBMODULE.to_string(), + kind: "commit".to_string(), + sha: "s1".to_string(), + }; + assert!( + git_mode::mode_move("vendor/kit", Some(&sub), Want::Executable(false), false) + .unwrap_err() + .contains("a submodule") + ); + // A file is never made a link by a mode, outside a restore. + assert!(git_mode::mode_move( + "ops/current", + Some(&entry(FILE, "l1")), + Want::Like(Some(&link)), + false + ) + .is_err()); + assert_eq!( + git_mode::mode_move( + CLEANUP, + Some(&entry(FILE, "a1")), + Want::Executable(true), + false + ), + Ok(Some(entry(EXECUTABLE, "a1"))) + ); + + let tool = mode_repair::set_mode_tool(); + assert_eq!(tool.name, "set_mode"); + assert!(tool.description.contains("does NOT reach the commit")); + assert_eq!( + common::tool_registry::builtin("set_mode"), + Some(common::tool_registry::Risk::Write) + ); + match common::coder_shell::classify(&format!("chmod +x {CLEANUP}")) { + common::coder_shell::Shell::Refuse(why) => { + assert!( + why.contains("doesn't reach the commit") && why.contains("set_mode"), + "{why}" + ) + } + other => panic!("{other:?}"), + } +} + +/// The repair sweep reads failed runs (failed first) and runs in flight, +/// never a run a person ended, a merged, retried or archived one; it no +/// longer takes the description catch-up's picks, reads every pull request +/// once more for the base comparison, and resumes a run that ended on red +/// CI once its modes are back. +#[test] +fn the_sweep_reaches_failed_runs_and_resumes_them() { + use common::run_status as rs; + for s in [ + rs::FAILED, + rs::RUNNING, + rs::AWAITING_CI, + rs::COMPLETED, + rs::NEEDS_INPUT, + ] { + assert!(mode_repair::reads(s), "{s}"); + } + for s in [ + rs::CANCELLED, + rs::CLOSED, + rs::MERGED, + rs::RETRIED, + rs::ARCHIVED, + ] { + assert!(!mode_repair::reads(s), "{s}"); + } + let sweep = fn_src(REPAIR, "pub async fn sweep("); + assert!(sweep.contains("picks(all, PER_TEAM, MAX_PRS)")); + assert!(!sweep.contains("catch_up_picks")); + assert!(sweep.contains("resume_after_mode_repair(")); + assert_eq!(mode_repair::VERSION, "2"); + let one = fn_src(REPAIR, "pub async fn repair_one("); + assert!( + one.contains("against_base("), + "the sweep compares with the base too" + ); + let resume = fn_src(RESUME, "pub(crate) async fn resume_after_mode_repair("); + assert!(resume.contains("#s = :failed AND #k = :red")); + assert!(resume.contains("AWAITING_CI")); + assert!(resume.contains("send_resume_message(")); +} diff --git a/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs new file mode 100644 index 000000000..19a52c015 --- /dev/null +++ b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs @@ -0,0 +1,336 @@ +//! xp. A person asked on an API repository's pull request why a card read +//! "Ages 1 - 4 years" when the data said 3 months to 4 years. CoderHelm's +//! reply named the website's age formatter as the cause and said it +//! couldn't open that formatter from this repository, so it hadn't +//! confirmed the rounding. The website was another repository of the same +//! team, and CoderHelm's GitHub app could read it. +//! +//! Why: the round that answered had only the tools of the repository it +//! worked in, nothing told the model the installation's other repositories +//! were readable, and nothing checked an answer that said it couldn't see +//! something it never tried to read. +//! +//! Guarantee, as invariants enforced in code: every worker model loop with +//! tools (the coder, every fix round, the reviewer, ticket replies, +//! triage) is offered `list_repos`, `read_repo_file` and `search_repo` over +//! every repository of the team's installation, and its prompt says so; +//! Chat and team agents read the same repositories through their code +//! tools, and Chat's prompt says so. Person-facing text claiming CoderHelm +//! can't see, open, access or confirm something is rejected unless a tool +//! call of that same turn returned a refusal, and then it must name the +//! repository or path and the refusal. A loop's answer that fails is sent +//! back once to look, and what still fails is taken out before anyone +//! reads it. No prompt tells the model it is limited to one repository. + +use common::repo_reach::{self, Refusal}; +use common::repo_read::{CodeReader, MemHost, RepoInfo}; +use serde_json::{json, Value}; + +use crate::agent::llm::{ToolDefinition, ToolExecutor}; +use crate::agent::reach; + +const API: &str = "acme/catalog-api"; +const SITE: &str = "acme/storefront"; +const FORMATTER: &str = "src/format/ages.ts"; + +/// The reply that was posted, with the names invented. +const GUESS: &str = "The 1 comes from the storefront's age formatter, which rounds the minimum \ + age to whole years. I can't open that formatter from this repo, so I haven't confirmed the \ + exact rounding."; + +fn host() -> MemHost { + MemHost::default() + .with_repo( + API, + "c0ffee1", + &[( + "src/programs/card.rs", + "pub struct Card { pub min_age_months: u32 }\n", + )], + ) + .with_repo( + SITE, + "5ca1ab1", + &[( + FORMATTER, + "export function ageRange(minMonths: number, maxMonths: number) {\n \ + const lo = Math.max(1, Math.round(minMonths / 12));\n \ + return `Ages ${lo} - ${Math.round(maxMonths / 12)} years`;\n}\n", + )], + ) +} + +fn repos() -> Vec { + vec![RepoInfo::new(API, "main"), RepoInfo::new(SITE, "main")] +} + +struct Nothing; + +#[async_trait::async_trait] +impl ToolExecutor for Nothing { + async fn execute( + &self, + name: &str, + _input: &Value, + ) -> Result> { + Err(format!("{name}: not in this replay").into()) + } +} + +/// The answer reads the sibling repository and cites the exact line. +#[tokio::test] +async fn an_answer_about_a_sibling_repo_reads_it_and_cites_the_line() { + let h = host(); + let reader = CodeReader::new(&h, repos()); + let listed = repo_reach::call(&reader, repo_reach::LIST_REPOS, &json!({})).await; + assert!(listed.text.contains(SITE) && listed.text.contains(API)); + let found = repo_reach::call( + &reader, + repo_reach::SEARCH_REPO, + &json!({"query": "ages", "repo": "storefront"}), + ) + .await; + assert!(found.text.contains(FORMATTER), "{}", found.text); + let read = repo_reach::call( + &reader, + repo_reach::READ_REPO_FILE, + &json!({"repo": "storefront", "path": FORMATTER}), + ) + .await; + assert_eq!(read.refusal, None); + assert!( + read.text + .contains("2 | const lo = Math.max(1, Math.round(minMonths / 12));"), + "{}", + read.text + ); + assert!( + read.text + .contains(&format!("Cite as {SITE}/{FORMATTER}:1-")), + "{}", + read.text + ); + // The answer written from it stands. + let answer = format!( + "`{FORMATTER}` line 2 in {SITE} rounds 3 months to 0 years and then raises it to 1 \ + (`Math.max(1, ...)`), so the card shows 1." + ); + assert_eq!(repo_reach::allowed(&answer, &[]), Ok(())); + assert_eq!(common::rendered::person_text(&answer), None); +} + +/// The guess-guard: the posted reply is rejected with no refusal behind +/// it, by the loop's check and by the person-text check, and what is left +/// after the guard is only what was said for certain. +#[test] +fn the_guess_is_rejected_before_posting() { + let why = repo_reach::allowed(GUESS, &[]).unwrap_err(); + assert!(why.contains("I can't open that formatter"), "{why}"); + assert!(common::rendered::person_text(GUESS) + .unwrap() + .contains("no refusal to show for it")); + let left = repo_reach::strip(GUESS, &[]); + assert!(!left.contains("can't open"), "{left}"); + assert!(left.starts_with("The 1 comes from"), "{left}"); + for t in [ + "CoderHelm doesn't have access to the storefront repository.", + "That formatter lives outside this repo.", + "I couldn't confirm the rounding because it is in another repository.", + ] { + assert!(repo_reach::allowed(t, &[]).is_err(), "{t}"); + } + let nudge = repo_reach::look_first(&why); + assert!(nudge.contains("read_repo_file") && nudge.contains("exact file and line")); +} + +/// A guess with no tool call is rejected; a real 404 or 403 from a tool in +/// the same loop lets the honest line through, when it names the path or +/// repository and the refusal. +#[tokio::test] +async fn a_real_refusal_lets_the_honest_line_through() { + let h = host(); + let reader = CodeReader::new(&h, repos()); + let exec = reach::Exec::new(&Nothing, Some(&reader), ""); + // No call yet: the guess has nothing behind it. + assert!(repo_reach::allowed(GUESS, &exec.refusals()).is_err()); + + let missing = "src/format/legacy-ages.ts"; + let out = exec + .execute( + repo_reach::READ_REPO_FILE, + &json!({"repo": SITE, "path": missing}), + ) + .await + .unwrap(); + assert!(out.as_str().unwrap().starts_with("Refused (404)"), "{out}"); + let refusals: Vec = exec.refusals(); + assert_eq!(refusals.len(), 1); + assert_eq!( + (refusals[0].status, refusals[0].path.as_str()), + (404, missing) + ); + + let honest = format!("I couldn't read `{missing}` in {SITE}: the read returned 404 not found."); + assert_eq!(repo_reach::allowed(&honest, &refusals), Ok(())); + assert_eq!( + common::rendered::person_text_after(&honest, &refusals), + None + ); + // The vague guess stays a guess even beside a refusal it doesn't name. + assert!(repo_reach::allowed(GUESS, &refusals).is_err()); + + // A 403 from another read tool counts the same way. + let gated = repo_reach::refusal_in( + "read_file", + &json!({"repo": SITE, "path": FORMATTER}), + "GitHub didn't let CoderHelm read acme/storefront (status 403).", + ) + .unwrap(); + assert_eq!(gated.status, 403); + let line = format!("GitHub refused the read of `{FORMATTER}` in {SITE} (403)."); + assert_eq!(repo_reach::allowed(&line, &[gated]), Ok(())); + + // With no installation at all, the tools say so as a refusal. + let none = reach::Exec::new(&Nothing, None, "the team has no GitHub installation stored"); + let said = none + .execute(repo_reach::LIST_REPOS, &json!({})) + .await + .unwrap(); + assert!(said.as_str().unwrap().contains("Refused (403)")); + assert_eq!(none.refusals()[0].status, 403); +} + +fn tool(name: &str) -> ToolDefinition { + ToolDefinition { + name: name.into(), + description: String::new(), + input_schema: json!({}), + } +} + +/// Every agent context's tools include the cross-repository tools: the +/// worker's one loop adds them to every loop with tools, with the prompt +/// and the answer guard; no worker loop with tools goes around it; Chat +/// and team agents carry their code tools, their prompt and the guard. +#[test] +fn every_agent_context_reads_the_whole_installation() { + for context in [ + vec![tool("read_file"), tool("edit_file"), tool("bash")], + vec![tool("read_file"), tool("search_code"), tool("search_org")], + vec![tool("read_file"), tool("restore_file"), tool("set_mode")], + ] { + let names: Vec = reach::offer(&context).into_iter().map(|t| t.name).collect(); + for t in repo_reach::TOOLS { + assert!(names.iter().any(|n| n == t), "{t} missing from {names:?}"); + assert_eq!( + common::tool_registry::builtin(t), + Some(common::tool_registry::Risk::Read) + ); + } + } + + let provider = include_str!("../../agent/provider.rs"); + let loop_ = super::fixture::fn_src(provider, "async fn converse_as("); + for part in [ + "super::reach::offer(tools)", + "super::reach::prompt(system_prompt)", + "super::reach::Exec::new(", + "common::repo_reach::allowed(", + "common::repo_reach::look_first(", + "common::repo_reach::strip(", + ] { + assert!(loop_.contains(part), "{part}"); + } + // Only the worker's one loop, the evals and the app map's own reader + // (which reads every repository on the map) start a tool loop. + let allowed = [ + "agent/provider.rs", + "agent/anthropic.rs", + "passes/review_eval.rs", + "passes/model_route_eval.rs", + "passes/app_map_trace.rs", + ]; + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut stray = Vec::new(); + for f in rs_files(&src) { + let rel = f + .strip_prefix(&src) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + if rel.contains("/incidents/") || allowed.contains(&rel.as_str()) { + continue; + } + if std::fs::read_to_string(&f) + .unwrap_or_default() + .contains("converse_tool_loop(") + { + stray.push(rel); + } + } + assert!(stray.is_empty(), "loops around the provider: {stray:?}"); + + let brain = include_str!("../../../../gateway/src/routes/brain.rs"); + let prompt = super::fixture::fn_src(brain, "pub fn system_prompt("); + assert!(prompt.contains("common::repo_reach::prompt_for(")); + assert!(brain.contains("tools.extend(chat_code::defs(&run.code_repos))")); + let chat = include_str!("../../../../gateway/src/routes/chat_agent.rs"); + let run = super::fixture::fn_src(chat, "pub async fn run("); + assert!(run.contains("common::repo_reach::allowed(")); + assert!(run.contains("common::repo_reach::refusal_in(")); +} + +/// No prompt tells the model it is limited to one repository. +#[test] +fn no_prompt_limits_the_model_to_one_repository() { + const LIMITS: &[&str] = &[ + "you can only read this", + "you can only read the", + "only have access to this repo", + "only have access to the current repo", + "limited to this repo", + "limited to the current repo", + "restricted to this repo", + "can't read other repositories", + "cannot read other repositories", + "can't see other repositories", + "no access to other repositories", + "don't have access to other repositories", + "only the repository you are working in", + ]; + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut found = Vec::new(); + for dir in ["worker/src", "common/src", "gateway/src"] { + for f in rs_files(&root.join(dir)) { + let p = f.to_string_lossy().replace('\\', "/"); + if p.contains("/incidents/") || p.ends_with("/repo_reach.rs") { + continue; + } + let text = std::fs::read_to_string(&f) + .unwrap_or_default() + .to_lowercase(); + for l in LIMITS { + if text.contains(l) { + found.push(format!("{p}: {l}")); + } + } + } + } + assert!(found.is_empty(), "{found:#?}"); +} + +fn rs_files(dir: &std::path::Path) -> Vec { + let mut out = Vec::new(); + let Ok(rd) = std::fs::read_dir(dir) else { + return out; + }; + for e in rd.flatten() { + let p = e.path(); + if p.is_dir() { + out.extend(rs_files(&p)); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } + out +} diff --git a/services/worker/src/passes/mode_repair.rs b/services/worker/src/passes/mode_repair.rs index cdbef7c4f..e4f0fd2f4 100644 --- a/services/worker/src/passes/mode_repair.rs +++ b/services/worker/src/passes/mode_repair.rs @@ -9,11 +9,21 @@ //! On the pull request watch sweep, each open pull request of a run //! changed in the last [`WINDOW_DAYS`] is read once ([`FIELD`] claims it on //! the run, against [`VERSION`]): CoderHelm's own commits of the window are -//! compared with their first parents, and each path one of them turned from -//! an executable or a symbolic link into a plain file gets its mode back at -//! the branch's head, in one commit named [`git_mode::RESTORE_MESSAGE`] -//! that changes nothing but modes. GitHub signs a commit an app makes -//! through its API. +//! compared with their first parents, and the pull request's files with its +//! merge base ([`against_base`]: a script deleted by one commit and written +//! again by the next shows no drop commit by commit). Each path turned from +//! an executable, a symbolic link or a submodule into a plain file gets its +//! mode back at the branch's head, in one commit named +//! [`git_mode::RESTORE_MESSAGE`] that changes nothing but modes. GitHub +//! signs a commit an app makes through its API. The sweep reads runs of +//! every status a pull request can still be open under ([`reads`]), failed +//! ones first, and a run that ended on red CI is resumed once its modes are +//! back (`resume::resume_after_mode_repair`). +//! +//! The CI loop asks the same base comparison before any fix round on a +//! check red on the pull request and green on its base ([`on_red`]), and +//! the fix rounds get `set_mode` ([`set_mode_tool`]); `restore_file` +//! restores a file's mode with its bytes ([`restore_mode`]). //! //! Only the mode moves, and only where nothing else is in doubt //! (`git_mode::repair`): a path a person touched since, a link whose text @@ -34,8 +44,12 @@ use crate::WorkerState; /// The run attribute claiming the repair of its pull request. pub const FIELD: &str = "modes_repaired"; -/// The repair's version: a pull request is read once per version. -pub const VERSION: &str = "1"; +/// The repair's version: a pull request is read once per version. Version +/// 2 compares each pull request with its base too (a script deleted and +/// written again showed no drop commit by commit), and reads the runs of +/// every status a pull request can still be open under, failed ones first +/// among them. +pub const VERSION: &str = "2"; /// CoderHelm's commits this recent are read. pub const WINDOW_DAYS: i64 = 30; /// Pull requests one sweep reads for each team. @@ -58,6 +72,8 @@ pub struct Repaired { pub restored: Vec<(String, GitEntry)>, /// Each path left as it is, with why. pub left: Vec, + /// The branch moved while the modes were being put back. + pub raced: bool, } /// The run's pull request is CoderHelm's and still open, in the window: @@ -179,29 +195,64 @@ pub async fn repair_one( read.push((sha.to_string(), true, before, after)); } let drops = drops_of(&read); - if drops.is_empty() { - return Ok(Repaired::default()); + let mut out = Repaired::default(); + if !drops.is_empty() { + // The paths a person's commit after the first drop touched: theirs + // to decide. + let first = drops + .iter() + .filter_map(|d| order.iter().position(|c| *c == d.commit)) + .min() + .unwrap_or(0); + let mut people: HashMap> = HashMap::new(); + for sha in persons { + if order.iter().position(|c| *c == sha).unwrap_or(0) > first { + let files = github.commit_files(owner, repo, &sha).await?; + people.insert(sha, files.into_iter().collect()); + } + } + let paths: Vec<&str> = drops.iter().map(|d| d.path.as_str()).collect(); + let at_head = github.entries_at(owner, repo, head, &paths).await?; + out = plan(drops, &at_head, &order, &people); } - // The paths a person's commit after the first drop touched: theirs to - // decide. - let first = drops - .iter() - .filter_map(|d| order.iter().position(|c| *c == d.commit)) - .min() - .unwrap_or(0); - let mut people: HashMap> = HashMap::new(); - for sha in persons { - if order.iter().position(|c| *c == sha).unwrap_or(0) > first { - let files = github.commit_files(owner, repo, &sha).await?; - people.insert(sha, files.into_iter().collect()); + // What the commits hid (a script deleted by one commit and written + // again by the next as a plain file) shows against the base. + let (base_side, _) = against_base(github, owner, repo, &pr_base_ref(&pr), branch).await?; + for (p, e) in base_side.restored { + if !out.restored.iter().any(|(q, _)| *q == p) { + out.restored.push((p, e)); + } + } + for why in base_side.left { + if !out.left.contains(&why) { + out.left.push(why); } } - let paths: Vec<&str> = drops.iter().map(|d| d.path.as_str()).collect(); - let at_head = github.entries_at(owner, repo, head, &paths).await?; - let mut out = plan(drops, &at_head, &order, &people); + write_restore(github, owner, repo, branch, head, &mut out).await?; + Ok(out) +} + +/// The base branch a pull request merges into, as its JSON names it. +fn pr_base_ref(pr: &serde_json::Value) -> String { + pr["base"]["ref"].as_str().unwrap_or("").to_string() +} + +/// Puts `out.restored` back at `head` of `branch` in one commit named +/// [`git_mode::RESTORE_MESSAGE`] that changes nothing but modes, moved +/// only as a fast forward from `head`. When the branch moved meanwhile +/// nothing is pushed, `out.raced` is set, and the next look reads it again. +pub async fn write_restore( + github: &GitHubClient, + owner: &str, + repo: &str, + branch: &str, + head: &str, + out: &mut Repaired, +) -> Result<(), Box> { if out.restored.is_empty() { - return Ok(out); + return Ok(()); } + out.restored.sort_by(|a, b| a.0.cmp(&b.0)); let (head_tree, _) = github.commit_tree_parents(owner, repo, head).await?; let changes: Vec<(String, Option)> = out .restored @@ -214,8 +265,8 @@ pub async fn repair_one( .put_commit(owner, repo, &message, &tree, &[head.to_string()]) .await?; // A fast forward from the head that was read, never a force push: when - // someone pushed meanwhile, nothing moves and the next version's look - // reads it again. + // someone pushed meanwhile, nothing moves and the next look reads it + // again. if github .fast_forward(owner, repo, branch, head, &commit) .await? @@ -226,8 +277,190 @@ pub async fn repair_one( "the branch moved while the modes were being put back; nothing was pushed to `{branch}`" )); out.restored.clear(); + out.raced = true; } - Ok(out) + Ok(()) +} + +/// The plan from the base side: each path the pull request changes +/// (`changed`) with its entry at the merge base (`base`) and at the head +/// (`head`), and the paths a person's commit on the branch touched +/// (`people`). See `git_mode::against_base`. +pub fn base_plan( + changed: &[String], + base: &HashMap, + head: &HashMap, + people: &HashSet, +) -> Repaired { + let mut out = Repaired::default(); + let mut paths: Vec<&String> = changed.iter().collect(); + paths.sort(); + paths.dedup(); + for p in paths { + match git_mode::against_base(p, base.get(p), head.get(p), people.contains(p)) { + Repair::Restore(e) => out.restored.push((p.clone(), e)), + Repair::Fine => {} + Repair::Leave(why) => out.left.push(why), + } + } + out +} + +/// The paths a pull request's head lost a mode on against its merge base +/// with `base_branch`, read from GitHub: what [`base_plan`] makes of the +/// comparison, and the head it was read at. Nothing is written. +pub async fn against_base( + github: &GitHubClient, + owner: &str, + repo: &str, + base_branch: &str, + branch: &str, +) -> Result<(Repaired, String), Box> { + let head = github.get_ref(owner, repo, branch).await?; + if base_branch.is_empty() { + return Ok((Repaired::default(), head)); + } + let (merge_base, changed) = github + .merge_base_and_files(owner, repo, base_branch, &head) + .await?; + if changed.is_empty() { + return Ok((Repaired::default(), head)); + } + let paths: Vec<&str> = changed.iter().map(String::as_str).collect(); + let base = github.entries_at(owner, repo, &merge_base, &paths).await?; + let at_head = github.entries_at(owner, repo, &head, &paths).await?; + let lost: Vec = changed + .iter() + .filter(|p| { + !matches!( + git_mode::against_base(p, base.get(*p), at_head.get(*p), false), + Repair::Fine + ) + }) + .cloned() + .collect(); + if lost.is_empty() { + return Ok((Repaired::default(), head)); + } + // A person's commit that touched one of them makes it theirs. + let bot = github.app_bot_login().await?; + let mut people = HashSet::new(); + for c in github + .compare_all_commits(owner, repo, &merge_base, &head) + .await? + { + if c["author"]["login"].as_str() == Some(bot.as_str()) { + continue; + } + let Some(sha) = c["sha"].as_str() else { + continue; + }; + for f in github.commit_files(owner, repo, sha).await? { + if lost.contains(&f) { + people.insert(f); + } + } + } + Ok((base_plan(&lost, &base, &at_head, &people), head)) +} + +/// What a red CI's mode diagnosis came to (see [`on_red`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ModeFix { + /// No mode CoderHelm dropped on the branch. + Nothing, + /// The modes were put back in one commit: the run page's line. + Fixed(String), + /// CoderHelm dropped a mode and couldn't put it back yet: why. Its own + /// problem, tried again; never a person's. + Stuck(String), +} + +/// The diagnosis a pull request red on a check that is green on its base +/// gets before any fix round: each file the pull request changes is +/// compared with the merge base, and an executable, a symbolic link or a +/// submodule CoderHelm's commits turned into a plain file is a known cause. +/// Its mode is put back in one commit with no model round. +pub async fn on_red( + github: &GitHubClient, + owner: &str, + repo: &str, + base_branch: &str, + branch: &str, +) -> ModeFix { + let (mut r, head) = match against_base(github, owner, repo, base_branch, branch).await { + Ok(x) => x, + Err(e) => { + warn!(owner, repo, branch, error = %e, "Mode diagnosis: couldn't compare the branch with its base"); + return ModeFix::Nothing; + } + }; + if r.restored.is_empty() { + return ModeFix::Nothing; + } + let wanted = r + .restored + .iter() + .map(|(p, _)| format!("`{p}`")) + .collect::>() + .join(", "); + if let Err(e) = write_restore(github, owner, repo, branch, &head, &mut r).await { + return ModeFix::Stuck(format!( + "CoderHelm's commits dropped the mode of {wanted}, and putting it back failed: {e}" + )); + } + if r.raced { + return ModeFix::Stuck(format!( + "CoderHelm's commits dropped the mode of {wanted}; the branch moved while it was being put back" + )); + } + match page_line(&r) { + Some(line) if r.commit.is_some() => ModeFix::Fixed(format!( + "CI failed on a check that passes on the base, and the branch had lost file modes \ + there: {line} CI runs again on the result." + )), + _ => ModeFix::Nothing, + } +} + +/// Whether the repair reads a run's pull request: every run whose pull +/// request can still be open and CoderHelm's (running, waiting, failed, +/// finished), never one a person cancelled or closed, nor one merged, +/// retried or archived. The description catch-up's own mark has no say: +/// the repair once took its picks from there, which skipped every run in +/// flight and every run whose description was already rebuilt. +pub fn reads(status: &str) -> bool { + use common::run_status as rs; + !(rs::ENDED_BY_PERSON.contains(&status) + || [rs::MERGED, rs::RETRIED, rs::ARCHIVED].contains(&status)) +} + +/// The pull requests one sweep reads: at most `per_team` for each team and +/// `max` in all, runs that ended failed first (a person may be looking at +/// a red pull request now), then the most recently changed. +pub fn picks(all: Vec, per_team: usize, max: usize) -> Vec { + let mut all: Vec = all.into_iter().filter(|c| reads(&c.status)).collect(); + all.sort_by(|a, b| { + let failed = |c: &Candidate| c.status == common::run_status::FAILED; + failed(b) + .cmp(&failed(a)) + .then_with(|| b.updated_at.cmp(&a.updated_at)) + .then_with(|| a.run_id.cmp(&b.run_id)) + }); + let mut per: HashMap = HashMap::new(); + let mut out = Vec::new(); + for c in all { + if out.len() >= max { + break; + } + let n = per.entry(c.team_id.clone()).or_default(); + if *n >= per_team { + continue; + } + *n += 1; + out.push(c); + } + out } /// The run page's line for a repair. @@ -314,7 +547,7 @@ pub async fn sweep( .collect(); let mut repaired = Vec::new(); let mut done: BTreeMap = BTreeMap::new(); - for c in pr_watch::catch_up_picks(all, PER_TEAM, MAX_PRS) { + for c in picks(all, PER_TEAM, MAX_PRS) { // Two runs on one pull request: it is read once. let key = format!("{}/{}#{}", c.owner, c.repo, c.pr); if done.insert(key.clone(), ()).is_some() { @@ -360,8 +593,125 @@ pub async fn sweep( } if r.commit.is_some() { info!(pr = %key, restored = r.restored.len(), "File mode repair: modes put back"); + // A run that ended on red CI CoderHelm's own dropped modes + // caused goes on: CI on the repaired head decides again. + if c.status == common::run_status::FAILED + && super::resume::resume_after_mode_repair( + state, + &c.team_id, + &c.run_id, + c.installation_id, + ) + .await + { + info!(pr = %key, run_id = %c.run_id, "File mode repair: the run ended on red CI goes on"); + } repaired.push(key); } } repaired } + +/// The `set_mode` tool: a file's executable bit is a commit like any +/// other, made here. A `chmod` in the sandbox changes the sandbox's copy +/// only and never reaches the branch. +pub fn set_mode_tool() -> crate::agent::llm::ToolDefinition { + crate::agent::llm::ToolDefinition { + name: SET_MODE.to_string(), + description: "Set a file's mode on the branch in a commit that changes nothing else. \ + `chmod` in the sandbox does NOT reach the commit: the sandbox works on a copy, so a \ + script made executable there is still a plain file on the branch. Use this instead. \ + Pass `executable` (true or false) to set the executable bit, or omit it to put back \ + the mode the file has at `from_ref` (default: this pull request's base branch), \ + which is how a script that lost its executable bit gets it back. Only a file's \ + executable bit is set: a symbolic link or a submodule is refused." + .to_string(), + input_schema: serde_json::json!({ + "type": "object", + "properties": { + "path": {"type": "string", "description": "File path relative to the repository root"}, + "executable": {"type": "boolean", "description": "true for an executable file, false for a plain one; omit to take the mode from from_ref"}, + "from_ref": {"type": "string", "description": "Optional commit SHA whose mode to take; omit for this pull request's base branch"} + }, + "required": ["path"] + }), + } +} + +/// The `set_mode` tool's name. +pub const SET_MODE: &str = "set_mode"; + +/// Runs a `set_mode` call on `branch`: what the model reads back. A +/// refusal (a symbolic link, a submodule, a ref other than the base or a +/// commit) is said, and nothing is written. +pub async fn set_mode_call( + github: &GitHubClient, + (owner, repo, branch, base_branch): (&str, &str, &str, &str), + input: &serde_json::Value, + message: &str, +) -> Result { + let path = input["path"] + .as_str() + .map(str::trim) + .filter(|p| !p.is_empty()) + .ok_or("Missing path")?; + let from_ref = input["from_ref"] + .as_str() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or(base_branch); + let want = match input["executable"].as_bool() { + Some(x) => crate::clients::github::SetModeTo::Executable(x), + None => { + if let Some(no) = super::stack::restore_refusal(from_ref, base_branch) { + return Err(no); + } + crate::clients::github::SetModeTo::Like(from_ref) + } + }; + match github + .set_mode(owner, repo, branch, path, want, message, false) + .await? + { + None => Ok(format!( + "`{path}` already has that mode on the branch; nothing was committed." + )), + Some((commit, change)) => Ok(format!( + "Committed {}: {}.", + &commit[..7.min(commit.len())], + change.line() + )), + } +} + +/// After `restore_file` wrote `path`'s content from `from_ref`, its mode +/// from there too: an executable comes back executable, and a symbolic +/// link whose text was restored exactly is a link again. The words for the +/// model, or `None` when the mode already matched. +pub async fn restore_mode( + github: &GitHubClient, + (owner, repo, branch): (&str, &str, &str), + path: &str, + from_ref: &str, + message: &str, +) -> Option { + match github + .set_mode( + owner, + repo, + branch, + path, + crate::clients::github::SetModeTo::Like(from_ref), + message, + true, + ) + .await + { + Ok(None) => None, + Ok(Some((_, change))) => Some(format!(" Its mode came back too: {}.", change.line())), + Err(why) => { + warn!(path, from_ref, why = %why, "restore_file: the mode wasn't restored"); + Some(format!(" Its mode wasn't restored: {why}.")) + } + } +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index c549d852f..f53fe1d72 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -3054,6 +3054,33 @@ pub async fn run( .await; } } + // Red on a check that is green on the base: before any model round, + // the files the pull request changes are compared with the base, and + // a mode CoderHelm's own commits dropped is put back in one commit + // (`mode_repair::on_red`). A sandbox `chmod` never reached the + // commit, and a restore once wrote every file plain. + if failing_wf.iter().any(|c| !on_base.contains(c)) { + if let Some(done) = mode_cause( + state, + &msg, + &ticket_msg, + &github, + &PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }, + &usage, + wall_clock_secs(created_at, &start), + &events, + ) + .await + { + return done; + } + } // Halt-on-no-progress: if the SAME failure keeps recurring, the fixes // aren't working (noop commits, placeholder stubs, wrong fixes). Stop // churning the PR and end on CoderHelm's own typed stop with what @@ -8819,6 +8846,13 @@ async fn hand_off_red_ci( // with why, and CI decides again. Nothing else ever comes out: a ticket // run's branch keeps its work, and the pull request says exactly what // fails (`wait_on_person`), never as a wait. + // A mode CoderHelm's own commits dropped is its own cause: put back, + // and CI decides again; never a person's to look at. + if let Some(done) = + mode_cause(state, msg, ticket_msg, github, pr, usage, duration, events).await + { + return done; + } if let Some(note) = take_out_failing_bumps(state, msg, ticket_msg, github, pr, excerpt).await { mark_events_processed(state, &msg.run_id, events).await; super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; @@ -10526,6 +10560,115 @@ async fn send_resume_message(state: &WorkerState, msg: &ResumeMessage, delay: u6 .is_ok() } +/// The mode diagnosis of a red pull request (`mode_repair::on_red`), as +/// the CI loop acts on it: `None` when CoderHelm dropped no mode on the +/// branch, so the loop goes on. Modes put back: the run waits on CI for +/// the restore commit. Modes CoderHelm dropped and couldn't put back yet: +/// its own problem (an internal alert and the run page's line), the run +/// waits on CI and is resumed to try again. Never `failed`, never a +/// person's to-do. +#[allow(clippy::too_many_arguments)] +async fn mode_cause( + state: &WorkerState, + msg: &ResumeMessage, + ticket_msg: &TicketMessage, + github: &GitHubClient, + pr: &PrRef<'_>, + usage: &TokenUsage, + duration: u64, + events: &[RunEvent], +) -> Option>> { + let base = github + .get_pull_request(pr.owner, pr.repo, pr.number) + .await + .ok()?["base"]["ref"] + .as_str()? + .to_string(); + let stuck = match super::mode_repair::on_red(github, pr.owner, pr.repo, &base, pr.branch).await + { + super::mode_repair::ModeFix::Nothing => return None, + super::mode_repair::ModeFix::Fixed(note) => { + super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; + None + } + super::mode_repair::ModeFix::Stuck(why) => Some(why), + }; + mark_events_processed(state, &msg.run_id, events).await; + if let Some(why) = &stuck { + let p = common::person_only::OwnProblem { + subject: common::person_only::OwnSubject::Tooling, + text: why.clone(), + }; + super::own_problems::record(state, &msg.team_id, &msg.run_id, &p).await; + } + let waiting = set_run_awaiting_ci( + state, + ticket_msg, + &msg.run_id, + pr.url, + pr.number, + pr.branch, + usage, + duration, + ) + .await; + if stuck.is_some() && matches!(waiting, Ok(true)) { + send_delayed_resume(state, msg, 300).await; + } + Some(waiting.map(|_| ())) +} + +/// A run that ended on red CI (its error kind `red_ci`) whose pull +/// request just got back the file modes CoderHelm's own commits dropped +/// (`mode_repair`) goes back to `awaiting_ci` and is resumed, so CI on the +/// repaired head decides again. False when the run isn't such a run any +/// more (one conditional write: two sweeps never resume it twice). +pub(crate) async fn resume_after_mode_repair( + state: &WorkerState, + team_id: &str, + run_id: &str, + installation_id: u64, +) -> bool { + let now = chrono::Utc::now().to_rfc3339(); + let back = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .condition_expression("#s = :failed AND #k = :red") + .update_expression( + "SET #s = :s, status_run_id = :sri, current_pass = :s, updated_at = :t REMOVE #e, #k", + ) + .expression_attribute_names("#s", "status") + .expression_attribute_names("#e", common::run_ending::FIELD_ENDING) + .expression_attribute_names("#k", common::run_recovery::FIELD_ERROR_KIND) + .expression_attribute_values(":failed", attr_s(common::run_status::FAILED)) + .expression_attribute_values(":red", attr_s(RED_CI_KIND)) + .expression_attribute_values(":s", attr_s(common::run_status::AWAITING_CI)) + .expression_attribute_values( + ":sri", + common::run_ending::working(common::run_ending::Working::AwaitingCi, run_id).sri_attr(), + ) + .expression_attribute_values(":t", attr_s(&now)) + .send() + .await; + if back.is_err() { + return false; + } + let msg = ResumeMessage { + team_id: team_id.to_string(), + run_id: run_id.to_string(), + installation_id, + ..Default::default() + }; + // CI starts on the restore commit; the resume reads its result. + send_resume_message(state, &msg, 120).await +} + +/// The `run_ending` kind a red CI hand-off is written with. +pub(crate) const RED_CI_KIND: &str = "red_ci"; + /// A fix that failed on a transient model error is sent again later (the /// one requeue policy, [`common::model_retry::requeue_delay`]) instead of /// completing the run with the fix unapplied. False when the error isn't From 17f1854db05d65af9e573d96408bdb21d3ed2cb6 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 4 Dec 2026 16:05:38 -0500 Subject: [PATCH 2/5] Name the own-modes case xq: xo is another open case's id --- ...o_own_modes_never_red_ci.md => xq_own_modes_never_red_ci.md} | 2 +- ...o_own_modes_never_red_ci.rs => xq_own_modes_never_red_ci.rs} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename docs/incidents/{xo_own_modes_never_red_ci.md => xq_own_modes_never_red_ci.md} (98%) rename services/worker/src/passes/incidents/{xo_own_modes_never_red_ci.rs => xq_own_modes_never_red_ci.rs} (99%) diff --git a/docs/incidents/xo_own_modes_never_red_ci.md b/docs/incidents/xq_own_modes_never_red_ci.md similarity index 98% rename from docs/incidents/xo_own_modes_never_red_ci.md rename to docs/incidents/xq_own_modes_never_red_ci.md index 890034177..34e9d8031 100644 --- a/docs/incidents/xo_own_modes_never_red_ci.md +++ b/docs/incidents/xq_own_modes_never_red_ci.md @@ -1,4 +1,4 @@ -# xo. `xo_own_modes_never_red_ci` +# xq. `xq_own_modes_never_red_ci` **What happened:** A front-end fix's pull request also listed three shell scripts of the repository's CI as files it changed: a cleanup script, a stub command its tests put on the path, and the test that runs it. Merging the base into the branch had dropped their executable bit (before `xl`). The pull request's script tests failed while the base stayed green on them. The fix rounds ran `chmod +x` in the sandbox, called `restore_file` on the scripts several times, and deleted and wrote them again in a batch write. None of it reached the mode. After five rounds the run ended failed on red CI and was handed to a person, for a cause CoderHelm made itself. diff --git a/services/worker/src/passes/incidents/xo_own_modes_never_red_ci.rs b/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs similarity index 99% rename from services/worker/src/passes/incidents/xo_own_modes_never_red_ci.rs rename to services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs index a96d47d54..595ebaf5c 100644 --- a/services/worker/src/passes/incidents/xo_own_modes_never_red_ci.rs +++ b/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs @@ -1,4 +1,4 @@ -//! xo. A front-end fix's pull request also listed three shell scripts of +//! xq. A front-end fix's pull request also listed three shell scripts of //! the repository's CI as files it changed (a cleanup script, a stub //! command its tests put on the path, and the test that runs it). Merging //! the base into the branch had dropped their executable bit, before file From deed81fd370015072cba0162a39997fc21c1339f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 4 Dec 2026 17:02:18 -0500 Subject: [PATCH 3/5] Register the new tools, keep the diagnosis ahead of the gap read, update the cases it moved --- services/common/src/agent_policy/registry.rs | 15 ++++++ services/worker/src/agent/provider.rs | 2 +- services/worker/src/clients/github.rs | 2 +- services/worker/src/passes/implement.rs | 4 +- .../passes/incidents/bm_teams_never_cross.rs | 1 + .../passes/incidents/xl_file_modes_kept.rs | 15 ++++-- .../xp_answers_read_the_other_repo.rs | 3 +- .../incidents/xq_own_modes_never_red_ci.rs | 6 +-- .../worker/src/passes/model_route_eval.rs | 3 ++ services/worker/src/passes/resume.rs | 54 +++++++++---------- 10 files changed, 66 insertions(+), 39 deletions(-) diff --git a/services/common/src/agent_policy/registry.rs b/services/common/src/agent_policy/registry.rs index ee8e32e06..86ef10db0 100644 --- a/services/common/src/agent_policy/registry.rs +++ b/services/common/src/agent_policy/registry.rs @@ -172,6 +172,11 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("get_diff", Risk::Read), ("github_history", Risk::Read), ("search_org", Risk::Read), + // Every repository of the team's installation, offered to every agent + // (`repo_reach`). + ("list_repos", Risk::Read), + ("read_repo_file", Risk::Read), + ("search_repo", Risk::Read), ("github__read_file", Risk::Read), ("github__search_code", Risk::Read), ("github__list_directory", Risk::Read), @@ -262,6 +267,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[ ("edit_file", Risk::Write), ("batch_write", Risk::Write), ("restore_file", Risk::Write), + ("set_mode", Risk::Write), ("run_codegen", Risk::Write), ("run_checks", Risk::Write), ("reproduce_on_base", Risk::Write), @@ -448,6 +454,15 @@ mod tests { assert_eq!(kind_of("confluence_append").0, CallKind::Outbound); } + /// The cross-repository tools every agent is offered are reads the + /// engine knows (their names are constants, out of the scan below). + #[test] + fn cross_repo_tools_are_reads() { + for t in crate::repo_reach::TOOLS { + assert_eq!(Builtin.risk(t), Some(Risk::Read), "{t}"); + } + } + #[test] fn builtins_are_listed_once() { let mut seen = BTreeSet::new(); diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 6af1b09eb..7021da65c 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -459,7 +459,7 @@ async fn converse_as( opts.deadline, opts.effort, observer, - log.as_deref_mut(), + log, form, ) .await; diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 50da81dcb..18edb0f8c 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3802,7 +3802,7 @@ impl GitHubClient { .map_err(fail)?; let message = git_mode::with_trailer(message, std::slice::from_ref(&change)); let commit = self - .put_commit(owner, repo, &message, &tree, &[head.clone()]) + .put_commit(owner, repo, &message, &tree, std::slice::from_ref(&head)) .await .map_err(fail)?; if !self diff --git a/services/worker/src/passes/implement.rs b/services/worker/src/passes/implement.rs index 8b2d5521b..51bf7c9ab 100644 --- a/services/worker/src/passes/implement.rs +++ b/services/worker/src/passes/implement.rs @@ -3095,7 +3095,7 @@ impl<'a> WriteToolExecutor<'a> { self.task_tracker.mark_files_done(&[path]).await; // The mode comes from the same ref as the bytes. let mode = super::mode_repair::restore_mode( - &self.github, + self.github, (&self.owner, &self.repo, &self.branch), path, from_ref, @@ -3121,7 +3121,7 @@ impl<'a> WriteToolExecutor<'a> { } let message = self.commit_message(&format!("Set the mode of {path}")); match super::mode_repair::set_mode_call( - &self.github, + self.github, (&self.owner, &self.repo, &self.branch, &self.base_branch), input, &message, diff --git a/services/worker/src/passes/incidents/bm_teams_never_cross.rs b/services/worker/src/passes/incidents/bm_teams_never_cross.rs index ccc6ee6c9..0c1508149 100644 --- a/services/worker/src/passes/incidents/bm_teams_never_cross.rs +++ b/services/worker/src/passes/incidents/bm_teams_never_cross.rs @@ -331,6 +331,7 @@ fn the_events_table_is_only_reached_through_run_events() { const CACHES: &[(&str, &str)] = &[ ("common/src/agent_policy/registry.rs::REGISTERED", "tool registrations by provider; no team data"), ("common/src/github_grants.rs::KNOWN", "installation id"), + ("worker/src/agent/reach.rs::CACHE", "team id; holds that team's own installation token and repository list"), ("common/src/hybrid/client.rs::TOKENS", "installation id"), ("common/src/hybrid/client.rs::FAILING", "installation id"), ("gateway/src/routes/jira_heal.rs::LAST", "team id; holds only when that team last asked the Jira app to register again"), diff --git a/services/worker/src/passes/incidents/xl_file_modes_kept.rs b/services/worker/src/passes/incidents/xl_file_modes_kept.rs index eafbe071c..aadc64cf6 100644 --- a/services/worker/src/passes/incidents/xl_file_modes_kept.rs +++ b/services/worker/src/passes/incidents/xl_file_modes_kept.rs @@ -458,13 +458,20 @@ fn the_repair_is_claimed_capped_and_never_forced() { let sweep = fn_src(src, "pub async fn sweep("); assert!(sweep.contains("if !claim(state, &c).await")); assert!(sweep.contains("budget.allows(state, c.installation_id, REQUESTS)")); - assert!(sweep.contains("catch_up_picks(all, PER_TEAM, MAX_PRS)")); + // Its own picks since `xq`: every run a pull request can still be open + // under, failed ones first. + assert!(sweep.contains("picks(all, PER_TEAM, MAX_PRS)")); assert!(sweep.contains("own_problems::alert(")); assert!(sweep.contains("add_progress_note(")); let one = fn_src(src, "pub async fn repair_one("); - assert!(one.contains(".fast_forward(owner, repo, branch, head, &commit)")); - assert!(!one.contains("move_with_lease")); - assert!(!one.contains("move_scratch_ref")); + // The write is shared with the CI loop's diagnosis since `xq`. + assert!(one.contains("write_restore(github, owner, repo, branch, head, &mut out)")); + let write = fn_src(src, "pub async fn write_restore("); + for f in [one, write] { + assert!(!f.contains("move_with_lease")); + assert!(!f.contains("move_scratch_ref")); + } + assert!(write.contains(".fast_forward(owner, repo, branch, head, &commit)")); assert_eq!(mode_repair::WINDOW_DAYS, 30); } diff --git a/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs index 19a52c015..84480488f 100644 --- a/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs +++ b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs @@ -263,7 +263,8 @@ fn every_agent_context_reads_the_whole_installation() { } if std::fs::read_to_string(&f) .unwrap_or_default() - .contains("converse_tool_loop(") + .lines() + .any(|l| l.contains("converse_tool_loop(") && !l.contains("fn converse_tool_loop(")) { stray.push(rel); } diff --git a/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs b/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs index 595ebaf5c..77a1c21e5 100644 --- a/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs +++ b/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs @@ -109,8 +109,8 @@ fn a_red_check_from_dropped_modes_is_fixed_by_a_mode_commit_not_handed_off() { restored, vec![ (CLEANUP, EXECUTABLE, "a1"), - (SPEC, EXECUTABLE, "c1"), (STUB, EXECUTABLE, "b1"), + (SPEC, EXECUTABLE, "c1"), ] ); // One commit, named, with nothing but modes in it. @@ -136,8 +136,8 @@ fn a_red_check_from_dropped_modes_is_fixed_by_a_mode_commit_not_handed_off() { ); // In the CI loop: a red check green on the base gets the diagnosis - // before the stall check spends a round or hands anything off, and the - // hand-off itself asks it first. + // before the content-gap read and the stall check spend anything, and + // the hand-off itself asks it first. let run = fn_src(RESUME, "pub async fn run("); let diag = run .find("mode_cause(") diff --git a/services/worker/src/passes/model_route_eval.rs b/services/worker/src/passes/model_route_eval.rs index 9666799bf..8969226dd 100644 --- a/services/worker/src/passes/model_route_eval.rs +++ b/services/worker/src/passes/model_route_eval.rs @@ -770,6 +770,9 @@ impl MemRepo<'_> { }; format!("Restored {path} to the base branch.") } + "set_mode" => { + format!("`{path}` already has that mode on the branch; nothing was committed.") + } "get_diff" => { let mut out = vec![]; for (p, c) in files.iter() { diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index f53fe1d72..68b5aa75b 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -2973,6 +2973,33 @@ pub async fn run( repair.note() ); } + // Red on a check that is green on the base: before any model round, + // the files the pull request changes are compared with the base, and + // a mode CoderHelm's own commits dropped is put back in one commit + // (`mode_repair::on_red`). A sandbox `chmod` never reached the + // commit, and a restore once wrote every file plain. + if failing_wf.iter().any(|c| !on_base.contains(c)) { + if let Some(done) = mode_cause( + state, + &msg, + &ticket_msg, + &github, + &PrRef { + owner: &repo_owner, + repo: &repo_name, + branch: &branch, + number: pr_number, + url: &pr_url, + }, + &usage, + wall_clock_secs(created_at, &start), + &events, + ) + .await + { + return done; + } + } // A red check that names missing content, data or a migration is // read before any fix round, so it never spends the budget // (`common::content_gap`): a failing test that waits only on the @@ -3054,33 +3081,6 @@ pub async fn run( .await; } } - // Red on a check that is green on the base: before any model round, - // the files the pull request changes are compared with the base, and - // a mode CoderHelm's own commits dropped is put back in one commit - // (`mode_repair::on_red`). A sandbox `chmod` never reached the - // commit, and a restore once wrote every file plain. - if failing_wf.iter().any(|c| !on_base.contains(c)) { - if let Some(done) = mode_cause( - state, - &msg, - &ticket_msg, - &github, - &PrRef { - owner: &repo_owner, - repo: &repo_name, - branch: &branch, - number: pr_number, - url: &pr_url, - }, - &usage, - wall_clock_secs(created_at, &start), - &events, - ) - .await - { - return done; - } - } // Halt-on-no-progress: if the SAME failure keeps recurring, the fixes // aren't working (noop commits, placeholder stubs, wrong fixes). Stop // churning the PR and end on CoderHelm's own typed stop with what From 6c3494835072976ba412b70bf66ba499e6180163 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 4 Dec 2026 22:05:05 -0500 Subject: [PATCH 4/5] Hold only first-person blindness claims, never edit code or data, bound stuck repairs The guard reads first-person claims only (I, we, CoderHelm, the agent): sentences about the code or the product pass untouched. It reads prose lines only: fenced code, data lines and structured output are never read or edited. A look-first retry that fails or runs out of time keeps the first answer and the history it came from. The claim check is part of person_text itself. A stuck mode repair retries while the tries put more back; after three tries with no progress it stops, records why once as its own problem, and the run waits on CI. A sweep whose branch moved gives its claim back. A failed installation read is kept for seconds, not minutes, and a comparison cut at one page says so. --- .../xp_answers_read_the_other_repo.md | 4 +- docs/incidents/xq_own_modes_never_red_ci.md | 4 +- services/common/src/rendered.rs | 20 +-- services/common/src/repo_reach.rs | 150 ++++++++++++++---- services/worker/src/agent/provider.rs | 25 ++- services/worker/src/agent/reach.rs | 49 +++++- services/worker/src/clients/github.rs | 13 +- .../xp_answers_read_the_other_repo.rs | 21 ++- .../incidents/xq_own_modes_never_red_ci.rs | 49 +++++- services/worker/src/passes/mode_repair.rs | 93 +++++++++-- services/worker/src/passes/resume.rs | 105 ++++++++++-- 11 files changed, 444 insertions(+), 89 deletions(-) diff --git a/docs/incidents/xp_answers_read_the_other_repo.md b/docs/incidents/xp_answers_read_the_other_repo.md index 19b2aae43..00c5c3c1c 100644 --- a/docs/incidents/xp_answers_read_the_other_repo.md +++ b/docs/incidents/xp_answers_read_the_other_repo.md @@ -8,7 +8,7 @@ - Every worker model loop that is offered tools (the coder, every fix round, the reviewer, ticket replies, triage, skills) is also offered `list_repos`, `read_repo_file` and `search_repo`, read only, over every repository of the team's GitHub installation. They are added in the one place every worker loop starts, and a source scan fails on a worker loop that goes around it. Chat and team agents read the same repositories through their code tools. - Every such system prompt says the team's whole installation is readable, and to look before answering. -- Text a person reads that claims CoderHelm can't see, open, access, read or confirm something is rejected before it is posted, unless a tool call in that same turn returned a refusal; then the line must name the repository or path and the refusal. A loop's answer that fails is sent back once to look with the tools, and what still fails is taken out. The person-text check and the reply composer hold the same rule. +- Text a person reads in which CoderHelm says, in the first person, that it can't see, open, access, read or confirm something is rejected before it is posted, unless a tool call in that same turn returned a refusal; then the line must name the repository or path and the refusal. Sentences about the code or the product are never read as such a claim. A loop's answer that fails is sent back once to look with the tools; a retry that fails or runs out of time never replaces the answer, and what still fails is taken out of the prose only. Code, data and structured output are never edited. The person-text check and the reply composer hold the same rule. - A source scan fails on any prompt that tells the model it is limited to one repository. -**Where it's enforced:** `common::repo_reach::{defs, call, prompt_for, claim, allowed, strip, look_first, refusal_in}`, `common::repo_read::GitHubHost::installation_repos`, `common::rendered::{person_text, person_text_after}`, `common::reply_compose::finish`, the worker's `agent::reach::{offer, prompt, Exec, access}` in `agent::provider::converse_as`, Chat's `brain::system_prompt` and `chat_agent::run`, and `tool_registry::BUILTIN`. +**Where it's enforced:** `common::repo_reach::{defs, call, prompt_for, claim, allowed, strip, look_first, refusal_in}`, `common::repo_read::GitHubHost::installation_repos`, `common::rendered::person_text`, `common::reply_compose::finish`, the worker's `agent::reach::{offer, prompt, Exec, access, kept_answer}` in `agent::provider::converse_as`, Chat's `brain::system_prompt` and `chat_agent::run`, and `tool_registry::BUILTIN`. diff --git a/docs/incidents/xq_own_modes_never_red_ci.md b/docs/incidents/xq_own_modes_never_red_ci.md index 34e9d8031..25c6f6b1c 100644 --- a/docs/incidents/xq_own_modes_never_red_ci.md +++ b/docs/incidents/xq_own_modes_never_red_ci.md @@ -4,6 +4,6 @@ **Why:** `restore_file` took the bytes from the ref and the mode from the branch, which had already lost it. No tool set a mode. Nothing compared the pull request's modes with the base when its checks were red and the base's green. The repair sweep of `xl` compared each CoderHelm commit with its parent only, where a delete followed by a write shows no drop. It took its runs from the description catch-up's picks, which skip runs in flight and every run whose description was already rebuilt, and it never set a failed run going again. -**The guarantee:** A check red on the pull request and green on the base first gets the mode diagnosis. Every file the pull request changes is compared with the merge base, and an executable, symbolic link or submodule that CoderHelm's commits turned into a plain file is put back in one commit, with no model round, and CI decides again. A mode CoderHelm dropped that it can't put back yet is its own problem: an internal alert, the run page's line, and a retry. It is never `failed` on red CI and never a person's to-do. A path a person's commit changed is theirs and is left. `restore_file` restores the mode from the same ref as the bytes. `set_mode` sets a file's executable bit as a commit, or puts back the base's mode, and refuses symbolic links and submodules. A `chmod` in the sandbox says it never reaches the commit and names `set_mode`. The repair sweep compares each pull request with its base too, reads runs of every status a pull request can still be open under (failed runs first, runs in flight included), and resumes a run that ended on red CI once its modes are back. +**The guarantee:** A check red on the pull request and green on the base first gets the mode diagnosis. Every file the pull request changes is compared with the merge base, and an executable, symbolic link or submodule that CoderHelm's commits turned into a plain file is put back in one commit, with no model round, and CI decides again. A mode CoderHelm dropped that it can't put back yet is its own problem: an internal alert, the run page's line, and a retry while the tries make progress. After three tries in a row that put nothing more back it stops retrying, records why once, and the run waits on CI. It is never `failed` on red CI and never a person's to-do. A sweep whose branch moved during the repair gives its claim back, so the pull request is read again. A path a person's commit changed is theirs and is left. `restore_file` restores the mode from the same ref as the bytes. `set_mode` sets a file's executable bit as a commit, or puts back the base's mode, and refuses symbolic links and submodules. A `chmod` in the sandbox says it never reaches the commit and names `set_mode`. The repair sweep compares each pull request with its base too, reads runs of every status a pull request can still be open under (failed runs first, runs in flight included), and resumes a run that ended on red CI once its modes are back. -**Where it's enforced:** `clients::git_mode::{mode_move, against_base}`, `GitHubClient::{set_mode, merge_base_and_files}`, `mode_repair::{base_plan, against_base, on_red, write_restore, picks, reads, set_mode_tool, set_mode_call, restore_mode, sweep, repair_one}`, `resume::{mode_cause, hand_off_red_ci, resume_after_mode_repair}`, the `restore_file` and `set_mode` arms of the coder's and the feedback round's executors, and `common::coder_shell::CHMOD`. +**Where it's enforced:** `clients::git_mode::{mode_move, against_base}`, `GitHubClient::{set_mode, merge_base_and_files}`, `mode_repair::{stuck_step, base_plan, against_base, on_red, write_restore, picks, reads, set_mode_tool, set_mode_call, restore_mode, sweep, repair_one}`, `resume::{mode_cause, hand_off_red_ci, resume_after_mode_repair}`, the `restore_file` and `set_mode` arms of the coder's and the feedback round's executors, and `common::coder_shell::CHMOD`. diff --git a/services/common/src/rendered.rs b/services/common/src/rendered.rs index 608d57a87..bd8afbe50 100644 --- a/services/common/src/rendered.rs +++ b/services/common/src/rendered.rs @@ -183,18 +183,6 @@ static RUN_ON: LazyLock = /// colons. Code spans are taken out first, so a command or a name in /// backticks never trips it. pub fn person_text(text: &str) -> Option { - person_text_after(text, &[]) -} - -/// [`person_text`] for text written in a turn whose tool calls returned -/// `refusals`: a line saying a read was refused stands when it names that -/// repository or path and the refusal (`repo_reach::allowed`). -pub fn person_text_after(text: &str, refusals: &[crate::repo_reach::Refusal]) -> Option { - if let Err(line) = crate::repo_reach::allowed(text, refusals) { - return Some(format!( - "a claim CoderHelm can't see or confirm something, with no refusal to show for it: {line}" - )); - } if let Some(gap) = empty_slot(text) { return Some(gap); } @@ -214,6 +202,14 @@ pub fn person_text_after(text: &str, refusals: &[crate::repo_reach::Refusal]) -> return Some(format!("words for the model (\"{p}\": {why}): {body}")); } } + // Every repository of the team's installation is readable, and a + // text CoderHelm writes for a person carries no refusal from a + // tool, so a first-person claim it can't see something is a guess. + if let Some(c) = crate::repo_reach::claim(body) { + return Some(format!( + "a claim CoderHelm can't see or confirm something: {c}" + )); + } if body.contains("(s)") { return Some(format!("a template plural: {body}")); } diff --git a/services/common/src/repo_reach.rs b/services/common/src/repo_reach.rs index 34d22fc76..9e87eea7a 100644 --- a/services/common/src/repo_reach.rs +++ b/services/common/src/repo_reach.rs @@ -279,20 +279,27 @@ pub fn refusal_in(name: &str, input: &Value, error: &str) -> Option { // ── The guard on what people read ────────────────────────────────────────── -/// A sentence saying CoderHelm can't see, open, access or read something, -/// or couldn't confirm it because of where it lives. +/// A sentence in which CoderHelm says, in the first person, that it can't +/// see, open, access, read or confirm something: every alternative has its +/// subject (I, we, CoderHelm, the agent). A sentence about the code or the +/// product ("the function can't access the cache", "users cannot open the +/// page", "anonymous users have no access to /admin") is never one. static CLAIM: LazyLock = LazyLock::new(|| { - let not = r"(?:can['’]?t|cannot|can not|couldn['’]?t|could not|am unable to|was unable to|unable to|am not able to|wasn['’]?t able to|not able to|have no way to)"; + let not = r"(?:can['’]?t|cannot|can not|couldn['’]?t|could not|am unable to|was unable to|were unable to|unable to|am not able to|wasn['’]?t able to|weren['’]?t able to|not able to|have no way to|had no way to)"; let lack = r"(?:don['’]?t|do not|doesn['’]?t|does not|didn['’]?t|did not)\s+have"; let who = r"(?:I|we|CoderHelm|the agent)"; let alternatives = [ - format!(r"\b{who}\s+{not}\s+(?:\w+\s+){{0,2}}?(?:open|see|access|read|view|reach|inspect|look at|look into|check|confirm|verify)\b"), + format!( + r"\b{who}\s+{not}\s+(?:\w+\s+){{0,2}}?(?:open|see|access|read|view|reach|inspect|look at|look into|check|confirm|verify)\b" + ), format!(r"\b{who}\s+{lack}\s+(?:\w+\s+){{0,2}}?(?:access|visibility|permission)\b"), - r"\bno access to\b".to_string(), - r"\b(?:lives?|sits?)\s+outside\s+(?:of\s+)?(?:this|the current)\s+(?:repo|repository)\b".to_string(), - format!(r"\boutside\s+(?:of\s+)?(?:this|the current)\s+(?:repo|repository),?\s+so\s+{who}\b"), - r"\b(?:couldn['’]?t|could not|can['’]?t|cannot|haven['’]?t|have not)\s+(?:\w+\s+){0,2}?(?:confirm|verify)(?:ed)?\b[^.\n]*\bbecause\b".to_string(), - format!(r"\bso\s+{who}\s+(?:haven['’]?t|have not|couldn['’]?t|could not)\s+(?:confirmed|verified|confirm|verify)\b"), + format!(r"\b{who}\s+(?:have|has|had)\s+no\s+(?:access|visibility)\b"), + format!( + r"\boutside\s+(?:of\s+)?(?:this|the current)\s+(?:repo|repository),?\s+so\s+{who}\b" + ), + format!( + r"\bso\s+{who}\s+(?:haven['’]?t|have not|hasn['’]?t|has not)\s+(?:confirmed|verified)\b" + ), ]; Regex::new(&format!("(?i){}", alternatives.join("|"))).expect("regex") }); @@ -344,24 +351,71 @@ pub fn allowed(text: &str, refusals: &[Refusal]) -> Result<(), String> { Ok(()) } -/// `text` with every sentence [`allowed`] refuses taken out. -pub fn strip(text: &str, refusals: &[Refusal]) -> String { +/// Whether `text` as a whole is structured output (a JSON object or +/// array), which the guard never reads or edits. +pub fn is_structured(text: &str) -> bool { + let t = text.trim(); + (t.starts_with('{') || t.starts_with('[')) && serde_json::from_str::(t).is_ok() +} + +/// The lines of `text` the guard reads, by index: prose only. Fenced code +/// blocks and lines that look like data (JSON keys and values, list +/// literals, table rows of code) are left out, and structured text has +/// none. +fn prose_lines(text: &str) -> Vec { + if is_structured(text) { + return Vec::new(); + } let mut out = Vec::new(); - for line in text.lines() { - if !CLAIM.is_match(line) { + let mut fenced = false; + for (i, line) in text.lines().enumerate() { + let t = line.trim_start(); + if t.starts_with("```") || t.starts_with("~~~") { + fenced = !fenced; + continue; + } + if fenced || line.starts_with(" ") || line.starts_with('\t') { + continue; + } + let data = t.starts_with('{') + || t.starts_with('[') + || t.starts_with('"') + || t.starts_with("//") + || t.starts_with('#') && !t.starts_with("# ") && !t.starts_with("##"); + if !data { + out.push(i); + } + } + out +} + +/// `text` with every prose sentence [`allowed`] refuses taken out. Code, +/// data and structured output are returned exactly as they were. +pub fn strip(text: &str, refusals: &[Refusal]) -> String { + let prose = prose_lines(text); + let lines: Vec<&str> = text.split('\n').collect(); + let mut out: Vec = Vec::with_capacity(lines.len()); + let mut changed = false; + for (i, line) in lines.iter().enumerate() { + if !prose.contains(&i) || !CLAIM.is_match(line) { out.push(line.to_string()); continue; } - let kept: Vec = sentences(line) + let kept: Vec = sentences_of(line) .into_iter() .filter(|s| !CLAIM.is_match(s) || names_refusal(s, refusals)) .map(|s| s.trim().to_string()) .collect(); + let indent = &line[..line.len() - line.trim_start().len()]; let kept = kept.join(" "); + changed = true; if !kept.trim().is_empty() { - out.push(kept); + out.push(format!("{indent}{kept}")); } } + if !changed { + return text.to_string(); + } out.join("\n") } @@ -376,23 +430,32 @@ pub fn look_first(sentence: &str) -> String { ) } -/// The sentences of `text`, each with its closing mark: cut after `.`, -/// `!` or `?` followed by a space, and at each line break. +/// The prose sentences of `text`, each with its closing mark: cut after +/// `.`, `!` or `?` followed by a space, and at each line break. Code and +/// data lines are left out ([`prose_lines`]). fn sentences(text: &str) -> Vec { + let prose = prose_lines(text); + text.lines() + .enumerate() + .filter(|(i, _)| prose.contains(i)) + .flat_map(|(_, l)| sentences_of(l)) + .collect() +} + +/// One line's sentences. +fn sentences_of(line: &str) -> Vec { let mut out = Vec::new(); - for line in text.lines() { - let mut cur = String::new(); - let mut chars = line.chars().peekable(); - while let Some(c) = chars.next() { - cur.push(c); - if matches!(c, '.' | '!' | '?') && chars.peek().is_some_and(|n| n.is_whitespace()) { - out.push(std::mem::take(&mut cur)); - } - } - if !cur.trim().is_empty() { - out.push(cur); + let mut cur = String::new(); + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + cur.push(c); + if matches!(c, '.' | '!' | '?') && chars.peek().is_some_and(|n| n.is_whitespace()) { + out.push(std::mem::take(&mut cur)); } } + if !cur.trim().is_empty() { + out.push(cur); + } out } @@ -415,9 +478,10 @@ mod tests { "The 2 comes from the storefront's label helper. I can't open that helper from this repo, so I haven't confirmed the rounding.", "CoderHelm doesn't have access to the billing service.", "I don't have access to that repository.", - "The helper lives outside this repo.", + "The helper is outside this repo, so I can't tell how it rounds.", "I couldn't confirm it because the code is in another repository.", "We cannot see the mobile app's code.", + "CoderHelm has no access to the storefront.", ] { assert!(claim(t).is_some(), "{t}"); assert!(allowed(t, &[]).is_err(), "{t}"); @@ -433,11 +497,39 @@ mod tests { "This change is outside the scope of the ticket.", "The cause is outside this repository: the queue's timeout is set in the account.", "`deploy` waits on a change outside this repository.", + "The function can't access the cache before it is warmed.", + "The endpoint can't verify the signature because the secret is empty.", + "Users can't confirm their email because the link expired.", + "Anonymous users have no access to /admin.", + "The queue timeout lives outside this repository.", + "The worker couldn't read the file because its path was relative.", ] { assert_eq!(claim(t), None, "{t}"); + assert_eq!(allowed(t, &[]), Ok(()), "{t}"); + assert_eq!(strip(t, &[]), t, "{t}"); } } + #[test] + fn code_and_structured_output_are_never_edited() { + let json = r#"{"body": "First. I couldn't verify the cache. Third."}"#; + assert_eq!(strip(json, &[]), json); + assert!(serde_json::from_str::(&strip(json, &[])).is_ok()); + let pretty = "{\n \"finding\": \"I can't open the helper.\",\n \"line\": 3\n}"; + assert_eq!(strip(pretty, &[]), pretty); + assert_eq!(allowed(pretty, &[]), Ok(())); + let fenced = "The cache warms on start.\n```rust\n // we can't read this until the lock is held\n let x = 1;\n```\nDone."; + assert_eq!(strip(fenced, &[]), fenced); + // Prose around the code is still read, and only the claim goes. + let mixed = format!("{fenced}\nI can't open the helper from here."); + assert_eq!(strip(&mixed, &[]), fenced); + // An indented prose line keeps its indentation. + assert_eq!( + strip("- The age rounds. I can't see the helper.", &[]), + "- The age rounds." + ); + } + #[test] fn a_real_refusal_named_lets_the_line_through() { let r = [refusal("acme/storefront", "src/labels.ts", 404)]; diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 7021da65c..746fd68ad 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -435,17 +435,22 @@ async fn converse_as( .await; // An answer saying CoderHelm can't see or confirm something, with no // refusal from this loop's tools to show for it, is sent back once to - // look first; what still says so is taken out before anyone reads it - // (`common::repo_reach`). - if let Ok(text) = &out { - if let Err(sentence) = common::repo_reach::allowed(text, &exec.refusals()) { + // look first; what still says so is taken out of its prose before + // anyone reads it (`common::repo_reach`). Structured output and code + // are never read or edited, and a retry that fails or runs out of time + // never replaces the answer the loop gave. + if let Ok(first) = &out { + if let Err(sentence) = common::repo_reach::allowed(first, &exec.refusals()) { tracing::warn!(sentence = %sentence, "An answer claimed it couldn't see something it never tried to read; asking it to look first"); + let first = first.clone(); + let mut retry = None; if reaches && form == super::llm::AnswerForm::Auto { + let before = messages.len(); messages.push(( "user".to_string(), vec![serde_json::json!({"type": "text", "text": common::repo_reach::look_first(&sentence)})], )); - out = anthropic::converse_tool_loop( + let again = anthropic::converse_tool_loop( &client, model_id, &system, @@ -462,9 +467,15 @@ async fn converse_as( log, form, ) - .await; + .await + .map_err(|e| e.to_string()); + if !super::reach::usable_retry(&again) { + // The history goes back to the answer that is kept. + messages.truncate(before); + } + retry = Some(again); } - out = out.map(|t| common::repo_reach::strip(&t, &exec.refusals())); + out = Ok(super::reach::kept_answer(&first, retry, &exec.refusals())); } } if own_log { diff --git a/services/worker/src/agent/reach.rs b/services/worker/src/agent/reach.rs index 670fa6635..86d11db82 100644 --- a/services/worker/src/agent/reach.rs +++ b/services/worker/src/agent/reach.rs @@ -25,6 +25,9 @@ static HTTP: GuardedHttps = GuardedHttps; /// How long a team's token and repository list are kept between loops. const KEEP: Duration = Duration::from_secs(600); +/// How long a failed read of them is kept: a passing GitHub error turns the +/// tools off for a moment, not for ten minutes. +const KEEP_FAILED: Duration = Duration::from_secs(30); /// What a team's loops read with: the installation token and every /// repository it can read. @@ -57,7 +60,8 @@ pub async fn access(state: &crate::WorkerState, team: &str) -> Result { } } +/// Whether a look-first retry's result can stand as the answer: an answer +/// with words in it, not an error and not the loop's out-of-time reply. +pub fn usable_retry(retry: &Result) -> bool { + matches!(retry, Ok(t) if !t.trim().is_empty() && t != super::anthropic::TIMED_OUT_REPLY) +} + +/// The answer a loop gives after its guard: the retry's when it is usable +/// ([`usable_retry`]), else the first answer, which is never lost; either +/// with what still claims blindness taken out of its prose. +pub fn kept_answer( + first: &str, + retry: Option>, + refusals: &[Refusal], +) -> String { + let answer = match retry { + Some(Ok(t)) if usable_retry(&Ok(t.clone())) => t, + _ => first.to_string(), + }; + repo_reach::strip(&answer, refusals) +} + #[cfg(test)] mod tests { use super::*; @@ -231,6 +256,28 @@ mod tests { assert_eq!(prompt(&p), p); } + #[test] + fn a_failed_retry_keeps_the_first_answer() { + let first = "The label rounds months down. I can't open the helper."; + let kept = "The label rounds months down."; + assert_eq!(kept_answer(first, None, &[]), kept); + assert_eq!(kept_answer(first, Some(Err("network".into())), &[]), kept); + assert_eq!( + kept_answer( + first, + Some(Ok(super::super::anthropic::TIMED_OUT_REPLY.to_string())), + &[] + ), + kept + ); + assert_eq!(kept_answer(first, Some(Ok(" ".into())), &[]), kept); + let better = "`src/format/ages.ts` line 2 raises 0 to 1."; + assert_eq!(kept_answer(first, Some(Ok(better.into())), &[]), better); + // Structured output passes untouched. + let json = r#"{"summary": "I can't open the helper."}"#; + assert_eq!(kept_answer(json, None, &[]), json); + } + #[test] fn a_tools_404_is_a_refusal() { let r = repo_reach::refusal_in( diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 18edb0f8c..52906daa3 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -3832,7 +3832,7 @@ impl GitHubClient { .as_str() .ok_or("the comparison named no merge base")? .to_string(); - let files = data["files"] + let files: Vec = data["files"] .as_array() .map(|arr| { arr.iter() @@ -3840,6 +3840,14 @@ impl GitHubClient { .collect() }) .unwrap_or_default(); + if files.len() >= COMPARE_FILES_PAGE { + tracing::warn!( + owner, + repo, + files = files.len(), + "The comparison lists one page of files; paths past it aren't read" + ); + } Ok((mb, files)) } @@ -6867,6 +6875,9 @@ pub struct DirEntry { pub path: String, } +/// The most files GitHub's comparison lists in one reply. +pub const COMPARE_FILES_PAGE: usize = 300; + /// What [`GitHubClient::set_mode`] sets a path to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SetModeTo<'a> { diff --git a/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs index 84480488f..92b59e432 100644 --- a/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs +++ b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs @@ -128,17 +128,26 @@ fn the_guess_is_rejected_before_posting() { assert!(why.contains("I can't open that formatter"), "{why}"); assert!(common::rendered::person_text(GUESS) .unwrap() - .contains("no refusal to show for it")); + .contains("a claim CoderHelm can't see")); let left = repo_reach::strip(GUESS, &[]); assert!(!left.contains("can't open"), "{left}"); assert!(left.starts_with("The 1 comes from"), "{left}"); for t in [ "CoderHelm doesn't have access to the storefront repository.", - "That formatter lives outside this repo.", + "That formatter is outside this repo, so I can't tell how it rounds.", "I couldn't confirm the rounding because it is in another repository.", ] { assert!(repo_reach::allowed(t, &[]).is_err(), "{t}"); } + // Sentences about the code or the product are never a claim. + for t in [ + "The formatter can't access the locale before the page loads.", + "Parents cannot open the card until the age range is set.", + "Guests have no access to the program's waitlist.", + ] { + assert_eq!(repo_reach::allowed(t, &[]), Ok(()), "{t}"); + assert_eq!(common::rendered::person_text(t), None, "{t}"); + } let nudge = repo_reach::look_first(&why); assert!(nudge.contains("read_repo_file") && nudge.contains("exact file and line")); } @@ -172,10 +181,7 @@ async fn a_real_refusal_lets_the_honest_line_through() { let honest = format!("I couldn't read `{missing}` in {SITE}: the read returned 404 not found."); assert_eq!(repo_reach::allowed(&honest, &refusals), Ok(())); - assert_eq!( - common::rendered::person_text_after(&honest, &refusals), - None - ); + assert_eq!(repo_reach::strip(&honest, &refusals), honest); // The vague guess stays a guess even beside a refusal it doesn't name. assert!(repo_reach::allowed(GUESS, &refusals).is_err()); @@ -237,7 +243,8 @@ fn every_agent_context_reads_the_whole_installation() { "super::reach::Exec::new(", "common::repo_reach::allowed(", "common::repo_reach::look_first(", - "common::repo_reach::strip(", + "super::reach::kept_answer(", + "messages.truncate(before)", ] { assert!(loop_.contains(part), "{part}"); } diff --git a/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs b/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs index 77a1c21e5..7303ea745 100644 --- a/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs +++ b/services/worker/src/passes/incidents/xq_own_modes_never_red_ci.rs @@ -157,7 +157,7 @@ fn a_red_check_from_dropped_modes_is_fixed_by_a_mode_commit_not_handed_off() { // own problem tried again; never a failed run. let cause = fn_src(RESUME, "async fn mode_cause("); for part in [ - "mode_repair::on_red(", + "mr::on_red(", "own_problems::record(", "set_run_awaiting_ci(", "send_delayed_resume(", @@ -355,3 +355,50 @@ fn the_sweep_reaches_failed_runs_and_resumes_them() { assert!(resume.contains("AWAITING_CI")); assert!(resume.contains("send_resume_message(")); } + +/// A repair that can't be put back is tried again only while the tries +/// make progress: after three tries in a row with nothing more put back it +/// stops retrying, its own problem recorded once with why, and the run +/// waits on CI. It is never handed to a person. A raced sweep gives its +/// claim back so the pull request is read again. +#[test] +fn a_stuck_repair_retries_while_it_makes_progress_then_stops() { + use mode_repair::{stuck_step, StuckStep, MAX_STUCK_TRIES}; + let three: Vec = [CLEANUP, STUB, SPEC].map(String::from).to_vec(); + let why = || "the branch moved while it was being put back".to_string(); + let mut prev = None; + for n in 1..=MAX_STUCK_TRIES { + match stuck_step(prev.as_ref(), three.clone(), why()) { + StuckStep::Retry(s) => { + assert_eq!(s.tries, n); + prev = Some(s); + } + other => panic!("try {n}: {other:?}"), + } + } + let stopped = match stuck_step(prev.as_ref(), three.clone(), why()) { + StuckStep::Stop { state, first } => { + assert!(first && state.stopped); + assert_eq!(state.why, why()); + state + } + other => panic!("{other:?}"), + }; + // Recorded once: a later look stops again without a second record. + match stuck_step(Some(&stopped), three.clone(), why()) { + StuckStep::Stop { first, .. } => assert!(!first), + other => panic!("{other:?}"), + } + // Progress (fewer paths left) starts the count again. + match stuck_step(Some(&stopped), vec![SPEC.to_string()], why()) { + StuckStep::Retry(s) => assert_eq!(s.tries, 1), + other => panic!("{other:?}"), + } + + let cause = fn_src(RESUME, "async fn mode_cause("); + assert!(cause.contains("mr::stuck_step(")); + assert!(cause.contains("if retry && matches!(waiting, Ok(true))")); + let sweep = fn_src(REPAIR, "pub async fn sweep("); + let raced = sweep.find("if r.raced {").expect("a raced repair"); + assert!(sweep[raced..].find("release(state, &c)").unwrap() < 200); +} diff --git a/services/worker/src/passes/mode_repair.rs b/services/worker/src/passes/mode_repair.rs index e4f0fd2f4..15ff85135 100644 --- a/services/worker/src/passes/mode_repair.rs +++ b/services/worker/src/passes/mode_repair.rs @@ -371,9 +371,66 @@ pub enum ModeFix { Nothing, /// The modes were put back in one commit: the run page's line. Fixed(String), - /// CoderHelm dropped a mode and couldn't put it back yet: why. Its own - /// problem, tried again; never a person's. - Stuck(String), + /// CoderHelm dropped a mode and couldn't put it back yet: why, and the + /// paths still to put back. Its own problem, tried again while the + /// tries make progress ([`stuck_step`]); never a person's. + Stuck { why: String, paths: Vec }, +} + +/// The run attribute holding a stuck repair's tries ([`StuckState`]). +pub const STUCK_FIELD: &str = "mode_stuck"; +/// Tries in a row without progress before a stuck repair stops retrying. +pub const MAX_STUCK_TRIES: u32 = 3; + +/// A stuck repair's record on the run: tries in a row without progress, +/// the paths still to put back, the last why, and whether it stopped. +#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct StuckState { + pub tries: u32, + pub paths: Vec, + pub why: String, + pub stopped: bool, +} + +/// What the CI loop does with a stuck repair. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StuckStep { + /// Try again later, with this record. + Retry(StuckState), + /// No progress in [`MAX_STUCK_TRIES`] tries: stop retrying, with this + /// record. `first`: this is the stop (its own problem is recorded once). + Stop { state: StuckState, first: bool }, +} + +/// The next step for a stuck repair from the run's record (`prev`) and +/// this try's paths and why. A try that leaves fewer paths to put back is +/// progress and starts the count again; otherwise the count goes on, and +/// past [`MAX_STUCK_TRIES`] the repair stops retrying, saying why. +pub fn stuck_step(prev: Option<&StuckState>, paths: Vec, why: String) -> StuckStep { + let progress = prev.is_none_or(|p| paths.len() < p.paths.len()); + let tries = if progress { + 1 + } else { + prev.map_or(0, |p| p.tries) + 1 + }; + if tries <= MAX_STUCK_TRIES { + return StuckStep::Retry(StuckState { + tries, + paths, + why, + stopped: false, + }); + } + let first = !prev.is_some_and(|p| p.stopped); + StuckStep::Stop { + state: StuckState { + tries, + paths, + why, + stopped: true, + }, + first, + } } /// The diagnosis a pull request red on a check that is green on its base @@ -398,21 +455,27 @@ pub async fn on_red( if r.restored.is_empty() { return ModeFix::Nothing; } - let wanted = r - .restored + let paths: Vec = r.restored.iter().map(|(p, _)| p.clone()).collect(); + let wanted = paths .iter() - .map(|(p, _)| format!("`{p}`")) + .map(|p| format!("`{p}`")) .collect::>() .join(", "); if let Err(e) = write_restore(github, owner, repo, branch, &head, &mut r).await { - return ModeFix::Stuck(format!( - "CoderHelm's commits dropped the mode of {wanted}, and putting it back failed: {e}" - )); + return ModeFix::Stuck { + why: format!( + "CoderHelm's commits dropped the mode of {wanted}, and putting it back failed: {e}" + ), + paths, + }; } if r.raced { - return ModeFix::Stuck(format!( - "CoderHelm's commits dropped the mode of {wanted}; the branch moved while it was being put back" - )); + return ModeFix::Stuck { + why: format!( + "CoderHelm's commits dropped the mode of {wanted}; the branch moved while it was being put back" + ), + paths, + }; } match page_line(&r) { Some(line) if r.commit.is_some() => ModeFix::Fixed(format!( @@ -578,6 +641,12 @@ pub async fn sweep( continue; } }; + // A branch that moved while the modes were being put back is read + // again by a later sweep: the claim is given back. + if r.raced { + release(state, &c).await; + continue; + } if let Some(line) = page_line(&r) { super::add_progress_note(state, &c.team_id, &c.run_id, &line).await; } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 68b5aa75b..f27bbb2e2 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -10584,23 +10584,49 @@ async fn mode_cause( .ok()?["base"]["ref"] .as_str()? .to_string(); - let stuck = match super::mode_repair::on_red(github, pr.owner, pr.repo, &base, pr.branch).await - { - super::mode_repair::ModeFix::Nothing => return None, - super::mode_repair::ModeFix::Fixed(note) => { + use super::mode_repair::{self as mr, ModeFix, StuckStep}; + // Retry: another look in a while. A stop is still CoderHelm's own + // problem: the run waits on CI, never on a person. + let mut retry = false; + match mr::on_red(github, pr.owner, pr.repo, &base, pr.branch).await { + ModeFix::Nothing => return None, + ModeFix::Fixed(note) => { super::add_progress_note(state, &msg.team_id, &msg.run_id, ¬e).await; - None + save_stuck(state, &msg.team_id, &msg.run_id, None).await; + } + ModeFix::Stuck { why, paths } => { + let prev = read_stuck(state, &msg.team_id, &msg.run_id).await; + let own = |text: String| common::person_only::OwnProblem { + subject: common::person_only::OwnSubject::Tooling, + text, + }; + match mr::stuck_step(prev.as_ref(), paths, why) { + StuckStep::Retry(s) => { + let p = own(format!( + "{} (try {} of {})", + s.why, + s.tries, + mr::MAX_STUCK_TRIES + )); + super::own_problems::record(state, &msg.team_id, &msg.run_id, &p).await; + save_stuck(state, &msg.team_id, &msg.run_id, Some(&s)).await; + retry = true; + } + StuckStep::Stop { state: s, first } => { + if first { + let p = own(format!( + "{}. {} tries made no progress, so CoderHelm stopped retrying", + s.why, + mr::MAX_STUCK_TRIES + )); + super::own_problems::record(state, &msg.team_id, &msg.run_id, &p).await; + } + save_stuck(state, &msg.team_id, &msg.run_id, Some(&s)).await; + } + } } - super::mode_repair::ModeFix::Stuck(why) => Some(why), - }; - mark_events_processed(state, &msg.run_id, events).await; - if let Some(why) = &stuck { - let p = common::person_only::OwnProblem { - subject: common::person_only::OwnSubject::Tooling, - text: why.clone(), - }; - super::own_problems::record(state, &msg.team_id, &msg.run_id, &p).await; } + mark_events_processed(state, &msg.run_id, events).await; let waiting = set_run_awaiting_ci( state, ticket_msg, @@ -10612,12 +10638,61 @@ async fn mode_cause( duration, ) .await; - if stuck.is_some() && matches!(waiting, Ok(true)) { + if retry && matches!(waiting, Ok(true)) { send_delayed_resume(state, msg, 300).await; } Some(waiting.map(|_| ())) } +/// A stuck mode repair's record on the run (`mode_repair::StuckState`). +async fn read_stuck( + state: &WorkerState, + team_id: &str, + run_id: &str, +) -> Option { + let item = state + .dynamo + .get_item() + .table_name(&state.config.runs_table_name) + .consistent_read(true) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .projection_expression("#f") + .expression_attribute_names("#f", super::mode_repair::STUCK_FIELD) + .send() + .await + .ok()? + .item?; + let raw = item.get(super::mode_repair::STUCK_FIELD)?.as_s().ok()?; + serde_json::from_str(raw).ok() +} + +/// Saves (or, with `None`, clears) a stuck mode repair's record. +async fn save_stuck( + state: &WorkerState, + team_id: &str, + run_id: &str, + s: Option<&super::mode_repair::StuckState>, +) { + let base = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key("team_id", attr_s(team_id)) + .key("run_id", attr_s(run_id)) + .condition_expression("attribute_exists(run_id)") + .expression_attribute_names("#f", super::mode_repair::STUCK_FIELD); + let req = match s.and_then(|s| serde_json::to_string(s).ok()) { + Some(json) => base + .update_expression("SET #f = :v") + .expression_attribute_values(":v", attr_s(&json)), + None => base.update_expression("REMOVE #f"), + }; + if let Err(e) = req.send().await { + warn!(run_id, error = %e, "Could not keep the stuck mode repair's record"); + } +} + /// A run that ended on red CI (its error kind `red_ci`) whose pull /// request just got back the file modes CoderHelm's own commits dropped /// (`mode_repair`) goes back to `awaiting_ci` and is resumed, so CI on the From 210441cdd6f43bc27f103cf62f635409918e1770 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 4 Dec 2026 22:29:28 -0500 Subject: [PATCH 5/5] Keep private repository content out of replies posted in public repositories Reading stays allowed everywhere. Visibility comes from the installation's repository list; a repository it doesn't name as public counts as private. A reply going to a public repository keeps every private read of its turn and is checked before sending: no verbatim line or code from those reads, no private repository name or path. It is asked for its conclusion in plain words, and what still carries private content is taken out, in prose and structured replies alike, never replaced by a claim that it can't see the code. --- .../xp_answers_read_the_other_repo.md | 3 +- services/common/src/repo_reach.rs | 214 +++++++++++++++++- services/common/src/repo_read.rs | 16 +- services/worker/src/agent/provider.rs | 53 ++++- services/worker/src/agent/reach.rs | 116 +++++++++- .../xp_answers_read_the_other_repo.rs | 160 +++++++++++++ 6 files changed, 545 insertions(+), 17 deletions(-) diff --git a/docs/incidents/xp_answers_read_the_other_repo.md b/docs/incidents/xp_answers_read_the_other_repo.md index 00c5c3c1c..d4b8e4612 100644 --- a/docs/incidents/xp_answers_read_the_other_repo.md +++ b/docs/incidents/xp_answers_read_the_other_repo.md @@ -10,5 +10,6 @@ - Every such system prompt says the team's whole installation is readable, and to look before answering. - Text a person reads in which CoderHelm says, in the first person, that it can't see, open, access, read or confirm something is rejected before it is posted, unless a tool call in that same turn returned a refusal; then the line must name the repository or path and the refusal. Sentences about the code or the product are never read as such a claim. A loop's answer that fails is sent back once to look with the tools; a retry that fails or runs out of time never replaces the answer, and what still fails is taken out of the prose only. Code, data and structured output are never edited. The person-text check and the reply composer hold the same rule. - A source scan fails on any prompt that tells the model it is limited to one repository. +- Content from a private repository never appears in text posted where people outside the installation can read it: a public repository's pull request, issue or comment. Reading stays allowed everywhere, so answers stay right. Repository visibility comes from the installation's repository list, and one it doesn't name as public counts as private. When a reply goes to a public repository, every read of a private repository in that turn is kept, and the reply is checked before it is sent: no line or code from those reads verbatim, and no private repository's name or path. A reply that trips the check is asked to state its conclusion in plain words; what still trips it is taken out, in prose and in structured replies alike. It never turns into "I can't see it". A reply in a private repository may quote what it read, and so may a reply in a public repository quoting another public one; a comment asking to paste a private file gets the conclusion only. -**Where it's enforced:** `common::repo_reach::{defs, call, prompt_for, claim, allowed, strip, look_first, refusal_in}`, `common::repo_read::GitHubHost::installation_repos`, `common::rendered::person_text`, `common::reply_compose::finish`, the worker's `agent::reach::{offer, prompt, Exec, access, kept_answer}` in `agent::provider::converse_as`, Chat's `brain::system_prompt` and `chat_agent::run`, and `tool_registry::BUILTIN`. +**Where it's enforced:** `common::repo_reach::{defs, call, prompt_for, claim, allowed, strip, look_first, refusal_in, leak, redact, conclusion_only}`, `common::repo_read::GitHubHost::{installation_repos, installation_listing}`, `common::rendered::person_text`, `common::reply_compose::finish`, the worker's `agent::reach::{offer, prompt, Exec, access, kept_answer, public_answer, is_public}` in `agent::provider::converse_as`, Chat's `brain::system_prompt` and `chat_agent::run`, and `tool_registry::BUILTIN`. diff --git a/services/common/src/repo_reach.rs b/services/common/src/repo_reach.rs index 9e87eea7a..7e4bc8338 100644 --- a/services/common/src/repo_reach.rs +++ b/services/common/src/repo_reach.rs @@ -114,12 +114,23 @@ pub struct Refusal { pub said: String, } -/// What one cross-repository call came to: the model's reply, and the -/// refusal when the read was refused. -#[derive(Debug, Clone, PartialEq)] +/// What one cross-repository call came to: the model's reply, the refusal +/// when the read was refused, and what it read (for the private-content +/// check, [`leak`]). +#[derive(Debug, Clone, PartialEq, Default)] pub struct Outcome { pub text: String, pub refusal: Option, + pub seen: Vec, +} + +/// Content a call read: the repository (`owner/name`), the path, and the +/// lines it returned. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Read { + pub repo: String, + pub path: String, + pub lines: Vec, } /// The status a read error stands for: 404 for what isn't there, the @@ -146,6 +157,7 @@ fn refused(repo: &str, path: &str, e: &ReadError) -> Outcome { status, said: e.to_string(), }), + seen: Vec::new(), } } @@ -160,6 +172,7 @@ pub fn without_access(name: &str, why: &str) -> Outcome { status: 403, said: format!("{name}: {why}"), }), + seen: Vec::new(), } } @@ -192,7 +205,7 @@ pub async fn call(reader: &CodeReader<'_>, name: &str, input: &Value) -> Outcome } Outcome { text, - refusal: None, + ..Default::default() } } READ_REPO_FILE => { @@ -217,6 +230,11 @@ pub async fn call(reader: &CodeReader<'_>, name: &str, input: &Value) -> Outcome slice.url() ), refusal: None, + seen: vec![Read { + repo: slice.repo.clone(), + path: slice.path.clone(), + lines: slice.text.lines().map(str::to_string).collect(), + }], }, Err(e) => refused(repo, path, &e), } @@ -231,19 +249,31 @@ pub async fn call(reader: &CodeReader<'_>, name: &str, input: &Value) -> Outcome match reader.search(&repos, query).await { Ok(hits) if hits.is_empty() => Outcome { text: format!("Nothing matched `{query}`."), - refusal: None, + ..Default::default() }, Ok(hits) => { let mut text = String::new(); + let mut seen = Vec::new(); for h in hits.iter().take(MAX_HITS) { text.push_str(&format!("{} {}\n", h.repo, h.path)); for f in h.fragments.iter().take(3) { text.push_str(&format!(" {}\n", f.trim())); } + seen.push(Read { + repo: h.repo.clone(), + path: h.path.clone(), + lines: h + .fragments + .iter() + .take(3) + .flat_map(|f| f.lines().map(str::to_string)) + .collect(), + }); } Outcome { text, refusal: None, + seen, } } Err(e) => refused(repo, "", &e), @@ -251,7 +281,7 @@ pub async fn call(reader: &CodeReader<'_>, name: &str, input: &Value) -> Outcome } _ => Outcome { text: format!("{name} isn't a cross-repository tool."), - refusal: None, + ..Default::default() }, } } @@ -277,6 +307,178 @@ pub fn refusal_in(name: &str, input: &Value, error: &str) -> Option { }) } +// ── Private content in public places ─────────────────────────────────────── +// +// Reading stays allowed everywhere, so answers stay right. What a reply +// posted where people outside the installation can read it (a public +// repository's pull request, issue or comment) never carries is what came +// from a private repository: no line of it verbatim, no code from it, and +// no private repository's name or a path read in it. A reply that trips +// [`leak`] is asked to state its conclusion in plain words; what still +// trips is taken out ([`redact`]). It never turns into "I can't see it". + +/// The words a loop replying in a public repository is told when its +/// answer carried private content. +pub fn conclusion_only(why: &str) -> String { + format!( + "This reply is posted in a public repository, and people outside the team can read \ + it. It carries content from a private repository of the team ({why}). Write the \ + whole answer again: state the conclusion in plain words, with no line or code \ + quoted from a private repository and no private repository's name or path. Don't \ + say you can't see or read it: you read it, so give the answer it led to." + ) +} + +/// A line read from a private repository that is long enough to be its +/// content rather than a common word or a brace. +fn quotable(line: &str) -> Option<&str> { + let t = line.trim(); + (t.chars().filter(|c| c.is_alphanumeric()).count() >= 12).then_some(t) +} + +/// The words of `reads` a public reply never carries: each repository's +/// `owner/name`, its name alone when it is distinctive (five characters or +/// more), and each path read. +fn names(reads: &[Read]) -> Vec { + let mut out: Vec = Vec::new(); + for r in reads { + out.push(r.repo.to_lowercase()); + let short = r.repo.rsplit('/').next().unwrap_or(&r.repo).to_lowercase(); + if short.chars().count() >= 5 { + out.push(short); + } + if !r.path.is_empty() { + out.push(r.path.to_lowercase()); + } + } + out.sort(); + out.dedup(); + out +} + +fn has_word(hay: &str, word: &str) -> bool { + let low = hay.to_lowercase(); + let mut from = 0; + while let Some(i) = low[from..].find(word) { + let at = from + i; + let before = low[..at].chars().next_back(); + let after = low[at + word.len()..].chars().next(); + let edge = + |c: Option| c.is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '-')); + if edge(before) && edge(after) { + return true; + } + from = at + word.len(); + } + false +} + +/// What in `text` (a reply posted in a public repository) came from the +/// private `reads`: a line of their content verbatim, or a private +/// repository's name or a path read in it. `None` when nothing did. +pub fn leak(text: &str, reads: &[Read]) -> Option { + if reads.is_empty() { + return None; + } + for r in reads { + for l in &r.lines { + if let Some(q) = quotable(l) { + if text.contains(q) { + return Some(format!("a line of `{}` quoted", r.path)); + } + } + } + } + names(reads) + .into_iter() + .find(|n| has_word(text, n)) + .map(|_| "a private repository or path named".to_string()) +} + +/// `text` with every part [`leak`] finds taken out: lines that quote +/// private content, and sentences that name a private repository or path. +/// A JSON answer is redacted value by value and stays valid JSON. +pub fn redact(text: &str, reads: &[Read]) -> String { + if reads.is_empty() { + return text.to_string(); + } + if is_structured(text) { + if let Ok(mut v) = serde_json::from_str::(text.trim()) { + redact_value(&mut v, reads); + return v.to_string(); + } + } + redact_prose(text, reads) +} + +fn redact_value(v: &mut Value, reads: &[Read]) { + match v { + Value::String(s) => *s = redact_prose(s, reads), + Value::Array(a) => a.iter_mut().for_each(|x| redact_value(x, reads)), + Value::Object(o) => o.values_mut().for_each(|x| redact_value(x, reads)), + _ => {} + } +} + +fn redact_prose(text: &str, reads: &[Read]) -> String { + let quotes: Vec<&str> = reads + .iter() + .flat_map(|r| r.lines.iter().filter_map(|l| quotable(l))) + .collect(); + let names = names(reads); + let mut out: Vec = Vec::new(); + let mut fence: Vec = Vec::new(); + let mut fenced = false; + for line in text.lines() { + let t = line.trim_start(); + if t.starts_with("```") || t.starts_with("~~~") { + if fenced { + fence.push(line.to_string()); + // A code block holding anything private goes whole. + let body = fence.join("\n"); + if !quotes.iter().any(|q| body.contains(q)) + && !names.iter().any(|n| has_word(&body, n)) + { + out.append(&mut fence); + } + fence.clear(); + } else { + fence.push(line.to_string()); + } + fenced = !fenced; + continue; + } + if fenced { + fence.push(line.to_string()); + continue; + } + let private = + |s: &str| quotes.iter().any(|q| s.contains(q)) || names.iter().any(|n| has_word(s, n)); + if !private(line) { + out.push(line.to_string()); + continue; + } + let kept: Vec = sentences_of(line) + .into_iter() + .filter(|s| !private(s)) + .map(|s| s.trim().to_string()) + .collect(); + let kept = kept.join(" "); + if !kept.trim().is_empty() { + let indent = &line[..line.len() - line.trim_start().len()]; + out.push(format!("{indent}{kept}")); + } + } + // An unclosed fence is checked as it stands. + if !fence.is_empty() { + let body = fence.join("\n"); + if !quotes.iter().any(|q| body.contains(q)) && !names.iter().any(|n| has_word(&body, n)) { + out.append(&mut fence); + } + } + out.join("\n").trim().to_string() +} + // ── The guard on what people read ────────────────────────────────────────── /// A sentence in which CoderHelm says, in the first person, that it can't diff --git a/services/common/src/repo_read.rs b/services/common/src/repo_read.rs index 84793a758..6992ffe88 100644 --- a/services/common/src/repo_read.rs +++ b/services/common/src/repo_read.rs @@ -172,7 +172,18 @@ impl GitHubHost<'_> { /// each), at most `max`: what an agent's cross-repository tools read /// (`repo_reach`). pub async fn installation_repos(&self, max: usize) -> Result, ReadError> { + Ok(self.installation_listing(max).await?.0) + } + + /// [`GitHubHost::installation_repos`] with the `owner/name` (lower + /// case) of each repository GitHub says is public. A repository it + /// doesn't say is public counts as private. + pub async fn installation_listing( + &self, + max: usize, + ) -> Result<(Vec, std::collections::BTreeSet), ReadError> { let mut out = Vec::new(); + let mut public = std::collections::BTreeSet::new(); for page in 1..=max.div_ceil(100).max(1) { let url = format!("{GITHUB_API}/installation/repositories?per_page=100&page={page}"); let (status, body) = self @@ -187,6 +198,9 @@ impl GitHubHost<'_> { let rows = v["repositories"].as_array().cloned().unwrap_or_default(); for r in &rows { if let Some(full) = r["full_name"].as_str() { + if r["private"].as_bool() == Some(false) { + public.insert(full.to_lowercase()); + } let mut info = RepoInfo::new(full, r["default_branch"].as_str().unwrap_or("main")); info.description = r["description"] @@ -201,7 +215,7 @@ impl GitHubHost<'_> { } } out.truncate(max); - Ok(out) + Ok((out, public)) } async fn send(&self, req: HttpRequest) -> Result<(u16, Vec), ReadError> { diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 746fd68ad..4f4705ef7 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -399,7 +399,15 @@ async fn converse_as( ) }); let missing = access.as_ref().err().cloned().unwrap_or_default(); - let exec = super::reach::Exec::new(tool_executor, reader.as_ref(), &missing); + // A reply posted in a public repository keeps apart what it read in + // a private one (`common::repo_reach::leak`). + let exec = super::reach::Exec::new(tool_executor, reader.as_ref(), &missing).posting_to( + &provider.scope.repo, + &access + .as_ref() + .map(|a| a.public.clone()) + .unwrap_or_default(), + ); let system = if reaches { super::reach::prompt(system_prompt) } else { @@ -464,7 +472,7 @@ async fn converse_as( opts.deadline, opts.effort, observer, - log, + log.as_deref_mut(), form, ) .await @@ -478,6 +486,47 @@ async fn converse_as( out = Ok(super::reach::kept_answer(&first, retry, &exec.refusals())); } } + // A reply posted in a public repository never carries what came from a + // private one: no line or code of it, no private name or path. It is + // asked once for its conclusion in plain words; what still carries it + // is taken out. Reading stays allowed, so the answer stays right. + if let Ok(first) = &out { + if let Some(why) = common::repo_reach::leak(first, &exec.private_reads()) { + tracing::warn!(why = %why, "A public reply carried private content; asking for the conclusion only"); + let first = first.clone(); + let before = messages.len(); + messages.push(( + "user".to_string(), + vec![serde_json::json!({"type": "text", "text": common::repo_reach::conclusion_only(&why)})], + )); + let again = anthropic::converse_tool_loop( + &client, + model_id, + &system, + messages, + &tools, + &exec, + &gate, + usage, + LOOK_FIRST_TURNS, + opts.max_tokens, + opts.deadline, + opts.effort, + observer, + log, + form, + ) + .await + .map_err(|e| e.to_string()); + let reads = exec.private_reads(); + let answer = + super::reach::public_answer(&first, Some(again.clone()), &reads, &exec.refusals()); + if again.as_deref().ok() != Some(answer.as_str()) { + messages.truncate(before); + } + out = Ok(answer); + } + } if own_log { let step = scope.agent(agent).key(); let pass = super::run_log::current_pass(&scope.run_id).unwrap_or_else(|| step.to_string()); diff --git a/services/worker/src/agent/reach.rs b/services/worker/src/agent/reach.rs index 86d11db82..1f2bd7fe3 100644 --- a/services/worker/src/agent/reach.rs +++ b/services/worker/src/agent/reach.rs @@ -9,12 +9,12 @@ //! kept. The loop's answer is then held to `repo_reach::allowed` with the //! refusals of that same loop. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::sync::{LazyLock, Mutex}; use std::time::{Duration, Instant}; use common::mcp_remote::http::GuardedHttps; -use common::repo_reach::{self, Refusal}; +use common::repo_reach::{self, Read, Refusal}; use common::repo_read::{CodeReader, GitHubHost, RepoInfo}; use serde_json::{json, Value}; @@ -35,6 +35,9 @@ const KEEP_FAILED: Duration = Duration::from_secs(30); pub struct Access { token: String, pub repos: Vec, + /// `owner/name` (lower case) of each repository GitHub says is + /// public. Any other is private, a failed read included. + pub public: BTreeSet, } impl Access { @@ -92,10 +95,11 @@ async fn read_access(state: &crate::WorkerState, team: &str) -> Result String { format!("{}\n\n{words}", system.trim_end()) } +/// Whether `repo` (`owner/name`, or its name alone) is one of `public`. +/// A repository the listing doesn't name as public is private. +pub fn is_public(public: &BTreeSet, repo: &str) -> bool { + let r = repo.trim().to_lowercase(); + if r.is_empty() { + return false; + } + if r.contains('/') { + return public.contains(&r); + } + public + .iter() + .any(|p| p.rsplit('/').next() == Some(r.as_str())) +} + /// A loop's executor with the cross-repository tools in front of it. pub struct Exec<'a> { inner: &'a dyn ToolExecutor, reader: Option<&'a CodeReader<'a>>, missing: String, refusals: Mutex>, + /// The repositories known public, when this loop's reply is posted in + /// a public repository; `None` otherwise (nothing to keep apart). + public_reply: Option>, + private_reads: Mutex>, } impl<'a> Exec<'a> { @@ -160,6 +183,44 @@ impl<'a> Exec<'a> { reader, missing: missing.to_string(), refusals: Mutex::new(Vec::new()), + public_reply: None, + private_reads: Mutex::new(Vec::new()), + } + } + + /// This loop's reply goes to `target` (`owner/name`). When `target` is + /// public (`public` names it), every read of a private repository is + /// kept for the reply's check (`repo_reach::leak`). A private target, + /// or none, keeps nothing: the reply may quote what it read. + pub fn posting_to(mut self, target: &str, public: &BTreeSet) -> Self { + if is_public(public, target) { + self.public_reply = Some(public.clone()); + } + self + } + + /// What this loop read from private repositories while its reply goes + /// to a public one. + pub fn private_reads(&self) -> Vec { + self.private_reads + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + } + + fn keep_reads(&self, reads: Vec) { + let Some(public) = &self.public_reply else { + return; + }; + let private: Vec = reads + .into_iter() + .filter(|r| !is_public(public, &r.repo)) + .collect(); + if !private.is_empty() { + self.private_reads + .lock() + .unwrap_or_else(|e| e.into_inner()) + .extend(private); } } @@ -194,12 +255,30 @@ impl ToolExecutor for Exec<'_> { if let Some(r) = out.refusal { self.keep(r); } + self.keep_reads(out.seen); return Ok(json!(out.text)); } let out = self.inner.execute(name, input).await; - if let Err(e) = &out { - if let Some(r) = repo_reach::refusal_in(name, input, &e.to_string()) { - self.keep(r); + match &out { + Err(e) => { + if let Some(r) = repo_reach::refusal_in(name, input, &e.to_string()) { + self.keep(r); + } + } + // Another tool that read a named repository: what it returned + // is that repository's content. + Ok(v) => { + if let Some(repo) = input["repo"].as_str().filter(|r| !r.trim().is_empty()) { + let text = v + .as_str() + .map(str::to_string) + .unwrap_or_else(|| v.to_string()); + self.keep_reads(vec![Read { + repo: repo.to_string(), + path: input["path"].as_str().unwrap_or_default().to_string(), + lines: text.lines().map(str::to_string).collect(), + }]); + } } } out @@ -227,6 +306,29 @@ pub fn kept_answer( repo_reach::strip(&answer, refusals) } +/// The answer a loop replying in a public repository gives after its +/// answer carried private content: the retry's when it is usable and +/// carries none, else the first; either with the blindness guard's strip +/// and what still came from `reads` taken out (`repo_reach::redact`). +pub fn public_answer( + first: &str, + retry: Option>, + reads: &[Read], + refusals: &[Refusal], +) -> String { + let answer = match retry { + Some(Ok(t)) + if usable_retry(&Ok(t.clone())) + && repo_reach::leak(&t, reads).is_none() + && repo_reach::allowed(&t, refusals).is_ok() => + { + t + } + _ => first.to_string(), + }; + repo_reach::redact(&repo_reach::strip(&answer, refusals), reads) +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs index 92b59e432..c0fc289ab 100644 --- a/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs +++ b/services/worker/src/passes/incidents/xp_answers_read_the_other_repo.rs @@ -342,3 +342,163 @@ fn rs_files(dir: &std::path::Path) -> Vec { } out } + +const RULES: &str = "acme/pricing-rules"; +const DISCOUNT: &str = "src/discounts/family.ts"; + +/// A team with a public API repository, a public storefront and a private +/// pricing repository. +fn with_private() -> MemHost { + host().with_repo( + RULES, + "d15c0de", + &[( + DISCOUNT, + "export const FAMILY_DISCOUNT_CAP_PERCENT = 20;\n\ + export function familyDiscount(children: number) {\n \ + return Math.min(children * 5, FAMILY_DISCOUNT_CAP_PERCENT);\n}\n", + )], + ) +} + +fn public_set() -> std::collections::BTreeSet { + [API, SITE].iter().map(|r| r.to_string()).collect() +} + +fn all_repos() -> Vec { + let mut r = repos(); + r.push(RepoInfo::new(RULES, "main")); + r +} + +/// A reply posted in a public repository that read a private repository's +/// file states the answer without quoting the file or naming it: the +/// conclusion in plain words, never "I can't see it". +#[tokio::test] +async fn a_public_reply_gives_the_conclusion_of_a_private_read_without_quoting_it() { + let h = with_private(); + let reader = CodeReader::new(&h, all_repos()); + let exec = reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &public_set()); + exec.execute( + repo_reach::READ_REPO_FILE, + &json!({"repo": RULES, "path": DISCOUNT}), + ) + .await + .unwrap(); + let reads = exec.private_reads(); + assert_eq!(reads.len(), 1); + assert_eq!(reads[0].repo, RULES); + + let quoted = format!( + "The cap comes from `{DISCOUNT}` in {RULES}: \ + `return Math.min(children * 5, FAMILY_DISCOUNT_CAP_PERCENT);` so three children get 15 \ + percent and five get 20." + ); + assert!(repo_reach::leak("ed, &reads).is_some()); + let plain = "The family discount is 5 percent per child and is capped at 20 percent, so \ + three children get 15 percent and five get 20."; + assert_eq!(repo_reach::leak(plain, &reads), None); + // The loop's retry in plain words is the answer. + assert_eq!( + reach::public_answer("ed, Some(Ok(plain.to_string())), &reads, &[]), + plain + ); + // A retry that fails, or quotes again, never posts the quote: the first + // answer goes out without it. + for retry in [ + Some(Err("network".to_string())), + Some(Ok(quoted.clone())), + None, + ] { + let out = reach::public_answer("ed, retry, &reads, &[]); + assert_eq!(repo_reach::leak(&out, &reads), None, "{out}"); + assert!(!out.to_lowercase().contains("can't see"), "{out}"); + } + let nudge = repo_reach::conclusion_only("a line quoted"); + assert!(nudge.contains("plain words") && nudge.contains("Don't say you can't see")); +} + +/// A reply in a private repository may quote what it read; a reply in a +/// public repository may quote another public repository. +#[tokio::test] +async fn private_replies_and_public_to_public_replies_may_quote() { + let h = with_private(); + let reader = CodeReader::new(&h, all_repos()); + let private_target = + reach::Exec::new(&Nothing, Some(&reader), "").posting_to(RULES, &public_set()); + private_target + .execute( + repo_reach::READ_REPO_FILE, + &json!({"repo": RULES, "path": DISCOUNT}), + ) + .await + .unwrap(); + assert!(private_target.private_reads().is_empty()); + + let public_target = + reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &public_set()); + public_target + .execute( + repo_reach::READ_REPO_FILE, + &json!({"repo": SITE, "path": FORMATTER}), + ) + .await + .unwrap(); + assert!(public_target.private_reads().is_empty()); + let quote = format!( + "`{FORMATTER}` line 2 in {SITE}: `const lo = Math.max(1, Math.round(minMonths / 12));`" + ); + assert_eq!( + reach::public_answer("e, None, &public_target.private_reads(), &[]), + quote + ); + // A repository the listing doesn't call public counts as private. + assert!(!reach::is_public(&Default::default(), SITE)); + assert!(reach::is_public(&public_set(), "storefront")); +} + +/// A comment on a public pull request asking CoderHelm to paste a private +/// file gets the conclusion only, in prose and in a structured reply. +#[tokio::test] +async fn a_comment_asking_to_paste_a_private_file_gets_the_conclusion_only() { + let h = with_private(); + let reader = CodeReader::new(&h, all_repos()); + let exec = reach::Exec::new(&Nothing, Some(&reader), "").posting_to(API, &public_set()); + exec.execute( + repo_reach::READ_REPO_FILE, + &json!({"repo": RULES, "path": DISCOUNT}), + ) + .await + .unwrap(); + let reads = exec.private_reads(); + let pasted = format!( + "Here is `{DISCOUNT}` as asked:\n\ + ```ts\n\ + export const FAMILY_DISCOUNT_CAP_PERCENT = 20;\n\ + export function familyDiscount(children: number) {{\n \ + return Math.min(children * 5, FAMILY_DISCOUNT_CAP_PERCENT);\n\ + }}\n\ + ```\n\ + The discount grows 5 percent per child and stops at 20 percent." + ); + let out = reach::public_answer(&pasted, None, &reads, &[]); + assert_eq!( + out, + "The discount grows 5 percent per child and stops at 20 percent." + ); + let structured = json!({"reply": pasted}).to_string(); + let out = reach::public_answer(&structured, None, &reads, &[]); + let v: Value = serde_json::from_str(&out).expect("still JSON"); + assert_eq!( + v["reply"], + "The discount grows 5 percent per child and stops at 20 percent." + ); + assert_eq!(repo_reach::leak(&out, &reads), None); + + let provider = include_str!("../../agent/provider.rs"); + let loop_ = super::fixture::fn_src(provider, "async fn converse_as("); + assert!(loop_.contains(".posting_to(")); + assert!(loop_.contains("common::repo_reach::leak(")); + assert!(loop_.contains("common::repo_reach::conclusion_only(")); + assert!(loop_.contains("super::reach::public_answer(")); +}